2 * xHCI host controller driver
4 * Copyright (C) 2008 Intel Corp.
7 * Some code borrowed from the Linux EHCI driver.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software Foundation,
20 * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 #include <linux/pci.h>
24 #include <linux/irq.h>
25 #include <linux/log2.h>
26 #include <linux/module.h>
27 #include <linux/moduleparam.h>
28 #include <linux/slab.h>
29 #include <linux/dmi.h>
30 #include <linux/dma-mapping.h>
33 #include "xhci-trace.h"
35 #define DRIVER_AUTHOR "Sarah Sharp"
36 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
38 #define PORT_WAKE_BITS (PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E)
40 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
41 static int link_quirk;
42 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
43 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
45 static unsigned int quirks;
46 module_param(quirks, uint, S_IRUGO);
47 MODULE_PARM_DESC(quirks, "Bit flags for quirks to be enabled as default");
49 /* TODO: copied from ehci-hcd.c - can this be refactored? */
51 * xhci_handshake - spin reading hc until handshake completes or fails
52 * @ptr: address of hc register to be read
53 * @mask: bits to look at in result of read
54 * @done: value of those bits when handshake succeeds
55 * @usec: timeout in microseconds
57 * Returns negative errno, or zero on success
59 * Success happens when the "mask" bits have the specified value (hardware
60 * handshake done). There are two failure modes: "usec" have passed (major
61 * hardware flakeout), or the register reads as all-ones (hardware removed).
63 int xhci_handshake(void __iomem *ptr, u32 mask, u32 done, int usec)
69 if (result == ~(u32)0) /* card removed */
81 * Disable interrupts and begin the xHCI halting process.
83 void xhci_quiesce(struct xhci_hcd *xhci)
90 halted = readl(&xhci->op_regs->status) & STS_HALT;
94 cmd = readl(&xhci->op_regs->command);
96 writel(cmd, &xhci->op_regs->command);
100 * Force HC into halt state.
102 * Disable any IRQs and clear the run/stop bit.
103 * HC will complete any current and actively pipelined transactions, and
104 * should halt within 16 ms of the run/stop bit being cleared.
105 * Read HC Halted bit in the status register to see when the HC is finished.
107 int xhci_halt(struct xhci_hcd *xhci)
110 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Halt the HC");
113 ret = xhci_handshake(&xhci->op_regs->status,
114 STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
116 xhci->xhc_state |= XHCI_STATE_HALTED;
117 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
119 xhci_warn(xhci, "Host not halted after %u microseconds.\n",
125 * Set the run bit and wait for the host to be running.
127 static int xhci_start(struct xhci_hcd *xhci)
132 temp = readl(&xhci->op_regs->command);
134 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Turn on HC, cmd = 0x%x.",
136 writel(temp, &xhci->op_regs->command);
139 * Wait for the HCHalted Status bit to be 0 to indicate the host is
142 ret = xhci_handshake(&xhci->op_regs->status,
143 STS_HALT, 0, XHCI_MAX_HALT_USEC);
144 if (ret == -ETIMEDOUT)
145 xhci_err(xhci, "Host took too long to start, "
146 "waited %u microseconds.\n",
149 xhci->xhc_state &= ~XHCI_STATE_HALTED;
156 * This resets pipelines, timers, counters, state machines, etc.
157 * Transactions will be terminated immediately, and operational registers
158 * will be set to their defaults.
160 int xhci_reset(struct xhci_hcd *xhci)
166 state = readl(&xhci->op_regs->status);
167 if ((state & STS_HALT) == 0) {
168 xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
172 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Reset the HC");
173 command = readl(&xhci->op_regs->command);
174 command |= CMD_RESET;
175 writel(command, &xhci->op_regs->command);
177 ret = xhci_handshake(&xhci->op_regs->command,
178 CMD_RESET, 0, 10 * 1000 * 1000);
182 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
183 "Wait for controller to be ready for doorbell rings");
185 * xHCI cannot write to any doorbells or operational registers other
186 * than status until the "Controller Not Ready" flag is cleared.
188 ret = xhci_handshake(&xhci->op_regs->status,
189 STS_CNR, 0, 10 * 1000 * 1000);
191 for (i = 0; i < 2; ++i) {
192 xhci->bus_state[i].port_c_suspend = 0;
193 xhci->bus_state[i].suspended_ports = 0;
194 xhci->bus_state[i].resuming_ports = 0;
201 static int xhci_free_msi(struct xhci_hcd *xhci)
205 if (!xhci->msix_entries)
208 for (i = 0; i < xhci->msix_count; i++)
209 if (xhci->msix_entries[i].vector)
210 free_irq(xhci->msix_entries[i].vector,
218 static int xhci_setup_msi(struct xhci_hcd *xhci)
221 struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
223 ret = pci_enable_msi(pdev);
225 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
226 "failed to allocate MSI entry");
230 ret = request_irq(pdev->irq, xhci_msi_irq,
231 0, "xhci_hcd", xhci_to_hcd(xhci));
233 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
234 "disable MSI interrupt");
235 pci_disable_msi(pdev);
243 * free all IRQs request
245 static void xhci_free_irq(struct xhci_hcd *xhci)
247 struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
250 /* return if using legacy interrupt */
251 if (xhci_to_hcd(xhci)->irq > 0)
254 ret = xhci_free_msi(xhci);
258 free_irq(pdev->irq, xhci_to_hcd(xhci));
266 static int xhci_setup_msix(struct xhci_hcd *xhci)
269 struct usb_hcd *hcd = xhci_to_hcd(xhci);
270 struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
273 * calculate number of msi-x vectors supported.
274 * - HCS_MAX_INTRS: the max number of interrupts the host can handle,
275 * with max number of interrupters based on the xhci HCSPARAMS1.
276 * - num_online_cpus: maximum msi-x vectors per CPUs core.
277 * Add additional 1 vector to ensure always available interrupt.
279 xhci->msix_count = min(num_online_cpus() + 1,
280 HCS_MAX_INTRS(xhci->hcs_params1));
283 kmalloc((sizeof(struct msix_entry))*xhci->msix_count,
285 if (!xhci->msix_entries) {
286 xhci_err(xhci, "Failed to allocate MSI-X entries\n");
290 for (i = 0; i < xhci->msix_count; i++) {
291 xhci->msix_entries[i].entry = i;
292 xhci->msix_entries[i].vector = 0;
295 ret = pci_enable_msix_exact(pdev, xhci->msix_entries, xhci->msix_count);
297 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
298 "Failed to enable MSI-X");
302 for (i = 0; i < xhci->msix_count; i++) {
303 ret = request_irq(xhci->msix_entries[i].vector,
305 0, "xhci_hcd", xhci_to_hcd(xhci));
310 hcd->msix_enabled = 1;
314 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "disable MSI-X interrupt");
316 pci_disable_msix(pdev);
318 kfree(xhci->msix_entries);
319 xhci->msix_entries = NULL;
323 /* Free any IRQs and disable MSI-X */
324 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
326 struct usb_hcd *hcd = xhci_to_hcd(xhci);
327 struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
329 if (xhci->quirks & XHCI_PLAT)
334 if (xhci->msix_entries) {
335 pci_disable_msix(pdev);
336 kfree(xhci->msix_entries);
337 xhci->msix_entries = NULL;
339 pci_disable_msi(pdev);
342 hcd->msix_enabled = 0;
346 static void __maybe_unused xhci_msix_sync_irqs(struct xhci_hcd *xhci)
350 if (xhci->msix_entries) {
351 for (i = 0; i < xhci->msix_count; i++)
352 synchronize_irq(xhci->msix_entries[i].vector);
356 static int xhci_try_enable_msi(struct usb_hcd *hcd)
358 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
359 struct pci_dev *pdev;
362 /* The xhci platform device has set up IRQs through usb_add_hcd. */
363 if (xhci->quirks & XHCI_PLAT)
366 pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
368 * Some Fresco Logic host controllers advertise MSI, but fail to
369 * generate interrupts. Don't even try to enable MSI.
371 if (xhci->quirks & XHCI_BROKEN_MSI)
374 /* unregister the legacy interrupt */
376 free_irq(hcd->irq, hcd);
379 ret = xhci_setup_msix(xhci);
381 /* fall back to msi*/
382 ret = xhci_setup_msi(xhci);
385 /* hcd->irq is 0, we have MSI */
389 xhci_err(xhci, "No msi-x/msi found and no IRQ in BIOS\n");
394 if (!strlen(hcd->irq_descr))
395 snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
396 hcd->driver->description, hcd->self.busnum);
398 /* fall back to legacy interrupt*/
399 ret = request_irq(pdev->irq, &usb_hcd_irq, IRQF_SHARED,
400 hcd->irq_descr, hcd);
402 xhci_err(xhci, "request interrupt %d failed\n",
406 hcd->irq = pdev->irq;
412 static inline int xhci_try_enable_msi(struct usb_hcd *hcd)
417 static inline void xhci_cleanup_msix(struct xhci_hcd *xhci)
421 static inline void xhci_msix_sync_irqs(struct xhci_hcd *xhci)
427 static void compliance_mode_recovery(unsigned long arg)
429 struct xhci_hcd *xhci;
434 xhci = (struct xhci_hcd *)arg;
436 for (i = 0; i < xhci->num_usb3_ports; i++) {
437 temp = readl(xhci->usb3_ports[i]);
438 if ((temp & PORT_PLS_MASK) == USB_SS_PORT_LS_COMP_MOD) {
440 * Compliance Mode Detected. Letting USB Core
441 * handle the Warm Reset
443 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
444 "Compliance mode detected->port %d",
446 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
447 "Attempting compliance mode recovery");
448 hcd = xhci->shared_hcd;
450 if (hcd->state == HC_STATE_SUSPENDED)
451 usb_hcd_resume_root_hub(hcd);
453 usb_hcd_poll_rh_status(hcd);
457 if (xhci->port_status_u0 != ((1 << xhci->num_usb3_ports)-1))
458 mod_timer(&xhci->comp_mode_recovery_timer,
459 jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
463 * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
464 * that causes ports behind that hardware to enter compliance mode sometimes.
465 * The quirk creates a timer that polls every 2 seconds the link state of
466 * each host controller's port and recovers it by issuing a Warm reset
467 * if Compliance mode is detected, otherwise the port will become "dead" (no
468 * device connections or disconnections will be detected anymore). Becasue no
469 * status event is generated when entering compliance mode (per xhci spec),
470 * this quirk is needed on systems that have the failing hardware installed.
472 static void compliance_mode_recovery_timer_init(struct xhci_hcd *xhci)
474 xhci->port_status_u0 = 0;
475 setup_timer(&xhci->comp_mode_recovery_timer,
476 compliance_mode_recovery, (unsigned long)xhci);
477 xhci->comp_mode_recovery_timer.expires = jiffies +
478 msecs_to_jiffies(COMP_MODE_RCVRY_MSECS);
480 set_timer_slack(&xhci->comp_mode_recovery_timer,
481 msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
482 add_timer(&xhci->comp_mode_recovery_timer);
483 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
484 "Compliance mode recovery timer initialized");
488 * This function identifies the systems that have installed the SN65LVPE502CP
489 * USB3.0 re-driver and that need the Compliance Mode Quirk.
491 * Vendor: Hewlett-Packard -> System Models: Z420, Z620 and Z820
493 static bool xhci_compliance_mode_recovery_timer_quirk_check(void)
495 const char *dmi_product_name, *dmi_sys_vendor;
497 dmi_product_name = dmi_get_system_info(DMI_PRODUCT_NAME);
498 dmi_sys_vendor = dmi_get_system_info(DMI_SYS_VENDOR);
499 if (!dmi_product_name || !dmi_sys_vendor)
502 if (!(strstr(dmi_sys_vendor, "Hewlett-Packard")))
505 if (strstr(dmi_product_name, "Z420") ||
506 strstr(dmi_product_name, "Z620") ||
507 strstr(dmi_product_name, "Z820") ||
508 strstr(dmi_product_name, "Z1 Workstation"))
514 static int xhci_all_ports_seen_u0(struct xhci_hcd *xhci)
516 return (xhci->port_status_u0 == ((1 << xhci->num_usb3_ports)-1));
521 * Initialize memory for HCD and xHC (one-time init).
523 * Program the PAGESIZE register, initialize the device context array, create
524 * device contexts (?), set up a command ring segment (or two?), create event
525 * ring (one for now).
527 int xhci_init(struct usb_hcd *hcd)
529 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
532 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_init");
533 spin_lock_init(&xhci->lock);
534 if (xhci->hci_version == 0x95 && link_quirk) {
535 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
536 "QUIRK: Not clearing Link TRB chain bits.");
537 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
539 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
540 "xHCI doesn't need link TRB QUIRK");
542 retval = xhci_mem_init(xhci, GFP_KERNEL);
543 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Finished xhci_init");
545 /* Initializing Compliance Mode Recovery Data If Needed */
546 if (xhci_compliance_mode_recovery_timer_quirk_check()) {
547 xhci->quirks |= XHCI_COMP_MODE_QUIRK;
548 compliance_mode_recovery_timer_init(xhci);
554 /*-------------------------------------------------------------------------*/
557 static int xhci_run_finished(struct xhci_hcd *xhci)
559 if (xhci_start(xhci)) {
563 xhci->shared_hcd->state = HC_STATE_RUNNING;
564 xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
566 if (xhci->quirks & XHCI_NEC_HOST)
567 xhci_ring_cmd_db(xhci);
569 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
570 "Finished xhci_run for USB3 roothub");
575 * Start the HC after it was halted.
577 * This function is called by the USB core when the HC driver is added.
578 * Its opposite is xhci_stop().
580 * xhci_init() must be called once before this function can be called.
581 * Reset the HC, enable device slot contexts, program DCBAAP, and
582 * set command ring pointer and event ring pointer.
584 * Setup MSI-X vectors and enable interrupts.
586 int xhci_run(struct usb_hcd *hcd)
591 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
593 /* Start the xHCI host controller running only after the USB 2.0 roothub
597 hcd->uses_new_polling = 1;
598 if (!usb_hcd_is_primary_hcd(hcd))
599 return xhci_run_finished(xhci);
601 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_run");
603 ret = xhci_try_enable_msi(hcd);
607 xhci_dbg(xhci, "Command ring memory map follows:\n");
608 xhci_debug_ring(xhci, xhci->cmd_ring);
609 xhci_dbg_ring_ptrs(xhci, xhci->cmd_ring);
610 xhci_dbg_cmd_ptrs(xhci);
612 xhci_dbg(xhci, "ERST memory map follows:\n");
613 xhci_dbg_erst(xhci, &xhci->erst);
614 xhci_dbg(xhci, "Event ring:\n");
615 xhci_debug_ring(xhci, xhci->event_ring);
616 xhci_dbg_ring_ptrs(xhci, xhci->event_ring);
617 temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
618 temp_64 &= ~ERST_PTR_MASK;
619 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
620 "ERST deq = 64'h%0lx", (long unsigned int) temp_64);
622 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
623 "// Set the interrupt modulation register");
624 temp = readl(&xhci->ir_set->irq_control);
625 temp &= ~ER_IRQ_INTERVAL_MASK;
627 writel(temp, &xhci->ir_set->irq_control);
629 /* Set the HCD state before we enable the irqs */
630 temp = readl(&xhci->op_regs->command);
632 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
633 "// Enable interrupts, cmd = 0x%x.", temp);
634 writel(temp, &xhci->op_regs->command);
636 temp = readl(&xhci->ir_set->irq_pending);
637 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
638 "// Enabling event ring interrupter %p by writing 0x%x to irq_pending",
639 xhci->ir_set, (unsigned int) ER_IRQ_ENABLE(temp));
640 writel(ER_IRQ_ENABLE(temp), &xhci->ir_set->irq_pending);
641 xhci_print_ir_set(xhci, 0);
643 if (xhci->quirks & XHCI_NEC_HOST) {
644 struct xhci_command *command;
645 command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
648 xhci_queue_vendor_command(xhci, command, 0, 0, 0,
649 TRB_TYPE(TRB_NEC_GET_FW));
651 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
652 "Finished xhci_run for USB2 roothub");
655 EXPORT_SYMBOL_GPL(xhci_run);
657 static void xhci_only_stop_hcd(struct usb_hcd *hcd)
659 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
661 spin_lock_irq(&xhci->lock);
664 /* The shared_hcd is going to be deallocated shortly (the USB core only
665 * calls this function when allocation fails in usb_add_hcd(), or
666 * usb_remove_hcd() is called). So we need to unset xHCI's pointer.
668 xhci->shared_hcd = NULL;
669 spin_unlock_irq(&xhci->lock);
675 * This function is called by the USB core when the HC driver is removed.
676 * Its opposite is xhci_run().
678 * Disable device contexts, disable IRQs, and quiesce the HC.
679 * Reset the HC, finish any completed transactions, and cleanup memory.
681 void xhci_stop(struct usb_hcd *hcd)
684 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
686 if (!usb_hcd_is_primary_hcd(hcd)) {
687 xhci_only_stop_hcd(xhci->shared_hcd);
691 spin_lock_irq(&xhci->lock);
692 /* Make sure the xHC is halted for a USB3 roothub
693 * (xhci_stop() could be called as part of failed init).
697 spin_unlock_irq(&xhci->lock);
699 xhci_cleanup_msix(xhci);
701 /* Deleting Compliance Mode Recovery Timer */
702 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
703 (!(xhci_all_ports_seen_u0(xhci)))) {
704 del_timer_sync(&xhci->comp_mode_recovery_timer);
705 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
706 "%s: compliance mode recovery timer deleted",
710 if (xhci->quirks & XHCI_AMD_PLL_FIX)
713 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
714 "// Disabling event ring interrupts");
715 temp = readl(&xhci->op_regs->status);
716 writel(temp & ~STS_EINT, &xhci->op_regs->status);
717 temp = readl(&xhci->ir_set->irq_pending);
718 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
719 xhci_print_ir_set(xhci, 0);
721 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
722 xhci_mem_cleanup(xhci);
723 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
724 "xhci_stop completed - status = %x",
725 readl(&xhci->op_regs->status));
729 * Shutdown HC (not bus-specific)
731 * This is called when the machine is rebooting or halting. We assume that the
732 * machine will be powered off, and the HC's internal state will be reset.
733 * Don't bother to free memory.
735 * This will only ever be called with the main usb_hcd (the USB3 roothub).
737 void xhci_shutdown(struct usb_hcd *hcd)
739 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
741 if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
742 usb_disable_xhci_ports(to_pci_dev(hcd->self.controller));
744 spin_lock_irq(&xhci->lock);
746 /* Workaround for spurious wakeups at shutdown with HSW */
747 if (xhci->quirks & XHCI_SPURIOUS_WAKEUP)
749 spin_unlock_irq(&xhci->lock);
751 xhci_cleanup_msix(xhci);
753 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
754 "xhci_shutdown completed - status = %x",
755 readl(&xhci->op_regs->status));
757 /* Yet another workaround for spurious wakeups at shutdown with HSW */
758 if (xhci->quirks & XHCI_SPURIOUS_WAKEUP)
759 pci_set_power_state(to_pci_dev(hcd->self.controller), PCI_D3hot);
763 static void xhci_save_registers(struct xhci_hcd *xhci)
765 xhci->s3.command = readl(&xhci->op_regs->command);
766 xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
767 xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
768 xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
769 xhci->s3.erst_size = readl(&xhci->ir_set->erst_size);
770 xhci->s3.erst_base = xhci_read_64(xhci, &xhci->ir_set->erst_base);
771 xhci->s3.erst_dequeue = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
772 xhci->s3.irq_pending = readl(&xhci->ir_set->irq_pending);
773 xhci->s3.irq_control = readl(&xhci->ir_set->irq_control);
776 static void xhci_restore_registers(struct xhci_hcd *xhci)
778 writel(xhci->s3.command, &xhci->op_regs->command);
779 writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
780 xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
781 writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
782 writel(xhci->s3.erst_size, &xhci->ir_set->erst_size);
783 xhci_write_64(xhci, xhci->s3.erst_base, &xhci->ir_set->erst_base);
784 xhci_write_64(xhci, xhci->s3.erst_dequeue, &xhci->ir_set->erst_dequeue);
785 writel(xhci->s3.irq_pending, &xhci->ir_set->irq_pending);
786 writel(xhci->s3.irq_control, &xhci->ir_set->irq_control);
789 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
793 /* step 2: initialize command ring buffer */
794 val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
795 val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
796 (xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
797 xhci->cmd_ring->dequeue) &
798 (u64) ~CMD_RING_RSVD_BITS) |
799 xhci->cmd_ring->cycle_state;
800 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
801 "// Setting command ring address to 0x%llx",
802 (long unsigned long) val_64);
803 xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
807 * The whole command ring must be cleared to zero when we suspend the host.
809 * The host doesn't save the command ring pointer in the suspend well, so we
810 * need to re-program it on resume. Unfortunately, the pointer must be 64-byte
811 * aligned, because of the reserved bits in the command ring dequeue pointer
812 * register. Therefore, we can't just set the dequeue pointer back in the
813 * middle of the ring (TRBs are 16-byte aligned).
815 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
817 struct xhci_ring *ring;
818 struct xhci_segment *seg;
820 ring = xhci->cmd_ring;
824 sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
825 seg->trbs[TRBS_PER_SEGMENT - 1].link.control &=
826 cpu_to_le32(~TRB_CYCLE);
828 } while (seg != ring->deq_seg);
830 /* Reset the software enqueue and dequeue pointers */
831 ring->deq_seg = ring->first_seg;
832 ring->dequeue = ring->first_seg->trbs;
833 ring->enq_seg = ring->deq_seg;
834 ring->enqueue = ring->dequeue;
836 ring->num_trbs_free = ring->num_segs * (TRBS_PER_SEGMENT - 1) - 1;
838 * Ring is now zeroed, so the HW should look for change of ownership
839 * when the cycle bit is set to 1.
841 ring->cycle_state = 1;
844 * Reset the hardware dequeue pointer.
845 * Yes, this will need to be re-written after resume, but we're paranoid
846 * and want to make sure the hardware doesn't access bogus memory
847 * because, say, the BIOS or an SMI started the host without changing
848 * the command ring pointers.
850 xhci_set_cmd_ring_deq(xhci);
853 static void xhci_disable_port_wake_on_bits(struct xhci_hcd *xhci)
856 __le32 __iomem **port_array;
860 spin_lock_irqsave(&xhci->lock, flags);
862 /* disble usb3 ports Wake bits*/
863 port_index = xhci->num_usb3_ports;
864 port_array = xhci->usb3_ports;
865 while (port_index--) {
866 t1 = readl(port_array[port_index]);
867 t1 = xhci_port_state_to_neutral(t1);
868 t2 = t1 & ~PORT_WAKE_BITS;
870 writel(t2, port_array[port_index]);
873 /* disble usb2 ports Wake bits*/
874 port_index = xhci->num_usb2_ports;
875 port_array = xhci->usb2_ports;
876 while (port_index--) {
877 t1 = readl(port_array[port_index]);
878 t1 = xhci_port_state_to_neutral(t1);
879 t2 = t1 & ~PORT_WAKE_BITS;
881 writel(t2, port_array[port_index]);
884 spin_unlock_irqrestore(&xhci->lock, flags);
888 * Stop HC (not bus-specific)
890 * This is called when the machine transition into S3/S4 mode.
893 int xhci_suspend(struct xhci_hcd *xhci, bool do_wakeup)
896 unsigned int delay = XHCI_MAX_HALT_USEC;
897 struct usb_hcd *hcd = xhci_to_hcd(xhci);
900 if (hcd->state != HC_STATE_SUSPENDED ||
901 xhci->shared_hcd->state != HC_STATE_SUSPENDED)
904 /* Clear root port wake on bits if wakeup not allowed. */
906 xhci_disable_port_wake_on_bits(xhci);
908 /* Don't poll the roothubs on bus suspend. */
909 xhci_dbg(xhci, "%s: stopping port polling.\n", __func__);
910 clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
911 del_timer_sync(&hcd->rh_timer);
912 clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
913 del_timer_sync(&xhci->shared_hcd->rh_timer);
915 spin_lock_irq(&xhci->lock);
916 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
917 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
918 /* step 1: stop endpoint */
919 /* skipped assuming that port suspend has done */
921 /* step 2: clear Run/Stop bit */
922 command = readl(&xhci->op_regs->command);
924 writel(command, &xhci->op_regs->command);
926 /* Some chips from Fresco Logic need an extraordinary delay */
927 delay *= (xhci->quirks & XHCI_SLOW_SUSPEND) ? 10 : 1;
929 if (xhci_handshake(&xhci->op_regs->status,
930 STS_HALT, STS_HALT, delay)) {
931 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
932 spin_unlock_irq(&xhci->lock);
935 xhci_clear_command_ring(xhci);
937 /* step 3: save registers */
938 xhci_save_registers(xhci);
940 /* step 4: set CSS flag */
941 command = readl(&xhci->op_regs->command);
943 writel(command, &xhci->op_regs->command);
944 if (xhci_handshake(&xhci->op_regs->status,
945 STS_SAVE, 0, 10 * 1000)) {
946 xhci_warn(xhci, "WARN: xHC save state timeout\n");
947 spin_unlock_irq(&xhci->lock);
950 spin_unlock_irq(&xhci->lock);
953 * Deleting Compliance Mode Recovery Timer because the xHCI Host
954 * is about to be suspended.
956 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
957 (!(xhci_all_ports_seen_u0(xhci)))) {
958 del_timer_sync(&xhci->comp_mode_recovery_timer);
959 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
960 "%s: compliance mode recovery timer deleted",
964 /* step 5: remove core well power */
965 /* synchronize irq when using MSI-X */
966 xhci_msix_sync_irqs(xhci);
970 EXPORT_SYMBOL_GPL(xhci_suspend);
973 * start xHC (not bus-specific)
975 * This is called when the machine transition from S3/S4 mode.
978 int xhci_resume(struct xhci_hcd *xhci, bool hibernated)
980 u32 command, temp = 0, status;
981 struct usb_hcd *hcd = xhci_to_hcd(xhci);
982 struct usb_hcd *secondary_hcd;
984 bool comp_timer_running = false;
986 /* Wait a bit if either of the roothubs need to settle from the
987 * transition into bus suspend.
989 if (time_before(jiffies, xhci->bus_state[0].next_statechange) ||
991 xhci->bus_state[1].next_statechange))
994 set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
995 set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
997 spin_lock_irq(&xhci->lock);
998 if (xhci->quirks & XHCI_RESET_ON_RESUME)
1002 /* step 1: restore register */
1003 xhci_restore_registers(xhci);
1004 /* step 2: initialize command ring buffer */
1005 xhci_set_cmd_ring_deq(xhci);
1006 /* step 3: restore state and start state*/
1007 /* step 3: set CRS flag */
1008 command = readl(&xhci->op_regs->command);
1010 writel(command, &xhci->op_regs->command);
1011 if (xhci_handshake(&xhci->op_regs->status,
1012 STS_RESTORE, 0, 10 * 1000)) {
1013 xhci_warn(xhci, "WARN: xHC restore state timeout\n");
1014 spin_unlock_irq(&xhci->lock);
1017 temp = readl(&xhci->op_regs->status);
1020 /* If restore operation fails, re-initialize the HC during resume */
1021 if ((temp & STS_SRE) || hibernated) {
1023 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1024 !(xhci_all_ports_seen_u0(xhci))) {
1025 del_timer_sync(&xhci->comp_mode_recovery_timer);
1026 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1027 "Compliance Mode Recovery Timer deleted!");
1030 /* Let the USB core know _both_ roothubs lost power. */
1031 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1032 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
1034 xhci_dbg(xhci, "Stop HCD\n");
1037 spin_unlock_irq(&xhci->lock);
1038 xhci_cleanup_msix(xhci);
1040 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1041 temp = readl(&xhci->op_regs->status);
1042 writel(temp & ~STS_EINT, &xhci->op_regs->status);
1043 temp = readl(&xhci->ir_set->irq_pending);
1044 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
1045 xhci_print_ir_set(xhci, 0);
1047 xhci_dbg(xhci, "cleaning up memory\n");
1048 xhci_mem_cleanup(xhci);
1049 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1050 readl(&xhci->op_regs->status));
1052 /* USB core calls the PCI reinit and start functions twice:
1053 * first with the primary HCD, and then with the secondary HCD.
1054 * If we don't do the same, the host will never be started.
1056 if (!usb_hcd_is_primary_hcd(hcd))
1057 secondary_hcd = hcd;
1059 secondary_hcd = xhci->shared_hcd;
1061 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1062 retval = xhci_init(hcd->primary_hcd);
1065 comp_timer_running = true;
1067 xhci_dbg(xhci, "Start the primary HCD\n");
1068 retval = xhci_run(hcd->primary_hcd);
1070 xhci_dbg(xhci, "Start the secondary HCD\n");
1071 retval = xhci_run(secondary_hcd);
1073 hcd->state = HC_STATE_SUSPENDED;
1074 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1078 /* step 4: set Run/Stop bit */
1079 command = readl(&xhci->op_regs->command);
1081 writel(command, &xhci->op_regs->command);
1082 xhci_handshake(&xhci->op_regs->status, STS_HALT,
1085 /* step 5: walk topology and initialize portsc,
1086 * portpmsc and portli
1088 /* this is done in bus_resume */
1090 /* step 6: restart each of the previously
1091 * Running endpoints by ringing their doorbells
1094 spin_unlock_irq(&xhci->lock);
1098 /* Resume root hubs only when have pending events. */
1099 status = readl(&xhci->op_regs->status);
1100 if (status & STS_EINT) {
1101 usb_hcd_resume_root_hub(hcd);
1102 usb_hcd_resume_root_hub(xhci->shared_hcd);
1107 * If system is subject to the Quirk, Compliance Mode Timer needs to
1108 * be re-initialized Always after a system resume. Ports are subject
1109 * to suffer the Compliance Mode issue again. It doesn't matter if
1110 * ports have entered previously to U0 before system's suspension.
1112 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
1113 compliance_mode_recovery_timer_init(xhci);
1115 /* Re-enable port polling. */
1116 xhci_dbg(xhci, "%s: starting port polling.\n", __func__);
1117 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1118 usb_hcd_poll_rh_status(hcd);
1119 set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
1120 usb_hcd_poll_rh_status(xhci->shared_hcd);
1124 EXPORT_SYMBOL_GPL(xhci_resume);
1125 #endif /* CONFIG_PM */
1127 /*-------------------------------------------------------------------------*/
1130 * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1131 * HCDs. Find the index for an endpoint given its descriptor. Use the return
1132 * value to right shift 1 for the bitmask.
1134 * Index = (epnum * 2) + direction - 1,
1135 * where direction = 0 for OUT, 1 for IN.
1136 * For control endpoints, the IN index is used (OUT index is unused), so
1137 * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1139 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1142 if (usb_endpoint_xfer_control(desc))
1143 index = (unsigned int) (usb_endpoint_num(desc)*2);
1145 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1146 (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1150 /* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
1151 * address from the XHCI endpoint index.
1153 unsigned int xhci_get_endpoint_address(unsigned int ep_index)
1155 unsigned int number = DIV_ROUND_UP(ep_index, 2);
1156 unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
1157 return direction | number;
1160 /* Find the flag for this endpoint (for use in the control context). Use the
1161 * endpoint index to create a bitmask. The slot context is bit 0, endpoint 0 is
1164 unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1166 return 1 << (xhci_get_endpoint_index(desc) + 1);
1169 /* Find the flag for this endpoint (for use in the control context). Use the
1170 * endpoint index to create a bitmask. The slot context is bit 0, endpoint 0 is
1173 unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
1175 return 1 << (ep_index + 1);
1178 /* Compute the last valid endpoint context index. Basically, this is the
1179 * endpoint index plus one. For slot contexts with more than valid endpoint,
1180 * we find the most significant bit set in the added contexts flags.
1181 * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1182 * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1184 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1186 return fls(added_ctxs) - 1;
1189 /* Returns 1 if the arguments are OK;
1190 * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1192 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1193 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1195 struct xhci_hcd *xhci;
1196 struct xhci_virt_device *virt_dev;
1198 if (!hcd || (check_ep && !ep) || !udev) {
1199 pr_debug("xHCI %s called with invalid args\n", func);
1202 if (!udev->parent) {
1203 pr_debug("xHCI %s called for root hub\n", func);
1207 xhci = hcd_to_xhci(hcd);
1208 if (check_virt_dev) {
1209 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1210 xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
1215 virt_dev = xhci->devs[udev->slot_id];
1216 if (virt_dev->udev != udev) {
1217 xhci_dbg(xhci, "xHCI %s called with udev and "
1218 "virt_dev does not match\n", func);
1223 if (xhci->xhc_state & XHCI_STATE_HALTED)
1229 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1230 struct usb_device *udev, struct xhci_command *command,
1231 bool ctx_change, bool must_succeed);
1234 * Full speed devices may have a max packet size greater than 8 bytes, but the
1235 * USB core doesn't know that until it reads the first 8 bytes of the
1236 * descriptor. If the usb_device's max packet size changes after that point,
1237 * we need to issue an evaluate context command and wait on it.
1239 static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
1240 unsigned int ep_index, struct urb *urb)
1242 struct xhci_container_ctx *out_ctx;
1243 struct xhci_input_control_ctx *ctrl_ctx;
1244 struct xhci_ep_ctx *ep_ctx;
1245 struct xhci_command *command;
1246 int max_packet_size;
1247 int hw_max_packet_size;
1250 out_ctx = xhci->devs[slot_id]->out_ctx;
1251 ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1252 hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1253 max_packet_size = usb_endpoint_maxp(&urb->dev->ep0.desc);
1254 if (hw_max_packet_size != max_packet_size) {
1255 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1256 "Max Packet Size for ep 0 changed.");
1257 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1258 "Max packet size in usb_device = %d",
1260 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1261 "Max packet size in xHCI HW = %d",
1262 hw_max_packet_size);
1263 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1264 "Issuing evaluate context command.");
1266 /* Set up the input context flags for the command */
1267 /* FIXME: This won't work if a non-default control endpoint
1268 * changes max packet sizes.
1271 command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
1275 command->in_ctx = xhci->devs[slot_id]->in_ctx;
1276 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
1278 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1281 goto command_cleanup;
1283 /* Set up the modified control endpoint 0 */
1284 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1285 xhci->devs[slot_id]->out_ctx, ep_index);
1287 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
1288 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1289 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1291 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1292 ctrl_ctx->drop_flags = 0;
1294 xhci_dbg(xhci, "Slot %d input context\n", slot_id);
1295 xhci_dbg_ctx(xhci, command->in_ctx, ep_index);
1296 xhci_dbg(xhci, "Slot %d output context\n", slot_id);
1297 xhci_dbg_ctx(xhci, out_ctx, ep_index);
1299 ret = xhci_configure_endpoint(xhci, urb->dev, command,
1302 /* Clean up the input context for later use by bandwidth
1305 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1307 kfree(command->completion);
1314 * non-error returns are a promise to giveback() the urb later
1315 * we drop ownership so next owner (or urb unlink) can get it
1317 int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1319 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1320 struct xhci_td *buffer;
1321 unsigned long flags;
1323 unsigned int slot_id, ep_index;
1324 struct urb_priv *urb_priv;
1327 if (!urb || xhci_check_args(hcd, urb->dev, urb->ep,
1328 true, true, __func__) <= 0)
1331 slot_id = urb->dev->slot_id;
1332 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1334 if (!HCD_HW_ACCESSIBLE(hcd)) {
1335 if (!in_interrupt())
1336 xhci_dbg(xhci, "urb submitted during PCI suspend\n");
1341 /* Reject urb if endpoint is in soft reset, queue must stay empty */
1342 if (xhci->devs[slot_id]->eps[ep_index].ep_state & EP_CONFIG_PENDING) {
1343 xhci_warn(xhci, "Can't enqueue URB while ep is in soft reset\n");
1347 if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1348 size = urb->number_of_packets;
1352 urb_priv = kzalloc(sizeof(struct urb_priv) +
1353 size * sizeof(struct xhci_td *), mem_flags);
1357 buffer = kzalloc(size * sizeof(struct xhci_td), mem_flags);
1363 for (i = 0; i < size; i++) {
1364 urb_priv->td[i] = buffer;
1368 urb_priv->length = size;
1369 urb_priv->td_cnt = 0;
1370 urb->hcpriv = urb_priv;
1372 if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1373 /* Check to see if the max packet size for the default control
1374 * endpoint changed during FS device enumeration
1376 if (urb->dev->speed == USB_SPEED_FULL) {
1377 ret = xhci_check_maxpacket(xhci, slot_id,
1380 xhci_urb_free_priv(urb_priv);
1386 /* We have a spinlock and interrupts disabled, so we must pass
1387 * atomic context to this function, which may allocate memory.
1389 spin_lock_irqsave(&xhci->lock, flags);
1390 if (xhci->xhc_state & XHCI_STATE_DYING)
1392 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1396 spin_unlock_irqrestore(&xhci->lock, flags);
1397 } else if (usb_endpoint_xfer_bulk(&urb->ep->desc)) {
1398 spin_lock_irqsave(&xhci->lock, flags);
1399 if (xhci->xhc_state & XHCI_STATE_DYING)
1401 if (xhci->devs[slot_id]->eps[ep_index].ep_state &
1402 EP_GETTING_STREAMS) {
1403 xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
1404 "is transitioning to using streams.\n");
1406 } else if (xhci->devs[slot_id]->eps[ep_index].ep_state &
1407 EP_GETTING_NO_STREAMS) {
1408 xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
1409 "is transitioning to "
1410 "not having streams.\n");
1413 ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1418 spin_unlock_irqrestore(&xhci->lock, flags);
1419 } else if (usb_endpoint_xfer_int(&urb->ep->desc)) {
1420 spin_lock_irqsave(&xhci->lock, flags);
1421 if (xhci->xhc_state & XHCI_STATE_DYING)
1423 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1427 spin_unlock_irqrestore(&xhci->lock, flags);
1429 spin_lock_irqsave(&xhci->lock, flags);
1430 if (xhci->xhc_state & XHCI_STATE_DYING)
1432 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1436 spin_unlock_irqrestore(&xhci->lock, flags);
1441 xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for "
1442 "non-responsive xHCI host.\n",
1443 urb->ep->desc.bEndpointAddress, urb);
1446 xhci_urb_free_priv(urb_priv);
1448 spin_unlock_irqrestore(&xhci->lock, flags);
1452 /* Get the right ring for the given URB.
1453 * If the endpoint supports streams, boundary check the URB's stream ID.
1454 * If the endpoint doesn't support streams, return the singular endpoint ring.
1456 static struct xhci_ring *xhci_urb_to_transfer_ring(struct xhci_hcd *xhci,
1459 unsigned int slot_id;
1460 unsigned int ep_index;
1461 unsigned int stream_id;
1462 struct xhci_virt_ep *ep;
1464 slot_id = urb->dev->slot_id;
1465 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1466 stream_id = urb->stream_id;
1467 ep = &xhci->devs[slot_id]->eps[ep_index];
1468 /* Common case: no streams */
1469 if (!(ep->ep_state & EP_HAS_STREAMS))
1472 if (stream_id == 0) {
1474 "WARN: Slot ID %u, ep index %u has streams, "
1475 "but URB has no stream ID.\n",
1480 if (stream_id < ep->stream_info->num_streams)
1481 return ep->stream_info->stream_rings[stream_id];
1484 "WARN: Slot ID %u, ep index %u has "
1485 "stream IDs 1 to %u allocated, "
1486 "but stream ID %u is requested.\n",
1488 ep->stream_info->num_streams - 1,
1494 * Remove the URB's TD from the endpoint ring. This may cause the HC to stop
1495 * USB transfers, potentially stopping in the middle of a TRB buffer. The HC
1496 * should pick up where it left off in the TD, unless a Set Transfer Ring
1497 * Dequeue Pointer is issued.
1499 * The TRBs that make up the buffers for the canceled URB will be "removed" from
1500 * the ring. Since the ring is a contiguous structure, they can't be physically
1501 * removed. Instead, there are two options:
1503 * 1) If the HC is in the middle of processing the URB to be canceled, we
1504 * simply move the ring's dequeue pointer past those TRBs using the Set
1505 * Transfer Ring Dequeue Pointer command. This will be the common case,
1506 * when drivers timeout on the last submitted URB and attempt to cancel.
1508 * 2) If the HC is in the middle of a different TD, we turn the TRBs into a
1509 * series of 1-TRB transfer no-op TDs. (No-ops shouldn't be chained.) The
1510 * HC will need to invalidate the any TRBs it has cached after the stop
1511 * endpoint command, as noted in the xHCI 0.95 errata.
1513 * 3) The TD may have completed by the time the Stop Endpoint Command
1514 * completes, so software needs to handle that case too.
1516 * This function should protect against the TD enqueueing code ringing the
1517 * doorbell while this code is waiting for a Stop Endpoint command to complete.
1518 * It also needs to account for multiple cancellations on happening at the same
1519 * time for the same endpoint.
1521 * Note that this function can be called in any context, or so says
1522 * usb_hcd_unlink_urb()
1524 int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1526 unsigned long flags;
1529 struct xhci_hcd *xhci;
1530 struct urb_priv *urb_priv;
1532 unsigned int ep_index;
1533 struct xhci_ring *ep_ring;
1534 struct xhci_virt_ep *ep;
1535 struct xhci_command *command;
1537 xhci = hcd_to_xhci(hcd);
1538 spin_lock_irqsave(&xhci->lock, flags);
1539 /* Make sure the URB hasn't completed or been unlinked already */
1540 ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1541 if (ret || !urb->hcpriv)
1543 temp = readl(&xhci->op_regs->status);
1544 if (temp == 0xffffffff || (xhci->xhc_state & XHCI_STATE_HALTED)) {
1545 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1546 "HW died, freeing TD.");
1547 urb_priv = urb->hcpriv;
1548 for (i = urb_priv->td_cnt; i < urb_priv->length; i++) {
1549 td = urb_priv->td[i];
1550 if (!list_empty(&td->td_list))
1551 list_del_init(&td->td_list);
1552 if (!list_empty(&td->cancelled_td_list))
1553 list_del_init(&td->cancelled_td_list);
1556 usb_hcd_unlink_urb_from_ep(hcd, urb);
1557 spin_unlock_irqrestore(&xhci->lock, flags);
1558 usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1559 xhci_urb_free_priv(urb_priv);
1562 if ((xhci->xhc_state & XHCI_STATE_DYING) ||
1563 (xhci->xhc_state & XHCI_STATE_HALTED)) {
1564 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1565 "Ep 0x%x: URB %p to be canceled on "
1566 "non-responsive xHCI host.",
1567 urb->ep->desc.bEndpointAddress, urb);
1568 /* Let the stop endpoint command watchdog timer (which set this
1569 * state) finish cleaning up the endpoint TD lists. We must
1570 * have caught it in the middle of dropping a lock and giving
1576 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1577 ep = &xhci->devs[urb->dev->slot_id]->eps[ep_index];
1578 ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1584 urb_priv = urb->hcpriv;
1585 i = urb_priv->td_cnt;
1586 if (i < urb_priv->length)
1587 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1588 "Cancel URB %p, dev %s, ep 0x%x, "
1589 "starting at offset 0x%llx",
1590 urb, urb->dev->devpath,
1591 urb->ep->desc.bEndpointAddress,
1592 (unsigned long long) xhci_trb_virt_to_dma(
1593 urb_priv->td[i]->start_seg,
1594 urb_priv->td[i]->first_trb));
1596 for (; i < urb_priv->length; i++) {
1597 td = urb_priv->td[i];
1598 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1601 /* Queue a stop endpoint command, but only if this is
1602 * the first cancellation to be handled.
1604 if (!(ep->ep_state & EP_HALT_PENDING)) {
1605 command = xhci_alloc_command(xhci, false, false, GFP_ATOMIC);
1610 ep->ep_state |= EP_HALT_PENDING;
1611 ep->stop_cmds_pending++;
1612 ep->stop_cmd_timer.expires = jiffies +
1613 XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1614 add_timer(&ep->stop_cmd_timer);
1615 xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1617 xhci_ring_cmd_db(xhci);
1620 spin_unlock_irqrestore(&xhci->lock, flags);
1624 /* Drop an endpoint from a new bandwidth configuration for this device.
1625 * Only one call to this function is allowed per endpoint before
1626 * check_bandwidth() or reset_bandwidth() must be called.
1627 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1628 * add the endpoint to the schedule with possibly new parameters denoted by a
1629 * different endpoint descriptor in usb_host_endpoint.
1630 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1633 * The USB core will not allow URBs to be queued to an endpoint that is being
1634 * disabled, so there's no need for mutual exclusion to protect
1635 * the xhci->devs[slot_id] structure.
1637 int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1638 struct usb_host_endpoint *ep)
1640 struct xhci_hcd *xhci;
1641 struct xhci_container_ctx *in_ctx, *out_ctx;
1642 struct xhci_input_control_ctx *ctrl_ctx;
1643 unsigned int ep_index;
1644 struct xhci_ep_ctx *ep_ctx;
1646 u32 new_add_flags, new_drop_flags;
1649 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1652 xhci = hcd_to_xhci(hcd);
1653 if (xhci->xhc_state & XHCI_STATE_DYING)
1656 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1657 drop_flag = xhci_get_endpoint_flag(&ep->desc);
1658 if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1659 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1660 __func__, drop_flag);
1664 in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1665 out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1666 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1668 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1673 ep_index = xhci_get_endpoint_index(&ep->desc);
1674 ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1675 /* If the HC already knows the endpoint is disabled,
1676 * or the HCD has noted it is disabled, ignore this request
1678 if (((ep_ctx->ep_info & cpu_to_le32(EP_STATE_MASK)) ==
1679 cpu_to_le32(EP_STATE_DISABLED)) ||
1680 le32_to_cpu(ctrl_ctx->drop_flags) &
1681 xhci_get_endpoint_flag(&ep->desc)) {
1682 /* Do not warn when called after a usb_device_reset */
1683 if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1684 xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1689 ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1690 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1692 ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1693 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1695 xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1697 xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1698 (unsigned int) ep->desc.bEndpointAddress,
1700 (unsigned int) new_drop_flags,
1701 (unsigned int) new_add_flags);
1705 /* Add an endpoint to a new possible bandwidth configuration for this device.
1706 * Only one call to this function is allowed per endpoint before
1707 * check_bandwidth() or reset_bandwidth() must be called.
1708 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1709 * add the endpoint to the schedule with possibly new parameters denoted by a
1710 * different endpoint descriptor in usb_host_endpoint.
1711 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1714 * The USB core will not allow URBs to be queued to an endpoint until the
1715 * configuration or alt setting is installed in the device, so there's no need
1716 * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1718 int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1719 struct usb_host_endpoint *ep)
1721 struct xhci_hcd *xhci;
1722 struct xhci_container_ctx *in_ctx;
1723 unsigned int ep_index;
1724 struct xhci_input_control_ctx *ctrl_ctx;
1726 u32 new_add_flags, new_drop_flags;
1727 struct xhci_virt_device *virt_dev;
1730 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1732 /* So we won't queue a reset ep command for a root hub */
1736 xhci = hcd_to_xhci(hcd);
1737 if (xhci->xhc_state & XHCI_STATE_DYING)
1740 added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1741 if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1742 /* FIXME when we have to issue an evaluate endpoint command to
1743 * deal with ep0 max packet size changing once we get the
1746 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1747 __func__, added_ctxs);
1751 virt_dev = xhci->devs[udev->slot_id];
1752 in_ctx = virt_dev->in_ctx;
1753 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1755 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1760 ep_index = xhci_get_endpoint_index(&ep->desc);
1761 /* If this endpoint is already in use, and the upper layers are trying
1762 * to add it again without dropping it, reject the addition.
1764 if (virt_dev->eps[ep_index].ring &&
1765 !(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
1766 xhci_warn(xhci, "Trying to add endpoint 0x%x "
1767 "without dropping it.\n",
1768 (unsigned int) ep->desc.bEndpointAddress);
1772 /* If the HCD has already noted the endpoint is enabled,
1773 * ignore this request.
1775 if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
1776 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1782 * Configuration and alternate setting changes must be done in
1783 * process context, not interrupt context (or so documenation
1784 * for usb_set_interface() and usb_set_configuration() claim).
1786 if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1787 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1788 __func__, ep->desc.bEndpointAddress);
1792 ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1793 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1795 /* If xhci_endpoint_disable() was called for this endpoint, but the
1796 * xHC hasn't been notified yet through the check_bandwidth() call,
1797 * this re-adds a new state for the endpoint from the new endpoint
1798 * descriptors. We must drop and re-add this endpoint, so we leave the
1801 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1803 /* Store the usb_device pointer for later use */
1806 xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1807 (unsigned int) ep->desc.bEndpointAddress,
1809 (unsigned int) new_drop_flags,
1810 (unsigned int) new_add_flags);
1814 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1816 struct xhci_input_control_ctx *ctrl_ctx;
1817 struct xhci_ep_ctx *ep_ctx;
1818 struct xhci_slot_ctx *slot_ctx;
1821 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1823 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1828 /* When a device's add flag and drop flag are zero, any subsequent
1829 * configure endpoint command will leave that endpoint's state
1830 * untouched. Make sure we don't leave any old state in the input
1831 * endpoint contexts.
1833 ctrl_ctx->drop_flags = 0;
1834 ctrl_ctx->add_flags = 0;
1835 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1836 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1837 /* Endpoint 0 is always valid */
1838 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
1839 for (i = 1; i < 31; ++i) {
1840 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1841 ep_ctx->ep_info = 0;
1842 ep_ctx->ep_info2 = 0;
1844 ep_ctx->tx_info = 0;
1848 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1849 struct usb_device *udev, u32 *cmd_status)
1853 switch (*cmd_status) {
1854 case COMP_CMD_ABORT:
1856 xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
1860 dev_warn(&udev->dev,
1861 "Not enough host controller resources for new device state.\n");
1863 /* FIXME: can we allocate more resources for the HC? */
1866 case COMP_2ND_BW_ERR:
1867 dev_warn(&udev->dev,
1868 "Not enough bandwidth for new device state.\n");
1870 /* FIXME: can we go back to the old state? */
1873 /* the HCD set up something wrong */
1874 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
1876 "and endpoint is not disabled.\n");
1880 dev_warn(&udev->dev,
1881 "ERROR: Incompatible device for endpoint configure command.\n");
1885 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1886 "Successful Endpoint Configure command");
1890 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1898 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
1899 struct usb_device *udev, u32 *cmd_status)
1902 struct xhci_virt_device *virt_dev = xhci->devs[udev->slot_id];
1904 switch (*cmd_status) {
1905 case COMP_CMD_ABORT:
1907 xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
1911 dev_warn(&udev->dev,
1912 "WARN: xHCI driver setup invalid evaluate context command.\n");
1916 dev_warn(&udev->dev,
1917 "WARN: slot not enabled for evaluate context command.\n");
1920 case COMP_CTX_STATE:
1921 dev_warn(&udev->dev,
1922 "WARN: invalid context state for evaluate context command.\n");
1923 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 1);
1927 dev_warn(&udev->dev,
1928 "ERROR: Incompatible device for evaluate context command.\n");
1932 /* Max Exit Latency too large error */
1933 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
1937 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1938 "Successful evaluate context command");
1942 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1950 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
1951 struct xhci_input_control_ctx *ctrl_ctx)
1953 u32 valid_add_flags;
1954 u32 valid_drop_flags;
1956 /* Ignore the slot flag (bit 0), and the default control endpoint flag
1957 * (bit 1). The default control endpoint is added during the Address
1958 * Device command and is never removed until the slot is disabled.
1960 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
1961 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
1963 /* Use hweight32 to count the number of ones in the add flags, or
1964 * number of endpoints added. Don't count endpoints that are changed
1965 * (both added and dropped).
1967 return hweight32(valid_add_flags) -
1968 hweight32(valid_add_flags & valid_drop_flags);
1971 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
1972 struct xhci_input_control_ctx *ctrl_ctx)
1974 u32 valid_add_flags;
1975 u32 valid_drop_flags;
1977 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
1978 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
1980 return hweight32(valid_drop_flags) -
1981 hweight32(valid_add_flags & valid_drop_flags);
1985 * We need to reserve the new number of endpoints before the configure endpoint
1986 * command completes. We can't subtract the dropped endpoints from the number
1987 * of active endpoints until the command completes because we can oversubscribe
1988 * the host in this case:
1990 * - the first configure endpoint command drops more endpoints than it adds
1991 * - a second configure endpoint command that adds more endpoints is queued
1992 * - the first configure endpoint command fails, so the config is unchanged
1993 * - the second command may succeed, even though there isn't enough resources
1995 * Must be called with xhci->lock held.
1997 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
1998 struct xhci_input_control_ctx *ctrl_ctx)
2002 added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2003 if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
2004 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2005 "Not enough ep ctxs: "
2006 "%u active, need to add %u, limit is %u.",
2007 xhci->num_active_eps, added_eps,
2008 xhci->limit_active_eps);
2011 xhci->num_active_eps += added_eps;
2012 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2013 "Adding %u ep ctxs, %u now active.", added_eps,
2014 xhci->num_active_eps);
2019 * The configure endpoint was failed by the xHC for some other reason, so we
2020 * need to revert the resources that failed configuration would have used.
2022 * Must be called with xhci->lock held.
2024 static void xhci_free_host_resources(struct xhci_hcd *xhci,
2025 struct xhci_input_control_ctx *ctrl_ctx)
2029 num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2030 xhci->num_active_eps -= num_failed_eps;
2031 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2032 "Removing %u failed ep ctxs, %u now active.",
2034 xhci->num_active_eps);
2038 * Now that the command has completed, clean up the active endpoint count by
2039 * subtracting out the endpoints that were dropped (but not changed).
2041 * Must be called with xhci->lock held.
2043 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
2044 struct xhci_input_control_ctx *ctrl_ctx)
2046 u32 num_dropped_eps;
2048 num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
2049 xhci->num_active_eps -= num_dropped_eps;
2050 if (num_dropped_eps)
2051 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2052 "Removing %u dropped ep ctxs, %u now active.",
2054 xhci->num_active_eps);
2057 static unsigned int xhci_get_block_size(struct usb_device *udev)
2059 switch (udev->speed) {
2061 case USB_SPEED_FULL:
2063 case USB_SPEED_HIGH:
2065 case USB_SPEED_SUPER:
2067 case USB_SPEED_UNKNOWN:
2068 case USB_SPEED_WIRELESS:
2070 /* Should never happen */
2076 xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
2078 if (interval_bw->overhead[LS_OVERHEAD_TYPE])
2080 if (interval_bw->overhead[FS_OVERHEAD_TYPE])
2085 /* If we are changing a LS/FS device under a HS hub,
2086 * make sure (if we are activating a new TT) that the HS bus has enough
2087 * bandwidth for this new TT.
2089 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2090 struct xhci_virt_device *virt_dev,
2093 struct xhci_interval_bw_table *bw_table;
2094 struct xhci_tt_bw_info *tt_info;
2096 /* Find the bandwidth table for the root port this TT is attached to. */
2097 bw_table = &xhci->rh_bw[virt_dev->real_port - 1].bw_table;
2098 tt_info = virt_dev->tt_info;
2099 /* If this TT already had active endpoints, the bandwidth for this TT
2100 * has already been added. Removing all periodic endpoints (and thus
2101 * making the TT enactive) will only decrease the bandwidth used.
2105 if (old_active_eps == 0 && tt_info->active_eps != 0) {
2106 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2110 /* Not sure why we would have no new active endpoints...
2112 * Maybe because of an Evaluate Context change for a hub update or a
2113 * control endpoint 0 max packet size change?
2114 * FIXME: skip the bandwidth calculation in that case.
2119 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2120 struct xhci_virt_device *virt_dev)
2122 unsigned int bw_reserved;
2124 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2125 if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2128 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2129 if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2136 * This algorithm is a very conservative estimate of the worst-case scheduling
2137 * scenario for any one interval. The hardware dynamically schedules the
2138 * packets, so we can't tell which microframe could be the limiting factor in
2139 * the bandwidth scheduling. This only takes into account periodic endpoints.
2141 * Obviously, we can't solve an NP complete problem to find the minimum worst
2142 * case scenario. Instead, we come up with an estimate that is no less than
2143 * the worst case bandwidth used for any one microframe, but may be an
2146 * We walk the requirements for each endpoint by interval, starting with the
2147 * smallest interval, and place packets in the schedule where there is only one
2148 * possible way to schedule packets for that interval. In order to simplify
2149 * this algorithm, we record the largest max packet size for each interval, and
2150 * assume all packets will be that size.
2152 * For interval 0, we obviously must schedule all packets for each interval.
2153 * The bandwidth for interval 0 is just the amount of data to be transmitted
2154 * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2155 * the number of packets).
2157 * For interval 1, we have two possible microframes to schedule those packets
2158 * in. For this algorithm, if we can schedule the same number of packets for
2159 * each possible scheduling opportunity (each microframe), we will do so. The
2160 * remaining number of packets will be saved to be transmitted in the gaps in
2161 * the next interval's scheduling sequence.
2163 * As we move those remaining packets to be scheduled with interval 2 packets,
2164 * we have to double the number of remaining packets to transmit. This is
2165 * because the intervals are actually powers of 2, and we would be transmitting
2166 * the previous interval's packets twice in this interval. We also have to be
2167 * sure that when we look at the largest max packet size for this interval, we
2168 * also look at the largest max packet size for the remaining packets and take
2169 * the greater of the two.
2171 * The algorithm continues to evenly distribute packets in each scheduling
2172 * opportunity, and push the remaining packets out, until we get to the last
2173 * interval. Then those packets and their associated overhead are just added
2174 * to the bandwidth used.
2176 static int xhci_check_bw_table(struct xhci_hcd *xhci,
2177 struct xhci_virt_device *virt_dev,
2180 unsigned int bw_reserved;
2181 unsigned int max_bandwidth;
2182 unsigned int bw_used;
2183 unsigned int block_size;
2184 struct xhci_interval_bw_table *bw_table;
2185 unsigned int packet_size = 0;
2186 unsigned int overhead = 0;
2187 unsigned int packets_transmitted = 0;
2188 unsigned int packets_remaining = 0;
2191 if (virt_dev->udev->speed == USB_SPEED_SUPER)
2192 return xhci_check_ss_bw(xhci, virt_dev);
2194 if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2195 max_bandwidth = HS_BW_LIMIT;
2196 /* Convert percent of bus BW reserved to blocks reserved */
2197 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2199 max_bandwidth = FS_BW_LIMIT;
2200 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2203 bw_table = virt_dev->bw_table;
2204 /* We need to translate the max packet size and max ESIT payloads into
2205 * the units the hardware uses.
2207 block_size = xhci_get_block_size(virt_dev->udev);
2209 /* If we are manipulating a LS/FS device under a HS hub, double check
2210 * that the HS bus has enough bandwidth if we are activing a new TT.
2212 if (virt_dev->tt_info) {
2213 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2214 "Recalculating BW for rootport %u",
2215 virt_dev->real_port);
2216 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2217 xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2218 "newly activated TT.\n");
2221 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2222 "Recalculating BW for TT slot %u port %u",
2223 virt_dev->tt_info->slot_id,
2224 virt_dev->tt_info->ttport);
2226 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2227 "Recalculating BW for rootport %u",
2228 virt_dev->real_port);
2231 /* Add in how much bandwidth will be used for interval zero, or the
2232 * rounded max ESIT payload + number of packets * largest overhead.
2234 bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2235 bw_table->interval_bw[0].num_packets *
2236 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2238 for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2239 unsigned int bw_added;
2240 unsigned int largest_mps;
2241 unsigned int interval_overhead;
2244 * How many packets could we transmit in this interval?
2245 * If packets didn't fit in the previous interval, we will need
2246 * to transmit that many packets twice within this interval.
2248 packets_remaining = 2 * packets_remaining +
2249 bw_table->interval_bw[i].num_packets;
2251 /* Find the largest max packet size of this or the previous
2254 if (list_empty(&bw_table->interval_bw[i].endpoints))
2257 struct xhci_virt_ep *virt_ep;
2258 struct list_head *ep_entry;
2260 ep_entry = bw_table->interval_bw[i].endpoints.next;
2261 virt_ep = list_entry(ep_entry,
2262 struct xhci_virt_ep, bw_endpoint_list);
2263 /* Convert to blocks, rounding up */
2264 largest_mps = DIV_ROUND_UP(
2265 virt_ep->bw_info.max_packet_size,
2268 if (largest_mps > packet_size)
2269 packet_size = largest_mps;
2271 /* Use the larger overhead of this or the previous interval. */
2272 interval_overhead = xhci_get_largest_overhead(
2273 &bw_table->interval_bw[i]);
2274 if (interval_overhead > overhead)
2275 overhead = interval_overhead;
2277 /* How many packets can we evenly distribute across
2278 * (1 << (i + 1)) possible scheduling opportunities?
2280 packets_transmitted = packets_remaining >> (i + 1);
2282 /* Add in the bandwidth used for those scheduled packets */
2283 bw_added = packets_transmitted * (overhead + packet_size);
2285 /* How many packets do we have remaining to transmit? */
2286 packets_remaining = packets_remaining % (1 << (i + 1));
2288 /* What largest max packet size should those packets have? */
2289 /* If we've transmitted all packets, don't carry over the
2290 * largest packet size.
2292 if (packets_remaining == 0) {
2295 } else if (packets_transmitted > 0) {
2296 /* Otherwise if we do have remaining packets, and we've
2297 * scheduled some packets in this interval, take the
2298 * largest max packet size from endpoints with this
2301 packet_size = largest_mps;
2302 overhead = interval_overhead;
2304 /* Otherwise carry over packet_size and overhead from the last
2305 * time we had a remainder.
2307 bw_used += bw_added;
2308 if (bw_used > max_bandwidth) {
2309 xhci_warn(xhci, "Not enough bandwidth. "
2310 "Proposed: %u, Max: %u\n",
2311 bw_used, max_bandwidth);
2316 * Ok, we know we have some packets left over after even-handedly
2317 * scheduling interval 15. We don't know which microframes they will
2318 * fit into, so we over-schedule and say they will be scheduled every
2321 if (packets_remaining > 0)
2322 bw_used += overhead + packet_size;
2324 if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2325 unsigned int port_index = virt_dev->real_port - 1;
2327 /* OK, we're manipulating a HS device attached to a
2328 * root port bandwidth domain. Include the number of active TTs
2329 * in the bandwidth used.
2331 bw_used += TT_HS_OVERHEAD *
2332 xhci->rh_bw[port_index].num_active_tts;
2335 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2336 "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2337 "Available: %u " "percent",
2338 bw_used, max_bandwidth, bw_reserved,
2339 (max_bandwidth - bw_used - bw_reserved) * 100 /
2342 bw_used += bw_reserved;
2343 if (bw_used > max_bandwidth) {
2344 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2345 bw_used, max_bandwidth);
2349 bw_table->bw_used = bw_used;
2353 static bool xhci_is_async_ep(unsigned int ep_type)
2355 return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2356 ep_type != ISOC_IN_EP &&
2357 ep_type != INT_IN_EP);
2360 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2362 return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
2365 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2367 unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2369 if (ep_bw->ep_interval == 0)
2370 return SS_OVERHEAD_BURST +
2371 (ep_bw->mult * ep_bw->num_packets *
2372 (SS_OVERHEAD + mps));
2373 return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2374 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2375 1 << ep_bw->ep_interval);
2379 void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2380 struct xhci_bw_info *ep_bw,
2381 struct xhci_interval_bw_table *bw_table,
2382 struct usb_device *udev,
2383 struct xhci_virt_ep *virt_ep,
2384 struct xhci_tt_bw_info *tt_info)
2386 struct xhci_interval_bw *interval_bw;
2387 int normalized_interval;
2389 if (xhci_is_async_ep(ep_bw->type))
2392 if (udev->speed == USB_SPEED_SUPER) {
2393 if (xhci_is_sync_in_ep(ep_bw->type))
2394 xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2395 xhci_get_ss_bw_consumed(ep_bw);
2397 xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2398 xhci_get_ss_bw_consumed(ep_bw);
2402 /* SuperSpeed endpoints never get added to intervals in the table, so
2403 * this check is only valid for HS/FS/LS devices.
2405 if (list_empty(&virt_ep->bw_endpoint_list))
2407 /* For LS/FS devices, we need to translate the interval expressed in
2408 * microframes to frames.
2410 if (udev->speed == USB_SPEED_HIGH)
2411 normalized_interval = ep_bw->ep_interval;
2413 normalized_interval = ep_bw->ep_interval - 3;
2415 if (normalized_interval == 0)
2416 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2417 interval_bw = &bw_table->interval_bw[normalized_interval];
2418 interval_bw->num_packets -= ep_bw->num_packets;
2419 switch (udev->speed) {
2421 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2423 case USB_SPEED_FULL:
2424 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2426 case USB_SPEED_HIGH:
2427 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2429 case USB_SPEED_SUPER:
2430 case USB_SPEED_UNKNOWN:
2431 case USB_SPEED_WIRELESS:
2432 /* Should never happen because only LS/FS/HS endpoints will get
2433 * added to the endpoint list.
2438 tt_info->active_eps -= 1;
2439 list_del_init(&virt_ep->bw_endpoint_list);
2442 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2443 struct xhci_bw_info *ep_bw,
2444 struct xhci_interval_bw_table *bw_table,
2445 struct usb_device *udev,
2446 struct xhci_virt_ep *virt_ep,
2447 struct xhci_tt_bw_info *tt_info)
2449 struct xhci_interval_bw *interval_bw;
2450 struct xhci_virt_ep *smaller_ep;
2451 int normalized_interval;
2453 if (xhci_is_async_ep(ep_bw->type))
2456 if (udev->speed == USB_SPEED_SUPER) {
2457 if (xhci_is_sync_in_ep(ep_bw->type))
2458 xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2459 xhci_get_ss_bw_consumed(ep_bw);
2461 xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2462 xhci_get_ss_bw_consumed(ep_bw);
2466 /* For LS/FS devices, we need to translate the interval expressed in
2467 * microframes to frames.
2469 if (udev->speed == USB_SPEED_HIGH)
2470 normalized_interval = ep_bw->ep_interval;
2472 normalized_interval = ep_bw->ep_interval - 3;
2474 if (normalized_interval == 0)
2475 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2476 interval_bw = &bw_table->interval_bw[normalized_interval];
2477 interval_bw->num_packets += ep_bw->num_packets;
2478 switch (udev->speed) {
2480 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2482 case USB_SPEED_FULL:
2483 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2485 case USB_SPEED_HIGH:
2486 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2488 case USB_SPEED_SUPER:
2489 case USB_SPEED_UNKNOWN:
2490 case USB_SPEED_WIRELESS:
2491 /* Should never happen because only LS/FS/HS endpoints will get
2492 * added to the endpoint list.
2498 tt_info->active_eps += 1;
2499 /* Insert the endpoint into the list, largest max packet size first. */
2500 list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2502 if (ep_bw->max_packet_size >=
2503 smaller_ep->bw_info.max_packet_size) {
2504 /* Add the new ep before the smaller endpoint */
2505 list_add_tail(&virt_ep->bw_endpoint_list,
2506 &smaller_ep->bw_endpoint_list);
2510 /* Add the new endpoint at the end of the list. */
2511 list_add_tail(&virt_ep->bw_endpoint_list,
2512 &interval_bw->endpoints);
2515 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2516 struct xhci_virt_device *virt_dev,
2519 struct xhci_root_port_bw_info *rh_bw_info;
2520 if (!virt_dev->tt_info)
2523 rh_bw_info = &xhci->rh_bw[virt_dev->real_port - 1];
2524 if (old_active_eps == 0 &&
2525 virt_dev->tt_info->active_eps != 0) {
2526 rh_bw_info->num_active_tts += 1;
2527 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2528 } else if (old_active_eps != 0 &&
2529 virt_dev->tt_info->active_eps == 0) {
2530 rh_bw_info->num_active_tts -= 1;
2531 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2535 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2536 struct xhci_virt_device *virt_dev,
2537 struct xhci_container_ctx *in_ctx)
2539 struct xhci_bw_info ep_bw_info[31];
2541 struct xhci_input_control_ctx *ctrl_ctx;
2542 int old_active_eps = 0;
2544 if (virt_dev->tt_info)
2545 old_active_eps = virt_dev->tt_info->active_eps;
2547 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2549 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2554 for (i = 0; i < 31; i++) {
2555 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2558 /* Make a copy of the BW info in case we need to revert this */
2559 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2560 sizeof(ep_bw_info[i]));
2561 /* Drop the endpoint from the interval table if the endpoint is
2562 * being dropped or changed.
2564 if (EP_IS_DROPPED(ctrl_ctx, i))
2565 xhci_drop_ep_from_interval_table(xhci,
2566 &virt_dev->eps[i].bw_info,
2572 /* Overwrite the information stored in the endpoints' bw_info */
2573 xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2574 for (i = 0; i < 31; i++) {
2575 /* Add any changed or added endpoints to the interval table */
2576 if (EP_IS_ADDED(ctrl_ctx, i))
2577 xhci_add_ep_to_interval_table(xhci,
2578 &virt_dev->eps[i].bw_info,
2585 if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2586 /* Ok, this fits in the bandwidth we have.
2587 * Update the number of active TTs.
2589 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2593 /* We don't have enough bandwidth for this, revert the stored info. */
2594 for (i = 0; i < 31; i++) {
2595 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2598 /* Drop the new copies of any added or changed endpoints from
2599 * the interval table.
2601 if (EP_IS_ADDED(ctrl_ctx, i)) {
2602 xhci_drop_ep_from_interval_table(xhci,
2603 &virt_dev->eps[i].bw_info,
2609 /* Revert the endpoint back to its old information */
2610 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2611 sizeof(ep_bw_info[i]));
2612 /* Add any changed or dropped endpoints back into the table */
2613 if (EP_IS_DROPPED(ctrl_ctx, i))
2614 xhci_add_ep_to_interval_table(xhci,
2615 &virt_dev->eps[i].bw_info,
2625 /* Issue a configure endpoint command or evaluate context command
2626 * and wait for it to finish.
2628 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2629 struct usb_device *udev,
2630 struct xhci_command *command,
2631 bool ctx_change, bool must_succeed)
2634 unsigned long flags;
2635 struct xhci_input_control_ctx *ctrl_ctx;
2636 struct xhci_virt_device *virt_dev;
2641 spin_lock_irqsave(&xhci->lock, flags);
2642 virt_dev = xhci->devs[udev->slot_id];
2644 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2646 spin_unlock_irqrestore(&xhci->lock, flags);
2647 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2652 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2653 xhci_reserve_host_resources(xhci, ctrl_ctx)) {
2654 spin_unlock_irqrestore(&xhci->lock, flags);
2655 xhci_warn(xhci, "Not enough host resources, "
2656 "active endpoint contexts = %u\n",
2657 xhci->num_active_eps);
2660 if ((xhci->quirks & XHCI_SW_BW_CHECKING) &&
2661 xhci_reserve_bandwidth(xhci, virt_dev, command->in_ctx)) {
2662 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2663 xhci_free_host_resources(xhci, ctrl_ctx);
2664 spin_unlock_irqrestore(&xhci->lock, flags);
2665 xhci_warn(xhci, "Not enough bandwidth\n");
2670 ret = xhci_queue_configure_endpoint(xhci, command,
2671 command->in_ctx->dma,
2672 udev->slot_id, must_succeed);
2674 ret = xhci_queue_evaluate_context(xhci, command,
2675 command->in_ctx->dma,
2676 udev->slot_id, must_succeed);
2678 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2679 xhci_free_host_resources(xhci, ctrl_ctx);
2680 spin_unlock_irqrestore(&xhci->lock, flags);
2681 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2682 "FIXME allocate a new ring segment");
2685 xhci_ring_cmd_db(xhci);
2686 spin_unlock_irqrestore(&xhci->lock, flags);
2688 /* Wait for the configure endpoint command to complete */
2689 wait_for_completion(command->completion);
2692 ret = xhci_configure_endpoint_result(xhci, udev,
2695 ret = xhci_evaluate_context_result(xhci, udev,
2698 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2699 spin_lock_irqsave(&xhci->lock, flags);
2700 /* If the command failed, remove the reserved resources.
2701 * Otherwise, clean up the estimate to include dropped eps.
2704 xhci_free_host_resources(xhci, ctrl_ctx);
2706 xhci_finish_resource_reservation(xhci, ctrl_ctx);
2707 spin_unlock_irqrestore(&xhci->lock, flags);
2712 static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
2713 struct xhci_virt_device *vdev, int i)
2715 struct xhci_virt_ep *ep = &vdev->eps[i];
2717 if (ep->ep_state & EP_HAS_STREAMS) {
2718 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
2719 xhci_get_endpoint_address(i));
2720 xhci_free_stream_info(xhci, ep->stream_info);
2721 ep->stream_info = NULL;
2722 ep->ep_state &= ~EP_HAS_STREAMS;
2726 /* Called after one or more calls to xhci_add_endpoint() or
2727 * xhci_drop_endpoint(). If this call fails, the USB core is expected
2728 * to call xhci_reset_bandwidth().
2730 * Since we are in the middle of changing either configuration or
2731 * installing a new alt setting, the USB core won't allow URBs to be
2732 * enqueued for any endpoint on the old config or interface. Nothing
2733 * else should be touching the xhci->devs[slot_id] structure, so we
2734 * don't need to take the xhci->lock for manipulating that.
2736 int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2740 struct xhci_hcd *xhci;
2741 struct xhci_virt_device *virt_dev;
2742 struct xhci_input_control_ctx *ctrl_ctx;
2743 struct xhci_slot_ctx *slot_ctx;
2744 struct xhci_command *command;
2746 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2749 xhci = hcd_to_xhci(hcd);
2750 if (xhci->xhc_state & XHCI_STATE_DYING)
2753 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2754 virt_dev = xhci->devs[udev->slot_id];
2756 command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
2760 command->in_ctx = virt_dev->in_ctx;
2762 /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
2763 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2765 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2768 goto command_cleanup;
2770 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2771 ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
2772 ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
2774 /* Don't issue the command if there's no endpoints to update. */
2775 if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2776 ctrl_ctx->drop_flags == 0) {
2778 goto command_cleanup;
2780 /* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
2781 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2782 for (i = 31; i >= 1; i--) {
2783 __le32 le32 = cpu_to_le32(BIT(i));
2785 if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
2786 || (ctrl_ctx->add_flags & le32) || i == 1) {
2787 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2788 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
2792 xhci_dbg(xhci, "New Input Control Context:\n");
2793 xhci_dbg_ctx(xhci, virt_dev->in_ctx,
2794 LAST_CTX_TO_EP_NUM(le32_to_cpu(slot_ctx->dev_info)));
2796 ret = xhci_configure_endpoint(xhci, udev, command,
2799 /* Callee should call reset_bandwidth() */
2800 goto command_cleanup;
2802 xhci_dbg(xhci, "Output context after successful config ep cmd:\n");
2803 xhci_dbg_ctx(xhci, virt_dev->out_ctx,
2804 LAST_CTX_TO_EP_NUM(le32_to_cpu(slot_ctx->dev_info)));
2806 /* Free any rings that were dropped, but not changed. */
2807 for (i = 1; i < 31; ++i) {
2808 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2809 !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
2810 xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
2811 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2814 xhci_zero_in_ctx(xhci, virt_dev);
2816 * Install any rings for completely new endpoints or changed endpoints,
2817 * and free or cache any old rings from changed endpoints.
2819 for (i = 1; i < 31; ++i) {
2820 if (!virt_dev->eps[i].new_ring)
2822 /* Only cache or free the old ring if it exists.
2823 * It may not if this is the first add of an endpoint.
2825 if (virt_dev->eps[i].ring) {
2826 xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
2828 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2829 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
2830 virt_dev->eps[i].new_ring = NULL;
2833 kfree(command->completion);
2839 void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2841 struct xhci_hcd *xhci;
2842 struct xhci_virt_device *virt_dev;
2845 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2848 xhci = hcd_to_xhci(hcd);
2850 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2851 virt_dev = xhci->devs[udev->slot_id];
2852 /* Free any rings allocated for added endpoints */
2853 for (i = 0; i < 31; ++i) {
2854 if (virt_dev->eps[i].new_ring) {
2855 xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
2856 virt_dev->eps[i].new_ring = NULL;
2859 xhci_zero_in_ctx(xhci, virt_dev);
2862 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
2863 struct xhci_container_ctx *in_ctx,
2864 struct xhci_container_ctx *out_ctx,
2865 struct xhci_input_control_ctx *ctrl_ctx,
2866 u32 add_flags, u32 drop_flags)
2868 ctrl_ctx->add_flags = cpu_to_le32(add_flags);
2869 ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
2870 xhci_slot_copy(xhci, in_ctx, out_ctx);
2871 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2873 xhci_dbg(xhci, "Input Context:\n");
2874 xhci_dbg_ctx(xhci, in_ctx, xhci_last_valid_endpoint(add_flags));
2877 static void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
2878 unsigned int slot_id, unsigned int ep_index,
2879 struct xhci_dequeue_state *deq_state)
2881 struct xhci_input_control_ctx *ctrl_ctx;
2882 struct xhci_container_ctx *in_ctx;
2883 struct xhci_ep_ctx *ep_ctx;
2887 in_ctx = xhci->devs[slot_id]->in_ctx;
2888 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2890 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2895 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
2896 xhci->devs[slot_id]->out_ctx, ep_index);
2897 ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
2898 addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
2899 deq_state->new_deq_ptr);
2901 xhci_warn(xhci, "WARN Cannot submit config ep after "
2902 "reset ep command\n");
2903 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
2904 deq_state->new_deq_seg,
2905 deq_state->new_deq_ptr);
2908 ep_ctx->deq = cpu_to_le64(addr | deq_state->new_cycle_state);
2910 added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
2911 xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
2912 xhci->devs[slot_id]->out_ctx, ctrl_ctx,
2913 added_ctxs, added_ctxs);
2916 void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci,
2917 unsigned int ep_index, struct xhci_td *td)
2919 struct xhci_dequeue_state deq_state;
2920 struct xhci_virt_ep *ep;
2921 struct usb_device *udev = td->urb->dev;
2923 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2924 "Cleaning up stalled endpoint ring");
2925 ep = &xhci->devs[udev->slot_id]->eps[ep_index];
2926 /* We need to move the HW's dequeue pointer past this TD,
2927 * or it will attempt to resend it on the next doorbell ring.
2929 xhci_find_new_dequeue_state(xhci, udev->slot_id,
2930 ep_index, ep->stopped_stream, td, &deq_state);
2932 if (!deq_state.new_deq_ptr || !deq_state.new_deq_seg)
2935 /* HW with the reset endpoint quirk will use the saved dequeue state to
2936 * issue a configure endpoint command later.
2938 if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
2939 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2940 "Queueing new dequeue state");
2941 xhci_queue_new_dequeue_state(xhci, udev->slot_id,
2942 ep_index, ep->stopped_stream, &deq_state);
2944 /* Better hope no one uses the input context between now and the
2945 * reset endpoint completion!
2946 * XXX: No idea how this hardware will react when stream rings
2949 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2950 "Setting up input context for "
2951 "configure endpoint command");
2952 xhci_setup_input_ctx_for_quirk(xhci, udev->slot_id,
2953 ep_index, &deq_state);
2957 /* Called after clearing a halted device. USB core should have sent the control
2958 * message to clear the device halt condition. The host side of the halt should
2959 * already be cleared with a reset endpoint command issued immediately when the
2960 * STALL tx event was received.
2963 void xhci_endpoint_reset(struct usb_hcd *hcd,
2964 struct usb_host_endpoint *ep)
2966 struct xhci_hcd *xhci;
2967 struct usb_device *udev;
2968 struct xhci_virt_device *virt_dev;
2969 struct xhci_virt_ep *virt_ep;
2970 struct xhci_input_control_ctx *ctrl_ctx;
2971 struct xhci_command *command;
2972 unsigned int ep_index, ep_state;
2973 unsigned long flags;
2976 xhci = hcd_to_xhci(hcd);
2977 udev = (struct usb_device *) ep->hcpriv;
2980 virt_dev = xhci->devs[udev->slot_id];
2981 ep_index = xhci_get_endpoint_index(&ep->desc);
2982 virt_ep = &virt_dev->eps[ep_index];
2983 ep_state = virt_ep->ep_state;
2986 * Implement the config ep command in xhci 4.6.8 additional note:
2987 * The Reset Endpoint Command may only be issued to endpoints in the
2988 * Halted state. If software wishes reset the Data Toggle or Sequence
2989 * Number of an endpoint that isn't in the Halted state, then software
2990 * may issue a Configure Endpoint Command with the Drop and Add bits set
2991 * for the target endpoint. that is in the Stopped state.
2994 if (ep_state & SET_DEQ_PENDING || ep_state & EP_RECENTLY_HALTED) {
2995 virt_ep->ep_state &= ~EP_RECENTLY_HALTED;
2996 xhci_dbg(xhci, "ep recently halted, no toggle reset needed\n");
3000 /* Only interrupt and bulk ep's use Data toggle, USB2 spec 5.5.4-> */
3001 if (usb_endpoint_xfer_control(&ep->desc) ||
3002 usb_endpoint_xfer_isoc(&ep->desc))
3005 ep_flag = xhci_get_endpoint_flag(&ep->desc);
3007 if (ep_flag == SLOT_FLAG || ep_flag == EP0_FLAG)
3010 command = xhci_alloc_command(xhci, true, true, GFP_NOWAIT);
3012 xhci_err(xhci, "Could not allocate xHCI command structure.\n");
3016 spin_lock_irqsave(&xhci->lock, flags);
3018 /* block ringing ep doorbell */
3019 virt_ep->ep_state |= EP_CONFIG_PENDING;
3022 * Make sure endpoint ring is empty before resetting the toggle/seq.
3023 * Driver is required to synchronously cancel all transfer request.
3025 * xhci 4.6.6 says we can issue a configure endpoint command on a
3026 * running endpoint ring as long as it's idle (queue empty)
3029 if (!list_empty(&virt_ep->ring->td_list)) {
3030 dev_err(&udev->dev, "EP not empty, refuse reset\n");
3031 spin_unlock_irqrestore(&xhci->lock, flags);
3035 xhci_dbg(xhci, "Reset toggle/seq for slot %d, ep_index: %d\n",
3036 udev->slot_id, ep_index);
3038 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3040 xhci_err(xhci, "Could not get input context, bad type. virt_dev: %p, in_ctx %p\n",
3041 virt_dev, virt_dev->in_ctx);
3042 spin_unlock_irqrestore(&xhci->lock, flags);
3045 xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3046 virt_dev->out_ctx, ctrl_ctx,
3048 xhci_endpoint_copy(xhci, command->in_ctx, virt_dev->out_ctx, ep_index);
3050 xhci_queue_configure_endpoint(xhci, command, command->in_ctx->dma,
3051 udev->slot_id, false);
3052 xhci_ring_cmd_db(xhci);
3053 spin_unlock_irqrestore(&xhci->lock, flags);
3055 wait_for_completion(command->completion);
3058 virt_ep->ep_state &= ~EP_CONFIG_PENDING;
3059 xhci_free_command(xhci, command);
3062 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
3063 struct usb_device *udev, struct usb_host_endpoint *ep,
3064 unsigned int slot_id)
3067 unsigned int ep_index;
3068 unsigned int ep_state;
3072 ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
3075 if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
3076 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
3077 " descriptor for ep 0x%x does not support streams\n",
3078 ep->desc.bEndpointAddress);
3082 ep_index = xhci_get_endpoint_index(&ep->desc);
3083 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3084 if (ep_state & EP_HAS_STREAMS ||
3085 ep_state & EP_GETTING_STREAMS) {
3086 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
3087 "already has streams set up.\n",
3088 ep->desc.bEndpointAddress);
3089 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
3090 "dynamic stream context array reallocation.\n");
3093 if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
3094 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
3095 "endpoint 0x%x; URBs are pending.\n",
3096 ep->desc.bEndpointAddress);
3102 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
3103 unsigned int *num_streams, unsigned int *num_stream_ctxs)
3105 unsigned int max_streams;
3107 /* The stream context array size must be a power of two */
3108 *num_stream_ctxs = roundup_pow_of_two(*num_streams);
3110 * Find out how many primary stream array entries the host controller
3111 * supports. Later we may use secondary stream arrays (similar to 2nd
3112 * level page entries), but that's an optional feature for xHCI host
3113 * controllers. xHCs must support at least 4 stream IDs.
3115 max_streams = HCC_MAX_PSA(xhci->hcc_params);
3116 if (*num_stream_ctxs > max_streams) {
3117 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
3119 *num_stream_ctxs = max_streams;
3120 *num_streams = max_streams;
3124 /* Returns an error code if one of the endpoint already has streams.
3125 * This does not change any data structures, it only checks and gathers
3128 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
3129 struct usb_device *udev,
3130 struct usb_host_endpoint **eps, unsigned int num_eps,
3131 unsigned int *num_streams, u32 *changed_ep_bitmask)
3133 unsigned int max_streams;
3134 unsigned int endpoint_flag;
3138 for (i = 0; i < num_eps; i++) {
3139 ret = xhci_check_streams_endpoint(xhci, udev,
3140 eps[i], udev->slot_id);
3144 max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
3145 if (max_streams < (*num_streams - 1)) {
3146 xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
3147 eps[i]->desc.bEndpointAddress,
3149 *num_streams = max_streams+1;
3152 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
3153 if (*changed_ep_bitmask & endpoint_flag)
3155 *changed_ep_bitmask |= endpoint_flag;
3160 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
3161 struct usb_device *udev,
3162 struct usb_host_endpoint **eps, unsigned int num_eps)
3164 u32 changed_ep_bitmask = 0;
3165 unsigned int slot_id;
3166 unsigned int ep_index;
3167 unsigned int ep_state;
3170 slot_id = udev->slot_id;
3171 if (!xhci->devs[slot_id])
3174 for (i = 0; i < num_eps; i++) {
3175 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3176 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3177 /* Are streams already being freed for the endpoint? */
3178 if (ep_state & EP_GETTING_NO_STREAMS) {
3179 xhci_warn(xhci, "WARN Can't disable streams for "
3181 "streams are being disabled already\n",
3182 eps[i]->desc.bEndpointAddress);
3185 /* Are there actually any streams to free? */
3186 if (!(ep_state & EP_HAS_STREAMS) &&
3187 !(ep_state & EP_GETTING_STREAMS)) {
3188 xhci_warn(xhci, "WARN Can't disable streams for "
3190 "streams are already disabled!\n",
3191 eps[i]->desc.bEndpointAddress);
3192 xhci_warn(xhci, "WARN xhci_free_streams() called "
3193 "with non-streams endpoint\n");
3196 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
3198 return changed_ep_bitmask;
3202 * The USB device drivers use this function (though the HCD interface in USB
3203 * core) to prepare a set of bulk endpoints to use streams. Streams are used to
3204 * coordinate mass storage command queueing across multiple endpoints (basically
3205 * a stream ID == a task ID).
3207 * Setting up streams involves allocating the same size stream context array
3208 * for each endpoint and issuing a configure endpoint command for all endpoints.
3210 * Don't allow the call to succeed if one endpoint only supports one stream
3211 * (which means it doesn't support streams at all).
3213 * Drivers may get less stream IDs than they asked for, if the host controller
3214 * hardware or endpoints claim they can't support the number of requested
3217 int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3218 struct usb_host_endpoint **eps, unsigned int num_eps,
3219 unsigned int num_streams, gfp_t mem_flags)
3222 struct xhci_hcd *xhci;
3223 struct xhci_virt_device *vdev;
3224 struct xhci_command *config_cmd;
3225 struct xhci_input_control_ctx *ctrl_ctx;
3226 unsigned int ep_index;
3227 unsigned int num_stream_ctxs;
3228 unsigned long flags;
3229 u32 changed_ep_bitmask = 0;
3234 /* Add one to the number of streams requested to account for
3235 * stream 0 that is reserved for xHCI usage.
3238 xhci = hcd_to_xhci(hcd);
3239 xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3242 /* MaxPSASize value 0 (2 streams) means streams are not supported */
3243 if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
3244 HCC_MAX_PSA(xhci->hcc_params) < 4) {
3245 xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3249 config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
3251 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
3254 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
3256 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3258 xhci_free_command(xhci, config_cmd);
3262 /* Check to make sure all endpoints are not already configured for
3263 * streams. While we're at it, find the maximum number of streams that
3264 * all the endpoints will support and check for duplicate endpoints.
3266 spin_lock_irqsave(&xhci->lock, flags);
3267 ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3268 num_eps, &num_streams, &changed_ep_bitmask);
3270 xhci_free_command(xhci, config_cmd);
3271 spin_unlock_irqrestore(&xhci->lock, flags);
3274 if (num_streams <= 1) {
3275 xhci_warn(xhci, "WARN: endpoints can't handle "
3276 "more than one stream.\n");
3277 xhci_free_command(xhci, config_cmd);
3278 spin_unlock_irqrestore(&xhci->lock, flags);
3281 vdev = xhci->devs[udev->slot_id];
3282 /* Mark each endpoint as being in transition, so
3283 * xhci_urb_enqueue() will reject all URBs.
3285 for (i = 0; i < num_eps; i++) {
3286 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3287 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3289 spin_unlock_irqrestore(&xhci->lock, flags);
3291 /* Setup internal data structures and allocate HW data structures for
3292 * streams (but don't install the HW structures in the input context
3293 * until we're sure all memory allocation succeeded).
3295 xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3296 xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3297 num_stream_ctxs, num_streams);
3299 for (i = 0; i < num_eps; i++) {
3300 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3301 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3303 num_streams, mem_flags);
3304 if (!vdev->eps[ep_index].stream_info)
3306 /* Set maxPstreams in endpoint context and update deq ptr to
3307 * point to stream context array. FIXME
3311 /* Set up the input context for a configure endpoint command. */
3312 for (i = 0; i < num_eps; i++) {
3313 struct xhci_ep_ctx *ep_ctx;
3315 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3316 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3318 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3319 vdev->out_ctx, ep_index);
3320 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3321 vdev->eps[ep_index].stream_info);
3323 /* Tell the HW to drop its old copy of the endpoint context info
3324 * and add the updated copy from the input context.
3326 xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3327 vdev->out_ctx, ctrl_ctx,
3328 changed_ep_bitmask, changed_ep_bitmask);
3330 /* Issue and wait for the configure endpoint command */
3331 ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3334 /* xHC rejected the configure endpoint command for some reason, so we
3335 * leave the old ring intact and free our internal streams data
3341 spin_lock_irqsave(&xhci->lock, flags);
3342 for (i = 0; i < num_eps; i++) {
3343 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3344 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3345 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3346 udev->slot_id, ep_index);
3347 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3349 xhci_free_command(xhci, config_cmd);
3350 spin_unlock_irqrestore(&xhci->lock, flags);
3352 /* Subtract 1 for stream 0, which drivers can't use */
3353 return num_streams - 1;
3356 /* If it didn't work, free the streams! */
3357 for (i = 0; i < num_eps; i++) {
3358 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3359 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3360 vdev->eps[ep_index].stream_info = NULL;
3361 /* FIXME Unset maxPstreams in endpoint context and
3362 * update deq ptr to point to normal string ring.
3364 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3365 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3366 xhci_endpoint_zero(xhci, vdev, eps[i]);
3368 xhci_free_command(xhci, config_cmd);
3372 /* Transition the endpoint from using streams to being a "normal" endpoint
3375 * Modify the endpoint context state, submit a configure endpoint command,
3376 * and free all endpoint rings for streams if that completes successfully.
3378 int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3379 struct usb_host_endpoint **eps, unsigned int num_eps,
3383 struct xhci_hcd *xhci;
3384 struct xhci_virt_device *vdev;
3385 struct xhci_command *command;
3386 struct xhci_input_control_ctx *ctrl_ctx;
3387 unsigned int ep_index;
3388 unsigned long flags;
3389 u32 changed_ep_bitmask;
3391 xhci = hcd_to_xhci(hcd);
3392 vdev = xhci->devs[udev->slot_id];
3394 /* Set up a configure endpoint command to remove the streams rings */
3395 spin_lock_irqsave(&xhci->lock, flags);
3396 changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3397 udev, eps, num_eps);
3398 if (changed_ep_bitmask == 0) {
3399 spin_unlock_irqrestore(&xhci->lock, flags);
3403 /* Use the xhci_command structure from the first endpoint. We may have
3404 * allocated too many, but the driver may call xhci_free_streams() for
3405 * each endpoint it grouped into one call to xhci_alloc_streams().
3407 ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3408 command = vdev->eps[ep_index].stream_info->free_streams_command;
3409 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3411 spin_unlock_irqrestore(&xhci->lock, flags);
3412 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3417 for (i = 0; i < num_eps; i++) {
3418 struct xhci_ep_ctx *ep_ctx;
3420 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3421 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3422 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3423 EP_GETTING_NO_STREAMS;
3425 xhci_endpoint_copy(xhci, command->in_ctx,
3426 vdev->out_ctx, ep_index);
3427 xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3428 &vdev->eps[ep_index]);
3430 xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3431 vdev->out_ctx, ctrl_ctx,
3432 changed_ep_bitmask, changed_ep_bitmask);
3433 spin_unlock_irqrestore(&xhci->lock, flags);
3435 /* Issue and wait for the configure endpoint command,
3436 * which must succeed.
3438 ret = xhci_configure_endpoint(xhci, udev, command,
3441 /* xHC rejected the configure endpoint command for some reason, so we
3442 * leave the streams rings intact.
3447 spin_lock_irqsave(&xhci->lock, flags);
3448 for (i = 0; i < num_eps; i++) {
3449 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3450 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3451 vdev->eps[ep_index].stream_info = NULL;
3452 /* FIXME Unset maxPstreams in endpoint context and
3453 * update deq ptr to point to normal string ring.
3455 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3456 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3458 spin_unlock_irqrestore(&xhci->lock, flags);
3464 * Deletes endpoint resources for endpoints that were active before a Reset
3465 * Device command, or a Disable Slot command. The Reset Device command leaves
3466 * the control endpoint intact, whereas the Disable Slot command deletes it.
3468 * Must be called with xhci->lock held.
3470 void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3471 struct xhci_virt_device *virt_dev, bool drop_control_ep)
3474 unsigned int num_dropped_eps = 0;
3475 unsigned int drop_flags = 0;
3477 for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3478 if (virt_dev->eps[i].ring) {
3479 drop_flags |= 1 << i;
3483 xhci->num_active_eps -= num_dropped_eps;
3484 if (num_dropped_eps)
3485 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3486 "Dropped %u ep ctxs, flags = 0x%x, "
3488 num_dropped_eps, drop_flags,
3489 xhci->num_active_eps);
3493 * This submits a Reset Device Command, which will set the device state to 0,
3494 * set the device address to 0, and disable all the endpoints except the default
3495 * control endpoint. The USB core should come back and call
3496 * xhci_address_device(), and then re-set up the configuration. If this is
3497 * called because of a usb_reset_and_verify_device(), then the old alternate
3498 * settings will be re-installed through the normal bandwidth allocation
3501 * Wait for the Reset Device command to finish. Remove all structures
3502 * associated with the endpoints that were disabled. Clear the input device
3503 * structure? Cache the rings? Reset the control endpoint 0 max packet size?
3505 * If the virt_dev to be reset does not exist or does not match the udev,
3506 * it means the device is lost, possibly due to the xHC restore error and
3507 * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3508 * re-allocate the device.
3510 int xhci_discover_or_reset_device(struct usb_hcd *hcd, struct usb_device *udev)
3513 unsigned long flags;
3514 struct xhci_hcd *xhci;
3515 unsigned int slot_id;
3516 struct xhci_virt_device *virt_dev;
3517 struct xhci_command *reset_device_cmd;
3518 int last_freed_endpoint;
3519 struct xhci_slot_ctx *slot_ctx;
3520 int old_active_eps = 0;
3522 ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3525 xhci = hcd_to_xhci(hcd);
3526 slot_id = udev->slot_id;
3527 virt_dev = xhci->devs[slot_id];
3529 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3530 "not exist. Re-allocate the device\n", slot_id);
3531 ret = xhci_alloc_dev(hcd, udev);
3538 if (virt_dev->udev != udev) {
3539 /* If the virt_dev and the udev does not match, this virt_dev
3540 * may belong to another udev.
3541 * Re-allocate the device.
3543 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3544 "not match the udev. Re-allocate the device\n",
3546 ret = xhci_alloc_dev(hcd, udev);
3553 /* If device is not setup, there is no point in resetting it */
3554 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3555 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3556 SLOT_STATE_DISABLED)
3559 xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3560 /* Allocate the command structure that holds the struct completion.
3561 * Assume we're in process context, since the normal device reset
3562 * process has to wait for the device anyway. Storage devices are
3563 * reset as part of error handling, so use GFP_NOIO instead of
3566 reset_device_cmd = xhci_alloc_command(xhci, false, true, GFP_NOIO);
3567 if (!reset_device_cmd) {
3568 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3572 /* Attempt to submit the Reset Device command to the command ring */
3573 spin_lock_irqsave(&xhci->lock, flags);
3575 ret = xhci_queue_reset_device(xhci, reset_device_cmd, slot_id);
3577 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3578 spin_unlock_irqrestore(&xhci->lock, flags);
3579 goto command_cleanup;
3581 xhci_ring_cmd_db(xhci);
3582 spin_unlock_irqrestore(&xhci->lock, flags);
3584 /* Wait for the Reset Device command to finish */
3585 wait_for_completion(reset_device_cmd->completion);
3587 /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3588 * unless we tried to reset a slot ID that wasn't enabled,
3589 * or the device wasn't in the addressed or configured state.
3591 ret = reset_device_cmd->status;
3593 case COMP_CMD_ABORT:
3595 xhci_warn(xhci, "Timeout waiting for reset device command\n");
3597 goto command_cleanup;
3598 case COMP_EBADSLT: /* 0.95 completion code for bad slot ID */
3599 case COMP_CTX_STATE: /* 0.96 completion code for same thing */
3600 xhci_dbg(xhci, "Can't reset device (slot ID %u) in %s state\n",
3602 xhci_get_slot_state(xhci, virt_dev->out_ctx));
3603 xhci_dbg(xhci, "Not freeing device rings.\n");
3604 /* Don't treat this as an error. May change my mind later. */
3606 goto command_cleanup;
3608 xhci_dbg(xhci, "Successful reset device command.\n");
3611 if (xhci_is_vendor_info_code(xhci, ret))
3613 xhci_warn(xhci, "Unknown completion code %u for "
3614 "reset device command.\n", ret);
3616 goto command_cleanup;
3619 /* Free up host controller endpoint resources */
3620 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3621 spin_lock_irqsave(&xhci->lock, flags);
3622 /* Don't delete the default control endpoint resources */
3623 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
3624 spin_unlock_irqrestore(&xhci->lock, flags);
3627 /* Everything but endpoint 0 is disabled, so free or cache the rings. */
3628 last_freed_endpoint = 1;
3629 for (i = 1; i < 31; ++i) {
3630 struct xhci_virt_ep *ep = &virt_dev->eps[i];
3632 if (ep->ep_state & EP_HAS_STREAMS) {
3633 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
3634 xhci_get_endpoint_address(i));
3635 xhci_free_stream_info(xhci, ep->stream_info);
3636 ep->stream_info = NULL;
3637 ep->ep_state &= ~EP_HAS_STREAMS;
3641 xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
3642 last_freed_endpoint = i;
3644 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
3645 xhci_drop_ep_from_interval_table(xhci,
3646 &virt_dev->eps[i].bw_info,
3651 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
3653 /* If necessary, update the number of active TTs on this root port */
3654 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
3656 xhci_dbg(xhci, "Output context after successful reset device cmd:\n");
3657 xhci_dbg_ctx(xhci, virt_dev->out_ctx, last_freed_endpoint);
3661 xhci_free_command(xhci, reset_device_cmd);
3666 * At this point, the struct usb_device is about to go away, the device has
3667 * disconnected, and all traffic has been stopped and the endpoints have been
3668 * disabled. Free any HC data structures associated with that device.
3670 void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3672 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3673 struct xhci_virt_device *virt_dev;
3674 unsigned long flags;
3677 struct xhci_command *command;
3679 command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
3683 #ifndef CONFIG_USB_DEFAULT_PERSIST
3685 * We called pm_runtime_get_noresume when the device was attached.
3686 * Decrement the counter here to allow controller to runtime suspend
3687 * if no devices remain.
3689 if (xhci->quirks & XHCI_RESET_ON_RESUME)
3690 pm_runtime_put_noidle(hcd->self.controller);
3693 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3694 /* If the host is halted due to driver unload, we still need to free the
3697 if (ret <= 0 && ret != -ENODEV) {
3702 virt_dev = xhci->devs[udev->slot_id];
3704 /* Stop any wayward timer functions (which may grab the lock) */
3705 for (i = 0; i < 31; ++i) {
3706 virt_dev->eps[i].ep_state &= ~EP_HALT_PENDING;
3707 del_timer_sync(&virt_dev->eps[i].stop_cmd_timer);
3710 spin_lock_irqsave(&xhci->lock, flags);
3711 /* Don't disable the slot if the host controller is dead. */
3712 state = readl(&xhci->op_regs->status);
3713 if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
3714 (xhci->xhc_state & XHCI_STATE_HALTED)) {
3715 xhci_free_virt_device(xhci, udev->slot_id);
3716 spin_unlock_irqrestore(&xhci->lock, flags);
3721 if (xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
3723 spin_unlock_irqrestore(&xhci->lock, flags);
3724 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3727 xhci_ring_cmd_db(xhci);
3728 spin_unlock_irqrestore(&xhci->lock, flags);
3731 * Event command completion handler will free any data structures
3732 * associated with the slot. XXX Can free sleep?
3737 * Checks if we have enough host controller resources for the default control
3740 * Must be called with xhci->lock held.
3742 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
3744 if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
3745 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3746 "Not enough ep ctxs: "
3747 "%u active, need to add 1, limit is %u.",
3748 xhci->num_active_eps, xhci->limit_active_eps);
3751 xhci->num_active_eps += 1;
3752 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3753 "Adding 1 ep ctx, %u now active.",
3754 xhci->num_active_eps);
3760 * Returns 0 if the xHC ran out of device slots, the Enable Slot command
3761 * timed out, or allocating memory failed. Returns 1 on success.
3763 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
3765 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3766 unsigned long flags;
3768 struct xhci_command *command;
3770 command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
3774 spin_lock_irqsave(&xhci->lock, flags);
3775 command->completion = &xhci->addr_dev;
3776 ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
3778 spin_unlock_irqrestore(&xhci->lock, flags);
3779 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3783 xhci_ring_cmd_db(xhci);
3784 spin_unlock_irqrestore(&xhci->lock, flags);
3786 wait_for_completion(command->completion);
3788 if (!xhci->slot_id || command->status != COMP_SUCCESS) {
3789 xhci_err(xhci, "Error while assigning device slot ID\n");
3790 xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
3792 readl(&xhci->cap_regs->hcs_params1)));
3797 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3798 spin_lock_irqsave(&xhci->lock, flags);
3799 ret = xhci_reserve_host_control_ep_resources(xhci);
3801 spin_unlock_irqrestore(&xhci->lock, flags);
3802 xhci_warn(xhci, "Not enough host resources, "
3803 "active endpoint contexts = %u\n",
3804 xhci->num_active_eps);
3807 spin_unlock_irqrestore(&xhci->lock, flags);
3809 /* Use GFP_NOIO, since this function can be called from
3810 * xhci_discover_or_reset_device(), which may be called as part of
3811 * mass storage driver error handling.
3813 if (!xhci_alloc_virt_device(xhci, xhci->slot_id, udev, GFP_NOIO)) {
3814 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
3817 udev->slot_id = xhci->slot_id;
3819 #ifndef CONFIG_USB_DEFAULT_PERSIST
3821 * If resetting upon resume, we can't put the controller into runtime
3822 * suspend if there is a device attached.
3824 if (xhci->quirks & XHCI_RESET_ON_RESUME)
3825 pm_runtime_get_noresume(hcd->self.controller);
3830 /* Is this a LS or FS device under a HS hub? */
3831 /* Hub or peripherial? */
3835 /* Disable slot, if we can do it without mem alloc */
3836 spin_lock_irqsave(&xhci->lock, flags);
3837 command->completion = NULL;
3838 command->status = 0;
3839 if (!xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
3841 xhci_ring_cmd_db(xhci);
3842 spin_unlock_irqrestore(&xhci->lock, flags);
3847 * Issue an Address Device command and optionally send a corresponding
3848 * SetAddress request to the device.
3849 * We should be protected by the usb_address0_mutex in hub_wq's hub_port_init,
3850 * so we should only issue and wait on one address command at the same time.
3852 static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
3853 enum xhci_setup_dev setup)
3855 const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
3856 unsigned long flags;
3857 struct xhci_virt_device *virt_dev;
3859 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3860 struct xhci_slot_ctx *slot_ctx;
3861 struct xhci_input_control_ctx *ctrl_ctx;
3863 struct xhci_command *command;
3865 if (!udev->slot_id) {
3866 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3867 "Bad Slot ID %d", udev->slot_id);
3871 virt_dev = xhci->devs[udev->slot_id];
3873 if (WARN_ON(!virt_dev)) {
3875 * In plug/unplug torture test with an NEC controller,
3876 * a zero-dereference was observed once due to virt_dev = 0.
3877 * Print useful debug rather than crash if it is observed again!
3879 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
3884 if (setup == SETUP_CONTEXT_ONLY) {
3885 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3886 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3887 SLOT_STATE_DEFAULT) {
3888 xhci_dbg(xhci, "Slot already in default state\n");
3893 command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
3897 command->in_ctx = virt_dev->in_ctx;
3898 command->completion = &xhci->addr_dev;
3900 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
3901 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
3903 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3909 * If this is the first Set Address since device plug-in or
3910 * virt_device realloaction after a resume with an xHCI power loss,
3911 * then set up the slot context.
3913 if (!slot_ctx->dev_info)
3914 xhci_setup_addressable_virt_dev(xhci, udev);
3915 /* Otherwise, update the control endpoint ring enqueue pointer. */
3917 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
3918 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
3919 ctrl_ctx->drop_flags = 0;
3921 xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
3922 xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
3923 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
3924 le32_to_cpu(slot_ctx->dev_info) >> 27);
3926 spin_lock_irqsave(&xhci->lock, flags);
3927 ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
3928 udev->slot_id, setup);
3930 spin_unlock_irqrestore(&xhci->lock, flags);
3931 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3932 "FIXME: allocate a command ring segment");
3936 xhci_ring_cmd_db(xhci);
3937 spin_unlock_irqrestore(&xhci->lock, flags);
3939 /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
3940 wait_for_completion(command->completion);
3942 /* FIXME: From section 4.3.4: "Software shall be responsible for timing
3943 * the SetAddress() "recovery interval" required by USB and aborting the
3944 * command on a timeout.
3946 switch (command->status) {
3947 case COMP_CMD_ABORT:
3949 xhci_warn(xhci, "Timeout while waiting for setup device command\n");
3952 case COMP_CTX_STATE:
3954 xhci_err(xhci, "Setup ERROR: setup %s command for slot %d.\n",
3955 act, udev->slot_id);
3959 dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
3963 dev_warn(&udev->dev,
3964 "ERROR: Incompatible device for setup %s command\n", act);
3968 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3969 "Successful setup %s command", act);
3973 "ERROR: unexpected setup %s command completion code 0x%x.\n",
3974 act, command->status);
3975 xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
3976 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
3977 trace_xhci_address_ctx(xhci, virt_dev->out_ctx, 1);
3985 temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
3986 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3987 "Op regs DCBAA ptr = %#016llx", temp_64);
3988 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3989 "Slot ID %d dcbaa entry @%p = %#016llx",
3991 &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
3992 (unsigned long long)
3993 le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
3994 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3995 "Output Context DMA address = %#08llx",
3996 (unsigned long long)virt_dev->out_ctx->dma);
3997 xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
3998 xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
3999 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4000 le32_to_cpu(slot_ctx->dev_info) >> 27);
4001 xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
4002 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
4004 * USB core uses address 1 for the roothubs, so we add one to the
4005 * address given back to us by the HC.
4007 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4008 trace_xhci_address_ctx(xhci, virt_dev->out_ctx,
4009 le32_to_cpu(slot_ctx->dev_info) >> 27);
4010 /* Zero the input context control for later use */
4011 ctrl_ctx->add_flags = 0;
4012 ctrl_ctx->drop_flags = 0;
4014 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4015 "Internal device address = %d",
4016 le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4021 int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev)
4023 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ADDRESS);
4026 int xhci_enable_device(struct usb_hcd *hcd, struct usb_device *udev)
4028 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ONLY);
4032 * Transfer the port index into real index in the HW port status
4033 * registers. Caculate offset between the port's PORTSC register
4034 * and port status base. Divide the number of per port register
4035 * to get the real index. The raw port number bases 1.
4037 int xhci_find_raw_port_number(struct usb_hcd *hcd, int port1)
4039 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4040 __le32 __iomem *base_addr = &xhci->op_regs->port_status_base;
4041 __le32 __iomem *addr;
4044 if (hcd->speed != HCD_USB3)
4045 addr = xhci->usb2_ports[port1 - 1];
4047 addr = xhci->usb3_ports[port1 - 1];
4049 raw_port = (addr - base_addr)/NUM_PORT_REGS + 1;
4054 * Issue an Evaluate Context command to change the Maximum Exit Latency in the
4055 * slot context. If that succeeds, store the new MEL in the xhci_virt_device.
4057 static int __maybe_unused xhci_change_max_exit_latency(struct xhci_hcd *xhci,
4058 struct usb_device *udev, u16 max_exit_latency)
4060 struct xhci_virt_device *virt_dev;
4061 struct xhci_command *command;
4062 struct xhci_input_control_ctx *ctrl_ctx;
4063 struct xhci_slot_ctx *slot_ctx;
4064 unsigned long flags;
4067 spin_lock_irqsave(&xhci->lock, flags);
4069 virt_dev = xhci->devs[udev->slot_id];
4072 * virt_dev might not exists yet if xHC resumed from hibernate (S4) and
4073 * xHC was re-initialized. Exit latency will be set later after
4074 * hub_port_finish_reset() is done and xhci->devs[] are re-allocated
4077 if (!virt_dev || max_exit_latency == virt_dev->current_mel) {
4078 spin_unlock_irqrestore(&xhci->lock, flags);
4082 /* Attempt to issue an Evaluate Context command to change the MEL. */
4083 command = xhci->lpm_command;
4084 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
4086 spin_unlock_irqrestore(&xhci->lock, flags);
4087 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4092 xhci_slot_copy(xhci, command->in_ctx, virt_dev->out_ctx);
4093 spin_unlock_irqrestore(&xhci->lock, flags);
4095 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4096 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
4097 slot_ctx->dev_info2 &= cpu_to_le32(~((u32) MAX_EXIT));
4098 slot_ctx->dev_info2 |= cpu_to_le32(max_exit_latency);
4099 slot_ctx->dev_state = 0;
4101 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
4102 "Set up evaluate context for LPM MEL change.");
4103 xhci_dbg(xhci, "Slot %u Input Context:\n", udev->slot_id);
4104 xhci_dbg_ctx(xhci, command->in_ctx, 0);
4106 /* Issue and wait for the evaluate context command. */
4107 ret = xhci_configure_endpoint(xhci, udev, command,
4109 xhci_dbg(xhci, "Slot %u Output Context:\n", udev->slot_id);
4110 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 0);
4113 spin_lock_irqsave(&xhci->lock, flags);
4114 virt_dev->current_mel = max_exit_latency;
4115 spin_unlock_irqrestore(&xhci->lock, flags);
4122 /* BESL to HIRD Encoding array for USB2 LPM */
4123 static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
4124 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
4126 /* Calculate HIRD/BESL for USB2 PORTPMSC*/
4127 static int xhci_calculate_hird_besl(struct xhci_hcd *xhci,
4128 struct usb_device *udev)
4130 int u2del, besl, besl_host;
4131 int besl_device = 0;
4134 u2del = HCS_U2_LATENCY(xhci->hcs_params3);
4135 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4137 if (field & USB_BESL_SUPPORT) {
4138 for (besl_host = 0; besl_host < 16; besl_host++) {
4139 if (xhci_besl_encoding[besl_host] >= u2del)
4142 /* Use baseline BESL value as default */
4143 if (field & USB_BESL_BASELINE_VALID)
4144 besl_device = USB_GET_BESL_BASELINE(field);
4145 else if (field & USB_BESL_DEEP_VALID)
4146 besl_device = USB_GET_BESL_DEEP(field);
4151 besl_host = (u2del - 51) / 75 + 1;
4154 besl = besl_host + besl_device;
4161 /* Calculate BESLD, L1 timeout and HIRDM for USB2 PORTHLPMC */
4162 static int xhci_calculate_usb2_hw_lpm_params(struct usb_device *udev)
4169 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4171 /* xHCI l1 is set in steps of 256us, xHCI 1.0 section 5.4.11.2 */
4172 l1 = udev->l1_params.timeout / 256;
4174 /* device has preferred BESLD */
4175 if (field & USB_BESL_DEEP_VALID) {
4176 besld = USB_GET_BESL_DEEP(field);
4180 return PORT_BESLD(besld) | PORT_L1_TIMEOUT(l1) | PORT_HIRDM(hirdm);
4183 int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4184 struct usb_device *udev, int enable)
4186 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4187 __le32 __iomem **port_array;
4188 __le32 __iomem *pm_addr, *hlpm_addr;
4189 u32 pm_val, hlpm_val, field;
4190 unsigned int port_num;
4191 unsigned long flags;
4192 int hird, exit_latency;
4195 if (hcd->speed == HCD_USB3 || !xhci->hw_lpm_support ||
4199 if (!udev->parent || udev->parent->parent ||
4200 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4203 if (udev->usb2_hw_lpm_capable != 1)
4206 spin_lock_irqsave(&xhci->lock, flags);
4208 port_array = xhci->usb2_ports;
4209 port_num = udev->portnum - 1;
4210 pm_addr = port_array[port_num] + PORTPMSC;
4211 pm_val = readl(pm_addr);
4212 hlpm_addr = port_array[port_num] + PORTHLPMC;
4213 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4215 xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
4216 enable ? "enable" : "disable", port_num + 1);
4219 /* Host supports BESL timeout instead of HIRD */
4220 if (udev->usb2_hw_lpm_besl_capable) {
4221 /* if device doesn't have a preferred BESL value use a
4222 * default one which works with mixed HIRD and BESL
4223 * systems. See XHCI_DEFAULT_BESL definition in xhci.h
4225 if ((field & USB_BESL_SUPPORT) &&
4226 (field & USB_BESL_BASELINE_VALID))
4227 hird = USB_GET_BESL_BASELINE(field);
4229 hird = udev->l1_params.besl;
4231 exit_latency = xhci_besl_encoding[hird];
4232 spin_unlock_irqrestore(&xhci->lock, flags);
4234 /* USB 3.0 code dedicate one xhci->lpm_command->in_ctx
4235 * input context for link powermanagement evaluate
4236 * context commands. It is protected by hcd->bandwidth
4237 * mutex and is shared by all devices. We need to set
4238 * the max ext latency in USB 2 BESL LPM as well, so
4239 * use the same mutex and xhci_change_max_exit_latency()
4241 mutex_lock(hcd->bandwidth_mutex);
4242 ret = xhci_change_max_exit_latency(xhci, udev,
4244 mutex_unlock(hcd->bandwidth_mutex);
4248 spin_lock_irqsave(&xhci->lock, flags);
4250 hlpm_val = xhci_calculate_usb2_hw_lpm_params(udev);
4251 writel(hlpm_val, hlpm_addr);
4255 hird = xhci_calculate_hird_besl(xhci, udev);
4258 pm_val &= ~PORT_HIRD_MASK;
4259 pm_val |= PORT_HIRD(hird) | PORT_RWE | PORT_L1DS(udev->slot_id);
4260 writel(pm_val, pm_addr);
4261 pm_val = readl(pm_addr);
4263 writel(pm_val, pm_addr);
4267 pm_val &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK | PORT_L1DS_MASK);
4268 writel(pm_val, pm_addr);
4271 if (udev->usb2_hw_lpm_besl_capable) {
4272 spin_unlock_irqrestore(&xhci->lock, flags);
4273 mutex_lock(hcd->bandwidth_mutex);
4274 xhci_change_max_exit_latency(xhci, udev, 0);
4275 mutex_unlock(hcd->bandwidth_mutex);
4280 spin_unlock_irqrestore(&xhci->lock, flags);
4284 /* check if a usb2 port supports a given extened capability protocol
4285 * only USB2 ports extended protocol capability values are cached.
4286 * Return 1 if capability is supported
4288 static int xhci_check_usb2_port_capability(struct xhci_hcd *xhci, int port,
4289 unsigned capability)
4291 u32 port_offset, port_count;
4294 for (i = 0; i < xhci->num_ext_caps; i++) {
4295 if (xhci->ext_caps[i] & capability) {
4296 /* port offsets starts at 1 */
4297 port_offset = XHCI_EXT_PORT_OFF(xhci->ext_caps[i]) - 1;
4298 port_count = XHCI_EXT_PORT_COUNT(xhci->ext_caps[i]);
4299 if (port >= port_offset &&
4300 port < port_offset + port_count)
4307 int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4309 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4310 int portnum = udev->portnum - 1;
4312 if (hcd->speed == HCD_USB3 || !xhci->sw_lpm_support ||
4316 /* we only support lpm for non-hub device connected to root hub yet */
4317 if (!udev->parent || udev->parent->parent ||
4318 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4321 if (xhci->hw_lpm_support == 1 &&
4322 xhci_check_usb2_port_capability(
4323 xhci, portnum, XHCI_HLC)) {
4324 udev->usb2_hw_lpm_capable = 1;
4325 udev->l1_params.timeout = XHCI_L1_TIMEOUT;
4326 udev->l1_params.besl = XHCI_DEFAULT_BESL;
4327 if (xhci_check_usb2_port_capability(xhci, portnum,
4329 udev->usb2_hw_lpm_besl_capable = 1;
4335 /*---------------------- USB 3.0 Link PM functions ------------------------*/
4337 /* Service interval in nanoseconds = 2^(bInterval - 1) * 125us * 1000ns / 1us */
4338 static unsigned long long xhci_service_interval_to_ns(
4339 struct usb_endpoint_descriptor *desc)
4341 return (1ULL << (desc->bInterval - 1)) * 125 * 1000;
4344 static u16 xhci_get_timeout_no_hub_lpm(struct usb_device *udev,
4345 enum usb3_link_state state)
4347 unsigned long long sel;
4348 unsigned long long pel;
4349 unsigned int max_sel_pel;
4354 /* Convert SEL and PEL stored in nanoseconds to microseconds */
4355 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4356 pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4357 max_sel_pel = USB3_LPM_MAX_U1_SEL_PEL;
4361 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4362 pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4363 max_sel_pel = USB3_LPM_MAX_U2_SEL_PEL;
4367 dev_warn(&udev->dev, "%s: Can't get timeout for non-U1 or U2 state.\n",
4369 return USB3_LPM_DISABLED;
4372 if (sel <= max_sel_pel && pel <= max_sel_pel)
4373 return USB3_LPM_DEVICE_INITIATED;
4375 if (sel > max_sel_pel)
4376 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4377 "due to long SEL %llu ms\n",
4380 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4381 "due to long PEL %llu ms\n",
4383 return USB3_LPM_DISABLED;
4386 /* The U1 timeout should be the maximum of the following values:
4387 * - For control endpoints, U1 system exit latency (SEL) * 3
4388 * - For bulk endpoints, U1 SEL * 5
4389 * - For interrupt endpoints:
4390 * - Notification EPs, U1 SEL * 3
4391 * - Periodic EPs, max(105% of bInterval, U1 SEL * 2)
4392 * - For isochronous endpoints, max(105% of bInterval, U1 SEL * 2)
4394 static unsigned long long xhci_calculate_intel_u1_timeout(
4395 struct usb_device *udev,
4396 struct usb_endpoint_descriptor *desc)
4398 unsigned long long timeout_ns;
4402 ep_type = usb_endpoint_type(desc);
4404 case USB_ENDPOINT_XFER_CONTROL:
4405 timeout_ns = udev->u1_params.sel * 3;
4407 case USB_ENDPOINT_XFER_BULK:
4408 timeout_ns = udev->u1_params.sel * 5;
4410 case USB_ENDPOINT_XFER_INT:
4411 intr_type = usb_endpoint_interrupt_type(desc);
4412 if (intr_type == USB_ENDPOINT_INTR_NOTIFICATION) {
4413 timeout_ns = udev->u1_params.sel * 3;
4416 /* Otherwise the calculation is the same as isoc eps */
4417 case USB_ENDPOINT_XFER_ISOC:
4418 timeout_ns = xhci_service_interval_to_ns(desc);
4419 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns * 105, 100);
4420 if (timeout_ns < udev->u1_params.sel * 2)
4421 timeout_ns = udev->u1_params.sel * 2;
4430 /* Returns the hub-encoded U1 timeout value. */
4431 static u16 xhci_calculate_u1_timeout(struct xhci_hcd *xhci,
4432 struct usb_device *udev,
4433 struct usb_endpoint_descriptor *desc)
4435 unsigned long long timeout_ns;
4437 if (xhci->quirks & XHCI_INTEL_HOST)
4438 timeout_ns = xhci_calculate_intel_u1_timeout(udev, desc);
4440 timeout_ns = udev->u1_params.sel;
4442 /* The U1 timeout is encoded in 1us intervals.
4443 * Don't return a timeout of zero, because that's USB3_LPM_DISABLED.
4445 if (timeout_ns == USB3_LPM_DISABLED)
4448 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 1000);
4450 /* If the necessary timeout value is bigger than what we can set in the
4451 * USB 3.0 hub, we have to disable hub-initiated U1.
4453 if (timeout_ns <= USB3_LPM_U1_MAX_TIMEOUT)
4455 dev_dbg(&udev->dev, "Hub-initiated U1 disabled "
4456 "due to long timeout %llu ms\n", timeout_ns);
4457 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U1);
4460 /* The U2 timeout should be the maximum of:
4461 * - 10 ms (to avoid the bandwidth impact on the scheduler)
4462 * - largest bInterval of any active periodic endpoint (to avoid going
4463 * into lower power link states between intervals).
4464 * - the U2 Exit Latency of the device
4466 static unsigned long long xhci_calculate_intel_u2_timeout(
4467 struct usb_device *udev,
4468 struct usb_endpoint_descriptor *desc)
4470 unsigned long long timeout_ns;
4471 unsigned long long u2_del_ns;
4473 timeout_ns = 10 * 1000 * 1000;
4475 if ((usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) &&
4476 (xhci_service_interval_to_ns(desc) > timeout_ns))
4477 timeout_ns = xhci_service_interval_to_ns(desc);
4479 u2_del_ns = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat) * 1000ULL;
4480 if (u2_del_ns > timeout_ns)
4481 timeout_ns = u2_del_ns;
4486 /* Returns the hub-encoded U2 timeout value. */
4487 static u16 xhci_calculate_u2_timeout(struct xhci_hcd *xhci,
4488 struct usb_device *udev,
4489 struct usb_endpoint_descriptor *desc)
4491 unsigned long long timeout_ns;
4493 if (xhci->quirks & XHCI_INTEL_HOST)
4494 timeout_ns = xhci_calculate_intel_u2_timeout(udev, desc);
4496 timeout_ns = udev->u2_params.sel;
4498 /* The U2 timeout is encoded in 256us intervals */
4499 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 256 * 1000);
4500 /* If the necessary timeout value is bigger than what we can set in the
4501 * USB 3.0 hub, we have to disable hub-initiated U2.
4503 if (timeout_ns <= USB3_LPM_U2_MAX_TIMEOUT)
4505 dev_dbg(&udev->dev, "Hub-initiated U2 disabled "
4506 "due to long timeout %llu ms\n", timeout_ns);
4507 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U2);
4510 static u16 xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4511 struct usb_device *udev,
4512 struct usb_endpoint_descriptor *desc,
4513 enum usb3_link_state state,
4516 if (state == USB3_LPM_U1)
4517 return xhci_calculate_u1_timeout(xhci, udev, desc);
4518 else if (state == USB3_LPM_U2)
4519 return xhci_calculate_u2_timeout(xhci, udev, desc);
4521 return USB3_LPM_DISABLED;
4524 static int xhci_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4525 struct usb_device *udev,
4526 struct usb_endpoint_descriptor *desc,
4527 enum usb3_link_state state,
4532 alt_timeout = xhci_call_host_update_timeout_for_endpoint(xhci, udev,
4533 desc, state, timeout);
4535 /* If we found we can't enable hub-initiated LPM, or
4536 * the U1 or U2 exit latency was too high to allow
4537 * device-initiated LPM as well, just stop searching.
4539 if (alt_timeout == USB3_LPM_DISABLED ||
4540 alt_timeout == USB3_LPM_DEVICE_INITIATED) {
4541 *timeout = alt_timeout;
4544 if (alt_timeout > *timeout)
4545 *timeout = alt_timeout;
4549 static int xhci_update_timeout_for_interface(struct xhci_hcd *xhci,
4550 struct usb_device *udev,
4551 struct usb_host_interface *alt,
4552 enum usb3_link_state state,
4557 for (j = 0; j < alt->desc.bNumEndpoints; j++) {
4558 if (xhci_update_timeout_for_endpoint(xhci, udev,
4559 &alt->endpoint[j].desc, state, timeout))
4566 static int xhci_check_intel_tier_policy(struct usb_device *udev,
4567 enum usb3_link_state state)
4569 struct usb_device *parent;
4570 unsigned int num_hubs;
4572 if (state == USB3_LPM_U2)
4575 /* Don't enable U1 if the device is on a 2nd tier hub or lower. */
4576 for (parent = udev->parent, num_hubs = 0; parent->parent;
4577 parent = parent->parent)
4583 dev_dbg(&udev->dev, "Disabling U1 link state for device"
4584 " below second-tier hub.\n");
4585 dev_dbg(&udev->dev, "Plug device into first-tier hub "
4586 "to decrease power consumption.\n");
4590 static int xhci_check_tier_policy(struct xhci_hcd *xhci,
4591 struct usb_device *udev,
4592 enum usb3_link_state state)
4594 if (xhci->quirks & XHCI_INTEL_HOST)
4595 return xhci_check_intel_tier_policy(udev, state);
4600 /* Returns the U1 or U2 timeout that should be enabled.
4601 * If the tier check or timeout setting functions return with a non-zero exit
4602 * code, that means the timeout value has been finalized and we shouldn't look
4603 * at any more endpoints.
4605 static u16 xhci_calculate_lpm_timeout(struct usb_hcd *hcd,
4606 struct usb_device *udev, enum usb3_link_state state)
4608 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4609 struct usb_host_config *config;
4612 u16 timeout = USB3_LPM_DISABLED;
4614 if (state == USB3_LPM_U1)
4616 else if (state == USB3_LPM_U2)
4619 dev_warn(&udev->dev, "Can't enable unknown link state %i\n",
4624 if (xhci_check_tier_policy(xhci, udev, state) < 0)
4627 /* Gather some information about the currently installed configuration
4628 * and alternate interface settings.
4630 if (xhci_update_timeout_for_endpoint(xhci, udev, &udev->ep0.desc,
4634 config = udev->actconfig;
4638 for (i = 0; i < config->desc.bNumInterfaces; i++) {
4639 struct usb_driver *driver;
4640 struct usb_interface *intf = config->interface[i];
4645 /* Check if any currently bound drivers want hub-initiated LPM
4648 if (intf->dev.driver) {
4649 driver = to_usb_driver(intf->dev.driver);
4650 if (driver && driver->disable_hub_initiated_lpm) {
4651 dev_dbg(&udev->dev, "Hub-initiated %s disabled "
4652 "at request of driver %s\n",
4653 state_name, driver->name);
4654 return xhci_get_timeout_no_hub_lpm(udev, state);
4658 /* Not sure how this could happen... */
4659 if (!intf->cur_altsetting)
4662 if (xhci_update_timeout_for_interface(xhci, udev,
4663 intf->cur_altsetting,
4670 static int calculate_max_exit_latency(struct usb_device *udev,
4671 enum usb3_link_state state_changed,
4672 u16 hub_encoded_timeout)
4674 unsigned long long u1_mel_us = 0;
4675 unsigned long long u2_mel_us = 0;
4676 unsigned long long mel_us = 0;
4682 disabling_u1 = (state_changed == USB3_LPM_U1 &&
4683 hub_encoded_timeout == USB3_LPM_DISABLED);
4684 disabling_u2 = (state_changed == USB3_LPM_U2 &&
4685 hub_encoded_timeout == USB3_LPM_DISABLED);
4687 enabling_u1 = (state_changed == USB3_LPM_U1 &&
4688 hub_encoded_timeout != USB3_LPM_DISABLED);
4689 enabling_u2 = (state_changed == USB3_LPM_U2 &&
4690 hub_encoded_timeout != USB3_LPM_DISABLED);
4692 /* If U1 was already enabled and we're not disabling it,
4693 * or we're going to enable U1, account for the U1 max exit latency.
4695 if ((udev->u1_params.timeout != USB3_LPM_DISABLED && !disabling_u1) ||
4697 u1_mel_us = DIV_ROUND_UP(udev->u1_params.mel, 1000);
4698 if ((udev->u2_params.timeout != USB3_LPM_DISABLED && !disabling_u2) ||
4700 u2_mel_us = DIV_ROUND_UP(udev->u2_params.mel, 1000);
4702 if (u1_mel_us > u2_mel_us)
4706 /* xHCI host controller max exit latency field is only 16 bits wide. */
4707 if (mel_us > MAX_EXIT) {
4708 dev_warn(&udev->dev, "Link PM max exit latency of %lluus "
4709 "is too big.\n", mel_us);
4715 /* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
4716 int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
4717 struct usb_device *udev, enum usb3_link_state state)
4719 struct xhci_hcd *xhci;
4720 u16 hub_encoded_timeout;
4724 xhci = hcd_to_xhci(hcd);
4725 /* The LPM timeout values are pretty host-controller specific, so don't
4726 * enable hub-initiated timeouts unless the vendor has provided
4727 * information about their timeout algorithm.
4729 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
4730 !xhci->devs[udev->slot_id])
4731 return USB3_LPM_DISABLED;
4733 hub_encoded_timeout = xhci_calculate_lpm_timeout(hcd, udev, state);
4734 mel = calculate_max_exit_latency(udev, state, hub_encoded_timeout);
4736 /* Max Exit Latency is too big, disable LPM. */
4737 hub_encoded_timeout = USB3_LPM_DISABLED;
4741 ret = xhci_change_max_exit_latency(xhci, udev, mel);
4744 return hub_encoded_timeout;
4747 int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
4748 struct usb_device *udev, enum usb3_link_state state)
4750 struct xhci_hcd *xhci;
4754 xhci = hcd_to_xhci(hcd);
4755 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
4756 !xhci->devs[udev->slot_id])
4759 mel = calculate_max_exit_latency(udev, state, USB3_LPM_DISABLED);
4760 ret = xhci_change_max_exit_latency(xhci, udev, mel);
4765 #else /* CONFIG_PM */
4767 int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4768 struct usb_device *udev, int enable)
4773 int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4778 int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
4779 struct usb_device *udev, enum usb3_link_state state)
4781 return USB3_LPM_DISABLED;
4784 int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
4785 struct usb_device *udev, enum usb3_link_state state)
4789 #endif /* CONFIG_PM */
4791 /*-------------------------------------------------------------------------*/
4793 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
4794 * internal data structures for the device.
4796 int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
4797 struct usb_tt *tt, gfp_t mem_flags)
4799 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4800 struct xhci_virt_device *vdev;
4801 struct xhci_command *config_cmd;
4802 struct xhci_input_control_ctx *ctrl_ctx;
4803 struct xhci_slot_ctx *slot_ctx;
4804 unsigned long flags;
4805 unsigned think_time;
4808 /* Ignore root hubs */
4812 vdev = xhci->devs[hdev->slot_id];
4814 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
4817 config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
4819 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
4822 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
4824 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4826 xhci_free_command(xhci, config_cmd);
4830 spin_lock_irqsave(&xhci->lock, flags);
4831 if (hdev->speed == USB_SPEED_HIGH &&
4832 xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
4833 xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
4834 xhci_free_command(xhci, config_cmd);
4835 spin_unlock_irqrestore(&xhci->lock, flags);
4839 xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
4840 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4841 slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
4842 slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
4844 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
4845 if (xhci->hci_version > 0x95) {
4846 xhci_dbg(xhci, "xHCI version %x needs hub "
4847 "TT think time and number of ports\n",
4848 (unsigned int) xhci->hci_version);
4849 slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
4850 /* Set TT think time - convert from ns to FS bit times.
4851 * 0 = 8 FS bit times, 1 = 16 FS bit times,
4852 * 2 = 24 FS bit times, 3 = 32 FS bit times.
4854 * xHCI 1.0: this field shall be 0 if the device is not a
4857 think_time = tt->think_time;
4858 if (think_time != 0)
4859 think_time = (think_time / 666) - 1;
4860 if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
4861 slot_ctx->tt_info |=
4862 cpu_to_le32(TT_THINK_TIME(think_time));
4864 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
4865 "TT think time or number of ports\n",
4866 (unsigned int) xhci->hci_version);
4868 slot_ctx->dev_state = 0;
4869 spin_unlock_irqrestore(&xhci->lock, flags);
4871 xhci_dbg(xhci, "Set up %s for hub device.\n",
4872 (xhci->hci_version > 0x95) ?
4873 "configure endpoint" : "evaluate context");
4874 xhci_dbg(xhci, "Slot %u Input Context:\n", hdev->slot_id);
4875 xhci_dbg_ctx(xhci, config_cmd->in_ctx, 0);
4877 /* Issue and wait for the configure endpoint or
4878 * evaluate context command.
4880 if (xhci->hci_version > 0x95)
4881 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
4884 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
4887 xhci_dbg(xhci, "Slot %u Output Context:\n", hdev->slot_id);
4888 xhci_dbg_ctx(xhci, vdev->out_ctx, 0);
4890 xhci_free_command(xhci, config_cmd);
4894 int xhci_get_frame(struct usb_hcd *hcd)
4896 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4897 /* EHCI mods by the periodic size. Why? */
4898 return readl(&xhci->run_regs->microframe_index) >> 3;
4901 int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
4903 struct xhci_hcd *xhci;
4904 struct device *dev = hcd->self.controller;
4907 /* Accept arbitrarily long scatter-gather lists */
4908 hcd->self.sg_tablesize = ~0;
4910 /* support to build packet from discontinuous buffers */
4911 hcd->self.no_sg_constraint = 1;
4913 /* XHCI controllers don't stop the ep queue on short packets :| */
4914 hcd->self.no_stop_on_short = 1;
4916 if (usb_hcd_is_primary_hcd(hcd)) {
4917 xhci = kzalloc(sizeof(struct xhci_hcd), GFP_KERNEL);
4920 *((struct xhci_hcd **) hcd->hcd_priv) = xhci;
4921 xhci->main_hcd = hcd;
4922 /* Mark the first roothub as being USB 2.0.
4923 * The xHCI driver will register the USB 3.0 roothub.
4925 hcd->speed = HCD_USB2;
4926 hcd->self.root_hub->speed = USB_SPEED_HIGH;
4928 * USB 2.0 roothub under xHCI has an integrated TT,
4929 * (rate matching hub) as opposed to having an OHCI/UHCI
4930 * companion controller.
4934 /* xHCI private pointer was set in xhci_pci_probe for the second
4935 * registered roothub.
4940 xhci->cap_regs = hcd->regs;
4941 xhci->op_regs = hcd->regs +
4942 HC_LENGTH(readl(&xhci->cap_regs->hc_capbase));
4943 xhci->run_regs = hcd->regs +
4944 (readl(&xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
4945 /* Cache read-only capability registers */
4946 xhci->hcs_params1 = readl(&xhci->cap_regs->hcs_params1);
4947 xhci->hcs_params2 = readl(&xhci->cap_regs->hcs_params2);
4948 xhci->hcs_params3 = readl(&xhci->cap_regs->hcs_params3);
4949 xhci->hcc_params = readl(&xhci->cap_regs->hc_capbase);
4950 xhci->hci_version = HC_VERSION(xhci->hcc_params);
4951 xhci->hcc_params = readl(&xhci->cap_regs->hcc_params);
4952 xhci_print_registers(xhci);
4954 xhci->quirks = quirks;
4956 get_quirks(dev, xhci);
4958 /* In xhci controllers which follow xhci 1.0 spec gives a spurious
4959 * success event after a short transfer. This quirk will ignore such
4962 if (xhci->hci_version > 0x96)
4963 xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
4965 /* Make sure the HC is halted. */
4966 retval = xhci_halt(xhci);
4970 xhci_dbg(xhci, "Resetting HCD\n");
4971 /* Reset the internal HC memory state and registers. */
4972 retval = xhci_reset(xhci);
4975 xhci_dbg(xhci, "Reset complete\n");
4977 /* Set dma_mask and coherent_dma_mask to 64-bits,
4978 * if xHC supports 64-bit addressing */
4979 if (HCC_64BIT_ADDR(xhci->hcc_params) &&
4980 !dma_set_mask(dev, DMA_BIT_MASK(64))) {
4981 xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
4982 dma_set_coherent_mask(dev, DMA_BIT_MASK(64));
4985 xhci_dbg(xhci, "Calling HCD init\n");
4986 /* Initialize HCD and host controller data structures. */
4987 retval = xhci_init(hcd);
4990 xhci_dbg(xhci, "Called HCD init\n");
4992 xhci_info(xhci, "hcc params 0x%08x hci version 0x%x quirks 0x%08x\n",
4993 xhci->hcc_params, xhci->hci_version, xhci->quirks);
5000 EXPORT_SYMBOL_GPL(xhci_gen_setup);
5002 static const struct hc_driver xhci_hc_driver = {
5003 .description = "xhci-hcd",
5004 .product_desc = "xHCI Host Controller",
5005 .hcd_priv_size = sizeof(struct xhci_hcd *),
5008 * generic hardware linkage
5011 .flags = HCD_MEMORY | HCD_USB3 | HCD_SHARED,
5014 * basic lifecycle operations
5016 .reset = NULL, /* set in xhci_init_driver() */
5019 .shutdown = xhci_shutdown,
5022 * managing i/o requests and associated device resources
5024 .urb_enqueue = xhci_urb_enqueue,
5025 .urb_dequeue = xhci_urb_dequeue,
5026 .alloc_dev = xhci_alloc_dev,
5027 .free_dev = xhci_free_dev,
5028 .alloc_streams = xhci_alloc_streams,
5029 .free_streams = xhci_free_streams,
5030 .add_endpoint = xhci_add_endpoint,
5031 .drop_endpoint = xhci_drop_endpoint,
5032 .endpoint_reset = xhci_endpoint_reset,
5033 .check_bandwidth = xhci_check_bandwidth,
5034 .reset_bandwidth = xhci_reset_bandwidth,
5035 .address_device = xhci_address_device,
5036 .enable_device = xhci_enable_device,
5037 .update_hub_device = xhci_update_hub_device,
5038 .reset_device = xhci_discover_or_reset_device,
5041 * scheduling support
5043 .get_frame_number = xhci_get_frame,
5048 .hub_control = xhci_hub_control,
5049 .hub_status_data = xhci_hub_status_data,
5050 .bus_suspend = xhci_bus_suspend,
5051 .bus_resume = xhci_bus_resume,
5054 * call back when device connected and addressed
5056 .update_device = xhci_update_device,
5057 .set_usb2_hw_lpm = xhci_set_usb2_hardware_lpm,
5058 .enable_usb3_lpm_timeout = xhci_enable_usb3_lpm_timeout,
5059 .disable_usb3_lpm_timeout = xhci_disable_usb3_lpm_timeout,
5060 .find_raw_port_number = xhci_find_raw_port_number,
5063 void xhci_init_driver(struct hc_driver *drv, int (*setup_fn)(struct usb_hcd *))
5066 *drv = xhci_hc_driver;
5067 drv->reset = setup_fn;
5069 EXPORT_SYMBOL_GPL(xhci_init_driver);
5071 MODULE_DESCRIPTION(DRIVER_DESC);
5072 MODULE_AUTHOR(DRIVER_AUTHOR);
5073 MODULE_LICENSE("GPL");
5075 static int __init xhci_hcd_init(void)
5078 * Check the compiler generated sizes of structures that must be laid
5079 * out in specific ways for hardware access.
5081 BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
5082 BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
5083 BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
5084 /* xhci_device_control has eight fields, and also
5085 * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
5087 BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
5088 BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
5089 BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
5090 BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 7*32/8);
5091 BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
5092 /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
5093 BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
5096 module_init(xhci_hcd_init);