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/iopoll.h>
25 #include <linux/irq.h>
26 #include <linux/log2.h>
27 #include <linux/module.h>
28 #include <linux/moduleparam.h>
29 #include <linux/slab.h>
30 #include <linux/dmi.h>
31 #include <linux/dma-mapping.h>
34 #include "xhci-trace.h"
37 #define DRIVER_AUTHOR "Sarah Sharp"
38 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
40 #define PORT_WAKE_BITS (PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E)
42 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
43 static int link_quirk;
44 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
45 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
47 static unsigned long long quirks;
48 module_param(quirks, ullong, S_IRUGO);
49 MODULE_PARM_DESC(quirks, "Bit flags for quirks to be enabled as default");
51 static bool td_on_ring(struct xhci_td *td, struct xhci_ring *ring)
53 struct xhci_segment *seg = ring->first_seg;
55 if (!td || !td->start_seg)
58 if (seg == td->start_seg)
61 } while (seg && seg != ring->first_seg);
67 * xhci_handshake - spin reading hc until handshake completes or fails
68 * @ptr: address of hc register to be read
69 * @mask: bits to look at in result of read
70 * @done: value of those bits when handshake succeeds
71 * @usec: timeout in microseconds
73 * Returns negative errno, or zero on success
75 * Success happens when the "mask" bits have the specified value (hardware
76 * handshake done). There are two failure modes: "usec" have passed (major
77 * hardware flakeout), or the register reads as all-ones (hardware removed).
79 int xhci_handshake(void __iomem *ptr, u32 mask, u32 done, u64 timeout_us)
84 ret = readl_poll_timeout_atomic(ptr, result,
85 (result & mask) == done ||
88 if (result == U32_MAX) /* card removed */
95 * Disable interrupts and begin the xHCI halting process.
97 void xhci_quiesce(struct xhci_hcd *xhci)
104 halted = readl(&xhci->op_regs->status) & STS_HALT;
108 cmd = readl(&xhci->op_regs->command);
110 writel(cmd, &xhci->op_regs->command);
114 * Force HC into halt state.
116 * Disable any IRQs and clear the run/stop bit.
117 * HC will complete any current and actively pipelined transactions, and
118 * should halt within 16 ms of the run/stop bit being cleared.
119 * Read HC Halted bit in the status register to see when the HC is finished.
121 int xhci_halt(struct xhci_hcd *xhci)
124 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Halt the HC");
127 ret = xhci_handshake(&xhci->op_regs->status,
128 STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
130 xhci_warn(xhci, "Host halt failed, %d\n", ret);
133 xhci->xhc_state |= XHCI_STATE_HALTED;
134 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
139 * Set the run bit and wait for the host to be running.
141 int xhci_start(struct xhci_hcd *xhci)
146 temp = readl(&xhci->op_regs->command);
148 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Turn on HC, cmd = 0x%x.",
150 writel(temp, &xhci->op_regs->command);
153 * Wait for the HCHalted Status bit to be 0 to indicate the host is
156 ret = xhci_handshake(&xhci->op_regs->status,
157 STS_HALT, 0, XHCI_MAX_HALT_USEC);
158 if (ret == -ETIMEDOUT)
159 xhci_err(xhci, "Host took too long to start, "
160 "waited %u microseconds.\n",
163 /* clear state flags. Including dying, halted or removing */
172 * This resets pipelines, timers, counters, state machines, etc.
173 * Transactions will be terminated immediately, and operational registers
174 * will be set to their defaults.
176 int xhci_reset(struct xhci_hcd *xhci, u64 timeout_us)
182 state = readl(&xhci->op_regs->status);
184 if (state == ~(u32)0) {
185 xhci_warn(xhci, "Host not accessible, reset failed.\n");
189 if ((state & STS_HALT) == 0) {
190 xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
194 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Reset the HC");
195 command = readl(&xhci->op_regs->command);
196 command |= CMD_RESET;
197 writel(command, &xhci->op_regs->command);
199 /* Existing Intel xHCI controllers require a delay of 1 mS,
200 * after setting the CMD_RESET bit, and before accessing any
201 * HC registers. This allows the HC to complete the
202 * reset operation and be ready for HC register access.
203 * Without this delay, the subsequent HC register access,
204 * may result in a system hang very rarely.
206 if (xhci->quirks & XHCI_INTEL_HOST)
209 ret = xhci_handshake(&xhci->op_regs->command, CMD_RESET, 0, timeout_us);
213 if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
214 usb_asmedia_modifyflowcontrol(to_pci_dev(xhci_to_hcd(xhci)->self.controller));
216 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
217 "Wait for controller to be ready for doorbell rings");
219 * xHCI cannot write to any doorbells or operational registers other
220 * than status until the "Controller Not Ready" flag is cleared.
222 ret = xhci_handshake(&xhci->op_regs->status, STS_CNR, 0, timeout_us);
224 for (i = 0; i < 2; i++) {
225 xhci->bus_state[i].port_c_suspend = 0;
226 xhci->bus_state[i].suspended_ports = 0;
227 xhci->bus_state[i].resuming_ports = 0;
234 #ifdef CONFIG_USB_PCI
238 static int xhci_setup_msi(struct xhci_hcd *xhci)
242 * TODO:Check with MSI Soc for sysdev
244 struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
246 ret = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_MSI);
248 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
249 "failed to allocate MSI entry");
253 ret = request_irq(pdev->irq, xhci_msi_irq,
254 0, "xhci_hcd", xhci_to_hcd(xhci));
256 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
257 "disable MSI interrupt");
258 pci_free_irq_vectors(pdev);
267 static int xhci_setup_msix(struct xhci_hcd *xhci)
270 struct usb_hcd *hcd = xhci_to_hcd(xhci);
271 struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
274 * calculate number of msi-x vectors supported.
275 * - HCS_MAX_INTRS: the max number of interrupts the host can handle,
276 * with max number of interrupters based on the xhci HCSPARAMS1.
277 * - num_online_cpus: maximum msi-x vectors per CPUs core.
278 * Add additional 1 vector to ensure always available interrupt.
280 xhci->msix_count = min(num_online_cpus() + 1,
281 HCS_MAX_INTRS(xhci->hcs_params1));
283 ret = pci_alloc_irq_vectors(pdev, xhci->msix_count, xhci->msix_count,
286 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
287 "Failed to enable MSI-X");
291 for (i = 0; i < xhci->msix_count; i++) {
292 ret = request_irq(pci_irq_vector(pdev, i), xhci_msi_irq, 0,
293 "xhci_hcd", xhci_to_hcd(xhci));
298 hcd->msix_enabled = 1;
302 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "disable MSI-X interrupt");
304 free_irq(pci_irq_vector(pdev, i), xhci_to_hcd(xhci));
305 pci_free_irq_vectors(pdev);
309 /* Free any IRQs and disable MSI-X */
310 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
312 struct usb_hcd *hcd = xhci_to_hcd(xhci);
313 struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
315 if (xhci->quirks & XHCI_PLAT)
318 /* return if using legacy interrupt */
322 if (hcd->msix_enabled) {
325 for (i = 0; i < xhci->msix_count; i++)
326 free_irq(pci_irq_vector(pdev, i), xhci_to_hcd(xhci));
328 free_irq(pci_irq_vector(pdev, 0), xhci_to_hcd(xhci));
331 pci_free_irq_vectors(pdev);
332 hcd->msix_enabled = 0;
335 static void __maybe_unused xhci_msix_sync_irqs(struct xhci_hcd *xhci)
337 struct usb_hcd *hcd = xhci_to_hcd(xhci);
339 if (hcd->msix_enabled) {
340 struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
343 for (i = 0; i < xhci->msix_count; i++)
344 synchronize_irq(pci_irq_vector(pdev, i));
348 static int xhci_try_enable_msi(struct usb_hcd *hcd)
350 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
351 struct pci_dev *pdev;
354 /* The xhci platform device has set up IRQs through usb_add_hcd. */
355 if (xhci->quirks & XHCI_PLAT)
358 pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
360 * Some Fresco Logic host controllers advertise MSI, but fail to
361 * generate interrupts. Don't even try to enable MSI.
363 if (xhci->quirks & XHCI_BROKEN_MSI)
366 /* unregister the legacy interrupt */
368 free_irq(hcd->irq, hcd);
371 ret = xhci_setup_msix(xhci);
373 /* fall back to msi*/
374 ret = xhci_setup_msi(xhci);
377 hcd->msi_enabled = 1;
382 xhci_err(xhci, "No msi-x/msi found and no IRQ in BIOS\n");
387 if (!strlen(hcd->irq_descr))
388 snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
389 hcd->driver->description, hcd->self.busnum);
391 /* fall back to legacy interrupt*/
392 ret = request_irq(pdev->irq, &usb_hcd_irq, IRQF_SHARED,
393 hcd->irq_descr, hcd);
395 xhci_err(xhci, "request interrupt %d failed\n",
399 hcd->irq = pdev->irq;
405 static inline int xhci_try_enable_msi(struct usb_hcd *hcd)
410 static inline void xhci_cleanup_msix(struct xhci_hcd *xhci)
414 static inline void xhci_msix_sync_irqs(struct xhci_hcd *xhci)
420 static void compliance_mode_recovery(unsigned long arg)
422 struct xhci_hcd *xhci;
427 xhci = (struct xhci_hcd *)arg;
429 for (i = 0; i < xhci->num_usb3_ports; i++) {
430 temp = readl(xhci->usb3_ports[i]);
431 if ((temp & PORT_PLS_MASK) == USB_SS_PORT_LS_COMP_MOD) {
433 * Compliance Mode Detected. Letting USB Core
434 * handle the Warm Reset
436 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
437 "Compliance mode detected->port %d",
439 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
440 "Attempting compliance mode recovery");
441 hcd = xhci->shared_hcd;
443 if (hcd->state == HC_STATE_SUSPENDED)
444 usb_hcd_resume_root_hub(hcd);
446 usb_hcd_poll_rh_status(hcd);
450 if (xhci->port_status_u0 != ((1 << xhci->num_usb3_ports)-1))
451 mod_timer(&xhci->comp_mode_recovery_timer,
452 jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
456 * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
457 * that causes ports behind that hardware to enter compliance mode sometimes.
458 * The quirk creates a timer that polls every 2 seconds the link state of
459 * each host controller's port and recovers it by issuing a Warm reset
460 * if Compliance mode is detected, otherwise the port will become "dead" (no
461 * device connections or disconnections will be detected anymore). Becasue no
462 * status event is generated when entering compliance mode (per xhci spec),
463 * this quirk is needed on systems that have the failing hardware installed.
465 static void compliance_mode_recovery_timer_init(struct xhci_hcd *xhci)
467 xhci->port_status_u0 = 0;
468 setup_timer(&xhci->comp_mode_recovery_timer,
469 compliance_mode_recovery, (unsigned long)xhci);
470 xhci->comp_mode_recovery_timer.expires = jiffies +
471 msecs_to_jiffies(COMP_MODE_RCVRY_MSECS);
473 add_timer(&xhci->comp_mode_recovery_timer);
474 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
475 "Compliance mode recovery timer initialized");
479 * This function identifies the systems that have installed the SN65LVPE502CP
480 * USB3.0 re-driver and that need the Compliance Mode Quirk.
482 * Vendor: Hewlett-Packard -> System Models: Z420, Z620 and Z820
484 static bool xhci_compliance_mode_recovery_timer_quirk_check(void)
486 const char *dmi_product_name, *dmi_sys_vendor;
488 dmi_product_name = dmi_get_system_info(DMI_PRODUCT_NAME);
489 dmi_sys_vendor = dmi_get_system_info(DMI_SYS_VENDOR);
490 if (!dmi_product_name || !dmi_sys_vendor)
493 if (!(strstr(dmi_sys_vendor, "Hewlett-Packard")))
496 if (strstr(dmi_product_name, "Z420") ||
497 strstr(dmi_product_name, "Z620") ||
498 strstr(dmi_product_name, "Z820") ||
499 strstr(dmi_product_name, "Z1 Workstation"))
505 static int xhci_all_ports_seen_u0(struct xhci_hcd *xhci)
507 return (xhci->port_status_u0 == ((1 << xhci->num_usb3_ports)-1));
512 * Initialize memory for HCD and xHC (one-time init).
514 * Program the PAGESIZE register, initialize the device context array, create
515 * device contexts (?), set up a command ring segment (or two?), create event
516 * ring (one for now).
518 static int xhci_init(struct usb_hcd *hcd)
520 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
523 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_init");
524 spin_lock_init(&xhci->lock);
525 if (xhci->hci_version == 0x95 && link_quirk) {
526 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
527 "QUIRK: Not clearing Link TRB chain bits.");
528 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
530 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
531 "xHCI doesn't need link TRB QUIRK");
533 retval = xhci_mem_init(xhci, GFP_KERNEL);
534 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Finished xhci_init");
536 /* Initializing Compliance Mode Recovery Data If Needed */
537 if (xhci_compliance_mode_recovery_timer_quirk_check()) {
538 xhci->quirks |= XHCI_COMP_MODE_QUIRK;
539 compliance_mode_recovery_timer_init(xhci);
545 /*-------------------------------------------------------------------------*/
548 static int xhci_run_finished(struct xhci_hcd *xhci)
550 if (xhci_start(xhci)) {
554 xhci->shared_hcd->state = HC_STATE_RUNNING;
555 xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
557 if (xhci->quirks & XHCI_NEC_HOST)
558 xhci_ring_cmd_db(xhci);
560 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
561 "Finished xhci_run for USB3 roothub");
566 * Start the HC after it was halted.
568 * This function is called by the USB core when the HC driver is added.
569 * Its opposite is xhci_stop().
571 * xhci_init() must be called once before this function can be called.
572 * Reset the HC, enable device slot contexts, program DCBAAP, and
573 * set command ring pointer and event ring pointer.
575 * Setup MSI-X vectors and enable interrupts.
577 int xhci_run(struct usb_hcd *hcd)
582 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
584 /* Start the xHCI host controller running only after the USB 2.0 roothub
588 hcd->uses_new_polling = 1;
589 if (!usb_hcd_is_primary_hcd(hcd))
590 return xhci_run_finished(xhci);
592 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_run");
594 ret = xhci_try_enable_msi(hcd);
598 xhci_dbg_cmd_ptrs(xhci);
600 xhci_dbg(xhci, "ERST memory map follows:\n");
601 xhci_dbg_erst(xhci, &xhci->erst);
602 temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
603 temp_64 &= ~ERST_PTR_MASK;
604 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
605 "ERST deq = 64'h%0lx", (long unsigned int) temp_64);
607 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
608 "// Set the interrupt modulation register");
609 temp = readl(&xhci->ir_set->irq_control);
610 temp &= ~ER_IRQ_INTERVAL_MASK;
612 * the increment interval is 8 times as much as that defined
613 * in xHCI spec on MTK's controller
615 temp |= (u32) ((xhci->quirks & XHCI_MTK_HOST) ? 20 : 160);
616 writel(temp, &xhci->ir_set->irq_control);
618 /* Set the HCD state before we enable the irqs */
619 temp = readl(&xhci->op_regs->command);
621 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
622 "// Enable interrupts, cmd = 0x%x.", temp);
623 writel(temp, &xhci->op_regs->command);
625 temp = readl(&xhci->ir_set->irq_pending);
626 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
627 "// Enabling event ring interrupter %p by writing 0x%x to irq_pending",
628 xhci->ir_set, (unsigned int) ER_IRQ_ENABLE(temp));
629 writel(ER_IRQ_ENABLE(temp), &xhci->ir_set->irq_pending);
630 xhci_print_ir_set(xhci, 0);
632 if (xhci->quirks & XHCI_NEC_HOST) {
633 struct xhci_command *command;
635 command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
639 ret = xhci_queue_vendor_command(xhci, command, 0, 0, 0,
640 TRB_TYPE(TRB_NEC_GET_FW));
642 xhci_free_command(xhci, command);
644 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
645 "Finished xhci_run for USB2 roothub");
648 EXPORT_SYMBOL_GPL(xhci_run);
653 * This function is called by the USB core when the HC driver is removed.
654 * Its opposite is xhci_run().
656 * Disable device contexts, disable IRQs, and quiesce the HC.
657 * Reset the HC, finish any completed transactions, and cleanup memory.
659 static void xhci_stop(struct usb_hcd *hcd)
662 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
664 mutex_lock(&xhci->mutex);
666 /* Only halt host and free memory after both hcds are removed */
667 if (!usb_hcd_is_primary_hcd(hcd)) {
668 mutex_unlock(&xhci->mutex);
672 spin_lock_irq(&xhci->lock);
673 xhci->xhc_state |= XHCI_STATE_HALTED;
674 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
676 xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
677 spin_unlock_irq(&xhci->lock);
679 xhci_cleanup_msix(xhci);
681 /* Deleting Compliance Mode Recovery Timer */
682 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
683 (!(xhci_all_ports_seen_u0(xhci)))) {
684 del_timer_sync(&xhci->comp_mode_recovery_timer);
685 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
686 "%s: compliance mode recovery timer deleted",
690 if (xhci->quirks & XHCI_AMD_PLL_FIX)
693 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
694 "// Disabling event ring interrupts");
695 temp = readl(&xhci->op_regs->status);
696 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
697 temp = readl(&xhci->ir_set->irq_pending);
698 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
699 xhci_print_ir_set(xhci, 0);
701 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
702 xhci_mem_cleanup(xhci);
703 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
704 "xhci_stop completed - status = %x",
705 readl(&xhci->op_regs->status));
706 mutex_unlock(&xhci->mutex);
710 * Shutdown HC (not bus-specific)
712 * This is called when the machine is rebooting or halting. We assume that the
713 * machine will be powered off, and the HC's internal state will be reset.
714 * Don't bother to free memory.
716 * This will only ever be called with the main usb_hcd (the USB3 roothub).
718 void xhci_shutdown(struct usb_hcd *hcd)
720 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
722 if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
723 usb_disable_xhci_ports(to_pci_dev(hcd->self.sysdev));
725 /* Don't poll the roothubs after shutdown. */
726 xhci_dbg(xhci, "%s: stopping usb%d port polling.\n",
727 __func__, hcd->self.busnum);
728 clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
729 del_timer_sync(&hcd->rh_timer);
731 if (xhci->shared_hcd) {
732 clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
733 del_timer_sync(&xhci->shared_hcd->rh_timer);
736 spin_lock_irq(&xhci->lock);
738 /* Workaround for spurious wakeups at shutdown with HSW */
739 if (xhci->quirks & XHCI_SPURIOUS_WAKEUP)
740 xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
741 spin_unlock_irq(&xhci->lock);
743 xhci_cleanup_msix(xhci);
745 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
746 "xhci_shutdown completed - status = %x",
747 readl(&xhci->op_regs->status));
749 EXPORT_SYMBOL_GPL(xhci_shutdown);
752 static void xhci_save_registers(struct xhci_hcd *xhci)
754 xhci->s3.command = readl(&xhci->op_regs->command);
755 xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
756 xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
757 xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
758 xhci->s3.erst_size = readl(&xhci->ir_set->erst_size);
759 xhci->s3.erst_base = xhci_read_64(xhci, &xhci->ir_set->erst_base);
760 xhci->s3.erst_dequeue = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
761 xhci->s3.irq_pending = readl(&xhci->ir_set->irq_pending);
762 xhci->s3.irq_control = readl(&xhci->ir_set->irq_control);
765 static void xhci_restore_registers(struct xhci_hcd *xhci)
767 writel(xhci->s3.command, &xhci->op_regs->command);
768 writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
769 xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
770 writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
771 writel(xhci->s3.erst_size, &xhci->ir_set->erst_size);
772 xhci_write_64(xhci, xhci->s3.erst_base, &xhci->ir_set->erst_base);
773 xhci_write_64(xhci, xhci->s3.erst_dequeue, &xhci->ir_set->erst_dequeue);
774 writel(xhci->s3.irq_pending, &xhci->ir_set->irq_pending);
775 writel(xhci->s3.irq_control, &xhci->ir_set->irq_control);
778 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
782 /* step 2: initialize command ring buffer */
783 val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
784 val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
785 (xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
786 xhci->cmd_ring->dequeue) &
787 (u64) ~CMD_RING_RSVD_BITS) |
788 xhci->cmd_ring->cycle_state;
789 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
790 "// Setting command ring address to 0x%llx",
791 (long unsigned long) val_64);
792 xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
796 * The whole command ring must be cleared to zero when we suspend the host.
798 * The host doesn't save the command ring pointer in the suspend well, so we
799 * need to re-program it on resume. Unfortunately, the pointer must be 64-byte
800 * aligned, because of the reserved bits in the command ring dequeue pointer
801 * register. Therefore, we can't just set the dequeue pointer back in the
802 * middle of the ring (TRBs are 16-byte aligned).
804 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
806 struct xhci_ring *ring;
807 struct xhci_segment *seg;
809 ring = xhci->cmd_ring;
813 sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
814 seg->trbs[TRBS_PER_SEGMENT - 1].link.control &=
815 cpu_to_le32(~TRB_CYCLE);
817 } while (seg != ring->deq_seg);
819 /* Reset the software enqueue and dequeue pointers */
820 ring->deq_seg = ring->first_seg;
821 ring->dequeue = ring->first_seg->trbs;
822 ring->enq_seg = ring->deq_seg;
823 ring->enqueue = ring->dequeue;
825 ring->num_trbs_free = ring->num_segs * (TRBS_PER_SEGMENT - 1) - 1;
827 * Ring is now zeroed, so the HW should look for change of ownership
828 * when the cycle bit is set to 1.
830 ring->cycle_state = 1;
833 * Reset the hardware dequeue pointer.
834 * Yes, this will need to be re-written after resume, but we're paranoid
835 * and want to make sure the hardware doesn't access bogus memory
836 * because, say, the BIOS or an SMI started the host without changing
837 * the command ring pointers.
839 xhci_set_cmd_ring_deq(xhci);
842 static void xhci_disable_port_wake_on_bits(struct xhci_hcd *xhci)
845 __le32 __iomem **port_array;
849 spin_lock_irqsave(&xhci->lock, flags);
851 /* disable usb3 ports Wake bits */
852 port_index = xhci->num_usb3_ports;
853 port_array = xhci->usb3_ports;
854 while (port_index--) {
855 t1 = readl(port_array[port_index]);
856 t1 = xhci_port_state_to_neutral(t1);
857 t2 = t1 & ~PORT_WAKE_BITS;
859 writel(t2, port_array[port_index]);
862 /* disable usb2 ports Wake bits */
863 port_index = xhci->num_usb2_ports;
864 port_array = xhci->usb2_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 spin_unlock_irqrestore(&xhci->lock, flags);
876 static bool xhci_pending_portevent(struct xhci_hcd *xhci)
878 __le32 __iomem **port_array;
883 status = readl(&xhci->op_regs->status);
884 if (status & STS_EINT)
887 * Checking STS_EINT is not enough as there is a lag between a change
888 * bit being set and the Port Status Change Event that it generated
889 * being written to the Event Ring. See note in xhci 1.1 section 4.19.2.
892 port_index = xhci->num_usb2_ports;
893 port_array = xhci->usb2_ports;
894 while (port_index--) {
895 portsc = readl(port_array[port_index]);
896 if (portsc & PORT_CHANGE_MASK ||
897 (portsc & PORT_PLS_MASK) == XDEV_RESUME)
900 port_index = xhci->num_usb3_ports;
901 port_array = xhci->usb3_ports;
902 while (port_index--) {
903 portsc = readl(port_array[port_index]);
904 if (portsc & PORT_CHANGE_MASK ||
905 (portsc & PORT_PLS_MASK) == XDEV_RESUME)
912 * Stop HC (not bus-specific)
914 * This is called when the machine transition into S3/S4 mode.
917 int xhci_suspend(struct xhci_hcd *xhci, bool do_wakeup)
920 unsigned int delay = XHCI_MAX_HALT_USEC * 2;
921 struct usb_hcd *hcd = xhci_to_hcd(xhci);
928 if (hcd->state != HC_STATE_SUSPENDED ||
929 xhci->shared_hcd->state != HC_STATE_SUSPENDED)
932 /* Clear root port wake on bits if wakeup not allowed. */
934 xhci_disable_port_wake_on_bits(xhci);
936 /* Don't poll the roothubs on bus suspend. */
937 xhci_dbg(xhci, "%s: stopping port polling.\n", __func__);
938 clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
939 del_timer_sync(&hcd->rh_timer);
940 clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
941 del_timer_sync(&xhci->shared_hcd->rh_timer);
943 if (xhci->quirks & XHCI_SUSPEND_DELAY)
944 usleep_range(1000, 1500);
946 spin_lock_irq(&xhci->lock);
947 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
948 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
949 /* step 1: stop endpoint */
950 /* skipped assuming that port suspend has done */
952 /* step 2: clear Run/Stop bit */
953 command = readl(&xhci->op_regs->command);
955 writel(command, &xhci->op_regs->command);
957 /* Some chips from Fresco Logic need an extraordinary delay */
958 delay *= (xhci->quirks & XHCI_SLOW_SUSPEND) ? 10 : 1;
960 if (xhci_handshake(&xhci->op_regs->status,
961 STS_HALT, STS_HALT, delay)) {
962 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
963 spin_unlock_irq(&xhci->lock);
966 xhci_clear_command_ring(xhci);
968 /* step 3: save registers */
969 xhci_save_registers(xhci);
971 /* step 4: set CSS flag */
972 command = readl(&xhci->op_regs->command);
974 writel(command, &xhci->op_regs->command);
975 xhci->broken_suspend = 0;
976 if (xhci_handshake(&xhci->op_regs->status,
977 STS_SAVE, 0, 20 * 1000)) {
979 * AMD SNPS xHC 3.0 occasionally does not clear the
980 * SSS bit of USBSTS and when driver tries to poll
981 * to see if the xHC clears BIT(8) which never happens
982 * and driver assumes that controller is not responding
983 * and times out. To workaround this, its good to check
984 * if SRE and HCE bits are not set (as per xhci
985 * Section 5.4.2) and bypass the timeout.
987 res = readl(&xhci->op_regs->status);
988 if ((xhci->quirks & XHCI_SNPS_BROKEN_SUSPEND) &&
989 (((res & STS_SRE) == 0) &&
990 ((res & STS_HCE) == 0))) {
991 xhci->broken_suspend = 1;
993 xhci_warn(xhci, "WARN: xHC save state timeout\n");
994 spin_unlock_irq(&xhci->lock);
998 spin_unlock_irq(&xhci->lock);
1001 * Deleting Compliance Mode Recovery Timer because the xHCI Host
1002 * is about to be suspended.
1004 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1005 (!(xhci_all_ports_seen_u0(xhci)))) {
1006 del_timer_sync(&xhci->comp_mode_recovery_timer);
1007 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1008 "%s: compliance mode recovery timer deleted",
1012 /* step 5: remove core well power */
1013 /* synchronize irq when using MSI-X */
1014 xhci_msix_sync_irqs(xhci);
1018 EXPORT_SYMBOL_GPL(xhci_suspend);
1021 * start xHC (not bus-specific)
1023 * This is called when the machine transition from S3/S4 mode.
1026 int xhci_resume(struct xhci_hcd *xhci, bool hibernated)
1028 u32 command, temp = 0;
1029 struct usb_hcd *hcd = xhci_to_hcd(xhci);
1030 struct usb_hcd *secondary_hcd;
1032 bool comp_timer_running = false;
1033 bool pending_portevent = false;
1034 bool reinit_xhc = false;
1039 /* Wait a bit if either of the roothubs need to settle from the
1040 * transition into bus suspend.
1042 if (time_before(jiffies, xhci->bus_state[0].next_statechange) ||
1043 time_before(jiffies,
1044 xhci->bus_state[1].next_statechange))
1047 set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1048 set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1050 spin_lock_irq(&xhci->lock);
1052 if (hibernated || xhci->quirks & XHCI_RESET_ON_RESUME || xhci->broken_suspend)
1057 * Some controllers might lose power during suspend, so wait
1058 * for controller not ready bit to clear, just as in xHC init.
1060 retval = xhci_handshake(&xhci->op_regs->status,
1061 STS_CNR, 0, 10 * 1000 * 1000);
1063 xhci_warn(xhci, "Controller not ready at resume %d\n",
1065 spin_unlock_irq(&xhci->lock);
1068 /* step 1: restore register */
1069 xhci_restore_registers(xhci);
1070 /* step 2: initialize command ring buffer */
1071 xhci_set_cmd_ring_deq(xhci);
1072 /* step 3: restore state and start state*/
1073 /* step 3: set CRS flag */
1074 command = readl(&xhci->op_regs->command);
1076 writel(command, &xhci->op_regs->command);
1078 * Some controllers take up to 55+ ms to complete the controller
1079 * restore so setting the timeout to 100ms. Xhci specification
1080 * doesn't mention any timeout value.
1082 if (xhci_handshake(&xhci->op_regs->status,
1083 STS_RESTORE, 0, 100 * 1000)) {
1084 xhci_warn(xhci, "WARN: xHC restore state timeout\n");
1085 spin_unlock_irq(&xhci->lock);
1090 temp = readl(&xhci->op_regs->status);
1092 /* re-initialize the HC on Restore Error, or Host Controller Error */
1093 if (temp & (STS_SRE | STS_HCE)) {
1095 xhci_warn(xhci, "xHC error in resume, USBSTS 0x%x, Reinit\n", temp);
1099 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1100 !(xhci_all_ports_seen_u0(xhci))) {
1101 del_timer_sync(&xhci->comp_mode_recovery_timer);
1102 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1103 "Compliance Mode Recovery Timer deleted!");
1106 /* Let the USB core know _both_ roothubs lost power. */
1107 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1108 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
1110 xhci_dbg(xhci, "Stop HCD\n");
1112 retval = xhci_reset(xhci, XHCI_RESET_LONG_USEC);
1113 spin_unlock_irq(&xhci->lock);
1116 xhci_cleanup_msix(xhci);
1118 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1119 temp = readl(&xhci->op_regs->status);
1120 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
1121 temp = readl(&xhci->ir_set->irq_pending);
1122 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
1123 xhci_print_ir_set(xhci, 0);
1125 xhci_dbg(xhci, "cleaning up memory\n");
1126 xhci_mem_cleanup(xhci);
1127 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1128 readl(&xhci->op_regs->status));
1130 /* USB core calls the PCI reinit and start functions twice:
1131 * first with the primary HCD, and then with the secondary HCD.
1132 * If we don't do the same, the host will never be started.
1134 if (!usb_hcd_is_primary_hcd(hcd))
1135 secondary_hcd = hcd;
1137 secondary_hcd = xhci->shared_hcd;
1139 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1140 retval = xhci_init(hcd->primary_hcd);
1143 comp_timer_running = true;
1145 xhci_dbg(xhci, "Start the primary HCD\n");
1146 retval = xhci_run(hcd->primary_hcd);
1148 xhci_dbg(xhci, "Start the secondary HCD\n");
1149 retval = xhci_run(secondary_hcd);
1151 hcd->state = HC_STATE_SUSPENDED;
1152 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1156 /* step 4: set Run/Stop bit */
1157 command = readl(&xhci->op_regs->command);
1159 writel(command, &xhci->op_regs->command);
1160 xhci_handshake(&xhci->op_regs->status, STS_HALT,
1163 /* step 5: walk topology and initialize portsc,
1164 * portpmsc and portli
1166 /* this is done in bus_resume */
1168 /* step 6: restart each of the previously
1169 * Running endpoints by ringing their doorbells
1172 spin_unlock_irq(&xhci->lock);
1177 * Resume roothubs only if there are pending events.
1178 * USB 3 devices resend U3 LFPS wake after a 100ms delay if
1179 * the first wake signalling failed, give it that chance.
1181 pending_portevent = xhci_pending_portevent(xhci);
1182 if (!pending_portevent) {
1184 pending_portevent = xhci_pending_portevent(xhci);
1187 if (pending_portevent) {
1188 usb_hcd_resume_root_hub(xhci->shared_hcd);
1189 usb_hcd_resume_root_hub(hcd);
1193 * If system is subject to the Quirk, Compliance Mode Timer needs to
1194 * be re-initialized Always after a system resume. Ports are subject
1195 * to suffer the Compliance Mode issue again. It doesn't matter if
1196 * ports have entered previously to U0 before system's suspension.
1198 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
1199 compliance_mode_recovery_timer_init(xhci);
1201 if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
1202 usb_asmedia_modifyflowcontrol(to_pci_dev(hcd->self.controller));
1204 /* Re-enable port polling. */
1205 xhci_dbg(xhci, "%s: starting port polling.\n", __func__);
1206 set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
1207 usb_hcd_poll_rh_status(xhci->shared_hcd);
1208 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1209 usb_hcd_poll_rh_status(hcd);
1213 EXPORT_SYMBOL_GPL(xhci_resume);
1214 #endif /* CONFIG_PM */
1216 /*-------------------------------------------------------------------------*/
1219 * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1220 * HCDs. Find the index for an endpoint given its descriptor. Use the return
1221 * value to right shift 1 for the bitmask.
1223 * Index = (epnum * 2) + direction - 1,
1224 * where direction = 0 for OUT, 1 for IN.
1225 * For control endpoints, the IN index is used (OUT index is unused), so
1226 * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1228 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1231 if (usb_endpoint_xfer_control(desc))
1232 index = (unsigned int) (usb_endpoint_num(desc)*2);
1234 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1235 (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1239 /* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
1240 * address from the XHCI endpoint index.
1242 unsigned int xhci_get_endpoint_address(unsigned int ep_index)
1244 unsigned int number = DIV_ROUND_UP(ep_index, 2);
1245 unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
1246 return direction | number;
1249 /* Find the flag for this endpoint (for use in the control context). Use the
1250 * endpoint index to create a bitmask. The slot context is bit 0, endpoint 0 is
1253 static unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1255 return 1 << (xhci_get_endpoint_index(desc) + 1);
1258 /* Find the flag for this endpoint (for use in the control context). Use the
1259 * endpoint index to create a bitmask. The slot context is bit 0, endpoint 0 is
1262 static unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
1264 return 1 << (ep_index + 1);
1267 /* Compute the last valid endpoint context index. Basically, this is the
1268 * endpoint index plus one. For slot contexts with more than valid endpoint,
1269 * we find the most significant bit set in the added contexts flags.
1270 * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1271 * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1273 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1275 return fls(added_ctxs) - 1;
1278 /* Returns 1 if the arguments are OK;
1279 * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1281 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1282 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1284 struct xhci_hcd *xhci;
1285 struct xhci_virt_device *virt_dev;
1287 if (!hcd || (check_ep && !ep) || !udev) {
1288 pr_debug("xHCI %s called with invalid args\n", func);
1291 if (!udev->parent) {
1292 pr_debug("xHCI %s called for root hub\n", func);
1296 xhci = hcd_to_xhci(hcd);
1297 if (check_virt_dev) {
1298 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1299 xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
1304 virt_dev = xhci->devs[udev->slot_id];
1305 if (virt_dev->udev != udev) {
1306 xhci_dbg(xhci, "xHCI %s called with udev and "
1307 "virt_dev does not match\n", func);
1312 if (xhci->xhc_state & XHCI_STATE_HALTED)
1318 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1319 struct usb_device *udev, struct xhci_command *command,
1320 bool ctx_change, bool must_succeed);
1323 * Full speed devices may have a max packet size greater than 8 bytes, but the
1324 * USB core doesn't know that until it reads the first 8 bytes of the
1325 * descriptor. If the usb_device's max packet size changes after that point,
1326 * we need to issue an evaluate context command and wait on it.
1328 static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
1329 unsigned int ep_index, struct urb *urb, gfp_t mem_flags)
1331 struct xhci_container_ctx *out_ctx;
1332 struct xhci_input_control_ctx *ctrl_ctx;
1333 struct xhci_ep_ctx *ep_ctx;
1334 struct xhci_command *command;
1335 int max_packet_size;
1336 int hw_max_packet_size;
1339 out_ctx = xhci->devs[slot_id]->out_ctx;
1340 ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1341 hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1342 max_packet_size = usb_endpoint_maxp(&urb->dev->ep0.desc);
1343 if (hw_max_packet_size != max_packet_size) {
1344 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1345 "Max Packet Size for ep 0 changed.");
1346 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1347 "Max packet size in usb_device = %d",
1349 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1350 "Max packet size in xHCI HW = %d",
1351 hw_max_packet_size);
1352 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1353 "Issuing evaluate context command.");
1355 /* Set up the input context flags for the command */
1356 /* FIXME: This won't work if a non-default control endpoint
1357 * changes max packet sizes.
1360 command = xhci_alloc_command(xhci, false, true, mem_flags);
1364 command->in_ctx = xhci->devs[slot_id]->in_ctx;
1365 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
1367 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1370 goto command_cleanup;
1372 /* Set up the modified control endpoint 0 */
1373 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1374 xhci->devs[slot_id]->out_ctx, ep_index);
1376 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
1377 ep_ctx->ep_info &= cpu_to_le32(~EP_STATE_MASK);/* must clear */
1378 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1379 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1381 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1382 ctrl_ctx->drop_flags = 0;
1384 ret = xhci_configure_endpoint(xhci, urb->dev, command,
1387 /* Clean up the input context for later use by bandwidth
1390 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1392 kfree(command->completion);
1399 * non-error returns are a promise to giveback() the urb later
1400 * we drop ownership so next owner (or urb unlink) can get it
1402 static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1404 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1405 unsigned long flags;
1407 unsigned int slot_id, ep_index, ep_state;
1408 struct urb_priv *urb_priv;
1413 ret = xhci_check_args(hcd, urb->dev, urb->ep,
1414 true, true, __func__);
1416 return ret ? ret : -EINVAL;
1418 slot_id = urb->dev->slot_id;
1419 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1421 if (!HCD_HW_ACCESSIBLE(hcd)) {
1422 if (!in_interrupt())
1423 xhci_dbg(xhci, "urb submitted during PCI suspend\n");
1427 if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1428 num_tds = urb->number_of_packets;
1429 else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
1430 urb->transfer_buffer_length > 0 &&
1431 urb->transfer_flags & URB_ZERO_PACKET &&
1432 !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
1437 urb_priv = kzalloc(sizeof(struct urb_priv) +
1438 num_tds * sizeof(struct xhci_td), mem_flags);
1442 urb_priv->num_tds = num_tds;
1443 urb_priv->num_tds_done = 0;
1444 urb->hcpriv = urb_priv;
1446 trace_xhci_urb_enqueue(urb);
1448 if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1449 /* Check to see if the max packet size for the default control
1450 * endpoint changed during FS device enumeration
1452 if (urb->dev->speed == USB_SPEED_FULL) {
1453 ret = xhci_check_maxpacket(xhci, slot_id,
1454 ep_index, urb, mem_flags);
1456 xhci_urb_free_priv(urb_priv);
1463 spin_lock_irqsave(&xhci->lock, flags);
1465 if (xhci->xhc_state & XHCI_STATE_DYING) {
1466 xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n",
1467 urb->ep->desc.bEndpointAddress, urb);
1472 switch (usb_endpoint_type(&urb->ep->desc)) {
1474 case USB_ENDPOINT_XFER_CONTROL:
1475 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1478 case USB_ENDPOINT_XFER_BULK:
1479 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
1480 if (ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) {
1481 xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n",
1486 ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1491 case USB_ENDPOINT_XFER_INT:
1492 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1496 case USB_ENDPOINT_XFER_ISOC:
1497 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1503 xhci_urb_free_priv(urb_priv);
1506 spin_unlock_irqrestore(&xhci->lock, flags);
1511 * Remove the URB's TD from the endpoint ring. This may cause the HC to stop
1512 * USB transfers, potentially stopping in the middle of a TRB buffer. The HC
1513 * should pick up where it left off in the TD, unless a Set Transfer Ring
1514 * Dequeue Pointer is issued.
1516 * The TRBs that make up the buffers for the canceled URB will be "removed" from
1517 * the ring. Since the ring is a contiguous structure, they can't be physically
1518 * removed. Instead, there are two options:
1520 * 1) If the HC is in the middle of processing the URB to be canceled, we
1521 * simply move the ring's dequeue pointer past those TRBs using the Set
1522 * Transfer Ring Dequeue Pointer command. This will be the common case,
1523 * when drivers timeout on the last submitted URB and attempt to cancel.
1525 * 2) If the HC is in the middle of a different TD, we turn the TRBs into a
1526 * series of 1-TRB transfer no-op TDs. (No-ops shouldn't be chained.) The
1527 * HC will need to invalidate the any TRBs it has cached after the stop
1528 * endpoint command, as noted in the xHCI 0.95 errata.
1530 * 3) The TD may have completed by the time the Stop Endpoint Command
1531 * completes, so software needs to handle that case too.
1533 * This function should protect against the TD enqueueing code ringing the
1534 * doorbell while this code is waiting for a Stop Endpoint command to complete.
1535 * It also needs to account for multiple cancellations on happening at the same
1536 * time for the same endpoint.
1538 * Note that this function can be called in any context, or so says
1539 * usb_hcd_unlink_urb()
1541 static int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1543 unsigned long flags;
1546 struct xhci_hcd *xhci;
1547 struct urb_priv *urb_priv;
1549 unsigned int ep_index;
1550 struct xhci_ring *ep_ring;
1551 struct xhci_virt_ep *ep;
1552 struct xhci_command *command;
1553 struct xhci_virt_device *vdev;
1555 xhci = hcd_to_xhci(hcd);
1556 spin_lock_irqsave(&xhci->lock, flags);
1558 trace_xhci_urb_dequeue(urb);
1560 /* Make sure the URB hasn't completed or been unlinked already */
1561 ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1565 /* give back URB now if we can't queue it for cancel */
1566 vdev = xhci->devs[urb->dev->slot_id];
1567 urb_priv = urb->hcpriv;
1568 if (!vdev || !urb_priv)
1571 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1572 ep = &vdev->eps[ep_index];
1573 ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1574 if (!ep || !ep_ring)
1577 /* If xHC is dead take it down and return ALL URBs in xhci_hc_died() */
1578 temp = readl(&xhci->op_regs->status);
1579 if (temp == ~(u32)0 || xhci->xhc_state & XHCI_STATE_DYING) {
1585 * check ring is not re-allocated since URB was enqueued. If it is, then
1586 * make sure none of the ring related pointers in this URB private data
1587 * are touched, such as td_list, otherwise we overwrite freed data
1589 if (!td_on_ring(&urb_priv->td[0], ep_ring)) {
1590 xhci_err(xhci, "Canceled URB td not found on endpoint ring");
1591 for (i = urb_priv->num_tds_done; i < urb_priv->num_tds; i++) {
1592 td = &urb_priv->td[i];
1593 if (!list_empty(&td->cancelled_td_list))
1594 list_del_init(&td->cancelled_td_list);
1599 if (xhci->xhc_state & XHCI_STATE_HALTED) {
1600 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1601 "HC halted, freeing TD manually.");
1602 for (i = urb_priv->num_tds_done;
1603 i < urb_priv->num_tds;
1605 td = &urb_priv->td[i];
1606 if (!list_empty(&td->td_list))
1607 list_del_init(&td->td_list);
1608 if (!list_empty(&td->cancelled_td_list))
1609 list_del_init(&td->cancelled_td_list);
1614 i = urb_priv->num_tds_done;
1615 if (i < urb_priv->num_tds)
1616 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1617 "Cancel URB %p, dev %s, ep 0x%x, "
1618 "starting at offset 0x%llx",
1619 urb, urb->dev->devpath,
1620 urb->ep->desc.bEndpointAddress,
1621 (unsigned long long) xhci_trb_virt_to_dma(
1622 urb_priv->td[i].start_seg,
1623 urb_priv->td[i].first_trb));
1625 for (; i < urb_priv->num_tds; i++) {
1626 td = &urb_priv->td[i];
1627 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1630 /* Queue a stop endpoint command, but only if this is
1631 * the first cancellation to be handled.
1633 if (!(ep->ep_state & EP_STOP_CMD_PENDING)) {
1634 command = xhci_alloc_command(xhci, false, false, GFP_ATOMIC);
1639 ep->ep_state |= EP_STOP_CMD_PENDING;
1640 ep->stop_cmd_timer.expires = jiffies +
1641 XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1642 add_timer(&ep->stop_cmd_timer);
1643 xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1645 xhci_ring_cmd_db(xhci);
1648 spin_unlock_irqrestore(&xhci->lock, flags);
1653 xhci_urb_free_priv(urb_priv);
1654 usb_hcd_unlink_urb_from_ep(hcd, urb);
1655 spin_unlock_irqrestore(&xhci->lock, flags);
1656 usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1660 /* Drop an endpoint from a new bandwidth configuration for this device.
1661 * Only one call to this function is allowed per endpoint before
1662 * check_bandwidth() or reset_bandwidth() must be called.
1663 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1664 * add the endpoint to the schedule with possibly new parameters denoted by a
1665 * different endpoint descriptor in usb_host_endpoint.
1666 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1669 * The USB core will not allow URBs to be queued to an endpoint that is being
1670 * disabled, so there's no need for mutual exclusion to protect
1671 * the xhci->devs[slot_id] structure.
1673 static int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1674 struct usb_host_endpoint *ep)
1676 struct xhci_hcd *xhci;
1677 struct xhci_container_ctx *in_ctx, *out_ctx;
1678 struct xhci_input_control_ctx *ctrl_ctx;
1679 unsigned int ep_index;
1680 struct xhci_ep_ctx *ep_ctx;
1682 u32 new_add_flags, new_drop_flags;
1685 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1688 xhci = hcd_to_xhci(hcd);
1689 if (xhci->xhc_state & XHCI_STATE_DYING)
1692 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1693 drop_flag = xhci_get_endpoint_flag(&ep->desc);
1694 if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1695 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1696 __func__, drop_flag);
1700 in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1701 out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1702 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1704 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1709 ep_index = xhci_get_endpoint_index(&ep->desc);
1710 ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1711 /* If the HC already knows the endpoint is disabled,
1712 * or the HCD has noted it is disabled, ignore this request
1714 if ((GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) ||
1715 le32_to_cpu(ctrl_ctx->drop_flags) &
1716 xhci_get_endpoint_flag(&ep->desc)) {
1717 /* Do not warn when called after a usb_device_reset */
1718 if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1719 xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1724 ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1725 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1727 ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1728 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1730 xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1732 if (xhci->quirks & XHCI_MTK_HOST)
1733 xhci_mtk_drop_ep_quirk(hcd, udev, ep);
1735 xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1736 (unsigned int) ep->desc.bEndpointAddress,
1738 (unsigned int) new_drop_flags,
1739 (unsigned int) new_add_flags);
1743 /* Add an endpoint to a new possible bandwidth configuration for this device.
1744 * Only one call to this function is allowed per endpoint before
1745 * check_bandwidth() or reset_bandwidth() must be called.
1746 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1747 * add the endpoint to the schedule with possibly new parameters denoted by a
1748 * different endpoint descriptor in usb_host_endpoint.
1749 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1752 * The USB core will not allow URBs to be queued to an endpoint until the
1753 * configuration or alt setting is installed in the device, so there's no need
1754 * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1756 static int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1757 struct usb_host_endpoint *ep)
1759 struct xhci_hcd *xhci;
1760 struct xhci_container_ctx *in_ctx;
1761 unsigned int ep_index;
1762 struct xhci_input_control_ctx *ctrl_ctx;
1764 u32 new_add_flags, new_drop_flags;
1765 struct xhci_virt_device *virt_dev;
1768 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1770 /* So we won't queue a reset ep command for a root hub */
1774 xhci = hcd_to_xhci(hcd);
1775 if (xhci->xhc_state & XHCI_STATE_DYING)
1778 added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1779 if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1780 /* FIXME when we have to issue an evaluate endpoint command to
1781 * deal with ep0 max packet size changing once we get the
1784 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1785 __func__, added_ctxs);
1789 virt_dev = xhci->devs[udev->slot_id];
1790 in_ctx = virt_dev->in_ctx;
1791 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1793 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1798 ep_index = xhci_get_endpoint_index(&ep->desc);
1799 /* If this endpoint is already in use, and the upper layers are trying
1800 * to add it again without dropping it, reject the addition.
1802 if (virt_dev->eps[ep_index].ring &&
1803 !(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
1804 xhci_warn(xhci, "Trying to add endpoint 0x%x "
1805 "without dropping it.\n",
1806 (unsigned int) ep->desc.bEndpointAddress);
1810 /* If the HCD has already noted the endpoint is enabled,
1811 * ignore this request.
1813 if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
1814 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1820 * Configuration and alternate setting changes must be done in
1821 * process context, not interrupt context (or so documenation
1822 * for usb_set_interface() and usb_set_configuration() claim).
1824 if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1825 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1826 __func__, ep->desc.bEndpointAddress);
1830 if (xhci->quirks & XHCI_MTK_HOST) {
1831 ret = xhci_mtk_add_ep_quirk(hcd, udev, ep);
1833 xhci_ring_free(xhci, virt_dev->eps[ep_index].new_ring);
1834 virt_dev->eps[ep_index].new_ring = NULL;
1839 ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1840 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1842 /* If xhci_endpoint_disable() was called for this endpoint, but the
1843 * xHC hasn't been notified yet through the check_bandwidth() call,
1844 * this re-adds a new state for the endpoint from the new endpoint
1845 * descriptors. We must drop and re-add this endpoint, so we leave the
1848 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1850 /* Store the usb_device pointer for later use */
1853 xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1854 (unsigned int) ep->desc.bEndpointAddress,
1856 (unsigned int) new_drop_flags,
1857 (unsigned int) new_add_flags);
1861 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1863 struct xhci_input_control_ctx *ctrl_ctx;
1864 struct xhci_ep_ctx *ep_ctx;
1865 struct xhci_slot_ctx *slot_ctx;
1868 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1870 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1875 /* When a device's add flag and drop flag are zero, any subsequent
1876 * configure endpoint command will leave that endpoint's state
1877 * untouched. Make sure we don't leave any old state in the input
1878 * endpoint contexts.
1880 ctrl_ctx->drop_flags = 0;
1881 ctrl_ctx->add_flags = 0;
1882 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1883 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1884 /* Endpoint 0 is always valid */
1885 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
1886 for (i = 1; i < 31; i++) {
1887 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1888 ep_ctx->ep_info = 0;
1889 ep_ctx->ep_info2 = 0;
1891 ep_ctx->tx_info = 0;
1895 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1896 struct usb_device *udev, u32 *cmd_status)
1900 switch (*cmd_status) {
1901 case COMP_COMMAND_ABORTED:
1902 case COMP_COMMAND_RING_STOPPED:
1903 xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
1906 case COMP_RESOURCE_ERROR:
1907 dev_warn(&udev->dev,
1908 "Not enough host controller resources for new device state.\n");
1910 /* FIXME: can we allocate more resources for the HC? */
1912 case COMP_BANDWIDTH_ERROR:
1913 case COMP_SECONDARY_BANDWIDTH_ERROR:
1914 dev_warn(&udev->dev,
1915 "Not enough bandwidth for new device state.\n");
1917 /* FIXME: can we go back to the old state? */
1919 case COMP_TRB_ERROR:
1920 /* the HCD set up something wrong */
1921 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
1923 "and endpoint is not disabled.\n");
1926 case COMP_INCOMPATIBLE_DEVICE_ERROR:
1927 dev_warn(&udev->dev,
1928 "ERROR: Incompatible device for endpoint configure command.\n");
1932 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1933 "Successful Endpoint Configure command");
1937 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1945 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
1946 struct usb_device *udev, u32 *cmd_status)
1950 switch (*cmd_status) {
1951 case COMP_COMMAND_ABORTED:
1952 case COMP_COMMAND_RING_STOPPED:
1953 xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
1956 case COMP_PARAMETER_ERROR:
1957 dev_warn(&udev->dev,
1958 "WARN: xHCI driver setup invalid evaluate context command.\n");
1961 case COMP_SLOT_NOT_ENABLED_ERROR:
1962 dev_warn(&udev->dev,
1963 "WARN: slot not enabled for evaluate context command.\n");
1966 case COMP_CONTEXT_STATE_ERROR:
1967 dev_warn(&udev->dev,
1968 "WARN: invalid context state for evaluate context command.\n");
1971 case COMP_INCOMPATIBLE_DEVICE_ERROR:
1972 dev_warn(&udev->dev,
1973 "ERROR: Incompatible device for evaluate context command.\n");
1976 case COMP_MAX_EXIT_LATENCY_TOO_LARGE_ERROR:
1977 /* Max Exit Latency too large error */
1978 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
1982 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1983 "Successful evaluate context command");
1987 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
1995 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
1996 struct xhci_input_control_ctx *ctrl_ctx)
1998 u32 valid_add_flags;
1999 u32 valid_drop_flags;
2001 /* Ignore the slot flag (bit 0), and the default control endpoint flag
2002 * (bit 1). The default control endpoint is added during the Address
2003 * Device command and is never removed until the slot is disabled.
2005 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2006 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2008 /* Use hweight32 to count the number of ones in the add flags, or
2009 * number of endpoints added. Don't count endpoints that are changed
2010 * (both added and dropped).
2012 return hweight32(valid_add_flags) -
2013 hweight32(valid_add_flags & valid_drop_flags);
2016 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
2017 struct xhci_input_control_ctx *ctrl_ctx)
2019 u32 valid_add_flags;
2020 u32 valid_drop_flags;
2022 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2023 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2025 return hweight32(valid_drop_flags) -
2026 hweight32(valid_add_flags & valid_drop_flags);
2030 * We need to reserve the new number of endpoints before the configure endpoint
2031 * command completes. We can't subtract the dropped endpoints from the number
2032 * of active endpoints until the command completes because we can oversubscribe
2033 * the host in this case:
2035 * - the first configure endpoint command drops more endpoints than it adds
2036 * - a second configure endpoint command that adds more endpoints is queued
2037 * - the first configure endpoint command fails, so the config is unchanged
2038 * - the second command may succeed, even though there isn't enough resources
2040 * Must be called with xhci->lock held.
2042 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
2043 struct xhci_input_control_ctx *ctrl_ctx)
2047 added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2048 if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
2049 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2050 "Not enough ep ctxs: "
2051 "%u active, need to add %u, limit is %u.",
2052 xhci->num_active_eps, added_eps,
2053 xhci->limit_active_eps);
2056 xhci->num_active_eps += added_eps;
2057 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2058 "Adding %u ep ctxs, %u now active.", added_eps,
2059 xhci->num_active_eps);
2064 * The configure endpoint was failed by the xHC for some other reason, so we
2065 * need to revert the resources that failed configuration would have used.
2067 * Must be called with xhci->lock held.
2069 static void xhci_free_host_resources(struct xhci_hcd *xhci,
2070 struct xhci_input_control_ctx *ctrl_ctx)
2074 num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2075 xhci->num_active_eps -= num_failed_eps;
2076 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2077 "Removing %u failed ep ctxs, %u now active.",
2079 xhci->num_active_eps);
2083 * Now that the command has completed, clean up the active endpoint count by
2084 * subtracting out the endpoints that were dropped (but not changed).
2086 * Must be called with xhci->lock held.
2088 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
2089 struct xhci_input_control_ctx *ctrl_ctx)
2091 u32 num_dropped_eps;
2093 num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
2094 xhci->num_active_eps -= num_dropped_eps;
2095 if (num_dropped_eps)
2096 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2097 "Removing %u dropped ep ctxs, %u now active.",
2099 xhci->num_active_eps);
2102 static unsigned int xhci_get_block_size(struct usb_device *udev)
2104 switch (udev->speed) {
2106 case USB_SPEED_FULL:
2108 case USB_SPEED_HIGH:
2110 case USB_SPEED_SUPER:
2111 case USB_SPEED_SUPER_PLUS:
2113 case USB_SPEED_UNKNOWN:
2114 case USB_SPEED_WIRELESS:
2116 /* Should never happen */
2122 xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
2124 if (interval_bw->overhead[LS_OVERHEAD_TYPE])
2126 if (interval_bw->overhead[FS_OVERHEAD_TYPE])
2131 /* If we are changing a LS/FS device under a HS hub,
2132 * make sure (if we are activating a new TT) that the HS bus has enough
2133 * bandwidth for this new TT.
2135 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2136 struct xhci_virt_device *virt_dev,
2139 struct xhci_interval_bw_table *bw_table;
2140 struct xhci_tt_bw_info *tt_info;
2142 /* Find the bandwidth table for the root port this TT is attached to. */
2143 bw_table = &xhci->rh_bw[virt_dev->real_port - 1].bw_table;
2144 tt_info = virt_dev->tt_info;
2145 /* If this TT already had active endpoints, the bandwidth for this TT
2146 * has already been added. Removing all periodic endpoints (and thus
2147 * making the TT enactive) will only decrease the bandwidth used.
2151 if (old_active_eps == 0 && tt_info->active_eps != 0) {
2152 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2156 /* Not sure why we would have no new active endpoints...
2158 * Maybe because of an Evaluate Context change for a hub update or a
2159 * control endpoint 0 max packet size change?
2160 * FIXME: skip the bandwidth calculation in that case.
2165 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2166 struct xhci_virt_device *virt_dev)
2168 unsigned int bw_reserved;
2170 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2171 if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2174 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2175 if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2182 * This algorithm is a very conservative estimate of the worst-case scheduling
2183 * scenario for any one interval. The hardware dynamically schedules the
2184 * packets, so we can't tell which microframe could be the limiting factor in
2185 * the bandwidth scheduling. This only takes into account periodic endpoints.
2187 * Obviously, we can't solve an NP complete problem to find the minimum worst
2188 * case scenario. Instead, we come up with an estimate that is no less than
2189 * the worst case bandwidth used for any one microframe, but may be an
2192 * We walk the requirements for each endpoint by interval, starting with the
2193 * smallest interval, and place packets in the schedule where there is only one
2194 * possible way to schedule packets for that interval. In order to simplify
2195 * this algorithm, we record the largest max packet size for each interval, and
2196 * assume all packets will be that size.
2198 * For interval 0, we obviously must schedule all packets for each interval.
2199 * The bandwidth for interval 0 is just the amount of data to be transmitted
2200 * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2201 * the number of packets).
2203 * For interval 1, we have two possible microframes to schedule those packets
2204 * in. For this algorithm, if we can schedule the same number of packets for
2205 * each possible scheduling opportunity (each microframe), we will do so. The
2206 * remaining number of packets will be saved to be transmitted in the gaps in
2207 * the next interval's scheduling sequence.
2209 * As we move those remaining packets to be scheduled with interval 2 packets,
2210 * we have to double the number of remaining packets to transmit. This is
2211 * because the intervals are actually powers of 2, and we would be transmitting
2212 * the previous interval's packets twice in this interval. We also have to be
2213 * sure that when we look at the largest max packet size for this interval, we
2214 * also look at the largest max packet size for the remaining packets and take
2215 * the greater of the two.
2217 * The algorithm continues to evenly distribute packets in each scheduling
2218 * opportunity, and push the remaining packets out, until we get to the last
2219 * interval. Then those packets and their associated overhead are just added
2220 * to the bandwidth used.
2222 static int xhci_check_bw_table(struct xhci_hcd *xhci,
2223 struct xhci_virt_device *virt_dev,
2226 unsigned int bw_reserved;
2227 unsigned int max_bandwidth;
2228 unsigned int bw_used;
2229 unsigned int block_size;
2230 struct xhci_interval_bw_table *bw_table;
2231 unsigned int packet_size = 0;
2232 unsigned int overhead = 0;
2233 unsigned int packets_transmitted = 0;
2234 unsigned int packets_remaining = 0;
2237 if (virt_dev->udev->speed >= USB_SPEED_SUPER)
2238 return xhci_check_ss_bw(xhci, virt_dev);
2240 if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2241 max_bandwidth = HS_BW_LIMIT;
2242 /* Convert percent of bus BW reserved to blocks reserved */
2243 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2245 max_bandwidth = FS_BW_LIMIT;
2246 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2249 bw_table = virt_dev->bw_table;
2250 /* We need to translate the max packet size and max ESIT payloads into
2251 * the units the hardware uses.
2253 block_size = xhci_get_block_size(virt_dev->udev);
2255 /* If we are manipulating a LS/FS device under a HS hub, double check
2256 * that the HS bus has enough bandwidth if we are activing a new TT.
2258 if (virt_dev->tt_info) {
2259 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2260 "Recalculating BW for rootport %u",
2261 virt_dev->real_port);
2262 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2263 xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2264 "newly activated TT.\n");
2267 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2268 "Recalculating BW for TT slot %u port %u",
2269 virt_dev->tt_info->slot_id,
2270 virt_dev->tt_info->ttport);
2272 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2273 "Recalculating BW for rootport %u",
2274 virt_dev->real_port);
2277 /* Add in how much bandwidth will be used for interval zero, or the
2278 * rounded max ESIT payload + number of packets * largest overhead.
2280 bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2281 bw_table->interval_bw[0].num_packets *
2282 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2284 for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2285 unsigned int bw_added;
2286 unsigned int largest_mps;
2287 unsigned int interval_overhead;
2290 * How many packets could we transmit in this interval?
2291 * If packets didn't fit in the previous interval, we will need
2292 * to transmit that many packets twice within this interval.
2294 packets_remaining = 2 * packets_remaining +
2295 bw_table->interval_bw[i].num_packets;
2297 /* Find the largest max packet size of this or the previous
2300 if (list_empty(&bw_table->interval_bw[i].endpoints))
2303 struct xhci_virt_ep *virt_ep;
2304 struct list_head *ep_entry;
2306 ep_entry = bw_table->interval_bw[i].endpoints.next;
2307 virt_ep = list_entry(ep_entry,
2308 struct xhci_virt_ep, bw_endpoint_list);
2309 /* Convert to blocks, rounding up */
2310 largest_mps = DIV_ROUND_UP(
2311 virt_ep->bw_info.max_packet_size,
2314 if (largest_mps > packet_size)
2315 packet_size = largest_mps;
2317 /* Use the larger overhead of this or the previous interval. */
2318 interval_overhead = xhci_get_largest_overhead(
2319 &bw_table->interval_bw[i]);
2320 if (interval_overhead > overhead)
2321 overhead = interval_overhead;
2323 /* How many packets can we evenly distribute across
2324 * (1 << (i + 1)) possible scheduling opportunities?
2326 packets_transmitted = packets_remaining >> (i + 1);
2328 /* Add in the bandwidth used for those scheduled packets */
2329 bw_added = packets_transmitted * (overhead + packet_size);
2331 /* How many packets do we have remaining to transmit? */
2332 packets_remaining = packets_remaining % (1 << (i + 1));
2334 /* What largest max packet size should those packets have? */
2335 /* If we've transmitted all packets, don't carry over the
2336 * largest packet size.
2338 if (packets_remaining == 0) {
2341 } else if (packets_transmitted > 0) {
2342 /* Otherwise if we do have remaining packets, and we've
2343 * scheduled some packets in this interval, take the
2344 * largest max packet size from endpoints with this
2347 packet_size = largest_mps;
2348 overhead = interval_overhead;
2350 /* Otherwise carry over packet_size and overhead from the last
2351 * time we had a remainder.
2353 bw_used += bw_added;
2354 if (bw_used > max_bandwidth) {
2355 xhci_warn(xhci, "Not enough bandwidth. "
2356 "Proposed: %u, Max: %u\n",
2357 bw_used, max_bandwidth);
2362 * Ok, we know we have some packets left over after even-handedly
2363 * scheduling interval 15. We don't know which microframes they will
2364 * fit into, so we over-schedule and say they will be scheduled every
2367 if (packets_remaining > 0)
2368 bw_used += overhead + packet_size;
2370 if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2371 unsigned int port_index = virt_dev->real_port - 1;
2373 /* OK, we're manipulating a HS device attached to a
2374 * root port bandwidth domain. Include the number of active TTs
2375 * in the bandwidth used.
2377 bw_used += TT_HS_OVERHEAD *
2378 xhci->rh_bw[port_index].num_active_tts;
2381 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2382 "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2383 "Available: %u " "percent",
2384 bw_used, max_bandwidth, bw_reserved,
2385 (max_bandwidth - bw_used - bw_reserved) * 100 /
2388 bw_used += bw_reserved;
2389 if (bw_used > max_bandwidth) {
2390 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2391 bw_used, max_bandwidth);
2395 bw_table->bw_used = bw_used;
2399 static bool xhci_is_async_ep(unsigned int ep_type)
2401 return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2402 ep_type != ISOC_IN_EP &&
2403 ep_type != INT_IN_EP);
2406 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2408 return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
2411 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2413 unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2415 if (ep_bw->ep_interval == 0)
2416 return SS_OVERHEAD_BURST +
2417 (ep_bw->mult * ep_bw->num_packets *
2418 (SS_OVERHEAD + mps));
2419 return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2420 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2421 1 << ep_bw->ep_interval);
2425 static void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2426 struct xhci_bw_info *ep_bw,
2427 struct xhci_interval_bw_table *bw_table,
2428 struct usb_device *udev,
2429 struct xhci_virt_ep *virt_ep,
2430 struct xhci_tt_bw_info *tt_info)
2432 struct xhci_interval_bw *interval_bw;
2433 int normalized_interval;
2435 if (xhci_is_async_ep(ep_bw->type))
2438 if (udev->speed >= USB_SPEED_SUPER) {
2439 if (xhci_is_sync_in_ep(ep_bw->type))
2440 xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2441 xhci_get_ss_bw_consumed(ep_bw);
2443 xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2444 xhci_get_ss_bw_consumed(ep_bw);
2448 /* SuperSpeed endpoints never get added to intervals in the table, so
2449 * this check is only valid for HS/FS/LS devices.
2451 if (list_empty(&virt_ep->bw_endpoint_list))
2453 /* For LS/FS devices, we need to translate the interval expressed in
2454 * microframes to frames.
2456 if (udev->speed == USB_SPEED_HIGH)
2457 normalized_interval = ep_bw->ep_interval;
2459 normalized_interval = ep_bw->ep_interval - 3;
2461 if (normalized_interval == 0)
2462 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2463 interval_bw = &bw_table->interval_bw[normalized_interval];
2464 interval_bw->num_packets -= ep_bw->num_packets;
2465 switch (udev->speed) {
2467 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2469 case USB_SPEED_FULL:
2470 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2472 case USB_SPEED_HIGH:
2473 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2475 case USB_SPEED_SUPER:
2476 case USB_SPEED_SUPER_PLUS:
2477 case USB_SPEED_UNKNOWN:
2478 case USB_SPEED_WIRELESS:
2479 /* Should never happen because only LS/FS/HS endpoints will get
2480 * added to the endpoint list.
2485 tt_info->active_eps -= 1;
2486 list_del_init(&virt_ep->bw_endpoint_list);
2489 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2490 struct xhci_bw_info *ep_bw,
2491 struct xhci_interval_bw_table *bw_table,
2492 struct usb_device *udev,
2493 struct xhci_virt_ep *virt_ep,
2494 struct xhci_tt_bw_info *tt_info)
2496 struct xhci_interval_bw *interval_bw;
2497 struct xhci_virt_ep *smaller_ep;
2498 int normalized_interval;
2500 if (xhci_is_async_ep(ep_bw->type))
2503 if (udev->speed == USB_SPEED_SUPER) {
2504 if (xhci_is_sync_in_ep(ep_bw->type))
2505 xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2506 xhci_get_ss_bw_consumed(ep_bw);
2508 xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2509 xhci_get_ss_bw_consumed(ep_bw);
2513 /* For LS/FS devices, we need to translate the interval expressed in
2514 * microframes to frames.
2516 if (udev->speed == USB_SPEED_HIGH)
2517 normalized_interval = ep_bw->ep_interval;
2519 normalized_interval = ep_bw->ep_interval - 3;
2521 if (normalized_interval == 0)
2522 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2523 interval_bw = &bw_table->interval_bw[normalized_interval];
2524 interval_bw->num_packets += ep_bw->num_packets;
2525 switch (udev->speed) {
2527 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2529 case USB_SPEED_FULL:
2530 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2532 case USB_SPEED_HIGH:
2533 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2535 case USB_SPEED_SUPER:
2536 case USB_SPEED_SUPER_PLUS:
2537 case USB_SPEED_UNKNOWN:
2538 case USB_SPEED_WIRELESS:
2539 /* Should never happen because only LS/FS/HS endpoints will get
2540 * added to the endpoint list.
2546 tt_info->active_eps += 1;
2547 /* Insert the endpoint into the list, largest max packet size first. */
2548 list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2550 if (ep_bw->max_packet_size >=
2551 smaller_ep->bw_info.max_packet_size) {
2552 /* Add the new ep before the smaller endpoint */
2553 list_add_tail(&virt_ep->bw_endpoint_list,
2554 &smaller_ep->bw_endpoint_list);
2558 /* Add the new endpoint at the end of the list. */
2559 list_add_tail(&virt_ep->bw_endpoint_list,
2560 &interval_bw->endpoints);
2563 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2564 struct xhci_virt_device *virt_dev,
2567 struct xhci_root_port_bw_info *rh_bw_info;
2568 if (!virt_dev->tt_info)
2571 rh_bw_info = &xhci->rh_bw[virt_dev->real_port - 1];
2572 if (old_active_eps == 0 &&
2573 virt_dev->tt_info->active_eps != 0) {
2574 rh_bw_info->num_active_tts += 1;
2575 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2576 } else if (old_active_eps != 0 &&
2577 virt_dev->tt_info->active_eps == 0) {
2578 rh_bw_info->num_active_tts -= 1;
2579 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2583 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2584 struct xhci_virt_device *virt_dev,
2585 struct xhci_container_ctx *in_ctx)
2587 struct xhci_bw_info ep_bw_info[31];
2589 struct xhci_input_control_ctx *ctrl_ctx;
2590 int old_active_eps = 0;
2592 if (virt_dev->tt_info)
2593 old_active_eps = virt_dev->tt_info->active_eps;
2595 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2597 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2602 for (i = 0; i < 31; i++) {
2603 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2606 /* Make a copy of the BW info in case we need to revert this */
2607 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2608 sizeof(ep_bw_info[i]));
2609 /* Drop the endpoint from the interval table if the endpoint is
2610 * being dropped or changed.
2612 if (EP_IS_DROPPED(ctrl_ctx, i))
2613 xhci_drop_ep_from_interval_table(xhci,
2614 &virt_dev->eps[i].bw_info,
2620 /* Overwrite the information stored in the endpoints' bw_info */
2621 xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2622 for (i = 0; i < 31; i++) {
2623 /* Add any changed or added endpoints to the interval table */
2624 if (EP_IS_ADDED(ctrl_ctx, i))
2625 xhci_add_ep_to_interval_table(xhci,
2626 &virt_dev->eps[i].bw_info,
2633 if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2634 /* Ok, this fits in the bandwidth we have.
2635 * Update the number of active TTs.
2637 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2641 /* We don't have enough bandwidth for this, revert the stored info. */
2642 for (i = 0; i < 31; i++) {
2643 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2646 /* Drop the new copies of any added or changed endpoints from
2647 * the interval table.
2649 if (EP_IS_ADDED(ctrl_ctx, i)) {
2650 xhci_drop_ep_from_interval_table(xhci,
2651 &virt_dev->eps[i].bw_info,
2657 /* Revert the endpoint back to its old information */
2658 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2659 sizeof(ep_bw_info[i]));
2660 /* Add any changed or dropped endpoints back into the table */
2661 if (EP_IS_DROPPED(ctrl_ctx, i))
2662 xhci_add_ep_to_interval_table(xhci,
2663 &virt_dev->eps[i].bw_info,
2673 /* Issue a configure endpoint command or evaluate context command
2674 * and wait for it to finish.
2676 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2677 struct usb_device *udev,
2678 struct xhci_command *command,
2679 bool ctx_change, bool must_succeed)
2682 unsigned long flags;
2683 struct xhci_input_control_ctx *ctrl_ctx;
2684 struct xhci_virt_device *virt_dev;
2689 spin_lock_irqsave(&xhci->lock, flags);
2691 if (xhci->xhc_state & XHCI_STATE_DYING) {
2692 spin_unlock_irqrestore(&xhci->lock, flags);
2696 virt_dev = xhci->devs[udev->slot_id];
2698 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2700 spin_unlock_irqrestore(&xhci->lock, flags);
2701 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2706 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2707 xhci_reserve_host_resources(xhci, ctrl_ctx)) {
2708 spin_unlock_irqrestore(&xhci->lock, flags);
2709 xhci_warn(xhci, "Not enough host resources, "
2710 "active endpoint contexts = %u\n",
2711 xhci->num_active_eps);
2714 if ((xhci->quirks & XHCI_SW_BW_CHECKING) &&
2715 xhci_reserve_bandwidth(xhci, virt_dev, command->in_ctx)) {
2716 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2717 xhci_free_host_resources(xhci, ctrl_ctx);
2718 spin_unlock_irqrestore(&xhci->lock, flags);
2719 xhci_warn(xhci, "Not enough bandwidth\n");
2724 ret = xhci_queue_configure_endpoint(xhci, command,
2725 command->in_ctx->dma,
2726 udev->slot_id, must_succeed);
2728 ret = xhci_queue_evaluate_context(xhci, command,
2729 command->in_ctx->dma,
2730 udev->slot_id, must_succeed);
2732 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2733 xhci_free_host_resources(xhci, ctrl_ctx);
2734 spin_unlock_irqrestore(&xhci->lock, flags);
2735 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2736 "FIXME allocate a new ring segment");
2739 xhci_ring_cmd_db(xhci);
2740 spin_unlock_irqrestore(&xhci->lock, flags);
2742 /* Wait for the configure endpoint command to complete */
2743 wait_for_completion(command->completion);
2746 ret = xhci_configure_endpoint_result(xhci, udev,
2749 ret = xhci_evaluate_context_result(xhci, udev,
2752 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2753 spin_lock_irqsave(&xhci->lock, flags);
2754 /* If the command failed, remove the reserved resources.
2755 * Otherwise, clean up the estimate to include dropped eps.
2758 xhci_free_host_resources(xhci, ctrl_ctx);
2760 xhci_finish_resource_reservation(xhci, ctrl_ctx);
2761 spin_unlock_irqrestore(&xhci->lock, flags);
2766 static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
2767 struct xhci_virt_device *vdev, int i)
2769 struct xhci_virt_ep *ep = &vdev->eps[i];
2771 if (ep->ep_state & EP_HAS_STREAMS) {
2772 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
2773 xhci_get_endpoint_address(i));
2774 xhci_free_stream_info(xhci, ep->stream_info);
2775 ep->stream_info = NULL;
2776 ep->ep_state &= ~EP_HAS_STREAMS;
2780 /* Called after one or more calls to xhci_add_endpoint() or
2781 * xhci_drop_endpoint(). If this call fails, the USB core is expected
2782 * to call xhci_reset_bandwidth().
2784 * Since we are in the middle of changing either configuration or
2785 * installing a new alt setting, the USB core won't allow URBs to be
2786 * enqueued for any endpoint on the old config or interface. Nothing
2787 * else should be touching the xhci->devs[slot_id] structure, so we
2788 * don't need to take the xhci->lock for manipulating that.
2790 static int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2794 struct xhci_hcd *xhci;
2795 struct xhci_virt_device *virt_dev;
2796 struct xhci_input_control_ctx *ctrl_ctx;
2797 struct xhci_slot_ctx *slot_ctx;
2798 struct xhci_command *command;
2800 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2803 xhci = hcd_to_xhci(hcd);
2804 if ((xhci->xhc_state & XHCI_STATE_DYING) ||
2805 (xhci->xhc_state & XHCI_STATE_REMOVING))
2808 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2809 virt_dev = xhci->devs[udev->slot_id];
2811 command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
2815 command->in_ctx = virt_dev->in_ctx;
2817 /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
2818 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2820 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2823 goto command_cleanup;
2825 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2826 ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
2827 ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
2829 /* Don't issue the command if there's no endpoints to update. */
2830 if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2831 ctrl_ctx->drop_flags == 0) {
2833 goto command_cleanup;
2835 /* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
2836 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2837 for (i = 31; i >= 1; i--) {
2838 __le32 le32 = cpu_to_le32(BIT(i));
2840 if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
2841 || (ctrl_ctx->add_flags & le32) || i == 1) {
2842 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2843 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
2848 ret = xhci_configure_endpoint(xhci, udev, command,
2851 /* Callee should call reset_bandwidth() */
2852 goto command_cleanup;
2854 /* Free any rings that were dropped, but not changed. */
2855 for (i = 1; i < 31; i++) {
2856 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2857 !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
2858 xhci_free_endpoint_ring(xhci, virt_dev, i);
2859 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2862 xhci_zero_in_ctx(xhci, virt_dev);
2864 * Install any rings for completely new endpoints or changed endpoints,
2865 * and free any old rings from changed endpoints.
2867 for (i = 1; i < 31; i++) {
2868 if (!virt_dev->eps[i].new_ring)
2870 /* Only free the old ring if it exists.
2871 * It may not if this is the first add of an endpoint.
2873 if (virt_dev->eps[i].ring) {
2874 xhci_free_endpoint_ring(xhci, virt_dev, i);
2876 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2877 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
2878 virt_dev->eps[i].new_ring = NULL;
2881 kfree(command->completion);
2887 static void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2889 struct xhci_hcd *xhci;
2890 struct xhci_virt_device *virt_dev;
2893 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2896 xhci = hcd_to_xhci(hcd);
2898 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2899 virt_dev = xhci->devs[udev->slot_id];
2900 /* Free any rings allocated for added endpoints */
2901 for (i = 0; i < 31; i++) {
2902 if (virt_dev->eps[i].new_ring) {
2903 xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
2904 virt_dev->eps[i].new_ring = NULL;
2907 xhci_zero_in_ctx(xhci, virt_dev);
2910 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
2911 struct xhci_container_ctx *in_ctx,
2912 struct xhci_container_ctx *out_ctx,
2913 struct xhci_input_control_ctx *ctrl_ctx,
2914 u32 add_flags, u32 drop_flags)
2916 ctrl_ctx->add_flags = cpu_to_le32(add_flags);
2917 ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
2918 xhci_slot_copy(xhci, in_ctx, out_ctx);
2919 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2922 static void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
2923 unsigned int slot_id, unsigned int ep_index,
2924 struct xhci_dequeue_state *deq_state)
2926 struct xhci_input_control_ctx *ctrl_ctx;
2927 struct xhci_container_ctx *in_ctx;
2928 struct xhci_ep_ctx *ep_ctx;
2932 in_ctx = xhci->devs[slot_id]->in_ctx;
2933 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2935 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2940 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
2941 xhci->devs[slot_id]->out_ctx, ep_index);
2942 ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
2943 addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
2944 deq_state->new_deq_ptr);
2946 xhci_warn(xhci, "WARN Cannot submit config ep after "
2947 "reset ep command\n");
2948 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
2949 deq_state->new_deq_seg,
2950 deq_state->new_deq_ptr);
2953 ep_ctx->deq = cpu_to_le64(addr | deq_state->new_cycle_state);
2955 added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
2956 xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
2957 xhci->devs[slot_id]->out_ctx, ctrl_ctx,
2958 added_ctxs, added_ctxs);
2961 void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci, unsigned int ep_index,
2962 unsigned int stream_id, struct xhci_td *td)
2964 struct xhci_dequeue_state deq_state;
2965 struct xhci_virt_ep *ep;
2966 struct usb_device *udev = td->urb->dev;
2968 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2969 "Cleaning up stalled endpoint ring");
2970 ep = &xhci->devs[udev->slot_id]->eps[ep_index];
2971 /* We need to move the HW's dequeue pointer past this TD,
2972 * or it will attempt to resend it on the next doorbell ring.
2974 xhci_find_new_dequeue_state(xhci, udev->slot_id,
2975 ep_index, stream_id, td, &deq_state);
2977 if (!deq_state.new_deq_ptr || !deq_state.new_deq_seg)
2980 /* HW with the reset endpoint quirk will use the saved dequeue state to
2981 * issue a configure endpoint command later.
2983 if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
2984 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
2985 "Queueing new dequeue state");
2986 xhci_queue_new_dequeue_state(xhci, udev->slot_id,
2987 ep_index, &deq_state);
2989 /* Better hope no one uses the input context between now and the
2990 * reset endpoint completion!
2991 * XXX: No idea how this hardware will react when stream rings
2994 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2995 "Setting up input context for "
2996 "configure endpoint command");
2997 xhci_setup_input_ctx_for_quirk(xhci, udev->slot_id,
2998 ep_index, &deq_state);
3002 /* Called when clearing halted device. The core should have sent the control
3003 * message to clear the device halt condition. The host side of the halt should
3004 * already be cleared with a reset endpoint command issued when the STALL tx
3005 * event was received.
3007 * Context: in_interrupt
3010 static void xhci_endpoint_reset(struct usb_hcd *hcd,
3011 struct usb_host_endpoint *ep)
3013 struct xhci_hcd *xhci;
3015 xhci = hcd_to_xhci(hcd);
3018 * We might need to implement the config ep cmd in xhci 4.8.1 note:
3019 * The Reset Endpoint Command may only be issued to endpoints in the
3020 * Halted state. If software wishes reset the Data Toggle or Sequence
3021 * Number of an endpoint that isn't in the Halted state, then software
3022 * may issue a Configure Endpoint Command with the Drop and Add bits set
3023 * for the target endpoint. that is in the Stopped state.
3026 /* For now just print debug to follow the situation */
3027 xhci_dbg(xhci, "Endpoint 0x%x ep reset callback called\n",
3028 ep->desc.bEndpointAddress);
3031 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
3032 struct usb_device *udev, struct usb_host_endpoint *ep,
3033 unsigned int slot_id)
3036 unsigned int ep_index;
3037 unsigned int ep_state;
3041 ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
3043 return ret ? ret : -EINVAL;
3044 if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
3045 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
3046 " descriptor for ep 0x%x does not support streams\n",
3047 ep->desc.bEndpointAddress);
3051 ep_index = xhci_get_endpoint_index(&ep->desc);
3052 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3053 if (ep_state & EP_HAS_STREAMS ||
3054 ep_state & EP_GETTING_STREAMS) {
3055 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
3056 "already has streams set up.\n",
3057 ep->desc.bEndpointAddress);
3058 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
3059 "dynamic stream context array reallocation.\n");
3062 if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
3063 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
3064 "endpoint 0x%x; URBs are pending.\n",
3065 ep->desc.bEndpointAddress);
3071 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
3072 unsigned int *num_streams, unsigned int *num_stream_ctxs)
3074 unsigned int max_streams;
3076 /* The stream context array size must be a power of two */
3077 *num_stream_ctxs = roundup_pow_of_two(*num_streams);
3079 * Find out how many primary stream array entries the host controller
3080 * supports. Later we may use secondary stream arrays (similar to 2nd
3081 * level page entries), but that's an optional feature for xHCI host
3082 * controllers. xHCs must support at least 4 stream IDs.
3084 max_streams = HCC_MAX_PSA(xhci->hcc_params);
3085 if (*num_stream_ctxs > max_streams) {
3086 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
3088 *num_stream_ctxs = max_streams;
3089 *num_streams = max_streams;
3093 /* Returns an error code if one of the endpoint already has streams.
3094 * This does not change any data structures, it only checks and gathers
3097 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
3098 struct usb_device *udev,
3099 struct usb_host_endpoint **eps, unsigned int num_eps,
3100 unsigned int *num_streams, u32 *changed_ep_bitmask)
3102 unsigned int max_streams;
3103 unsigned int endpoint_flag;
3107 for (i = 0; i < num_eps; i++) {
3108 ret = xhci_check_streams_endpoint(xhci, udev,
3109 eps[i], udev->slot_id);
3113 max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
3114 if (max_streams < (*num_streams - 1)) {
3115 xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
3116 eps[i]->desc.bEndpointAddress,
3118 *num_streams = max_streams+1;
3121 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
3122 if (*changed_ep_bitmask & endpoint_flag)
3124 *changed_ep_bitmask |= endpoint_flag;
3129 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
3130 struct usb_device *udev,
3131 struct usb_host_endpoint **eps, unsigned int num_eps)
3133 u32 changed_ep_bitmask = 0;
3134 unsigned int slot_id;
3135 unsigned int ep_index;
3136 unsigned int ep_state;
3139 slot_id = udev->slot_id;
3140 if (!xhci->devs[slot_id])
3143 for (i = 0; i < num_eps; i++) {
3144 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3145 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3146 /* Are streams already being freed for the endpoint? */
3147 if (ep_state & EP_GETTING_NO_STREAMS) {
3148 xhci_warn(xhci, "WARN Can't disable streams for "
3150 "streams are being disabled already\n",
3151 eps[i]->desc.bEndpointAddress);
3154 /* Are there actually any streams to free? */
3155 if (!(ep_state & EP_HAS_STREAMS) &&
3156 !(ep_state & EP_GETTING_STREAMS)) {
3157 xhci_warn(xhci, "WARN Can't disable streams for "
3159 "streams are already disabled!\n",
3160 eps[i]->desc.bEndpointAddress);
3161 xhci_warn(xhci, "WARN xhci_free_streams() called "
3162 "with non-streams endpoint\n");
3165 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
3167 return changed_ep_bitmask;
3171 * The USB device drivers use this function (through the HCD interface in USB
3172 * core) to prepare a set of bulk endpoints to use streams. Streams are used to
3173 * coordinate mass storage command queueing across multiple endpoints (basically
3174 * a stream ID == a task ID).
3176 * Setting up streams involves allocating the same size stream context array
3177 * for each endpoint and issuing a configure endpoint command for all endpoints.
3179 * Don't allow the call to succeed if one endpoint only supports one stream
3180 * (which means it doesn't support streams at all).
3182 * Drivers may get less stream IDs than they asked for, if the host controller
3183 * hardware or endpoints claim they can't support the number of requested
3186 static int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3187 struct usb_host_endpoint **eps, unsigned int num_eps,
3188 unsigned int num_streams, gfp_t mem_flags)
3191 struct xhci_hcd *xhci;
3192 struct xhci_virt_device *vdev;
3193 struct xhci_command *config_cmd;
3194 struct xhci_input_control_ctx *ctrl_ctx;
3195 unsigned int ep_index;
3196 unsigned int num_stream_ctxs;
3197 unsigned int max_packet;
3198 unsigned long flags;
3199 u32 changed_ep_bitmask = 0;
3204 /* Add one to the number of streams requested to account for
3205 * stream 0 that is reserved for xHCI usage.
3208 xhci = hcd_to_xhci(hcd);
3209 xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3212 /* MaxPSASize value 0 (2 streams) means streams are not supported */
3213 if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
3214 HCC_MAX_PSA(xhci->hcc_params) < 4) {
3215 xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3219 config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
3223 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
3225 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3227 xhci_free_command(xhci, config_cmd);
3231 /* Check to make sure all endpoints are not already configured for
3232 * streams. While we're at it, find the maximum number of streams that
3233 * all the endpoints will support and check for duplicate endpoints.
3235 spin_lock_irqsave(&xhci->lock, flags);
3236 ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3237 num_eps, &num_streams, &changed_ep_bitmask);
3239 xhci_free_command(xhci, config_cmd);
3240 spin_unlock_irqrestore(&xhci->lock, flags);
3243 if (num_streams <= 1) {
3244 xhci_warn(xhci, "WARN: endpoints can't handle "
3245 "more than one stream.\n");
3246 xhci_free_command(xhci, config_cmd);
3247 spin_unlock_irqrestore(&xhci->lock, flags);
3250 vdev = xhci->devs[udev->slot_id];
3251 /* Mark each endpoint as being in transition, so
3252 * xhci_urb_enqueue() will reject all URBs.
3254 for (i = 0; i < num_eps; i++) {
3255 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3256 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3258 spin_unlock_irqrestore(&xhci->lock, flags);
3260 /* Setup internal data structures and allocate HW data structures for
3261 * streams (but don't install the HW structures in the input context
3262 * until we're sure all memory allocation succeeded).
3264 xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3265 xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3266 num_stream_ctxs, num_streams);
3268 for (i = 0; i < num_eps; i++) {
3269 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3270 max_packet = usb_endpoint_maxp(&eps[i]->desc);
3271 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3274 max_packet, mem_flags);
3275 if (!vdev->eps[ep_index].stream_info)
3277 /* Set maxPstreams in endpoint context and update deq ptr to
3278 * point to stream context array. FIXME
3282 /* Set up the input context for a configure endpoint command. */
3283 for (i = 0; i < num_eps; i++) {
3284 struct xhci_ep_ctx *ep_ctx;
3286 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3287 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3289 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3290 vdev->out_ctx, ep_index);
3291 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3292 vdev->eps[ep_index].stream_info);
3294 /* Tell the HW to drop its old copy of the endpoint context info
3295 * and add the updated copy from the input context.
3297 xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3298 vdev->out_ctx, ctrl_ctx,
3299 changed_ep_bitmask, changed_ep_bitmask);
3301 /* Issue and wait for the configure endpoint command */
3302 ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3305 /* xHC rejected the configure endpoint command for some reason, so we
3306 * leave the old ring intact and free our internal streams data
3312 spin_lock_irqsave(&xhci->lock, flags);
3313 for (i = 0; i < num_eps; i++) {
3314 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3315 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3316 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3317 udev->slot_id, ep_index);
3318 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3320 xhci_free_command(xhci, config_cmd);
3321 spin_unlock_irqrestore(&xhci->lock, flags);
3323 /* Subtract 1 for stream 0, which drivers can't use */
3324 return num_streams - 1;
3327 /* If it didn't work, free the streams! */
3328 for (i = 0; i < num_eps; i++) {
3329 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3330 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3331 vdev->eps[ep_index].stream_info = NULL;
3332 /* FIXME Unset maxPstreams in endpoint context and
3333 * update deq ptr to point to normal string ring.
3335 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3336 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3337 xhci_endpoint_zero(xhci, vdev, eps[i]);
3339 xhci_free_command(xhci, config_cmd);
3343 /* Transition the endpoint from using streams to being a "normal" endpoint
3346 * Modify the endpoint context state, submit a configure endpoint command,
3347 * and free all endpoint rings for streams if that completes successfully.
3349 static int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3350 struct usb_host_endpoint **eps, unsigned int num_eps,
3354 struct xhci_hcd *xhci;
3355 struct xhci_virt_device *vdev;
3356 struct xhci_command *command;
3357 struct xhci_input_control_ctx *ctrl_ctx;
3358 unsigned int ep_index;
3359 unsigned long flags;
3360 u32 changed_ep_bitmask;
3362 xhci = hcd_to_xhci(hcd);
3363 vdev = xhci->devs[udev->slot_id];
3365 /* Set up a configure endpoint command to remove the streams rings */
3366 spin_lock_irqsave(&xhci->lock, flags);
3367 changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3368 udev, eps, num_eps);
3369 if (changed_ep_bitmask == 0) {
3370 spin_unlock_irqrestore(&xhci->lock, flags);
3374 /* Use the xhci_command structure from the first endpoint. We may have
3375 * allocated too many, but the driver may call xhci_free_streams() for
3376 * each endpoint it grouped into one call to xhci_alloc_streams().
3378 ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3379 command = vdev->eps[ep_index].stream_info->free_streams_command;
3380 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3382 spin_unlock_irqrestore(&xhci->lock, flags);
3383 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3388 for (i = 0; i < num_eps; i++) {
3389 struct xhci_ep_ctx *ep_ctx;
3391 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3392 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3393 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3394 EP_GETTING_NO_STREAMS;
3396 xhci_endpoint_copy(xhci, command->in_ctx,
3397 vdev->out_ctx, ep_index);
3398 xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3399 &vdev->eps[ep_index]);
3401 xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3402 vdev->out_ctx, ctrl_ctx,
3403 changed_ep_bitmask, changed_ep_bitmask);
3404 spin_unlock_irqrestore(&xhci->lock, flags);
3406 /* Issue and wait for the configure endpoint command,
3407 * which must succeed.
3409 ret = xhci_configure_endpoint(xhci, udev, command,
3412 /* xHC rejected the configure endpoint command for some reason, so we
3413 * leave the streams rings intact.
3418 spin_lock_irqsave(&xhci->lock, flags);
3419 for (i = 0; i < num_eps; i++) {
3420 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3421 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3422 vdev->eps[ep_index].stream_info = NULL;
3423 /* FIXME Unset maxPstreams in endpoint context and
3424 * update deq ptr to point to normal string ring.
3426 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3427 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3429 spin_unlock_irqrestore(&xhci->lock, flags);
3435 * Deletes endpoint resources for endpoints that were active before a Reset
3436 * Device command, or a Disable Slot command. The Reset Device command leaves
3437 * the control endpoint intact, whereas the Disable Slot command deletes it.
3439 * Must be called with xhci->lock held.
3441 void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3442 struct xhci_virt_device *virt_dev, bool drop_control_ep)
3445 unsigned int num_dropped_eps = 0;
3446 unsigned int drop_flags = 0;
3448 for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3449 if (virt_dev->eps[i].ring) {
3450 drop_flags |= 1 << i;
3454 xhci->num_active_eps -= num_dropped_eps;
3455 if (num_dropped_eps)
3456 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3457 "Dropped %u ep ctxs, flags = 0x%x, "
3459 num_dropped_eps, drop_flags,
3460 xhci->num_active_eps);
3464 * This submits a Reset Device Command, which will set the device state to 0,
3465 * set the device address to 0, and disable all the endpoints except the default
3466 * control endpoint. The USB core should come back and call
3467 * xhci_address_device(), and then re-set up the configuration. If this is
3468 * called because of a usb_reset_and_verify_device(), then the old alternate
3469 * settings will be re-installed through the normal bandwidth allocation
3472 * Wait for the Reset Device command to finish. Remove all structures
3473 * associated with the endpoints that were disabled. Clear the input device
3474 * structure? Reset the control endpoint 0 max packet size?
3476 * If the virt_dev to be reset does not exist or does not match the udev,
3477 * it means the device is lost, possibly due to the xHC restore error and
3478 * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3479 * re-allocate the device.
3481 static int xhci_discover_or_reset_device(struct usb_hcd *hcd,
3482 struct usb_device *udev)
3485 unsigned long flags;
3486 struct xhci_hcd *xhci;
3487 unsigned int slot_id;
3488 struct xhci_virt_device *virt_dev;
3489 struct xhci_command *reset_device_cmd;
3490 int last_freed_endpoint;
3491 struct xhci_slot_ctx *slot_ctx;
3492 int old_active_eps = 0;
3494 ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3497 xhci = hcd_to_xhci(hcd);
3498 slot_id = udev->slot_id;
3499 virt_dev = xhci->devs[slot_id];
3501 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3502 "not exist. Re-allocate the device\n", slot_id);
3503 ret = xhci_alloc_dev(hcd, udev);
3510 if (virt_dev->tt_info)
3511 old_active_eps = virt_dev->tt_info->active_eps;
3513 if (virt_dev->udev != udev) {
3514 /* If the virt_dev and the udev does not match, this virt_dev
3515 * may belong to another udev.
3516 * Re-allocate the device.
3518 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3519 "not match the udev. Re-allocate the device\n",
3521 ret = xhci_alloc_dev(hcd, udev);
3528 /* If device is not setup, there is no point in resetting it */
3529 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3530 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3531 SLOT_STATE_DISABLED)
3534 trace_xhci_discover_or_reset_device(slot_ctx);
3536 xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3537 /* Allocate the command structure that holds the struct completion.
3538 * Assume we're in process context, since the normal device reset
3539 * process has to wait for the device anyway. Storage devices are
3540 * reset as part of error handling, so use GFP_NOIO instead of
3543 reset_device_cmd = xhci_alloc_command(xhci, false, true, GFP_NOIO);
3544 if (!reset_device_cmd) {
3545 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3549 /* Attempt to submit the Reset Device command to the command ring */
3550 spin_lock_irqsave(&xhci->lock, flags);
3552 ret = xhci_queue_reset_device(xhci, reset_device_cmd, slot_id);
3554 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3555 spin_unlock_irqrestore(&xhci->lock, flags);
3556 goto command_cleanup;
3558 xhci_ring_cmd_db(xhci);
3559 spin_unlock_irqrestore(&xhci->lock, flags);
3561 /* Wait for the Reset Device command to finish */
3562 wait_for_completion(reset_device_cmd->completion);
3564 /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3565 * unless we tried to reset a slot ID that wasn't enabled,
3566 * or the device wasn't in the addressed or configured state.
3568 ret = reset_device_cmd->status;
3570 case COMP_COMMAND_ABORTED:
3571 case COMP_COMMAND_RING_STOPPED:
3572 xhci_warn(xhci, "Timeout waiting for reset device command\n");
3574 goto command_cleanup;
3575 case COMP_SLOT_NOT_ENABLED_ERROR: /* 0.95 completion for bad slot ID */
3576 case COMP_CONTEXT_STATE_ERROR: /* 0.96 completion code for same thing */
3577 xhci_dbg(xhci, "Can't reset device (slot ID %u) in %s state\n",
3579 xhci_get_slot_state(xhci, virt_dev->out_ctx));
3580 xhci_dbg(xhci, "Not freeing device rings.\n");
3581 /* Don't treat this as an error. May change my mind later. */
3583 goto command_cleanup;
3585 xhci_dbg(xhci, "Successful reset device command.\n");
3588 if (xhci_is_vendor_info_code(xhci, ret))
3590 xhci_warn(xhci, "Unknown completion code %u for "
3591 "reset device command.\n", ret);
3593 goto command_cleanup;
3596 /* Free up host controller endpoint resources */
3597 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3598 spin_lock_irqsave(&xhci->lock, flags);
3599 /* Don't delete the default control endpoint resources */
3600 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
3601 spin_unlock_irqrestore(&xhci->lock, flags);
3604 /* Everything but endpoint 0 is disabled, so free the rings. */
3605 last_freed_endpoint = 1;
3606 for (i = 1; i < 31; i++) {
3607 struct xhci_virt_ep *ep = &virt_dev->eps[i];
3609 if (ep->ep_state & EP_HAS_STREAMS) {
3610 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
3611 xhci_get_endpoint_address(i));
3612 xhci_free_stream_info(xhci, ep->stream_info);
3613 ep->stream_info = NULL;
3614 ep->ep_state &= ~EP_HAS_STREAMS;
3618 xhci_free_endpoint_ring(xhci, virt_dev, i);
3619 last_freed_endpoint = i;
3621 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
3622 xhci_drop_ep_from_interval_table(xhci,
3623 &virt_dev->eps[i].bw_info,
3628 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
3630 /* If necessary, update the number of active TTs on this root port */
3631 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
3635 xhci_free_command(xhci, reset_device_cmd);
3640 * At this point, the struct usb_device is about to go away, the device has
3641 * disconnected, and all traffic has been stopped and the endpoints have been
3642 * disabled. Free any HC data structures associated with that device.
3644 static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3646 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3647 struct xhci_virt_device *virt_dev;
3648 struct xhci_slot_ctx *slot_ctx;
3652 * We called pm_runtime_get_noresume when the device was attached.
3653 * Decrement the counter here to allow controller to runtime suspend
3654 * if no devices remain.
3656 if (xhci->quirks & XHCI_RESET_ON_RESUME)
3657 pm_runtime_put_noidle(hcd->self.controller);
3659 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3660 /* If the host is halted due to driver unload, we still need to free the
3663 if (ret <= 0 && ret != -ENODEV)
3666 virt_dev = xhci->devs[udev->slot_id];
3667 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3668 trace_xhci_free_dev(slot_ctx);
3670 /* Stop any wayward timer functions (which may grab the lock) */
3671 for (i = 0; i < 31; i++) {
3672 virt_dev->eps[i].ep_state &= ~EP_STOP_CMD_PENDING;
3673 del_timer_sync(&virt_dev->eps[i].stop_cmd_timer);
3676 virt_dev->udev = NULL;
3677 xhci_disable_slot(xhci, udev->slot_id);
3679 * Event command completion handler will free any data structures
3680 * associated with the slot. XXX Can free sleep?
3684 int xhci_disable_slot(struct xhci_hcd *xhci, u32 slot_id)
3686 struct xhci_command *command;
3687 unsigned long flags;
3691 command = xhci_alloc_command(xhci, false, false, GFP_KERNEL);
3695 spin_lock_irqsave(&xhci->lock, flags);
3696 /* Don't disable the slot if the host controller is dead. */
3697 state = readl(&xhci->op_regs->status);
3698 if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
3699 (xhci->xhc_state & XHCI_STATE_HALTED)) {
3700 spin_unlock_irqrestore(&xhci->lock, flags);
3705 ret = xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
3708 spin_unlock_irqrestore(&xhci->lock, flags);
3712 xhci_ring_cmd_db(xhci);
3713 spin_unlock_irqrestore(&xhci->lock, flags);
3718 * Checks if we have enough host controller resources for the default control
3721 * Must be called with xhci->lock held.
3723 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
3725 if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
3726 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3727 "Not enough ep ctxs: "
3728 "%u active, need to add 1, limit is %u.",
3729 xhci->num_active_eps, xhci->limit_active_eps);
3732 xhci->num_active_eps += 1;
3733 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3734 "Adding 1 ep ctx, %u now active.",
3735 xhci->num_active_eps);
3741 * Returns 0 if the xHC ran out of device slots, the Enable Slot command
3742 * timed out, or allocating memory failed. Returns 1 on success.
3744 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
3746 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3747 struct xhci_virt_device *vdev;
3748 struct xhci_slot_ctx *slot_ctx;
3749 unsigned long flags;
3751 struct xhci_command *command;
3753 command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
3757 /* xhci->slot_id and xhci->addr_dev are not thread-safe */
3758 mutex_lock(&xhci->mutex);
3759 spin_lock_irqsave(&xhci->lock, flags);
3760 ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
3762 spin_unlock_irqrestore(&xhci->lock, flags);
3763 mutex_unlock(&xhci->mutex);
3764 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3765 xhci_free_command(xhci, command);
3768 xhci_ring_cmd_db(xhci);
3769 spin_unlock_irqrestore(&xhci->lock, flags);
3771 wait_for_completion(command->completion);
3772 slot_id = command->slot_id;
3773 mutex_unlock(&xhci->mutex);
3775 if (!slot_id || command->status != COMP_SUCCESS) {
3776 xhci_err(xhci, "Error while assigning device slot ID\n");
3777 xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
3779 readl(&xhci->cap_regs->hcs_params1)));
3780 xhci_free_command(xhci, command);
3784 xhci_free_command(xhci, command);
3786 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3787 spin_lock_irqsave(&xhci->lock, flags);
3788 ret = xhci_reserve_host_control_ep_resources(xhci);
3790 spin_unlock_irqrestore(&xhci->lock, flags);
3791 xhci_warn(xhci, "Not enough host resources, "
3792 "active endpoint contexts = %u\n",
3793 xhci->num_active_eps);
3796 spin_unlock_irqrestore(&xhci->lock, flags);
3798 /* Use GFP_NOIO, since this function can be called from
3799 * xhci_discover_or_reset_device(), which may be called as part of
3800 * mass storage driver error handling.
3802 if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) {
3803 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
3806 vdev = xhci->devs[slot_id];
3807 slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
3808 trace_xhci_alloc_dev(slot_ctx);
3810 udev->slot_id = slot_id;
3813 * If resetting upon resume, we can't put the controller into runtime
3814 * suspend if there is a device attached.
3816 if (xhci->quirks & XHCI_RESET_ON_RESUME)
3817 pm_runtime_get_noresume(hcd->self.controller);
3819 /* Is this a LS or FS device under a HS hub? */
3820 /* Hub or peripherial? */
3824 return xhci_disable_slot(xhci, udev->slot_id);
3828 * Issue an Address Device command and optionally send a corresponding
3829 * SetAddress request to the device.
3831 static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
3832 enum xhci_setup_dev setup)
3834 const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
3835 unsigned long flags;
3836 struct xhci_virt_device *virt_dev;
3838 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3839 struct xhci_slot_ctx *slot_ctx;
3840 struct xhci_input_control_ctx *ctrl_ctx;
3842 struct xhci_command *command = NULL;
3844 mutex_lock(&xhci->mutex);
3846 if (xhci->xhc_state) { /* dying, removing or halted */
3851 if (!udev->slot_id) {
3852 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3853 "Bad Slot ID %d", udev->slot_id);
3858 virt_dev = xhci->devs[udev->slot_id];
3860 if (WARN_ON(!virt_dev)) {
3862 * In plug/unplug torture test with an NEC controller,
3863 * a zero-dereference was observed once due to virt_dev = 0.
3864 * Print useful debug rather than crash if it is observed again!
3866 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
3871 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3872 trace_xhci_setup_device_slot(slot_ctx);
3874 if (setup == SETUP_CONTEXT_ONLY) {
3875 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3876 SLOT_STATE_DEFAULT) {
3877 xhci_dbg(xhci, "Slot already in default state\n");
3882 command = xhci_alloc_command(xhci, false, true, GFP_KERNEL);
3888 command->in_ctx = virt_dev->in_ctx;
3890 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
3891 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
3893 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3899 * If this is the first Set Address since device plug-in or
3900 * virt_device realloaction after a resume with an xHCI power loss,
3901 * then set up the slot context.
3903 if (!slot_ctx->dev_info)
3904 xhci_setup_addressable_virt_dev(xhci, udev);
3905 /* Otherwise, update the control endpoint ring enqueue pointer. */
3907 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
3908 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
3909 ctrl_ctx->drop_flags = 0;
3911 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
3912 le32_to_cpu(slot_ctx->dev_info) >> 27);
3914 spin_lock_irqsave(&xhci->lock, flags);
3915 trace_xhci_setup_device(virt_dev);
3916 ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
3917 udev->slot_id, setup);
3919 spin_unlock_irqrestore(&xhci->lock, flags);
3920 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3921 "FIXME: allocate a command ring segment");
3924 xhci_ring_cmd_db(xhci);
3925 spin_unlock_irqrestore(&xhci->lock, flags);
3927 /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
3928 wait_for_completion(command->completion);
3930 /* FIXME: From section 4.3.4: "Software shall be responsible for timing
3931 * the SetAddress() "recovery interval" required by USB and aborting the
3932 * command on a timeout.
3934 switch (command->status) {
3935 case COMP_COMMAND_ABORTED:
3936 case COMP_COMMAND_RING_STOPPED:
3937 xhci_warn(xhci, "Timeout while waiting for setup device command\n");
3940 case COMP_CONTEXT_STATE_ERROR:
3941 case COMP_SLOT_NOT_ENABLED_ERROR:
3942 xhci_err(xhci, "Setup ERROR: setup %s command for slot %d.\n",
3943 act, udev->slot_id);
3946 case COMP_USB_TRANSACTION_ERROR:
3947 dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
3950 case COMP_INCOMPATIBLE_DEVICE_ERROR:
3951 dev_warn(&udev->dev,
3952 "ERROR: Incompatible device for setup %s command\n", act);
3956 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3957 "Successful setup %s command", act);
3961 "ERROR: unexpected setup %s command completion code 0x%x.\n",
3962 act, command->status);
3963 trace_xhci_address_ctx(xhci, virt_dev->out_ctx, 1);
3969 temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
3970 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3971 "Op regs DCBAA ptr = %#016llx", temp_64);
3972 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3973 "Slot ID %d dcbaa entry @%p = %#016llx",
3975 &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
3976 (unsigned long long)
3977 le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
3978 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3979 "Output Context DMA address = %#08llx",
3980 (unsigned long long)virt_dev->out_ctx->dma);
3981 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
3982 le32_to_cpu(slot_ctx->dev_info) >> 27);
3984 * USB core uses address 1 for the roothubs, so we add one to the
3985 * address given back to us by the HC.
3987 trace_xhci_address_ctx(xhci, virt_dev->out_ctx,
3988 le32_to_cpu(slot_ctx->dev_info) >> 27);
3989 /* Zero the input context control for later use */
3990 ctrl_ctx->add_flags = 0;
3991 ctrl_ctx->drop_flags = 0;
3993 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
3994 "Internal device address = %d",
3995 le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
3997 mutex_unlock(&xhci->mutex);
3999 kfree(command->completion);
4005 static int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev)
4007 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ADDRESS);
4010 static int xhci_enable_device(struct usb_hcd *hcd, struct usb_device *udev)
4012 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ONLY);
4016 * Transfer the port index into real index in the HW port status
4017 * registers. Caculate offset between the port's PORTSC register
4018 * and port status base. Divide the number of per port register
4019 * to get the real index. The raw port number bases 1.
4021 int xhci_find_raw_port_number(struct usb_hcd *hcd, int port1)
4023 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4024 __le32 __iomem *base_addr = &xhci->op_regs->port_status_base;
4025 __le32 __iomem *addr;
4028 if (hcd->speed < HCD_USB3)
4029 addr = xhci->usb2_ports[port1 - 1];
4031 addr = xhci->usb3_ports[port1 - 1];
4033 raw_port = (addr - base_addr)/NUM_PORT_REGS + 1;
4038 * Issue an Evaluate Context command to change the Maximum Exit Latency in the
4039 * slot context. If that succeeds, store the new MEL in the xhci_virt_device.
4041 static int __maybe_unused xhci_change_max_exit_latency(struct xhci_hcd *xhci,
4042 struct usb_device *udev, u16 max_exit_latency)
4044 struct xhci_virt_device *virt_dev;
4045 struct xhci_command *command;
4046 struct xhci_input_control_ctx *ctrl_ctx;
4047 struct xhci_slot_ctx *slot_ctx;
4048 unsigned long flags;
4051 spin_lock_irqsave(&xhci->lock, flags);
4053 virt_dev = xhci->devs[udev->slot_id];
4056 * virt_dev might not exists yet if xHC resumed from hibernate (S4) and
4057 * xHC was re-initialized. Exit latency will be set later after
4058 * hub_port_finish_reset() is done and xhci->devs[] are re-allocated
4061 if (!virt_dev || max_exit_latency == virt_dev->current_mel) {
4062 spin_unlock_irqrestore(&xhci->lock, flags);
4066 /* Attempt to issue an Evaluate Context command to change the MEL. */
4067 command = xhci->lpm_command;
4068 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
4070 spin_unlock_irqrestore(&xhci->lock, flags);
4071 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4076 xhci_slot_copy(xhci, command->in_ctx, virt_dev->out_ctx);
4077 spin_unlock_irqrestore(&xhci->lock, flags);
4079 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4080 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
4081 slot_ctx->dev_info2 &= cpu_to_le32(~((u32) MAX_EXIT));
4082 slot_ctx->dev_info2 |= cpu_to_le32(max_exit_latency);
4083 slot_ctx->dev_state = 0;
4085 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
4086 "Set up evaluate context for LPM MEL change.");
4088 /* Issue and wait for the evaluate context command. */
4089 ret = xhci_configure_endpoint(xhci, udev, command,
4093 spin_lock_irqsave(&xhci->lock, flags);
4094 virt_dev->current_mel = max_exit_latency;
4095 spin_unlock_irqrestore(&xhci->lock, flags);
4102 /* BESL to HIRD Encoding array for USB2 LPM */
4103 static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
4104 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
4106 /* Calculate HIRD/BESL for USB2 PORTPMSC*/
4107 static int xhci_calculate_hird_besl(struct xhci_hcd *xhci,
4108 struct usb_device *udev)
4110 int u2del, besl, besl_host;
4111 int besl_device = 0;
4114 u2del = HCS_U2_LATENCY(xhci->hcs_params3);
4115 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4117 if (field & USB_BESL_SUPPORT) {
4118 for (besl_host = 0; besl_host < 16; besl_host++) {
4119 if (xhci_besl_encoding[besl_host] >= u2del)
4122 /* Use baseline BESL value as default */
4123 if (field & USB_BESL_BASELINE_VALID)
4124 besl_device = USB_GET_BESL_BASELINE(field);
4125 else if (field & USB_BESL_DEEP_VALID)
4126 besl_device = USB_GET_BESL_DEEP(field);
4131 besl_host = (u2del - 51) / 75 + 1;
4134 besl = besl_host + besl_device;
4141 /* Calculate BESLD, L1 timeout and HIRDM for USB2 PORTHLPMC */
4142 static int xhci_calculate_usb2_hw_lpm_params(struct usb_device *udev)
4149 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4151 /* xHCI l1 is set in steps of 256us, xHCI 1.0 section 5.4.11.2 */
4152 l1 = udev->l1_params.timeout / 256;
4154 /* device has preferred BESLD */
4155 if (field & USB_BESL_DEEP_VALID) {
4156 besld = USB_GET_BESL_DEEP(field);
4160 return PORT_BESLD(besld) | PORT_L1_TIMEOUT(l1) | PORT_HIRDM(hirdm);
4163 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4164 struct usb_device *udev, int enable)
4166 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4167 __le32 __iomem **port_array;
4168 __le32 __iomem *pm_addr, *hlpm_addr;
4169 u32 pm_val, hlpm_val, field;
4170 unsigned int port_num;
4171 unsigned long flags;
4172 int hird, exit_latency;
4175 if (hcd->speed >= HCD_USB3 || !xhci->hw_lpm_support ||
4179 if (!udev->parent || udev->parent->parent ||
4180 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4183 if (udev->usb2_hw_lpm_capable != 1)
4186 spin_lock_irqsave(&xhci->lock, flags);
4188 port_array = xhci->usb2_ports;
4189 port_num = udev->portnum - 1;
4190 pm_addr = port_array[port_num] + PORTPMSC;
4191 pm_val = readl(pm_addr);
4192 hlpm_addr = port_array[port_num] + PORTHLPMC;
4194 xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
4195 enable ? "enable" : "disable", port_num + 1);
4198 /* Host supports BESL timeout instead of HIRD */
4199 if (udev->usb2_hw_lpm_besl_capable) {
4200 /* if device doesn't have a preferred BESL value use a
4201 * default one which works with mixed HIRD and BESL
4202 * systems. See XHCI_DEFAULT_BESL definition in xhci.h
4204 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4205 if ((field & USB_BESL_SUPPORT) &&
4206 (field & USB_BESL_BASELINE_VALID))
4207 hird = USB_GET_BESL_BASELINE(field);
4209 hird = udev->l1_params.besl;
4211 exit_latency = xhci_besl_encoding[hird];
4212 spin_unlock_irqrestore(&xhci->lock, flags);
4214 /* USB 3.0 code dedicate one xhci->lpm_command->in_ctx
4215 * input context for link powermanagement evaluate
4216 * context commands. It is protected by hcd->bandwidth
4217 * mutex and is shared by all devices. We need to set
4218 * the max ext latency in USB 2 BESL LPM as well, so
4219 * use the same mutex and xhci_change_max_exit_latency()
4221 mutex_lock(hcd->bandwidth_mutex);
4222 ret = xhci_change_max_exit_latency(xhci, udev,
4224 mutex_unlock(hcd->bandwidth_mutex);
4228 spin_lock_irqsave(&xhci->lock, flags);
4230 hlpm_val = xhci_calculate_usb2_hw_lpm_params(udev);
4231 writel(hlpm_val, hlpm_addr);
4235 hird = xhci_calculate_hird_besl(xhci, udev);
4238 pm_val &= ~PORT_HIRD_MASK;
4239 pm_val |= PORT_HIRD(hird) | PORT_RWE | PORT_L1DS(udev->slot_id);
4240 writel(pm_val, pm_addr);
4241 pm_val = readl(pm_addr);
4243 writel(pm_val, pm_addr);
4247 pm_val &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK | PORT_L1DS_MASK);
4248 writel(pm_val, pm_addr);
4251 if (udev->usb2_hw_lpm_besl_capable) {
4252 spin_unlock_irqrestore(&xhci->lock, flags);
4253 mutex_lock(hcd->bandwidth_mutex);
4254 xhci_change_max_exit_latency(xhci, udev, 0);
4255 mutex_unlock(hcd->bandwidth_mutex);
4256 readl_poll_timeout(port_array[port_num], pm_val,
4257 (pm_val & PORT_PLS_MASK) == XDEV_U0,
4263 spin_unlock_irqrestore(&xhci->lock, flags);
4267 /* check if a usb2 port supports a given extened capability protocol
4268 * only USB2 ports extended protocol capability values are cached.
4269 * Return 1 if capability is supported
4271 static int xhci_check_usb2_port_capability(struct xhci_hcd *xhci, int port,
4272 unsigned capability)
4274 u32 port_offset, port_count;
4277 for (i = 0; i < xhci->num_ext_caps; i++) {
4278 if (xhci->ext_caps[i] & capability) {
4279 /* port offsets starts at 1 */
4280 port_offset = XHCI_EXT_PORT_OFF(xhci->ext_caps[i]) - 1;
4281 port_count = XHCI_EXT_PORT_COUNT(xhci->ext_caps[i]);
4282 if (port >= port_offset &&
4283 port < port_offset + port_count)
4290 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4292 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4293 int portnum = udev->portnum - 1;
4295 if (hcd->speed >= HCD_USB3 || !xhci->sw_lpm_support ||
4299 /* we only support lpm for non-hub device connected to root hub yet */
4300 if (!udev->parent || udev->parent->parent ||
4301 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4304 if (xhci->hw_lpm_support == 1 &&
4305 xhci_check_usb2_port_capability(
4306 xhci, portnum, XHCI_HLC)) {
4307 udev->usb2_hw_lpm_capable = 1;
4308 udev->l1_params.timeout = XHCI_L1_TIMEOUT;
4309 udev->l1_params.besl = XHCI_DEFAULT_BESL;
4310 if (xhci_check_usb2_port_capability(xhci, portnum,
4312 udev->usb2_hw_lpm_besl_capable = 1;
4318 /*---------------------- USB 3.0 Link PM functions ------------------------*/
4320 /* Service interval in nanoseconds = 2^(bInterval - 1) * 125us * 1000ns / 1us */
4321 static unsigned long long xhci_service_interval_to_ns(
4322 struct usb_endpoint_descriptor *desc)
4324 return (1ULL << (desc->bInterval - 1)) * 125 * 1000;
4327 static u16 xhci_get_timeout_no_hub_lpm(struct usb_device *udev,
4328 enum usb3_link_state state)
4330 unsigned long long sel;
4331 unsigned long long pel;
4332 unsigned int max_sel_pel;
4337 /* Convert SEL and PEL stored in nanoseconds to microseconds */
4338 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4339 pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4340 max_sel_pel = USB3_LPM_MAX_U1_SEL_PEL;
4344 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4345 pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4346 max_sel_pel = USB3_LPM_MAX_U2_SEL_PEL;
4350 dev_warn(&udev->dev, "%s: Can't get timeout for non-U1 or U2 state.\n",
4352 return USB3_LPM_DISABLED;
4355 if (sel <= max_sel_pel && pel <= max_sel_pel)
4356 return USB3_LPM_DEVICE_INITIATED;
4358 if (sel > max_sel_pel)
4359 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4360 "due to long SEL %llu ms\n",
4363 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4364 "due to long PEL %llu ms\n",
4366 return USB3_LPM_DISABLED;
4369 /* The U1 timeout should be the maximum of the following values:
4370 * - For control endpoints, U1 system exit latency (SEL) * 3
4371 * - For bulk endpoints, U1 SEL * 5
4372 * - For interrupt endpoints:
4373 * - Notification EPs, U1 SEL * 3
4374 * - Periodic EPs, max(105% of bInterval, U1 SEL * 2)
4375 * - For isochronous endpoints, max(105% of bInterval, U1 SEL * 2)
4377 static unsigned long long xhci_calculate_intel_u1_timeout(
4378 struct usb_device *udev,
4379 struct usb_endpoint_descriptor *desc)
4381 unsigned long long timeout_ns;
4385 ep_type = usb_endpoint_type(desc);
4387 case USB_ENDPOINT_XFER_CONTROL:
4388 timeout_ns = udev->u1_params.sel * 3;
4390 case USB_ENDPOINT_XFER_BULK:
4391 timeout_ns = udev->u1_params.sel * 5;
4393 case USB_ENDPOINT_XFER_INT:
4394 intr_type = usb_endpoint_interrupt_type(desc);
4395 if (intr_type == USB_ENDPOINT_INTR_NOTIFICATION) {
4396 timeout_ns = udev->u1_params.sel * 3;
4399 /* Otherwise the calculation is the same as isoc eps */
4400 case USB_ENDPOINT_XFER_ISOC:
4401 timeout_ns = xhci_service_interval_to_ns(desc);
4402 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns * 105, 100);
4403 if (timeout_ns < udev->u1_params.sel * 2)
4404 timeout_ns = udev->u1_params.sel * 2;
4413 /* Returns the hub-encoded U1 timeout value. */
4414 static u16 xhci_calculate_u1_timeout(struct xhci_hcd *xhci,
4415 struct usb_device *udev,
4416 struct usb_endpoint_descriptor *desc)
4418 unsigned long long timeout_ns;
4420 /* Prevent U1 if service interval is shorter than U1 exit latency */
4421 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4422 if (xhci_service_interval_to_ns(desc) <= udev->u1_params.mel) {
4423 dev_dbg(&udev->dev, "Disable U1, ESIT shorter than exit latency\n");
4424 return USB3_LPM_DISABLED;
4428 if (xhci->quirks & XHCI_INTEL_HOST)
4429 timeout_ns = xhci_calculate_intel_u1_timeout(udev, desc);
4431 timeout_ns = udev->u1_params.sel;
4433 /* The U1 timeout is encoded in 1us intervals.
4434 * Don't return a timeout of zero, because that's USB3_LPM_DISABLED.
4436 if (timeout_ns == USB3_LPM_DISABLED)
4439 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 1000);
4441 /* If the necessary timeout value is bigger than what we can set in the
4442 * USB 3.0 hub, we have to disable hub-initiated U1.
4444 if (timeout_ns <= USB3_LPM_U1_MAX_TIMEOUT)
4446 dev_dbg(&udev->dev, "Hub-initiated U1 disabled "
4447 "due to long timeout %llu ms\n", timeout_ns);
4448 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U1);
4451 /* The U2 timeout should be the maximum of:
4452 * - 10 ms (to avoid the bandwidth impact on the scheduler)
4453 * - largest bInterval of any active periodic endpoint (to avoid going
4454 * into lower power link states between intervals).
4455 * - the U2 Exit Latency of the device
4457 static unsigned long long xhci_calculate_intel_u2_timeout(
4458 struct usb_device *udev,
4459 struct usb_endpoint_descriptor *desc)
4461 unsigned long long timeout_ns;
4462 unsigned long long u2_del_ns;
4464 timeout_ns = 10 * 1000 * 1000;
4466 if ((usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) &&
4467 (xhci_service_interval_to_ns(desc) > timeout_ns))
4468 timeout_ns = xhci_service_interval_to_ns(desc);
4470 u2_del_ns = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat) * 1000ULL;
4471 if (u2_del_ns > timeout_ns)
4472 timeout_ns = u2_del_ns;
4477 /* Returns the hub-encoded U2 timeout value. */
4478 static u16 xhci_calculate_u2_timeout(struct xhci_hcd *xhci,
4479 struct usb_device *udev,
4480 struct usb_endpoint_descriptor *desc)
4482 unsigned long long timeout_ns;
4484 /* Prevent U2 if service interval is shorter than U2 exit latency */
4485 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4486 if (xhci_service_interval_to_ns(desc) <= udev->u2_params.mel) {
4487 dev_dbg(&udev->dev, "Disable U2, ESIT shorter than exit latency\n");
4488 return USB3_LPM_DISABLED;
4492 if (xhci->quirks & XHCI_INTEL_HOST)
4493 timeout_ns = xhci_calculate_intel_u2_timeout(udev, desc);
4495 timeout_ns = udev->u2_params.sel;
4497 /* The U2 timeout is encoded in 256us intervals */
4498 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 256 * 1000);
4499 /* If the necessary timeout value is bigger than what we can set in the
4500 * USB 3.0 hub, we have to disable hub-initiated U2.
4502 if (timeout_ns <= USB3_LPM_U2_MAX_TIMEOUT)
4504 dev_dbg(&udev->dev, "Hub-initiated U2 disabled "
4505 "due to long timeout %llu ms\n", timeout_ns);
4506 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U2);
4509 static u16 xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4510 struct usb_device *udev,
4511 struct usb_endpoint_descriptor *desc,
4512 enum usb3_link_state state,
4515 if (state == USB3_LPM_U1)
4516 return xhci_calculate_u1_timeout(xhci, udev, desc);
4517 else if (state == USB3_LPM_U2)
4518 return xhci_calculate_u2_timeout(xhci, udev, desc);
4520 return USB3_LPM_DISABLED;
4523 static int xhci_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4524 struct usb_device *udev,
4525 struct usb_endpoint_descriptor *desc,
4526 enum usb3_link_state state,
4531 alt_timeout = xhci_call_host_update_timeout_for_endpoint(xhci, udev,
4532 desc, state, timeout);
4534 /* If we found we can't enable hub-initiated LPM, and
4535 * the U1 or U2 exit latency was too high to allow
4536 * device-initiated LPM as well, then we will disable LPM
4537 * for this device, so stop searching any further.
4539 if (alt_timeout == USB3_LPM_DISABLED) {
4540 *timeout = alt_timeout;
4543 if (alt_timeout > *timeout)
4544 *timeout = alt_timeout;
4548 static int xhci_update_timeout_for_interface(struct xhci_hcd *xhci,
4549 struct usb_device *udev,
4550 struct usb_host_interface *alt,
4551 enum usb3_link_state state,
4556 for (j = 0; j < alt->desc.bNumEndpoints; j++) {
4557 if (xhci_update_timeout_for_endpoint(xhci, udev,
4558 &alt->endpoint[j].desc, state, timeout))
4565 static int xhci_check_intel_tier_policy(struct usb_device *udev,
4566 enum usb3_link_state state)
4568 struct usb_device *parent;
4569 unsigned int num_hubs;
4571 if (state == USB3_LPM_U2)
4574 /* Don't enable U1 if the device is on a 2nd tier hub or lower. */
4575 for (parent = udev->parent, num_hubs = 0; parent->parent;
4576 parent = parent->parent)
4582 dev_dbg(&udev->dev, "Disabling U1 link state for device"
4583 " below second-tier hub.\n");
4584 dev_dbg(&udev->dev, "Plug device into first-tier hub "
4585 "to decrease power consumption.\n");
4589 static int xhci_check_tier_policy(struct xhci_hcd *xhci,
4590 struct usb_device *udev,
4591 enum usb3_link_state state)
4593 if (xhci->quirks & XHCI_INTEL_HOST)
4594 return xhci_check_intel_tier_policy(udev, state);
4599 /* Returns the U1 or U2 timeout that should be enabled.
4600 * If the tier check or timeout setting functions return with a non-zero exit
4601 * code, that means the timeout value has been finalized and we shouldn't look
4602 * at any more endpoints.
4604 static u16 xhci_calculate_lpm_timeout(struct usb_hcd *hcd,
4605 struct usb_device *udev, enum usb3_link_state state)
4607 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4608 struct usb_host_config *config;
4611 u16 timeout = USB3_LPM_DISABLED;
4613 if (state == USB3_LPM_U1)
4615 else if (state == USB3_LPM_U2)
4618 dev_warn(&udev->dev, "Can't enable unknown link state %i\n",
4623 if (xhci_check_tier_policy(xhci, udev, state) < 0)
4626 /* Gather some information about the currently installed configuration
4627 * and alternate interface settings.
4629 if (xhci_update_timeout_for_endpoint(xhci, udev, &udev->ep0.desc,
4633 config = udev->actconfig;
4637 for (i = 0; i < config->desc.bNumInterfaces; i++) {
4638 struct usb_driver *driver;
4639 struct usb_interface *intf = config->interface[i];
4644 /* Check if any currently bound drivers want hub-initiated LPM
4647 if (intf->dev.driver) {
4648 driver = to_usb_driver(intf->dev.driver);
4649 if (driver && driver->disable_hub_initiated_lpm) {
4650 dev_dbg(&udev->dev, "Hub-initiated %s disabled at request of driver %s\n",
4651 state_name, driver->name);
4652 timeout = xhci_get_timeout_no_hub_lpm(udev,
4654 if (timeout == USB3_LPM_DISABLED)
4659 /* Not sure how this could happen... */
4660 if (!intf->cur_altsetting)
4663 if (xhci_update_timeout_for_interface(xhci, udev,
4664 intf->cur_altsetting,
4671 static int calculate_max_exit_latency(struct usb_device *udev,
4672 enum usb3_link_state state_changed,
4673 u16 hub_encoded_timeout)
4675 unsigned long long u1_mel_us = 0;
4676 unsigned long long u2_mel_us = 0;
4677 unsigned long long mel_us = 0;
4683 disabling_u1 = (state_changed == USB3_LPM_U1 &&
4684 hub_encoded_timeout == USB3_LPM_DISABLED);
4685 disabling_u2 = (state_changed == USB3_LPM_U2 &&
4686 hub_encoded_timeout == USB3_LPM_DISABLED);
4688 enabling_u1 = (state_changed == USB3_LPM_U1 &&
4689 hub_encoded_timeout != USB3_LPM_DISABLED);
4690 enabling_u2 = (state_changed == USB3_LPM_U2 &&
4691 hub_encoded_timeout != USB3_LPM_DISABLED);
4693 /* If U1 was already enabled and we're not disabling it,
4694 * or we're going to enable U1, account for the U1 max exit latency.
4696 if ((udev->u1_params.timeout != USB3_LPM_DISABLED && !disabling_u1) ||
4698 u1_mel_us = DIV_ROUND_UP(udev->u1_params.mel, 1000);
4699 if ((udev->u2_params.timeout != USB3_LPM_DISABLED && !disabling_u2) ||
4701 u2_mel_us = DIV_ROUND_UP(udev->u2_params.mel, 1000);
4703 if (u1_mel_us > u2_mel_us)
4707 /* xHCI host controller max exit latency field is only 16 bits wide. */
4708 if (mel_us > MAX_EXIT) {
4709 dev_warn(&udev->dev, "Link PM max exit latency of %lluus "
4710 "is too big.\n", mel_us);
4716 /* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
4717 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
4718 struct usb_device *udev, enum usb3_link_state state)
4720 struct xhci_hcd *xhci;
4721 u16 hub_encoded_timeout;
4725 xhci = hcd_to_xhci(hcd);
4726 /* The LPM timeout values are pretty host-controller specific, so don't
4727 * enable hub-initiated timeouts unless the vendor has provided
4728 * information about their timeout algorithm.
4730 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
4731 !xhci->devs[udev->slot_id])
4732 return USB3_LPM_DISABLED;
4734 hub_encoded_timeout = xhci_calculate_lpm_timeout(hcd, udev, state);
4735 mel = calculate_max_exit_latency(udev, state, hub_encoded_timeout);
4737 /* Max Exit Latency is too big, disable LPM. */
4738 hub_encoded_timeout = USB3_LPM_DISABLED;
4742 ret = xhci_change_max_exit_latency(xhci, udev, mel);
4745 return hub_encoded_timeout;
4748 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
4749 struct usb_device *udev, enum usb3_link_state state)
4751 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 return xhci_change_max_exit_latency(xhci, udev, mel);
4762 #else /* CONFIG_PM */
4764 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4765 struct usb_device *udev, int enable)
4770 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4775 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
4776 struct usb_device *udev, enum usb3_link_state state)
4778 return USB3_LPM_DISABLED;
4781 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
4782 struct usb_device *udev, enum usb3_link_state state)
4786 #endif /* CONFIG_PM */
4788 /*-------------------------------------------------------------------------*/
4790 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
4791 * internal data structures for the device.
4793 static int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
4794 struct usb_tt *tt, gfp_t mem_flags)
4796 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4797 struct xhci_virt_device *vdev;
4798 struct xhci_command *config_cmd;
4799 struct xhci_input_control_ctx *ctrl_ctx;
4800 struct xhci_slot_ctx *slot_ctx;
4801 unsigned long flags;
4802 unsigned think_time;
4805 /* Ignore root hubs */
4809 vdev = xhci->devs[hdev->slot_id];
4811 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
4815 config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
4819 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
4821 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4823 xhci_free_command(xhci, config_cmd);
4827 spin_lock_irqsave(&xhci->lock, flags);
4828 if (hdev->speed == USB_SPEED_HIGH &&
4829 xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
4830 xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
4831 xhci_free_command(xhci, config_cmd);
4832 spin_unlock_irqrestore(&xhci->lock, flags);
4836 xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
4837 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4838 slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
4839 slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
4841 * refer to section 6.2.2: MTT should be 0 for full speed hub,
4842 * but it may be already set to 1 when setup an xHCI virtual
4843 * device, so clear it anyway.
4846 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
4847 else if (hdev->speed == USB_SPEED_FULL)
4848 slot_ctx->dev_info &= cpu_to_le32(~DEV_MTT);
4850 if (xhci->hci_version > 0x95) {
4851 xhci_dbg(xhci, "xHCI version %x needs hub "
4852 "TT think time and number of ports\n",
4853 (unsigned int) xhci->hci_version);
4854 slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
4855 /* Set TT think time - convert from ns to FS bit times.
4856 * 0 = 8 FS bit times, 1 = 16 FS bit times,
4857 * 2 = 24 FS bit times, 3 = 32 FS bit times.
4859 * xHCI 1.0: this field shall be 0 if the device is not a
4862 think_time = tt->think_time;
4863 if (think_time != 0)
4864 think_time = (think_time / 666) - 1;
4865 if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
4866 slot_ctx->tt_info |=
4867 cpu_to_le32(TT_THINK_TIME(think_time));
4869 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
4870 "TT think time or number of ports\n",
4871 (unsigned int) xhci->hci_version);
4873 slot_ctx->dev_state = 0;
4874 spin_unlock_irqrestore(&xhci->lock, flags);
4876 xhci_dbg(xhci, "Set up %s for hub device.\n",
4877 (xhci->hci_version > 0x95) ?
4878 "configure endpoint" : "evaluate context");
4880 /* Issue and wait for the configure endpoint or
4881 * evaluate context command.
4883 if (xhci->hci_version > 0x95)
4884 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
4887 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
4890 xhci_free_command(xhci, config_cmd);
4894 static 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;
4905 * TODO: Check with DWC3 clients for sysdev according to
4908 struct device *dev = hcd->self.sysdev;
4909 unsigned int minor_rev;
4912 /* Accept arbitrarily long scatter-gather lists */
4913 hcd->self.sg_tablesize = ~0;
4915 /* support to build packet from discontinuous buffers */
4916 hcd->self.no_sg_constraint = 1;
4918 /* XHCI controllers don't stop the ep queue on short packets :| */
4919 hcd->self.no_stop_on_short = 1;
4921 xhci = hcd_to_xhci(hcd);
4923 if (usb_hcd_is_primary_hcd(hcd)) {
4924 xhci->main_hcd = hcd;
4925 /* Mark the first roothub as being USB 2.0.
4926 * The xHCI driver will register the USB 3.0 roothub.
4928 hcd->speed = HCD_USB2;
4929 hcd->self.root_hub->speed = USB_SPEED_HIGH;
4931 * USB 2.0 roothub under xHCI has an integrated TT,
4932 * (rate matching hub) as opposed to having an OHCI/UHCI
4933 * companion controller.
4938 * Some 3.1 hosts return sbrn 0x30, use xhci supported protocol
4939 * minor revision instead of sbrn
4941 minor_rev = xhci->usb3_rhub.min_rev;
4943 hcd->speed = HCD_USB31;
4944 hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
4946 xhci_info(xhci, "Host supports USB 3.%x %s SuperSpeed\n",
4948 minor_rev ? "Enhanced" : "");
4950 /* xHCI private pointer was set in xhci_pci_probe for the second
4951 * registered roothub.
4956 mutex_init(&xhci->mutex);
4957 xhci->cap_regs = hcd->regs;
4958 xhci->op_regs = hcd->regs +
4959 HC_LENGTH(readl(&xhci->cap_regs->hc_capbase));
4960 xhci->run_regs = hcd->regs +
4961 (readl(&xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
4962 /* Cache read-only capability registers */
4963 xhci->hcs_params1 = readl(&xhci->cap_regs->hcs_params1);
4964 xhci->hcs_params2 = readl(&xhci->cap_regs->hcs_params2);
4965 xhci->hcs_params3 = readl(&xhci->cap_regs->hcs_params3);
4966 xhci->hcc_params = readl(&xhci->cap_regs->hc_capbase);
4967 xhci->hci_version = HC_VERSION(xhci->hcc_params);
4968 xhci->hcc_params = readl(&xhci->cap_regs->hcc_params);
4969 if (xhci->hci_version > 0x100)
4970 xhci->hcc_params2 = readl(&xhci->cap_regs->hcc_params2);
4971 xhci_print_registers(xhci);
4973 xhci->quirks |= quirks;
4975 get_quirks(dev, xhci);
4977 /* In xhci controllers which follow xhci 1.0 spec gives a spurious
4978 * success event after a short transfer. This quirk will ignore such
4981 if (xhci->hci_version > 0x96)
4982 xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
4984 /* Make sure the HC is halted. */
4985 retval = xhci_halt(xhci);
4989 xhci_dbg(xhci, "Resetting HCD\n");
4990 /* Reset the internal HC memory state and registers. */
4991 retval = xhci_reset(xhci, XHCI_RESET_LONG_USEC);
4994 xhci_dbg(xhci, "Reset complete\n");
4997 * On some xHCI controllers (e.g. R-Car SoCs), the AC64 bit (bit 0)
4998 * of HCCPARAMS1 is set to 1. However, the xHCs don't support 64-bit
4999 * address memory pointers actually. So, this driver clears the AC64
5000 * bit of xhci->hcc_params to call dma_set_coherent_mask(dev,
5001 * DMA_BIT_MASK(32)) in this xhci_gen_setup().
5003 if (xhci->quirks & XHCI_NO_64BIT_SUPPORT)
5004 xhci->hcc_params &= ~BIT(0);
5006 /* Set dma_mask and coherent_dma_mask to 64-bits,
5007 * if xHC supports 64-bit addressing */
5008 if (HCC_64BIT_ADDR(xhci->hcc_params) &&
5009 !dma_set_mask(dev, DMA_BIT_MASK(64))) {
5010 xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
5011 dma_set_coherent_mask(dev, DMA_BIT_MASK(64));
5014 * This is to avoid error in cases where a 32-bit USB
5015 * controller is used on a 64-bit capable system.
5017 retval = dma_set_mask(dev, DMA_BIT_MASK(32));
5020 xhci_dbg(xhci, "Enabling 32-bit DMA addresses.\n");
5021 dma_set_coherent_mask(dev, DMA_BIT_MASK(32));
5024 xhci_dbg(xhci, "Calling HCD init\n");
5025 /* Initialize HCD and host controller data structures. */
5026 retval = xhci_init(hcd);
5029 xhci_dbg(xhci, "Called HCD init\n");
5031 xhci_info(xhci, "hcc params 0x%08x hci version 0x%x quirks 0x%016llx\n",
5032 xhci->hcc_params, xhci->hci_version, xhci->quirks);
5036 EXPORT_SYMBOL_GPL(xhci_gen_setup);
5038 static const struct hc_driver xhci_hc_driver = {
5039 .description = "xhci-hcd",
5040 .product_desc = "xHCI Host Controller",
5041 .hcd_priv_size = sizeof(struct xhci_hcd),
5044 * generic hardware linkage
5047 .flags = HCD_MEMORY | HCD_USB3 | HCD_SHARED,
5050 * basic lifecycle operations
5052 .reset = NULL, /* set in xhci_init_driver() */
5055 .shutdown = xhci_shutdown,
5058 * managing i/o requests and associated device resources
5060 .urb_enqueue = xhci_urb_enqueue,
5061 .urb_dequeue = xhci_urb_dequeue,
5062 .alloc_dev = xhci_alloc_dev,
5063 .free_dev = xhci_free_dev,
5064 .alloc_streams = xhci_alloc_streams,
5065 .free_streams = xhci_free_streams,
5066 .add_endpoint = xhci_add_endpoint,
5067 .drop_endpoint = xhci_drop_endpoint,
5068 .endpoint_reset = xhci_endpoint_reset,
5069 .check_bandwidth = xhci_check_bandwidth,
5070 .reset_bandwidth = xhci_reset_bandwidth,
5071 .address_device = xhci_address_device,
5072 .enable_device = xhci_enable_device,
5073 .update_hub_device = xhci_update_hub_device,
5074 .reset_device = xhci_discover_or_reset_device,
5077 * scheduling support
5079 .get_frame_number = xhci_get_frame,
5084 .hub_control = xhci_hub_control,
5085 .hub_status_data = xhci_hub_status_data,
5086 .bus_suspend = xhci_bus_suspend,
5087 .bus_resume = xhci_bus_resume,
5090 * call back when device connected and addressed
5092 .update_device = xhci_update_device,
5093 .set_usb2_hw_lpm = xhci_set_usb2_hardware_lpm,
5094 .enable_usb3_lpm_timeout = xhci_enable_usb3_lpm_timeout,
5095 .disable_usb3_lpm_timeout = xhci_disable_usb3_lpm_timeout,
5096 .find_raw_port_number = xhci_find_raw_port_number,
5099 void xhci_init_driver(struct hc_driver *drv,
5100 const struct xhci_driver_overrides *over)
5104 /* Copy the generic table to drv then apply the overrides */
5105 *drv = xhci_hc_driver;
5108 drv->hcd_priv_size += over->extra_priv_size;
5110 drv->reset = over->reset;
5112 drv->start = over->start;
5115 EXPORT_SYMBOL_GPL(xhci_init_driver);
5117 MODULE_DESCRIPTION(DRIVER_DESC);
5118 MODULE_AUTHOR(DRIVER_AUTHOR);
5119 MODULE_LICENSE("GPL");
5121 static int __init xhci_hcd_init(void)
5124 * Check the compiler generated sizes of structures that must be laid
5125 * out in specific ways for hardware access.
5127 BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
5128 BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
5129 BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
5130 /* xhci_device_control has eight fields, and also
5131 * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
5133 BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
5134 BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
5135 BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
5136 BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 8*32/8);
5137 BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
5138 /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
5139 BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
5148 * If an init function is provided, an exit function must also be provided
5149 * to allow module unload.
5151 static void __exit xhci_hcd_fini(void) { }
5153 module_init(xhci_hcd_init);
5154 module_exit(xhci_hcd_fini);