1 // SPDX-License-Identifier: GPL-2.0
3 * xHCI host controller driver
5 * Copyright (C) 2008 Intel Corp.
8 * Some code borrowed from the Linux EHCI driver.
11 #include <linux/jiffies.h>
12 #include <linux/pci.h>
13 #include <linux/iommu.h>
14 #include <linux/iopoll.h>
15 #include <linux/irq.h>
16 #include <linux/log2.h>
17 #include <linux/module.h>
18 #include <linux/moduleparam.h>
19 #include <linux/slab.h>
20 #include <linux/string_choices.h>
21 #include <linux/dmi.h>
22 #include <linux/dma-mapping.h>
23 #include <linux/usb/xhci-sideband.h>
26 #include "xhci-trace.h"
27 #include "xhci-debugfs.h"
28 #include "xhci-dbgcap.h"
30 #define DRIVER_AUTHOR "Sarah Sharp"
31 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
33 #define PORT_WAKE_BITS (PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E)
35 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
36 static int link_quirk;
37 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
38 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
40 static unsigned long long quirks;
41 module_param(quirks, ullong, S_IRUGO);
42 MODULE_PARM_DESC(quirks, "Bit flags for quirks to be enabled as default");
44 static bool td_on_ring(struct xhci_td *td, struct xhci_ring *ring)
46 struct xhci_segment *seg;
48 if (!td || !td->start_seg)
51 xhci_for_each_ring_seg(ring->first_seg, seg) {
52 if (seg == td->start_seg)
60 * xhci_handshake - spin reading hc until handshake completes or fails
61 * @ptr: address of hc register to be read
62 * @mask: bits to look at in result of read
63 * @done: value of those bits when handshake succeeds
64 * @usec: timeout in microseconds
66 * Returns negative errno, or zero on success
68 * Success happens when the "mask" bits have the specified value (hardware
69 * handshake done). There are two failure modes: "usec" have passed (major
70 * hardware flakeout), or the register reads as all-ones (hardware removed).
72 int xhci_handshake(void __iomem *ptr, u32 mask, u32 done, u64 timeout_us)
77 ret = readl_poll_timeout_atomic(ptr, result,
78 (result & mask) == done ||
81 if (result == U32_MAX) /* card removed */
88 * Disable interrupts and begin the xHCI halting process.
90 void xhci_quiesce(struct xhci_hcd *xhci)
97 halted = readl(&xhci->op_regs->status) & STS_HALT;
101 cmd = readl(&xhci->op_regs->command);
103 writel(cmd, &xhci->op_regs->command);
107 * Force HC into halt state.
109 * Disable any IRQs and clear the run/stop bit.
110 * HC will complete any current and actively pipelined transactions, and
111 * should halt within 16 ms of the run/stop bit being cleared.
112 * Read HC Halted bit in the status register to see when the HC is finished.
114 int xhci_halt(struct xhci_hcd *xhci)
118 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Halt the HC");
121 ret = xhci_handshake(&xhci->op_regs->status,
122 STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
124 if (!(xhci->xhc_state & XHCI_STATE_DYING))
125 xhci_warn(xhci, "Host halt failed, %d\n", ret);
129 xhci->xhc_state |= XHCI_STATE_HALTED;
130 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
136 * Set the run bit and wait for the host to be running.
138 int xhci_start(struct xhci_hcd *xhci)
143 temp = readl(&xhci->op_regs->command);
145 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Turn on HC, cmd = 0x%x.",
147 writel(temp, &xhci->op_regs->command);
150 * Wait for the HCHalted Status bit to be 0 to indicate the host is
153 ret = xhci_handshake(&xhci->op_regs->status,
154 STS_HALT, 0, XHCI_MAX_HALT_USEC);
155 if (ret == -ETIMEDOUT)
156 xhci_err(xhci, "Host took too long to start, "
157 "waited %u microseconds.\n",
160 /* clear state flags. Including dying, halted or removing */
162 xhci->run_graceperiod = jiffies + msecs_to_jiffies(500);
171 * This resets pipelines, timers, counters, state machines, etc.
172 * Transactions will be terminated immediately, and operational registers
173 * will be set to their defaults.
175 int xhci_reset(struct xhci_hcd *xhci, u64 timeout_us)
181 state = readl(&xhci->op_regs->status);
183 if (state == ~(u32)0) {
184 if (!(xhci->xhc_state & XHCI_STATE_DYING))
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 xhci->usb2_rhub.bus_state.port_c_suspend = 0;
225 xhci->usb2_rhub.bus_state.suspended_ports = 0;
226 xhci->usb2_rhub.bus_state.resuming_ports = 0;
227 xhci->usb3_rhub.bus_state.port_c_suspend = 0;
228 xhci->usb3_rhub.bus_state.suspended_ports = 0;
229 xhci->usb3_rhub.bus_state.resuming_ports = 0;
234 static void xhci_zero_64b_regs(struct xhci_hcd *xhci)
236 struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
237 struct iommu_domain *domain;
243 * Some Renesas controllers get into a weird state if they are
244 * reset while programmed with 64bit addresses (they will preserve
245 * the top half of the address in internal, non visible
246 * registers). You end up with half the address coming from the
247 * kernel, and the other half coming from the firmware. Also,
248 * changing the programming leads to extra accesses even if the
249 * controller is supposed to be halted. The controller ends up with
250 * a fatal fault, and is then ripe for being properly reset.
252 * Special care is taken to only apply this if the device is behind
253 * an iommu. Doing anything when there is no iommu is definitely
256 domain = iommu_get_domain_for_dev(dev);
257 if (!(xhci->quirks & XHCI_ZERO_64B_REGS) || !domain ||
258 domain->type == IOMMU_DOMAIN_IDENTITY)
261 xhci_info(xhci, "Zeroing 64bit base registers, expecting fault\n");
263 /* Clear HSEIE so that faults do not get signaled */
264 val = readl(&xhci->op_regs->command);
266 writel(val, &xhci->op_regs->command);
268 /* Clear HSE (aka FATAL) */
269 val = readl(&xhci->op_regs->status);
271 writel(val, &xhci->op_regs->status);
273 /* Now zero the registers, and brace for impact */
274 val = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
275 if (upper_32_bits(val))
276 xhci_write_64(xhci, 0, &xhci->op_regs->dcbaa_ptr);
277 val = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
278 if (upper_32_bits(val))
279 xhci_write_64(xhci, 0, &xhci->op_regs->cmd_ring);
281 intrs = min_t(u32, HCS_MAX_INTRS(xhci->hcs_params1),
282 ARRAY_SIZE(xhci->run_regs->ir_set));
284 for (i = 0; i < intrs; i++) {
285 struct xhci_intr_reg __iomem *ir;
287 ir = &xhci->run_regs->ir_set[i];
288 val = xhci_read_64(xhci, &ir->erst_base);
289 if (upper_32_bits(val))
290 xhci_write_64(xhci, 0, &ir->erst_base);
291 val= xhci_read_64(xhci, &ir->erst_dequeue);
292 if (upper_32_bits(val))
293 xhci_write_64(xhci, 0, &ir->erst_dequeue);
296 /* Wait for the fault to appear. It will be cleared on reset */
297 err = xhci_handshake(&xhci->op_regs->status,
298 STS_FATAL, STS_FATAL,
301 xhci_info(xhci, "Fault detected\n");
304 int xhci_enable_interrupter(struct xhci_interrupter *ir)
308 if (!ir || !ir->ir_set)
311 iman = readl(&ir->ir_set->iman);
314 writel(iman, &ir->ir_set->iman);
316 /* Read operation to guarantee the write has been flushed from posted buffers */
317 readl(&ir->ir_set->iman);
321 int xhci_disable_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
325 if (!ir || !ir->ir_set)
328 iman = readl(&ir->ir_set->iman);
331 writel(iman, &ir->ir_set->iman);
333 iman = readl(&ir->ir_set->iman);
335 xhci_dbg(xhci, "%s: Interrupt pending\n", __func__);
340 /* interrupt moderation interval imod_interval in nanoseconds */
341 int xhci_set_interrupter_moderation(struct xhci_interrupter *ir,
346 if (!ir || !ir->ir_set)
349 /* IMODI value in IMOD register is in 250ns increments */
350 imod_interval = umin(imod_interval / 250, IMODI_MASK);
352 imod = readl(&ir->ir_set->imod);
354 imod |= imod_interval;
355 writel(imod, &ir->ir_set->imod);
360 static void compliance_mode_recovery(struct timer_list *t)
362 struct xhci_hcd *xhci;
364 struct xhci_hub *rhub;
368 xhci = timer_container_of(xhci, t, comp_mode_recovery_timer);
369 rhub = &xhci->usb3_rhub;
375 for (i = 0; i < rhub->num_ports; i++) {
376 temp = readl(rhub->ports[i]->addr);
377 if ((temp & PORT_PLS_MASK) == USB_SS_PORT_LS_COMP_MOD) {
379 * Compliance Mode Detected. Letting USB Core
380 * handle the Warm Reset
382 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
383 "Compliance mode detected->port %d",
385 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
386 "Attempting compliance mode recovery");
388 if (hcd->state == HC_STATE_SUSPENDED)
389 usb_hcd_resume_root_hub(hcd);
391 usb_hcd_poll_rh_status(hcd);
395 if (xhci->port_status_u0 != ((1 << rhub->num_ports) - 1))
396 mod_timer(&xhci->comp_mode_recovery_timer,
397 jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
401 * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
402 * that causes ports behind that hardware to enter compliance mode sometimes.
403 * The quirk creates a timer that polls every 2 seconds the link state of
404 * each host controller's port and recovers it by issuing a Warm reset
405 * if Compliance mode is detected, otherwise the port will become "dead" (no
406 * device connections or disconnections will be detected anymore). Becasue no
407 * status event is generated when entering compliance mode (per xhci spec),
408 * this quirk is needed on systems that have the failing hardware installed.
410 static void compliance_mode_recovery_timer_init(struct xhci_hcd *xhci)
412 xhci->port_status_u0 = 0;
413 timer_setup(&xhci->comp_mode_recovery_timer, compliance_mode_recovery,
415 xhci->comp_mode_recovery_timer.expires = jiffies +
416 msecs_to_jiffies(COMP_MODE_RCVRY_MSECS);
418 add_timer(&xhci->comp_mode_recovery_timer);
419 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
420 "Compliance mode recovery timer initialized");
424 * This function identifies the systems that have installed the SN65LVPE502CP
425 * USB3.0 re-driver and that need the Compliance Mode Quirk.
427 * Vendor: Hewlett-Packard -> System Models: Z420, Z620 and Z820
429 static bool xhci_compliance_mode_recovery_timer_quirk_check(void)
431 const char *dmi_product_name, *dmi_sys_vendor;
433 dmi_product_name = dmi_get_system_info(DMI_PRODUCT_NAME);
434 dmi_sys_vendor = dmi_get_system_info(DMI_SYS_VENDOR);
435 if (!dmi_product_name || !dmi_sys_vendor)
438 if (!(strstr(dmi_sys_vendor, "Hewlett-Packard")))
441 if (strstr(dmi_product_name, "Z420") ||
442 strstr(dmi_product_name, "Z620") ||
443 strstr(dmi_product_name, "Z820") ||
444 strstr(dmi_product_name, "Z1 Workstation"))
450 static int xhci_all_ports_seen_u0(struct xhci_hcd *xhci)
452 return (xhci->port_status_u0 == ((1 << xhci->usb3_rhub.num_ports) - 1));
455 static void xhci_hcd_page_size(struct xhci_hcd *xhci)
459 page_size = readl(&xhci->op_regs->page_size) & XHCI_PAGE_SIZE_MASK;
460 if (!is_power_of_2(page_size)) {
461 xhci_warn(xhci, "Invalid page size register = 0x%x\n", page_size);
462 /* Fallback to 4K page size, since that's common */
466 xhci->page_size = page_size << 12;
467 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "HCD page size set to %iK",
468 xhci->page_size >> 10);
471 static void xhci_enable_max_dev_slots(struct xhci_hcd *xhci)
476 max_slots = HCS_MAX_SLOTS(xhci->hcs_params1);
477 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xHC can handle at most %d device slots",
480 config_reg = readl(&xhci->op_regs->config_reg);
481 config_reg &= ~HCS_SLOTS_MASK;
482 config_reg |= max_slots;
484 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Setting Max device slots reg = 0x%x",
486 writel(config_reg, &xhci->op_regs->config_reg);
489 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
494 deq_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg, xhci->cmd_ring->dequeue);
495 deq_dma &= CMD_RING_PTR_MASK;
497 crcr = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
498 crcr &= ~CMD_RING_PTR_MASK;
501 crcr &= ~CMD_RING_CYCLE;
502 crcr |= xhci->cmd_ring->cycle_state;
504 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Setting command ring address to 0x%llx", crcr);
505 xhci_write_64(xhci, crcr, &xhci->op_regs->cmd_ring);
508 static void xhci_set_doorbell_ptr(struct xhci_hcd *xhci)
512 offset = readl(&xhci->cap_regs->db_off) & DBOFF_MASK;
513 xhci->dba = (void __iomem *)xhci->cap_regs + offset;
514 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
515 "Doorbell array is located at offset 0x%x from cap regs base addr", offset);
519 * Enable USB 3.0 device notifications for function remote wake, which is necessary
520 * for allowing USB 3.0 devices to do remote wakeup from U3 (device suspend).
522 static void xhci_set_dev_notifications(struct xhci_hcd *xhci)
526 dev_notf = readl(&xhci->op_regs->dev_notification);
527 dev_notf &= ~DEV_NOTE_MASK;
528 dev_notf |= DEV_NOTE_FWAKE;
529 writel(dev_notf, &xhci->op_regs->dev_notification);
533 * Initialize memory for HCD and xHC (one-time init).
535 * Program the PAGESIZE register, initialize the device context array, create
536 * device contexts (?), set up a command ring segment (or two?), create event
537 * ring (one for now).
539 static int xhci_init(struct usb_hcd *hcd)
541 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
544 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Starting %s", __func__);
545 spin_lock_init(&xhci->lock);
547 INIT_LIST_HEAD(&xhci->cmd_list);
548 INIT_DELAYED_WORK(&xhci->cmd_timer, xhci_handle_command_timeout);
549 init_completion(&xhci->cmd_ring_stop_completion);
550 xhci_hcd_page_size(xhci);
551 memset(xhci->devs, 0, MAX_HC_SLOTS * sizeof(*xhci->devs));
553 retval = xhci_mem_init(xhci, GFP_KERNEL);
557 /* Set the Number of Device Slots Enabled to the maximum supported value */
558 xhci_enable_max_dev_slots(xhci);
560 /* Set the address in the Command Ring Control register */
561 xhci_set_cmd_ring_deq(xhci);
563 /* Set Device Context Base Address Array pointer */
564 xhci_write_64(xhci, xhci->dcbaa->dma, &xhci->op_regs->dcbaa_ptr);
566 /* Set Doorbell array pointer */
567 xhci_set_doorbell_ptr(xhci);
569 /* Set USB 3.0 device notifications for function remote wake */
570 xhci_set_dev_notifications(xhci);
572 /* Initialize the Primary interrupter */
573 xhci_add_interrupter(xhci, 0);
574 xhci->interrupters[0]->isoc_bei_interval = AVOID_BEI_INTERVAL_MAX;
576 /* Initializing Compliance Mode Recovery Data If Needed */
577 if (xhci_compliance_mode_recovery_timer_quirk_check()) {
578 xhci->quirks |= XHCI_COMP_MODE_QUIRK;
579 compliance_mode_recovery_timer_init(xhci);
582 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Finished %s", __func__);
586 /*-------------------------------------------------------------------------*/
588 static int xhci_run_finished(struct xhci_hcd *xhci)
590 struct xhci_interrupter *ir = xhci->interrupters[0];
595 * Enable interrupts before starting the host (xhci 4.2 and 5.5.2).
596 * Protect the short window before host is running with a lock
598 spin_lock_irqsave(&xhci->lock, flags);
600 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Enable interrupts");
601 temp = readl(&xhci->op_regs->command);
603 writel(temp, &xhci->op_regs->command);
605 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Enable primary interrupter");
606 xhci_enable_interrupter(ir);
608 if (xhci_start(xhci)) {
610 spin_unlock_irqrestore(&xhci->lock, flags);
614 xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
616 if (xhci->quirks & XHCI_NEC_HOST)
617 xhci_ring_cmd_db(xhci);
619 spin_unlock_irqrestore(&xhci->lock, flags);
625 * Start the HC after it was halted.
627 * This function is called by the USB core when the HC driver is added.
628 * Its opposite is xhci_stop().
630 * xhci_init() must be called once before this function can be called.
631 * Reset the HC, enable device slot contexts, program DCBAAP, and
632 * set command ring pointer and event ring pointer.
634 * Setup MSI-X vectors and enable interrupts.
636 int xhci_run(struct usb_hcd *hcd)
640 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
641 struct xhci_interrupter *ir = xhci->interrupters[0];
642 /* Start the xHCI host controller running only after the USB 2.0 roothub
646 hcd->uses_new_polling = 1;
647 if (hcd->msi_enabled)
648 ir->ip_autoclear = true;
650 if (!usb_hcd_is_primary_hcd(hcd))
651 return xhci_run_finished(xhci);
653 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_run");
655 temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
656 temp_64 &= ERST_PTR_MASK;
657 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
658 "ERST deq = 64'h%0lx", (long unsigned int) temp_64);
660 xhci_set_interrupter_moderation(ir, xhci->imod_interval);
662 if (xhci->quirks & XHCI_NEC_HOST) {
663 struct xhci_command *command;
665 command = xhci_alloc_command(xhci, false, GFP_KERNEL);
669 ret = xhci_queue_vendor_command(xhci, command, 0, 0, 0,
670 TRB_TYPE(TRB_NEC_GET_FW));
672 xhci_free_command(xhci, command);
674 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
675 "Finished %s for main hcd", __func__);
677 xhci_create_dbc_dev(xhci);
679 xhci_debugfs_init(xhci);
681 if (xhci_has_one_roothub(xhci))
682 return xhci_run_finished(xhci);
684 set_bit(HCD_FLAG_DEFER_RH_REGISTER, &hcd->flags);
688 EXPORT_SYMBOL_GPL(xhci_run);
693 * This function is called by the USB core when the HC driver is removed.
694 * Its opposite is xhci_run().
696 * Disable device contexts, disable IRQs, and quiesce the HC.
697 * Reset the HC, finish any completed transactions, and cleanup memory.
699 void xhci_stop(struct usb_hcd *hcd)
702 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
703 struct xhci_interrupter *ir = xhci->interrupters[0];
705 mutex_lock(&xhci->mutex);
707 /* Only halt host and free memory after both hcds are removed */
708 if (!usb_hcd_is_primary_hcd(hcd)) {
709 mutex_unlock(&xhci->mutex);
713 xhci_remove_dbc_dev(xhci);
715 spin_lock_irq(&xhci->lock);
716 xhci->xhc_state |= XHCI_STATE_HALTED;
717 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
719 xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
720 spin_unlock_irq(&xhci->lock);
722 /* Deleting Compliance Mode Recovery Timer */
723 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
724 (!(xhci_all_ports_seen_u0(xhci)))) {
725 timer_delete_sync(&xhci->comp_mode_recovery_timer);
726 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
727 "%s: compliance mode recovery timer deleted",
731 if (xhci->quirks & XHCI_AMD_PLL_FIX)
734 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
735 "// Disabling event ring interrupts");
736 temp = readl(&xhci->op_regs->status);
737 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
738 xhci_disable_interrupter(xhci, ir);
740 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
741 xhci_mem_cleanup(xhci);
742 xhci_debugfs_exit(xhci);
743 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
744 "xhci_stop completed - status = %x",
745 readl(&xhci->op_regs->status));
746 mutex_unlock(&xhci->mutex);
748 EXPORT_SYMBOL_GPL(xhci_stop);
751 * Shutdown HC (not bus-specific)
753 * This is called when the machine is rebooting or halting. We assume that the
754 * machine will be powered off, and the HC's internal state will be reset.
755 * Don't bother to free memory.
757 * This will only ever be called with the main usb_hcd (the USB3 roothub).
759 void xhci_shutdown(struct usb_hcd *hcd)
761 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
763 if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
764 usb_disable_xhci_ports(to_pci_dev(hcd->self.sysdev));
766 /* Don't poll the roothubs after shutdown. */
767 xhci_dbg(xhci, "%s: stopping usb%d port polling.\n",
768 __func__, hcd->self.busnum);
769 clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
770 timer_delete_sync(&hcd->rh_timer);
772 if (xhci->shared_hcd) {
773 clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
774 timer_delete_sync(&xhci->shared_hcd->rh_timer);
777 spin_lock_irq(&xhci->lock);
781 * Workaround for spurious wakeps at shutdown with HSW, and for boot
782 * firmware delay in ADL-P PCH if port are left in U3 at shutdown
784 if (xhci->quirks & XHCI_SPURIOUS_WAKEUP ||
785 xhci->quirks & XHCI_RESET_TO_DEFAULT)
786 xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
788 spin_unlock_irq(&xhci->lock);
790 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
791 "xhci_shutdown completed - status = %x",
792 readl(&xhci->op_regs->status));
794 EXPORT_SYMBOL_GPL(xhci_shutdown);
797 static void xhci_save_registers(struct xhci_hcd *xhci)
799 struct xhci_interrupter *ir;
802 xhci->s3.command = readl(&xhci->op_regs->command);
803 xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
804 xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
805 xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
807 /* save both primary and all secondary interrupters */
808 /* fixme, shold we lock to prevent race with remove secondary interrupter? */
809 for (i = 0; i < xhci->max_interrupters; i++) {
810 ir = xhci->interrupters[i];
814 ir->s3_erst_size = readl(&ir->ir_set->erst_size);
815 ir->s3_erst_base = xhci_read_64(xhci, &ir->ir_set->erst_base);
816 ir->s3_erst_dequeue = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
817 ir->s3_iman = readl(&ir->ir_set->iman);
818 ir->s3_imod = readl(&ir->ir_set->imod);
822 static void xhci_restore_registers(struct xhci_hcd *xhci)
824 struct xhci_interrupter *ir;
827 writel(xhci->s3.command, &xhci->op_regs->command);
828 writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
829 xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
830 writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
832 /* FIXME should we lock to protect against freeing of interrupters */
833 for (i = 0; i < xhci->max_interrupters; i++) {
834 ir = xhci->interrupters[i];
838 writel(ir->s3_erst_size, &ir->ir_set->erst_size);
839 xhci_write_64(xhci, ir->s3_erst_base, &ir->ir_set->erst_base);
840 xhci_write_64(xhci, ir->s3_erst_dequeue, &ir->ir_set->erst_dequeue);
841 writel(ir->s3_iman, &ir->ir_set->iman);
842 writel(ir->s3_imod, &ir->ir_set->imod);
847 * The whole command ring must be cleared to zero when we suspend the host.
849 * The host doesn't save the command ring pointer in the suspend well, so we
850 * need to re-program it on resume. Unfortunately, the pointer must be 64-byte
851 * aligned, because of the reserved bits in the command ring dequeue pointer
852 * register. Therefore, we can't just set the dequeue pointer back in the
853 * middle of the ring (TRBs are 16-byte aligned).
855 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
857 struct xhci_ring *ring;
858 struct xhci_segment *seg;
860 ring = xhci->cmd_ring;
861 xhci_for_each_ring_seg(ring->first_seg, seg) {
862 /* erase all TRBs before the link */
863 memset(seg->trbs, 0, sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
864 /* clear link cycle bit */
865 seg->trbs[TRBS_PER_SEGMENT - 1].link.control &= cpu_to_le32(~TRB_CYCLE);
868 xhci_initialize_ring_info(ring);
870 * Reset the hardware dequeue pointer.
871 * Yes, this will need to be re-written after resume, but we're paranoid
872 * and want to make sure the hardware doesn't access bogus memory
873 * because, say, the BIOS or an SMI started the host without changing
874 * the command ring pointers.
876 xhci_set_cmd_ring_deq(xhci);
880 * Disable port wake bits if do_wakeup is not set.
882 * Also clear a possible internal port wake state left hanging for ports that
883 * detected termination but never successfully enumerated (trained to 0U).
884 * Internal wake causes immediate xHCI wake after suspend. PORT_CSC write done
885 * at enumeration clears this wake, force one here as well for unconnected ports
888 static void xhci_disable_hub_port_wake(struct xhci_hcd *xhci,
889 struct xhci_hub *rhub,
896 spin_lock_irqsave(&xhci->lock, flags);
898 for (i = 0; i < rhub->num_ports; i++) {
899 portsc = readl(rhub->ports[i]->addr);
900 t1 = xhci_port_state_to_neutral(portsc);
903 /* clear wake bits if do_wake is not set */
905 t2 &= ~PORT_WAKE_BITS;
907 /* Don't touch csc bit if connected or connect change is set */
908 if (!(portsc & (PORT_CSC | PORT_CONNECT)))
912 writel(t2, rhub->ports[i]->addr);
913 xhci_dbg(xhci, "config port %d-%d wake bits, portsc: 0x%x, write: 0x%x\n",
914 rhub->hcd->self.busnum, i + 1, portsc, t2);
917 spin_unlock_irqrestore(&xhci->lock, flags);
920 static bool xhci_pending_portevent(struct xhci_hcd *xhci)
922 struct xhci_port **ports;
927 status = readl(&xhci->op_regs->status);
928 if (status & STS_EINT)
931 * Checking STS_EINT is not enough as there is a lag between a change
932 * bit being set and the Port Status Change Event that it generated
933 * being written to the Event Ring. See note in xhci 1.1 section 4.19.2.
936 port_index = xhci->usb2_rhub.num_ports;
937 ports = xhci->usb2_rhub.ports;
938 while (port_index--) {
939 portsc = readl(ports[port_index]->addr);
940 if (portsc & PORT_CHANGE_MASK ||
941 (portsc & PORT_PLS_MASK) == XDEV_RESUME)
944 port_index = xhci->usb3_rhub.num_ports;
945 ports = xhci->usb3_rhub.ports;
946 while (port_index--) {
947 portsc = readl(ports[port_index]->addr);
948 if (portsc & (PORT_CHANGE_MASK | PORT_CAS) ||
949 (portsc & PORT_PLS_MASK) == XDEV_RESUME)
956 * Stop HC (not bus-specific)
958 * This is called when the machine transition into S3/S4 mode.
961 int xhci_suspend(struct xhci_hcd *xhci, bool do_wakeup)
964 unsigned int delay = XHCI_MAX_HALT_USEC * 2;
965 struct usb_hcd *hcd = xhci_to_hcd(xhci);
972 if (hcd->state != HC_STATE_SUSPENDED ||
973 (xhci->shared_hcd && xhci->shared_hcd->state != HC_STATE_SUSPENDED))
976 /* Clear root port wake on bits if wakeup not allowed. */
977 xhci_disable_hub_port_wake(xhci, &xhci->usb3_rhub, do_wakeup);
978 xhci_disable_hub_port_wake(xhci, &xhci->usb2_rhub, do_wakeup);
980 if (!HCD_HW_ACCESSIBLE(hcd))
983 xhci_dbc_suspend(xhci);
985 /* Don't poll the roothubs on bus suspend. */
986 xhci_dbg(xhci, "%s: stopping usb%d port polling.\n",
987 __func__, hcd->self.busnum);
988 clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
989 timer_delete_sync(&hcd->rh_timer);
990 if (xhci->shared_hcd) {
991 clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
992 timer_delete_sync(&xhci->shared_hcd->rh_timer);
995 if (xhci->quirks & XHCI_SUSPEND_DELAY)
996 usleep_range(1000, 1500);
998 spin_lock_irq(&xhci->lock);
999 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1000 if (xhci->shared_hcd)
1001 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1002 /* step 1: stop endpoint */
1003 /* skipped assuming that port suspend has done */
1005 /* step 2: clear Run/Stop bit */
1006 command = readl(&xhci->op_regs->command);
1007 command &= ~CMD_RUN;
1008 writel(command, &xhci->op_regs->command);
1010 /* Some chips from Fresco Logic need an extraordinary delay */
1011 delay *= (xhci->quirks & XHCI_SLOW_SUSPEND) ? 10 : 1;
1013 if (xhci_handshake(&xhci->op_regs->status,
1014 STS_HALT, STS_HALT, delay)) {
1015 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
1016 spin_unlock_irq(&xhci->lock);
1019 xhci_clear_command_ring(xhci);
1021 /* step 3: save registers */
1022 xhci_save_registers(xhci);
1024 /* step 4: set CSS flag */
1025 command = readl(&xhci->op_regs->command);
1027 writel(command, &xhci->op_regs->command);
1028 xhci->broken_suspend = 0;
1029 if (xhci_handshake(&xhci->op_regs->status,
1030 STS_SAVE, 0, 20 * 1000)) {
1032 * AMD SNPS xHC 3.0 occasionally does not clear the
1033 * SSS bit of USBSTS and when driver tries to poll
1034 * to see if the xHC clears BIT(8) which never happens
1035 * and driver assumes that controller is not responding
1036 * and times out. To workaround this, its good to check
1037 * if SRE and HCE bits are not set (as per xhci
1038 * Section 5.4.2) and bypass the timeout.
1040 res = readl(&xhci->op_regs->status);
1041 if ((xhci->quirks & XHCI_SNPS_BROKEN_SUSPEND) &&
1042 (((res & STS_SRE) == 0) &&
1043 ((res & STS_HCE) == 0))) {
1044 xhci->broken_suspend = 1;
1046 xhci_warn(xhci, "WARN: xHC save state timeout\n");
1047 spin_unlock_irq(&xhci->lock);
1051 spin_unlock_irq(&xhci->lock);
1054 * Deleting Compliance Mode Recovery Timer because the xHCI Host
1055 * is about to be suspended.
1057 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1058 (!(xhci_all_ports_seen_u0(xhci)))) {
1059 timer_delete_sync(&xhci->comp_mode_recovery_timer);
1060 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1061 "%s: compliance mode recovery timer deleted",
1067 EXPORT_SYMBOL_GPL(xhci_suspend);
1070 * start xHC (not bus-specific)
1072 * This is called when the machine transition from S3/S4 mode.
1075 int xhci_resume(struct xhci_hcd *xhci, bool power_lost, bool is_auto_resume)
1077 u32 command, temp = 0;
1078 struct usb_hcd *hcd = xhci_to_hcd(xhci);
1080 bool comp_timer_running = false;
1081 bool pending_portevent = false;
1082 bool suspended_usb3_devs = false;
1087 /* Wait a bit if either of the roothubs need to settle from the
1088 * transition into bus suspend.
1091 if (time_before(jiffies, xhci->usb2_rhub.bus_state.next_statechange) ||
1092 time_before(jiffies, xhci->usb3_rhub.bus_state.next_statechange))
1095 set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1096 if (xhci->shared_hcd)
1097 set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1099 spin_lock_irq(&xhci->lock);
1101 if (xhci->quirks & XHCI_RESET_ON_RESUME || xhci->broken_suspend)
1106 * Some controllers might lose power during suspend, so wait
1107 * for controller not ready bit to clear, just as in xHC init.
1109 retval = xhci_handshake(&xhci->op_regs->status,
1110 STS_CNR, 0, 10 * 1000 * 1000);
1112 xhci_warn(xhci, "Controller not ready at resume %d\n",
1114 spin_unlock_irq(&xhci->lock);
1117 /* step 1: restore register */
1118 xhci_restore_registers(xhci);
1119 /* step 2: initialize command ring buffer */
1120 xhci_set_cmd_ring_deq(xhci);
1121 /* step 3: restore state and start state*/
1122 /* step 3: set CRS flag */
1123 command = readl(&xhci->op_regs->command);
1125 writel(command, &xhci->op_regs->command);
1127 * Some controllers take up to 55+ ms to complete the controller
1128 * restore so setting the timeout to 100ms. Xhci specification
1129 * doesn't mention any timeout value.
1131 if (xhci_handshake(&xhci->op_regs->status,
1132 STS_RESTORE, 0, 100 * 1000)) {
1133 xhci_warn(xhci, "WARN: xHC restore state timeout\n");
1134 spin_unlock_irq(&xhci->lock);
1139 temp = readl(&xhci->op_regs->status);
1141 /* re-initialize the HC on Restore Error, or Host Controller Error */
1142 if ((temp & (STS_SRE | STS_HCE)) &&
1143 !(xhci->xhc_state & XHCI_STATE_REMOVING)) {
1145 xhci_warn(xhci, "xHC error in resume, USBSTS 0x%x, Reinit\n", temp);
1150 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1151 !(xhci_all_ports_seen_u0(xhci))) {
1152 timer_delete_sync(&xhci->comp_mode_recovery_timer);
1153 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1154 "Compliance Mode Recovery Timer deleted!");
1157 /* Let the USB core know _both_ roothubs lost power. */
1158 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1159 if (xhci->shared_hcd)
1160 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
1162 xhci_dbg(xhci, "Stop HCD\n");
1164 xhci_zero_64b_regs(xhci);
1165 if (xhci->xhc_state & XHCI_STATE_REMOVING)
1168 retval = xhci_reset(xhci, XHCI_RESET_LONG_USEC);
1169 spin_unlock_irq(&xhci->lock);
1173 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1174 temp = readl(&xhci->op_regs->status);
1175 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
1176 xhci_disable_interrupter(xhci, xhci->interrupters[0]);
1178 xhci_dbg(xhci, "cleaning up memory\n");
1179 xhci_mem_cleanup(xhci);
1180 xhci_debugfs_exit(xhci);
1181 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1182 readl(&xhci->op_regs->status));
1184 /* USB core calls the PCI reinit and start functions twice:
1185 * first with the primary HCD, and then with the secondary HCD.
1186 * If we don't do the same, the host will never be started.
1188 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1189 retval = xhci_init(hcd);
1192 comp_timer_running = true;
1194 xhci_dbg(xhci, "Start the primary HCD\n");
1195 retval = xhci_run(hcd);
1196 if (!retval && xhci->shared_hcd) {
1197 xhci_dbg(xhci, "Start the secondary HCD\n");
1198 retval = xhci_run(xhci->shared_hcd);
1203 * Resume roothubs unconditionally as PORTSC change bits are not
1204 * immediately visible after xHC reset
1206 hcd->state = HC_STATE_SUSPENDED;
1208 if (xhci->shared_hcd) {
1209 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1210 usb_hcd_resume_root_hub(xhci->shared_hcd);
1212 usb_hcd_resume_root_hub(hcd);
1217 /* step 4: set Run/Stop bit */
1218 command = readl(&xhci->op_regs->command);
1220 writel(command, &xhci->op_regs->command);
1221 xhci_handshake(&xhci->op_regs->status, STS_HALT,
1224 /* step 5: walk topology and initialize portsc,
1225 * portpmsc and portli
1227 /* this is done in bus_resume */
1229 /* step 6: restart each of the previously
1230 * Running endpoints by ringing their doorbells
1233 spin_unlock_irq(&xhci->lock);
1235 xhci_dbc_resume(xhci);
1239 * Resume roothubs only if there are pending events.
1240 * USB 3 devices resend U3 LFPS wake after a 100ms delay if
1241 * the first wake signalling failed, give it that chance if
1242 * there are suspended USB 3 devices.
1244 if (xhci->usb3_rhub.bus_state.suspended_ports ||
1245 xhci->usb3_rhub.bus_state.bus_suspended)
1246 suspended_usb3_devs = true;
1248 pending_portevent = xhci_pending_portevent(xhci);
1250 if (suspended_usb3_devs && !pending_portevent && is_auto_resume) {
1252 pending_portevent = xhci_pending_portevent(xhci);
1255 if (pending_portevent) {
1256 if (xhci->shared_hcd)
1257 usb_hcd_resume_root_hub(xhci->shared_hcd);
1258 usb_hcd_resume_root_hub(hcd);
1263 * If system is subject to the Quirk, Compliance Mode Timer needs to
1264 * be re-initialized Always after a system resume. Ports are subject
1265 * to suffer the Compliance Mode issue again. It doesn't matter if
1266 * ports have entered previously to U0 before system's suspension.
1268 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
1269 compliance_mode_recovery_timer_init(xhci);
1271 if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
1272 usb_asmedia_modifyflowcontrol(to_pci_dev(hcd->self.controller));
1274 /* Re-enable port polling. */
1275 xhci_dbg(xhci, "%s: starting usb%d port polling.\n",
1276 __func__, hcd->self.busnum);
1277 if (xhci->shared_hcd) {
1278 set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
1279 usb_hcd_poll_rh_status(xhci->shared_hcd);
1281 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1282 usb_hcd_poll_rh_status(hcd);
1286 EXPORT_SYMBOL_GPL(xhci_resume);
1287 #endif /* CONFIG_PM */
1289 /*-------------------------------------------------------------------------*/
1291 static int xhci_map_temp_buffer(struct usb_hcd *hcd, struct urb *urb)
1295 unsigned int buf_len;
1296 enum dma_data_direction dir;
1298 dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1299 buf_len = urb->transfer_buffer_length;
1301 temp = kzalloc_node(buf_len, GFP_ATOMIC,
1302 dev_to_node(hcd->self.sysdev));
1306 if (usb_urb_dir_out(urb))
1307 sg_pcopy_to_buffer(urb->sg, urb->num_sgs,
1310 urb->transfer_buffer = temp;
1311 urb->transfer_dma = dma_map_single(hcd->self.sysdev,
1312 urb->transfer_buffer,
1313 urb->transfer_buffer_length,
1316 if (dma_mapping_error(hcd->self.sysdev,
1317 urb->transfer_dma)) {
1321 urb->transfer_flags |= URB_DMA_MAP_SINGLE;
1327 static bool xhci_urb_temp_buffer_required(struct usb_hcd *hcd,
1332 unsigned int len = 0;
1333 unsigned int trb_size;
1334 unsigned int max_pkt;
1335 struct scatterlist *sg;
1336 struct scatterlist *tail_sg;
1339 max_pkt = usb_endpoint_maxp(&urb->ep->desc);
1344 if (urb->dev->speed >= USB_SPEED_SUPER)
1345 trb_size = TRB_CACHE_SIZE_SS;
1347 trb_size = TRB_CACHE_SIZE_HS;
1349 if (urb->transfer_buffer_length != 0 &&
1350 !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)) {
1351 for_each_sg(urb->sg, sg, urb->num_sgs, i) {
1352 len = len + sg->length;
1353 if (i > trb_size - 2) {
1354 len = len - tail_sg->length;
1355 if (len < max_pkt) {
1360 tail_sg = sg_next(tail_sg);
1367 static void xhci_unmap_temp_buf(struct usb_hcd *hcd, struct urb *urb)
1370 unsigned int buf_len;
1371 enum dma_data_direction dir;
1373 dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1375 buf_len = urb->transfer_buffer_length;
1377 if (IS_ENABLED(CONFIG_HAS_DMA) &&
1378 (urb->transfer_flags & URB_DMA_MAP_SINGLE))
1379 dma_unmap_single(hcd->self.sysdev,
1381 urb->transfer_buffer_length,
1384 if (usb_urb_dir_in(urb)) {
1385 len = sg_pcopy_from_buffer(urb->sg, urb->num_sgs,
1386 urb->transfer_buffer,
1389 if (len != buf_len) {
1390 xhci_dbg(hcd_to_xhci(hcd),
1391 "Copy from tmp buf to urb sg list failed\n");
1392 urb->actual_length = len;
1395 urb->transfer_flags &= ~URB_DMA_MAP_SINGLE;
1396 kfree(urb->transfer_buffer);
1397 urb->transfer_buffer = NULL;
1401 * Bypass the DMA mapping if URB is suitable for Immediate Transfer (IDT),
1402 * we'll copy the actual data into the TRB address register. This is limited to
1403 * transfers up to 8 bytes on output endpoints of any kind with wMaxPacketSize
1404 * >= 8 bytes. If suitable for IDT only one Transfer TRB per TD is allowed.
1406 static int xhci_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
1409 struct xhci_hcd *xhci;
1411 xhci = hcd_to_xhci(hcd);
1413 if (xhci_urb_suitable_for_idt(urb))
1416 if (xhci->quirks & XHCI_SG_TRB_CACHE_SIZE_QUIRK) {
1417 if (xhci_urb_temp_buffer_required(hcd, urb))
1418 return xhci_map_temp_buffer(hcd, urb);
1420 return usb_hcd_map_urb_for_dma(hcd, urb, mem_flags);
1423 static void xhci_unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
1425 struct xhci_hcd *xhci;
1426 bool unmap_temp_buf = false;
1428 xhci = hcd_to_xhci(hcd);
1430 if (urb->num_sgs && (urb->transfer_flags & URB_DMA_MAP_SINGLE))
1431 unmap_temp_buf = true;
1433 if ((xhci->quirks & XHCI_SG_TRB_CACHE_SIZE_QUIRK) && unmap_temp_buf)
1434 xhci_unmap_temp_buf(hcd, urb);
1436 usb_hcd_unmap_urb_for_dma(hcd, urb);
1440 * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1441 * HCDs. Find the index for an endpoint given its descriptor. Use the return
1442 * value to right shift 1 for the bitmask.
1443 * @desc: USB endpoint descriptor to determine index for
1445 * Index = (epnum * 2) + direction - 1,
1446 * where direction = 0 for OUT, 1 for IN.
1447 * For control endpoints, the IN index is used (OUT index is unused), so
1448 * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1450 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1453 if (usb_endpoint_xfer_control(desc))
1454 index = (unsigned int) (usb_endpoint_num(desc)*2);
1456 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1457 (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1460 EXPORT_SYMBOL_GPL(xhci_get_endpoint_index);
1462 /* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
1463 * address from the XHCI endpoint index.
1465 static unsigned int xhci_get_endpoint_address(unsigned int ep_index)
1467 unsigned int number = DIV_ROUND_UP(ep_index, 2);
1468 unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
1469 return direction | number;
1472 /* Find the flag for this endpoint (for use in the control context). Use the
1473 * endpoint index to create a bitmask. The slot context is bit 0, endpoint 0 is
1476 static unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1478 return 1 << (xhci_get_endpoint_index(desc) + 1);
1481 /* Compute the last valid endpoint context index. Basically, this is the
1482 * endpoint index plus one. For slot contexts with more than valid endpoint,
1483 * we find the most significant bit set in the added contexts flags.
1484 * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1485 * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1487 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1489 return fls(added_ctxs) - 1;
1492 /* Returns 1 if the arguments are OK;
1493 * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1495 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1496 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1498 struct xhci_hcd *xhci;
1499 struct xhci_virt_device *virt_dev;
1501 if (!hcd || (check_ep && !ep) || !udev) {
1502 pr_debug("xHCI %s called with invalid args\n", func);
1505 if (!udev->parent) {
1506 pr_debug("xHCI %s called for root hub\n", func);
1510 xhci = hcd_to_xhci(hcd);
1511 if (check_virt_dev) {
1512 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1513 xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
1518 virt_dev = xhci->devs[udev->slot_id];
1519 if (virt_dev->udev != udev) {
1520 xhci_dbg(xhci, "xHCI %s called with udev and "
1521 "virt_dev does not match\n", func);
1526 if (xhci->xhc_state & XHCI_STATE_HALTED)
1532 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1533 struct usb_device *udev, struct xhci_command *command,
1534 bool ctx_change, bool must_succeed);
1537 * Full speed devices may have a max packet size greater than 8 bytes, but the
1538 * USB core doesn't know that until it reads the first 8 bytes of the
1539 * descriptor. If the usb_device's max packet size changes after that point,
1540 * we need to issue an evaluate context command and wait on it.
1542 static int xhci_check_ep0_maxpacket(struct xhci_hcd *xhci, struct xhci_virt_device *vdev)
1544 struct xhci_input_control_ctx *ctrl_ctx;
1545 struct xhci_ep_ctx *ep_ctx;
1546 struct xhci_command *command;
1547 int max_packet_size;
1548 int hw_max_packet_size;
1551 ep_ctx = xhci_get_ep_ctx(xhci, vdev->out_ctx, 0);
1552 hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1553 max_packet_size = usb_endpoint_maxp(&vdev->udev->ep0.desc);
1555 if (hw_max_packet_size == max_packet_size)
1558 switch (max_packet_size) {
1559 case 8: case 16: case 32: case 64: case 9:
1560 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1561 "Max Packet Size for ep 0 changed.");
1562 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1563 "Max packet size in usb_device = %d",
1565 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1566 "Max packet size in xHCI HW = %d",
1567 hw_max_packet_size);
1568 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1569 "Issuing evaluate context command.");
1571 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
1575 command->in_ctx = vdev->in_ctx;
1576 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
1578 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1583 /* Set up the modified control endpoint 0 */
1584 xhci_endpoint_copy(xhci, vdev->in_ctx, vdev->out_ctx, 0);
1586 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, 0);
1587 ep_ctx->ep_info &= cpu_to_le32(~EP_STATE_MASK);/* must clear */
1588 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1589 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1591 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1592 ctrl_ctx->drop_flags = 0;
1594 ret = xhci_configure_endpoint(xhci, vdev->udev, command,
1596 /* Clean up the input context for later use by bandwidth functions */
1597 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1600 dev_dbg(&vdev->udev->dev, "incorrect max packet size %d for ep0\n",
1605 kfree(command->completion);
1612 * non-error returns are a promise to giveback() the urb later
1613 * we drop ownership so next owner (or urb unlink) can get it
1615 static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1617 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1618 unsigned long flags;
1620 unsigned int slot_id, ep_index;
1621 unsigned int *ep_state;
1622 struct urb_priv *urb_priv;
1625 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1627 if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1628 num_tds = urb->number_of_packets;
1629 else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
1630 urb->transfer_buffer_length > 0 &&
1631 urb->transfer_flags & URB_ZERO_PACKET &&
1632 !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
1637 urb_priv = kzalloc(struct_size(urb_priv, td, num_tds), mem_flags);
1641 urb_priv->num_tds = num_tds;
1642 urb_priv->num_tds_done = 0;
1643 urb->hcpriv = urb_priv;
1645 trace_xhci_urb_enqueue(urb);
1647 spin_lock_irqsave(&xhci->lock, flags);
1649 ret = xhci_check_args(hcd, urb->dev, urb->ep,
1650 true, true, __func__);
1652 ret = ret ? ret : -EINVAL;
1656 slot_id = urb->dev->slot_id;
1658 if (!HCD_HW_ACCESSIBLE(hcd)) {
1663 if (xhci->devs[slot_id]->flags & VDEV_PORT_ERROR) {
1664 xhci_dbg(xhci, "Can't queue urb, port error, link inactive\n");
1669 if (xhci->xhc_state & XHCI_STATE_DYING) {
1670 xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n",
1671 urb->ep->desc.bEndpointAddress, urb);
1676 ep_state = &xhci->devs[slot_id]->eps[ep_index].ep_state;
1678 if (*ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) {
1679 xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n",
1684 if (*ep_state & EP_SOFT_CLEAR_TOGGLE) {
1685 xhci_warn(xhci, "Can't enqueue URB while manually clearing toggle\n");
1690 switch (usb_endpoint_type(&urb->ep->desc)) {
1692 case USB_ENDPOINT_XFER_CONTROL:
1693 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1696 case USB_ENDPOINT_XFER_BULK:
1697 ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1700 case USB_ENDPOINT_XFER_INT:
1701 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1704 case USB_ENDPOINT_XFER_ISOC:
1705 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1711 xhci_urb_free_priv(urb_priv);
1714 spin_unlock_irqrestore(&xhci->lock, flags);
1719 * Remove the URB's TD from the endpoint ring. This may cause the HC to stop
1720 * USB transfers, potentially stopping in the middle of a TRB buffer. The HC
1721 * should pick up where it left off in the TD, unless a Set Transfer Ring
1722 * Dequeue Pointer is issued.
1724 * The TRBs that make up the buffers for the canceled URB will be "removed" from
1725 * the ring. Since the ring is a contiguous structure, they can't be physically
1726 * removed. Instead, there are two options:
1728 * 1) If the HC is in the middle of processing the URB to be canceled, we
1729 * simply move the ring's dequeue pointer past those TRBs using the Set
1730 * Transfer Ring Dequeue Pointer command. This will be the common case,
1731 * when drivers timeout on the last submitted URB and attempt to cancel.
1733 * 2) If the HC is in the middle of a different TD, we turn the TRBs into a
1734 * series of 1-TRB transfer no-op TDs. (No-ops shouldn't be chained.) The
1735 * HC will need to invalidate the any TRBs it has cached after the stop
1736 * endpoint command, as noted in the xHCI 0.95 errata.
1738 * 3) The TD may have completed by the time the Stop Endpoint Command
1739 * completes, so software needs to handle that case too.
1741 * This function should protect against the TD enqueueing code ringing the
1742 * doorbell while this code is waiting for a Stop Endpoint command to complete.
1743 * It also needs to account for multiple cancellations on happening at the same
1744 * time for the same endpoint.
1746 * Note that this function can be called in any context, or so says
1747 * usb_hcd_unlink_urb()
1749 static int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1751 unsigned long flags;
1754 struct xhci_hcd *xhci;
1755 struct urb_priv *urb_priv;
1757 unsigned int ep_index;
1758 struct xhci_ring *ep_ring;
1759 struct xhci_virt_ep *ep;
1760 struct xhci_command *command;
1761 struct xhci_virt_device *vdev;
1763 xhci = hcd_to_xhci(hcd);
1764 spin_lock_irqsave(&xhci->lock, flags);
1766 trace_xhci_urb_dequeue(urb);
1768 /* Make sure the URB hasn't completed or been unlinked already */
1769 ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1773 /* give back URB now if we can't queue it for cancel */
1774 vdev = xhci->devs[urb->dev->slot_id];
1775 urb_priv = urb->hcpriv;
1776 if (!vdev || !urb_priv)
1779 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1780 ep = &vdev->eps[ep_index];
1781 ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1782 if (!ep || !ep_ring)
1785 /* If xHC is dead take it down and return ALL URBs in xhci_hc_died() */
1786 temp = readl(&xhci->op_regs->status);
1787 if (temp == ~(u32)0 || xhci->xhc_state & XHCI_STATE_DYING) {
1793 * check ring is not re-allocated since URB was enqueued. If it is, then
1794 * make sure none of the ring related pointers in this URB private data
1795 * are touched, such as td_list, otherwise we overwrite freed data
1797 if (!td_on_ring(&urb_priv->td[0], ep_ring)) {
1798 xhci_err(xhci, "Canceled URB td not found on endpoint ring");
1799 for (i = urb_priv->num_tds_done; i < urb_priv->num_tds; i++) {
1800 td = &urb_priv->td[i];
1801 if (!list_empty(&td->cancelled_td_list))
1802 list_del_init(&td->cancelled_td_list);
1807 if (xhci->xhc_state & XHCI_STATE_HALTED) {
1808 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1809 "HC halted, freeing TD manually.");
1810 for (i = urb_priv->num_tds_done;
1811 i < urb_priv->num_tds;
1813 td = &urb_priv->td[i];
1814 if (!list_empty(&td->td_list))
1815 list_del_init(&td->td_list);
1816 if (!list_empty(&td->cancelled_td_list))
1817 list_del_init(&td->cancelled_td_list);
1822 i = urb_priv->num_tds_done;
1823 if (i < urb_priv->num_tds)
1824 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1825 "Cancel URB %p, dev %s, ep 0x%x, "
1826 "starting at offset 0x%llx",
1827 urb, urb->dev->devpath,
1828 urb->ep->desc.bEndpointAddress,
1829 (unsigned long long) xhci_trb_virt_to_dma(
1830 urb_priv->td[i].start_seg,
1831 urb_priv->td[i].start_trb));
1833 for (; i < urb_priv->num_tds; i++) {
1834 td = &urb_priv->td[i];
1835 /* TD can already be on cancelled list if ep halted on it */
1836 if (list_empty(&td->cancelled_td_list)) {
1837 td->cancel_status = TD_DIRTY;
1838 list_add_tail(&td->cancelled_td_list,
1839 &ep->cancelled_td_list);
1843 /* These completion handlers will sort out cancelled TDs for us */
1844 if (ep->ep_state & (EP_STOP_CMD_PENDING | EP_HALTED | SET_DEQ_PENDING)) {
1845 xhci_dbg(xhci, "Not queuing Stop Endpoint on slot %d ep %d in state 0x%x\n",
1846 urb->dev->slot_id, ep_index, ep->ep_state);
1850 /* In this case no commands are pending but the endpoint is stopped */
1851 if (ep->ep_state & EP_CLEARING_TT) {
1852 /* and cancelled TDs can be given back right away */
1853 xhci_dbg(xhci, "Invalidating TDs instantly on slot %d ep %d in state 0x%x\n",
1854 urb->dev->slot_id, ep_index, ep->ep_state);
1855 xhci_process_cancelled_tds(ep);
1857 /* Otherwise, queue a new Stop Endpoint command */
1858 command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
1863 ep->stop_time = jiffies;
1864 ep->ep_state |= EP_STOP_CMD_PENDING;
1865 xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1867 xhci_ring_cmd_db(xhci);
1870 spin_unlock_irqrestore(&xhci->lock, flags);
1875 xhci_urb_free_priv(urb_priv);
1876 usb_hcd_unlink_urb_from_ep(hcd, urb);
1877 spin_unlock_irqrestore(&xhci->lock, flags);
1878 usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1882 /* Drop an endpoint from a new bandwidth configuration for this device.
1883 * Only one call to this function is allowed per endpoint before
1884 * check_bandwidth() or reset_bandwidth() must be called.
1885 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1886 * add the endpoint to the schedule with possibly new parameters denoted by a
1887 * different endpoint descriptor in usb_host_endpoint.
1888 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1891 * The USB core will not allow URBs to be queued to an endpoint that is being
1892 * disabled, so there's no need for mutual exclusion to protect
1893 * the xhci->devs[slot_id] structure.
1895 int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1896 struct usb_host_endpoint *ep)
1898 struct xhci_hcd *xhci;
1899 struct xhci_container_ctx *in_ctx, *out_ctx;
1900 struct xhci_input_control_ctx *ctrl_ctx;
1901 unsigned int ep_index;
1902 struct xhci_ep_ctx *ep_ctx;
1904 u32 new_add_flags, new_drop_flags;
1907 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1910 xhci = hcd_to_xhci(hcd);
1911 if (xhci->xhc_state & XHCI_STATE_DYING)
1914 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1915 drop_flag = xhci_get_endpoint_flag(&ep->desc);
1916 if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1917 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1918 __func__, drop_flag);
1922 in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1923 out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1924 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1926 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1931 ep_index = xhci_get_endpoint_index(&ep->desc);
1932 ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1933 /* If the HC already knows the endpoint is disabled,
1934 * or the HCD has noted it is disabled, ignore this request
1936 if ((GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) ||
1937 le32_to_cpu(ctrl_ctx->drop_flags) &
1938 xhci_get_endpoint_flag(&ep->desc)) {
1939 /* Do not warn when called after a usb_device_reset */
1940 if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1941 xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1946 ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1947 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1949 ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1950 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1952 xhci_debugfs_remove_endpoint(xhci, xhci->devs[udev->slot_id], ep_index);
1954 xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1956 xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1957 (unsigned int) ep->desc.bEndpointAddress,
1959 (unsigned int) new_drop_flags,
1960 (unsigned int) new_add_flags);
1963 EXPORT_SYMBOL_GPL(xhci_drop_endpoint);
1965 /* Add an endpoint to a new possible bandwidth configuration for this device.
1966 * Only one call to this function is allowed per endpoint before
1967 * check_bandwidth() or reset_bandwidth() must be called.
1968 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1969 * add the endpoint to the schedule with possibly new parameters denoted by a
1970 * different endpoint descriptor in usb_host_endpoint.
1971 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1974 * The USB core will not allow URBs to be queued to an endpoint until the
1975 * configuration or alt setting is installed in the device, so there's no need
1976 * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1978 int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1979 struct usb_host_endpoint *ep)
1981 struct xhci_hcd *xhci;
1982 struct xhci_container_ctx *in_ctx;
1983 unsigned int ep_index;
1984 struct xhci_input_control_ctx *ctrl_ctx;
1985 struct xhci_ep_ctx *ep_ctx;
1987 u32 new_add_flags, new_drop_flags;
1988 struct xhci_virt_device *virt_dev;
1991 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1993 /* So we won't queue a reset ep command for a root hub */
1997 xhci = hcd_to_xhci(hcd);
1998 if (xhci->xhc_state & XHCI_STATE_DYING)
2001 added_ctxs = xhci_get_endpoint_flag(&ep->desc);
2002 if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
2003 /* FIXME when we have to issue an evaluate endpoint command to
2004 * deal with ep0 max packet size changing once we get the
2007 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
2008 __func__, added_ctxs);
2012 virt_dev = xhci->devs[udev->slot_id];
2013 in_ctx = virt_dev->in_ctx;
2014 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2016 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2021 ep_index = xhci_get_endpoint_index(&ep->desc);
2022 /* If this endpoint is already in use, and the upper layers are trying
2023 * to add it again without dropping it, reject the addition.
2025 if (virt_dev->eps[ep_index].ring &&
2026 !(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
2027 xhci_warn(xhci, "Trying to add endpoint 0x%x "
2028 "without dropping it.\n",
2029 (unsigned int) ep->desc.bEndpointAddress);
2033 /* If the HCD has already noted the endpoint is enabled,
2034 * ignore this request.
2036 if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
2037 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
2043 * Configuration and alternate setting changes must be done in
2044 * process context, not interrupt context (or so documenation
2045 * for usb_set_interface() and usb_set_configuration() claim).
2047 if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
2048 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
2049 __func__, ep->desc.bEndpointAddress);
2053 ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
2054 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
2056 /* If xhci_endpoint_disable() was called for this endpoint, but the
2057 * xHC hasn't been notified yet through the check_bandwidth() call,
2058 * this re-adds a new state for the endpoint from the new endpoint
2059 * descriptors. We must drop and re-add this endpoint, so we leave the
2062 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
2064 /* Store the usb_device pointer for later use */
2067 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, ep_index);
2068 trace_xhci_add_endpoint(ep_ctx);
2070 xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
2071 (unsigned int) ep->desc.bEndpointAddress,
2073 (unsigned int) new_drop_flags,
2074 (unsigned int) new_add_flags);
2077 EXPORT_SYMBOL_GPL(xhci_add_endpoint);
2079 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
2081 struct xhci_input_control_ctx *ctrl_ctx;
2082 struct xhci_ep_ctx *ep_ctx;
2083 struct xhci_slot_ctx *slot_ctx;
2086 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
2088 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2093 /* When a device's add flag and drop flag are zero, any subsequent
2094 * configure endpoint command will leave that endpoint's state
2095 * untouched. Make sure we don't leave any old state in the input
2096 * endpoint contexts.
2098 ctrl_ctx->drop_flags = 0;
2099 ctrl_ctx->add_flags = 0;
2100 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2101 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2102 /* Endpoint 0 is always valid */
2103 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
2104 for (i = 1; i < 31; i++) {
2105 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
2106 ep_ctx->ep_info = 0;
2107 ep_ctx->ep_info2 = 0;
2109 ep_ctx->tx_info = 0;
2113 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
2114 struct usb_device *udev, u32 *cmd_status)
2118 switch (*cmd_status) {
2119 case COMP_COMMAND_ABORTED:
2120 case COMP_COMMAND_RING_STOPPED:
2121 xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
2124 case COMP_RESOURCE_ERROR:
2125 dev_warn(&udev->dev,
2126 "Not enough host controller resources for new device state.\n");
2128 /* FIXME: can we allocate more resources for the HC? */
2130 case COMP_BANDWIDTH_ERROR:
2131 case COMP_SECONDARY_BANDWIDTH_ERROR:
2132 dev_warn(&udev->dev,
2133 "Not enough bandwidth for new device state.\n");
2135 /* FIXME: can we go back to the old state? */
2137 case COMP_TRB_ERROR:
2138 /* the HCD set up something wrong */
2139 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
2141 "and endpoint is not disabled.\n");
2144 case COMP_INCOMPATIBLE_DEVICE_ERROR:
2145 dev_warn(&udev->dev,
2146 "ERROR: Incompatible device for endpoint configure command.\n");
2150 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2151 "Successful Endpoint Configure command");
2155 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2163 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
2164 struct usb_device *udev, u32 *cmd_status)
2168 switch (*cmd_status) {
2169 case COMP_COMMAND_ABORTED:
2170 case COMP_COMMAND_RING_STOPPED:
2171 xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
2174 case COMP_PARAMETER_ERROR:
2175 dev_warn(&udev->dev,
2176 "WARN: xHCI driver setup invalid evaluate context command.\n");
2179 case COMP_SLOT_NOT_ENABLED_ERROR:
2180 dev_warn(&udev->dev,
2181 "WARN: slot not enabled for evaluate context command.\n");
2184 case COMP_CONTEXT_STATE_ERROR:
2185 dev_warn(&udev->dev,
2186 "WARN: invalid context state for evaluate context command.\n");
2189 case COMP_INCOMPATIBLE_DEVICE_ERROR:
2190 dev_warn(&udev->dev,
2191 "ERROR: Incompatible device for evaluate context command.\n");
2194 case COMP_MAX_EXIT_LATENCY_TOO_LARGE_ERROR:
2195 /* Max Exit Latency too large error */
2196 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
2200 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2201 "Successful evaluate context command");
2205 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2213 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
2214 struct xhci_input_control_ctx *ctrl_ctx)
2216 u32 valid_add_flags;
2217 u32 valid_drop_flags;
2219 /* Ignore the slot flag (bit 0), and the default control endpoint flag
2220 * (bit 1). The default control endpoint is added during the Address
2221 * Device command and is never removed until the slot is disabled.
2223 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2224 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2226 /* Use hweight32 to count the number of ones in the add flags, or
2227 * number of endpoints added. Don't count endpoints that are changed
2228 * (both added and dropped).
2230 return hweight32(valid_add_flags) -
2231 hweight32(valid_add_flags & valid_drop_flags);
2234 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
2235 struct xhci_input_control_ctx *ctrl_ctx)
2237 u32 valid_add_flags;
2238 u32 valid_drop_flags;
2240 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2241 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2243 return hweight32(valid_drop_flags) -
2244 hweight32(valid_add_flags & valid_drop_flags);
2248 * We need to reserve the new number of endpoints before the configure endpoint
2249 * command completes. We can't subtract the dropped endpoints from the number
2250 * of active endpoints until the command completes because we can oversubscribe
2251 * the host in this case:
2253 * - the first configure endpoint command drops more endpoints than it adds
2254 * - a second configure endpoint command that adds more endpoints is queued
2255 * - the first configure endpoint command fails, so the config is unchanged
2256 * - the second command may succeed, even though there isn't enough resources
2258 * Must be called with xhci->lock held.
2260 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
2261 struct xhci_input_control_ctx *ctrl_ctx)
2265 added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2266 if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
2267 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2268 "Not enough ep ctxs: "
2269 "%u active, need to add %u, limit is %u.",
2270 xhci->num_active_eps, added_eps,
2271 xhci->limit_active_eps);
2274 xhci->num_active_eps += added_eps;
2275 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2276 "Adding %u ep ctxs, %u now active.", added_eps,
2277 xhci->num_active_eps);
2282 * The configure endpoint was failed by the xHC for some other reason, so we
2283 * need to revert the resources that failed configuration would have used.
2285 * Must be called with xhci->lock held.
2287 static void xhci_free_host_resources(struct xhci_hcd *xhci,
2288 struct xhci_input_control_ctx *ctrl_ctx)
2292 num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2293 xhci->num_active_eps -= num_failed_eps;
2294 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2295 "Removing %u failed ep ctxs, %u now active.",
2297 xhci->num_active_eps);
2301 * Now that the command has completed, clean up the active endpoint count by
2302 * subtracting out the endpoints that were dropped (but not changed).
2304 * Must be called with xhci->lock held.
2306 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
2307 struct xhci_input_control_ctx *ctrl_ctx)
2309 u32 num_dropped_eps;
2311 num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
2312 xhci->num_active_eps -= num_dropped_eps;
2313 if (num_dropped_eps)
2314 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2315 "Removing %u dropped ep ctxs, %u now active.",
2317 xhci->num_active_eps);
2320 static unsigned int xhci_get_block_size(struct usb_device *udev)
2322 switch (udev->speed) {
2324 case USB_SPEED_FULL:
2326 case USB_SPEED_HIGH:
2328 case USB_SPEED_SUPER:
2329 case USB_SPEED_SUPER_PLUS:
2331 case USB_SPEED_UNKNOWN:
2333 /* Should never happen */
2339 xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
2341 if (interval_bw->overhead[LS_OVERHEAD_TYPE])
2343 if (interval_bw->overhead[FS_OVERHEAD_TYPE])
2348 /* If we are changing a LS/FS device under a HS hub,
2349 * make sure (if we are activating a new TT) that the HS bus has enough
2350 * bandwidth for this new TT.
2352 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2353 struct xhci_virt_device *virt_dev,
2356 struct xhci_interval_bw_table *bw_table;
2357 struct xhci_tt_bw_info *tt_info;
2359 /* Find the bandwidth table for the root port this TT is attached to. */
2360 bw_table = &xhci->rh_bw[virt_dev->rhub_port->hw_portnum].bw_table;
2361 tt_info = virt_dev->tt_info;
2362 /* If this TT already had active endpoints, the bandwidth for this TT
2363 * has already been added. Removing all periodic endpoints (and thus
2364 * making the TT enactive) will only decrease the bandwidth used.
2368 if (old_active_eps == 0 && tt_info->active_eps != 0) {
2369 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2373 /* Not sure why we would have no new active endpoints...
2375 * Maybe because of an Evaluate Context change for a hub update or a
2376 * control endpoint 0 max packet size change?
2377 * FIXME: skip the bandwidth calculation in that case.
2382 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2383 struct xhci_virt_device *virt_dev)
2385 unsigned int bw_reserved;
2387 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2388 if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2391 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2392 if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2399 * This algorithm is a very conservative estimate of the worst-case scheduling
2400 * scenario for any one interval. The hardware dynamically schedules the
2401 * packets, so we can't tell which microframe could be the limiting factor in
2402 * the bandwidth scheduling. This only takes into account periodic endpoints.
2404 * Obviously, we can't solve an NP complete problem to find the minimum worst
2405 * case scenario. Instead, we come up with an estimate that is no less than
2406 * the worst case bandwidth used for any one microframe, but may be an
2409 * We walk the requirements for each endpoint by interval, starting with the
2410 * smallest interval, and place packets in the schedule where there is only one
2411 * possible way to schedule packets for that interval. In order to simplify
2412 * this algorithm, we record the largest max packet size for each interval, and
2413 * assume all packets will be that size.
2415 * For interval 0, we obviously must schedule all packets for each interval.
2416 * The bandwidth for interval 0 is just the amount of data to be transmitted
2417 * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2418 * the number of packets).
2420 * For interval 1, we have two possible microframes to schedule those packets
2421 * in. For this algorithm, if we can schedule the same number of packets for
2422 * each possible scheduling opportunity (each microframe), we will do so. The
2423 * remaining number of packets will be saved to be transmitted in the gaps in
2424 * the next interval's scheduling sequence.
2426 * As we move those remaining packets to be scheduled with interval 2 packets,
2427 * we have to double the number of remaining packets to transmit. This is
2428 * because the intervals are actually powers of 2, and we would be transmitting
2429 * the previous interval's packets twice in this interval. We also have to be
2430 * sure that when we look at the largest max packet size for this interval, we
2431 * also look at the largest max packet size for the remaining packets and take
2432 * the greater of the two.
2434 * The algorithm continues to evenly distribute packets in each scheduling
2435 * opportunity, and push the remaining packets out, until we get to the last
2436 * interval. Then those packets and their associated overhead are just added
2437 * to the bandwidth used.
2439 static int xhci_check_bw_table(struct xhci_hcd *xhci,
2440 struct xhci_virt_device *virt_dev,
2443 unsigned int bw_reserved;
2444 unsigned int max_bandwidth;
2445 unsigned int bw_used;
2446 unsigned int block_size;
2447 struct xhci_interval_bw_table *bw_table;
2448 unsigned int packet_size = 0;
2449 unsigned int overhead = 0;
2450 unsigned int packets_transmitted = 0;
2451 unsigned int packets_remaining = 0;
2454 if (virt_dev->udev->speed >= USB_SPEED_SUPER)
2455 return xhci_check_ss_bw(xhci, virt_dev);
2457 if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2458 max_bandwidth = HS_BW_LIMIT;
2459 /* Convert percent of bus BW reserved to blocks reserved */
2460 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2462 max_bandwidth = FS_BW_LIMIT;
2463 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2466 bw_table = virt_dev->bw_table;
2467 /* We need to translate the max packet size and max ESIT payloads into
2468 * the units the hardware uses.
2470 block_size = xhci_get_block_size(virt_dev->udev);
2472 /* If we are manipulating a LS/FS device under a HS hub, double check
2473 * that the HS bus has enough bandwidth if we are activing a new TT.
2475 if (virt_dev->tt_info) {
2476 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2477 "Recalculating BW for rootport %u",
2478 virt_dev->rhub_port->hw_portnum + 1);
2479 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2480 xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2481 "newly activated TT.\n");
2484 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2485 "Recalculating BW for TT slot %u port %u",
2486 virt_dev->tt_info->slot_id,
2487 virt_dev->tt_info->ttport);
2489 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2490 "Recalculating BW for rootport %u",
2491 virt_dev->rhub_port->hw_portnum + 1);
2494 /* Add in how much bandwidth will be used for interval zero, or the
2495 * rounded max ESIT payload + number of packets * largest overhead.
2497 bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2498 bw_table->interval_bw[0].num_packets *
2499 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2501 for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2502 unsigned int bw_added;
2503 unsigned int largest_mps;
2504 unsigned int interval_overhead;
2507 * How many packets could we transmit in this interval?
2508 * If packets didn't fit in the previous interval, we will need
2509 * to transmit that many packets twice within this interval.
2511 packets_remaining = 2 * packets_remaining +
2512 bw_table->interval_bw[i].num_packets;
2514 /* Find the largest max packet size of this or the previous
2517 if (list_empty(&bw_table->interval_bw[i].endpoints))
2520 struct xhci_virt_ep *virt_ep;
2521 struct list_head *ep_entry;
2523 ep_entry = bw_table->interval_bw[i].endpoints.next;
2524 virt_ep = list_entry(ep_entry,
2525 struct xhci_virt_ep, bw_endpoint_list);
2526 /* Convert to blocks, rounding up */
2527 largest_mps = DIV_ROUND_UP(
2528 virt_ep->bw_info.max_packet_size,
2531 if (largest_mps > packet_size)
2532 packet_size = largest_mps;
2534 /* Use the larger overhead of this or the previous interval. */
2535 interval_overhead = xhci_get_largest_overhead(
2536 &bw_table->interval_bw[i]);
2537 if (interval_overhead > overhead)
2538 overhead = interval_overhead;
2540 /* How many packets can we evenly distribute across
2541 * (1 << (i + 1)) possible scheduling opportunities?
2543 packets_transmitted = packets_remaining >> (i + 1);
2545 /* Add in the bandwidth used for those scheduled packets */
2546 bw_added = packets_transmitted * (overhead + packet_size);
2548 /* How many packets do we have remaining to transmit? */
2549 packets_remaining = packets_remaining % (1 << (i + 1));
2551 /* What largest max packet size should those packets have? */
2552 /* If we've transmitted all packets, don't carry over the
2553 * largest packet size.
2555 if (packets_remaining == 0) {
2558 } else if (packets_transmitted > 0) {
2559 /* Otherwise if we do have remaining packets, and we've
2560 * scheduled some packets in this interval, take the
2561 * largest max packet size from endpoints with this
2564 packet_size = largest_mps;
2565 overhead = interval_overhead;
2567 /* Otherwise carry over packet_size and overhead from the last
2568 * time we had a remainder.
2570 bw_used += bw_added;
2571 if (bw_used > max_bandwidth) {
2572 xhci_warn(xhci, "Not enough bandwidth. "
2573 "Proposed: %u, Max: %u\n",
2574 bw_used, max_bandwidth);
2579 * Ok, we know we have some packets left over after even-handedly
2580 * scheduling interval 15. We don't know which microframes they will
2581 * fit into, so we over-schedule and say they will be scheduled every
2584 if (packets_remaining > 0)
2585 bw_used += overhead + packet_size;
2587 if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2588 /* OK, we're manipulating a HS device attached to a
2589 * root port bandwidth domain. Include the number of active TTs
2590 * in the bandwidth used.
2592 bw_used += TT_HS_OVERHEAD *
2593 xhci->rh_bw[virt_dev->rhub_port->hw_portnum].num_active_tts;
2596 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2597 "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2598 "Available: %u " "percent",
2599 bw_used, max_bandwidth, bw_reserved,
2600 (max_bandwidth - bw_used - bw_reserved) * 100 /
2603 bw_used += bw_reserved;
2604 if (bw_used > max_bandwidth) {
2605 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2606 bw_used, max_bandwidth);
2610 bw_table->bw_used = bw_used;
2614 static bool xhci_is_async_ep(unsigned int ep_type)
2616 return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2617 ep_type != ISOC_IN_EP &&
2618 ep_type != INT_IN_EP);
2621 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2623 return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
2626 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2628 unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2630 if (ep_bw->ep_interval == 0)
2631 return SS_OVERHEAD_BURST +
2632 (ep_bw->mult * ep_bw->num_packets *
2633 (SS_OVERHEAD + mps));
2634 return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2635 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2636 1 << ep_bw->ep_interval);
2640 static void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2641 struct xhci_bw_info *ep_bw,
2642 struct xhci_interval_bw_table *bw_table,
2643 struct usb_device *udev,
2644 struct xhci_virt_ep *virt_ep,
2645 struct xhci_tt_bw_info *tt_info)
2647 struct xhci_interval_bw *interval_bw;
2648 int normalized_interval;
2650 if (xhci_is_async_ep(ep_bw->type))
2653 if (udev->speed >= USB_SPEED_SUPER) {
2654 if (xhci_is_sync_in_ep(ep_bw->type))
2655 xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2656 xhci_get_ss_bw_consumed(ep_bw);
2658 xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2659 xhci_get_ss_bw_consumed(ep_bw);
2663 /* SuperSpeed endpoints never get added to intervals in the table, so
2664 * this check is only valid for HS/FS/LS devices.
2666 if (list_empty(&virt_ep->bw_endpoint_list))
2668 /* For LS/FS devices, we need to translate the interval expressed in
2669 * microframes to frames.
2671 if (udev->speed == USB_SPEED_HIGH)
2672 normalized_interval = ep_bw->ep_interval;
2674 normalized_interval = ep_bw->ep_interval - 3;
2676 if (normalized_interval == 0)
2677 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2678 interval_bw = &bw_table->interval_bw[normalized_interval];
2679 interval_bw->num_packets -= ep_bw->num_packets;
2680 switch (udev->speed) {
2682 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2684 case USB_SPEED_FULL:
2685 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2687 case USB_SPEED_HIGH:
2688 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2691 /* Should never happen because only LS/FS/HS endpoints will get
2692 * added to the endpoint list.
2697 tt_info->active_eps -= 1;
2698 list_del_init(&virt_ep->bw_endpoint_list);
2701 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2702 struct xhci_bw_info *ep_bw,
2703 struct xhci_interval_bw_table *bw_table,
2704 struct usb_device *udev,
2705 struct xhci_virt_ep *virt_ep,
2706 struct xhci_tt_bw_info *tt_info)
2708 struct xhci_interval_bw *interval_bw;
2709 struct xhci_virt_ep *smaller_ep;
2710 int normalized_interval;
2712 if (xhci_is_async_ep(ep_bw->type))
2715 if (udev->speed == USB_SPEED_SUPER) {
2716 if (xhci_is_sync_in_ep(ep_bw->type))
2717 xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2718 xhci_get_ss_bw_consumed(ep_bw);
2720 xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2721 xhci_get_ss_bw_consumed(ep_bw);
2725 /* For LS/FS devices, we need to translate the interval expressed in
2726 * microframes to frames.
2728 if (udev->speed == USB_SPEED_HIGH)
2729 normalized_interval = ep_bw->ep_interval;
2731 normalized_interval = ep_bw->ep_interval - 3;
2733 if (normalized_interval == 0)
2734 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2735 interval_bw = &bw_table->interval_bw[normalized_interval];
2736 interval_bw->num_packets += ep_bw->num_packets;
2737 switch (udev->speed) {
2739 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2741 case USB_SPEED_FULL:
2742 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2744 case USB_SPEED_HIGH:
2745 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2748 /* Should never happen because only LS/FS/HS endpoints will get
2749 * added to the endpoint list.
2755 tt_info->active_eps += 1;
2756 /* Insert the endpoint into the list, largest max packet size first. */
2757 list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2759 if (ep_bw->max_packet_size >=
2760 smaller_ep->bw_info.max_packet_size) {
2761 /* Add the new ep before the smaller endpoint */
2762 list_add_tail(&virt_ep->bw_endpoint_list,
2763 &smaller_ep->bw_endpoint_list);
2767 /* Add the new endpoint at the end of the list. */
2768 list_add_tail(&virt_ep->bw_endpoint_list,
2769 &interval_bw->endpoints);
2772 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2773 struct xhci_virt_device *virt_dev,
2776 struct xhci_root_port_bw_info *rh_bw_info;
2777 if (!virt_dev->tt_info)
2780 rh_bw_info = &xhci->rh_bw[virt_dev->rhub_port->hw_portnum];
2781 if (old_active_eps == 0 &&
2782 virt_dev->tt_info->active_eps != 0) {
2783 rh_bw_info->num_active_tts += 1;
2784 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2785 } else if (old_active_eps != 0 &&
2786 virt_dev->tt_info->active_eps == 0) {
2787 rh_bw_info->num_active_tts -= 1;
2788 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2792 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2793 struct xhci_virt_device *virt_dev,
2794 struct xhci_container_ctx *in_ctx)
2796 struct xhci_bw_info ep_bw_info[31];
2798 struct xhci_input_control_ctx *ctrl_ctx;
2799 int old_active_eps = 0;
2801 if (virt_dev->tt_info)
2802 old_active_eps = virt_dev->tt_info->active_eps;
2804 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2806 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2811 for (i = 0; i < 31; i++) {
2812 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2815 /* Make a copy of the BW info in case we need to revert this */
2816 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2817 sizeof(ep_bw_info[i]));
2818 /* Drop the endpoint from the interval table if the endpoint is
2819 * being dropped or changed.
2821 if (EP_IS_DROPPED(ctrl_ctx, i))
2822 xhci_drop_ep_from_interval_table(xhci,
2823 &virt_dev->eps[i].bw_info,
2829 /* Overwrite the information stored in the endpoints' bw_info */
2830 xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2831 for (i = 0; i < 31; i++) {
2832 /* Add any changed or added endpoints to the interval table */
2833 if (EP_IS_ADDED(ctrl_ctx, i))
2834 xhci_add_ep_to_interval_table(xhci,
2835 &virt_dev->eps[i].bw_info,
2842 if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2843 /* Ok, this fits in the bandwidth we have.
2844 * Update the number of active TTs.
2846 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2850 /* We don't have enough bandwidth for this, revert the stored info. */
2851 for (i = 0; i < 31; i++) {
2852 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2855 /* Drop the new copies of any added or changed endpoints from
2856 * the interval table.
2858 if (EP_IS_ADDED(ctrl_ctx, i)) {
2859 xhci_drop_ep_from_interval_table(xhci,
2860 &virt_dev->eps[i].bw_info,
2866 /* Revert the endpoint back to its old information */
2867 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2868 sizeof(ep_bw_info[i]));
2869 /* Add any changed or dropped endpoints back into the table */
2870 if (EP_IS_DROPPED(ctrl_ctx, i))
2871 xhci_add_ep_to_interval_table(xhci,
2872 &virt_dev->eps[i].bw_info,
2882 * Synchronous XHCI stop endpoint helper. Issues the stop endpoint command and
2883 * waits for the command completion before returning. This does not call
2884 * xhci_handle_cmd_stop_ep(), which has additional handling for 'context error'
2885 * cases, along with transfer ring cleanup.
2887 * xhci_stop_endpoint_sync() is intended to be utilized by clients that manage
2888 * their own transfer ring, such as offload situations.
2890 int xhci_stop_endpoint_sync(struct xhci_hcd *xhci, struct xhci_virt_ep *ep, int suspend,
2893 struct xhci_command *command;
2894 unsigned long flags;
2897 command = xhci_alloc_command(xhci, true, gfp_flags);
2901 spin_lock_irqsave(&xhci->lock, flags);
2902 ret = xhci_queue_stop_endpoint(xhci, command, ep->vdev->slot_id,
2903 ep->ep_index, suspend);
2905 spin_unlock_irqrestore(&xhci->lock, flags);
2909 xhci_ring_cmd_db(xhci);
2910 spin_unlock_irqrestore(&xhci->lock, flags);
2912 wait_for_completion(command->completion);
2914 /* No handling for COMP_CONTEXT_STATE_ERROR done at command completion*/
2915 if (command->status == COMP_COMMAND_ABORTED ||
2916 command->status == COMP_COMMAND_RING_STOPPED) {
2917 xhci_warn(xhci, "Timeout while waiting for stop endpoint command\n");
2921 xhci_free_command(xhci, command);
2925 EXPORT_SYMBOL_GPL(xhci_stop_endpoint_sync);
2927 /* Issue a configure endpoint command or evaluate context command
2928 * and wait for it to finish.
2930 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2931 struct usb_device *udev,
2932 struct xhci_command *command,
2933 bool ctx_change, bool must_succeed)
2936 unsigned long flags;
2937 struct xhci_input_control_ctx *ctrl_ctx;
2938 struct xhci_virt_device *virt_dev;
2939 struct xhci_slot_ctx *slot_ctx;
2944 spin_lock_irqsave(&xhci->lock, flags);
2946 if (xhci->xhc_state & XHCI_STATE_DYING) {
2947 spin_unlock_irqrestore(&xhci->lock, flags);
2951 virt_dev = xhci->devs[udev->slot_id];
2953 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2955 spin_unlock_irqrestore(&xhci->lock, flags);
2956 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2961 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2962 xhci_reserve_host_resources(xhci, ctrl_ctx)) {
2963 spin_unlock_irqrestore(&xhci->lock, flags);
2964 xhci_warn(xhci, "Not enough host resources, "
2965 "active endpoint contexts = %u\n",
2966 xhci->num_active_eps);
2969 if ((xhci->quirks & XHCI_SW_BW_CHECKING) && !ctx_change &&
2970 xhci_reserve_bandwidth(xhci, virt_dev, command->in_ctx)) {
2971 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2972 xhci_free_host_resources(xhci, ctrl_ctx);
2973 spin_unlock_irqrestore(&xhci->lock, flags);
2974 xhci_warn(xhci, "Not enough bandwidth\n");
2978 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
2980 trace_xhci_configure_endpoint_ctrl_ctx(ctrl_ctx);
2981 trace_xhci_configure_endpoint(slot_ctx);
2984 ret = xhci_queue_configure_endpoint(xhci, command,
2985 command->in_ctx->dma,
2986 udev->slot_id, must_succeed);
2988 ret = xhci_queue_evaluate_context(xhci, command,
2989 command->in_ctx->dma,
2990 udev->slot_id, must_succeed);
2992 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2993 xhci_free_host_resources(xhci, ctrl_ctx);
2994 spin_unlock_irqrestore(&xhci->lock, flags);
2995 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2996 "FIXME allocate a new ring segment");
2999 xhci_ring_cmd_db(xhci);
3000 spin_unlock_irqrestore(&xhci->lock, flags);
3002 /* Wait for the configure endpoint command to complete */
3003 wait_for_completion(command->completion);
3006 ret = xhci_configure_endpoint_result(xhci, udev,
3009 ret = xhci_evaluate_context_result(xhci, udev,
3012 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3013 spin_lock_irqsave(&xhci->lock, flags);
3014 /* If the command failed, remove the reserved resources.
3015 * Otherwise, clean up the estimate to include dropped eps.
3018 xhci_free_host_resources(xhci, ctrl_ctx);
3020 xhci_finish_resource_reservation(xhci, ctrl_ctx);
3021 spin_unlock_irqrestore(&xhci->lock, flags);
3026 static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
3027 struct xhci_virt_device *vdev, int i)
3029 struct xhci_virt_ep *ep = &vdev->eps[i];
3031 if (ep->ep_state & EP_HAS_STREAMS) {
3032 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
3033 xhci_get_endpoint_address(i));
3034 xhci_free_stream_info(xhci, ep->stream_info);
3035 ep->stream_info = NULL;
3036 ep->ep_state &= ~EP_HAS_STREAMS;
3040 /* Called after one or more calls to xhci_add_endpoint() or
3041 * xhci_drop_endpoint(). If this call fails, the USB core is expected
3042 * to call xhci_reset_bandwidth().
3044 * Since we are in the middle of changing either configuration or
3045 * installing a new alt setting, the USB core won't allow URBs to be
3046 * enqueued for any endpoint on the old config or interface. Nothing
3047 * else should be touching the xhci->devs[slot_id] structure, so we
3048 * don't need to take the xhci->lock for manipulating that.
3050 int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
3054 struct xhci_hcd *xhci;
3055 struct xhci_virt_device *virt_dev;
3056 struct xhci_input_control_ctx *ctrl_ctx;
3057 struct xhci_slot_ctx *slot_ctx;
3058 struct xhci_command *command;
3060 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3063 xhci = hcd_to_xhci(hcd);
3064 if ((xhci->xhc_state & XHCI_STATE_DYING) ||
3065 (xhci->xhc_state & XHCI_STATE_REMOVING))
3068 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
3069 virt_dev = xhci->devs[udev->slot_id];
3071 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
3075 command->in_ctx = virt_dev->in_ctx;
3077 /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
3078 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3080 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3083 goto command_cleanup;
3085 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
3086 ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
3087 ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
3089 /* Don't issue the command if there's no endpoints to update. */
3090 if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
3091 ctrl_ctx->drop_flags == 0) {
3093 goto command_cleanup;
3095 /* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
3096 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
3097 for (i = 31; i >= 1; i--) {
3098 __le32 le32 = cpu_to_le32(BIT(i));
3100 if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
3101 || (ctrl_ctx->add_flags & le32) || i == 1) {
3102 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
3103 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
3108 ret = xhci_configure_endpoint(xhci, udev, command,
3111 /* Callee should call reset_bandwidth() */
3112 goto command_cleanup;
3114 /* Free any rings that were dropped, but not changed. */
3115 for (i = 1; i < 31; i++) {
3116 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
3117 !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
3118 xhci_free_endpoint_ring(xhci, virt_dev, i);
3119 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
3122 xhci_zero_in_ctx(xhci, virt_dev);
3124 * Install any rings for completely new endpoints or changed endpoints,
3125 * and free any old rings from changed endpoints.
3127 for (i = 1; i < 31; i++) {
3128 if (!virt_dev->eps[i].new_ring)
3130 /* Only free the old ring if it exists.
3131 * It may not if this is the first add of an endpoint.
3133 if (virt_dev->eps[i].ring) {
3134 xhci_free_endpoint_ring(xhci, virt_dev, i);
3136 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
3137 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
3138 virt_dev->eps[i].new_ring = NULL;
3139 xhci_debugfs_create_endpoint(xhci, virt_dev, i);
3142 kfree(command->completion);
3147 EXPORT_SYMBOL_GPL(xhci_check_bandwidth);
3149 void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
3151 struct xhci_hcd *xhci;
3152 struct xhci_virt_device *virt_dev;
3155 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3158 xhci = hcd_to_xhci(hcd);
3160 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
3161 virt_dev = xhci->devs[udev->slot_id];
3162 /* Free any rings allocated for added endpoints */
3163 for (i = 0; i < 31; i++) {
3164 if (virt_dev->eps[i].new_ring) {
3165 xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
3166 xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
3167 virt_dev->eps[i].new_ring = NULL;
3170 xhci_zero_in_ctx(xhci, virt_dev);
3172 EXPORT_SYMBOL_GPL(xhci_reset_bandwidth);
3174 /* Get the available bandwidth of the ports under the xhci roothub */
3175 int xhci_get_port_bandwidth(struct xhci_hcd *xhci, struct xhci_container_ctx *ctx,
3178 struct xhci_command *cmd;
3179 unsigned long flags;
3185 cmd = xhci_alloc_command(xhci, true, GFP_KERNEL);
3191 /* get xhci port bandwidth, refer to xhci rev1_2 protocol 4.6.15 */
3192 spin_lock_irqsave(&xhci->lock, flags);
3194 ret = xhci_queue_get_port_bw(xhci, cmd, ctx->dma, dev_speed, 0);
3196 spin_unlock_irqrestore(&xhci->lock, flags);
3199 xhci_ring_cmd_db(xhci);
3200 spin_unlock_irqrestore(&xhci->lock, flags);
3202 wait_for_completion(cmd->completion);
3204 kfree(cmd->completion);
3210 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
3211 struct xhci_container_ctx *in_ctx,
3212 struct xhci_container_ctx *out_ctx,
3213 struct xhci_input_control_ctx *ctrl_ctx,
3214 u32 add_flags, u32 drop_flags)
3216 ctrl_ctx->add_flags = cpu_to_le32(add_flags);
3217 ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
3218 xhci_slot_copy(xhci, in_ctx, out_ctx);
3219 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
3222 static void xhci_endpoint_disable(struct usb_hcd *hcd,
3223 struct usb_host_endpoint *host_ep)
3225 struct xhci_hcd *xhci;
3226 struct xhci_virt_device *vdev;
3227 struct xhci_virt_ep *ep;
3228 struct usb_device *udev;
3229 unsigned long flags;
3230 unsigned int ep_index;
3232 xhci = hcd_to_xhci(hcd);
3234 spin_lock_irqsave(&xhci->lock, flags);
3236 udev = (struct usb_device *)host_ep->hcpriv;
3237 if (!udev || !udev->slot_id)
3240 vdev = xhci->devs[udev->slot_id];
3244 ep_index = xhci_get_endpoint_index(&host_ep->desc);
3245 ep = &vdev->eps[ep_index];
3247 /* wait for hub_tt_work to finish clearing hub TT */
3248 if (ep->ep_state & EP_CLEARING_TT) {
3249 spin_unlock_irqrestore(&xhci->lock, flags);
3250 schedule_timeout_uninterruptible(1);
3255 xhci_dbg(xhci, "endpoint disable with ep_state 0x%x\n",
3258 host_ep->hcpriv = NULL;
3259 spin_unlock_irqrestore(&xhci->lock, flags);
3263 * Called after usb core issues a clear halt control message.
3264 * The host side of the halt should already be cleared by a reset endpoint
3265 * command issued when the STALL event was received.
3267 * The reset endpoint command may only be issued to endpoints in the halted
3268 * state. For software that wishes to reset the data toggle or sequence number
3269 * of an endpoint that isn't in the halted state this function will issue a
3270 * configure endpoint command with the Drop and Add bits set for the target
3271 * endpoint. Refer to the additional note in xhci spcification section 4.6.8.
3273 * vdev may be lost due to xHC restore error and re-initialization during S3/S4
3274 * resume. A new vdev will be allocated later by xhci_discover_or_reset_device()
3277 static void xhci_endpoint_reset(struct usb_hcd *hcd,
3278 struct usb_host_endpoint *host_ep)
3280 struct xhci_hcd *xhci;
3281 struct usb_device *udev;
3282 struct xhci_virt_device *vdev;
3283 struct xhci_virt_ep *ep;
3284 struct xhci_input_control_ctx *ctrl_ctx;
3285 struct xhci_command *stop_cmd, *cfg_cmd;
3286 unsigned int ep_index;
3287 unsigned long flags;
3291 xhci = hcd_to_xhci(hcd);
3292 ep_index = xhci_get_endpoint_index(&host_ep->desc);
3295 * Usb core assumes a max packet value for ep0 on FS devices until the
3296 * real value is read from the descriptor. Core resets Ep0 if values
3297 * mismatch. Reconfigure the xhci ep0 endpoint context here in that case
3299 if (usb_endpoint_xfer_control(&host_ep->desc) && ep_index == 0) {
3301 udev = container_of(host_ep, struct usb_device, ep0);
3302 if (udev->speed != USB_SPEED_FULL || !udev->slot_id)
3305 vdev = xhci->devs[udev->slot_id];
3306 if (!vdev || vdev->udev != udev)
3309 xhci_check_ep0_maxpacket(xhci, vdev);
3311 /* Nothing else should be done here for ep0 during ep reset */
3315 if (!host_ep->hcpriv)
3317 udev = (struct usb_device *) host_ep->hcpriv;
3318 vdev = xhci->devs[udev->slot_id];
3320 if (!udev->slot_id || !vdev)
3323 ep = &vdev->eps[ep_index];
3325 /* Bail out if toggle is already being cleared by a endpoint reset */
3326 spin_lock_irqsave(&xhci->lock, flags);
3327 if (ep->ep_state & EP_HARD_CLEAR_TOGGLE) {
3328 ep->ep_state &= ~EP_HARD_CLEAR_TOGGLE;
3329 spin_unlock_irqrestore(&xhci->lock, flags);
3332 spin_unlock_irqrestore(&xhci->lock, flags);
3333 /* Only interrupt and bulk ep's use data toggle, USB2 spec 5.5.4-> */
3334 if (usb_endpoint_xfer_control(&host_ep->desc) ||
3335 usb_endpoint_xfer_isoc(&host_ep->desc))
3338 ep_flag = xhci_get_endpoint_flag(&host_ep->desc);
3340 if (ep_flag == SLOT_FLAG || ep_flag == EP0_FLAG)
3343 stop_cmd = xhci_alloc_command(xhci, true, GFP_NOWAIT);
3347 cfg_cmd = xhci_alloc_command_with_ctx(xhci, true, GFP_NOWAIT);
3351 spin_lock_irqsave(&xhci->lock, flags);
3353 /* block queuing new trbs and ringing ep doorbell */
3354 ep->ep_state |= EP_SOFT_CLEAR_TOGGLE;
3357 * Make sure endpoint ring is empty before resetting the toggle/seq.
3358 * Driver is required to synchronously cancel all transfer request.
3359 * Stop the endpoint to force xHC to update the output context
3362 if (!list_empty(&ep->ring->td_list)) {
3363 dev_err(&udev->dev, "EP not empty, refuse reset\n");
3364 spin_unlock_irqrestore(&xhci->lock, flags);
3365 xhci_free_command(xhci, cfg_cmd);
3369 err = xhci_queue_stop_endpoint(xhci, stop_cmd, udev->slot_id,
3372 spin_unlock_irqrestore(&xhci->lock, flags);
3373 xhci_free_command(xhci, cfg_cmd);
3374 xhci_dbg(xhci, "%s: Failed to queue stop ep command, %d ",
3379 xhci_ring_cmd_db(xhci);
3380 spin_unlock_irqrestore(&xhci->lock, flags);
3382 wait_for_completion(stop_cmd->completion);
3384 spin_lock_irqsave(&xhci->lock, flags);
3386 /* config ep command clears toggle if add and drop ep flags are set */
3387 ctrl_ctx = xhci_get_input_control_ctx(cfg_cmd->in_ctx);
3389 spin_unlock_irqrestore(&xhci->lock, flags);
3390 xhci_free_command(xhci, cfg_cmd);
3391 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3396 xhci_setup_input_ctx_for_config_ep(xhci, cfg_cmd->in_ctx, vdev->out_ctx,
3397 ctrl_ctx, ep_flag, ep_flag);
3398 xhci_endpoint_copy(xhci, cfg_cmd->in_ctx, vdev->out_ctx, ep_index);
3400 err = xhci_queue_configure_endpoint(xhci, cfg_cmd, cfg_cmd->in_ctx->dma,
3401 udev->slot_id, false);
3403 spin_unlock_irqrestore(&xhci->lock, flags);
3404 xhci_free_command(xhci, cfg_cmd);
3405 xhci_dbg(xhci, "%s: Failed to queue config ep command, %d ",
3410 xhci_ring_cmd_db(xhci);
3411 spin_unlock_irqrestore(&xhci->lock, flags);
3413 wait_for_completion(cfg_cmd->completion);
3415 xhci_free_command(xhci, cfg_cmd);
3417 xhci_free_command(xhci, stop_cmd);
3418 spin_lock_irqsave(&xhci->lock, flags);
3419 if (ep->ep_state & EP_SOFT_CLEAR_TOGGLE)
3420 ep->ep_state &= ~EP_SOFT_CLEAR_TOGGLE;
3421 spin_unlock_irqrestore(&xhci->lock, flags);
3424 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
3425 struct usb_device *udev, struct usb_host_endpoint *ep,
3426 unsigned int slot_id)
3429 unsigned int ep_index;
3430 unsigned int ep_state;
3434 ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
3436 return ret ? ret : -EINVAL;
3437 if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
3438 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
3439 " descriptor for ep 0x%x does not support streams\n",
3440 ep->desc.bEndpointAddress);
3444 ep_index = xhci_get_endpoint_index(&ep->desc);
3445 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3446 if (ep_state & EP_HAS_STREAMS ||
3447 ep_state & EP_GETTING_STREAMS) {
3448 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
3449 "already has streams set up.\n",
3450 ep->desc.bEndpointAddress);
3451 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
3452 "dynamic stream context array reallocation.\n");
3455 if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
3456 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
3457 "endpoint 0x%x; URBs are pending.\n",
3458 ep->desc.bEndpointAddress);
3464 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
3465 unsigned int *num_streams, unsigned int *num_stream_ctxs)
3467 unsigned int max_streams;
3469 /* The stream context array size must be a power of two */
3470 *num_stream_ctxs = roundup_pow_of_two(*num_streams);
3472 * Find out how many primary stream array entries the host controller
3473 * supports. Later we may use secondary stream arrays (similar to 2nd
3474 * level page entries), but that's an optional feature for xHCI host
3475 * controllers. xHCs must support at least 4 stream IDs.
3477 max_streams = HCC_MAX_PSA(xhci->hcc_params);
3478 if (*num_stream_ctxs > max_streams) {
3479 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
3481 *num_stream_ctxs = max_streams;
3482 *num_streams = max_streams;
3486 /* Returns an error code if one of the endpoint already has streams.
3487 * This does not change any data structures, it only checks and gathers
3490 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
3491 struct usb_device *udev,
3492 struct usb_host_endpoint **eps, unsigned int num_eps,
3493 unsigned int *num_streams, u32 *changed_ep_bitmask)
3495 unsigned int max_streams;
3496 unsigned int endpoint_flag;
3500 for (i = 0; i < num_eps; i++) {
3501 ret = xhci_check_streams_endpoint(xhci, udev,
3502 eps[i], udev->slot_id);
3506 max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
3507 if (max_streams < (*num_streams - 1)) {
3508 xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
3509 eps[i]->desc.bEndpointAddress,
3511 *num_streams = max_streams+1;
3514 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
3515 if (*changed_ep_bitmask & endpoint_flag)
3517 *changed_ep_bitmask |= endpoint_flag;
3522 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
3523 struct usb_device *udev,
3524 struct usb_host_endpoint **eps, unsigned int num_eps)
3526 u32 changed_ep_bitmask = 0;
3527 unsigned int slot_id;
3528 unsigned int ep_index;
3529 unsigned int ep_state;
3532 slot_id = udev->slot_id;
3533 if (!xhci->devs[slot_id])
3536 for (i = 0; i < num_eps; i++) {
3537 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3538 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3539 /* Are streams already being freed for the endpoint? */
3540 if (ep_state & EP_GETTING_NO_STREAMS) {
3541 xhci_warn(xhci, "WARN Can't disable streams for "
3543 "streams are being disabled already\n",
3544 eps[i]->desc.bEndpointAddress);
3547 /* Are there actually any streams to free? */
3548 if (!(ep_state & EP_HAS_STREAMS) &&
3549 !(ep_state & EP_GETTING_STREAMS)) {
3550 xhci_warn(xhci, "WARN Can't disable streams for "
3552 "streams are already disabled!\n",
3553 eps[i]->desc.bEndpointAddress);
3554 xhci_warn(xhci, "WARN xhci_free_streams() called "
3555 "with non-streams endpoint\n");
3558 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
3560 return changed_ep_bitmask;
3564 * The USB device drivers use this function (through the HCD interface in USB
3565 * core) to prepare a set of bulk endpoints to use streams. Streams are used to
3566 * coordinate mass storage command queueing across multiple endpoints (basically
3567 * a stream ID == a task ID).
3569 * Setting up streams involves allocating the same size stream context array
3570 * for each endpoint and issuing a configure endpoint command for all endpoints.
3572 * Don't allow the call to succeed if one endpoint only supports one stream
3573 * (which means it doesn't support streams at all).
3575 * Drivers may get less stream IDs than they asked for, if the host controller
3576 * hardware or endpoints claim they can't support the number of requested
3579 static int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3580 struct usb_host_endpoint **eps, unsigned int num_eps,
3581 unsigned int num_streams, gfp_t mem_flags)
3584 struct xhci_hcd *xhci;
3585 struct xhci_virt_device *vdev;
3586 struct xhci_command *config_cmd;
3587 struct xhci_input_control_ctx *ctrl_ctx;
3588 unsigned int ep_index;
3589 unsigned int num_stream_ctxs;
3590 unsigned int max_packet;
3591 unsigned long flags;
3592 u32 changed_ep_bitmask = 0;
3597 /* Add one to the number of streams requested to account for
3598 * stream 0 that is reserved for xHCI usage.
3601 xhci = hcd_to_xhci(hcd);
3602 xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3605 /* MaxPSASize value 0 (2 streams) means streams are not supported */
3606 if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
3607 HCC_MAX_PSA(xhci->hcc_params) < 4) {
3608 xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3612 config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
3616 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
3618 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3620 xhci_free_command(xhci, config_cmd);
3624 /* Check to make sure all endpoints are not already configured for
3625 * streams. While we're at it, find the maximum number of streams that
3626 * all the endpoints will support and check for duplicate endpoints.
3628 spin_lock_irqsave(&xhci->lock, flags);
3629 ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3630 num_eps, &num_streams, &changed_ep_bitmask);
3632 xhci_free_command(xhci, config_cmd);
3633 spin_unlock_irqrestore(&xhci->lock, flags);
3636 if (num_streams <= 1) {
3637 xhci_warn(xhci, "WARN: endpoints can't handle "
3638 "more than one stream.\n");
3639 xhci_free_command(xhci, config_cmd);
3640 spin_unlock_irqrestore(&xhci->lock, flags);
3643 vdev = xhci->devs[udev->slot_id];
3644 /* Mark each endpoint as being in transition, so
3645 * xhci_urb_enqueue() will reject all URBs.
3647 for (i = 0; i < num_eps; i++) {
3648 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3649 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3651 spin_unlock_irqrestore(&xhci->lock, flags);
3653 /* Setup internal data structures and allocate HW data structures for
3654 * streams (but don't install the HW structures in the input context
3655 * until we're sure all memory allocation succeeded).
3657 xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3658 xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3659 num_stream_ctxs, num_streams);
3661 for (i = 0; i < num_eps; i++) {
3662 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3663 max_packet = usb_endpoint_maxp(&eps[i]->desc);
3664 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3667 max_packet, mem_flags);
3668 if (!vdev->eps[ep_index].stream_info)
3670 /* Set maxPstreams in endpoint context and update deq ptr to
3671 * point to stream context array. FIXME
3675 /* Set up the input context for a configure endpoint command. */
3676 for (i = 0; i < num_eps; i++) {
3677 struct xhci_ep_ctx *ep_ctx;
3679 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3680 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3682 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3683 vdev->out_ctx, ep_index);
3684 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3685 vdev->eps[ep_index].stream_info);
3687 /* Tell the HW to drop its old copy of the endpoint context info
3688 * and add the updated copy from the input context.
3690 xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3691 vdev->out_ctx, ctrl_ctx,
3692 changed_ep_bitmask, changed_ep_bitmask);
3694 /* Issue and wait for the configure endpoint command */
3695 ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3698 /* xHC rejected the configure endpoint command for some reason, so we
3699 * leave the old ring intact and free our internal streams data
3705 spin_lock_irqsave(&xhci->lock, flags);
3706 for (i = 0; i < num_eps; i++) {
3707 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3708 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3709 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3710 udev->slot_id, ep_index);
3711 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3713 xhci_free_command(xhci, config_cmd);
3714 spin_unlock_irqrestore(&xhci->lock, flags);
3716 for (i = 0; i < num_eps; i++) {
3717 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3718 xhci_debugfs_create_stream_files(xhci, vdev, ep_index);
3720 /* Subtract 1 for stream 0, which drivers can't use */
3721 return num_streams - 1;
3724 /* If it didn't work, free the streams! */
3725 for (i = 0; i < num_eps; i++) {
3726 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3727 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3728 vdev->eps[ep_index].stream_info = NULL;
3729 /* FIXME Unset maxPstreams in endpoint context and
3730 * update deq ptr to point to normal string ring.
3732 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3733 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3734 xhci_endpoint_zero(xhci, vdev, eps[i]);
3736 xhci_free_command(xhci, config_cmd);
3740 /* Transition the endpoint from using streams to being a "normal" endpoint
3743 * Modify the endpoint context state, submit a configure endpoint command,
3744 * and free all endpoint rings for streams if that completes successfully.
3746 static int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3747 struct usb_host_endpoint **eps, unsigned int num_eps,
3751 struct xhci_hcd *xhci;
3752 struct xhci_virt_device *vdev;
3753 struct xhci_command *command;
3754 struct xhci_input_control_ctx *ctrl_ctx;
3755 unsigned int ep_index;
3756 unsigned long flags;
3757 u32 changed_ep_bitmask;
3759 xhci = hcd_to_xhci(hcd);
3760 vdev = xhci->devs[udev->slot_id];
3762 /* Set up a configure endpoint command to remove the streams rings */
3763 spin_lock_irqsave(&xhci->lock, flags);
3764 changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3765 udev, eps, num_eps);
3766 if (changed_ep_bitmask == 0) {
3767 spin_unlock_irqrestore(&xhci->lock, flags);
3771 /* Use the xhci_command structure from the first endpoint. We may have
3772 * allocated too many, but the driver may call xhci_free_streams() for
3773 * each endpoint it grouped into one call to xhci_alloc_streams().
3775 ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3776 command = vdev->eps[ep_index].stream_info->free_streams_command;
3777 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3779 spin_unlock_irqrestore(&xhci->lock, flags);
3780 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3785 for (i = 0; i < num_eps; i++) {
3786 struct xhci_ep_ctx *ep_ctx;
3788 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3789 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3790 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3791 EP_GETTING_NO_STREAMS;
3793 xhci_endpoint_copy(xhci, command->in_ctx,
3794 vdev->out_ctx, ep_index);
3795 xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3796 &vdev->eps[ep_index]);
3798 xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3799 vdev->out_ctx, ctrl_ctx,
3800 changed_ep_bitmask, changed_ep_bitmask);
3801 spin_unlock_irqrestore(&xhci->lock, flags);
3803 /* Issue and wait for the configure endpoint command,
3804 * which must succeed.
3806 ret = xhci_configure_endpoint(xhci, udev, command,
3809 /* xHC rejected the configure endpoint command for some reason, so we
3810 * leave the streams rings intact.
3815 spin_lock_irqsave(&xhci->lock, flags);
3816 for (i = 0; i < num_eps; i++) {
3817 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3818 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3819 vdev->eps[ep_index].stream_info = NULL;
3820 /* FIXME Unset maxPstreams in endpoint context and
3821 * update deq ptr to point to normal string ring.
3823 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3824 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3826 spin_unlock_irqrestore(&xhci->lock, flags);
3832 * Deletes endpoint resources for endpoints that were active before a Reset
3833 * Device command, or a Disable Slot command. The Reset Device command leaves
3834 * the control endpoint intact, whereas the Disable Slot command deletes it.
3836 * Must be called with xhci->lock held.
3838 void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3839 struct xhci_virt_device *virt_dev, bool drop_control_ep)
3842 unsigned int num_dropped_eps = 0;
3843 unsigned int drop_flags = 0;
3845 for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3846 if (virt_dev->eps[i].ring) {
3847 drop_flags |= 1 << i;
3851 xhci->num_active_eps -= num_dropped_eps;
3852 if (num_dropped_eps)
3853 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3854 "Dropped %u ep ctxs, flags = 0x%x, "
3856 num_dropped_eps, drop_flags,
3857 xhci->num_active_eps);
3860 static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev);
3863 * This submits a Reset Device Command, which will set the device state to 0,
3864 * set the device address to 0, and disable all the endpoints except the default
3865 * control endpoint. The USB core should come back and call
3866 * xhci_address_device(), and then re-set up the configuration. If this is
3867 * called because of a usb_reset_and_verify_device(), then the old alternate
3868 * settings will be re-installed through the normal bandwidth allocation
3871 * Wait for the Reset Device command to finish. Remove all structures
3872 * associated with the endpoints that were disabled. Clear the input device
3873 * structure? Reset the control endpoint 0 max packet size?
3875 * If the virt_dev to be reset does not exist or does not match the udev,
3876 * it means the device is lost, possibly due to the xHC restore error and
3877 * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3878 * re-allocate the device.
3880 static int xhci_discover_or_reset_device(struct usb_hcd *hcd,
3881 struct usb_device *udev)
3884 unsigned long flags;
3885 struct xhci_hcd *xhci;
3886 unsigned int slot_id;
3887 struct xhci_virt_device *virt_dev;
3888 struct xhci_command *reset_device_cmd;
3889 struct xhci_slot_ctx *slot_ctx;
3890 int old_active_eps = 0;
3892 ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3895 xhci = hcd_to_xhci(hcd);
3896 slot_id = udev->slot_id;
3897 virt_dev = xhci->devs[slot_id];
3899 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3900 "not exist. Re-allocate the device\n", slot_id);
3901 ret = xhci_alloc_dev(hcd, udev);
3908 if (virt_dev->tt_info)
3909 old_active_eps = virt_dev->tt_info->active_eps;
3911 if (virt_dev->udev != udev) {
3912 /* If the virt_dev and the udev does not match, this virt_dev
3913 * may belong to another udev.
3914 * Re-allocate the device.
3916 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3917 "not match the udev. Re-allocate the device\n",
3919 ret = xhci_alloc_dev(hcd, udev);
3926 /* If device is not setup, there is no point in resetting it */
3927 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3928 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3929 SLOT_STATE_DISABLED)
3932 if (xhci->quirks & XHCI_ETRON_HOST) {
3934 * Obtaining a new device slot to inform the xHCI host that
3935 * the USB device has been reset.
3937 ret = xhci_disable_and_free_slot(xhci, udev->slot_id);
3939 ret = xhci_alloc_dev(hcd, udev);
3948 trace_xhci_discover_or_reset_device(slot_ctx);
3950 xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3951 /* Allocate the command structure that holds the struct completion.
3952 * Assume we're in process context, since the normal device reset
3953 * process has to wait for the device anyway. Storage devices are
3954 * reset as part of error handling, so use GFP_NOIO instead of
3957 reset_device_cmd = xhci_alloc_command(xhci, true, GFP_NOIO);
3958 if (!reset_device_cmd) {
3959 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3963 /* Attempt to submit the Reset Device command to the command ring */
3964 spin_lock_irqsave(&xhci->lock, flags);
3966 ret = xhci_queue_reset_device(xhci, reset_device_cmd, slot_id);
3968 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3969 spin_unlock_irqrestore(&xhci->lock, flags);
3970 goto command_cleanup;
3972 xhci_ring_cmd_db(xhci);
3973 spin_unlock_irqrestore(&xhci->lock, flags);
3975 /* Wait for the Reset Device command to finish */
3976 wait_for_completion(reset_device_cmd->completion);
3978 /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3979 * unless we tried to reset a slot ID that wasn't enabled,
3980 * or the device wasn't in the addressed or configured state.
3982 ret = reset_device_cmd->status;
3984 case COMP_COMMAND_ABORTED:
3985 case COMP_COMMAND_RING_STOPPED:
3986 xhci_warn(xhci, "Timeout waiting for reset device command\n");
3988 goto command_cleanup;
3989 case COMP_SLOT_NOT_ENABLED_ERROR: /* 0.95 completion for bad slot ID */
3990 case COMP_CONTEXT_STATE_ERROR: /* 0.96 completion code for same thing */
3991 xhci_dbg(xhci, "Can't reset device (slot ID %u) in %s state\n",
3993 xhci_get_slot_state(xhci, virt_dev->out_ctx));
3994 xhci_dbg(xhci, "Not freeing device rings.\n");
3995 /* Don't treat this as an error. May change my mind later. */
3997 goto command_cleanup;
3999 xhci_dbg(xhci, "Successful reset device command.\n");
4002 if (xhci_is_vendor_info_code(xhci, ret))
4004 xhci_warn(xhci, "Unknown completion code %u for "
4005 "reset device command.\n", ret);
4007 goto command_cleanup;
4010 /* Free up host controller endpoint resources */
4011 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
4012 spin_lock_irqsave(&xhci->lock, flags);
4013 /* Don't delete the default control endpoint resources */
4014 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
4015 spin_unlock_irqrestore(&xhci->lock, flags);
4018 /* Everything but endpoint 0 is disabled, so free the rings. */
4019 for (i = 1; i < 31; i++) {
4020 struct xhci_virt_ep *ep = &virt_dev->eps[i];
4022 if (ep->ep_state & EP_HAS_STREAMS) {
4023 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
4024 xhci_get_endpoint_address(i));
4025 xhci_free_stream_info(xhci, ep->stream_info);
4026 ep->stream_info = NULL;
4027 ep->ep_state &= ~EP_HAS_STREAMS;
4032 xhci_sideband_notify_ep_ring_free(ep->sideband, i);
4033 xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
4034 xhci_free_endpoint_ring(xhci, virt_dev, i);
4036 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
4037 xhci_drop_ep_from_interval_table(xhci,
4038 &virt_dev->eps[i].bw_info,
4043 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
4045 /* If necessary, update the number of active TTs on this root port */
4046 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
4047 virt_dev->flags = 0;
4051 xhci_free_command(xhci, reset_device_cmd);
4056 * At this point, the struct usb_device is about to go away, the device has
4057 * disconnected, and all traffic has been stopped and the endpoints have been
4058 * disabled. Free any HC data structures associated with that device.
4060 static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
4062 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4063 struct xhci_virt_device *virt_dev;
4064 struct xhci_slot_ctx *slot_ctx;
4065 unsigned long flags;
4069 * We called pm_runtime_get_noresume when the device was attached.
4070 * Decrement the counter here to allow controller to runtime suspend
4071 * if no devices remain.
4073 if (xhci->quirks & XHCI_RESET_ON_RESUME)
4074 pm_runtime_put_noidle(hcd->self.controller);
4076 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
4077 /* If the host is halted due to driver unload, we still need to free the
4080 if (ret <= 0 && ret != -ENODEV)
4083 virt_dev = xhci->devs[udev->slot_id];
4084 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4085 trace_xhci_free_dev(slot_ctx);
4087 /* Stop any wayward timer functions (which may grab the lock) */
4088 for (i = 0; i < 31; i++)
4089 virt_dev->eps[i].ep_state &= ~EP_STOP_CMD_PENDING;
4090 virt_dev->udev = NULL;
4091 xhci_disable_slot(xhci, udev->slot_id);
4093 spin_lock_irqsave(&xhci->lock, flags);
4094 xhci_free_virt_device(xhci, virt_dev, udev->slot_id);
4095 spin_unlock_irqrestore(&xhci->lock, flags);
4099 int xhci_disable_slot(struct xhci_hcd *xhci, u32 slot_id)
4101 struct xhci_command *command;
4102 unsigned long flags;
4106 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4110 xhci_debugfs_remove_slot(xhci, slot_id);
4112 spin_lock_irqsave(&xhci->lock, flags);
4113 /* Don't disable the slot if the host controller is dead. */
4114 state = readl(&xhci->op_regs->status);
4115 if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
4116 (xhci->xhc_state & XHCI_STATE_HALTED)) {
4117 spin_unlock_irqrestore(&xhci->lock, flags);
4122 ret = xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
4125 spin_unlock_irqrestore(&xhci->lock, flags);
4129 xhci_ring_cmd_db(xhci);
4130 spin_unlock_irqrestore(&xhci->lock, flags);
4132 wait_for_completion(command->completion);
4134 if (command->status != COMP_SUCCESS)
4135 xhci_warn(xhci, "Unsuccessful disable slot %u command, status %d\n",
4136 slot_id, command->status);
4138 xhci_free_command(xhci, command);
4143 int xhci_disable_and_free_slot(struct xhci_hcd *xhci, u32 slot_id)
4145 struct xhci_virt_device *vdev = xhci->devs[slot_id];
4148 ret = xhci_disable_slot(xhci, slot_id);
4149 xhci_free_virt_device(xhci, vdev, slot_id);
4154 * Checks if we have enough host controller resources for the default control
4157 * Must be called with xhci->lock held.
4159 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
4161 if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
4162 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
4163 "Not enough ep ctxs: "
4164 "%u active, need to add 1, limit is %u.",
4165 xhci->num_active_eps, xhci->limit_active_eps);
4168 xhci->num_active_eps += 1;
4169 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
4170 "Adding 1 ep ctx, %u now active.",
4171 xhci->num_active_eps);
4177 * Returns 0 if the xHC ran out of device slots, the Enable Slot command
4178 * timed out, or allocating memory failed. Returns 1 on success.
4180 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
4182 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4183 struct xhci_virt_device *vdev;
4184 struct xhci_slot_ctx *slot_ctx;
4185 unsigned long flags;
4187 struct xhci_command *command;
4189 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4193 spin_lock_irqsave(&xhci->lock, flags);
4194 ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
4196 spin_unlock_irqrestore(&xhci->lock, flags);
4197 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
4198 xhci_free_command(xhci, command);
4201 xhci_ring_cmd_db(xhci);
4202 spin_unlock_irqrestore(&xhci->lock, flags);
4204 wait_for_completion(command->completion);
4205 slot_id = command->slot_id;
4207 if (!slot_id || command->status != COMP_SUCCESS) {
4208 xhci_err(xhci, "Error while assigning device slot ID: %s\n",
4209 xhci_trb_comp_code_string(command->status));
4210 xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
4212 readl(&xhci->cap_regs->hcs_params1)));
4213 xhci_free_command(xhci, command);
4217 xhci_free_command(xhci, command);
4219 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
4220 spin_lock_irqsave(&xhci->lock, flags);
4221 ret = xhci_reserve_host_control_ep_resources(xhci);
4223 spin_unlock_irqrestore(&xhci->lock, flags);
4224 xhci_warn(xhci, "Not enough host resources, "
4225 "active endpoint contexts = %u\n",
4226 xhci->num_active_eps);
4229 spin_unlock_irqrestore(&xhci->lock, flags);
4231 /* Use GFP_NOIO, since this function can be called from
4232 * xhci_discover_or_reset_device(), which may be called as part of
4233 * mass storage driver error handling.
4235 if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) {
4236 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
4239 vdev = xhci->devs[slot_id];
4240 slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
4241 trace_xhci_alloc_dev(slot_ctx);
4243 udev->slot_id = slot_id;
4245 xhci_debugfs_create_slot(xhci, slot_id);
4248 * If resetting upon resume, we can't put the controller into runtime
4249 * suspend if there is a device attached.
4251 if (xhci->quirks & XHCI_RESET_ON_RESUME)
4252 pm_runtime_get_noresume(hcd->self.controller);
4254 /* Is this a LS or FS device under a HS hub? */
4255 /* Hub or peripherial? */
4259 xhci_disable_and_free_slot(xhci, udev->slot_id);
4265 * xhci_setup_device - issues an Address Device command to assign a unique
4267 * @hcd: USB host controller data structure.
4268 * @udev: USB dev structure representing the connected device.
4269 * @setup: Enum specifying setup mode: address only or with context.
4270 * @timeout_ms: Max wait time (ms) for the command operation to complete.
4272 * Return: 0 if successful; otherwise, negative error code.
4274 static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
4275 enum xhci_setup_dev setup, unsigned int timeout_ms)
4277 const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
4278 unsigned long flags;
4279 struct xhci_virt_device *virt_dev;
4281 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4282 struct xhci_slot_ctx *slot_ctx;
4283 struct xhci_input_control_ctx *ctrl_ctx;
4285 struct xhci_command *command = NULL;
4287 mutex_lock(&xhci->mutex);
4289 if (xhci->xhc_state) { /* dying, removing or halted */
4294 if (!udev->slot_id) {
4295 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4296 "Bad Slot ID %d", udev->slot_id);
4301 virt_dev = xhci->devs[udev->slot_id];
4303 if (WARN_ON(!virt_dev)) {
4305 * In plug/unplug torture test with an NEC controller,
4306 * a zero-dereference was observed once due to virt_dev = 0.
4307 * Print useful debug rather than crash if it is observed again!
4309 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
4314 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4315 trace_xhci_setup_device_slot(slot_ctx);
4317 if (setup == SETUP_CONTEXT_ONLY) {
4318 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
4319 SLOT_STATE_DEFAULT) {
4320 xhci_dbg(xhci, "Slot already in default state\n");
4325 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4331 command->in_ctx = virt_dev->in_ctx;
4332 command->timeout_ms = timeout_ms;
4334 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
4335 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
4337 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4343 * If this is the first Set Address since device plug-in or
4344 * virt_device realloaction after a resume with an xHCI power loss,
4345 * then set up the slot context.
4347 if (!slot_ctx->dev_info)
4348 xhci_setup_addressable_virt_dev(xhci, udev);
4349 /* Otherwise, update the control endpoint ring enqueue pointer. */
4351 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
4352 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
4353 ctrl_ctx->drop_flags = 0;
4355 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4356 le32_to_cpu(slot_ctx->dev_info) >> 27);
4358 trace_xhci_address_ctrl_ctx(ctrl_ctx);
4359 spin_lock_irqsave(&xhci->lock, flags);
4360 trace_xhci_setup_device(virt_dev);
4361 ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
4362 udev->slot_id, setup);
4364 spin_unlock_irqrestore(&xhci->lock, flags);
4365 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4366 "FIXME: allocate a command ring segment");
4369 xhci_ring_cmd_db(xhci);
4370 spin_unlock_irqrestore(&xhci->lock, flags);
4372 /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
4373 wait_for_completion(command->completion);
4375 /* FIXME: From section 4.3.4: "Software shall be responsible for timing
4376 * the SetAddress() "recovery interval" required by USB and aborting the
4377 * command on a timeout.
4379 switch (command->status) {
4380 case COMP_COMMAND_ABORTED:
4381 case COMP_COMMAND_RING_STOPPED:
4382 xhci_warn(xhci, "Timeout while waiting for setup device command\n");
4385 case COMP_CONTEXT_STATE_ERROR:
4386 case COMP_SLOT_NOT_ENABLED_ERROR:
4387 xhci_err(xhci, "Setup ERROR: setup %s command for slot %d.\n",
4388 act, udev->slot_id);
4391 case COMP_USB_TRANSACTION_ERROR:
4392 dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
4394 mutex_unlock(&xhci->mutex);
4395 ret = xhci_disable_and_free_slot(xhci, udev->slot_id);
4397 if (xhci_alloc_dev(hcd, udev) == 1)
4398 xhci_setup_addressable_virt_dev(xhci, udev);
4400 kfree(command->completion);
4403 case COMP_INCOMPATIBLE_DEVICE_ERROR:
4404 dev_warn(&udev->dev,
4405 "ERROR: Incompatible device for setup %s command\n", act);
4409 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4410 "Successful setup %s command", act);
4414 "ERROR: unexpected setup %s command completion code 0x%x.\n",
4415 act, command->status);
4416 trace_xhci_address_ctx(xhci, virt_dev->out_ctx, 1);
4422 temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
4423 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4424 "Op regs DCBAA ptr = %#016llx", temp_64);
4425 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4426 "Slot ID %d dcbaa entry @%p = %#016llx",
4428 &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
4429 (unsigned long long)
4430 le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
4431 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4432 "Output Context DMA address = %#08llx",
4433 (unsigned long long)virt_dev->out_ctx->dma);
4434 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4435 le32_to_cpu(slot_ctx->dev_info) >> 27);
4437 * USB core uses address 1 for the roothubs, so we add one to the
4438 * address given back to us by the HC.
4440 trace_xhci_address_ctx(xhci, virt_dev->out_ctx,
4441 le32_to_cpu(slot_ctx->dev_info) >> 27);
4442 /* Zero the input context control for later use */
4443 ctrl_ctx->add_flags = 0;
4444 ctrl_ctx->drop_flags = 0;
4445 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4446 udev->devaddr = (u8)(le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4448 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4449 "Internal device address = %d",
4450 le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4452 mutex_unlock(&xhci->mutex);
4454 kfree(command->completion);
4460 static int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev,
4461 unsigned int timeout_ms)
4463 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ADDRESS, timeout_ms);
4466 static int xhci_enable_device(struct usb_hcd *hcd, struct usb_device *udev)
4468 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ONLY,
4469 XHCI_CMD_DEFAULT_TIMEOUT);
4473 * Transfer the port index into real index in the HW port status
4474 * registers. Caculate offset between the port's PORTSC register
4475 * and port status base. Divide the number of per port register
4476 * to get the real index. The raw port number bases 1.
4478 int xhci_find_raw_port_number(struct usb_hcd *hcd, int port1)
4480 struct xhci_hub *rhub;
4482 rhub = xhci_get_rhub(hcd);
4483 return rhub->ports[port1 - 1]->hw_portnum + 1;
4487 * Issue an Evaluate Context command to change the Maximum Exit Latency in the
4488 * slot context. If that succeeds, store the new MEL in the xhci_virt_device.
4490 static int __maybe_unused xhci_change_max_exit_latency(struct xhci_hcd *xhci,
4491 struct usb_device *udev, u16 max_exit_latency)
4493 struct xhci_virt_device *virt_dev;
4494 struct xhci_command *command;
4495 struct xhci_input_control_ctx *ctrl_ctx;
4496 struct xhci_slot_ctx *slot_ctx;
4497 unsigned long flags;
4500 command = xhci_alloc_command_with_ctx(xhci, true, GFP_KERNEL);
4504 spin_lock_irqsave(&xhci->lock, flags);
4506 virt_dev = xhci->devs[udev->slot_id];
4509 * virt_dev might not exists yet if xHC resumed from hibernate (S4) and
4510 * xHC was re-initialized. Exit latency will be set later after
4511 * hub_port_finish_reset() is done and xhci->devs[] are re-allocated
4514 if (!virt_dev || max_exit_latency == virt_dev->current_mel) {
4515 spin_unlock_irqrestore(&xhci->lock, flags);
4516 xhci_free_command(xhci, command);
4520 /* Attempt to issue an Evaluate Context command to change the MEL. */
4521 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
4523 spin_unlock_irqrestore(&xhci->lock, flags);
4524 xhci_free_command(xhci, command);
4525 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4530 xhci_slot_copy(xhci, command->in_ctx, virt_dev->out_ctx);
4531 spin_unlock_irqrestore(&xhci->lock, flags);
4533 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4534 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
4535 slot_ctx->dev_info2 &= cpu_to_le32(~((u32) MAX_EXIT));
4536 slot_ctx->dev_info2 |= cpu_to_le32(max_exit_latency);
4537 slot_ctx->dev_state = 0;
4539 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
4540 "Set up evaluate context for LPM MEL change.");
4542 /* Issue and wait for the evaluate context command. */
4543 ret = xhci_configure_endpoint(xhci, udev, command,
4547 spin_lock_irqsave(&xhci->lock, flags);
4548 virt_dev->current_mel = max_exit_latency;
4549 spin_unlock_irqrestore(&xhci->lock, flags);
4552 xhci_free_command(xhci, command);
4559 /* BESL to HIRD Encoding array for USB2 LPM */
4560 static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
4561 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
4563 /* Calculate HIRD/BESL for USB2 PORTPMSC*/
4564 static int xhci_calculate_hird_besl(struct xhci_hcd *xhci,
4565 struct usb_device *udev)
4567 int u2del, besl, besl_host;
4568 int besl_device = 0;
4571 u2del = HCS_U2_LATENCY(xhci->hcs_params3);
4572 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4574 if (field & USB_BESL_SUPPORT) {
4575 for (besl_host = 0; besl_host < 16; besl_host++) {
4576 if (xhci_besl_encoding[besl_host] >= u2del)
4579 /* Use baseline BESL value as default */
4580 if (field & USB_BESL_BASELINE_VALID)
4581 besl_device = USB_GET_BESL_BASELINE(field);
4582 else if (field & USB_BESL_DEEP_VALID)
4583 besl_device = USB_GET_BESL_DEEP(field);
4588 besl_host = (u2del - 51) / 75 + 1;
4591 besl = besl_host + besl_device;
4598 /* Calculate BESLD, L1 timeout and HIRDM for USB2 PORTHLPMC */
4599 static int xhci_calculate_usb2_hw_lpm_params(struct usb_device *udev)
4606 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4608 /* xHCI l1 is set in steps of 256us, xHCI 1.0 section 5.4.11.2 */
4609 l1 = udev->l1_params.timeout / 256;
4611 /* device has preferred BESLD */
4612 if (field & USB_BESL_DEEP_VALID) {
4613 besld = USB_GET_BESL_DEEP(field);
4617 return PORT_BESLD(besld) | PORT_L1_TIMEOUT(l1) | PORT_HIRDM(hirdm);
4620 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4621 struct usb_device *udev, int enable)
4623 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4624 struct xhci_port **ports;
4625 __le32 __iomem *pm_addr, *hlpm_addr;
4626 u32 pm_val, hlpm_val, field;
4627 unsigned int port_num;
4628 unsigned long flags;
4629 int hird, exit_latency;
4632 if (xhci->quirks & XHCI_HW_LPM_DISABLE)
4635 if (hcd->speed >= HCD_USB3 || !xhci->hw_lpm_support ||
4639 if (!udev->parent || udev->parent->parent ||
4640 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4643 if (udev->usb2_hw_lpm_capable != 1)
4646 spin_lock_irqsave(&xhci->lock, flags);
4648 ports = xhci->usb2_rhub.ports;
4649 port_num = udev->portnum - 1;
4650 pm_addr = ports[port_num]->addr + PORTPMSC;
4651 pm_val = readl(pm_addr);
4652 hlpm_addr = ports[port_num]->addr + PORTHLPMC;
4654 xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
4655 str_enable_disable(enable), port_num + 1);
4658 /* Host supports BESL timeout instead of HIRD */
4659 if (udev->usb2_hw_lpm_besl_capable) {
4660 /* if device doesn't have a preferred BESL value use a
4661 * default one which works with mixed HIRD and BESL
4662 * systems. See XHCI_DEFAULT_BESL definition in xhci.h
4664 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4665 if ((field & USB_BESL_SUPPORT) &&
4666 (field & USB_BESL_BASELINE_VALID))
4667 hird = USB_GET_BESL_BASELINE(field);
4669 hird = udev->l1_params.besl;
4671 exit_latency = xhci_besl_encoding[hird];
4672 spin_unlock_irqrestore(&xhci->lock, flags);
4674 ret = xhci_change_max_exit_latency(xhci, udev,
4678 spin_lock_irqsave(&xhci->lock, flags);
4680 hlpm_val = xhci_calculate_usb2_hw_lpm_params(udev);
4681 writel(hlpm_val, hlpm_addr);
4685 hird = xhci_calculate_hird_besl(xhci, udev);
4688 pm_val &= ~PORT_HIRD_MASK;
4689 pm_val |= PORT_HIRD(hird) | PORT_RWE | PORT_L1DS(udev->slot_id);
4690 writel(pm_val, pm_addr);
4691 pm_val = readl(pm_addr);
4693 writel(pm_val, pm_addr);
4697 pm_val &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK | PORT_L1DS_MASK);
4698 writel(pm_val, pm_addr);
4701 if (udev->usb2_hw_lpm_besl_capable) {
4702 spin_unlock_irqrestore(&xhci->lock, flags);
4703 xhci_change_max_exit_latency(xhci, udev, 0);
4704 readl_poll_timeout(ports[port_num]->addr, pm_val,
4705 (pm_val & PORT_PLS_MASK) == XDEV_U0,
4711 spin_unlock_irqrestore(&xhci->lock, flags);
4715 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4717 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4718 struct xhci_port *port;
4721 /* Check if USB3 device at root port is tunneled over USB4 */
4722 if (hcd->speed >= HCD_USB3 && !udev->parent->parent) {
4723 port = xhci->usb3_rhub.ports[udev->portnum - 1];
4725 udev->tunnel_mode = xhci_port_is_tunneled(xhci, port);
4726 if (udev->tunnel_mode == USB_LINK_UNKNOWN)
4727 dev_dbg(&udev->dev, "link tunnel state unknown\n");
4728 else if (udev->tunnel_mode == USB_LINK_TUNNELED)
4729 dev_dbg(&udev->dev, "tunneled over USB4 link\n");
4730 else if (udev->tunnel_mode == USB_LINK_NATIVE)
4731 dev_dbg(&udev->dev, "native USB 3.x link\n");
4735 if (hcd->speed >= HCD_USB3 || !udev->lpm_capable || !xhci->hw_lpm_support)
4738 /* we only support lpm for non-hub device connected to root hub yet */
4739 if (!udev->parent || udev->parent->parent ||
4740 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4743 port = xhci->usb2_rhub.ports[udev->portnum - 1];
4744 capability = port->port_cap->protocol_caps;
4746 if (capability & XHCI_HLC) {
4747 udev->usb2_hw_lpm_capable = 1;
4748 udev->l1_params.timeout = XHCI_L1_TIMEOUT;
4749 udev->l1_params.besl = XHCI_DEFAULT_BESL;
4750 if (capability & XHCI_BLC)
4751 udev->usb2_hw_lpm_besl_capable = 1;
4757 /*---------------------- USB 3.0 Link PM functions ------------------------*/
4759 /* Service interval in nanoseconds = 2^(bInterval - 1) * 125us * 1000ns / 1us */
4760 static unsigned long long xhci_service_interval_to_ns(
4761 struct usb_endpoint_descriptor *desc)
4763 return (1ULL << (desc->bInterval - 1)) * 125 * 1000;
4766 static u16 xhci_get_timeout_no_hub_lpm(struct usb_device *udev,
4767 enum usb3_link_state state)
4769 unsigned long long sel;
4770 unsigned long long pel;
4771 unsigned int max_sel_pel;
4776 /* Convert SEL and PEL stored in nanoseconds to microseconds */
4777 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4778 pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4779 max_sel_pel = USB3_LPM_MAX_U1_SEL_PEL;
4783 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4784 pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4785 max_sel_pel = USB3_LPM_MAX_U2_SEL_PEL;
4789 dev_warn(&udev->dev, "%s: Can't get timeout for non-U1 or U2 state.\n",
4791 return USB3_LPM_DISABLED;
4794 if (sel <= max_sel_pel && pel <= max_sel_pel)
4795 return USB3_LPM_DEVICE_INITIATED;
4797 if (sel > max_sel_pel)
4798 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4799 "due to long SEL %llu ms\n",
4802 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4803 "due to long PEL %llu ms\n",
4805 return USB3_LPM_DISABLED;
4808 /* The U1 timeout should be the maximum of the following values:
4809 * - For control endpoints, U1 system exit latency (SEL) * 3
4810 * - For bulk endpoints, U1 SEL * 5
4811 * - For interrupt endpoints:
4812 * - Notification EPs, U1 SEL * 3
4813 * - Periodic EPs, max(105% of bInterval, U1 SEL * 2)
4814 * - For isochronous endpoints, max(105% of bInterval, U1 SEL * 2)
4816 static unsigned long long xhci_calculate_intel_u1_timeout(
4817 struct usb_device *udev,
4818 struct usb_endpoint_descriptor *desc)
4820 unsigned long long timeout_ns;
4824 ep_type = usb_endpoint_type(desc);
4826 case USB_ENDPOINT_XFER_CONTROL:
4827 timeout_ns = udev->u1_params.sel * 3;
4829 case USB_ENDPOINT_XFER_BULK:
4830 timeout_ns = udev->u1_params.sel * 5;
4832 case USB_ENDPOINT_XFER_INT:
4833 intr_type = usb_endpoint_interrupt_type(desc);
4834 if (intr_type == USB_ENDPOINT_INTR_NOTIFICATION) {
4835 timeout_ns = udev->u1_params.sel * 3;
4838 /* Otherwise the calculation is the same as isoc eps */
4840 case USB_ENDPOINT_XFER_ISOC:
4841 timeout_ns = xhci_service_interval_to_ns(desc);
4842 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns * 105, 100);
4843 if (timeout_ns < udev->u1_params.sel * 2)
4844 timeout_ns = udev->u1_params.sel * 2;
4853 /* Returns the hub-encoded U1 timeout value. */
4854 static u16 xhci_calculate_u1_timeout(struct xhci_hcd *xhci,
4855 struct usb_device *udev,
4856 struct usb_endpoint_descriptor *desc)
4858 unsigned long long timeout_ns;
4860 /* Prevent U1 if service interval is shorter than U1 exit latency */
4861 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4862 if (xhci_service_interval_to_ns(desc) <= udev->u1_params.mel) {
4863 dev_dbg(&udev->dev, "Disable U1, ESIT shorter than exit latency\n");
4864 return USB3_LPM_DISABLED;
4868 if (xhci->quirks & (XHCI_INTEL_HOST | XHCI_ZHAOXIN_HOST))
4869 timeout_ns = xhci_calculate_intel_u1_timeout(udev, desc);
4871 timeout_ns = udev->u1_params.sel;
4873 /* The U1 timeout is encoded in 1us intervals.
4874 * Don't return a timeout of zero, because that's USB3_LPM_DISABLED.
4876 if (timeout_ns == USB3_LPM_DISABLED)
4879 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 1000);
4881 /* If the necessary timeout value is bigger than what we can set in the
4882 * USB 3.0 hub, we have to disable hub-initiated U1.
4884 if (timeout_ns <= USB3_LPM_U1_MAX_TIMEOUT)
4886 dev_dbg(&udev->dev, "Hub-initiated U1 disabled due to long timeout %lluus\n",
4888 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U1);
4891 /* The U2 timeout should be the maximum of:
4892 * - 10 ms (to avoid the bandwidth impact on the scheduler)
4893 * - largest bInterval of any active periodic endpoint (to avoid going
4894 * into lower power link states between intervals).
4895 * - the U2 Exit Latency of the device
4897 static unsigned long long xhci_calculate_intel_u2_timeout(
4898 struct usb_device *udev,
4899 struct usb_endpoint_descriptor *desc)
4901 unsigned long long timeout_ns;
4902 unsigned long long u2_del_ns;
4904 timeout_ns = 10 * 1000 * 1000;
4906 if ((usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) &&
4907 (xhci_service_interval_to_ns(desc) > timeout_ns))
4908 timeout_ns = xhci_service_interval_to_ns(desc);
4910 u2_del_ns = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat) * 1000ULL;
4911 if (u2_del_ns > timeout_ns)
4912 timeout_ns = u2_del_ns;
4917 /* Returns the hub-encoded U2 timeout value. */
4918 static u16 xhci_calculate_u2_timeout(struct xhci_hcd *xhci,
4919 struct usb_device *udev,
4920 struct usb_endpoint_descriptor *desc)
4922 unsigned long long timeout_ns;
4924 /* Prevent U2 if service interval is shorter than U2 exit latency */
4925 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4926 if (xhci_service_interval_to_ns(desc) <= udev->u2_params.mel) {
4927 dev_dbg(&udev->dev, "Disable U2, ESIT shorter than exit latency\n");
4928 return USB3_LPM_DISABLED;
4932 if (xhci->quirks & (XHCI_INTEL_HOST | XHCI_ZHAOXIN_HOST))
4933 timeout_ns = xhci_calculate_intel_u2_timeout(udev, desc);
4935 timeout_ns = udev->u2_params.sel;
4937 /* The U2 timeout is encoded in 256us intervals */
4938 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 256 * 1000);
4939 /* If the necessary timeout value is bigger than what we can set in the
4940 * USB 3.0 hub, we have to disable hub-initiated U2.
4942 if (timeout_ns <= USB3_LPM_U2_MAX_TIMEOUT)
4944 dev_dbg(&udev->dev, "Hub-initiated U2 disabled due to long timeout %lluus\n",
4946 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U2);
4949 static u16 xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4950 struct usb_device *udev,
4951 struct usb_endpoint_descriptor *desc,
4952 enum usb3_link_state state,
4955 if (state == USB3_LPM_U1)
4956 return xhci_calculate_u1_timeout(xhci, udev, desc);
4957 else if (state == USB3_LPM_U2)
4958 return xhci_calculate_u2_timeout(xhci, udev, desc);
4960 return USB3_LPM_DISABLED;
4963 static int xhci_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4964 struct usb_device *udev,
4965 struct usb_endpoint_descriptor *desc,
4966 enum usb3_link_state state,
4971 alt_timeout = xhci_call_host_update_timeout_for_endpoint(xhci, udev,
4972 desc, state, timeout);
4974 /* If we found we can't enable hub-initiated LPM, and
4975 * the U1 or U2 exit latency was too high to allow
4976 * device-initiated LPM as well, then we will disable LPM
4977 * for this device, so stop searching any further.
4979 if (alt_timeout == USB3_LPM_DISABLED) {
4980 *timeout = alt_timeout;
4983 if (alt_timeout > *timeout)
4984 *timeout = alt_timeout;
4988 static int xhci_update_timeout_for_interface(struct xhci_hcd *xhci,
4989 struct usb_device *udev,
4990 struct usb_host_interface *alt,
4991 enum usb3_link_state state,
4996 for (j = 0; j < alt->desc.bNumEndpoints; j++) {
4997 if (xhci_update_timeout_for_endpoint(xhci, udev,
4998 &alt->endpoint[j].desc, state, timeout))
5004 static int xhci_check_tier_policy(struct xhci_hcd *xhci,
5005 struct usb_device *udev,
5006 enum usb3_link_state state)
5008 struct usb_device *parent = udev->parent;
5009 int tier = 1; /* roothub is tier1 */
5012 parent = parent->parent;
5016 if (xhci->quirks & XHCI_INTEL_HOST && tier > 3)
5018 if (xhci->quirks & XHCI_ZHAOXIN_HOST && tier > 2)
5023 dev_dbg(&udev->dev, "Tier policy prevents U1/U2 LPM states for devices at tier %d\n",
5028 /* Returns the U1 or U2 timeout that should be enabled.
5029 * If the tier check or timeout setting functions return with a non-zero exit
5030 * code, that means the timeout value has been finalized and we shouldn't look
5031 * at any more endpoints.
5033 static u16 xhci_calculate_lpm_timeout(struct usb_hcd *hcd,
5034 struct usb_device *udev, enum usb3_link_state state)
5036 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5037 struct usb_host_config *config;
5040 u16 timeout = USB3_LPM_DISABLED;
5042 if (state == USB3_LPM_U1)
5044 else if (state == USB3_LPM_U2)
5047 dev_warn(&udev->dev, "Can't enable unknown link state %i\n",
5052 /* Gather some information about the currently installed configuration
5053 * and alternate interface settings.
5055 if (xhci_update_timeout_for_endpoint(xhci, udev, &udev->ep0.desc,
5059 config = udev->actconfig;
5063 for (i = 0; i < config->desc.bNumInterfaces; i++) {
5064 struct usb_driver *driver;
5065 struct usb_interface *intf = config->interface[i];
5070 /* Check if any currently bound drivers want hub-initiated LPM
5073 if (intf->dev.driver) {
5074 driver = to_usb_driver(intf->dev.driver);
5075 if (driver && driver->disable_hub_initiated_lpm) {
5076 dev_dbg(&udev->dev, "Hub-initiated %s disabled at request of driver %s\n",
5077 state_name, driver->name);
5078 timeout = xhci_get_timeout_no_hub_lpm(udev,
5080 if (timeout == USB3_LPM_DISABLED)
5085 /* Not sure how this could happen... */
5086 if (!intf->cur_altsetting)
5089 if (xhci_update_timeout_for_interface(xhci, udev,
5090 intf->cur_altsetting,
5097 static int calculate_max_exit_latency(struct usb_device *udev,
5098 enum usb3_link_state state_changed,
5099 u16 hub_encoded_timeout)
5101 unsigned long long u1_mel_us = 0;
5102 unsigned long long u2_mel_us = 0;
5103 unsigned long long mel_us = 0;
5109 disabling_u1 = (state_changed == USB3_LPM_U1 &&
5110 hub_encoded_timeout == USB3_LPM_DISABLED);
5111 disabling_u2 = (state_changed == USB3_LPM_U2 &&
5112 hub_encoded_timeout == USB3_LPM_DISABLED);
5114 enabling_u1 = (state_changed == USB3_LPM_U1 &&
5115 hub_encoded_timeout != USB3_LPM_DISABLED);
5116 enabling_u2 = (state_changed == USB3_LPM_U2 &&
5117 hub_encoded_timeout != USB3_LPM_DISABLED);
5119 /* If U1 was already enabled and we're not disabling it,
5120 * or we're going to enable U1, account for the U1 max exit latency.
5122 if ((udev->u1_params.timeout != USB3_LPM_DISABLED && !disabling_u1) ||
5124 u1_mel_us = DIV_ROUND_UP(udev->u1_params.mel, 1000);
5125 if ((udev->u2_params.timeout != USB3_LPM_DISABLED && !disabling_u2) ||
5127 u2_mel_us = DIV_ROUND_UP(udev->u2_params.mel, 1000);
5129 mel_us = max(u1_mel_us, u2_mel_us);
5131 /* xHCI host controller max exit latency field is only 16 bits wide. */
5132 if (mel_us > MAX_EXIT) {
5133 dev_warn(&udev->dev, "Link PM max exit latency of %lluus "
5134 "is too big.\n", mel_us);
5140 /* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
5141 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
5142 struct usb_device *udev, enum usb3_link_state state)
5144 struct xhci_hcd *xhci;
5145 struct xhci_port *port;
5146 u16 hub_encoded_timeout;
5150 xhci = hcd_to_xhci(hcd);
5151 /* The LPM timeout values are pretty host-controller specific, so don't
5152 * enable hub-initiated timeouts unless the vendor has provided
5153 * information about their timeout algorithm.
5155 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
5156 !xhci->devs[udev->slot_id])
5157 return USB3_LPM_DISABLED;
5159 if (xhci_check_tier_policy(xhci, udev, state) < 0)
5160 return USB3_LPM_DISABLED;
5162 /* If connected to root port then check port can handle lpm */
5163 if (udev->parent && !udev->parent->parent) {
5164 port = xhci->usb3_rhub.ports[udev->portnum - 1];
5165 if (port->lpm_incapable)
5166 return USB3_LPM_DISABLED;
5169 hub_encoded_timeout = xhci_calculate_lpm_timeout(hcd, udev, state);
5170 mel = calculate_max_exit_latency(udev, state, hub_encoded_timeout);
5172 /* Max Exit Latency is too big, disable LPM. */
5173 hub_encoded_timeout = USB3_LPM_DISABLED;
5177 ret = xhci_change_max_exit_latency(xhci, udev, mel);
5180 return hub_encoded_timeout;
5183 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
5184 struct usb_device *udev, enum usb3_link_state state)
5186 struct xhci_hcd *xhci;
5189 xhci = hcd_to_xhci(hcd);
5190 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
5191 !xhci->devs[udev->slot_id])
5194 mel = calculate_max_exit_latency(udev, state, USB3_LPM_DISABLED);
5195 return xhci_change_max_exit_latency(xhci, udev, mel);
5197 #else /* CONFIG_PM */
5199 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
5200 struct usb_device *udev, int enable)
5205 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
5210 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
5211 struct usb_device *udev, enum usb3_link_state state)
5213 return USB3_LPM_DISABLED;
5216 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
5217 struct usb_device *udev, enum usb3_link_state state)
5221 #endif /* CONFIG_PM */
5223 /*-------------------------------------------------------------------------*/
5225 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
5226 * internal data structures for the device.
5228 int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
5229 struct usb_tt *tt, gfp_t mem_flags)
5231 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5232 struct xhci_virt_device *vdev;
5233 struct xhci_command *config_cmd;
5234 struct xhci_input_control_ctx *ctrl_ctx;
5235 struct xhci_slot_ctx *slot_ctx;
5236 unsigned long flags;
5237 unsigned think_time;
5240 /* Ignore root hubs */
5244 vdev = xhci->devs[hdev->slot_id];
5246 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
5250 config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
5254 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
5256 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
5258 xhci_free_command(xhci, config_cmd);
5262 spin_lock_irqsave(&xhci->lock, flags);
5263 if (hdev->speed == USB_SPEED_HIGH &&
5264 xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
5265 xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
5266 xhci_free_command(xhci, config_cmd);
5267 spin_unlock_irqrestore(&xhci->lock, flags);
5271 xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
5272 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
5273 slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
5274 slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
5276 * refer to section 6.2.2: MTT should be 0 for full speed hub,
5277 * but it may be already set to 1 when setup an xHCI virtual
5278 * device, so clear it anyway.
5281 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
5282 else if (hdev->speed == USB_SPEED_FULL)
5283 slot_ctx->dev_info &= cpu_to_le32(~DEV_MTT);
5285 if (xhci->hci_version > 0x95) {
5286 xhci_dbg(xhci, "xHCI version %x needs hub "
5287 "TT think time and number of ports\n",
5288 (unsigned int) xhci->hci_version);
5289 slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
5290 /* Set TT think time - convert from ns to FS bit times.
5291 * 0 = 8 FS bit times, 1 = 16 FS bit times,
5292 * 2 = 24 FS bit times, 3 = 32 FS bit times.
5294 * xHCI 1.0: this field shall be 0 if the device is not a
5297 think_time = tt->think_time;
5298 if (think_time != 0)
5299 think_time = (think_time / 666) - 1;
5300 if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
5301 slot_ctx->tt_info |=
5302 cpu_to_le32(TT_THINK_TIME(think_time));
5304 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
5305 "TT think time or number of ports\n",
5306 (unsigned int) xhci->hci_version);
5308 slot_ctx->dev_state = 0;
5309 spin_unlock_irqrestore(&xhci->lock, flags);
5311 xhci_dbg(xhci, "Set up %s for hub device.\n",
5312 (xhci->hci_version > 0x95) ?
5313 "configure endpoint" : "evaluate context");
5315 /* Issue and wait for the configure endpoint or
5316 * evaluate context command.
5318 if (xhci->hci_version > 0x95)
5319 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5322 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5325 xhci_free_command(xhci, config_cmd);
5328 EXPORT_SYMBOL_GPL(xhci_update_hub_device);
5330 static int xhci_get_frame(struct usb_hcd *hcd)
5332 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5333 /* EHCI mods by the periodic size. Why? */
5334 return readl(&xhci->run_regs->microframe_index) >> 3;
5337 static void xhci_hcd_init_usb2_data(struct xhci_hcd *xhci, struct usb_hcd *hcd)
5339 xhci->usb2_rhub.hcd = hcd;
5340 hcd->speed = HCD_USB2;
5341 hcd->self.root_hub->speed = USB_SPEED_HIGH;
5343 * USB 2.0 roothub under xHCI has an integrated TT,
5344 * (rate matching hub) as opposed to having an OHCI/UHCI
5345 * companion controller.
5350 static void xhci_hcd_init_usb3_data(struct xhci_hcd *xhci, struct usb_hcd *hcd)
5352 unsigned int minor_rev;
5355 * Early xHCI 1.1 spec did not mention USB 3.1 capable hosts
5356 * should return 0x31 for sbrn, or that the minor revision
5357 * is a two digit BCD containig minor and sub-minor numbers.
5358 * This was later clarified in xHCI 1.2.
5360 * Some USB 3.1 capable hosts therefore have sbrn 0x30, and
5361 * minor revision set to 0x1 instead of 0x10.
5363 if (xhci->usb3_rhub.min_rev == 0x1)
5366 minor_rev = xhci->usb3_rhub.min_rev / 0x10;
5368 switch (minor_rev) {
5370 hcd->speed = HCD_USB32;
5371 hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5372 hcd->self.root_hub->rx_lanes = 2;
5373 hcd->self.root_hub->tx_lanes = 2;
5374 hcd->self.root_hub->ssp_rate = USB_SSP_GEN_2x2;
5377 hcd->speed = HCD_USB31;
5378 hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5379 hcd->self.root_hub->ssp_rate = USB_SSP_GEN_2x1;
5382 xhci_info(xhci, "Host supports USB 3.%x %sSuperSpeed\n",
5383 minor_rev, minor_rev ? "Enhanced " : "");
5385 xhci->usb3_rhub.hcd = hcd;
5388 int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
5390 struct xhci_hcd *xhci;
5392 * TODO: Check with DWC3 clients for sysdev according to
5395 struct device *dev = hcd->self.sysdev;
5398 /* Accept arbitrarily long scatter-gather lists */
5399 hcd->self.sg_tablesize = ~0;
5401 /* support to build packet from discontinuous buffers */
5402 hcd->self.no_sg_constraint = 1;
5404 /* XHCI controllers don't stop the ep queue on short packets :| */
5405 hcd->self.no_stop_on_short = 1;
5407 xhci = hcd_to_xhci(hcd);
5409 if (!usb_hcd_is_primary_hcd(hcd)) {
5410 xhci_hcd_init_usb3_data(xhci, hcd);
5414 mutex_init(&xhci->mutex);
5415 xhci->main_hcd = hcd;
5416 xhci->cap_regs = hcd->regs;
5417 xhci->op_regs = hcd->regs +
5418 HC_LENGTH(readl(&xhci->cap_regs->hc_capbase));
5419 xhci->run_regs = hcd->regs +
5420 (readl(&xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
5421 /* Cache read-only capability registers */
5422 xhci->hcs_params1 = readl(&xhci->cap_regs->hcs_params1);
5423 xhci->hcs_params2 = readl(&xhci->cap_regs->hcs_params2);
5424 xhci->hcs_params3 = readl(&xhci->cap_regs->hcs_params3);
5425 xhci->hci_version = HC_VERSION(readl(&xhci->cap_regs->hc_capbase));
5426 xhci->hcc_params = readl(&xhci->cap_regs->hcc_params);
5427 if (xhci->hci_version > 0x100)
5428 xhci->hcc_params2 = readl(&xhci->cap_regs->hcc_params2);
5430 /* xhci-plat or xhci-pci might have set max_interrupters already */
5431 if ((!xhci->max_interrupters) ||
5432 xhci->max_interrupters > HCS_MAX_INTRS(xhci->hcs_params1))
5433 xhci->max_interrupters = HCS_MAX_INTRS(xhci->hcs_params1);
5435 xhci->quirks |= quirks;
5438 get_quirks(dev, xhci);
5440 /* In xhci controllers which follow xhci 1.0 spec gives a spurious
5441 * success event after a short transfer. This quirk will ignore such
5444 if (xhci->hci_version > 0x96)
5445 xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
5447 if (xhci->hci_version == 0x95 && link_quirk) {
5448 xhci_dbg(xhci, "QUIRK: Not clearing Link TRB chain bits");
5449 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
5452 /* Make sure the HC is halted. */
5453 retval = xhci_halt(xhci);
5457 xhci_zero_64b_regs(xhci);
5459 xhci_dbg(xhci, "Resetting HCD\n");
5460 /* Reset the internal HC memory state and registers. */
5461 retval = xhci_reset(xhci, XHCI_RESET_LONG_USEC);
5464 xhci_dbg(xhci, "Reset complete\n");
5467 * On some xHCI controllers (e.g. R-Car SoCs), the AC64 bit (bit 0)
5468 * of HCCPARAMS1 is set to 1. However, the xHCs don't support 64-bit
5469 * address memory pointers actually. So, this driver clears the AC64
5470 * bit of xhci->hcc_params to call dma_set_coherent_mask(dev,
5471 * DMA_BIT_MASK(32)) in this xhci_gen_setup().
5473 if (xhci->quirks & XHCI_NO_64BIT_SUPPORT)
5474 xhci->hcc_params &= ~BIT(0);
5476 /* Set dma_mask and coherent_dma_mask to 64-bits,
5477 * if xHC supports 64-bit addressing */
5478 if (HCC_64BIT_ADDR(xhci->hcc_params) &&
5479 !dma_set_mask(dev, DMA_BIT_MASK(64))) {
5480 xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
5481 dma_set_coherent_mask(dev, DMA_BIT_MASK(64));
5484 * This is to avoid error in cases where a 32-bit USB
5485 * controller is used on a 64-bit capable system.
5487 retval = dma_set_mask(dev, DMA_BIT_MASK(32));
5490 xhci_dbg(xhci, "Enabling 32-bit DMA addresses.\n");
5491 dma_set_coherent_mask(dev, DMA_BIT_MASK(32));
5494 xhci_dbg(xhci, "Calling HCD init\n");
5495 /* Initialize HCD and host controller data structures. */
5496 retval = xhci_init(hcd);
5499 xhci_dbg(xhci, "Called HCD init\n");
5501 if (xhci_hcd_is_usb3(hcd))
5502 xhci_hcd_init_usb3_data(xhci, hcd);
5504 xhci_hcd_init_usb2_data(xhci, hcd);
5506 xhci_info(xhci, "hcc params 0x%08x hci version 0x%x quirks 0x%016llx\n",
5507 xhci->hcc_params, xhci->hci_version, xhci->quirks);
5511 EXPORT_SYMBOL_GPL(xhci_gen_setup);
5513 static void xhci_clear_tt_buffer_complete(struct usb_hcd *hcd,
5514 struct usb_host_endpoint *ep)
5516 struct xhci_hcd *xhci;
5517 struct usb_device *udev;
5518 unsigned int slot_id;
5519 unsigned int ep_index;
5520 unsigned long flags;
5522 xhci = hcd_to_xhci(hcd);
5524 spin_lock_irqsave(&xhci->lock, flags);
5525 udev = (struct usb_device *)ep->hcpriv;
5526 slot_id = udev->slot_id;
5527 ep_index = xhci_get_endpoint_index(&ep->desc);
5529 xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_CLEARING_TT;
5530 xhci_ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
5531 spin_unlock_irqrestore(&xhci->lock, flags);
5534 static const struct hc_driver xhci_hc_driver = {
5535 .description = "xhci-hcd",
5536 .product_desc = "xHCI Host Controller",
5537 .hcd_priv_size = sizeof(struct xhci_hcd),
5540 * generic hardware linkage
5543 .flags = HCD_MEMORY | HCD_DMA | HCD_USB3 | HCD_SHARED |
5547 * basic lifecycle operations
5549 .reset = NULL, /* set in xhci_init_driver() */
5552 .shutdown = xhci_shutdown,
5555 * managing i/o requests and associated device resources
5557 .map_urb_for_dma = xhci_map_urb_for_dma,
5558 .unmap_urb_for_dma = xhci_unmap_urb_for_dma,
5559 .urb_enqueue = xhci_urb_enqueue,
5560 .urb_dequeue = xhci_urb_dequeue,
5561 .alloc_dev = xhci_alloc_dev,
5562 .free_dev = xhci_free_dev,
5563 .alloc_streams = xhci_alloc_streams,
5564 .free_streams = xhci_free_streams,
5565 .add_endpoint = xhci_add_endpoint,
5566 .drop_endpoint = xhci_drop_endpoint,
5567 .endpoint_disable = xhci_endpoint_disable,
5568 .endpoint_reset = xhci_endpoint_reset,
5569 .check_bandwidth = xhci_check_bandwidth,
5570 .reset_bandwidth = xhci_reset_bandwidth,
5571 .address_device = xhci_address_device,
5572 .enable_device = xhci_enable_device,
5573 .update_hub_device = xhci_update_hub_device,
5574 .reset_device = xhci_discover_or_reset_device,
5577 * scheduling support
5579 .get_frame_number = xhci_get_frame,
5584 .hub_control = xhci_hub_control,
5585 .hub_status_data = xhci_hub_status_data,
5586 .bus_suspend = xhci_bus_suspend,
5587 .bus_resume = xhci_bus_resume,
5588 .get_resuming_ports = xhci_get_resuming_ports,
5591 * call back when device connected and addressed
5593 .update_device = xhci_update_device,
5594 .set_usb2_hw_lpm = xhci_set_usb2_hardware_lpm,
5595 .enable_usb3_lpm_timeout = xhci_enable_usb3_lpm_timeout,
5596 .disable_usb3_lpm_timeout = xhci_disable_usb3_lpm_timeout,
5597 .find_raw_port_number = xhci_find_raw_port_number,
5598 .clear_tt_buffer_complete = xhci_clear_tt_buffer_complete,
5601 void xhci_init_driver(struct hc_driver *drv,
5602 const struct xhci_driver_overrides *over)
5606 /* Copy the generic table to drv then apply the overrides */
5607 *drv = xhci_hc_driver;
5610 drv->hcd_priv_size += over->extra_priv_size;
5612 drv->reset = over->reset;
5614 drv->start = over->start;
5615 if (over->add_endpoint)
5616 drv->add_endpoint = over->add_endpoint;
5617 if (over->drop_endpoint)
5618 drv->drop_endpoint = over->drop_endpoint;
5619 if (over->check_bandwidth)
5620 drv->check_bandwidth = over->check_bandwidth;
5621 if (over->reset_bandwidth)
5622 drv->reset_bandwidth = over->reset_bandwidth;
5623 if (over->update_hub_device)
5624 drv->update_hub_device = over->update_hub_device;
5625 if (over->hub_control)
5626 drv->hub_control = over->hub_control;
5629 EXPORT_SYMBOL_GPL(xhci_init_driver);
5631 MODULE_DESCRIPTION(DRIVER_DESC);
5632 MODULE_AUTHOR(DRIVER_AUTHOR);
5633 MODULE_LICENSE("GPL");
5635 static int __init xhci_hcd_init(void)
5638 * Check the compiler generated sizes of structures that must be laid
5639 * out in specific ways for hardware access.
5641 BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
5642 BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
5643 BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
5644 /* xhci_device_control has eight fields, and also
5645 * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
5647 BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
5648 BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
5649 BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
5650 BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 8*32/8);
5651 BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
5652 /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
5653 BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
5658 xhci_debugfs_create_root();
5665 * If an init function is provided, an exit function must also be provided
5666 * to allow module unload.
5668 static void __exit xhci_hcd_fini(void)
5670 xhci_debugfs_remove_root();
5674 module_init(xhci_hcd_init);
5675 module_exit(xhci_hcd_fini);