xref: /linux/drivers/usb/host/xhci.c (revision 3a39d672e7f48b8d6b91a09afa4b55352773b4b5)
15fd54aceSGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2bc75fa38SAlex Chiang /*
3bc75fa38SAlex Chiang  * xHCI host controller driver
4bc75fa38SAlex Chiang  *
5bc75fa38SAlex Chiang  * Copyright (C) 2008 Intel Corp.
6bc75fa38SAlex Chiang  *
7bc75fa38SAlex Chiang  * Author: Sarah Sharp
8bc75fa38SAlex Chiang  * Some code borrowed from the Linux EHCI driver.
9bc75fa38SAlex Chiang  */
10bc75fa38SAlex Chiang 
1143b86af8SDong Nguyen #include <linux/pci.h>
12ecaa4902SD Scott Phillips #include <linux/iommu.h>
13f7fac17cSAndrey Smirnov #include <linux/iopoll.h>
14bc75fa38SAlex Chiang #include <linux/irq.h>
158df75f42SSarah Sharp #include <linux/log2.h>
16bc75fa38SAlex Chiang #include <linux/module.h>
17bc75fa38SAlex Chiang #include <linux/moduleparam.h>
185a0e3ad6STejun Heo #include <linux/slab.h>
1971c731a2SAlexis R. Cortes #include <linux/dmi.h>
20008eb957SJames Hogan #include <linux/dma-mapping.h>
21bc75fa38SAlex Chiang 
22bc75fa38SAlex Chiang #include "xhci.h"
2384a99f6fSXenia Ragiadakou #include "xhci-trace.h"
2402b6fdc2SLu Baolu #include "xhci-debugfs.h"
25dfba2174SLu Baolu #include "xhci-dbgcap.h"
26bc75fa38SAlex Chiang 
27bc75fa38SAlex Chiang #define DRIVER_AUTHOR "Sarah Sharp"
28bc75fa38SAlex Chiang #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
29bc75fa38SAlex Chiang 
30a1377e53SLu Baolu #define	PORT_WAKE_BITS	(PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E)
31a1377e53SLu Baolu 
32bc75fa38SAlex Chiang /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
33bc75fa38SAlex Chiang static int link_quirk;
34bc75fa38SAlex Chiang module_param(link_quirk, int, S_IRUGO | S_IWUSR);
35bc75fa38SAlex Chiang MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
36bc75fa38SAlex Chiang 
3736b68579SMarc Zyngier static unsigned long long quirks;
3836b68579SMarc Zyngier module_param(quirks, ullong, S_IRUGO);
394e6a1ee7STakashi Iwai MODULE_PARM_DESC(quirks, "Bit flags for quirks to be enabled as default");
404e6a1ee7STakashi Iwai 
td_on_ring(struct xhci_td * td,struct xhci_ring * ring)414937213bSMathias Nyman static bool td_on_ring(struct xhci_td *td, struct xhci_ring *ring)
424937213bSMathias Nyman {
434937213bSMathias Nyman 	struct xhci_segment *seg = ring->first_seg;
444937213bSMathias Nyman 
454937213bSMathias Nyman 	if (!td || !td->start_seg)
464937213bSMathias Nyman 		return false;
474937213bSMathias Nyman 	do {
484937213bSMathias Nyman 		if (seg == td->start_seg)
494937213bSMathias Nyman 			return true;
504937213bSMathias Nyman 		seg = seg->next;
514937213bSMathias Nyman 	} while (seg && seg != ring->first_seg);
524937213bSMathias Nyman 
534937213bSMathias Nyman 	return false;
544937213bSMathias Nyman }
554937213bSMathias Nyman 
56bc75fa38SAlex Chiang /*
572611bd18SSarah Sharp  * xhci_handshake - spin reading hc until handshake completes or fails
58bc75fa38SAlex Chiang  * @ptr: address of hc register to be read
59bc75fa38SAlex Chiang  * @mask: bits to look at in result of read
60bc75fa38SAlex Chiang  * @done: value of those bits when handshake succeeds
61bc75fa38SAlex Chiang  * @usec: timeout in microseconds
62bc75fa38SAlex Chiang  *
63bc75fa38SAlex Chiang  * Returns negative errno, or zero on success
64bc75fa38SAlex Chiang  *
65bc75fa38SAlex Chiang  * Success happens when the "mask" bits have the specified value (hardware
66bc75fa38SAlex Chiang  * handshake done).  There are two failure modes:  "usec" have passed (major
67bc75fa38SAlex Chiang  * hardware flakeout), or the register reads as all-ones (hardware removed).
68bc75fa38SAlex Chiang  */
xhci_handshake(void __iomem * ptr,u32 mask,u32 done,u64 timeout_us)6914073ce9SMathias Nyman int xhci_handshake(void __iomem *ptr, u32 mask, u32 done, u64 timeout_us)
70bc75fa38SAlex Chiang {
71bc75fa38SAlex Chiang 	u32	result;
72f7fac17cSAndrey Smirnov 	int	ret;
73bc75fa38SAlex Chiang 
74f7fac17cSAndrey Smirnov 	ret = readl_poll_timeout_atomic(ptr, result,
75f7fac17cSAndrey Smirnov 					(result & mask) == done ||
76f7fac17cSAndrey Smirnov 					result == U32_MAX,
7714073ce9SMathias Nyman 					1, timeout_us);
78f7fac17cSAndrey Smirnov 	if (result == U32_MAX)		/* card removed */
79bc75fa38SAlex Chiang 		return -ENODEV;
80f7fac17cSAndrey Smirnov 
81f7fac17cSAndrey Smirnov 	return ret;
82bc75fa38SAlex Chiang }
83bc75fa38SAlex Chiang 
84bc75fa38SAlex Chiang /*
856ccb83d6SUdipto Goswami  * xhci_handshake_check_state - same as xhci_handshake but takes an additional
866ccb83d6SUdipto Goswami  * exit_state parameter, and bails out with an error immediately when xhc_state
876ccb83d6SUdipto Goswami  * has exit_state flag set.
886ccb83d6SUdipto Goswami  */
xhci_handshake_check_state(struct xhci_hcd * xhci,void __iomem * ptr,u32 mask,u32 done,int usec,unsigned int exit_state)896ccb83d6SUdipto Goswami int xhci_handshake_check_state(struct xhci_hcd *xhci, void __iomem *ptr,
906ccb83d6SUdipto Goswami 		u32 mask, u32 done, int usec, unsigned int exit_state)
916ccb83d6SUdipto Goswami {
926ccb83d6SUdipto Goswami 	u32	result;
936ccb83d6SUdipto Goswami 	int	ret;
946ccb83d6SUdipto Goswami 
956ccb83d6SUdipto Goswami 	ret = readl_poll_timeout_atomic(ptr, result,
966ccb83d6SUdipto Goswami 				(result & mask) == done ||
976ccb83d6SUdipto Goswami 				result == U32_MAX ||
986ccb83d6SUdipto Goswami 				xhci->xhc_state & exit_state,
996ccb83d6SUdipto Goswami 				1, usec);
1006ccb83d6SUdipto Goswami 
1016ccb83d6SUdipto Goswami 	if (result == U32_MAX || xhci->xhc_state & exit_state)
1026ccb83d6SUdipto Goswami 		return -ENODEV;
1036ccb83d6SUdipto Goswami 
1046ccb83d6SUdipto Goswami 	return ret;
1056ccb83d6SUdipto Goswami }
1066ccb83d6SUdipto Goswami 
1076ccb83d6SUdipto Goswami /*
108bc75fa38SAlex Chiang  * Disable interrupts and begin the xHCI halting process.
109bc75fa38SAlex Chiang  */
xhci_quiesce(struct xhci_hcd * xhci)110bc75fa38SAlex Chiang void xhci_quiesce(struct xhci_hcd *xhci)
111bc75fa38SAlex Chiang {
112bc75fa38SAlex Chiang 	u32 halted;
113bc75fa38SAlex Chiang 	u32 cmd;
114bc75fa38SAlex Chiang 	u32 mask;
115bc75fa38SAlex Chiang 
116bc75fa38SAlex Chiang 	mask = ~(XHCI_IRQS);
117b0ba9720SXenia Ragiadakou 	halted = readl(&xhci->op_regs->status) & STS_HALT;
118bc75fa38SAlex Chiang 	if (!halted)
119bc75fa38SAlex Chiang 		mask &= ~CMD_RUN;
120bc75fa38SAlex Chiang 
121b0ba9720SXenia Ragiadakou 	cmd = readl(&xhci->op_regs->command);
122bc75fa38SAlex Chiang 	cmd &= mask;
123204b7793SXenia Ragiadakou 	writel(cmd, &xhci->op_regs->command);
124bc75fa38SAlex Chiang }
125bc75fa38SAlex Chiang 
126bc75fa38SAlex Chiang /*
127bc75fa38SAlex Chiang  * Force HC into halt state.
128bc75fa38SAlex Chiang  *
129bc75fa38SAlex Chiang  * Disable any IRQs and clear the run/stop bit.
130bc75fa38SAlex Chiang  * HC will complete any current and actively pipelined transactions, and
131bdfca502SAndiry Xu  * should halt within 16 ms of the run/stop bit being cleared.
132bc75fa38SAlex Chiang  * Read HC Halted bit in the status register to see when the HC is finished.
133bc75fa38SAlex Chiang  */
xhci_halt(struct xhci_hcd * xhci)134bc75fa38SAlex Chiang int xhci_halt(struct xhci_hcd *xhci)
135bc75fa38SAlex Chiang {
136c6cc27c7SSarah Sharp 	int ret;
137c2b0d550SLinyu Yuan 
138d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Halt the HC");
139bc75fa38SAlex Chiang 	xhci_quiesce(xhci);
140bc75fa38SAlex Chiang 
141dc0b177cSLin Wang 	ret = xhci_handshake(&xhci->op_regs->status,
142bc75fa38SAlex Chiang 			STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
14399154fd3SMathias Nyman 	if (ret) {
14499154fd3SMathias Nyman 		xhci_warn(xhci, "Host halt failed, %d\n", ret);
14599154fd3SMathias Nyman 		return ret;
14699154fd3SMathias Nyman 	}
147c2b0d550SLinyu Yuan 
148c6cc27c7SSarah Sharp 	xhci->xhc_state |= XHCI_STATE_HALTED;
149c181bc5bSElric Fu 	xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
150c2b0d550SLinyu Yuan 
151c6cc27c7SSarah Sharp 	return ret;
152bc75fa38SAlex Chiang }
153bc75fa38SAlex Chiang 
154bc75fa38SAlex Chiang /*
155ed07453fSSarah Sharp  * Set the run bit and wait for the host to be running.
156ed07453fSSarah Sharp  */
xhci_start(struct xhci_hcd * xhci)15726bba5c7SGuoqing Zhang int xhci_start(struct xhci_hcd *xhci)
158ed07453fSSarah Sharp {
159ed07453fSSarah Sharp 	u32 temp;
160ed07453fSSarah Sharp 	int ret;
161ed07453fSSarah Sharp 
162b0ba9720SXenia Ragiadakou 	temp = readl(&xhci->op_regs->command);
163ed07453fSSarah Sharp 	temp |= (CMD_RUN);
164d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Turn on HC, cmd = 0x%x.",
165ed07453fSSarah Sharp 			temp);
166204b7793SXenia Ragiadakou 	writel(temp, &xhci->op_regs->command);
167ed07453fSSarah Sharp 
168ed07453fSSarah Sharp 	/*
169ed07453fSSarah Sharp 	 * Wait for the HCHalted Status bit to be 0 to indicate the host is
170ed07453fSSarah Sharp 	 * running.
171ed07453fSSarah Sharp 	 */
172dc0b177cSLin Wang 	ret = xhci_handshake(&xhci->op_regs->status,
173ed07453fSSarah Sharp 			STS_HALT, 0, XHCI_MAX_HALT_USEC);
174ed07453fSSarah Sharp 	if (ret == -ETIMEDOUT)
175ed07453fSSarah Sharp 		xhci_err(xhci, "Host took too long to start, "
176ed07453fSSarah Sharp 				"waited %u microseconds.\n",
177ed07453fSSarah Sharp 				XHCI_MAX_HALT_USEC);
17833e32158SMathias Nyman 	if (!ret) {
17998d74f9cSMathias Nyman 		/* clear state flags. Including dying, halted or removing */
18098d74f9cSMathias Nyman 		xhci->xhc_state = 0;
18133e32158SMathias Nyman 		xhci->run_graceperiod = jiffies + msecs_to_jiffies(500);
18233e32158SMathias Nyman 	}
183e5bfeab0SRoger Quadros 
184ed07453fSSarah Sharp 	return ret;
185ed07453fSSarah Sharp }
186ed07453fSSarah Sharp 
187ed07453fSSarah Sharp /*
188ac04e6ffSSarah Sharp  * Reset a halted HC.
189bc75fa38SAlex Chiang  *
190bc75fa38SAlex Chiang  * This resets pipelines, timers, counters, state machines, etc.
191bc75fa38SAlex Chiang  * Transactions will be terminated immediately, and operational registers
192bc75fa38SAlex Chiang  * will be set to their defaults.
193bc75fa38SAlex Chiang  */
xhci_reset(struct xhci_hcd * xhci,u64 timeout_us)19414073ce9SMathias Nyman int xhci_reset(struct xhci_hcd *xhci, u64 timeout_us)
195bc75fa38SAlex Chiang {
196bc75fa38SAlex Chiang 	u32 command;
197bc75fa38SAlex Chiang 	u32 state;
198f6187f42SMathias Nyman 	int ret;
199bc75fa38SAlex Chiang 
200b0ba9720SXenia Ragiadakou 	state = readl(&xhci->op_regs->status);
201c11ae038SMathias Nyman 
202c11ae038SMathias Nyman 	if (state == ~(u32)0) {
203c11ae038SMathias Nyman 		xhci_warn(xhci, "Host not accessible, reset failed.\n");
204c11ae038SMathias Nyman 		return -ENODEV;
205c11ae038SMathias Nyman 	}
206c11ae038SMathias Nyman 
207bc75fa38SAlex Chiang 	if ((state & STS_HALT) == 0) {
208bc75fa38SAlex Chiang 		xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
209bc75fa38SAlex Chiang 		return 0;
210bc75fa38SAlex Chiang 	}
211bc75fa38SAlex Chiang 
212d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Reset the HC");
213b0ba9720SXenia Ragiadakou 	command = readl(&xhci->op_regs->command);
214bc75fa38SAlex Chiang 	command |= CMD_RESET;
215204b7793SXenia Ragiadakou 	writel(command, &xhci->op_regs->command);
216bc75fa38SAlex Chiang 
217a5964396SRajmohan Mani 	/* Existing Intel xHCI controllers require a delay of 1 mS,
218a5964396SRajmohan Mani 	 * after setting the CMD_RESET bit, and before accessing any
219a5964396SRajmohan Mani 	 * HC registers. This allows the HC to complete the
220a5964396SRajmohan Mani 	 * reset operation and be ready for HC register access.
221a5964396SRajmohan Mani 	 * Without this delay, the subsequent HC register access,
222a5964396SRajmohan Mani 	 * may result in a system hang very rarely.
223a5964396SRajmohan Mani 	 */
224a5964396SRajmohan Mani 	if (xhci->quirks & XHCI_INTEL_HOST)
225a5964396SRajmohan Mani 		udelay(1000);
226a5964396SRajmohan Mani 
2276ccb83d6SUdipto Goswami 	ret = xhci_handshake_check_state(xhci, &xhci->op_regs->command,
2286ccb83d6SUdipto Goswami 				CMD_RESET, 0, timeout_us, XHCI_STATE_REMOVING);
2292d62f3eeSSarah Sharp 	if (ret)
2302d62f3eeSSarah Sharp 		return ret;
2312d62f3eeSSarah Sharp 
2329da5a109SJiahau Chang 	if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
2339da5a109SJiahau Chang 		usb_asmedia_modifyflowcontrol(to_pci_dev(xhci_to_hcd(xhci)->self.controller));
2349da5a109SJiahau Chang 
235d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
236d195fcffSXenia Ragiadakou 			 "Wait for controller to be ready for doorbell rings");
2372d62f3eeSSarah Sharp 	/*
2382d62f3eeSSarah Sharp 	 * xHCI cannot write to any doorbells or operational registers other
2392d62f3eeSSarah Sharp 	 * than status until the "Controller Not Ready" flag is cleared.
2402d62f3eeSSarah Sharp 	 */
24114073ce9SMathias Nyman 	ret = xhci_handshake(&xhci->op_regs->status, STS_CNR, 0, timeout_us);
242f370b996SAndiry Xu 
243f6187f42SMathias Nyman 	xhci->usb2_rhub.bus_state.port_c_suspend = 0;
244f6187f42SMathias Nyman 	xhci->usb2_rhub.bus_state.suspended_ports = 0;
245f6187f42SMathias Nyman 	xhci->usb2_rhub.bus_state.resuming_ports = 0;
246f6187f42SMathias Nyman 	xhci->usb3_rhub.bus_state.port_c_suspend = 0;
247f6187f42SMathias Nyman 	xhci->usb3_rhub.bus_state.suspended_ports = 0;
248f6187f42SMathias Nyman 	xhci->usb3_rhub.bus_state.resuming_ports = 0;
249f370b996SAndiry Xu 
250f370b996SAndiry Xu 	return ret;
251bc75fa38SAlex Chiang }
252bc75fa38SAlex Chiang 
xhci_zero_64b_regs(struct xhci_hcd * xhci)25312de0a35SMarc Zyngier static void xhci_zero_64b_regs(struct xhci_hcd *xhci)
25412de0a35SMarc Zyngier {
25512de0a35SMarc Zyngier 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
256ecaa4902SD Scott Phillips 	struct iommu_domain *domain;
25712de0a35SMarc Zyngier 	int err, i;
25812de0a35SMarc Zyngier 	u64 val;
259286fd02fSMathias Nyman 	u32 intrs;
26012de0a35SMarc Zyngier 
26112de0a35SMarc Zyngier 	/*
26212de0a35SMarc Zyngier 	 * Some Renesas controllers get into a weird state if they are
26312de0a35SMarc Zyngier 	 * reset while programmed with 64bit addresses (they will preserve
26412de0a35SMarc Zyngier 	 * the top half of the address in internal, non visible
26512de0a35SMarc Zyngier 	 * registers). You end up with half the address coming from the
26612de0a35SMarc Zyngier 	 * kernel, and the other half coming from the firmware. Also,
26712de0a35SMarc Zyngier 	 * changing the programming leads to extra accesses even if the
26812de0a35SMarc Zyngier 	 * controller is supposed to be halted. The controller ends up with
26912de0a35SMarc Zyngier 	 * a fatal fault, and is then ripe for being properly reset.
27012de0a35SMarc Zyngier 	 *
27112de0a35SMarc Zyngier 	 * Special care is taken to only apply this if the device is behind
27212de0a35SMarc Zyngier 	 * an iommu. Doing anything when there is no iommu is definitely
27312de0a35SMarc Zyngier 	 * unsafe...
27412de0a35SMarc Zyngier 	 */
275ecaa4902SD Scott Phillips 	domain = iommu_get_domain_for_dev(dev);
276ecaa4902SD Scott Phillips 	if (!(xhci->quirks & XHCI_ZERO_64B_REGS) || !domain ||
277ecaa4902SD Scott Phillips 	    domain->type == IOMMU_DOMAIN_IDENTITY)
27812de0a35SMarc Zyngier 		return;
27912de0a35SMarc Zyngier 
28012de0a35SMarc Zyngier 	xhci_info(xhci, "Zeroing 64bit base registers, expecting fault\n");
28112de0a35SMarc Zyngier 
28212de0a35SMarc Zyngier 	/* Clear HSEIE so that faults do not get signaled */
28312de0a35SMarc Zyngier 	val = readl(&xhci->op_regs->command);
28412de0a35SMarc Zyngier 	val &= ~CMD_HSEIE;
28512de0a35SMarc Zyngier 	writel(val, &xhci->op_regs->command);
28612de0a35SMarc Zyngier 
28712de0a35SMarc Zyngier 	/* Clear HSE (aka FATAL) */
28812de0a35SMarc Zyngier 	val = readl(&xhci->op_regs->status);
28912de0a35SMarc Zyngier 	val |= STS_FATAL;
29012de0a35SMarc Zyngier 	writel(val, &xhci->op_regs->status);
29112de0a35SMarc Zyngier 
29212de0a35SMarc Zyngier 	/* Now zero the registers, and brace for impact */
29312de0a35SMarc Zyngier 	val = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
29412de0a35SMarc Zyngier 	if (upper_32_bits(val))
29512de0a35SMarc Zyngier 		xhci_write_64(xhci, 0, &xhci->op_regs->dcbaa_ptr);
29612de0a35SMarc Zyngier 	val = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
29712de0a35SMarc Zyngier 	if (upper_32_bits(val))
29812de0a35SMarc Zyngier 		xhci_write_64(xhci, 0, &xhci->op_regs->cmd_ring);
29912de0a35SMarc Zyngier 
300286fd02fSMathias Nyman 	intrs = min_t(u32, HCS_MAX_INTRS(xhci->hcs_params1),
301286fd02fSMathias Nyman 		      ARRAY_SIZE(xhci->run_regs->ir_set));
302286fd02fSMathias Nyman 
303286fd02fSMathias Nyman 	for (i = 0; i < intrs; i++) {
30412de0a35SMarc Zyngier 		struct xhci_intr_reg __iomem *ir;
30512de0a35SMarc Zyngier 
30612de0a35SMarc Zyngier 		ir = &xhci->run_regs->ir_set[i];
30712de0a35SMarc Zyngier 		val = xhci_read_64(xhci, &ir->erst_base);
30812de0a35SMarc Zyngier 		if (upper_32_bits(val))
30912de0a35SMarc Zyngier 			xhci_write_64(xhci, 0, &ir->erst_base);
31012de0a35SMarc Zyngier 		val= xhci_read_64(xhci, &ir->erst_dequeue);
31112de0a35SMarc Zyngier 		if (upper_32_bits(val))
31212de0a35SMarc Zyngier 			xhci_write_64(xhci, 0, &ir->erst_dequeue);
31312de0a35SMarc Zyngier 	}
31412de0a35SMarc Zyngier 
31512de0a35SMarc Zyngier 	/* Wait for the fault to appear. It will be cleared on reset */
31612de0a35SMarc Zyngier 	err = xhci_handshake(&xhci->op_regs->status,
31712de0a35SMarc Zyngier 			     STS_FATAL, STS_FATAL,
31812de0a35SMarc Zyngier 			     XHCI_MAX_HALT_USEC);
31912de0a35SMarc Zyngier 	if (!err)
32012de0a35SMarc Zyngier 		xhci_info(xhci, "Fault detected\n");
32112de0a35SMarc Zyngier }
32277d45b45SChristoph Hellwig 
xhci_enable_interrupter(struct xhci_interrupter * ir)32352dd0483SMathias Nyman static int xhci_enable_interrupter(struct xhci_interrupter *ir)
32452dd0483SMathias Nyman {
32552dd0483SMathias Nyman 	u32 iman;
32652dd0483SMathias Nyman 
32752dd0483SMathias Nyman 	if (!ir || !ir->ir_set)
32852dd0483SMathias Nyman 		return -EINVAL;
32952dd0483SMathias Nyman 
33052dd0483SMathias Nyman 	iman = readl(&ir->ir_set->irq_pending);
33152dd0483SMathias Nyman 	writel(ER_IRQ_ENABLE(iman), &ir->ir_set->irq_pending);
33252dd0483SMathias Nyman 
33352dd0483SMathias Nyman 	return 0;
33452dd0483SMathias Nyman }
33552dd0483SMathias Nyman 
xhci_disable_interrupter(struct xhci_interrupter * ir)33652dd0483SMathias Nyman static int xhci_disable_interrupter(struct xhci_interrupter *ir)
33752dd0483SMathias Nyman {
33852dd0483SMathias Nyman 	u32 iman;
33952dd0483SMathias Nyman 
34052dd0483SMathias Nyman 	if (!ir || !ir->ir_set)
34152dd0483SMathias Nyman 		return -EINVAL;
34252dd0483SMathias Nyman 
34352dd0483SMathias Nyman 	iman = readl(&ir->ir_set->irq_pending);
34452dd0483SMathias Nyman 	writel(ER_IRQ_DISABLE(iman), &ir->ir_set->irq_pending);
34552dd0483SMathias Nyman 
34652dd0483SMathias Nyman 	return 0;
34752dd0483SMathias Nyman }
34852dd0483SMathias Nyman 
349ace21625SMathias Nyman /* interrupt moderation interval imod_interval in nanoseconds */
xhci_set_interrupter_moderation(struct xhci_interrupter * ir,u32 imod_interval)350*9c0c11bbSMathias Nyman int xhci_set_interrupter_moderation(struct xhci_interrupter *ir,
351ace21625SMathias Nyman 				    u32 imod_interval)
352ace21625SMathias Nyman {
353ace21625SMathias Nyman 	u32 imod;
354ace21625SMathias Nyman 
355ace21625SMathias Nyman 	if (!ir || !ir->ir_set || imod_interval > U16_MAX * 250)
356ace21625SMathias Nyman 		return -EINVAL;
357ace21625SMathias Nyman 
358ace21625SMathias Nyman 	imod = readl(&ir->ir_set->irq_control);
359ace21625SMathias Nyman 	imod &= ~ER_IRQ_INTERVAL_MASK;
360ace21625SMathias Nyman 	imod |= (imod_interval / 250) & ER_IRQ_INTERVAL_MASK;
361ace21625SMathias Nyman 	writel(imod, &ir->ir_set->irq_control);
362ace21625SMathias Nyman 
363ace21625SMathias Nyman 	return 0;
364ace21625SMathias Nyman }
365ace21625SMathias Nyman 
compliance_mode_recovery(struct timer_list * t)366e99e88a9SKees Cook static void compliance_mode_recovery(struct timer_list *t)
36771c731a2SAlexis R. Cortes {
36871c731a2SAlexis R. Cortes 	struct xhci_hcd *xhci;
36971c731a2SAlexis R. Cortes 	struct usb_hcd *hcd;
37038986ffaSMathias Nyman 	struct xhci_hub *rhub;
37171c731a2SAlexis R. Cortes 	u32 temp;
37271c731a2SAlexis R. Cortes 	int i;
37371c731a2SAlexis R. Cortes 
374e99e88a9SKees Cook 	xhci = from_timer(xhci, t, comp_mode_recovery_timer);
37538986ffaSMathias Nyman 	rhub = &xhci->usb3_rhub;
376873f3236SHeiner Kallweit 	hcd = rhub->hcd;
377873f3236SHeiner Kallweit 
378873f3236SHeiner Kallweit 	if (!hcd)
379873f3236SHeiner Kallweit 		return;
38071c731a2SAlexis R. Cortes 
38138986ffaSMathias Nyman 	for (i = 0; i < rhub->num_ports; i++) {
38238986ffaSMathias Nyman 		temp = readl(rhub->ports[i]->addr);
38371c731a2SAlexis R. Cortes 		if ((temp & PORT_PLS_MASK) == USB_SS_PORT_LS_COMP_MOD) {
38471c731a2SAlexis R. Cortes 			/*
38571c731a2SAlexis R. Cortes 			 * Compliance Mode Detected. Letting USB Core
38671c731a2SAlexis R. Cortes 			 * handle the Warm Reset
38771c731a2SAlexis R. Cortes 			 */
3884bdfe4c3SXenia Ragiadakou 			xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3894bdfe4c3SXenia Ragiadakou 					"Compliance mode detected->port %d",
39071c731a2SAlexis R. Cortes 					i + 1);
3914bdfe4c3SXenia Ragiadakou 			xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3924bdfe4c3SXenia Ragiadakou 					"Attempting compliance mode recovery");
39371c731a2SAlexis R. Cortes 
39471c731a2SAlexis R. Cortes 			if (hcd->state == HC_STATE_SUSPENDED)
39571c731a2SAlexis R. Cortes 				usb_hcd_resume_root_hub(hcd);
39671c731a2SAlexis R. Cortes 
39771c731a2SAlexis R. Cortes 			usb_hcd_poll_rh_status(hcd);
39871c731a2SAlexis R. Cortes 		}
39971c731a2SAlexis R. Cortes 	}
40071c731a2SAlexis R. Cortes 
40138986ffaSMathias Nyman 	if (xhci->port_status_u0 != ((1 << rhub->num_ports) - 1))
40271c731a2SAlexis R. Cortes 		mod_timer(&xhci->comp_mode_recovery_timer,
40371c731a2SAlexis R. Cortes 			jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
40471c731a2SAlexis R. Cortes }
40571c731a2SAlexis R. Cortes 
40671c731a2SAlexis R. Cortes /*
40771c731a2SAlexis R. Cortes  * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
40871c731a2SAlexis R. Cortes  * that causes ports behind that hardware to enter compliance mode sometimes.
40971c731a2SAlexis R. Cortes  * The quirk creates a timer that polls every 2 seconds the link state of
41071c731a2SAlexis R. Cortes  * each host controller's port and recovers it by issuing a Warm reset
41171c731a2SAlexis R. Cortes  * if Compliance mode is detected, otherwise the port will become "dead" (no
41271c731a2SAlexis R. Cortes  * device connections or disconnections will be detected anymore). Becasue no
41371c731a2SAlexis R. Cortes  * status event is generated when entering compliance mode (per xhci spec),
41471c731a2SAlexis R. Cortes  * this quirk is needed on systems that have the failing hardware installed.
41571c731a2SAlexis R. Cortes  */
compliance_mode_recovery_timer_init(struct xhci_hcd * xhci)41671c731a2SAlexis R. Cortes static void compliance_mode_recovery_timer_init(struct xhci_hcd *xhci)
41771c731a2SAlexis R. Cortes {
41871c731a2SAlexis R. Cortes 	xhci->port_status_u0 = 0;
419e99e88a9SKees Cook 	timer_setup(&xhci->comp_mode_recovery_timer, compliance_mode_recovery,
420e99e88a9SKees Cook 		    0);
42171c731a2SAlexis R. Cortes 	xhci->comp_mode_recovery_timer.expires = jiffies +
42271c731a2SAlexis R. Cortes 			msecs_to_jiffies(COMP_MODE_RCVRY_MSECS);
42371c731a2SAlexis R. Cortes 
42471c731a2SAlexis R. Cortes 	add_timer(&xhci->comp_mode_recovery_timer);
4254bdfe4c3SXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
4264bdfe4c3SXenia Ragiadakou 			"Compliance mode recovery timer initialized");
42771c731a2SAlexis R. Cortes }
42871c731a2SAlexis R. Cortes 
42971c731a2SAlexis R. Cortes /*
43071c731a2SAlexis R. Cortes  * This function identifies the systems that have installed the SN65LVPE502CP
43171c731a2SAlexis R. Cortes  * USB3.0 re-driver and that need the Compliance Mode Quirk.
43271c731a2SAlexis R. Cortes  * Systems:
43371c731a2SAlexis R. Cortes  * Vendor: Hewlett-Packard -> System Models: Z420, Z620 and Z820
43471c731a2SAlexis R. Cortes  */
xhci_compliance_mode_recovery_timer_quirk_check(void)435e1cd9727SAndrew Bresticker static bool xhci_compliance_mode_recovery_timer_quirk_check(void)
43671c731a2SAlexis R. Cortes {
43771c731a2SAlexis R. Cortes 	const char *dmi_product_name, *dmi_sys_vendor;
43871c731a2SAlexis R. Cortes 
43971c731a2SAlexis R. Cortes 	dmi_product_name = dmi_get_system_info(DMI_PRODUCT_NAME);
44071c731a2SAlexis R. Cortes 	dmi_sys_vendor = dmi_get_system_info(DMI_SYS_VENDOR);
441457a73d3SVivek Gautam 	if (!dmi_product_name || !dmi_sys_vendor)
442457a73d3SVivek Gautam 		return false;
44371c731a2SAlexis R. Cortes 
44471c731a2SAlexis R. Cortes 	if (!(strstr(dmi_sys_vendor, "Hewlett-Packard")))
44571c731a2SAlexis R. Cortes 		return false;
44671c731a2SAlexis R. Cortes 
44771c731a2SAlexis R. Cortes 	if (strstr(dmi_product_name, "Z420") ||
44871c731a2SAlexis R. Cortes 			strstr(dmi_product_name, "Z620") ||
44947080974SAlexis R. Cortes 			strstr(dmi_product_name, "Z820") ||
450b0e4e606SAlexis R. Cortes 			strstr(dmi_product_name, "Z1 Workstation"))
45171c731a2SAlexis R. Cortes 		return true;
45271c731a2SAlexis R. Cortes 
45371c731a2SAlexis R. Cortes 	return false;
45471c731a2SAlexis R. Cortes }
45571c731a2SAlexis R. Cortes 
xhci_all_ports_seen_u0(struct xhci_hcd * xhci)45671c731a2SAlexis R. Cortes static int xhci_all_ports_seen_u0(struct xhci_hcd *xhci)
45771c731a2SAlexis R. Cortes {
45838986ffaSMathias Nyman 	return (xhci->port_status_u0 == ((1 << xhci->usb3_rhub.num_ports) - 1));
45971c731a2SAlexis R. Cortes }
46071c731a2SAlexis R. Cortes 
46171c731a2SAlexis R. Cortes 
462bc75fa38SAlex Chiang /*
463bc75fa38SAlex Chiang  * Initialize memory for HCD and xHC (one-time init).
464bc75fa38SAlex Chiang  *
465bc75fa38SAlex Chiang  * Program the PAGESIZE register, initialize the device context array, create
466bc75fa38SAlex Chiang  * device contexts (?), set up a command ring segment (or two?), create event
467bc75fa38SAlex Chiang  * ring (one for now).
468bc75fa38SAlex Chiang  */
xhci_init(struct usb_hcd * hcd)4693969384cSLu Baolu static int xhci_init(struct usb_hcd *hcd)
470bc75fa38SAlex Chiang {
471bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
47298d107b8SLinyu Yuan 	int retval;
473bc75fa38SAlex Chiang 
474d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_init");
475bc75fa38SAlex Chiang 	spin_lock_init(&xhci->lock);
476d7826599SSebastian Andrzej Siewior 	if (xhci->hci_version == 0x95 && link_quirk) {
4774bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
4784bdfe4c3SXenia Ragiadakou 				"QUIRK: Not clearing Link TRB chain bits.");
479bc75fa38SAlex Chiang 		xhci->quirks |= XHCI_LINK_TRB_QUIRK;
480bc75fa38SAlex Chiang 	} else {
481d195fcffSXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_init,
482d195fcffSXenia Ragiadakou 				"xHCI doesn't need link TRB QUIRK");
483bc75fa38SAlex Chiang 	}
484bc75fa38SAlex Chiang 	retval = xhci_mem_init(xhci, GFP_KERNEL);
485d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Finished xhci_init");
486bc75fa38SAlex Chiang 
48771c731a2SAlexis R. Cortes 	/* Initializing Compliance Mode Recovery Data If Needed */
488c3897aa5SSarah Sharp 	if (xhci_compliance_mode_recovery_timer_quirk_check()) {
48971c731a2SAlexis R. Cortes 		xhci->quirks |= XHCI_COMP_MODE_QUIRK;
49071c731a2SAlexis R. Cortes 		compliance_mode_recovery_timer_init(xhci);
49171c731a2SAlexis R. Cortes 	}
49271c731a2SAlexis R. Cortes 
493bc75fa38SAlex Chiang 	return retval;
494bc75fa38SAlex Chiang }
495bc75fa38SAlex Chiang 
496bc75fa38SAlex Chiang /*-------------------------------------------------------------------------*/
497bc75fa38SAlex Chiang 
xhci_run_finished(struct xhci_hcd * xhci)498f6ff0ac8SSarah Sharp static int xhci_run_finished(struct xhci_hcd *xhci)
499f6ff0ac8SSarah Sharp {
500c99b38c4SMathias Nyman 	struct xhci_interrupter *ir = xhci->interrupters[0];
501a8089250SHongyu Xie 	unsigned long	flags;
502a8089250SHongyu Xie 	u32		temp;
503a8089250SHongyu Xie 
504a8089250SHongyu Xie 	/*
505a8089250SHongyu Xie 	 * Enable interrupts before starting the host (xhci 4.2 and 5.5.2).
506a8089250SHongyu Xie 	 * Protect the short window before host is running with a lock
507a8089250SHongyu Xie 	 */
508a8089250SHongyu Xie 	spin_lock_irqsave(&xhci->lock, flags);
509a8089250SHongyu Xie 
510a8089250SHongyu Xie 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Enable interrupts");
511a8089250SHongyu Xie 	temp = readl(&xhci->op_regs->command);
512a8089250SHongyu Xie 	temp |= (CMD_EIE);
513a8089250SHongyu Xie 	writel(temp, &xhci->op_regs->command);
514a8089250SHongyu Xie 
515a8089250SHongyu Xie 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Enable primary interrupter");
51652dd0483SMathias Nyman 	xhci_enable_interrupter(ir);
517a8089250SHongyu Xie 
518f6ff0ac8SSarah Sharp 	if (xhci_start(xhci)) {
519f6ff0ac8SSarah Sharp 		xhci_halt(xhci);
520a8089250SHongyu Xie 		spin_unlock_irqrestore(&xhci->lock, flags);
521f6ff0ac8SSarah Sharp 		return -ENODEV;
522f6ff0ac8SSarah Sharp 	}
523a8089250SHongyu Xie 
524c181bc5bSElric Fu 	xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
525f6ff0ac8SSarah Sharp 
526f6ff0ac8SSarah Sharp 	if (xhci->quirks & XHCI_NEC_HOST)
527f6ff0ac8SSarah Sharp 		xhci_ring_cmd_db(xhci);
528f6ff0ac8SSarah Sharp 
529a8089250SHongyu Xie 	spin_unlock_irqrestore(&xhci->lock, flags);
530a8089250SHongyu Xie 
531f6ff0ac8SSarah Sharp 	return 0;
532f6ff0ac8SSarah Sharp }
533f6ff0ac8SSarah Sharp 
534bc75fa38SAlex Chiang /*
535bc75fa38SAlex Chiang  * Start the HC after it was halted.
536bc75fa38SAlex Chiang  *
537bc75fa38SAlex Chiang  * This function is called by the USB core when the HC driver is added.
538bc75fa38SAlex Chiang  * Its opposite is xhci_stop().
539bc75fa38SAlex Chiang  *
540bc75fa38SAlex Chiang  * xhci_init() must be called once before this function can be called.
541bc75fa38SAlex Chiang  * Reset the HC, enable device slot contexts, program DCBAAP, and
542bc75fa38SAlex Chiang  * set command ring pointer and event ring pointer.
543bc75fa38SAlex Chiang  *
544bc75fa38SAlex Chiang  * Setup MSI-X vectors and enable interrupts.
545bc75fa38SAlex Chiang  */
xhci_run(struct usb_hcd * hcd)546bc75fa38SAlex Chiang int xhci_run(struct usb_hcd *hcd)
547bc75fa38SAlex Chiang {
548bc75fa38SAlex Chiang 	u64 temp_64;
5493fd1ec58SSebastian Andrzej Siewior 	int ret;
550bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
551c99b38c4SMathias Nyman 	struct xhci_interrupter *ir = xhci->interrupters[0];
552f6ff0ac8SSarah Sharp 	/* Start the xHCI host controller running only after the USB 2.0 roothub
553f6ff0ac8SSarah Sharp 	 * is setup.
554f6ff0ac8SSarah Sharp 	 */
555bc75fa38SAlex Chiang 
556bc75fa38SAlex Chiang 	hcd->uses_new_polling = 1;
5574f022aadSMathias Nyman 	if (hcd->msi_enabled)
5584f022aadSMathias Nyman 		ir->ip_autoclear = true;
5594f022aadSMathias Nyman 
560f6ff0ac8SSarah Sharp 	if (!usb_hcd_is_primary_hcd(hcd))
561f6ff0ac8SSarah Sharp 		return xhci_run_finished(xhci);
562bc75fa38SAlex Chiang 
563d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_run");
564bc75fa38SAlex Chiang 
565b17a57f8SMathias Nyman 	temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
56608cc5616SLukas Wunner 	temp_64 &= ERST_PTR_MASK;
567d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
568d195fcffSXenia Ragiadakou 			"ERST deq = 64'h%0lx", (long unsigned int) temp_64);
569bc75fa38SAlex Chiang 
570ace21625SMathias Nyman 	xhci_set_interrupter_moderation(ir, xhci->imod_interval);
571bc75fa38SAlex Chiang 
572ddba5cd0SMathias Nyman 	if (xhci->quirks & XHCI_NEC_HOST) {
573ddba5cd0SMathias Nyman 		struct xhci_command *command;
57474e0b564SLu Baolu 
575103afda0SMathias Nyman 		command = xhci_alloc_command(xhci, false, GFP_KERNEL);
576ddba5cd0SMathias Nyman 		if (!command)
577ddba5cd0SMathias Nyman 			return -ENOMEM;
57874e0b564SLu Baolu 
579d6f5f071SShu Wang 		ret = xhci_queue_vendor_command(xhci, command, 0, 0, 0,
5800238634dSSarah Sharp 				TRB_TYPE(TRB_NEC_GET_FW));
581d6f5f071SShu Wang 		if (ret)
582d6f5f071SShu Wang 			xhci_free_command(xhci, command);
583ddba5cd0SMathias Nyman 	}
584d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
585873f3236SHeiner Kallweit 			"Finished %s for main hcd", __func__);
58602b6fdc2SLu Baolu 
5875c44d9d7SMathias Nyman 	xhci_create_dbc_dev(xhci);
588dfba2174SLu Baolu 
58902b6fdc2SLu Baolu 	xhci_debugfs_init(xhci);
59002b6fdc2SLu Baolu 
591873f3236SHeiner Kallweit 	if (xhci_has_one_roothub(xhci))
592873f3236SHeiner Kallweit 		return xhci_run_finished(xhci);
593873f3236SHeiner Kallweit 
5941bd8bb7dSMathias Nyman 	set_bit(HCD_FLAG_DEFER_RH_REGISTER, &hcd->flags);
5951bd8bb7dSMathias Nyman 
596f6ff0ac8SSarah Sharp 	return 0;
597ed07453fSSarah Sharp }
598436e8c7dSAndrew Bresticker EXPORT_SYMBOL_GPL(xhci_run);
599ed07453fSSarah Sharp 
600bc75fa38SAlex Chiang /*
601bc75fa38SAlex Chiang  * Stop xHCI driver.
602bc75fa38SAlex Chiang  *
603bc75fa38SAlex Chiang  * This function is called by the USB core when the HC driver is removed.
604bc75fa38SAlex Chiang  * Its opposite is xhci_run().
605bc75fa38SAlex Chiang  *
606bc75fa38SAlex Chiang  * Disable device contexts, disable IRQs, and quiesce the HC.
607bc75fa38SAlex Chiang  * Reset the HC, finish any completed transactions, and cleanup memory.
608bc75fa38SAlex Chiang  */
xhci_stop(struct usb_hcd * hcd)609ed526ba2SJosue David Hernandez Gutierrez void xhci_stop(struct usb_hcd *hcd)
610bc75fa38SAlex Chiang {
611bc75fa38SAlex Chiang 	u32 temp;
612bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
613c99b38c4SMathias Nyman 	struct xhci_interrupter *ir = xhci->interrupters[0];
614bc75fa38SAlex Chiang 
6158c24d6d7SRoger Quadros 	mutex_lock(&xhci->mutex);
61627a41a83SGabriel Krisman Bertazi 
617fe190ed0SJoel Stanley 	/* Only halt host and free memory after both hcds are removed */
618fe190ed0SJoel Stanley 	if (!usb_hcd_is_primary_hcd(hcd)) {
619fe190ed0SJoel Stanley 		mutex_unlock(&xhci->mutex);
620fe190ed0SJoel Stanley 		return;
621fe190ed0SJoel Stanley 	}
62227a41a83SGabriel Krisman Bertazi 
6235c44d9d7SMathias Nyman 	xhci_remove_dbc_dev(xhci);
624dfba2174SLu Baolu 
625fe190ed0SJoel Stanley 	spin_lock_irq(&xhci->lock);
6268c24d6d7SRoger Quadros 	xhci->xhc_state |= XHCI_STATE_HALTED;
6278c24d6d7SRoger Quadros 	xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
628bc75fa38SAlex Chiang 	xhci_halt(xhci);
62914073ce9SMathias Nyman 	xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
630bc75fa38SAlex Chiang 	spin_unlock_irq(&xhci->lock);
631bc75fa38SAlex Chiang 
63271c731a2SAlexis R. Cortes 	/* Deleting Compliance Mode Recovery Timer */
63371c731a2SAlexis R. Cortes 	if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
63458b1d799STony Camuso 			(!(xhci_all_ports_seen_u0(xhci)))) {
63571c731a2SAlexis R. Cortes 		del_timer_sync(&xhci->comp_mode_recovery_timer);
6364bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
6374bdfe4c3SXenia Ragiadakou 				"%s: compliance mode recovery timer deleted",
63858b1d799STony Camuso 				__func__);
63958b1d799STony Camuso 	}
64071c731a2SAlexis R. Cortes 
641c41136b0SAndiry Xu 	if (xhci->quirks & XHCI_AMD_PLL_FIX)
642c41136b0SAndiry Xu 		usb_amd_dev_put();
643c41136b0SAndiry Xu 
644d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
645d195fcffSXenia Ragiadakou 			"// Disabling event ring interrupts");
646b0ba9720SXenia Ragiadakou 	temp = readl(&xhci->op_regs->status);
647d1001ab4SLu Baolu 	writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
64852dd0483SMathias Nyman 	xhci_disable_interrupter(ir);
649bc75fa38SAlex Chiang 
650d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
651bc75fa38SAlex Chiang 	xhci_mem_cleanup(xhci);
65211cd764dSZhengjun Xing 	xhci_debugfs_exit(xhci);
653d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
654d195fcffSXenia Ragiadakou 			"xhci_stop completed - status = %x",
655b0ba9720SXenia Ragiadakou 			readl(&xhci->op_regs->status));
65685ac90f8SRoger Quadros 	mutex_unlock(&xhci->mutex);
657bc75fa38SAlex Chiang }
658ed526ba2SJosue David Hernandez Gutierrez EXPORT_SYMBOL_GPL(xhci_stop);
659bc75fa38SAlex Chiang 
660bc75fa38SAlex Chiang /*
661bc75fa38SAlex Chiang  * Shutdown HC (not bus-specific)
662bc75fa38SAlex Chiang  *
663bc75fa38SAlex Chiang  * This is called when the machine is rebooting or halting.  We assume that the
664bc75fa38SAlex Chiang  * machine will be powered off, and the HC's internal state will be reset.
665bc75fa38SAlex Chiang  * Don't bother to free memory.
666f6ff0ac8SSarah Sharp  *
667f6ff0ac8SSarah Sharp  * This will only ever be called with the main usb_hcd (the USB3 roothub).
668bc75fa38SAlex Chiang  */
xhci_shutdown(struct usb_hcd * hcd)669f2c710f7SHenry Lin void xhci_shutdown(struct usb_hcd *hcd)
670bc75fa38SAlex Chiang {
671bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
672bc75fa38SAlex Chiang 
673052c7f9fSDan Carpenter 	if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
6744c39d4b9SArnd Bergmann 		usb_disable_xhci_ports(to_pci_dev(hcd->self.sysdev));
675e95829f4SSarah Sharp 
676dc92944aSHenry Lin 	/* Don't poll the roothubs after shutdown. */
677dc92944aSHenry Lin 	xhci_dbg(xhci, "%s: stopping usb%d port polling.\n",
678dc92944aSHenry Lin 			__func__, hcd->self.busnum);
679dc92944aSHenry Lin 	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
680dc92944aSHenry Lin 	del_timer_sync(&hcd->rh_timer);
681dc92944aSHenry Lin 
682dc92944aSHenry Lin 	if (xhci->shared_hcd) {
683dc92944aSHenry Lin 		clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
684dc92944aSHenry Lin 		del_timer_sync(&xhci->shared_hcd->rh_timer);
685dc92944aSHenry Lin 	}
686dc92944aSHenry Lin 
6878531aa16SMathias Nyman 	spin_lock_irq(&xhci->lock);
688bc75fa38SAlex Chiang 	xhci_halt(xhci);
68934cd2db4SMathias Nyman 
69034cd2db4SMathias Nyman 	/*
69134cd2db4SMathias Nyman 	 * Workaround for spurious wakeps at shutdown with HSW, and for boot
69234cd2db4SMathias Nyman 	 * firmware delay in ADL-P PCH if port are left in U3 at shutdown
69334cd2db4SMathias Nyman 	 */
69434cd2db4SMathias Nyman 	if (xhci->quirks & XHCI_SPURIOUS_WAKEUP ||
69534cd2db4SMathias Nyman 	    xhci->quirks & XHCI_RESET_TO_DEFAULT)
69614073ce9SMathias Nyman 		xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
69734cd2db4SMathias Nyman 
6988531aa16SMathias Nyman 	spin_unlock_irq(&xhci->lock);
699bc75fa38SAlex Chiang 
700d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
701d195fcffSXenia Ragiadakou 			"xhci_shutdown completed - status = %x",
702b0ba9720SXenia Ragiadakou 			readl(&xhci->op_regs->status));
703bc75fa38SAlex Chiang }
704f2c710f7SHenry Lin EXPORT_SYMBOL_GPL(xhci_shutdown);
705bc75fa38SAlex Chiang 
706b5b5c3acSSarah Sharp #ifdef CONFIG_PM
xhci_save_registers(struct xhci_hcd * xhci)7075535b1d5SAndiry Xu static void xhci_save_registers(struct xhci_hcd *xhci)
7085535b1d5SAndiry Xu {
709c99b38c4SMathias Nyman 	struct xhci_interrupter *ir;
710c99b38c4SMathias Nyman 	unsigned int i;
711b17a57f8SMathias Nyman 
712b0ba9720SXenia Ragiadakou 	xhci->s3.command = readl(&xhci->op_regs->command);
713b0ba9720SXenia Ragiadakou 	xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
714f7b2e403SSarah Sharp 	xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
715b0ba9720SXenia Ragiadakou 	xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
716b17a57f8SMathias Nyman 
717c99b38c4SMathias Nyman 	/* save both primary and all secondary interrupters */
718c99b38c4SMathias Nyman 	/* fixme, shold we lock  to prevent race with remove secondary interrupter? */
719c99b38c4SMathias Nyman 	for (i = 0; i < xhci->max_interrupters; i++) {
720c99b38c4SMathias Nyman 		ir = xhci->interrupters[i];
721b17a57f8SMathias Nyman 		if (!ir)
722c99b38c4SMathias Nyman 			continue;
723b17a57f8SMathias Nyman 
724b17a57f8SMathias Nyman 		ir->s3_erst_size = readl(&ir->ir_set->erst_size);
725b17a57f8SMathias Nyman 		ir->s3_erst_base = xhci_read_64(xhci, &ir->ir_set->erst_base);
726b17a57f8SMathias Nyman 		ir->s3_erst_dequeue = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
727b17a57f8SMathias Nyman 		ir->s3_irq_pending = readl(&ir->ir_set->irq_pending);
728b17a57f8SMathias Nyman 		ir->s3_irq_control = readl(&ir->ir_set->irq_control);
7295535b1d5SAndiry Xu 	}
730c99b38c4SMathias Nyman }
7315535b1d5SAndiry Xu 
xhci_restore_registers(struct xhci_hcd * xhci)7325535b1d5SAndiry Xu static void xhci_restore_registers(struct xhci_hcd *xhci)
7335535b1d5SAndiry Xu {
734c99b38c4SMathias Nyman 	struct xhci_interrupter *ir;
735c99b38c4SMathias Nyman 	unsigned int i;
736b17a57f8SMathias Nyman 
737204b7793SXenia Ragiadakou 	writel(xhci->s3.command, &xhci->op_regs->command);
738204b7793SXenia Ragiadakou 	writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
739477632dfSSarah Sharp 	xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
740204b7793SXenia Ragiadakou 	writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
741c99b38c4SMathias Nyman 
742c99b38c4SMathias Nyman 	/* FIXME should we lock to protect against freeing of interrupters */
743c99b38c4SMathias Nyman 	for (i = 0; i < xhci->max_interrupters; i++) {
744c99b38c4SMathias Nyman 		ir = xhci->interrupters[i];
745c99b38c4SMathias Nyman 		if (!ir)
746c99b38c4SMathias Nyman 			continue;
747c99b38c4SMathias Nyman 
748b17a57f8SMathias Nyman 		writel(ir->s3_erst_size, &ir->ir_set->erst_size);
749b17a57f8SMathias Nyman 		xhci_write_64(xhci, ir->s3_erst_base, &ir->ir_set->erst_base);
750b17a57f8SMathias Nyman 		xhci_write_64(xhci, ir->s3_erst_dequeue, &ir->ir_set->erst_dequeue);
751b17a57f8SMathias Nyman 		writel(ir->s3_irq_pending, &ir->ir_set->irq_pending);
752b17a57f8SMathias Nyman 		writel(ir->s3_irq_control, &ir->ir_set->irq_control);
7535535b1d5SAndiry Xu 	}
754c99b38c4SMathias Nyman }
7555535b1d5SAndiry Xu 
xhci_set_cmd_ring_deq(struct xhci_hcd * xhci)75689821320SSarah Sharp static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
75789821320SSarah Sharp {
75889821320SSarah Sharp 	u64	val_64;
75989821320SSarah Sharp 
76089821320SSarah Sharp 	/* step 2: initialize command ring buffer */
761f7b2e403SSarah Sharp 	val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
76289821320SSarah Sharp 	val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
76389821320SSarah Sharp 		(xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
76489821320SSarah Sharp 				      xhci->cmd_ring->dequeue) &
76589821320SSarah Sharp 		 (u64) ~CMD_RING_RSVD_BITS) |
76689821320SSarah Sharp 		xhci->cmd_ring->cycle_state;
767d195fcffSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
768d195fcffSXenia Ragiadakou 			"// Setting command ring address to 0x%llx",
76989821320SSarah Sharp 			(long unsigned long) val_64);
770477632dfSSarah Sharp 	xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
77189821320SSarah Sharp }
77289821320SSarah Sharp 
77389821320SSarah Sharp /*
77489821320SSarah Sharp  * The whole command ring must be cleared to zero when we suspend the host.
77589821320SSarah Sharp  *
77689821320SSarah Sharp  * The host doesn't save the command ring pointer in the suspend well, so we
77789821320SSarah Sharp  * need to re-program it on resume.  Unfortunately, the pointer must be 64-byte
77889821320SSarah Sharp  * aligned, because of the reserved bits in the command ring dequeue pointer
77989821320SSarah Sharp  * register.  Therefore, we can't just set the dequeue pointer back in the
78089821320SSarah Sharp  * middle of the ring (TRBs are 16-byte aligned).
78189821320SSarah Sharp  */
xhci_clear_command_ring(struct xhci_hcd * xhci)78289821320SSarah Sharp static void xhci_clear_command_ring(struct xhci_hcd *xhci)
78389821320SSarah Sharp {
78489821320SSarah Sharp 	struct xhci_ring *ring;
78589821320SSarah Sharp 	struct xhci_segment *seg;
78689821320SSarah Sharp 
78789821320SSarah Sharp 	ring = xhci->cmd_ring;
78889821320SSarah Sharp 	seg = ring->deq_seg;
78989821320SSarah Sharp 	do {
790158886cdSAndiry Xu 		memset(seg->trbs, 0,
791158886cdSAndiry Xu 			sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
792158886cdSAndiry Xu 		seg->trbs[TRBS_PER_SEGMENT - 1].link.control &=
793158886cdSAndiry Xu 			cpu_to_le32(~TRB_CYCLE);
79489821320SSarah Sharp 		seg = seg->next;
79589821320SSarah Sharp 	} while (seg != ring->deq_seg);
79689821320SSarah Sharp 
79700bdc4a3SNiklas Neronin 	xhci_initialize_ring_info(ring, 1);
79889821320SSarah Sharp 	/*
79989821320SSarah Sharp 	 * Reset the hardware dequeue pointer.
80089821320SSarah Sharp 	 * Yes, this will need to be re-written after resume, but we're paranoid
80189821320SSarah Sharp 	 * and want to make sure the hardware doesn't access bogus memory
80289821320SSarah Sharp 	 * because, say, the BIOS or an SMI started the host without changing
80389821320SSarah Sharp 	 * the command ring pointers.
80489821320SSarah Sharp 	 */
80589821320SSarah Sharp 	xhci_set_cmd_ring_deq(xhci);
80689821320SSarah Sharp }
80789821320SSarah Sharp 
808d26c00e7SMathias Nyman /*
809d26c00e7SMathias Nyman  * Disable port wake bits if do_wakeup is not set.
810d26c00e7SMathias Nyman  *
811d26c00e7SMathias Nyman  * Also clear a possible internal port wake state left hanging for ports that
812d26c00e7SMathias Nyman  * detected termination but never successfully enumerated (trained to 0U).
813d26c00e7SMathias Nyman  * Internal wake causes immediate xHCI wake after suspend. PORT_CSC write done
814d26c00e7SMathias Nyman  * at enumeration clears this wake, force one here as well for unconnected ports
815d26c00e7SMathias Nyman  */
816d26c00e7SMathias Nyman 
xhci_disable_hub_port_wake(struct xhci_hcd * xhci,struct xhci_hub * rhub,bool do_wakeup)817d26c00e7SMathias Nyman static void xhci_disable_hub_port_wake(struct xhci_hcd *xhci,
818d26c00e7SMathias Nyman 				       struct xhci_hub *rhub,
819d26c00e7SMathias Nyman 				       bool do_wakeup)
820a1377e53SLu Baolu {
821a1377e53SLu Baolu 	unsigned long flags;
822d70d5a84SMathias Nyman 	u32 t1, t2, portsc;
823d26c00e7SMathias Nyman 	int i;
824a1377e53SLu Baolu 
825a1377e53SLu Baolu 	spin_lock_irqsave(&xhci->lock, flags);
826a1377e53SLu Baolu 
827d26c00e7SMathias Nyman 	for (i = 0; i < rhub->num_ports; i++) {
828d26c00e7SMathias Nyman 		portsc = readl(rhub->ports[i]->addr);
829d26c00e7SMathias Nyman 		t1 = xhci_port_state_to_neutral(portsc);
830d26c00e7SMathias Nyman 		t2 = t1;
831a1377e53SLu Baolu 
832d26c00e7SMathias Nyman 		/* clear wake bits if do_wake is not set */
833d26c00e7SMathias Nyman 		if (!do_wakeup)
834d26c00e7SMathias Nyman 			t2 &= ~PORT_WAKE_BITS;
835d26c00e7SMathias Nyman 
836d26c00e7SMathias Nyman 		/* Don't touch csc bit if connected or connect change is set */
837d26c00e7SMathias Nyman 		if (!(portsc & (PORT_CSC | PORT_CONNECT)))
838d26c00e7SMathias Nyman 			t2 |= PORT_CSC;
839d26c00e7SMathias Nyman 
840d70d5a84SMathias Nyman 		if (t1 != t2) {
841d26c00e7SMathias Nyman 			writel(t2, rhub->ports[i]->addr);
842d26c00e7SMathias Nyman 			xhci_dbg(xhci, "config port %d-%d wake bits, portsc: 0x%x, write: 0x%x\n",
843d26c00e7SMathias Nyman 				 rhub->hcd->self.busnum, i + 1, portsc, t2);
844a1377e53SLu Baolu 		}
845d70d5a84SMathias Nyman 	}
846a1377e53SLu Baolu 	spin_unlock_irqrestore(&xhci->lock, flags);
847a1377e53SLu Baolu }
848a1377e53SLu Baolu 
xhci_pending_portevent(struct xhci_hcd * xhci)849229bc19fSMathias Nyman static bool xhci_pending_portevent(struct xhci_hcd *xhci)
850229bc19fSMathias Nyman {
851229bc19fSMathias Nyman 	struct xhci_port	**ports;
852229bc19fSMathias Nyman 	int			port_index;
853229bc19fSMathias Nyman 	u32			status;
854229bc19fSMathias Nyman 	u32			portsc;
855229bc19fSMathias Nyman 
856229bc19fSMathias Nyman 	status = readl(&xhci->op_regs->status);
857229bc19fSMathias Nyman 	if (status & STS_EINT)
858229bc19fSMathias Nyman 		return true;
859229bc19fSMathias Nyman 	/*
860229bc19fSMathias Nyman 	 * Checking STS_EINT is not enough as there is a lag between a change
861229bc19fSMathias Nyman 	 * bit being set and the Port Status Change Event that it generated
862229bc19fSMathias Nyman 	 * being written to the Event Ring. See note in xhci 1.1 section 4.19.2.
863229bc19fSMathias Nyman 	 */
864229bc19fSMathias Nyman 
865229bc19fSMathias Nyman 	port_index = xhci->usb2_rhub.num_ports;
866229bc19fSMathias Nyman 	ports = xhci->usb2_rhub.ports;
867229bc19fSMathias Nyman 	while (port_index--) {
868229bc19fSMathias Nyman 		portsc = readl(ports[port_index]->addr);
869229bc19fSMathias Nyman 		if (portsc & PORT_CHANGE_MASK ||
870229bc19fSMathias Nyman 		    (portsc & PORT_PLS_MASK) == XDEV_RESUME)
871229bc19fSMathias Nyman 			return true;
872229bc19fSMathias Nyman 	}
873229bc19fSMathias Nyman 	port_index = xhci->usb3_rhub.num_ports;
874229bc19fSMathias Nyman 	ports = xhci->usb3_rhub.ports;
875229bc19fSMathias Nyman 	while (port_index--) {
876229bc19fSMathias Nyman 		portsc = readl(ports[port_index]->addr);
877b9e43779SMathias Nyman 		if (portsc & (PORT_CHANGE_MASK | PORT_CAS) ||
878229bc19fSMathias Nyman 		    (portsc & PORT_PLS_MASK) == XDEV_RESUME)
879229bc19fSMathias Nyman 			return true;
880229bc19fSMathias Nyman 	}
881229bc19fSMathias Nyman 	return false;
882229bc19fSMathias Nyman }
883229bc19fSMathias Nyman 
8845535b1d5SAndiry Xu /*
8855535b1d5SAndiry Xu  * Stop HC (not bus-specific)
8865535b1d5SAndiry Xu  *
8875535b1d5SAndiry Xu  * This is called when the machine transition into S3/S4 mode.
8885535b1d5SAndiry Xu  *
8895535b1d5SAndiry Xu  */
xhci_suspend(struct xhci_hcd * xhci,bool do_wakeup)890a1377e53SLu Baolu int xhci_suspend(struct xhci_hcd *xhci, bool do_wakeup)
8915535b1d5SAndiry Xu {
8925535b1d5SAndiry Xu 	int			rc = 0;
8937c67cf66SKai-Heng Feng 	unsigned int		delay = XHCI_MAX_HALT_USEC * 2;
8945535b1d5SAndiry Xu 	struct usb_hcd		*hcd = xhci_to_hcd(xhci);
8955535b1d5SAndiry Xu 	u32			command;
896a7d57abcSSandeep Singh 	u32			res;
8975535b1d5SAndiry Xu 
8989fa733f2SRoger Quadros 	if (!hcd->state)
8999fa733f2SRoger Quadros 		return 0;
9009fa733f2SRoger Quadros 
90177b84767SFelipe Balbi 	if (hcd->state != HC_STATE_SUSPENDED ||
902873f3236SHeiner Kallweit 	    (xhci->shared_hcd && xhci->shared_hcd->state != HC_STATE_SUSPENDED))
90377b84767SFelipe Balbi 		return -EINVAL;
90477b84767SFelipe Balbi 
905a1377e53SLu Baolu 	/* Clear root port wake on bits if wakeup not allowed. */
906d26c00e7SMathias Nyman 	xhci_disable_hub_port_wake(xhci, &xhci->usb3_rhub, do_wakeup);
907d26c00e7SMathias Nyman 	xhci_disable_hub_port_wake(xhci, &xhci->usb2_rhub, do_wakeup);
908a1377e53SLu Baolu 
90918a367e8SPeter Chen 	if (!HCD_HW_ACCESSIBLE(hcd))
91018a367e8SPeter Chen 		return 0;
91118a367e8SPeter Chen 
91218a367e8SPeter Chen 	xhci_dbc_suspend(xhci);
91318a367e8SPeter Chen 
914c52804a4SSarah Sharp 	/* Don't poll the roothubs on bus suspend. */
915669bc5a1SMathias Nyman 	xhci_dbg(xhci, "%s: stopping usb%d port polling.\n",
916669bc5a1SMathias Nyman 		 __func__, hcd->self.busnum);
917c52804a4SSarah Sharp 	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
918c52804a4SSarah Sharp 	del_timer_sync(&hcd->rh_timer);
919873f3236SHeiner Kallweit 	if (xhci->shared_hcd) {
92014e61a1bSAl Cooper 		clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
92114e61a1bSAl Cooper 		del_timer_sync(&xhci->shared_hcd->rh_timer);
922873f3236SHeiner Kallweit 	}
923c52804a4SSarah Sharp 
924191edc5eSKai-Heng Feng 	if (xhci->quirks & XHCI_SUSPEND_DELAY)
925191edc5eSKai-Heng Feng 		usleep_range(1000, 1500);
926191edc5eSKai-Heng Feng 
9275535b1d5SAndiry Xu 	spin_lock_irq(&xhci->lock);
9285535b1d5SAndiry Xu 	clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
929873f3236SHeiner Kallweit 	if (xhci->shared_hcd)
930b3209379SSarah Sharp 		clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
9315535b1d5SAndiry Xu 	/* step 1: stop endpoint */
9325535b1d5SAndiry Xu 	/* skipped assuming that port suspend has done */
9335535b1d5SAndiry Xu 
9345535b1d5SAndiry Xu 	/* step 2: clear Run/Stop bit */
935b0ba9720SXenia Ragiadakou 	command = readl(&xhci->op_regs->command);
9365535b1d5SAndiry Xu 	command &= ~CMD_RUN;
937204b7793SXenia Ragiadakou 	writel(command, &xhci->op_regs->command);
938455f5892SOliver Neukum 
939455f5892SOliver Neukum 	/* Some chips from Fresco Logic need an extraordinary delay */
940455f5892SOliver Neukum 	delay *= (xhci->quirks & XHCI_SLOW_SUSPEND) ? 10 : 1;
941455f5892SOliver Neukum 
942dc0b177cSLin Wang 	if (xhci_handshake(&xhci->op_regs->status,
943455f5892SOliver Neukum 		      STS_HALT, STS_HALT, delay)) {
9445535b1d5SAndiry Xu 		xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
9455535b1d5SAndiry Xu 		spin_unlock_irq(&xhci->lock);
9465535b1d5SAndiry Xu 		return -ETIMEDOUT;
9475535b1d5SAndiry Xu 	}
94889821320SSarah Sharp 	xhci_clear_command_ring(xhci);
9495535b1d5SAndiry Xu 
9505535b1d5SAndiry Xu 	/* step 3: save registers */
9515535b1d5SAndiry Xu 	xhci_save_registers(xhci);
9525535b1d5SAndiry Xu 
9535535b1d5SAndiry Xu 	/* step 4: set CSS flag */
954b0ba9720SXenia Ragiadakou 	command = readl(&xhci->op_regs->command);
9555535b1d5SAndiry Xu 	command |= CMD_CSS;
956204b7793SXenia Ragiadakou 	writel(command, &xhci->op_regs->command);
957a7d57abcSSandeep Singh 	xhci->broken_suspend = 0;
958dc0b177cSLin Wang 	if (xhci_handshake(&xhci->op_regs->status,
959ac343366SKai-Heng Feng 				STS_SAVE, 0, 20 * 1000)) {
960a7d57abcSSandeep Singh 	/*
961a7d57abcSSandeep Singh 	 * AMD SNPS xHC 3.0 occasionally does not clear the
962a7d57abcSSandeep Singh 	 * SSS bit of USBSTS and when driver tries to poll
963a7d57abcSSandeep Singh 	 * to see if the xHC clears BIT(8) which never happens
964a7d57abcSSandeep Singh 	 * and driver assumes that controller is not responding
965a7d57abcSSandeep Singh 	 * and times out. To workaround this, its good to check
966a7d57abcSSandeep Singh 	 * if SRE and HCE bits are not set (as per xhci
967a7d57abcSSandeep Singh 	 * Section 5.4.2) and bypass the timeout.
968a7d57abcSSandeep Singh 	 */
969a7d57abcSSandeep Singh 		res = readl(&xhci->op_regs->status);
970a7d57abcSSandeep Singh 		if ((xhci->quirks & XHCI_SNPS_BROKEN_SUSPEND) &&
971a7d57abcSSandeep Singh 		    (((res & STS_SRE) == 0) &&
972a7d57abcSSandeep Singh 				((res & STS_HCE) == 0))) {
973a7d57abcSSandeep Singh 			xhci->broken_suspend = 1;
974a7d57abcSSandeep Singh 		} else {
975622eb783SAndiry Xu 			xhci_warn(xhci, "WARN: xHC save state timeout\n");
9765535b1d5SAndiry Xu 			spin_unlock_irq(&xhci->lock);
9775535b1d5SAndiry Xu 			return -ETIMEDOUT;
9785535b1d5SAndiry Xu 		}
979a7d57abcSSandeep Singh 	}
9805535b1d5SAndiry Xu 	spin_unlock_irq(&xhci->lock);
9815535b1d5SAndiry Xu 
98271c731a2SAlexis R. Cortes 	/*
98371c731a2SAlexis R. Cortes 	 * Deleting Compliance Mode Recovery Timer because the xHCI Host
98471c731a2SAlexis R. Cortes 	 * is about to be suspended.
98571c731a2SAlexis R. Cortes 	 */
98671c731a2SAlexis R. Cortes 	if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
98771c731a2SAlexis R. Cortes 			(!(xhci_all_ports_seen_u0(xhci)))) {
98871c731a2SAlexis R. Cortes 		del_timer_sync(&xhci->comp_mode_recovery_timer);
9894bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
9904bdfe4c3SXenia Ragiadakou 				"%s: compliance mode recovery timer deleted",
99158b1d799STony Camuso 				__func__);
99271c731a2SAlexis R. Cortes 	}
99371c731a2SAlexis R. Cortes 
9945535b1d5SAndiry Xu 	return rc;
9955535b1d5SAndiry Xu }
996436e8c7dSAndrew Bresticker EXPORT_SYMBOL_GPL(xhci_suspend);
9975535b1d5SAndiry Xu 
9985535b1d5SAndiry Xu /*
9995535b1d5SAndiry Xu  * start xHC (not bus-specific)
10005535b1d5SAndiry Xu  *
10015535b1d5SAndiry Xu  * This is called when the machine transition from S3/S4 mode.
10025535b1d5SAndiry Xu  *
10035535b1d5SAndiry Xu  */
xhci_resume(struct xhci_hcd * xhci,pm_message_t msg)10041f7d5520SBasavaraj Natikar int xhci_resume(struct xhci_hcd *xhci, pm_message_t msg)
10055535b1d5SAndiry Xu {
10061f7d5520SBasavaraj Natikar 	bool			hibernated = (msg.event == PM_EVENT_RESTORE);
1007229bc19fSMathias Nyman 	u32			command, temp = 0;
10085535b1d5SAndiry Xu 	struct usb_hcd		*hcd = xhci_to_hcd(xhci);
1009f69e3120SAlan Stern 	int			retval = 0;
101077df9e0bSTony Camuso 	bool			comp_timer_running = false;
1011253f588cSMathias Nyman 	bool			pending_portevent = false;
10126add6dd3SWesley Cheng 	bool			suspended_usb3_devs = false;
10138b328f80SPuma Hsu 	bool			reinit_xhc = false;
10145535b1d5SAndiry Xu 
10159fa733f2SRoger Quadros 	if (!hcd->state)
10169fa733f2SRoger Quadros 		return 0;
10179fa733f2SRoger Quadros 
1018f6ff0ac8SSarah Sharp 	/* Wait a bit if either of the roothubs need to settle from the
101925985edcSLucas De Marchi 	 * transition into bus suspend.
102020b67cf5SSarah Sharp 	 */
1021f6187f42SMathias Nyman 
1022f6187f42SMathias Nyman 	if (time_before(jiffies, xhci->usb2_rhub.bus_state.next_statechange) ||
1023f6187f42SMathias Nyman 	    time_before(jiffies, xhci->usb3_rhub.bus_state.next_statechange))
10245535b1d5SAndiry Xu 		msleep(100);
10255535b1d5SAndiry Xu 
1026f69e3120SAlan Stern 	set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1027873f3236SHeiner Kallweit 	if (xhci->shared_hcd)
1028f69e3120SAlan Stern 		set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1029f69e3120SAlan Stern 
10305535b1d5SAndiry Xu 	spin_lock_irq(&xhci->lock);
10315535b1d5SAndiry Xu 
10328b328f80SPuma Hsu 	if (hibernated || xhci->quirks & XHCI_RESET_ON_RESUME || xhci->broken_suspend)
10338b328f80SPuma Hsu 		reinit_xhc = true;
10348b328f80SPuma Hsu 
10358b328f80SPuma Hsu 	if (!reinit_xhc) {
1036a70bcbc3SRick Tseng 		/*
1037a70bcbc3SRick Tseng 		 * Some controllers might lose power during suspend, so wait
1038a70bcbc3SRick Tseng 		 * for controller not ready bit to clear, just as in xHC init.
1039a70bcbc3SRick Tseng 		 */
1040a70bcbc3SRick Tseng 		retval = xhci_handshake(&xhci->op_regs->status,
1041a70bcbc3SRick Tseng 					STS_CNR, 0, 10 * 1000 * 1000);
1042a70bcbc3SRick Tseng 		if (retval) {
1043a70bcbc3SRick Tseng 			xhci_warn(xhci, "Controller not ready at resume %d\n",
1044a70bcbc3SRick Tseng 				  retval);
1045a70bcbc3SRick Tseng 			spin_unlock_irq(&xhci->lock);
1046a70bcbc3SRick Tseng 			return retval;
1047a70bcbc3SRick Tseng 		}
10485535b1d5SAndiry Xu 		/* step 1: restore register */
10495535b1d5SAndiry Xu 		xhci_restore_registers(xhci);
10505535b1d5SAndiry Xu 		/* step 2: initialize command ring buffer */
105189821320SSarah Sharp 		xhci_set_cmd_ring_deq(xhci);
10525535b1d5SAndiry Xu 		/* step 3: restore state and start state*/
10535535b1d5SAndiry Xu 		/* step 3: set CRS flag */
1054b0ba9720SXenia Ragiadakou 		command = readl(&xhci->op_regs->command);
10555535b1d5SAndiry Xu 		command |= CMD_CRS;
1056204b7793SXenia Ragiadakou 		writel(command, &xhci->op_regs->command);
1057305886caSAjay Gupta 		/*
1058305886caSAjay Gupta 		 * Some controllers take up to 55+ ms to complete the controller
1059305886caSAjay Gupta 		 * restore so setting the timeout to 100ms. Xhci specification
1060305886caSAjay Gupta 		 * doesn't mention any timeout value.
1061305886caSAjay Gupta 		 */
1062dc0b177cSLin Wang 		if (xhci_handshake(&xhci->op_regs->status,
1063305886caSAjay Gupta 			      STS_RESTORE, 0, 100 * 1000)) {
1064622eb783SAndiry Xu 			xhci_warn(xhci, "WARN: xHC restore state timeout\n");
10655535b1d5SAndiry Xu 			spin_unlock_irq(&xhci->lock);
10665535b1d5SAndiry Xu 			return -ETIMEDOUT;
10675535b1d5SAndiry Xu 		}
10685535b1d5SAndiry Xu 	}
10695535b1d5SAndiry Xu 
10708b328f80SPuma Hsu 	temp = readl(&xhci->op_regs->status);
107177df9e0bSTony Camuso 
10728b328f80SPuma Hsu 	/* re-initialize the HC on Restore Error, or Host Controller Error */
1073fb2ce178SWesley Cheng 	if ((temp & (STS_SRE | STS_HCE)) &&
1074fb2ce178SWesley Cheng 	    !(xhci->xhc_state & XHCI_STATE_REMOVING)) {
10758b328f80SPuma Hsu 		reinit_xhc = true;
1076484d6f7aSMario Limonciello 		if (!xhci->broken_suspend)
10778b328f80SPuma Hsu 			xhci_warn(xhci, "xHC error in resume, USBSTS 0x%x, Reinit\n", temp);
10788b328f80SPuma Hsu 	}
10798b328f80SPuma Hsu 
10808b328f80SPuma Hsu 	if (reinit_xhc) {
108177df9e0bSTony Camuso 		if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
108277df9e0bSTony Camuso 				!(xhci_all_ports_seen_u0(xhci))) {
108377df9e0bSTony Camuso 			del_timer_sync(&xhci->comp_mode_recovery_timer);
10844bdfe4c3SXenia Ragiadakou 			xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
10854bdfe4c3SXenia Ragiadakou 				"Compliance Mode Recovery Timer deleted!");
108677df9e0bSTony Camuso 		}
108777df9e0bSTony Camuso 
1088fedd383eSSarah Sharp 		/* Let the USB core know _both_ roothubs lost power. */
1089fedd383eSSarah Sharp 		usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1090873f3236SHeiner Kallweit 		if (xhci->shared_hcd)
1091fedd383eSSarah Sharp 			usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
10925535b1d5SAndiry Xu 
10935535b1d5SAndiry Xu 		xhci_dbg(xhci, "Stop HCD\n");
10945535b1d5SAndiry Xu 		xhci_halt(xhci);
109512de0a35SMarc Zyngier 		xhci_zero_64b_regs(xhci);
109614073ce9SMathias Nyman 		retval = xhci_reset(xhci, XHCI_RESET_LONG_USEC);
10975535b1d5SAndiry Xu 		spin_unlock_irq(&xhci->lock);
109872ae1947SMathias Nyman 		if (retval)
109972ae1947SMathias Nyman 			return retval;
11005535b1d5SAndiry Xu 
11015535b1d5SAndiry Xu 		xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1102b0ba9720SXenia Ragiadakou 		temp = readl(&xhci->op_regs->status);
1103d1001ab4SLu Baolu 		writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
1104c99b38c4SMathias Nyman 		xhci_disable_interrupter(xhci->interrupters[0]);
11055535b1d5SAndiry Xu 
11065535b1d5SAndiry Xu 		xhci_dbg(xhci, "cleaning up memory\n");
11075535b1d5SAndiry Xu 		xhci_mem_cleanup(xhci);
1108d9167671SZhengjun Xing 		xhci_debugfs_exit(xhci);
11095535b1d5SAndiry Xu 		xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1110b0ba9720SXenia Ragiadakou 			    readl(&xhci->op_regs->status));
11115535b1d5SAndiry Xu 
111265b22f93SSarah Sharp 		/* USB core calls the PCI reinit and start functions twice:
111365b22f93SSarah Sharp 		 * first with the primary HCD, and then with the secondary HCD.
111465b22f93SSarah Sharp 		 * If we don't do the same, the host will never be started.
111565b22f93SSarah Sharp 		 */
111665b22f93SSarah Sharp 		xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1117802dcafcSMathias Nyman 		retval = xhci_init(hcd);
11185535b1d5SAndiry Xu 		if (retval)
11195535b1d5SAndiry Xu 			return retval;
112077df9e0bSTony Camuso 		comp_timer_running = true;
112177df9e0bSTony Camuso 
112265b22f93SSarah Sharp 		xhci_dbg(xhci, "Start the primary HCD\n");
1123802dcafcSMathias Nyman 		retval = xhci_run(hcd);
1124802dcafcSMathias Nyman 		if (!retval && xhci->shared_hcd) {
112565b22f93SSarah Sharp 			xhci_dbg(xhci, "Start the secondary HCD\n");
1126802dcafcSMathias Nyman 			retval = xhci_run(xhci->shared_hcd);
1127b3209379SSarah Sharp 		}
112879989bd4SMathias Nyman 		if (retval)
112979989bd4SMathias Nyman 			return retval;
113079989bd4SMathias Nyman 		/*
113179989bd4SMathias Nyman 		 * Resume roothubs unconditionally as PORTSC change bits are not
113279989bd4SMathias Nyman 		 * immediately visible after xHC reset
113379989bd4SMathias Nyman 		 */
11345535b1d5SAndiry Xu 		hcd->state = HC_STATE_SUSPENDED;
113579989bd4SMathias Nyman 
113679989bd4SMathias Nyman 		if (xhci->shared_hcd) {
1137b3209379SSarah Sharp 			xhci->shared_hcd->state = HC_STATE_SUSPENDED;
113879989bd4SMathias Nyman 			usb_hcd_resume_root_hub(xhci->shared_hcd);
113979989bd4SMathias Nyman 		}
114079989bd4SMathias Nyman 		usb_hcd_resume_root_hub(hcd);
114179989bd4SMathias Nyman 
1142f69e3120SAlan Stern 		goto done;
11435535b1d5SAndiry Xu 	}
11445535b1d5SAndiry Xu 
11455535b1d5SAndiry Xu 	/* step 4: set Run/Stop bit */
1146b0ba9720SXenia Ragiadakou 	command = readl(&xhci->op_regs->command);
11475535b1d5SAndiry Xu 	command |= CMD_RUN;
1148204b7793SXenia Ragiadakou 	writel(command, &xhci->op_regs->command);
1149dc0b177cSLin Wang 	xhci_handshake(&xhci->op_regs->status, STS_HALT,
11505535b1d5SAndiry Xu 		  0, 250 * 1000);
11515535b1d5SAndiry Xu 
11525535b1d5SAndiry Xu 	/* step 5: walk topology and initialize portsc,
11535535b1d5SAndiry Xu 	 * portpmsc and portli
11545535b1d5SAndiry Xu 	 */
11555535b1d5SAndiry Xu 	/* this is done in bus_resume */
11565535b1d5SAndiry Xu 
11575535b1d5SAndiry Xu 	/* step 6: restart each of the previously
11585535b1d5SAndiry Xu 	 * Running endpoints by ringing their doorbells
11595535b1d5SAndiry Xu 	 */
11605535b1d5SAndiry Xu 
11615535b1d5SAndiry Xu 	spin_unlock_irq(&xhci->lock);
1162f69e3120SAlan Stern 
1163dfba2174SLu Baolu 	xhci_dbc_resume(xhci);
1164dfba2174SLu Baolu 
1165f69e3120SAlan Stern 	if (retval == 0) {
1166253f588cSMathias Nyman 		/*
1167253f588cSMathias Nyman 		 * Resume roothubs only if there are pending events.
1168253f588cSMathias Nyman 		 * USB 3 devices resend U3 LFPS wake after a 100ms delay if
11696add6dd3SWesley Cheng 		 * the first wake signalling failed, give it that chance if
11706add6dd3SWesley Cheng 		 * there are suspended USB 3 devices.
1171253f588cSMathias Nyman 		 */
11726add6dd3SWesley Cheng 		if (xhci->usb3_rhub.bus_state.suspended_ports ||
11736add6dd3SWesley Cheng 		    xhci->usb3_rhub.bus_state.bus_suspended)
11746add6dd3SWesley Cheng 			suspended_usb3_devs = true;
11756add6dd3SWesley Cheng 
1176253f588cSMathias Nyman 		pending_portevent = xhci_pending_portevent(xhci);
11776add6dd3SWesley Cheng 
11786add6dd3SWesley Cheng 		if (suspended_usb3_devs && !pending_portevent &&
11796add6dd3SWesley Cheng 		    msg.event == PM_EVENT_AUTO_RESUME) {
1180253f588cSMathias Nyman 			msleep(120);
1181253f588cSMathias Nyman 			pending_portevent = xhci_pending_portevent(xhci);
1182253f588cSMathias Nyman 		}
1183253f588cSMathias Nyman 
1184253f588cSMathias Nyman 		if (pending_portevent) {
1185873f3236SHeiner Kallweit 			if (xhci->shared_hcd)
1186f69e3120SAlan Stern 				usb_hcd_resume_root_hub(xhci->shared_hcd);
1187671ffdffSMathias Nyman 			usb_hcd_resume_root_hub(hcd);
1188f69e3120SAlan Stern 		}
1189d6236f6dSWang, Yu 	}
119079989bd4SMathias Nyman done:
119171c731a2SAlexis R. Cortes 	/*
119271c731a2SAlexis R. Cortes 	 * If system is subject to the Quirk, Compliance Mode Timer needs to
119371c731a2SAlexis R. Cortes 	 * be re-initialized Always after a system resume. Ports are subject
119471c731a2SAlexis R. Cortes 	 * to suffer the Compliance Mode issue again. It doesn't matter if
119571c731a2SAlexis R. Cortes 	 * ports have entered previously to U0 before system's suspension.
119671c731a2SAlexis R. Cortes 	 */
119777df9e0bSTony Camuso 	if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
119871c731a2SAlexis R. Cortes 		compliance_mode_recovery_timer_init(xhci);
119971c731a2SAlexis R. Cortes 
12009da5a109SJiahau Chang 	if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
12019da5a109SJiahau Chang 		usb_asmedia_modifyflowcontrol(to_pci_dev(hcd->self.controller));
12029da5a109SJiahau Chang 
1203c52804a4SSarah Sharp 	/* Re-enable port polling. */
1204669bc5a1SMathias Nyman 	xhci_dbg(xhci, "%s: starting usb%d port polling.\n",
1205669bc5a1SMathias Nyman 		 __func__, hcd->self.busnum);
1206873f3236SHeiner Kallweit 	if (xhci->shared_hcd) {
120714e61a1bSAl Cooper 		set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
120814e61a1bSAl Cooper 		usb_hcd_poll_rh_status(xhci->shared_hcd);
1209873f3236SHeiner Kallweit 	}
1210671ffdffSMathias Nyman 	set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1211671ffdffSMathias Nyman 	usb_hcd_poll_rh_status(hcd);
1212c52804a4SSarah Sharp 
1213f69e3120SAlan Stern 	return retval;
12145535b1d5SAndiry Xu }
1215436e8c7dSAndrew Bresticker EXPORT_SYMBOL_GPL(xhci_resume);
1216b5b5c3acSSarah Sharp #endif	/* CONFIG_PM */
1217b5b5c3acSSarah Sharp 
1218bc75fa38SAlex Chiang /*-------------------------------------------------------------------------*/
1219bc75fa38SAlex Chiang 
xhci_map_temp_buffer(struct usb_hcd * hcd,struct urb * urb)12202017a1e5STejas Joglekar static int xhci_map_temp_buffer(struct usb_hcd *hcd, struct urb *urb)
12212017a1e5STejas Joglekar {
12222017a1e5STejas Joglekar 	void *temp;
12232017a1e5STejas Joglekar 	int ret = 0;
12242017a1e5STejas Joglekar 	unsigned int buf_len;
12252017a1e5STejas Joglekar 	enum dma_data_direction dir;
12262017a1e5STejas Joglekar 
12272017a1e5STejas Joglekar 	dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
12282017a1e5STejas Joglekar 	buf_len = urb->transfer_buffer_length;
12292017a1e5STejas Joglekar 
12302017a1e5STejas Joglekar 	temp = kzalloc_node(buf_len, GFP_ATOMIC,
12312017a1e5STejas Joglekar 			    dev_to_node(hcd->self.sysdev));
1232be95cc6dSPrashanth K 	if (!temp)
1233be95cc6dSPrashanth K 		return -ENOMEM;
12342017a1e5STejas Joglekar 
12352017a1e5STejas Joglekar 	if (usb_urb_dir_out(urb))
12362017a1e5STejas Joglekar 		sg_pcopy_to_buffer(urb->sg, urb->num_sgs,
12372017a1e5STejas Joglekar 				   temp, buf_len, 0);
12382017a1e5STejas Joglekar 
12392017a1e5STejas Joglekar 	urb->transfer_buffer = temp;
12402017a1e5STejas Joglekar 	urb->transfer_dma = dma_map_single(hcd->self.sysdev,
12412017a1e5STejas Joglekar 					   urb->transfer_buffer,
12422017a1e5STejas Joglekar 					   urb->transfer_buffer_length,
12432017a1e5STejas Joglekar 					   dir);
12442017a1e5STejas Joglekar 
12452017a1e5STejas Joglekar 	if (dma_mapping_error(hcd->self.sysdev,
12462017a1e5STejas Joglekar 			      urb->transfer_dma)) {
12472017a1e5STejas Joglekar 		ret = -EAGAIN;
12482017a1e5STejas Joglekar 		kfree(temp);
12492017a1e5STejas Joglekar 	} else {
12502017a1e5STejas Joglekar 		urb->transfer_flags |= URB_DMA_MAP_SINGLE;
12512017a1e5STejas Joglekar 	}
12522017a1e5STejas Joglekar 
12532017a1e5STejas Joglekar 	return ret;
12542017a1e5STejas Joglekar }
12552017a1e5STejas Joglekar 
xhci_urb_temp_buffer_required(struct usb_hcd * hcd,struct urb * urb)12562017a1e5STejas Joglekar static bool xhci_urb_temp_buffer_required(struct usb_hcd *hcd,
12572017a1e5STejas Joglekar 					  struct urb *urb)
12582017a1e5STejas Joglekar {
12592017a1e5STejas Joglekar 	bool ret = false;
12602017a1e5STejas Joglekar 	unsigned int i;
12612017a1e5STejas Joglekar 	unsigned int len = 0;
12622017a1e5STejas Joglekar 	unsigned int trb_size;
12632017a1e5STejas Joglekar 	unsigned int max_pkt;
12642017a1e5STejas Joglekar 	struct scatterlist *sg;
12652017a1e5STejas Joglekar 	struct scatterlist *tail_sg;
12662017a1e5STejas Joglekar 
12672017a1e5STejas Joglekar 	tail_sg = urb->sg;
12682017a1e5STejas Joglekar 	max_pkt = usb_endpoint_maxp(&urb->ep->desc);
12692017a1e5STejas Joglekar 
12702017a1e5STejas Joglekar 	if (!urb->num_sgs)
12712017a1e5STejas Joglekar 		return ret;
12722017a1e5STejas Joglekar 
12732017a1e5STejas Joglekar 	if (urb->dev->speed >= USB_SPEED_SUPER)
12742017a1e5STejas Joglekar 		trb_size = TRB_CACHE_SIZE_SS;
12752017a1e5STejas Joglekar 	else
12762017a1e5STejas Joglekar 		trb_size = TRB_CACHE_SIZE_HS;
12772017a1e5STejas Joglekar 
12782017a1e5STejas Joglekar 	if (urb->transfer_buffer_length != 0 &&
12792017a1e5STejas Joglekar 	    !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)) {
12802017a1e5STejas Joglekar 		for_each_sg(urb->sg, sg, urb->num_sgs, i) {
12812017a1e5STejas Joglekar 			len = len + sg->length;
12822017a1e5STejas Joglekar 			if (i > trb_size - 2) {
12832017a1e5STejas Joglekar 				len = len - tail_sg->length;
12842017a1e5STejas Joglekar 				if (len < max_pkt) {
12852017a1e5STejas Joglekar 					ret = true;
12862017a1e5STejas Joglekar 					break;
12872017a1e5STejas Joglekar 				}
12882017a1e5STejas Joglekar 
12892017a1e5STejas Joglekar 				tail_sg = sg_next(tail_sg);
12902017a1e5STejas Joglekar 			}
12912017a1e5STejas Joglekar 		}
12922017a1e5STejas Joglekar 	}
12932017a1e5STejas Joglekar 	return ret;
12942017a1e5STejas Joglekar }
12952017a1e5STejas Joglekar 
xhci_unmap_temp_buf(struct usb_hcd * hcd,struct urb * urb)12962017a1e5STejas Joglekar static void xhci_unmap_temp_buf(struct usb_hcd *hcd, struct urb *urb)
12972017a1e5STejas Joglekar {
12982017a1e5STejas Joglekar 	unsigned int len;
12992017a1e5STejas Joglekar 	unsigned int buf_len;
13002017a1e5STejas Joglekar 	enum dma_data_direction dir;
13012017a1e5STejas Joglekar 
13022017a1e5STejas Joglekar 	dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
13032017a1e5STejas Joglekar 
13042017a1e5STejas Joglekar 	buf_len = urb->transfer_buffer_length;
13052017a1e5STejas Joglekar 
13062017a1e5STejas Joglekar 	if (IS_ENABLED(CONFIG_HAS_DMA) &&
13072017a1e5STejas Joglekar 	    (urb->transfer_flags & URB_DMA_MAP_SINGLE))
13082017a1e5STejas Joglekar 		dma_unmap_single(hcd->self.sysdev,
13092017a1e5STejas Joglekar 				 urb->transfer_dma,
13102017a1e5STejas Joglekar 				 urb->transfer_buffer_length,
13112017a1e5STejas Joglekar 				 dir);
13122017a1e5STejas Joglekar 
1313271a21d8SMathias Nyman 	if (usb_urb_dir_in(urb)) {
13142017a1e5STejas Joglekar 		len = sg_pcopy_from_buffer(urb->sg, urb->num_sgs,
13152017a1e5STejas Joglekar 					   urb->transfer_buffer,
13162017a1e5STejas Joglekar 					   buf_len,
13172017a1e5STejas Joglekar 					   0);
1318271a21d8SMathias Nyman 		if (len != buf_len) {
1319271a21d8SMathias Nyman 			xhci_dbg(hcd_to_xhci(hcd),
1320271a21d8SMathias Nyman 				 "Copy from tmp buf to urb sg list failed\n");
1321271a21d8SMathias Nyman 			urb->actual_length = len;
1322271a21d8SMathias Nyman 		}
1323271a21d8SMathias Nyman 	}
13242017a1e5STejas Joglekar 	urb->transfer_flags &= ~URB_DMA_MAP_SINGLE;
13252017a1e5STejas Joglekar 	kfree(urb->transfer_buffer);
13262017a1e5STejas Joglekar 	urb->transfer_buffer = NULL;
13272017a1e5STejas Joglekar }
13282017a1e5STejas Joglekar 
132933e39350SNicolas Saenz Julienne /*
133033e39350SNicolas Saenz Julienne  * Bypass the DMA mapping if URB is suitable for Immediate Transfer (IDT),
133133e39350SNicolas Saenz Julienne  * we'll copy the actual data into the TRB address register. This is limited to
133233e39350SNicolas Saenz Julienne  * transfers up to 8 bytes on output endpoints of any kind with wMaxPacketSize
133333e39350SNicolas Saenz Julienne  * >= 8 bytes. If suitable for IDT only one Transfer TRB per TD is allowed.
133433e39350SNicolas Saenz Julienne  */
xhci_map_urb_for_dma(struct usb_hcd * hcd,struct urb * urb,gfp_t mem_flags)133533e39350SNicolas Saenz Julienne static int xhci_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
133633e39350SNicolas Saenz Julienne 				gfp_t mem_flags)
133733e39350SNicolas Saenz Julienne {
13382017a1e5STejas Joglekar 	struct xhci_hcd *xhci;
13392017a1e5STejas Joglekar 
13402017a1e5STejas Joglekar 	xhci = hcd_to_xhci(hcd);
13412017a1e5STejas Joglekar 
134233e39350SNicolas Saenz Julienne 	if (xhci_urb_suitable_for_idt(urb))
134333e39350SNicolas Saenz Julienne 		return 0;
134433e39350SNicolas Saenz Julienne 
13452017a1e5STejas Joglekar 	if (xhci->quirks & XHCI_SG_TRB_CACHE_SIZE_QUIRK) {
13462017a1e5STejas Joglekar 		if (xhci_urb_temp_buffer_required(hcd, urb))
13472017a1e5STejas Joglekar 			return xhci_map_temp_buffer(hcd, urb);
13482017a1e5STejas Joglekar 	}
134933e39350SNicolas Saenz Julienne 	return usb_hcd_map_urb_for_dma(hcd, urb, mem_flags);
135033e39350SNicolas Saenz Julienne }
135133e39350SNicolas Saenz Julienne 
xhci_unmap_urb_for_dma(struct usb_hcd * hcd,struct urb * urb)13522017a1e5STejas Joglekar static void xhci_unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
13532017a1e5STejas Joglekar {
13542017a1e5STejas Joglekar 	struct xhci_hcd *xhci;
13552017a1e5STejas Joglekar 	bool unmap_temp_buf = false;
13562017a1e5STejas Joglekar 
13572017a1e5STejas Joglekar 	xhci = hcd_to_xhci(hcd);
13582017a1e5STejas Joglekar 
13592017a1e5STejas Joglekar 	if (urb->num_sgs && (urb->transfer_flags & URB_DMA_MAP_SINGLE))
13602017a1e5STejas Joglekar 		unmap_temp_buf = true;
13612017a1e5STejas Joglekar 
13622017a1e5STejas Joglekar 	if ((xhci->quirks & XHCI_SG_TRB_CACHE_SIZE_QUIRK) && unmap_temp_buf)
13632017a1e5STejas Joglekar 		xhci_unmap_temp_buf(hcd, urb);
13642017a1e5STejas Joglekar 	else
13652017a1e5STejas Joglekar 		usb_hcd_unmap_urb_for_dma(hcd, urb);
13662017a1e5STejas Joglekar }
13672017a1e5STejas Joglekar 
13682017a1e5STejas Joglekar /**
1369bc75fa38SAlex Chiang  * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1370bc75fa38SAlex Chiang  * HCDs.  Find the index for an endpoint given its descriptor.  Use the return
1371bc75fa38SAlex Chiang  * value to right shift 1 for the bitmask.
1372bc75fa38SAlex Chiang  *
1373bc75fa38SAlex Chiang  * Index  = (epnum * 2) + direction - 1,
1374bc75fa38SAlex Chiang  * where direction = 0 for OUT, 1 for IN.
1375bc75fa38SAlex Chiang  * For control endpoints, the IN index is used (OUT index is unused), so
1376bc75fa38SAlex Chiang  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1377bc75fa38SAlex Chiang  */
xhci_get_endpoint_index(struct usb_endpoint_descriptor * desc)1378bc75fa38SAlex Chiang unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1379bc75fa38SAlex Chiang {
1380bc75fa38SAlex Chiang 	unsigned int index;
1381bc75fa38SAlex Chiang 	if (usb_endpoint_xfer_control(desc))
1382bc75fa38SAlex Chiang 		index = (unsigned int) (usb_endpoint_num(desc)*2);
1383bc75fa38SAlex Chiang 	else
1384bc75fa38SAlex Chiang 		index = (unsigned int) (usb_endpoint_num(desc)*2) +
1385bc75fa38SAlex Chiang 			(usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1386bc75fa38SAlex Chiang 	return index;
1387bc75fa38SAlex Chiang }
138814295a15SChunfeng Yun EXPORT_SYMBOL_GPL(xhci_get_endpoint_index);
1389bc75fa38SAlex Chiang 
139001c5f447SJulius Werner /* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
139101c5f447SJulius Werner  * address from the XHCI endpoint index.
139201c5f447SJulius Werner  */
xhci_get_endpoint_address(unsigned int ep_index)1393d017aeafSGreg Kroah-Hartman static unsigned int xhci_get_endpoint_address(unsigned int ep_index)
139401c5f447SJulius Werner {
139501c5f447SJulius Werner 	unsigned int number = DIV_ROUND_UP(ep_index, 2);
139601c5f447SJulius Werner 	unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
139701c5f447SJulius Werner 	return direction | number;
139801c5f447SJulius Werner }
139901c5f447SJulius Werner 
1400bc75fa38SAlex Chiang /* Find the flag for this endpoint (for use in the control context).  Use the
1401bc75fa38SAlex Chiang  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1402bc75fa38SAlex Chiang  * bit 1, etc.
1403bc75fa38SAlex Chiang  */
xhci_get_endpoint_flag(struct usb_endpoint_descriptor * desc)14043969384cSLu Baolu static unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1405bc75fa38SAlex Chiang {
1406bc75fa38SAlex Chiang 	return 1 << (xhci_get_endpoint_index(desc) + 1);
1407bc75fa38SAlex Chiang }
1408bc75fa38SAlex Chiang 
1409bc75fa38SAlex Chiang /* Compute the last valid endpoint context index.  Basically, this is the
1410bc75fa38SAlex Chiang  * endpoint index plus one.  For slot contexts with more than valid endpoint,
1411bc75fa38SAlex Chiang  * we find the most significant bit set in the added contexts flags.
1412bc75fa38SAlex Chiang  * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1413bc75fa38SAlex Chiang  * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1414bc75fa38SAlex Chiang  */
xhci_last_valid_endpoint(u32 added_ctxs)1415bc75fa38SAlex Chiang unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1416bc75fa38SAlex Chiang {
1417bc75fa38SAlex Chiang 	return fls(added_ctxs) - 1;
1418bc75fa38SAlex Chiang }
1419bc75fa38SAlex Chiang 
1420bc75fa38SAlex Chiang /* Returns 1 if the arguments are OK;
1421bc75fa38SAlex Chiang  * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1422bc75fa38SAlex Chiang  */
xhci_check_args(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint * ep,int check_ep,bool check_virt_dev,const char * func)14238212a49dSDmitry Torokhov static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
142464927730SAndiry Xu 		struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
142564927730SAndiry Xu 		const char *func) {
142664927730SAndiry Xu 	struct xhci_hcd	*xhci;
142764927730SAndiry Xu 	struct xhci_virt_device	*virt_dev;
142864927730SAndiry Xu 
1429bc75fa38SAlex Chiang 	if (!hcd || (check_ep && !ep) || !udev) {
14305c1127d3SXenia Ragiadakou 		pr_debug("xHCI %s called with invalid args\n", func);
1431bc75fa38SAlex Chiang 		return -EINVAL;
1432bc75fa38SAlex Chiang 	}
1433bc75fa38SAlex Chiang 	if (!udev->parent) {
14345c1127d3SXenia Ragiadakou 		pr_debug("xHCI %s called for root hub\n", func);
1435bc75fa38SAlex Chiang 		return 0;
1436bc75fa38SAlex Chiang 	}
143764927730SAndiry Xu 
143864927730SAndiry Xu 	xhci = hcd_to_xhci(hcd);
14397bd89b40SSarah Sharp 	if (check_virt_dev) {
144073ddc247Ssifram.rajas@gmail.com 		if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
14415c1127d3SXenia Ragiadakou 			xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
14425c1127d3SXenia Ragiadakou 					func);
1443bc75fa38SAlex Chiang 			return -EINVAL;
1444bc75fa38SAlex Chiang 		}
144564927730SAndiry Xu 
144664927730SAndiry Xu 		virt_dev = xhci->devs[udev->slot_id];
144764927730SAndiry Xu 		if (virt_dev->udev != udev) {
14485c1127d3SXenia Ragiadakou 			xhci_dbg(xhci, "xHCI %s called with udev and "
144964927730SAndiry Xu 					  "virt_dev does not match\n", func);
145064927730SAndiry Xu 			return -EINVAL;
145164927730SAndiry Xu 		}
145264927730SAndiry Xu 	}
145364927730SAndiry Xu 
1454203a8661SSarah Sharp 	if (xhci->xhc_state & XHCI_STATE_HALTED)
1455203a8661SSarah Sharp 		return -ENODEV;
1456203a8661SSarah Sharp 
1457bc75fa38SAlex Chiang 	return 1;
1458bc75fa38SAlex Chiang }
1459bc75fa38SAlex Chiang 
1460bc75fa38SAlex Chiang static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1461bc75fa38SAlex Chiang 		struct usb_device *udev, struct xhci_command *command,
1462bc75fa38SAlex Chiang 		bool ctx_change, bool must_succeed);
1463bc75fa38SAlex Chiang 
1464bc75fa38SAlex Chiang /*
1465bc75fa38SAlex Chiang  * Full speed devices may have a max packet size greater than 8 bytes, but the
1466bc75fa38SAlex Chiang  * USB core doesn't know that until it reads the first 8 bytes of the
1467bc75fa38SAlex Chiang  * descriptor.  If the usb_device's max packet size changes after that point,
1468bc75fa38SAlex Chiang  * we need to issue an evaluate context command and wait on it.
1469bc75fa38SAlex Chiang  */
xhci_check_ep0_maxpacket(struct xhci_hcd * xhci,struct xhci_virt_device * vdev)1470e34900f4SMathias Nyman static int xhci_check_ep0_maxpacket(struct xhci_hcd *xhci, struct xhci_virt_device *vdev)
1471bc75fa38SAlex Chiang {
1472bc75fa38SAlex Chiang 	struct xhci_input_control_ctx *ctrl_ctx;
1473bc75fa38SAlex Chiang 	struct xhci_ep_ctx *ep_ctx;
1474ddba5cd0SMathias Nyman 	struct xhci_command *command;
1475bc75fa38SAlex Chiang 	int max_packet_size;
1476bc75fa38SAlex Chiang 	int hw_max_packet_size;
1477bc75fa38SAlex Chiang 	int ret = 0;
1478bc75fa38SAlex Chiang 
1479e34900f4SMathias Nyman 	ep_ctx = xhci_get_ep_ctx(xhci, vdev->out_ctx, 0);
148028ccd296SMatt Evans 	hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1481e34900f4SMathias Nyman 	max_packet_size = usb_endpoint_maxp(&vdev->udev->ep0.desc);
1482e34900f4SMathias Nyman 
1483e34900f4SMathias Nyman 	if (hw_max_packet_size == max_packet_size)
1484e34900f4SMathias Nyman 		return 0;
1485e34900f4SMathias Nyman 
1486e34900f4SMathias Nyman 	switch (max_packet_size) {
1487e34900f4SMathias Nyman 	case 8: case 16: case 32: case 64: case 9:
14883a7fa5beSXenia Ragiadakou 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
14893a7fa5beSXenia Ragiadakou 				"Max Packet Size for ep 0 changed.");
14903a7fa5beSXenia Ragiadakou 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
14913a7fa5beSXenia Ragiadakou 				"Max packet size in usb_device = %d",
1492bc75fa38SAlex Chiang 				max_packet_size);
14933a7fa5beSXenia Ragiadakou 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
14943a7fa5beSXenia Ragiadakou 				"Max packet size in xHCI HW = %d",
1495bc75fa38SAlex Chiang 				hw_max_packet_size);
14963a7fa5beSXenia Ragiadakou 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
14973a7fa5beSXenia Ragiadakou 				"Issuing evaluate context command.");
1498bc75fa38SAlex Chiang 
1499e34900f4SMathias Nyman 		command = xhci_alloc_command(xhci, true, GFP_KERNEL);
1500ddba5cd0SMathias Nyman 		if (!command)
1501ddba5cd0SMathias Nyman 			return -ENOMEM;
1502ddba5cd0SMathias Nyman 
1503e34900f4SMathias Nyman 		command->in_ctx = vdev->in_ctx;
15044daf9df5SLin Wang 		ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
150592f8e767SSarah Sharp 		if (!ctrl_ctx) {
150692f8e767SSarah Sharp 			xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
150792f8e767SSarah Sharp 					__func__);
1508ddba5cd0SMathias Nyman 			ret = -ENOMEM;
1509e34900f4SMathias Nyman 			break;
151092f8e767SSarah Sharp 		}
151192f8e767SSarah Sharp 		/* Set up the modified control endpoint 0 */
1512e34900f4SMathias Nyman 		xhci_endpoint_copy(xhci, vdev->in_ctx, vdev->out_ctx, 0);
151392f8e767SSarah Sharp 
1514e34900f4SMathias Nyman 		ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, 0);
1515a73d9d9cSAl Cooper 		ep_ctx->ep_info &= cpu_to_le32(~EP_STATE_MASK);/* must clear */
151692f8e767SSarah Sharp 		ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
151792f8e767SSarah Sharp 		ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
151892f8e767SSarah Sharp 
151928ccd296SMatt Evans 		ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1520bc75fa38SAlex Chiang 		ctrl_ctx->drop_flags = 0;
1521bc75fa38SAlex Chiang 
1522e34900f4SMathias Nyman 		ret = xhci_configure_endpoint(xhci, vdev->udev, command,
1523bc75fa38SAlex Chiang 					      true, false);
1524e34900f4SMathias Nyman 		/* Clean up the input context for later use by bandwidth functions */
152528ccd296SMatt Evans 		ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1526e34900f4SMathias Nyman 		break;
1527e34900f4SMathias Nyman 	default:
1528e34900f4SMathias Nyman 		dev_dbg(&vdev->udev->dev, "incorrect max packet size %d for ep0\n",
1529e34900f4SMathias Nyman 			max_packet_size);
1530e34900f4SMathias Nyman 		return -EINVAL;
1531e34900f4SMathias Nyman 	}
1532e34900f4SMathias Nyman 
1533ddba5cd0SMathias Nyman 	kfree(command->completion);
1534ddba5cd0SMathias Nyman 	kfree(command);
1535e34900f4SMathias Nyman 
1536bc75fa38SAlex Chiang 	return ret;
1537bc75fa38SAlex Chiang }
1538bc75fa38SAlex Chiang 
1539bc75fa38SAlex Chiang /*
1540bc75fa38SAlex Chiang  * non-error returns are a promise to giveback() the urb later
1541bc75fa38SAlex Chiang  * we drop ownership so next owner (or urb unlink) can get it
1542bc75fa38SAlex Chiang  */
xhci_urb_enqueue(struct usb_hcd * hcd,struct urb * urb,gfp_t mem_flags)15433969384cSLu Baolu static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1544bc75fa38SAlex Chiang {
1545bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1546bc75fa38SAlex Chiang 	unsigned long flags;
1547bc75fa38SAlex Chiang 	int ret = 0;
154815febf5eSMathias Nyman 	unsigned int slot_id, ep_index;
154915febf5eSMathias Nyman 	unsigned int *ep_state;
15508e51adccSAndiry Xu 	struct urb_priv	*urb_priv;
15517e64b037SMathias Nyman 	int num_tds;
1552bc75fa38SAlex Chiang 
1553bc75fa38SAlex Chiang 	ep_index = xhci_get_endpoint_index(&urb->ep->desc);
15548e51adccSAndiry Xu 
15558e51adccSAndiry Xu 	if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1556e6f7caa3SMathias Nyman 		num_tds = urb->number_of_packets;
15574758dcd1SReyad Attiyat 	else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
15584758dcd1SReyad Attiyat 	    urb->transfer_buffer_length > 0 &&
15594758dcd1SReyad Attiyat 	    urb->transfer_flags & URB_ZERO_PACKET &&
15604758dcd1SReyad Attiyat 	    !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
1561e6f7caa3SMathias Nyman 		num_tds = 2;
15628e51adccSAndiry Xu 	else
1563e6f7caa3SMathias Nyman 		num_tds = 1;
15648e51adccSAndiry Xu 
1565da79ff6eSGustavo A. R. Silva 	urb_priv = kzalloc(struct_size(urb_priv, td, num_tds), mem_flags);
15668e51adccSAndiry Xu 	if (!urb_priv)
15678e51adccSAndiry Xu 		return -ENOMEM;
15688e51adccSAndiry Xu 
15699ef7fbbbSMathias Nyman 	urb_priv->num_tds = num_tds;
15709ef7fbbbSMathias Nyman 	urb_priv->num_tds_done = 0;
15718e51adccSAndiry Xu 	urb->hcpriv = urb_priv;
15728e51adccSAndiry Xu 
15735abdc2e6SFelipe Balbi 	trace_xhci_urb_enqueue(urb);
15745abdc2e6SFelipe Balbi 
1575bc75fa38SAlex Chiang 	spin_lock_irqsave(&xhci->lock, flags);
15766969408dSMathias Nyman 
1577e2e2aacfSMathias Nyman 	ret = xhci_check_args(hcd, urb->dev, urb->ep,
1578e2e2aacfSMathias Nyman 			      true, true, __func__);
1579e2e2aacfSMathias Nyman 	if (ret <= 0) {
1580e2e2aacfSMathias Nyman 		ret = ret ? ret : -EINVAL;
1581e2e2aacfSMathias Nyman 		goto free_priv;
1582e2e2aacfSMathias Nyman 	}
1583e2e2aacfSMathias Nyman 
1584e2e2aacfSMathias Nyman 	slot_id = urb->dev->slot_id;
1585e2e2aacfSMathias Nyman 
1586e2e2aacfSMathias Nyman 	if (!HCD_HW_ACCESSIBLE(hcd)) {
1587e2e2aacfSMathias Nyman 		ret = -ESHUTDOWN;
1588e2e2aacfSMathias Nyman 		goto free_priv;
1589e2e2aacfSMathias Nyman 	}
1590e2e2aacfSMathias Nyman 
1591e2e2aacfSMathias Nyman 	if (xhci->devs[slot_id]->flags & VDEV_PORT_ERROR) {
1592e2e2aacfSMathias Nyman 		xhci_dbg(xhci, "Can't queue urb, port error, link inactive\n");
1593e2e2aacfSMathias Nyman 		ret = -ENODEV;
1594e2e2aacfSMathias Nyman 		goto free_priv;
1595e2e2aacfSMathias Nyman 	}
1596e2e2aacfSMathias Nyman 
15976969408dSMathias Nyman 	if (xhci->xhc_state & XHCI_STATE_DYING) {
15986969408dSMathias Nyman 		xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n",
1599bc75fa38SAlex Chiang 			 urb->ep->desc.bEndpointAddress, urb);
1600d13565c1SSarah Sharp 		ret = -ESHUTDOWN;
16016969408dSMathias Nyman 		goto free_priv;
16026969408dSMathias Nyman 	}
1603e2e2aacfSMathias Nyman 
1604e2e2aacfSMathias Nyman 	ep_state = &xhci->devs[slot_id]->eps[ep_index].ep_state;
1605e2e2aacfSMathias Nyman 
160615febf5eSMathias Nyman 	if (*ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) {
160715febf5eSMathias Nyman 		xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n",
160815febf5eSMathias Nyman 			  *ep_state);
160915febf5eSMathias Nyman 		ret = -EINVAL;
161015febf5eSMathias Nyman 		goto free_priv;
161115febf5eSMathias Nyman 	}
1612f5249461SMathias Nyman 	if (*ep_state & EP_SOFT_CLEAR_TOGGLE) {
1613f5249461SMathias Nyman 		xhci_warn(xhci, "Can't enqueue URB while manually clearing toggle\n");
1614f5249461SMathias Nyman 		ret = -EINVAL;
1615f5249461SMathias Nyman 		goto free_priv;
1616f5249461SMathias Nyman 	}
16176969408dSMathias Nyman 
16186969408dSMathias Nyman 	switch (usb_endpoint_type(&urb->ep->desc)) {
16196969408dSMathias Nyman 
16206969408dSMathias Nyman 	case USB_ENDPOINT_XFER_CONTROL:
16216969408dSMathias Nyman 		ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
16226969408dSMathias Nyman 					 slot_id, ep_index);
16236969408dSMathias Nyman 		break;
16246969408dSMathias Nyman 	case USB_ENDPOINT_XFER_BULK:
16256969408dSMathias Nyman 		ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
16266969408dSMathias Nyman 					 slot_id, ep_index);
16276969408dSMathias Nyman 		break;
16286969408dSMathias Nyman 	case USB_ENDPOINT_XFER_INT:
16296969408dSMathias Nyman 		ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
16306969408dSMathias Nyman 				slot_id, ep_index);
16316969408dSMathias Nyman 		break;
16326969408dSMathias Nyman 	case USB_ENDPOINT_XFER_ISOC:
16336969408dSMathias Nyman 		ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
16346969408dSMathias Nyman 				slot_id, ep_index);
16356969408dSMathias Nyman 	}
16366969408dSMathias Nyman 
16376969408dSMathias Nyman 	if (ret) {
1638d13565c1SSarah Sharp free_priv:
16394daf9df5SLin Wang 		xhci_urb_free_priv(urb_priv);
1640d13565c1SSarah Sharp 		urb->hcpriv = NULL;
16416969408dSMathias Nyman 	}
1642bc75fa38SAlex Chiang 	spin_unlock_irqrestore(&xhci->lock, flags);
1643d13565c1SSarah Sharp 	return ret;
1644bc75fa38SAlex Chiang }
1645bc75fa38SAlex Chiang 
1646bc75fa38SAlex Chiang /*
1647bc75fa38SAlex Chiang  * Remove the URB's TD from the endpoint ring.  This may cause the HC to stop
1648bc75fa38SAlex Chiang  * USB transfers, potentially stopping in the middle of a TRB buffer.  The HC
1649bc75fa38SAlex Chiang  * should pick up where it left off in the TD, unless a Set Transfer Ring
1650bc75fa38SAlex Chiang  * Dequeue Pointer is issued.
1651bc75fa38SAlex Chiang  *
1652bc75fa38SAlex Chiang  * The TRBs that make up the buffers for the canceled URB will be "removed" from
1653bc75fa38SAlex Chiang  * the ring.  Since the ring is a contiguous structure, they can't be physically
1654bc75fa38SAlex Chiang  * removed.  Instead, there are two options:
1655bc75fa38SAlex Chiang  *
1656bc75fa38SAlex Chiang  *  1) If the HC is in the middle of processing the URB to be canceled, we
1657bc75fa38SAlex Chiang  *     simply move the ring's dequeue pointer past those TRBs using the Set
1658bc75fa38SAlex Chiang  *     Transfer Ring Dequeue Pointer command.  This will be the common case,
1659bc75fa38SAlex Chiang  *     when drivers timeout on the last submitted URB and attempt to cancel.
1660bc75fa38SAlex Chiang  *
1661bc75fa38SAlex Chiang  *  2) If the HC is in the middle of a different TD, we turn the TRBs into a
1662bc75fa38SAlex Chiang  *     series of 1-TRB transfer no-op TDs.  (No-ops shouldn't be chained.)  The
1663bc75fa38SAlex Chiang  *     HC will need to invalidate the any TRBs it has cached after the stop
1664bc75fa38SAlex Chiang  *     endpoint command, as noted in the xHCI 0.95 errata.
1665bc75fa38SAlex Chiang  *
1666bc75fa38SAlex Chiang  *  3) The TD may have completed by the time the Stop Endpoint Command
1667bc75fa38SAlex Chiang  *     completes, so software needs to handle that case too.
1668bc75fa38SAlex Chiang  *
1669bc75fa38SAlex Chiang  * This function should protect against the TD enqueueing code ringing the
1670bc75fa38SAlex Chiang  * doorbell while this code is waiting for a Stop Endpoint command to complete.
1671bc75fa38SAlex Chiang  * It also needs to account for multiple cancellations on happening at the same
1672bc75fa38SAlex Chiang  * time for the same endpoint.
1673bc75fa38SAlex Chiang  *
1674bc75fa38SAlex Chiang  * Note that this function can be called in any context, or so says
1675bc75fa38SAlex Chiang  * usb_hcd_unlink_urb()
1676bc75fa38SAlex Chiang  */
xhci_urb_dequeue(struct usb_hcd * hcd,struct urb * urb,int status)16773969384cSLu Baolu static int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1678bc75fa38SAlex Chiang {
1679bc75fa38SAlex Chiang 	unsigned long flags;
16808e51adccSAndiry Xu 	int ret, i;
1681bc75fa38SAlex Chiang 	u32 temp;
1682bc75fa38SAlex Chiang 	struct xhci_hcd *xhci;
16838e51adccSAndiry Xu 	struct urb_priv	*urb_priv;
1684bc75fa38SAlex Chiang 	struct xhci_td *td;
1685bc75fa38SAlex Chiang 	unsigned int ep_index;
1686bc75fa38SAlex Chiang 	struct xhci_ring *ep_ring;
1687bc75fa38SAlex Chiang 	struct xhci_virt_ep *ep;
1688ddba5cd0SMathias Nyman 	struct xhci_command *command;
1689d3519b9dSMathias Nyman 	struct xhci_virt_device *vdev;
1690bc75fa38SAlex Chiang 
1691bc75fa38SAlex Chiang 	xhci = hcd_to_xhci(hcd);
1692bc75fa38SAlex Chiang 	spin_lock_irqsave(&xhci->lock, flags);
16935abdc2e6SFelipe Balbi 
16945abdc2e6SFelipe Balbi 	trace_xhci_urb_dequeue(urb);
16955abdc2e6SFelipe Balbi 
1696bc75fa38SAlex Chiang 	/* Make sure the URB hasn't completed or been unlinked already */
1697bc75fa38SAlex Chiang 	ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1698d3519b9dSMathias Nyman 	if (ret)
1699bc75fa38SAlex Chiang 		goto done;
1700d3519b9dSMathias Nyman 
1701d3519b9dSMathias Nyman 	/* give back URB now if we can't queue it for cancel */
1702d3519b9dSMathias Nyman 	vdev = xhci->devs[urb->dev->slot_id];
1703d3519b9dSMathias Nyman 	urb_priv = urb->hcpriv;
1704d3519b9dSMathias Nyman 	if (!vdev || !urb_priv)
1705d3519b9dSMathias Nyman 		goto err_giveback;
1706d3519b9dSMathias Nyman 
1707d3519b9dSMathias Nyman 	ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1708d3519b9dSMathias Nyman 	ep = &vdev->eps[ep_index];
1709d3519b9dSMathias Nyman 	ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1710d3519b9dSMathias Nyman 	if (!ep || !ep_ring)
1711d3519b9dSMathias Nyman 		goto err_giveback;
1712d3519b9dSMathias Nyman 
1713d9f11ba9SMathias Nyman 	/* If xHC is dead take it down and return ALL URBs in xhci_hc_died() */
1714b0ba9720SXenia Ragiadakou 	temp = readl(&xhci->op_regs->status);
1715d9f11ba9SMathias Nyman 	if (temp == ~(u32)0 || xhci->xhc_state & XHCI_STATE_DYING) {
1716d9f11ba9SMathias Nyman 		xhci_hc_died(xhci);
1717d9f11ba9SMathias Nyman 		goto done;
1718d9f11ba9SMathias Nyman 	}
1719d9f11ba9SMathias Nyman 
17204937213bSMathias Nyman 	/*
17214937213bSMathias Nyman 	 * check ring is not re-allocated since URB was enqueued. If it is, then
17224937213bSMathias Nyman 	 * make sure none of the ring related pointers in this URB private data
17234937213bSMathias Nyman 	 * are touched, such as td_list, otherwise we overwrite freed data
17244937213bSMathias Nyman 	 */
17254937213bSMathias Nyman 	if (!td_on_ring(&urb_priv->td[0], ep_ring)) {
17264937213bSMathias Nyman 		xhci_err(xhci, "Canceled URB td not found on endpoint ring");
17274937213bSMathias Nyman 		for (i = urb_priv->num_tds_done; i < urb_priv->num_tds; i++) {
17284937213bSMathias Nyman 			td = &urb_priv->td[i];
17294937213bSMathias Nyman 			if (!list_empty(&td->cancelled_td_list))
17304937213bSMathias Nyman 				list_del_init(&td->cancelled_td_list);
17314937213bSMathias Nyman 		}
17324937213bSMathias Nyman 		goto err_giveback;
17334937213bSMathias Nyman 	}
17344937213bSMathias Nyman 
1735d9f11ba9SMathias Nyman 	if (xhci->xhc_state & XHCI_STATE_HALTED) {
1736aa50b290SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1737d9f11ba9SMathias Nyman 				"HC halted, freeing TD manually.");
17389ef7fbbbSMathias Nyman 		for (i = urb_priv->num_tds_done;
1739d3519b9dSMathias Nyman 		     i < urb_priv->num_tds;
17405c821711SMathias Nyman 		     i++) {
17417e64b037SMathias Nyman 			td = &urb_priv->td[i];
1742585df1d9SSarah Sharp 			if (!list_empty(&td->td_list))
1743585df1d9SSarah Sharp 				list_del_init(&td->td_list);
1744585df1d9SSarah Sharp 			if (!list_empty(&td->cancelled_td_list))
1745585df1d9SSarah Sharp 				list_del_init(&td->cancelled_td_list);
1746585df1d9SSarah Sharp 		}
1747d3519b9dSMathias Nyman 		goto err_giveback;
1748bc75fa38SAlex Chiang 	}
1749bc75fa38SAlex Chiang 
17509ef7fbbbSMathias Nyman 	i = urb_priv->num_tds_done;
17519ef7fbbbSMathias Nyman 	if (i < urb_priv->num_tds)
1752aa50b290SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1753aa50b290SXenia Ragiadakou 				"Cancel URB %p, dev %s, ep 0x%x, "
1754aa50b290SXenia Ragiadakou 				"starting at offset 0x%llx",
175579688acfSSarah Sharp 				urb, urb->dev->devpath,
175679688acfSSarah Sharp 				urb->ep->desc.bEndpointAddress,
175779688acfSSarah Sharp 				(unsigned long long) xhci_trb_virt_to_dma(
17587e64b037SMathias Nyman 					urb_priv->td[i].start_seg,
17597e64b037SMathias Nyman 					urb_priv->td[i].first_trb));
17608e51adccSAndiry Xu 
17619ef7fbbbSMathias Nyman 	for (; i < urb_priv->num_tds; i++) {
17627e64b037SMathias Nyman 		td = &urb_priv->td[i];
1763674f8438SMathias Nyman 		/* TD can already be on cancelled list if ep halted on it */
1764674f8438SMathias Nyman 		if (list_empty(&td->cancelled_td_list)) {
1765674f8438SMathias Nyman 			td->cancel_status = TD_DIRTY;
1766674f8438SMathias Nyman 			list_add_tail(&td->cancelled_td_list,
1767674f8438SMathias Nyman 				      &ep->cancelled_td_list);
1768674f8438SMathias Nyman 		}
17698e51adccSAndiry Xu 	}
17708e51adccSAndiry Xu 
1771bc75fa38SAlex Chiang 	/* Queue a stop endpoint command, but only if this is
1772bc75fa38SAlex Chiang 	 * the first cancellation to be handled.
1773bc75fa38SAlex Chiang 	 */
17749983a5fcSMathias Nyman 	if (!(ep->ep_state & EP_STOP_CMD_PENDING)) {
1775103afda0SMathias Nyman 		command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
1776a0ee619fSHans de Goede 		if (!command) {
1777a0ee619fSHans de Goede 			ret = -ENOMEM;
1778a0ee619fSHans de Goede 			goto done;
1779a0ee619fSHans de Goede 		}
17809983a5fcSMathias Nyman 		ep->ep_state |= EP_STOP_CMD_PENDING;
1781ddba5cd0SMathias Nyman 		xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1782ddba5cd0SMathias Nyman 					 ep_index, 0);
1783bc75fa38SAlex Chiang 		xhci_ring_cmd_db(xhci);
1784bc75fa38SAlex Chiang 	}
1785bc75fa38SAlex Chiang done:
1786bc75fa38SAlex Chiang 	spin_unlock_irqrestore(&xhci->lock, flags);
1787bc75fa38SAlex Chiang 	return ret;
1788d3519b9dSMathias Nyman 
1789d3519b9dSMathias Nyman err_giveback:
1790d3519b9dSMathias Nyman 	if (urb_priv)
1791d3519b9dSMathias Nyman 		xhci_urb_free_priv(urb_priv);
1792d3519b9dSMathias Nyman 	usb_hcd_unlink_urb_from_ep(hcd, urb);
1793d3519b9dSMathias Nyman 	spin_unlock_irqrestore(&xhci->lock, flags);
1794d3519b9dSMathias Nyman 	usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1795d3519b9dSMathias Nyman 	return ret;
1796bc75fa38SAlex Chiang }
1797bc75fa38SAlex Chiang 
1798bc75fa38SAlex Chiang /* Drop an endpoint from a new bandwidth configuration for this device.
1799bc75fa38SAlex Chiang  * Only one call to this function is allowed per endpoint before
1800bc75fa38SAlex Chiang  * check_bandwidth() or reset_bandwidth() must be called.
1801bc75fa38SAlex Chiang  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1802bc75fa38SAlex Chiang  * add the endpoint to the schedule with possibly new parameters denoted by a
1803bc75fa38SAlex Chiang  * different endpoint descriptor in usb_host_endpoint.
1804bc75fa38SAlex Chiang  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1805bc75fa38SAlex Chiang  * not allowed.
1806bc75fa38SAlex Chiang  *
1807bc75fa38SAlex Chiang  * The USB core will not allow URBs to be queued to an endpoint that is being
1808bc75fa38SAlex Chiang  * disabled, so there's no need for mutual exclusion to protect
1809bc75fa38SAlex Chiang  * the xhci->devs[slot_id] structure.
1810bc75fa38SAlex Chiang  */
xhci_drop_endpoint(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint * ep)181114295a15SChunfeng Yun int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1812bc75fa38SAlex Chiang 		       struct usb_host_endpoint *ep)
1813bc75fa38SAlex Chiang {
1814bc75fa38SAlex Chiang 	struct xhci_hcd *xhci;
1815bc75fa38SAlex Chiang 	struct xhci_container_ctx *in_ctx, *out_ctx;
1816bc75fa38SAlex Chiang 	struct xhci_input_control_ctx *ctrl_ctx;
1817bc75fa38SAlex Chiang 	unsigned int ep_index;
1818bc75fa38SAlex Chiang 	struct xhci_ep_ctx *ep_ctx;
1819bc75fa38SAlex Chiang 	u32 drop_flag;
1820d6759133SJulius Werner 	u32 new_add_flags, new_drop_flags;
1821bc75fa38SAlex Chiang 	int ret;
1822bc75fa38SAlex Chiang 
182364927730SAndiry Xu 	ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1824bc75fa38SAlex Chiang 	if (ret <= 0)
1825bc75fa38SAlex Chiang 		return ret;
1826bc75fa38SAlex Chiang 	xhci = hcd_to_xhci(hcd);
1827fe6c6c13SSarah Sharp 	if (xhci->xhc_state & XHCI_STATE_DYING)
1828fe6c6c13SSarah Sharp 		return -ENODEV;
1829bc75fa38SAlex Chiang 
1830fe6c6c13SSarah Sharp 	xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1831bc75fa38SAlex Chiang 	drop_flag = xhci_get_endpoint_flag(&ep->desc);
1832bc75fa38SAlex Chiang 	if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1833bc75fa38SAlex Chiang 		xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1834bc75fa38SAlex Chiang 				__func__, drop_flag);
1835bc75fa38SAlex Chiang 		return 0;
1836bc75fa38SAlex Chiang 	}
1837bc75fa38SAlex Chiang 
1838bc75fa38SAlex Chiang 	in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1839bc75fa38SAlex Chiang 	out_ctx = xhci->devs[udev->slot_id]->out_ctx;
18404daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
184192f8e767SSarah Sharp 	if (!ctrl_ctx) {
184292f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
184392f8e767SSarah Sharp 				__func__);
184492f8e767SSarah Sharp 		return 0;
184592f8e767SSarah Sharp 	}
184692f8e767SSarah Sharp 
1847bc75fa38SAlex Chiang 	ep_index = xhci_get_endpoint_index(&ep->desc);
1848bc75fa38SAlex Chiang 	ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1849bc75fa38SAlex Chiang 	/* If the HC already knows the endpoint is disabled,
1850bc75fa38SAlex Chiang 	 * or the HCD has noted it is disabled, ignore this request
1851bc75fa38SAlex Chiang 	 */
18525071e6b2SMathias Nyman 	if ((GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) ||
185328ccd296SMatt Evans 	    le32_to_cpu(ctrl_ctx->drop_flags) &
185428ccd296SMatt Evans 	    xhci_get_endpoint_flag(&ep->desc)) {
1855a6134136SHans de Goede 		/* Do not warn when called after a usb_device_reset */
1856a6134136SHans de Goede 		if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1857bc75fa38SAlex Chiang 			xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1858bc75fa38SAlex Chiang 				  __func__, ep);
1859bc75fa38SAlex Chiang 		return 0;
1860bc75fa38SAlex Chiang 	}
1861bc75fa38SAlex Chiang 
186228ccd296SMatt Evans 	ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
186328ccd296SMatt Evans 	new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1864bc75fa38SAlex Chiang 
186528ccd296SMatt Evans 	ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
186628ccd296SMatt Evans 	new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1867bc75fa38SAlex Chiang 
186802b6fdc2SLu Baolu 	xhci_debugfs_remove_endpoint(xhci, xhci->devs[udev->slot_id], ep_index);
186902b6fdc2SLu Baolu 
1870bc75fa38SAlex Chiang 	xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1871bc75fa38SAlex Chiang 
1872d6759133SJulius Werner 	xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1873bc75fa38SAlex Chiang 			(unsigned int) ep->desc.bEndpointAddress,
1874bc75fa38SAlex Chiang 			udev->slot_id,
1875bc75fa38SAlex Chiang 			(unsigned int) new_drop_flags,
1876d6759133SJulius Werner 			(unsigned int) new_add_flags);
1877bc75fa38SAlex Chiang 	return 0;
1878bc75fa38SAlex Chiang }
187914295a15SChunfeng Yun EXPORT_SYMBOL_GPL(xhci_drop_endpoint);
1880bc75fa38SAlex Chiang 
1881bc75fa38SAlex Chiang /* Add an endpoint to a new possible bandwidth configuration for this device.
1882bc75fa38SAlex Chiang  * Only one call to this function is allowed per endpoint before
1883bc75fa38SAlex Chiang  * check_bandwidth() or reset_bandwidth() must be called.
1884bc75fa38SAlex Chiang  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1885bc75fa38SAlex Chiang  * add the endpoint to the schedule with possibly new parameters denoted by a
1886bc75fa38SAlex Chiang  * different endpoint descriptor in usb_host_endpoint.
1887bc75fa38SAlex Chiang  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1888bc75fa38SAlex Chiang  * not allowed.
1889bc75fa38SAlex Chiang  *
1890bc75fa38SAlex Chiang  * The USB core will not allow URBs to be queued to an endpoint until the
1891bc75fa38SAlex Chiang  * configuration or alt setting is installed in the device, so there's no need
1892bc75fa38SAlex Chiang  * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1893bc75fa38SAlex Chiang  */
xhci_add_endpoint(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint * ep)189414295a15SChunfeng Yun int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1895bc75fa38SAlex Chiang 		      struct usb_host_endpoint *ep)
1896bc75fa38SAlex Chiang {
1897bc75fa38SAlex Chiang 	struct xhci_hcd *xhci;
189892c9691bSLin Wang 	struct xhci_container_ctx *in_ctx;
1899bc75fa38SAlex Chiang 	unsigned int ep_index;
1900bc75fa38SAlex Chiang 	struct xhci_input_control_ctx *ctrl_ctx;
19015afa0a5eSMathias Nyman 	struct xhci_ep_ctx *ep_ctx;
1902bc75fa38SAlex Chiang 	u32 added_ctxs;
1903d6759133SJulius Werner 	u32 new_add_flags, new_drop_flags;
1904fa75ac37SSarah Sharp 	struct xhci_virt_device *virt_dev;
1905bc75fa38SAlex Chiang 	int ret = 0;
1906bc75fa38SAlex Chiang 
190764927730SAndiry Xu 	ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1908bc75fa38SAlex Chiang 	if (ret <= 0) {
1909bc75fa38SAlex Chiang 		/* So we won't queue a reset ep command for a root hub */
1910bc75fa38SAlex Chiang 		ep->hcpriv = NULL;
1911bc75fa38SAlex Chiang 		return ret;
1912bc75fa38SAlex Chiang 	}
1913bc75fa38SAlex Chiang 	xhci = hcd_to_xhci(hcd);
1914fe6c6c13SSarah Sharp 	if (xhci->xhc_state & XHCI_STATE_DYING)
1915fe6c6c13SSarah Sharp 		return -ENODEV;
1916bc75fa38SAlex Chiang 
1917bc75fa38SAlex Chiang 	added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1918bc75fa38SAlex Chiang 	if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1919bc75fa38SAlex Chiang 		/* FIXME when we have to issue an evaluate endpoint command to
1920bc75fa38SAlex Chiang 		 * deal with ep0 max packet size changing once we get the
1921bc75fa38SAlex Chiang 		 * descriptors
1922bc75fa38SAlex Chiang 		 */
1923bc75fa38SAlex Chiang 		xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1924bc75fa38SAlex Chiang 				__func__, added_ctxs);
1925bc75fa38SAlex Chiang 		return 0;
1926bc75fa38SAlex Chiang 	}
1927bc75fa38SAlex Chiang 
1928fa75ac37SSarah Sharp 	virt_dev = xhci->devs[udev->slot_id];
1929fa75ac37SSarah Sharp 	in_ctx = virt_dev->in_ctx;
19304daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
193192f8e767SSarah Sharp 	if (!ctrl_ctx) {
193292f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
193392f8e767SSarah Sharp 				__func__);
193492f8e767SSarah Sharp 		return 0;
193592f8e767SSarah Sharp 	}
1936fa75ac37SSarah Sharp 
193792f8e767SSarah Sharp 	ep_index = xhci_get_endpoint_index(&ep->desc);
1938fa75ac37SSarah Sharp 	/* If this endpoint is already in use, and the upper layers are trying
1939fa75ac37SSarah Sharp 	 * to add it again without dropping it, reject the addition.
1940fa75ac37SSarah Sharp 	 */
1941fa75ac37SSarah Sharp 	if (virt_dev->eps[ep_index].ring &&
194292c9691bSLin Wang 			!(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
1943fa75ac37SSarah Sharp 		xhci_warn(xhci, "Trying to add endpoint 0x%x "
1944fa75ac37SSarah Sharp 				"without dropping it.\n",
1945fa75ac37SSarah Sharp 				(unsigned int) ep->desc.bEndpointAddress);
1946fa75ac37SSarah Sharp 		return -EINVAL;
1947fa75ac37SSarah Sharp 	}
1948fa75ac37SSarah Sharp 
1949bc75fa38SAlex Chiang 	/* If the HCD has already noted the endpoint is enabled,
1950bc75fa38SAlex Chiang 	 * ignore this request.
1951bc75fa38SAlex Chiang 	 */
195292c9691bSLin Wang 	if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
1953bc75fa38SAlex Chiang 		xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1954bc75fa38SAlex Chiang 				__func__, ep);
1955bc75fa38SAlex Chiang 		return 0;
1956bc75fa38SAlex Chiang 	}
1957bc75fa38SAlex Chiang 
1958bc75fa38SAlex Chiang 	/*
1959bc75fa38SAlex Chiang 	 * Configuration and alternate setting changes must be done in
1960bc75fa38SAlex Chiang 	 * process context, not interrupt context (or so documenation
1961bc75fa38SAlex Chiang 	 * for usb_set_interface() and usb_set_configuration() claim).
1962bc75fa38SAlex Chiang 	 */
1963fa75ac37SSarah Sharp 	if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1964bc75fa38SAlex Chiang 		dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1965bc75fa38SAlex Chiang 				__func__, ep->desc.bEndpointAddress);
1966bc75fa38SAlex Chiang 		return -ENOMEM;
1967bc75fa38SAlex Chiang 	}
1968bc75fa38SAlex Chiang 
196928ccd296SMatt Evans 	ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
197028ccd296SMatt Evans 	new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1971bc75fa38SAlex Chiang 
1972bc75fa38SAlex Chiang 	/* If xhci_endpoint_disable() was called for this endpoint, but the
1973bc75fa38SAlex Chiang 	 * xHC hasn't been notified yet through the check_bandwidth() call,
1974bc75fa38SAlex Chiang 	 * this re-adds a new state for the endpoint from the new endpoint
1975bc75fa38SAlex Chiang 	 * descriptors.  We must drop and re-add this endpoint, so we leave the
1976bc75fa38SAlex Chiang 	 * drop flags alone.
1977bc75fa38SAlex Chiang 	 */
197828ccd296SMatt Evans 	new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1979bc75fa38SAlex Chiang 
1980bc75fa38SAlex Chiang 	/* Store the usb_device pointer for later use */
1981bc75fa38SAlex Chiang 	ep->hcpriv = udev;
1982bc75fa38SAlex Chiang 
19835afa0a5eSMathias Nyman 	ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, ep_index);
19845afa0a5eSMathias Nyman 	trace_xhci_add_endpoint(ep_ctx);
19855afa0a5eSMathias Nyman 
1986d6759133SJulius Werner 	xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1987bc75fa38SAlex Chiang 			(unsigned int) ep->desc.bEndpointAddress,
1988bc75fa38SAlex Chiang 			udev->slot_id,
1989bc75fa38SAlex Chiang 			(unsigned int) new_drop_flags,
1990d6759133SJulius Werner 			(unsigned int) new_add_flags);
1991bc75fa38SAlex Chiang 	return 0;
1992bc75fa38SAlex Chiang }
199314295a15SChunfeng Yun EXPORT_SYMBOL_GPL(xhci_add_endpoint);
1994bc75fa38SAlex Chiang 
xhci_zero_in_ctx(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev)1995bc75fa38SAlex Chiang static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1996bc75fa38SAlex Chiang {
1997bc75fa38SAlex Chiang 	struct xhci_input_control_ctx *ctrl_ctx;
1998bc75fa38SAlex Chiang 	struct xhci_ep_ctx *ep_ctx;
1999bc75fa38SAlex Chiang 	struct xhci_slot_ctx *slot_ctx;
2000bc75fa38SAlex Chiang 	int i;
2001bc75fa38SAlex Chiang 
20024daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
200392f8e767SSarah Sharp 	if (!ctrl_ctx) {
200492f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
200592f8e767SSarah Sharp 				__func__);
200692f8e767SSarah Sharp 		return;
200792f8e767SSarah Sharp 	}
200892f8e767SSarah Sharp 
2009bc75fa38SAlex Chiang 	/* When a device's add flag and drop flag are zero, any subsequent
2010bc75fa38SAlex Chiang 	 * configure endpoint command will leave that endpoint's state
2011bc75fa38SAlex Chiang 	 * untouched.  Make sure we don't leave any old state in the input
2012bc75fa38SAlex Chiang 	 * endpoint contexts.
2013bc75fa38SAlex Chiang 	 */
2014bc75fa38SAlex Chiang 	ctrl_ctx->drop_flags = 0;
2015bc75fa38SAlex Chiang 	ctrl_ctx->add_flags = 0;
2016bc75fa38SAlex Chiang 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
201728ccd296SMatt Evans 	slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2018bc75fa38SAlex Chiang 	/* Endpoint 0 is always valid */
201928ccd296SMatt Evans 	slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
202098871e94SFelipe Balbi 	for (i = 1; i < 31; i++) {
2021bc75fa38SAlex Chiang 		ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
2022bc75fa38SAlex Chiang 		ep_ctx->ep_info = 0;
2023bc75fa38SAlex Chiang 		ep_ctx->ep_info2 = 0;
2024bc75fa38SAlex Chiang 		ep_ctx->deq = 0;
2025bc75fa38SAlex Chiang 		ep_ctx->tx_info = 0;
2026bc75fa38SAlex Chiang 	}
2027bc75fa38SAlex Chiang }
2028bc75fa38SAlex Chiang 
xhci_configure_endpoint_result(struct xhci_hcd * xhci,struct usb_device * udev,u32 * cmd_status)2029bc75fa38SAlex Chiang static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
203000161f7dSSarah Sharp 		struct usb_device *udev, u32 *cmd_status)
2031bc75fa38SAlex Chiang {
2032bc75fa38SAlex Chiang 	int ret;
2033bc75fa38SAlex Chiang 
2034bc75fa38SAlex Chiang 	switch (*cmd_status) {
20350b7c105aSFelipe Balbi 	case COMP_COMMAND_ABORTED:
2036604d02a2SMathias Nyman 	case COMP_COMMAND_RING_STOPPED:
2037c311e391SMathias Nyman 		xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
2038c311e391SMathias Nyman 		ret = -ETIME;
2039c311e391SMathias Nyman 		break;
20400b7c105aSFelipe Balbi 	case COMP_RESOURCE_ERROR:
2041288c0f44SOliver Neukum 		dev_warn(&udev->dev,
2042288c0f44SOliver Neukum 			 "Not enough host controller resources for new device state.\n");
2043bc75fa38SAlex Chiang 		ret = -ENOMEM;
2044bc75fa38SAlex Chiang 		/* FIXME: can we allocate more resources for the HC? */
2045bc75fa38SAlex Chiang 		break;
20460b7c105aSFelipe Balbi 	case COMP_BANDWIDTH_ERROR:
20470b7c105aSFelipe Balbi 	case COMP_SECONDARY_BANDWIDTH_ERROR:
2048288c0f44SOliver Neukum 		dev_warn(&udev->dev,
2049288c0f44SOliver Neukum 			 "Not enough bandwidth for new device state.\n");
2050bc75fa38SAlex Chiang 		ret = -ENOSPC;
2051bc75fa38SAlex Chiang 		/* FIXME: can we go back to the old state? */
2052bc75fa38SAlex Chiang 		break;
20530b7c105aSFelipe Balbi 	case COMP_TRB_ERROR:
2054bc75fa38SAlex Chiang 		/* the HCD set up something wrong */
2055bc75fa38SAlex Chiang 		dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
2056bc75fa38SAlex Chiang 				"add flag = 1, "
2057bc75fa38SAlex Chiang 				"and endpoint is not disabled.\n");
2058bc75fa38SAlex Chiang 		ret = -EINVAL;
2059bc75fa38SAlex Chiang 		break;
20600b7c105aSFelipe Balbi 	case COMP_INCOMPATIBLE_DEVICE_ERROR:
2061288c0f44SOliver Neukum 		dev_warn(&udev->dev,
2062288c0f44SOliver Neukum 			 "ERROR: Incompatible device for endpoint configure command.\n");
2063f6ba6fe2SAlex He 		ret = -ENODEV;
2064f6ba6fe2SAlex He 		break;
2065bc75fa38SAlex Chiang 	case COMP_SUCCESS:
20663a7fa5beSXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
20673a7fa5beSXenia Ragiadakou 				"Successful Endpoint Configure command");
2068bc75fa38SAlex Chiang 		ret = 0;
2069bc75fa38SAlex Chiang 		break;
2070bc75fa38SAlex Chiang 	default:
2071288c0f44SOliver Neukum 		xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2072288c0f44SOliver Neukum 				*cmd_status);
2073bc75fa38SAlex Chiang 		ret = -EINVAL;
2074bc75fa38SAlex Chiang 		break;
2075bc75fa38SAlex Chiang 	}
2076bc75fa38SAlex Chiang 	return ret;
2077bc75fa38SAlex Chiang }
2078bc75fa38SAlex Chiang 
xhci_evaluate_context_result(struct xhci_hcd * xhci,struct usb_device * udev,u32 * cmd_status)2079bc75fa38SAlex Chiang static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
208000161f7dSSarah Sharp 		struct usb_device *udev, u32 *cmd_status)
2081bc75fa38SAlex Chiang {
2082bc75fa38SAlex Chiang 	int ret;
2083bc75fa38SAlex Chiang 
2084bc75fa38SAlex Chiang 	switch (*cmd_status) {
20850b7c105aSFelipe Balbi 	case COMP_COMMAND_ABORTED:
2086604d02a2SMathias Nyman 	case COMP_COMMAND_RING_STOPPED:
2087c311e391SMathias Nyman 		xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
2088c311e391SMathias Nyman 		ret = -ETIME;
2089c311e391SMathias Nyman 		break;
20900b7c105aSFelipe Balbi 	case COMP_PARAMETER_ERROR:
2091288c0f44SOliver Neukum 		dev_warn(&udev->dev,
2092288c0f44SOliver Neukum 			 "WARN: xHCI driver setup invalid evaluate context command.\n");
2093bc75fa38SAlex Chiang 		ret = -EINVAL;
2094bc75fa38SAlex Chiang 		break;
20950b7c105aSFelipe Balbi 	case COMP_SLOT_NOT_ENABLED_ERROR:
2096288c0f44SOliver Neukum 		dev_warn(&udev->dev,
2097288c0f44SOliver Neukum 			"WARN: slot not enabled for evaluate context command.\n");
2098b8031342SSarah Sharp 		ret = -EINVAL;
2099b8031342SSarah Sharp 		break;
21000b7c105aSFelipe Balbi 	case COMP_CONTEXT_STATE_ERROR:
2101288c0f44SOliver Neukum 		dev_warn(&udev->dev,
2102288c0f44SOliver Neukum 			"WARN: invalid context state for evaluate context command.\n");
2103bc75fa38SAlex Chiang 		ret = -EINVAL;
2104bc75fa38SAlex Chiang 		break;
21050b7c105aSFelipe Balbi 	case COMP_INCOMPATIBLE_DEVICE_ERROR:
2106288c0f44SOliver Neukum 		dev_warn(&udev->dev,
2107288c0f44SOliver Neukum 			"ERROR: Incompatible device for evaluate context command.\n");
2108f6ba6fe2SAlex He 		ret = -ENODEV;
2109f6ba6fe2SAlex He 		break;
21100b7c105aSFelipe Balbi 	case COMP_MAX_EXIT_LATENCY_TOO_LARGE_ERROR:
21111bb73a88SAlex He 		/* Max Exit Latency too large error */
21121bb73a88SAlex He 		dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
21131bb73a88SAlex He 		ret = -EINVAL;
21141bb73a88SAlex He 		break;
2115bc75fa38SAlex Chiang 	case COMP_SUCCESS:
21163a7fa5beSXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
21173a7fa5beSXenia Ragiadakou 				"Successful evaluate context command");
2118bc75fa38SAlex Chiang 		ret = 0;
2119bc75fa38SAlex Chiang 		break;
2120bc75fa38SAlex Chiang 	default:
2121288c0f44SOliver Neukum 		xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2122288c0f44SOliver Neukum 			*cmd_status);
2123bc75fa38SAlex Chiang 		ret = -EINVAL;
2124bc75fa38SAlex Chiang 		break;
2125bc75fa38SAlex Chiang 	}
2126bc75fa38SAlex Chiang 	return ret;
2127bc75fa38SAlex Chiang }
2128bc75fa38SAlex Chiang 
xhci_count_num_new_endpoints(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)21292cf95c18SSarah Sharp static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
213092f8e767SSarah Sharp 		struct xhci_input_control_ctx *ctrl_ctx)
21312cf95c18SSarah Sharp {
21322cf95c18SSarah Sharp 	u32 valid_add_flags;
21332cf95c18SSarah Sharp 	u32 valid_drop_flags;
21342cf95c18SSarah Sharp 
21352cf95c18SSarah Sharp 	/* Ignore the slot flag (bit 0), and the default control endpoint flag
21362cf95c18SSarah Sharp 	 * (bit 1).  The default control endpoint is added during the Address
21372cf95c18SSarah Sharp 	 * Device command and is never removed until the slot is disabled.
21382cf95c18SSarah Sharp 	 */
2139ef73400cSXenia Ragiadakou 	valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2140ef73400cSXenia Ragiadakou 	valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
21412cf95c18SSarah Sharp 
21422cf95c18SSarah Sharp 	/* Use hweight32 to count the number of ones in the add flags, or
21432cf95c18SSarah Sharp 	 * number of endpoints added.  Don't count endpoints that are changed
21442cf95c18SSarah Sharp 	 * (both added and dropped).
21452cf95c18SSarah Sharp 	 */
21462cf95c18SSarah Sharp 	return hweight32(valid_add_flags) -
21472cf95c18SSarah Sharp 		hweight32(valid_add_flags & valid_drop_flags);
21482cf95c18SSarah Sharp }
21492cf95c18SSarah Sharp 
xhci_count_num_dropped_endpoints(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)21502cf95c18SSarah Sharp static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
215192f8e767SSarah Sharp 		struct xhci_input_control_ctx *ctrl_ctx)
21522cf95c18SSarah Sharp {
21532cf95c18SSarah Sharp 	u32 valid_add_flags;
21542cf95c18SSarah Sharp 	u32 valid_drop_flags;
21552cf95c18SSarah Sharp 
215678d1ff02SXenia Ragiadakou 	valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
215778d1ff02SXenia Ragiadakou 	valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
21582cf95c18SSarah Sharp 
21592cf95c18SSarah Sharp 	return hweight32(valid_drop_flags) -
21602cf95c18SSarah Sharp 		hweight32(valid_add_flags & valid_drop_flags);
21612cf95c18SSarah Sharp }
21622cf95c18SSarah Sharp 
21632cf95c18SSarah Sharp /*
21642cf95c18SSarah Sharp  * We need to reserve the new number of endpoints before the configure endpoint
21652cf95c18SSarah Sharp  * command completes.  We can't subtract the dropped endpoints from the number
21662cf95c18SSarah Sharp  * of active endpoints until the command completes because we can oversubscribe
21672cf95c18SSarah Sharp  * the host in this case:
21682cf95c18SSarah Sharp  *
21692cf95c18SSarah Sharp  *  - the first configure endpoint command drops more endpoints than it adds
21702cf95c18SSarah Sharp  *  - a second configure endpoint command that adds more endpoints is queued
21712cf95c18SSarah Sharp  *  - the first configure endpoint command fails, so the config is unchanged
21722cf95c18SSarah Sharp  *  - the second command may succeed, even though there isn't enough resources
21732cf95c18SSarah Sharp  *
21742cf95c18SSarah Sharp  * Must be called with xhci->lock held.
21752cf95c18SSarah Sharp  */
xhci_reserve_host_resources(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)21762cf95c18SSarah Sharp static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
217792f8e767SSarah Sharp 		struct xhci_input_control_ctx *ctrl_ctx)
21782cf95c18SSarah Sharp {
21792cf95c18SSarah Sharp 	u32 added_eps;
21802cf95c18SSarah Sharp 
218192f8e767SSarah Sharp 	added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
21822cf95c18SSarah Sharp 	if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
21834bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
21844bdfe4c3SXenia Ragiadakou 				"Not enough ep ctxs: "
21854bdfe4c3SXenia Ragiadakou 				"%u active, need to add %u, limit is %u.",
21862cf95c18SSarah Sharp 				xhci->num_active_eps, added_eps,
21872cf95c18SSarah Sharp 				xhci->limit_active_eps);
21882cf95c18SSarah Sharp 		return -ENOMEM;
21892cf95c18SSarah Sharp 	}
21902cf95c18SSarah Sharp 	xhci->num_active_eps += added_eps;
21914bdfe4c3SXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
21924bdfe4c3SXenia Ragiadakou 			"Adding %u ep ctxs, %u now active.", added_eps,
21932cf95c18SSarah Sharp 			xhci->num_active_eps);
21942cf95c18SSarah Sharp 	return 0;
21952cf95c18SSarah Sharp }
21962cf95c18SSarah Sharp 
21972cf95c18SSarah Sharp /*
21982cf95c18SSarah Sharp  * The configure endpoint was failed by the xHC for some other reason, so we
21992cf95c18SSarah Sharp  * need to revert the resources that failed configuration would have used.
22002cf95c18SSarah Sharp  *
22012cf95c18SSarah Sharp  * Must be called with xhci->lock held.
22022cf95c18SSarah Sharp  */
xhci_free_host_resources(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)22032cf95c18SSarah Sharp static void xhci_free_host_resources(struct xhci_hcd *xhci,
220492f8e767SSarah Sharp 		struct xhci_input_control_ctx *ctrl_ctx)
22052cf95c18SSarah Sharp {
22062cf95c18SSarah Sharp 	u32 num_failed_eps;
22072cf95c18SSarah Sharp 
220892f8e767SSarah Sharp 	num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
22092cf95c18SSarah Sharp 	xhci->num_active_eps -= num_failed_eps;
22104bdfe4c3SXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
22114bdfe4c3SXenia Ragiadakou 			"Removing %u failed ep ctxs, %u now active.",
22122cf95c18SSarah Sharp 			num_failed_eps,
22132cf95c18SSarah Sharp 			xhci->num_active_eps);
22142cf95c18SSarah Sharp }
22152cf95c18SSarah Sharp 
22162cf95c18SSarah Sharp /*
22172cf95c18SSarah Sharp  * Now that the command has completed, clean up the active endpoint count by
22182cf95c18SSarah Sharp  * subtracting out the endpoints that were dropped (but not changed).
22192cf95c18SSarah Sharp  *
22202cf95c18SSarah Sharp  * Must be called with xhci->lock held.
22212cf95c18SSarah Sharp  */
xhci_finish_resource_reservation(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)22222cf95c18SSarah Sharp static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
222392f8e767SSarah Sharp 		struct xhci_input_control_ctx *ctrl_ctx)
22242cf95c18SSarah Sharp {
22252cf95c18SSarah Sharp 	u32 num_dropped_eps;
22262cf95c18SSarah Sharp 
222792f8e767SSarah Sharp 	num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
22282cf95c18SSarah Sharp 	xhci->num_active_eps -= num_dropped_eps;
22292cf95c18SSarah Sharp 	if (num_dropped_eps)
22304bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
22314bdfe4c3SXenia Ragiadakou 				"Removing %u dropped ep ctxs, %u now active.",
22322cf95c18SSarah Sharp 				num_dropped_eps,
22332cf95c18SSarah Sharp 				xhci->num_active_eps);
22342cf95c18SSarah Sharp }
22352cf95c18SSarah Sharp 
xhci_get_block_size(struct usb_device * udev)2236ed384bd3SFelipe Balbi static unsigned int xhci_get_block_size(struct usb_device *udev)
2237c29eea62SSarah Sharp {
2238c29eea62SSarah Sharp 	switch (udev->speed) {
2239c29eea62SSarah Sharp 	case USB_SPEED_LOW:
2240c29eea62SSarah Sharp 	case USB_SPEED_FULL:
2241c29eea62SSarah Sharp 		return FS_BLOCK;
2242c29eea62SSarah Sharp 	case USB_SPEED_HIGH:
2243c29eea62SSarah Sharp 		return HS_BLOCK;
2244c29eea62SSarah Sharp 	case USB_SPEED_SUPER:
22450caf6b33SMathias Nyman 	case USB_SPEED_SUPER_PLUS:
2246c29eea62SSarah Sharp 		return SS_BLOCK;
2247c29eea62SSarah Sharp 	case USB_SPEED_UNKNOWN:
2248c29eea62SSarah Sharp 	default:
2249c29eea62SSarah Sharp 		/* Should never happen */
2250c29eea62SSarah Sharp 		return 1;
2251c29eea62SSarah Sharp 	}
2252c29eea62SSarah Sharp }
2253c29eea62SSarah Sharp 
2254ed384bd3SFelipe Balbi static unsigned int
xhci_get_largest_overhead(struct xhci_interval_bw * interval_bw)2255ed384bd3SFelipe Balbi xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
2256c29eea62SSarah Sharp {
2257c29eea62SSarah Sharp 	if (interval_bw->overhead[LS_OVERHEAD_TYPE])
2258c29eea62SSarah Sharp 		return LS_OVERHEAD;
2259c29eea62SSarah Sharp 	if (interval_bw->overhead[FS_OVERHEAD_TYPE])
2260c29eea62SSarah Sharp 		return FS_OVERHEAD;
2261c29eea62SSarah Sharp 	return HS_OVERHEAD;
2262c29eea62SSarah Sharp }
2263c29eea62SSarah Sharp 
2264c29eea62SSarah Sharp /* If we are changing a LS/FS device under a HS hub,
2265c29eea62SSarah Sharp  * make sure (if we are activating a new TT) that the HS bus has enough
2266c29eea62SSarah Sharp  * bandwidth for this new TT.
2267c29eea62SSarah Sharp  */
xhci_check_tt_bw_table(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,int old_active_eps)2268c29eea62SSarah Sharp static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2269c29eea62SSarah Sharp 		struct xhci_virt_device *virt_dev,
2270c29eea62SSarah Sharp 		int old_active_eps)
2271c29eea62SSarah Sharp {
2272c29eea62SSarah Sharp 	struct xhci_interval_bw_table *bw_table;
2273c29eea62SSarah Sharp 	struct xhci_tt_bw_info *tt_info;
2274c29eea62SSarah Sharp 
2275c29eea62SSarah Sharp 	/* Find the bandwidth table for the root port this TT is attached to. */
227606790c19SNiklas Neronin 	bw_table = &xhci->rh_bw[virt_dev->rhub_port->hw_portnum].bw_table;
2277c29eea62SSarah Sharp 	tt_info = virt_dev->tt_info;
2278c29eea62SSarah Sharp 	/* If this TT already had active endpoints, the bandwidth for this TT
2279c29eea62SSarah Sharp 	 * has already been added.  Removing all periodic endpoints (and thus
2280c29eea62SSarah Sharp 	 * making the TT enactive) will only decrease the bandwidth used.
2281c29eea62SSarah Sharp 	 */
2282c29eea62SSarah Sharp 	if (old_active_eps)
2283c29eea62SSarah Sharp 		return 0;
2284c29eea62SSarah Sharp 	if (old_active_eps == 0 && tt_info->active_eps != 0) {
2285c29eea62SSarah Sharp 		if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2286c29eea62SSarah Sharp 			return -ENOMEM;
2287c29eea62SSarah Sharp 		return 0;
2288c29eea62SSarah Sharp 	}
2289c29eea62SSarah Sharp 	/* Not sure why we would have no new active endpoints...
2290c29eea62SSarah Sharp 	 *
2291c29eea62SSarah Sharp 	 * Maybe because of an Evaluate Context change for a hub update or a
2292c29eea62SSarah Sharp 	 * control endpoint 0 max packet size change?
2293c29eea62SSarah Sharp 	 * FIXME: skip the bandwidth calculation in that case.
2294c29eea62SSarah Sharp 	 */
2295c29eea62SSarah Sharp 	return 0;
2296c29eea62SSarah Sharp }
2297c29eea62SSarah Sharp 
xhci_check_ss_bw(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev)22982b698999SSarah Sharp static int xhci_check_ss_bw(struct xhci_hcd *xhci,
22992b698999SSarah Sharp 		struct xhci_virt_device *virt_dev)
23002b698999SSarah Sharp {
23012b698999SSarah Sharp 	unsigned int bw_reserved;
23022b698999SSarah Sharp 
23032b698999SSarah Sharp 	bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
23042b698999SSarah Sharp 	if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
23052b698999SSarah Sharp 		return -ENOMEM;
23062b698999SSarah Sharp 
23072b698999SSarah Sharp 	bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
23082b698999SSarah Sharp 	if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
23092b698999SSarah Sharp 		return -ENOMEM;
23102b698999SSarah Sharp 
23112b698999SSarah Sharp 	return 0;
23122b698999SSarah Sharp }
23132b698999SSarah Sharp 
2314c29eea62SSarah Sharp /*
2315c29eea62SSarah Sharp  * This algorithm is a very conservative estimate of the worst-case scheduling
2316c29eea62SSarah Sharp  * scenario for any one interval.  The hardware dynamically schedules the
2317c29eea62SSarah Sharp  * packets, so we can't tell which microframe could be the limiting factor in
2318c29eea62SSarah Sharp  * the bandwidth scheduling.  This only takes into account periodic endpoints.
2319c29eea62SSarah Sharp  *
2320c29eea62SSarah Sharp  * Obviously, we can't solve an NP complete problem to find the minimum worst
2321c29eea62SSarah Sharp  * case scenario.  Instead, we come up with an estimate that is no less than
2322c29eea62SSarah Sharp  * the worst case bandwidth used for any one microframe, but may be an
2323c29eea62SSarah Sharp  * over-estimate.
2324c29eea62SSarah Sharp  *
2325c29eea62SSarah Sharp  * We walk the requirements for each endpoint by interval, starting with the
2326c29eea62SSarah Sharp  * smallest interval, and place packets in the schedule where there is only one
2327c29eea62SSarah Sharp  * possible way to schedule packets for that interval.  In order to simplify
2328c29eea62SSarah Sharp  * this algorithm, we record the largest max packet size for each interval, and
2329c29eea62SSarah Sharp  * assume all packets will be that size.
2330c29eea62SSarah Sharp  *
2331c29eea62SSarah Sharp  * For interval 0, we obviously must schedule all packets for each interval.
2332c29eea62SSarah Sharp  * The bandwidth for interval 0 is just the amount of data to be transmitted
2333c29eea62SSarah Sharp  * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2334c29eea62SSarah Sharp  * the number of packets).
2335c29eea62SSarah Sharp  *
2336c29eea62SSarah Sharp  * For interval 1, we have two possible microframes to schedule those packets
2337c29eea62SSarah Sharp  * in.  For this algorithm, if we can schedule the same number of packets for
2338c29eea62SSarah Sharp  * each possible scheduling opportunity (each microframe), we will do so.  The
2339c29eea62SSarah Sharp  * remaining number of packets will be saved to be transmitted in the gaps in
2340c29eea62SSarah Sharp  * the next interval's scheduling sequence.
2341c29eea62SSarah Sharp  *
2342c29eea62SSarah Sharp  * As we move those remaining packets to be scheduled with interval 2 packets,
2343c29eea62SSarah Sharp  * we have to double the number of remaining packets to transmit.  This is
2344c29eea62SSarah Sharp  * because the intervals are actually powers of 2, and we would be transmitting
2345c29eea62SSarah Sharp  * the previous interval's packets twice in this interval.  We also have to be
2346c29eea62SSarah Sharp  * sure that when we look at the largest max packet size for this interval, we
2347c29eea62SSarah Sharp  * also look at the largest max packet size for the remaining packets and take
2348c29eea62SSarah Sharp  * the greater of the two.
2349c29eea62SSarah Sharp  *
2350c29eea62SSarah Sharp  * The algorithm continues to evenly distribute packets in each scheduling
2351c29eea62SSarah Sharp  * opportunity, and push the remaining packets out, until we get to the last
2352c29eea62SSarah Sharp  * interval.  Then those packets and their associated overhead are just added
2353c29eea62SSarah Sharp  * to the bandwidth used.
23542e27980eSSarah Sharp  */
xhci_check_bw_table(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,int old_active_eps)23552e27980eSSarah Sharp static int xhci_check_bw_table(struct xhci_hcd *xhci,
23562e27980eSSarah Sharp 		struct xhci_virt_device *virt_dev,
23572e27980eSSarah Sharp 		int old_active_eps)
23582e27980eSSarah Sharp {
2359c29eea62SSarah Sharp 	unsigned int bw_reserved;
2360c29eea62SSarah Sharp 	unsigned int max_bandwidth;
2361c29eea62SSarah Sharp 	unsigned int bw_used;
2362c29eea62SSarah Sharp 	unsigned int block_size;
2363c29eea62SSarah Sharp 	struct xhci_interval_bw_table *bw_table;
2364c29eea62SSarah Sharp 	unsigned int packet_size = 0;
2365c29eea62SSarah Sharp 	unsigned int overhead = 0;
2366c29eea62SSarah Sharp 	unsigned int packets_transmitted = 0;
2367c29eea62SSarah Sharp 	unsigned int packets_remaining = 0;
2368c29eea62SSarah Sharp 	unsigned int i;
2369c29eea62SSarah Sharp 
23700caf6b33SMathias Nyman 	if (virt_dev->udev->speed >= USB_SPEED_SUPER)
23712b698999SSarah Sharp 		return xhci_check_ss_bw(xhci, virt_dev);
23722b698999SSarah Sharp 
2373c29eea62SSarah Sharp 	if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2374c29eea62SSarah Sharp 		max_bandwidth = HS_BW_LIMIT;
2375c29eea62SSarah Sharp 		/* Convert percent of bus BW reserved to blocks reserved */
2376c29eea62SSarah Sharp 		bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2377c29eea62SSarah Sharp 	} else {
2378c29eea62SSarah Sharp 		max_bandwidth = FS_BW_LIMIT;
2379c29eea62SSarah Sharp 		bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2380c29eea62SSarah Sharp 	}
2381c29eea62SSarah Sharp 
2382c29eea62SSarah Sharp 	bw_table = virt_dev->bw_table;
2383c29eea62SSarah Sharp 	/* We need to translate the max packet size and max ESIT payloads into
2384c29eea62SSarah Sharp 	 * the units the hardware uses.
2385c29eea62SSarah Sharp 	 */
2386c29eea62SSarah Sharp 	block_size = xhci_get_block_size(virt_dev->udev);
2387c29eea62SSarah Sharp 
2388c29eea62SSarah Sharp 	/* If we are manipulating a LS/FS device under a HS hub, double check
2389c29eea62SSarah Sharp 	 * that the HS bus has enough bandwidth if we are activing a new TT.
2390c29eea62SSarah Sharp 	 */
2391c29eea62SSarah Sharp 	if (virt_dev->tt_info) {
23924bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
23934bdfe4c3SXenia Ragiadakou 				"Recalculating BW for rootport %u",
239406790c19SNiklas Neronin 				virt_dev->rhub_port->hw_portnum + 1);
2395c29eea62SSarah Sharp 		if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2396c29eea62SSarah Sharp 			xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2397c29eea62SSarah Sharp 					"newly activated TT.\n");
2398c29eea62SSarah Sharp 			return -ENOMEM;
2399c29eea62SSarah Sharp 		}
24004bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
24014bdfe4c3SXenia Ragiadakou 				"Recalculating BW for TT slot %u port %u",
2402c29eea62SSarah Sharp 				virt_dev->tt_info->slot_id,
2403c29eea62SSarah Sharp 				virt_dev->tt_info->ttport);
2404c29eea62SSarah Sharp 	} else {
24054bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
24064bdfe4c3SXenia Ragiadakou 				"Recalculating BW for rootport %u",
240706790c19SNiklas Neronin 				virt_dev->rhub_port->hw_portnum + 1);
2408c29eea62SSarah Sharp 	}
2409c29eea62SSarah Sharp 
2410c29eea62SSarah Sharp 	/* Add in how much bandwidth will be used for interval zero, or the
2411c29eea62SSarah Sharp 	 * rounded max ESIT payload + number of packets * largest overhead.
2412c29eea62SSarah Sharp 	 */
2413c29eea62SSarah Sharp 	bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2414c29eea62SSarah Sharp 		bw_table->interval_bw[0].num_packets *
2415c29eea62SSarah Sharp 		xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2416c29eea62SSarah Sharp 
2417c29eea62SSarah Sharp 	for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2418c29eea62SSarah Sharp 		unsigned int bw_added;
2419c29eea62SSarah Sharp 		unsigned int largest_mps;
2420c29eea62SSarah Sharp 		unsigned int interval_overhead;
2421c29eea62SSarah Sharp 
2422c29eea62SSarah Sharp 		/*
2423c29eea62SSarah Sharp 		 * How many packets could we transmit in this interval?
2424c29eea62SSarah Sharp 		 * If packets didn't fit in the previous interval, we will need
2425c29eea62SSarah Sharp 		 * to transmit that many packets twice within this interval.
2426c29eea62SSarah Sharp 		 */
2427c29eea62SSarah Sharp 		packets_remaining = 2 * packets_remaining +
2428c29eea62SSarah Sharp 			bw_table->interval_bw[i].num_packets;
2429c29eea62SSarah Sharp 
2430c29eea62SSarah Sharp 		/* Find the largest max packet size of this or the previous
2431c29eea62SSarah Sharp 		 * interval.
2432c29eea62SSarah Sharp 		 */
2433c29eea62SSarah Sharp 		if (list_empty(&bw_table->interval_bw[i].endpoints))
2434c29eea62SSarah Sharp 			largest_mps = 0;
2435c29eea62SSarah Sharp 		else {
2436c29eea62SSarah Sharp 			struct xhci_virt_ep *virt_ep;
2437c29eea62SSarah Sharp 			struct list_head *ep_entry;
2438c29eea62SSarah Sharp 
2439c29eea62SSarah Sharp 			ep_entry = bw_table->interval_bw[i].endpoints.next;
2440c29eea62SSarah Sharp 			virt_ep = list_entry(ep_entry,
2441c29eea62SSarah Sharp 					struct xhci_virt_ep, bw_endpoint_list);
2442c29eea62SSarah Sharp 			/* Convert to blocks, rounding up */
2443c29eea62SSarah Sharp 			largest_mps = DIV_ROUND_UP(
2444c29eea62SSarah Sharp 					virt_ep->bw_info.max_packet_size,
2445c29eea62SSarah Sharp 					block_size);
2446c29eea62SSarah Sharp 		}
2447c29eea62SSarah Sharp 		if (largest_mps > packet_size)
2448c29eea62SSarah Sharp 			packet_size = largest_mps;
2449c29eea62SSarah Sharp 
2450c29eea62SSarah Sharp 		/* Use the larger overhead of this or the previous interval. */
2451c29eea62SSarah Sharp 		interval_overhead = xhci_get_largest_overhead(
2452c29eea62SSarah Sharp 				&bw_table->interval_bw[i]);
2453c29eea62SSarah Sharp 		if (interval_overhead > overhead)
2454c29eea62SSarah Sharp 			overhead = interval_overhead;
2455c29eea62SSarah Sharp 
2456c29eea62SSarah Sharp 		/* How many packets can we evenly distribute across
2457c29eea62SSarah Sharp 		 * (1 << (i + 1)) possible scheduling opportunities?
2458c29eea62SSarah Sharp 		 */
2459c29eea62SSarah Sharp 		packets_transmitted = packets_remaining >> (i + 1);
2460c29eea62SSarah Sharp 
2461c29eea62SSarah Sharp 		/* Add in the bandwidth used for those scheduled packets */
2462c29eea62SSarah Sharp 		bw_added = packets_transmitted * (overhead + packet_size);
2463c29eea62SSarah Sharp 
2464c29eea62SSarah Sharp 		/* How many packets do we have remaining to transmit? */
2465c29eea62SSarah Sharp 		packets_remaining = packets_remaining % (1 << (i + 1));
2466c29eea62SSarah Sharp 
2467c29eea62SSarah Sharp 		/* What largest max packet size should those packets have? */
2468c29eea62SSarah Sharp 		/* If we've transmitted all packets, don't carry over the
2469c29eea62SSarah Sharp 		 * largest packet size.
2470c29eea62SSarah Sharp 		 */
2471c29eea62SSarah Sharp 		if (packets_remaining == 0) {
2472c29eea62SSarah Sharp 			packet_size = 0;
2473c29eea62SSarah Sharp 			overhead = 0;
2474c29eea62SSarah Sharp 		} else if (packets_transmitted > 0) {
2475c29eea62SSarah Sharp 			/* Otherwise if we do have remaining packets, and we've
2476c29eea62SSarah Sharp 			 * scheduled some packets in this interval, take the
2477c29eea62SSarah Sharp 			 * largest max packet size from endpoints with this
2478c29eea62SSarah Sharp 			 * interval.
2479c29eea62SSarah Sharp 			 */
2480c29eea62SSarah Sharp 			packet_size = largest_mps;
2481c29eea62SSarah Sharp 			overhead = interval_overhead;
2482c29eea62SSarah Sharp 		}
2483c29eea62SSarah Sharp 		/* Otherwise carry over packet_size and overhead from the last
2484c29eea62SSarah Sharp 		 * time we had a remainder.
2485c29eea62SSarah Sharp 		 */
2486c29eea62SSarah Sharp 		bw_used += bw_added;
2487c29eea62SSarah Sharp 		if (bw_used > max_bandwidth) {
2488c29eea62SSarah Sharp 			xhci_warn(xhci, "Not enough bandwidth. "
2489c29eea62SSarah Sharp 					"Proposed: %u, Max: %u\n",
2490c29eea62SSarah Sharp 				bw_used, max_bandwidth);
2491c29eea62SSarah Sharp 			return -ENOMEM;
2492c29eea62SSarah Sharp 		}
2493c29eea62SSarah Sharp 	}
2494c29eea62SSarah Sharp 	/*
2495c29eea62SSarah Sharp 	 * Ok, we know we have some packets left over after even-handedly
2496c29eea62SSarah Sharp 	 * scheduling interval 15.  We don't know which microframes they will
2497c29eea62SSarah Sharp 	 * fit into, so we over-schedule and say they will be scheduled every
2498c29eea62SSarah Sharp 	 * microframe.
2499c29eea62SSarah Sharp 	 */
2500c29eea62SSarah Sharp 	if (packets_remaining > 0)
2501c29eea62SSarah Sharp 		bw_used += overhead + packet_size;
2502c29eea62SSarah Sharp 
2503c29eea62SSarah Sharp 	if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2504c29eea62SSarah Sharp 		/* OK, we're manipulating a HS device attached to a
2505c29eea62SSarah Sharp 		 * root port bandwidth domain.  Include the number of active TTs
2506c29eea62SSarah Sharp 		 * in the bandwidth used.
2507c29eea62SSarah Sharp 		 */
2508c29eea62SSarah Sharp 		bw_used += TT_HS_OVERHEAD *
250906790c19SNiklas Neronin 			xhci->rh_bw[virt_dev->rhub_port->hw_portnum].num_active_tts;
2510c29eea62SSarah Sharp 	}
2511c29eea62SSarah Sharp 
25124bdfe4c3SXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
25134bdfe4c3SXenia Ragiadakou 		"Final bandwidth: %u, Limit: %u, Reserved: %u, "
25144bdfe4c3SXenia Ragiadakou 		"Available: %u " "percent",
2515c29eea62SSarah Sharp 		bw_used, max_bandwidth, bw_reserved,
2516c29eea62SSarah Sharp 		(max_bandwidth - bw_used - bw_reserved) * 100 /
2517c29eea62SSarah Sharp 		max_bandwidth);
2518c29eea62SSarah Sharp 
2519c29eea62SSarah Sharp 	bw_used += bw_reserved;
2520c29eea62SSarah Sharp 	if (bw_used > max_bandwidth) {
2521c29eea62SSarah Sharp 		xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2522c29eea62SSarah Sharp 				bw_used, max_bandwidth);
2523c29eea62SSarah Sharp 		return -ENOMEM;
2524c29eea62SSarah Sharp 	}
2525c29eea62SSarah Sharp 
2526c29eea62SSarah Sharp 	bw_table->bw_used = bw_used;
25272e27980eSSarah Sharp 	return 0;
25282e27980eSSarah Sharp }
25292e27980eSSarah Sharp 
xhci_is_async_ep(unsigned int ep_type)25302e27980eSSarah Sharp static bool xhci_is_async_ep(unsigned int ep_type)
25312e27980eSSarah Sharp {
25322e27980eSSarah Sharp 	return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
25332e27980eSSarah Sharp 					ep_type != ISOC_IN_EP &&
25342e27980eSSarah Sharp 					ep_type != INT_IN_EP);
25352e27980eSSarah Sharp }
25362e27980eSSarah Sharp 
xhci_is_sync_in_ep(unsigned int ep_type)25372b698999SSarah Sharp static bool xhci_is_sync_in_ep(unsigned int ep_type)
25382b698999SSarah Sharp {
2539392a07aeSSarah Sharp 	return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
25402b698999SSarah Sharp }
25412b698999SSarah Sharp 
xhci_get_ss_bw_consumed(struct xhci_bw_info * ep_bw)25422b698999SSarah Sharp static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
25432b698999SSarah Sharp {
25442b698999SSarah Sharp 	unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
25452b698999SSarah Sharp 
25462b698999SSarah Sharp 	if (ep_bw->ep_interval == 0)
25472b698999SSarah Sharp 		return SS_OVERHEAD_BURST +
25482b698999SSarah Sharp 			(ep_bw->mult * ep_bw->num_packets *
25492b698999SSarah Sharp 					(SS_OVERHEAD + mps));
25502b698999SSarah Sharp 	return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
25512b698999SSarah Sharp 				(SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
25522b698999SSarah Sharp 				1 << ep_bw->ep_interval);
25532b698999SSarah Sharp 
25542b698999SSarah Sharp }
25552b698999SSarah Sharp 
xhci_drop_ep_from_interval_table(struct xhci_hcd * xhci,struct xhci_bw_info * ep_bw,struct xhci_interval_bw_table * bw_table,struct usb_device * udev,struct xhci_virt_ep * virt_ep,struct xhci_tt_bw_info * tt_info)25563969384cSLu Baolu static void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
25572e27980eSSarah Sharp 		struct xhci_bw_info *ep_bw,
25582e27980eSSarah Sharp 		struct xhci_interval_bw_table *bw_table,
25592e27980eSSarah Sharp 		struct usb_device *udev,
25602e27980eSSarah Sharp 		struct xhci_virt_ep *virt_ep,
25612e27980eSSarah Sharp 		struct xhci_tt_bw_info *tt_info)
25622e27980eSSarah Sharp {
25632e27980eSSarah Sharp 	struct xhci_interval_bw	*interval_bw;
25642e27980eSSarah Sharp 	int normalized_interval;
25652e27980eSSarah Sharp 
25662b698999SSarah Sharp 	if (xhci_is_async_ep(ep_bw->type))
25672e27980eSSarah Sharp 		return;
25682e27980eSSarah Sharp 
25690caf6b33SMathias Nyman 	if (udev->speed >= USB_SPEED_SUPER) {
25702b698999SSarah Sharp 		if (xhci_is_sync_in_ep(ep_bw->type))
25712b698999SSarah Sharp 			xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
25722b698999SSarah Sharp 				xhci_get_ss_bw_consumed(ep_bw);
25732b698999SSarah Sharp 		else
25742b698999SSarah Sharp 			xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
25752b698999SSarah Sharp 				xhci_get_ss_bw_consumed(ep_bw);
25762b698999SSarah Sharp 		return;
25772b698999SSarah Sharp 	}
25782b698999SSarah Sharp 
25792b698999SSarah Sharp 	/* SuperSpeed endpoints never get added to intervals in the table, so
25802b698999SSarah Sharp 	 * this check is only valid for HS/FS/LS devices.
25812b698999SSarah Sharp 	 */
25822b698999SSarah Sharp 	if (list_empty(&virt_ep->bw_endpoint_list))
25832b698999SSarah Sharp 		return;
25842e27980eSSarah Sharp 	/* For LS/FS devices, we need to translate the interval expressed in
25852e27980eSSarah Sharp 	 * microframes to frames.
25862e27980eSSarah Sharp 	 */
25872e27980eSSarah Sharp 	if (udev->speed == USB_SPEED_HIGH)
25882e27980eSSarah Sharp 		normalized_interval = ep_bw->ep_interval;
25892e27980eSSarah Sharp 	else
25902e27980eSSarah Sharp 		normalized_interval = ep_bw->ep_interval - 3;
25912e27980eSSarah Sharp 
25922e27980eSSarah Sharp 	if (normalized_interval == 0)
25932e27980eSSarah Sharp 		bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
25942e27980eSSarah Sharp 	interval_bw = &bw_table->interval_bw[normalized_interval];
25952e27980eSSarah Sharp 	interval_bw->num_packets -= ep_bw->num_packets;
25962e27980eSSarah Sharp 	switch (udev->speed) {
25972e27980eSSarah Sharp 	case USB_SPEED_LOW:
25982e27980eSSarah Sharp 		interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
25992e27980eSSarah Sharp 		break;
26002e27980eSSarah Sharp 	case USB_SPEED_FULL:
26012e27980eSSarah Sharp 		interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
26022e27980eSSarah Sharp 		break;
26032e27980eSSarah Sharp 	case USB_SPEED_HIGH:
26042e27980eSSarah Sharp 		interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
26052e27980eSSarah Sharp 		break;
26061e4c5742SAlan Stern 	default:
26072e27980eSSarah Sharp 		/* Should never happen because only LS/FS/HS endpoints will get
26082e27980eSSarah Sharp 		 * added to the endpoint list.
26092e27980eSSarah Sharp 		 */
26102e27980eSSarah Sharp 		return;
26112e27980eSSarah Sharp 	}
26122e27980eSSarah Sharp 	if (tt_info)
26132e27980eSSarah Sharp 		tt_info->active_eps -= 1;
26142e27980eSSarah Sharp 	list_del_init(&virt_ep->bw_endpoint_list);
26152e27980eSSarah Sharp }
26162e27980eSSarah Sharp 
xhci_add_ep_to_interval_table(struct xhci_hcd * xhci,struct xhci_bw_info * ep_bw,struct xhci_interval_bw_table * bw_table,struct usb_device * udev,struct xhci_virt_ep * virt_ep,struct xhci_tt_bw_info * tt_info)26172e27980eSSarah Sharp static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
26182e27980eSSarah Sharp 		struct xhci_bw_info *ep_bw,
26192e27980eSSarah Sharp 		struct xhci_interval_bw_table *bw_table,
26202e27980eSSarah Sharp 		struct usb_device *udev,
26212e27980eSSarah Sharp 		struct xhci_virt_ep *virt_ep,
26222e27980eSSarah Sharp 		struct xhci_tt_bw_info *tt_info)
26232e27980eSSarah Sharp {
26242e27980eSSarah Sharp 	struct xhci_interval_bw	*interval_bw;
26252e27980eSSarah Sharp 	struct xhci_virt_ep *smaller_ep;
26262e27980eSSarah Sharp 	int normalized_interval;
26272e27980eSSarah Sharp 
26282e27980eSSarah Sharp 	if (xhci_is_async_ep(ep_bw->type))
26292e27980eSSarah Sharp 		return;
26302e27980eSSarah Sharp 
26312b698999SSarah Sharp 	if (udev->speed == USB_SPEED_SUPER) {
26322b698999SSarah Sharp 		if (xhci_is_sync_in_ep(ep_bw->type))
26332b698999SSarah Sharp 			xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
26342b698999SSarah Sharp 				xhci_get_ss_bw_consumed(ep_bw);
26352b698999SSarah Sharp 		else
26362b698999SSarah Sharp 			xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
26372b698999SSarah Sharp 				xhci_get_ss_bw_consumed(ep_bw);
26382b698999SSarah Sharp 		return;
26392b698999SSarah Sharp 	}
26402b698999SSarah Sharp 
26412e27980eSSarah Sharp 	/* For LS/FS devices, we need to translate the interval expressed in
26422e27980eSSarah Sharp 	 * microframes to frames.
26432e27980eSSarah Sharp 	 */
26442e27980eSSarah Sharp 	if (udev->speed == USB_SPEED_HIGH)
26452e27980eSSarah Sharp 		normalized_interval = ep_bw->ep_interval;
26462e27980eSSarah Sharp 	else
26472e27980eSSarah Sharp 		normalized_interval = ep_bw->ep_interval - 3;
26482e27980eSSarah Sharp 
26492e27980eSSarah Sharp 	if (normalized_interval == 0)
26502e27980eSSarah Sharp 		bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
26512e27980eSSarah Sharp 	interval_bw = &bw_table->interval_bw[normalized_interval];
26522e27980eSSarah Sharp 	interval_bw->num_packets += ep_bw->num_packets;
26532e27980eSSarah Sharp 	switch (udev->speed) {
26542e27980eSSarah Sharp 	case USB_SPEED_LOW:
26552e27980eSSarah Sharp 		interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
26562e27980eSSarah Sharp 		break;
26572e27980eSSarah Sharp 	case USB_SPEED_FULL:
26582e27980eSSarah Sharp 		interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
26592e27980eSSarah Sharp 		break;
26602e27980eSSarah Sharp 	case USB_SPEED_HIGH:
26612e27980eSSarah Sharp 		interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
26622e27980eSSarah Sharp 		break;
26631e4c5742SAlan Stern 	default:
26642e27980eSSarah Sharp 		/* Should never happen because only LS/FS/HS endpoints will get
26652e27980eSSarah Sharp 		 * added to the endpoint list.
26662e27980eSSarah Sharp 		 */
26672e27980eSSarah Sharp 		return;
26682e27980eSSarah Sharp 	}
26692e27980eSSarah Sharp 
26702e27980eSSarah Sharp 	if (tt_info)
26712e27980eSSarah Sharp 		tt_info->active_eps += 1;
26722e27980eSSarah Sharp 	/* Insert the endpoint into the list, largest max packet size first. */
26732e27980eSSarah Sharp 	list_for_each_entry(smaller_ep, &interval_bw->endpoints,
26742e27980eSSarah Sharp 			bw_endpoint_list) {
26752e27980eSSarah Sharp 		if (ep_bw->max_packet_size >=
26762e27980eSSarah Sharp 				smaller_ep->bw_info.max_packet_size) {
26772e27980eSSarah Sharp 			/* Add the new ep before the smaller endpoint */
26782e27980eSSarah Sharp 			list_add_tail(&virt_ep->bw_endpoint_list,
26792e27980eSSarah Sharp 					&smaller_ep->bw_endpoint_list);
26802e27980eSSarah Sharp 			return;
26812e27980eSSarah Sharp 		}
26822e27980eSSarah Sharp 	}
26832e27980eSSarah Sharp 	/* Add the new endpoint at the end of the list. */
26842e27980eSSarah Sharp 	list_add_tail(&virt_ep->bw_endpoint_list,
26852e27980eSSarah Sharp 			&interval_bw->endpoints);
26862e27980eSSarah Sharp }
26872e27980eSSarah Sharp 
xhci_update_tt_active_eps(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,int old_active_eps)26882e27980eSSarah Sharp void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
26892e27980eSSarah Sharp 		struct xhci_virt_device *virt_dev,
26902e27980eSSarah Sharp 		int old_active_eps)
26912e27980eSSarah Sharp {
26922e27980eSSarah Sharp 	struct xhci_root_port_bw_info *rh_bw_info;
26932e27980eSSarah Sharp 	if (!virt_dev->tt_info)
26942e27980eSSarah Sharp 		return;
26952e27980eSSarah Sharp 
269606790c19SNiklas Neronin 	rh_bw_info = &xhci->rh_bw[virt_dev->rhub_port->hw_portnum];
26972e27980eSSarah Sharp 	if (old_active_eps == 0 &&
26982e27980eSSarah Sharp 				virt_dev->tt_info->active_eps != 0) {
26992e27980eSSarah Sharp 		rh_bw_info->num_active_tts += 1;
2700c29eea62SSarah Sharp 		rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
27012e27980eSSarah Sharp 	} else if (old_active_eps != 0 &&
27022e27980eSSarah Sharp 				virt_dev->tt_info->active_eps == 0) {
27032e27980eSSarah Sharp 		rh_bw_info->num_active_tts -= 1;
2704c29eea62SSarah Sharp 		rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
27052e27980eSSarah Sharp 	}
27062e27980eSSarah Sharp }
27072e27980eSSarah Sharp 
xhci_reserve_bandwidth(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,struct xhci_container_ctx * in_ctx)27082e27980eSSarah Sharp static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
27092e27980eSSarah Sharp 		struct xhci_virt_device *virt_dev,
27102e27980eSSarah Sharp 		struct xhci_container_ctx *in_ctx)
27112e27980eSSarah Sharp {
27122e27980eSSarah Sharp 	struct xhci_bw_info ep_bw_info[31];
27132e27980eSSarah Sharp 	int i;
27142e27980eSSarah Sharp 	struct xhci_input_control_ctx *ctrl_ctx;
27152e27980eSSarah Sharp 	int old_active_eps = 0;
27162e27980eSSarah Sharp 
27172e27980eSSarah Sharp 	if (virt_dev->tt_info)
27182e27980eSSarah Sharp 		old_active_eps = virt_dev->tt_info->active_eps;
27192e27980eSSarah Sharp 
27204daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
272192f8e767SSarah Sharp 	if (!ctrl_ctx) {
272292f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
272392f8e767SSarah Sharp 				__func__);
272492f8e767SSarah Sharp 		return -ENOMEM;
272592f8e767SSarah Sharp 	}
27262e27980eSSarah Sharp 
27272e27980eSSarah Sharp 	for (i = 0; i < 31; i++) {
27282e27980eSSarah Sharp 		if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
27292e27980eSSarah Sharp 			continue;
27302e27980eSSarah Sharp 
27312e27980eSSarah Sharp 		/* Make a copy of the BW info in case we need to revert this */
27322e27980eSSarah Sharp 		memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
27332e27980eSSarah Sharp 				sizeof(ep_bw_info[i]));
27342e27980eSSarah Sharp 		/* Drop the endpoint from the interval table if the endpoint is
27352e27980eSSarah Sharp 		 * being dropped or changed.
27362e27980eSSarah Sharp 		 */
27372e27980eSSarah Sharp 		if (EP_IS_DROPPED(ctrl_ctx, i))
27382e27980eSSarah Sharp 			xhci_drop_ep_from_interval_table(xhci,
27392e27980eSSarah Sharp 					&virt_dev->eps[i].bw_info,
27402e27980eSSarah Sharp 					virt_dev->bw_table,
27412e27980eSSarah Sharp 					virt_dev->udev,
27422e27980eSSarah Sharp 					&virt_dev->eps[i],
27432e27980eSSarah Sharp 					virt_dev->tt_info);
27442e27980eSSarah Sharp 	}
27452e27980eSSarah Sharp 	/* Overwrite the information stored in the endpoints' bw_info */
27462e27980eSSarah Sharp 	xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
27472e27980eSSarah Sharp 	for (i = 0; i < 31; i++) {
27482e27980eSSarah Sharp 		/* Add any changed or added endpoints to the interval table */
27492e27980eSSarah Sharp 		if (EP_IS_ADDED(ctrl_ctx, i))
27502e27980eSSarah Sharp 			xhci_add_ep_to_interval_table(xhci,
27512e27980eSSarah Sharp 					&virt_dev->eps[i].bw_info,
27522e27980eSSarah Sharp 					virt_dev->bw_table,
27532e27980eSSarah Sharp 					virt_dev->udev,
27542e27980eSSarah Sharp 					&virt_dev->eps[i],
27552e27980eSSarah Sharp 					virt_dev->tt_info);
27562e27980eSSarah Sharp 	}
27572e27980eSSarah Sharp 
27582e27980eSSarah Sharp 	if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
27592e27980eSSarah Sharp 		/* Ok, this fits in the bandwidth we have.
27602e27980eSSarah Sharp 		 * Update the number of active TTs.
27612e27980eSSarah Sharp 		 */
27622e27980eSSarah Sharp 		xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
27632e27980eSSarah Sharp 		return 0;
27642e27980eSSarah Sharp 	}
27652e27980eSSarah Sharp 
27662e27980eSSarah Sharp 	/* We don't have enough bandwidth for this, revert the stored info. */
27672e27980eSSarah Sharp 	for (i = 0; i < 31; i++) {
27682e27980eSSarah Sharp 		if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
27692e27980eSSarah Sharp 			continue;
27702e27980eSSarah Sharp 
27712e27980eSSarah Sharp 		/* Drop the new copies of any added or changed endpoints from
27722e27980eSSarah Sharp 		 * the interval table.
27732e27980eSSarah Sharp 		 */
27742e27980eSSarah Sharp 		if (EP_IS_ADDED(ctrl_ctx, i)) {
27752e27980eSSarah Sharp 			xhci_drop_ep_from_interval_table(xhci,
27762e27980eSSarah Sharp 					&virt_dev->eps[i].bw_info,
27772e27980eSSarah Sharp 					virt_dev->bw_table,
27782e27980eSSarah Sharp 					virt_dev->udev,
27792e27980eSSarah Sharp 					&virt_dev->eps[i],
27802e27980eSSarah Sharp 					virt_dev->tt_info);
27812e27980eSSarah Sharp 		}
27822e27980eSSarah Sharp 		/* Revert the endpoint back to its old information */
27832e27980eSSarah Sharp 		memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
27842e27980eSSarah Sharp 				sizeof(ep_bw_info[i]));
27852e27980eSSarah Sharp 		/* Add any changed or dropped endpoints back into the table */
27862e27980eSSarah Sharp 		if (EP_IS_DROPPED(ctrl_ctx, i))
27872e27980eSSarah Sharp 			xhci_add_ep_to_interval_table(xhci,
27882e27980eSSarah Sharp 					&virt_dev->eps[i].bw_info,
27892e27980eSSarah Sharp 					virt_dev->bw_table,
27902e27980eSSarah Sharp 					virt_dev->udev,
27912e27980eSSarah Sharp 					&virt_dev->eps[i],
27922e27980eSSarah Sharp 					virt_dev->tt_info);
27932e27980eSSarah Sharp 	}
27942e27980eSSarah Sharp 	return -ENOMEM;
27952e27980eSSarah Sharp }
27962e27980eSSarah Sharp 
27972e27980eSSarah Sharp 
2798bc75fa38SAlex Chiang /* Issue a configure endpoint command or evaluate context command
2799bc75fa38SAlex Chiang  * and wait for it to finish.
2800bc75fa38SAlex Chiang  */
xhci_configure_endpoint(struct xhci_hcd * xhci,struct usb_device * udev,struct xhci_command * command,bool ctx_change,bool must_succeed)2801bc75fa38SAlex Chiang static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2802bc75fa38SAlex Chiang 		struct usb_device *udev,
2803bc75fa38SAlex Chiang 		struct xhci_command *command,
2804bc75fa38SAlex Chiang 		bool ctx_change, bool must_succeed)
2805bc75fa38SAlex Chiang {
2806bc75fa38SAlex Chiang 	int ret;
2807bc75fa38SAlex Chiang 	unsigned long flags;
280892f8e767SSarah Sharp 	struct xhci_input_control_ctx *ctrl_ctx;
2809bc75fa38SAlex Chiang 	struct xhci_virt_device *virt_dev;
2810e3a78ff0SMathias Nyman 	struct xhci_slot_ctx *slot_ctx;
2811ddba5cd0SMathias Nyman 
2812ddba5cd0SMathias Nyman 	if (!command)
2813ddba5cd0SMathias Nyman 		return -EINVAL;
2814bc75fa38SAlex Chiang 
2815bc75fa38SAlex Chiang 	spin_lock_irqsave(&xhci->lock, flags);
2816d9f11ba9SMathias Nyman 
2817d9f11ba9SMathias Nyman 	if (xhci->xhc_state & XHCI_STATE_DYING) {
2818d9f11ba9SMathias Nyman 		spin_unlock_irqrestore(&xhci->lock, flags);
2819d9f11ba9SMathias Nyman 		return -ESHUTDOWN;
2820d9f11ba9SMathias Nyman 	}
2821d9f11ba9SMathias Nyman 
2822bc75fa38SAlex Chiang 	virt_dev = xhci->devs[udev->slot_id];
2823750645f8SSarah Sharp 
28244daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
282592f8e767SSarah Sharp 	if (!ctrl_ctx) {
28261f21569cSEmil Goode 		spin_unlock_irqrestore(&xhci->lock, flags);
282792f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
282892f8e767SSarah Sharp 				__func__);
282992f8e767SSarah Sharp 		return -ENOMEM;
283092f8e767SSarah Sharp 	}
2831750645f8SSarah Sharp 
28322cf95c18SSarah Sharp 	if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
283392f8e767SSarah Sharp 			xhci_reserve_host_resources(xhci, ctrl_ctx)) {
28342cf95c18SSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
28352cf95c18SSarah Sharp 		xhci_warn(xhci, "Not enough host resources, "
28362cf95c18SSarah Sharp 				"active endpoint contexts = %u\n",
28372cf95c18SSarah Sharp 				xhci->num_active_eps);
28382cf95c18SSarah Sharp 		return -ENOMEM;
28392cf95c18SSarah Sharp 	}
2840af8e119fSMathias Nyman 	if ((xhci->quirks & XHCI_SW_BW_CHECKING) && !ctx_change &&
2841ddba5cd0SMathias Nyman 	    xhci_reserve_bandwidth(xhci, virt_dev, command->in_ctx)) {
28422e27980eSSarah Sharp 		if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
284392f8e767SSarah Sharp 			xhci_free_host_resources(xhci, ctrl_ctx);
28442e27980eSSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
28452e27980eSSarah Sharp 		xhci_warn(xhci, "Not enough bandwidth\n");
28462e27980eSSarah Sharp 		return -ENOMEM;
28472e27980eSSarah Sharp 	}
28482cf95c18SSarah Sharp 
2849e3a78ff0SMathias Nyman 	slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
285090d6d573SMathias Nyman 
285190d6d573SMathias Nyman 	trace_xhci_configure_endpoint_ctrl_ctx(ctrl_ctx);
2852e3a78ff0SMathias Nyman 	trace_xhci_configure_endpoint(slot_ctx);
2853e3a78ff0SMathias Nyman 
2854bc75fa38SAlex Chiang 	if (!ctx_change)
2855ddba5cd0SMathias Nyman 		ret = xhci_queue_configure_endpoint(xhci, command,
2856ddba5cd0SMathias Nyman 				command->in_ctx->dma,
2857bc75fa38SAlex Chiang 				udev->slot_id, must_succeed);
2858bc75fa38SAlex Chiang 	else
2859ddba5cd0SMathias Nyman 		ret = xhci_queue_evaluate_context(xhci, command,
2860ddba5cd0SMathias Nyman 				command->in_ctx->dma,
28614b266541SSarah Sharp 				udev->slot_id, must_succeed);
2862bc75fa38SAlex Chiang 	if (ret < 0) {
28632cf95c18SSarah Sharp 		if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
286492f8e767SSarah Sharp 			xhci_free_host_resources(xhci, ctrl_ctx);
2865bc75fa38SAlex Chiang 		spin_unlock_irqrestore(&xhci->lock, flags);
28663a7fa5beSXenia Ragiadakou 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
28673a7fa5beSXenia Ragiadakou 				"FIXME allocate a new ring segment");
2868bc75fa38SAlex Chiang 		return -ENOMEM;
2869bc75fa38SAlex Chiang 	}
2870bc75fa38SAlex Chiang 	xhci_ring_cmd_db(xhci);
2871bc75fa38SAlex Chiang 	spin_unlock_irqrestore(&xhci->lock, flags);
2872bc75fa38SAlex Chiang 
2873bc75fa38SAlex Chiang 	/* Wait for the configure endpoint command to complete */
2874c311e391SMathias Nyman 	wait_for_completion(command->completion);
2875bc75fa38SAlex Chiang 
2876bc75fa38SAlex Chiang 	if (!ctx_change)
2877ddba5cd0SMathias Nyman 		ret = xhci_configure_endpoint_result(xhci, udev,
2878ddba5cd0SMathias Nyman 						     &command->status);
28792cf95c18SSarah Sharp 	else
2880ddba5cd0SMathias Nyman 		ret = xhci_evaluate_context_result(xhci, udev,
2881ddba5cd0SMathias Nyman 						   &command->status);
28822cf95c18SSarah Sharp 
28832cf95c18SSarah Sharp 	if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
28842cf95c18SSarah Sharp 		spin_lock_irqsave(&xhci->lock, flags);
28852cf95c18SSarah Sharp 		/* If the command failed, remove the reserved resources.
28862cf95c18SSarah Sharp 		 * Otherwise, clean up the estimate to include dropped eps.
28872cf95c18SSarah Sharp 		 */
28882cf95c18SSarah Sharp 		if (ret)
288992f8e767SSarah Sharp 			xhci_free_host_resources(xhci, ctrl_ctx);
28902cf95c18SSarah Sharp 		else
289192f8e767SSarah Sharp 			xhci_finish_resource_reservation(xhci, ctrl_ctx);
28922cf95c18SSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
28932cf95c18SSarah Sharp 	}
28942cf95c18SSarah Sharp 	return ret;
2895bc75fa38SAlex Chiang }
2896bc75fa38SAlex Chiang 
xhci_check_bw_drop_ep_streams(struct xhci_hcd * xhci,struct xhci_virt_device * vdev,int i)2897df613834SHans de Goede static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
2898df613834SHans de Goede 	struct xhci_virt_device *vdev, int i)
2899df613834SHans de Goede {
2900df613834SHans de Goede 	struct xhci_virt_ep *ep = &vdev->eps[i];
2901df613834SHans de Goede 
2902df613834SHans de Goede 	if (ep->ep_state & EP_HAS_STREAMS) {
2903df613834SHans de Goede 		xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
2904df613834SHans de Goede 				xhci_get_endpoint_address(i));
2905df613834SHans de Goede 		xhci_free_stream_info(xhci, ep->stream_info);
2906df613834SHans de Goede 		ep->stream_info = NULL;
2907df613834SHans de Goede 		ep->ep_state &= ~EP_HAS_STREAMS;
2908df613834SHans de Goede 	}
2909df613834SHans de Goede }
2910df613834SHans de Goede 
2911bc75fa38SAlex Chiang /* Called after one or more calls to xhci_add_endpoint() or
2912bc75fa38SAlex Chiang  * xhci_drop_endpoint().  If this call fails, the USB core is expected
2913bc75fa38SAlex Chiang  * to call xhci_reset_bandwidth().
2914bc75fa38SAlex Chiang  *
2915bc75fa38SAlex Chiang  * Since we are in the middle of changing either configuration or
2916bc75fa38SAlex Chiang  * installing a new alt setting, the USB core won't allow URBs to be
2917bc75fa38SAlex Chiang  * enqueued for any endpoint on the old config or interface.  Nothing
2918bc75fa38SAlex Chiang  * else should be touching the xhci->devs[slot_id] structure, so we
2919bc75fa38SAlex Chiang  * don't need to take the xhci->lock for manipulating that.
2920bc75fa38SAlex Chiang  */
xhci_check_bandwidth(struct usb_hcd * hcd,struct usb_device * udev)29211d69f9d9SIkjoon Jang int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2922bc75fa38SAlex Chiang {
2923bc75fa38SAlex Chiang 	int i;
2924bc75fa38SAlex Chiang 	int ret = 0;
2925bc75fa38SAlex Chiang 	struct xhci_hcd *xhci;
2926bc75fa38SAlex Chiang 	struct xhci_virt_device	*virt_dev;
2927bc75fa38SAlex Chiang 	struct xhci_input_control_ctx *ctrl_ctx;
2928bc75fa38SAlex Chiang 	struct xhci_slot_ctx *slot_ctx;
2929ddba5cd0SMathias Nyman 	struct xhci_command *command;
2930bc75fa38SAlex Chiang 
293164927730SAndiry Xu 	ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2932bc75fa38SAlex Chiang 	if (ret <= 0)
2933bc75fa38SAlex Chiang 		return ret;
2934bc75fa38SAlex Chiang 	xhci = hcd_to_xhci(hcd);
293598d74f9cSMathias Nyman 	if ((xhci->xhc_state & XHCI_STATE_DYING) ||
293698d74f9cSMathias Nyman 		(xhci->xhc_state & XHCI_STATE_REMOVING))
2937fe6c6c13SSarah Sharp 		return -ENODEV;
2938bc75fa38SAlex Chiang 
2939bc75fa38SAlex Chiang 	xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2940bc75fa38SAlex Chiang 	virt_dev = xhci->devs[udev->slot_id];
2941bc75fa38SAlex Chiang 
2942103afda0SMathias Nyman 	command = xhci_alloc_command(xhci, true, GFP_KERNEL);
2943ddba5cd0SMathias Nyman 	if (!command)
2944ddba5cd0SMathias Nyman 		return -ENOMEM;
2945ddba5cd0SMathias Nyman 
2946ddba5cd0SMathias Nyman 	command->in_ctx = virt_dev->in_ctx;
2947ddba5cd0SMathias Nyman 
2948bc75fa38SAlex Chiang 	/* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
29494daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
295092f8e767SSarah Sharp 	if (!ctrl_ctx) {
295192f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
295292f8e767SSarah Sharp 				__func__);
2953ddba5cd0SMathias Nyman 		ret = -ENOMEM;
2954ddba5cd0SMathias Nyman 		goto command_cleanup;
295592f8e767SSarah Sharp 	}
295628ccd296SMatt Evans 	ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
295728ccd296SMatt Evans 	ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
295828ccd296SMatt Evans 	ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
29592dc37539SSarah Sharp 
29602dc37539SSarah Sharp 	/* Don't issue the command if there's no endpoints to update. */
29612dc37539SSarah Sharp 	if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2962ddba5cd0SMathias Nyman 	    ctrl_ctx->drop_flags == 0) {
2963ddba5cd0SMathias Nyman 		ret = 0;
2964ddba5cd0SMathias Nyman 		goto command_cleanup;
2965ddba5cd0SMathias Nyman 	}
2966d6759133SJulius Werner 	/* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
2967bc75fa38SAlex Chiang 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2968d6759133SJulius Werner 	for (i = 31; i >= 1; i--) {
2969d6759133SJulius Werner 		__le32 le32 = cpu_to_le32(BIT(i));
2970d6759133SJulius Werner 
2971d6759133SJulius Werner 		if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
2972d6759133SJulius Werner 		    || (ctrl_ctx->add_flags & le32) || i == 1) {
2973d6759133SJulius Werner 			slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2974d6759133SJulius Werner 			slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
2975d6759133SJulius Werner 			break;
2976d6759133SJulius Werner 		}
2977d6759133SJulius Werner 	}
2978bc75fa38SAlex Chiang 
2979ddba5cd0SMathias Nyman 	ret = xhci_configure_endpoint(xhci, udev, command,
2980bc75fa38SAlex Chiang 			false, false);
2981ddba5cd0SMathias Nyman 	if (ret)
2982bc75fa38SAlex Chiang 		/* Callee should call reset_bandwidth() */
2983ddba5cd0SMathias Nyman 		goto command_cleanup;
2984bc75fa38SAlex Chiang 
2985834cb0fcSSarah Sharp 	/* Free any rings that were dropped, but not changed. */
298698871e94SFelipe Balbi 	for (i = 1; i < 31; i++) {
29874819fef5SMatt Evans 		if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2988df613834SHans de Goede 		    !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
2989c5628a2aSMathias Nyman 			xhci_free_endpoint_ring(xhci, virt_dev, i);
2990df613834SHans de Goede 			xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2991df613834SHans de Goede 		}
2992834cb0fcSSarah Sharp 	}
2993bc75fa38SAlex Chiang 	xhci_zero_in_ctx(xhci, virt_dev);
2994834cb0fcSSarah Sharp 	/*
2995834cb0fcSSarah Sharp 	 * Install any rings for completely new endpoints or changed endpoints,
2996c5628a2aSMathias Nyman 	 * and free any old rings from changed endpoints.
2997834cb0fcSSarah Sharp 	 */
299898871e94SFelipe Balbi 	for (i = 1; i < 31; i++) {
2999bc75fa38SAlex Chiang 		if (!virt_dev->eps[i].new_ring)
3000bc75fa38SAlex Chiang 			continue;
3001c5628a2aSMathias Nyman 		/* Only free the old ring if it exists.
3002bc75fa38SAlex Chiang 		 * It may not if this is the first add of an endpoint.
3003bc75fa38SAlex Chiang 		 */
3004bc75fa38SAlex Chiang 		if (virt_dev->eps[i].ring) {
3005c5628a2aSMathias Nyman 			xhci_free_endpoint_ring(xhci, virt_dev, i);
3006bc75fa38SAlex Chiang 		}
3007df613834SHans de Goede 		xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
3008bc75fa38SAlex Chiang 		virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
3009bc75fa38SAlex Chiang 		virt_dev->eps[i].new_ring = NULL;
3010167657a1SMathias Nyman 		xhci_debugfs_create_endpoint(xhci, virt_dev, i);
3011bc75fa38SAlex Chiang 	}
3012ddba5cd0SMathias Nyman command_cleanup:
3013ddba5cd0SMathias Nyman 	kfree(command->completion);
3014ddba5cd0SMathias Nyman 	kfree(command);
3015bc75fa38SAlex Chiang 
3016bc75fa38SAlex Chiang 	return ret;
3017bc75fa38SAlex Chiang }
301814295a15SChunfeng Yun EXPORT_SYMBOL_GPL(xhci_check_bandwidth);
3019bc75fa38SAlex Chiang 
xhci_reset_bandwidth(struct usb_hcd * hcd,struct usb_device * udev)30201d69f9d9SIkjoon Jang void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
3021bc75fa38SAlex Chiang {
3022bc75fa38SAlex Chiang 	struct xhci_hcd *xhci;
3023bc75fa38SAlex Chiang 	struct xhci_virt_device	*virt_dev;
3024bc75fa38SAlex Chiang 	int i, ret;
3025bc75fa38SAlex Chiang 
302664927730SAndiry Xu 	ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3027bc75fa38SAlex Chiang 	if (ret <= 0)
3028bc75fa38SAlex Chiang 		return;
3029bc75fa38SAlex Chiang 	xhci = hcd_to_xhci(hcd);
3030bc75fa38SAlex Chiang 
3031bc75fa38SAlex Chiang 	xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
3032bc75fa38SAlex Chiang 	virt_dev = xhci->devs[udev->slot_id];
3033bc75fa38SAlex Chiang 	/* Free any rings allocated for added endpoints */
303498871e94SFelipe Balbi 	for (i = 0; i < 31; i++) {
3035bc75fa38SAlex Chiang 		if (virt_dev->eps[i].new_ring) {
303602b6fdc2SLu Baolu 			xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
3037bc75fa38SAlex Chiang 			xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
3038bc75fa38SAlex Chiang 			virt_dev->eps[i].new_ring = NULL;
3039bc75fa38SAlex Chiang 		}
3040bc75fa38SAlex Chiang 	}
3041bc75fa38SAlex Chiang 	xhci_zero_in_ctx(xhci, virt_dev);
3042bc75fa38SAlex Chiang }
304314295a15SChunfeng Yun EXPORT_SYMBOL_GPL(xhci_reset_bandwidth);
3044bc75fa38SAlex Chiang 
xhci_setup_input_ctx_for_config_ep(struct xhci_hcd * xhci,struct xhci_container_ctx * in_ctx,struct xhci_container_ctx * out_ctx,struct xhci_input_control_ctx * ctrl_ctx,u32 add_flags,u32 drop_flags)3045bc75fa38SAlex Chiang static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
3046bc75fa38SAlex Chiang 		struct xhci_container_ctx *in_ctx,
3047bc75fa38SAlex Chiang 		struct xhci_container_ctx *out_ctx,
304892f8e767SSarah Sharp 		struct xhci_input_control_ctx *ctrl_ctx,
3049bc75fa38SAlex Chiang 		u32 add_flags, u32 drop_flags)
3050bc75fa38SAlex Chiang {
305128ccd296SMatt Evans 	ctrl_ctx->add_flags = cpu_to_le32(add_flags);
305228ccd296SMatt Evans 	ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
3053bc75fa38SAlex Chiang 	xhci_slot_copy(xhci, in_ctx, out_ctx);
305428ccd296SMatt Evans 	ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
3055bc75fa38SAlex Chiang }
3056bc75fa38SAlex Chiang 
xhci_endpoint_disable(struct usb_hcd * hcd,struct usb_host_endpoint * host_ep)305718b74067SMathias Nyman static void xhci_endpoint_disable(struct usb_hcd *hcd,
305818b74067SMathias Nyman 				  struct usb_host_endpoint *host_ep)
305918b74067SMathias Nyman {
306018b74067SMathias Nyman 	struct xhci_hcd		*xhci;
306118b74067SMathias Nyman 	struct xhci_virt_device	*vdev;
306218b74067SMathias Nyman 	struct xhci_virt_ep	*ep;
306318b74067SMathias Nyman 	struct usb_device	*udev;
306418b74067SMathias Nyman 	unsigned long		flags;
306518b74067SMathias Nyman 	unsigned int		ep_index;
306618b74067SMathias Nyman 
306718b74067SMathias Nyman 	xhci = hcd_to_xhci(hcd);
306818b74067SMathias Nyman rescan:
306918b74067SMathias Nyman 	spin_lock_irqsave(&xhci->lock, flags);
307018b74067SMathias Nyman 
307118b74067SMathias Nyman 	udev = (struct usb_device *)host_ep->hcpriv;
307218b74067SMathias Nyman 	if (!udev || !udev->slot_id)
307318b74067SMathias Nyman 		goto done;
307418b74067SMathias Nyman 
307518b74067SMathias Nyman 	vdev = xhci->devs[udev->slot_id];
307618b74067SMathias Nyman 	if (!vdev)
307718b74067SMathias Nyman 		goto done;
307818b74067SMathias Nyman 
307918b74067SMathias Nyman 	ep_index = xhci_get_endpoint_index(&host_ep->desc);
308018b74067SMathias Nyman 	ep = &vdev->eps[ep_index];
308118b74067SMathias Nyman 
308218b74067SMathias Nyman 	/* wait for hub_tt_work to finish clearing hub TT */
308318b74067SMathias Nyman 	if (ep->ep_state & EP_CLEARING_TT) {
308418b74067SMathias Nyman 		spin_unlock_irqrestore(&xhci->lock, flags);
308518b74067SMathias Nyman 		schedule_timeout_uninterruptible(1);
308618b74067SMathias Nyman 		goto rescan;
308718b74067SMathias Nyman 	}
308818b74067SMathias Nyman 
308918b74067SMathias Nyman 	if (ep->ep_state)
309018b74067SMathias Nyman 		xhci_dbg(xhci, "endpoint disable with ep_state 0x%x\n",
309118b74067SMathias Nyman 			 ep->ep_state);
309218b74067SMathias Nyman done:
309318b74067SMathias Nyman 	host_ep->hcpriv = NULL;
309418b74067SMathias Nyman 	spin_unlock_irqrestore(&xhci->lock, flags);
309518b74067SMathias Nyman }
309618b74067SMathias Nyman 
3097f5249461SMathias Nyman /*
3098f5249461SMathias Nyman  * Called after usb core issues a clear halt control message.
3099f5249461SMathias Nyman  * The host side of the halt should already be cleared by a reset endpoint
3100f5249461SMathias Nyman  * command issued when the STALL event was received.
3101d0167ad2SMathias Nyman  *
3102f5249461SMathias Nyman  * The reset endpoint command may only be issued to endpoints in the halted
3103f5249461SMathias Nyman  * state. For software that wishes to reset the data toggle or sequence number
3104f5249461SMathias Nyman  * of an endpoint that isn't in the halted state this function will issue a
3105f5249461SMathias Nyman  * configure endpoint command with the Drop and Add bits set for the target
3106f5249461SMathias Nyman  * endpoint. Refer to the additional note in xhci spcification section 4.6.8.
310780602b6bSMathias Nyman  *
310880602b6bSMathias Nyman  * vdev may be lost due to xHC restore error and re-initialization during S3/S4
310980602b6bSMathias Nyman  * resume. A new vdev will be allocated later by xhci_discover_or_reset_device()
3110bc75fa38SAlex Chiang  */
31118e71a322SMathias Nyman 
xhci_endpoint_reset(struct usb_hcd * hcd,struct usb_host_endpoint * host_ep)31123969384cSLu Baolu static void xhci_endpoint_reset(struct usb_hcd *hcd,
3113f5249461SMathias Nyman 		struct usb_host_endpoint *host_ep)
3114bc75fa38SAlex Chiang {
3115bc75fa38SAlex Chiang 	struct xhci_hcd *xhci;
3116f5249461SMathias Nyman 	struct usb_device *udev;
3117f5249461SMathias Nyman 	struct xhci_virt_device *vdev;
3118f5249461SMathias Nyman 	struct xhci_virt_ep *ep;
3119f5249461SMathias Nyman 	struct xhci_input_control_ctx *ctrl_ctx;
31203bf0514dSGreg Kroah-Hartman 	struct xhci_command *stop_cmd, *cfg_cmd;
3121f5249461SMathias Nyman 	unsigned int ep_index;
3122f5249461SMathias Nyman 	unsigned long flags;
3123f5249461SMathias Nyman 	u32 ep_flag;
31248de66b0eSBill Kuzeja 	int err;
3125bc75fa38SAlex Chiang 
3126bc75fa38SAlex Chiang 	xhci = hcd_to_xhci(hcd);
3127e34900f4SMathias Nyman 	ep_index = xhci_get_endpoint_index(&host_ep->desc);
3128e34900f4SMathias Nyman 
3129e34900f4SMathias Nyman 	/*
3130e34900f4SMathias Nyman 	 * Usb core assumes a max packet value for ep0 on FS devices until the
3131e34900f4SMathias Nyman 	 * real value is read from the descriptor. Core resets Ep0 if values
3132e34900f4SMathias Nyman 	 * mismatch. Reconfigure the xhci ep0 endpoint context here in that case
3133e34900f4SMathias Nyman 	 */
3134e34900f4SMathias Nyman 	if (usb_endpoint_xfer_control(&host_ep->desc) && ep_index == 0) {
313580602b6bSMathias Nyman 
3136e34900f4SMathias Nyman 		udev = container_of(host_ep, struct usb_device, ep0);
313780602b6bSMathias Nyman 		if (udev->speed != USB_SPEED_FULL || !udev->slot_id)
313880602b6bSMathias Nyman 			return;
313980602b6bSMathias Nyman 
314080602b6bSMathias Nyman 		vdev = xhci->devs[udev->slot_id];
314180602b6bSMathias Nyman 		if (!vdev || vdev->udev != udev)
314280602b6bSMathias Nyman 			return;
314380602b6bSMathias Nyman 
314480602b6bSMathias Nyman 		xhci_check_ep0_maxpacket(xhci, vdev);
314580602b6bSMathias Nyman 
3146e34900f4SMathias Nyman 		/* Nothing else should be done here for ep0 during ep reset */
3147e34900f4SMathias Nyman 		return;
3148e34900f4SMathias Nyman 	}
3149e34900f4SMathias Nyman 
3150f5249461SMathias Nyman 	if (!host_ep->hcpriv)
3151f5249461SMathias Nyman 		return;
3152f5249461SMathias Nyman 	udev = (struct usb_device *) host_ep->hcpriv;
3153f5249461SMathias Nyman 	vdev = xhci->devs[udev->slot_id];
3154cb53c517SMathias Nyman 
3155cb53c517SMathias Nyman 	if (!udev->slot_id || !vdev)
3156cb53c517SMathias Nyman 		return;
3157e34900f4SMathias Nyman 
3158f5249461SMathias Nyman 	ep = &vdev->eps[ep_index];
3159f5249461SMathias Nyman 
3160f5249461SMathias Nyman 	/* Bail out if toggle is already being cleared by a endpoint reset */
3161a01ba2a3SJonathan Bell 	spin_lock_irqsave(&xhci->lock, flags);
3162f5249461SMathias Nyman 	if (ep->ep_state & EP_HARD_CLEAR_TOGGLE) {
3163f5249461SMathias Nyman 		ep->ep_state &= ~EP_HARD_CLEAR_TOGGLE;
3164a01ba2a3SJonathan Bell 		spin_unlock_irqrestore(&xhci->lock, flags);
3165f5249461SMathias Nyman 		return;
3166f5249461SMathias Nyman 	}
3167a01ba2a3SJonathan Bell 	spin_unlock_irqrestore(&xhci->lock, flags);
3168f5249461SMathias Nyman 	/* Only interrupt and bulk ep's use data toggle, USB2 spec 5.5.4-> */
3169f5249461SMathias Nyman 	if (usb_endpoint_xfer_control(&host_ep->desc) ||
3170f5249461SMathias Nyman 	    usb_endpoint_xfer_isoc(&host_ep->desc))
3171f5249461SMathias Nyman 		return;
3172f5249461SMathias Nyman 
3173f5249461SMathias Nyman 	ep_flag = xhci_get_endpoint_flag(&host_ep->desc);
3174f5249461SMathias Nyman 
3175f5249461SMathias Nyman 	if (ep_flag == SLOT_FLAG || ep_flag == EP0_FLAG)
3176f5249461SMathias Nyman 		return;
3177f5249461SMathias Nyman 
31783bf0514dSGreg Kroah-Hartman 	stop_cmd = xhci_alloc_command(xhci, true, GFP_NOWAIT);
31793bf0514dSGreg Kroah-Hartman 	if (!stop_cmd)
31803bf0514dSGreg Kroah-Hartman 		return;
31813bf0514dSGreg Kroah-Hartman 
3182f5249461SMathias Nyman 	cfg_cmd = xhci_alloc_command_with_ctx(xhci, true, GFP_NOWAIT);
3183f5249461SMathias Nyman 	if (!cfg_cmd)
3184f5249461SMathias Nyman 		goto cleanup;
3185f5249461SMathias Nyman 
3186f5249461SMathias Nyman 	spin_lock_irqsave(&xhci->lock, flags);
3187f5249461SMathias Nyman 
3188f5249461SMathias Nyman 	/* block queuing new trbs and ringing ep doorbell */
3189f5249461SMathias Nyman 	ep->ep_state |= EP_SOFT_CLEAR_TOGGLE;
3190bc75fa38SAlex Chiang 
3191bc75fa38SAlex Chiang 	/*
3192f5249461SMathias Nyman 	 * Make sure endpoint ring is empty before resetting the toggle/seq.
3193f5249461SMathias Nyman 	 * Driver is required to synchronously cancel all transfer request.
3194f5249461SMathias Nyman 	 * Stop the endpoint to force xHC to update the output context
3195bc75fa38SAlex Chiang 	 */
3196bc75fa38SAlex Chiang 
3197f5249461SMathias Nyman 	if (!list_empty(&ep->ring->td_list)) {
3198f5249461SMathias Nyman 		dev_err(&udev->dev, "EP not empty, refuse reset\n");
3199f5249461SMathias Nyman 		spin_unlock_irqrestore(&xhci->lock, flags);
3200d89b7664SZheng Xiaowei 		xhci_free_command(xhci, cfg_cmd);
3201f5249461SMathias Nyman 		goto cleanup;
3202f5249461SMathias Nyman 	}
32038de66b0eSBill Kuzeja 
32043bf0514dSGreg Kroah-Hartman 	err = xhci_queue_stop_endpoint(xhci, stop_cmd, udev->slot_id,
32053bf0514dSGreg Kroah-Hartman 					ep_index, 0);
32069affb1d9SMathias Nyman 	if (err < 0) {
32073bf0514dSGreg Kroah-Hartman 		spin_unlock_irqrestore(&xhci->lock, flags);
32083bf0514dSGreg Kroah-Hartman 		xhci_free_command(xhci, cfg_cmd);
32098de66b0eSBill Kuzeja 		xhci_dbg(xhci, "%s: Failed to queue stop ep command, %d ",
32108de66b0eSBill Kuzeja 				__func__, err);
32118de66b0eSBill Kuzeja 		goto cleanup;
32128de66b0eSBill Kuzeja 	}
32138de66b0eSBill Kuzeja 
32143bf0514dSGreg Kroah-Hartman 	xhci_ring_cmd_db(xhci);
32153bf0514dSGreg Kroah-Hartman 	spin_unlock_irqrestore(&xhci->lock, flags);
32163bf0514dSGreg Kroah-Hartman 
32173bf0514dSGreg Kroah-Hartman 	wait_for_completion(stop_cmd->completion);
32183bf0514dSGreg Kroah-Hartman 
3219f5249461SMathias Nyman 	spin_lock_irqsave(&xhci->lock, flags);
32203bf0514dSGreg Kroah-Hartman 
3221f5249461SMathias Nyman 	/* config ep command clears toggle if add and drop ep flags are set */
3222f5249461SMathias Nyman 	ctrl_ctx = xhci_get_input_control_ctx(cfg_cmd->in_ctx);
3223597899d2SMathias Nyman 	if (!ctrl_ctx) {
3224597899d2SMathias Nyman 		spin_unlock_irqrestore(&xhci->lock, flags);
3225597899d2SMathias Nyman 		xhci_free_command(xhci, cfg_cmd);
3226597899d2SMathias Nyman 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3227597899d2SMathias Nyman 				__func__);
3228597899d2SMathias Nyman 		goto cleanup;
3229597899d2SMathias Nyman 	}
3230597899d2SMathias Nyman 
3231f5249461SMathias Nyman 	xhci_setup_input_ctx_for_config_ep(xhci, cfg_cmd->in_ctx, vdev->out_ctx,
3232f5249461SMathias Nyman 					   ctrl_ctx, ep_flag, ep_flag);
3233f5249461SMathias Nyman 	xhci_endpoint_copy(xhci, cfg_cmd->in_ctx, vdev->out_ctx, ep_index);
3234f5249461SMathias Nyman 
32358de66b0eSBill Kuzeja 	err = xhci_queue_configure_endpoint(xhci, cfg_cmd, cfg_cmd->in_ctx->dma,
3236f5249461SMathias Nyman 				      udev->slot_id, false);
32378de66b0eSBill Kuzeja 	if (err < 0) {
32388de66b0eSBill Kuzeja 		spin_unlock_irqrestore(&xhci->lock, flags);
32398de66b0eSBill Kuzeja 		xhci_free_command(xhci, cfg_cmd);
32408de66b0eSBill Kuzeja 		xhci_dbg(xhci, "%s: Failed to queue config ep command, %d ",
32418de66b0eSBill Kuzeja 				__func__, err);
32428de66b0eSBill Kuzeja 		goto cleanup;
32438de66b0eSBill Kuzeja 	}
32448de66b0eSBill Kuzeja 
3245f5249461SMathias Nyman 	xhci_ring_cmd_db(xhci);
3246f5249461SMathias Nyman 	spin_unlock_irqrestore(&xhci->lock, flags);
3247f5249461SMathias Nyman 
3248f5249461SMathias Nyman 	wait_for_completion(cfg_cmd->completion);
3249f5249461SMathias Nyman 
3250f5249461SMathias Nyman 	xhci_free_command(xhci, cfg_cmd);
3251f5249461SMathias Nyman cleanup:
32523bf0514dSGreg Kroah-Hartman 	xhci_free_command(xhci, stop_cmd);
3253a01ba2a3SJonathan Bell 	spin_lock_irqsave(&xhci->lock, flags);
3254f1ec7ae6SDing Hui 	if (ep->ep_state & EP_SOFT_CLEAR_TOGGLE)
3255f1ec7ae6SDing Hui 		ep->ep_state &= ~EP_SOFT_CLEAR_TOGGLE;
3256a01ba2a3SJonathan Bell 	spin_unlock_irqrestore(&xhci->lock, flags);
3257bc75fa38SAlex Chiang }
3258bc75fa38SAlex Chiang 
xhci_check_streams_endpoint(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_host_endpoint * ep,unsigned int slot_id)32598df75f42SSarah Sharp static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
32608df75f42SSarah Sharp 		struct usb_device *udev, struct usb_host_endpoint *ep,
32618df75f42SSarah Sharp 		unsigned int slot_id)
32628df75f42SSarah Sharp {
32638df75f42SSarah Sharp 	int ret;
32648df75f42SSarah Sharp 	unsigned int ep_index;
32658df75f42SSarah Sharp 	unsigned int ep_state;
32668df75f42SSarah Sharp 
32678df75f42SSarah Sharp 	if (!ep)
32688df75f42SSarah Sharp 		return -EINVAL;
326964927730SAndiry Xu 	ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
32708df75f42SSarah Sharp 	if (ret <= 0)
3271243a1dd7SHongyu Xie 		return ret ? ret : -EINVAL;
3272a3901538SHans de Goede 	if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
32738df75f42SSarah Sharp 		xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
32748df75f42SSarah Sharp 				" descriptor for ep 0x%x does not support streams\n",
32758df75f42SSarah Sharp 				ep->desc.bEndpointAddress);
32768df75f42SSarah Sharp 		return -EINVAL;
32778df75f42SSarah Sharp 	}
32788df75f42SSarah Sharp 
32798df75f42SSarah Sharp 	ep_index = xhci_get_endpoint_index(&ep->desc);
32808df75f42SSarah Sharp 	ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
32818df75f42SSarah Sharp 	if (ep_state & EP_HAS_STREAMS ||
32828df75f42SSarah Sharp 			ep_state & EP_GETTING_STREAMS) {
32838df75f42SSarah Sharp 		xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
32848df75f42SSarah Sharp 				"already has streams set up.\n",
32858df75f42SSarah Sharp 				ep->desc.bEndpointAddress);
32868df75f42SSarah Sharp 		xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
32878df75f42SSarah Sharp 				"dynamic stream context array reallocation.\n");
32888df75f42SSarah Sharp 		return -EINVAL;
32898df75f42SSarah Sharp 	}
32908df75f42SSarah Sharp 	if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
32918df75f42SSarah Sharp 		xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
32928df75f42SSarah Sharp 				"endpoint 0x%x; URBs are pending.\n",
32938df75f42SSarah Sharp 				ep->desc.bEndpointAddress);
32948df75f42SSarah Sharp 		return -EINVAL;
32958df75f42SSarah Sharp 	}
32968df75f42SSarah Sharp 	return 0;
32978df75f42SSarah Sharp }
32988df75f42SSarah Sharp 
xhci_calculate_streams_entries(struct xhci_hcd * xhci,unsigned int * num_streams,unsigned int * num_stream_ctxs)32998df75f42SSarah Sharp static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
33008df75f42SSarah Sharp 		unsigned int *num_streams, unsigned int *num_stream_ctxs)
33018df75f42SSarah Sharp {
33028df75f42SSarah Sharp 	unsigned int max_streams;
33038df75f42SSarah Sharp 
33048df75f42SSarah Sharp 	/* The stream context array size must be a power of two */
33058df75f42SSarah Sharp 	*num_stream_ctxs = roundup_pow_of_two(*num_streams);
33068df75f42SSarah Sharp 	/*
33078df75f42SSarah Sharp 	 * Find out how many primary stream array entries the host controller
33088df75f42SSarah Sharp 	 * supports.  Later we may use secondary stream arrays (similar to 2nd
33098df75f42SSarah Sharp 	 * level page entries), but that's an optional feature for xHCI host
33108df75f42SSarah Sharp 	 * controllers. xHCs must support at least 4 stream IDs.
33118df75f42SSarah Sharp 	 */
33128df75f42SSarah Sharp 	max_streams = HCC_MAX_PSA(xhci->hcc_params);
33138df75f42SSarah Sharp 	if (*num_stream_ctxs > max_streams) {
33148df75f42SSarah Sharp 		xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
33158df75f42SSarah Sharp 				max_streams);
33168df75f42SSarah Sharp 		*num_stream_ctxs = max_streams;
33178df75f42SSarah Sharp 		*num_streams = max_streams;
33188df75f42SSarah Sharp 	}
33198df75f42SSarah Sharp }
33208df75f42SSarah Sharp 
33218df75f42SSarah Sharp /* Returns an error code if one of the endpoint already has streams.
33228df75f42SSarah Sharp  * This does not change any data structures, it only checks and gathers
33238df75f42SSarah Sharp  * information.
33248df75f42SSarah Sharp  */
xhci_calculate_streams_and_bitmask(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_host_endpoint ** eps,unsigned int num_eps,unsigned int * num_streams,u32 * changed_ep_bitmask)33258df75f42SSarah Sharp static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
33268df75f42SSarah Sharp 		struct usb_device *udev,
33278df75f42SSarah Sharp 		struct usb_host_endpoint **eps, unsigned int num_eps,
33288df75f42SSarah Sharp 		unsigned int *num_streams, u32 *changed_ep_bitmask)
33298df75f42SSarah Sharp {
33308df75f42SSarah Sharp 	unsigned int max_streams;
33318df75f42SSarah Sharp 	unsigned int endpoint_flag;
33328df75f42SSarah Sharp 	int i;
33338df75f42SSarah Sharp 	int ret;
33348df75f42SSarah Sharp 
33358df75f42SSarah Sharp 	for (i = 0; i < num_eps; i++) {
33368df75f42SSarah Sharp 		ret = xhci_check_streams_endpoint(xhci, udev,
33378df75f42SSarah Sharp 				eps[i], udev->slot_id);
33388df75f42SSarah Sharp 		if (ret < 0)
33398df75f42SSarah Sharp 			return ret;
33408df75f42SSarah Sharp 
334118b7ede5SFelipe Balbi 		max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
33428df75f42SSarah Sharp 		if (max_streams < (*num_streams - 1)) {
33438df75f42SSarah Sharp 			xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
33448df75f42SSarah Sharp 					eps[i]->desc.bEndpointAddress,
33458df75f42SSarah Sharp 					max_streams);
33468df75f42SSarah Sharp 			*num_streams = max_streams+1;
33478df75f42SSarah Sharp 		}
33488df75f42SSarah Sharp 
33498df75f42SSarah Sharp 		endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
33508df75f42SSarah Sharp 		if (*changed_ep_bitmask & endpoint_flag)
33518df75f42SSarah Sharp 			return -EINVAL;
33528df75f42SSarah Sharp 		*changed_ep_bitmask |= endpoint_flag;
33538df75f42SSarah Sharp 	}
33548df75f42SSarah Sharp 	return 0;
33558df75f42SSarah Sharp }
33568df75f42SSarah Sharp 
xhci_calculate_no_streams_bitmask(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_host_endpoint ** eps,unsigned int num_eps)33578df75f42SSarah Sharp static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
33588df75f42SSarah Sharp 		struct usb_device *udev,
33598df75f42SSarah Sharp 		struct usb_host_endpoint **eps, unsigned int num_eps)
33608df75f42SSarah Sharp {
33618df75f42SSarah Sharp 	u32 changed_ep_bitmask = 0;
33628df75f42SSarah Sharp 	unsigned int slot_id;
33638df75f42SSarah Sharp 	unsigned int ep_index;
33648df75f42SSarah Sharp 	unsigned int ep_state;
33658df75f42SSarah Sharp 	int i;
33668df75f42SSarah Sharp 
33678df75f42SSarah Sharp 	slot_id = udev->slot_id;
33688df75f42SSarah Sharp 	if (!xhci->devs[slot_id])
33698df75f42SSarah Sharp 		return 0;
33708df75f42SSarah Sharp 
33718df75f42SSarah Sharp 	for (i = 0; i < num_eps; i++) {
33728df75f42SSarah Sharp 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
33738df75f42SSarah Sharp 		ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
33748df75f42SSarah Sharp 		/* Are streams already being freed for the endpoint? */
33758df75f42SSarah Sharp 		if (ep_state & EP_GETTING_NO_STREAMS) {
33768df75f42SSarah Sharp 			xhci_warn(xhci, "WARN Can't disable streams for "
337703e64e96SJoe Perches 					"endpoint 0x%x, "
337803e64e96SJoe Perches 					"streams are being disabled already\n",
33798df75f42SSarah Sharp 					eps[i]->desc.bEndpointAddress);
33808df75f42SSarah Sharp 			return 0;
33818df75f42SSarah Sharp 		}
33828df75f42SSarah Sharp 		/* Are there actually any streams to free? */
33838df75f42SSarah Sharp 		if (!(ep_state & EP_HAS_STREAMS) &&
33848df75f42SSarah Sharp 				!(ep_state & EP_GETTING_STREAMS)) {
33858df75f42SSarah Sharp 			xhci_warn(xhci, "WARN Can't disable streams for "
338603e64e96SJoe Perches 					"endpoint 0x%x, "
338703e64e96SJoe Perches 					"streams are already disabled!\n",
33888df75f42SSarah Sharp 					eps[i]->desc.bEndpointAddress);
33898df75f42SSarah Sharp 			xhci_warn(xhci, "WARN xhci_free_streams() called "
33908df75f42SSarah Sharp 					"with non-streams endpoint\n");
33918df75f42SSarah Sharp 			return 0;
33928df75f42SSarah Sharp 		}
33938df75f42SSarah Sharp 		changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
33948df75f42SSarah Sharp 	}
33958df75f42SSarah Sharp 	return changed_ep_bitmask;
33968df75f42SSarah Sharp }
33978df75f42SSarah Sharp 
33988df75f42SSarah Sharp /*
3399c2a298d9SLuis de Bethencourt  * The USB device drivers use this function (through the HCD interface in USB
34008df75f42SSarah Sharp  * core) to prepare a set of bulk endpoints to use streams.  Streams are used to
34018df75f42SSarah Sharp  * coordinate mass storage command queueing across multiple endpoints (basically
34028df75f42SSarah Sharp  * a stream ID == a task ID).
34038df75f42SSarah Sharp  *
34048df75f42SSarah Sharp  * Setting up streams involves allocating the same size stream context array
34058df75f42SSarah Sharp  * for each endpoint and issuing a configure endpoint command for all endpoints.
34068df75f42SSarah Sharp  *
34078df75f42SSarah Sharp  * Don't allow the call to succeed if one endpoint only supports one stream
34088df75f42SSarah Sharp  * (which means it doesn't support streams at all).
34098df75f42SSarah Sharp  *
34108df75f42SSarah Sharp  * Drivers may get less stream IDs than they asked for, if the host controller
34118df75f42SSarah Sharp  * hardware or endpoints claim they can't support the number of requested
34128df75f42SSarah Sharp  * stream IDs.
34138df75f42SSarah Sharp  */
xhci_alloc_streams(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint ** eps,unsigned int num_eps,unsigned int num_streams,gfp_t mem_flags)34143969384cSLu Baolu static int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
34158df75f42SSarah Sharp 		struct usb_host_endpoint **eps, unsigned int num_eps,
34168df75f42SSarah Sharp 		unsigned int num_streams, gfp_t mem_flags)
34178df75f42SSarah Sharp {
34188df75f42SSarah Sharp 	int i, ret;
34198df75f42SSarah Sharp 	struct xhci_hcd *xhci;
34208df75f42SSarah Sharp 	struct xhci_virt_device *vdev;
34218df75f42SSarah Sharp 	struct xhci_command *config_cmd;
342292f8e767SSarah Sharp 	struct xhci_input_control_ctx *ctrl_ctx;
34238df75f42SSarah Sharp 	unsigned int ep_index;
34248df75f42SSarah Sharp 	unsigned int num_stream_ctxs;
3425f9c589e1SMathias Nyman 	unsigned int max_packet;
34268df75f42SSarah Sharp 	unsigned long flags;
34278df75f42SSarah Sharp 	u32 changed_ep_bitmask = 0;
34288df75f42SSarah Sharp 
34298df75f42SSarah Sharp 	if (!eps)
34308df75f42SSarah Sharp 		return -EINVAL;
34318df75f42SSarah Sharp 
34328df75f42SSarah Sharp 	/* Add one to the number of streams requested to account for
34338df75f42SSarah Sharp 	 * stream 0 that is reserved for xHCI usage.
34348df75f42SSarah Sharp 	 */
34358df75f42SSarah Sharp 	num_streams += 1;
34368df75f42SSarah Sharp 	xhci = hcd_to_xhci(hcd);
34378df75f42SSarah Sharp 	xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
34388df75f42SSarah Sharp 			num_streams);
34398df75f42SSarah Sharp 
3440f7920884SHans de Goede 	/* MaxPSASize value 0 (2 streams) means streams are not supported */
34418f873c1fSHans de Goede 	if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
34428f873c1fSHans de Goede 			HCC_MAX_PSA(xhci->hcc_params) < 4) {
3443f7920884SHans de Goede 		xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3444f7920884SHans de Goede 		return -ENOSYS;
3445f7920884SHans de Goede 	}
3446f7920884SHans de Goede 
344714d49b7aSMathias Nyman 	config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
344874e0b564SLu Baolu 	if (!config_cmd)
34498df75f42SSarah Sharp 		return -ENOMEM;
345074e0b564SLu Baolu 
34514daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
345292f8e767SSarah Sharp 	if (!ctrl_ctx) {
345392f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
345492f8e767SSarah Sharp 				__func__);
345592f8e767SSarah Sharp 		xhci_free_command(xhci, config_cmd);
345692f8e767SSarah Sharp 		return -ENOMEM;
345792f8e767SSarah Sharp 	}
34588df75f42SSarah Sharp 
34598df75f42SSarah Sharp 	/* Check to make sure all endpoints are not already configured for
34608df75f42SSarah Sharp 	 * streams.  While we're at it, find the maximum number of streams that
34618df75f42SSarah Sharp 	 * all the endpoints will support and check for duplicate endpoints.
34628df75f42SSarah Sharp 	 */
34638df75f42SSarah Sharp 	spin_lock_irqsave(&xhci->lock, flags);
34648df75f42SSarah Sharp 	ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
34658df75f42SSarah Sharp 			num_eps, &num_streams, &changed_ep_bitmask);
34668df75f42SSarah Sharp 	if (ret < 0) {
34678df75f42SSarah Sharp 		xhci_free_command(xhci, config_cmd);
34688df75f42SSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
34698df75f42SSarah Sharp 		return ret;
34708df75f42SSarah Sharp 	}
34718df75f42SSarah Sharp 	if (num_streams <= 1) {
34728df75f42SSarah Sharp 		xhci_warn(xhci, "WARN: endpoints can't handle "
34738df75f42SSarah Sharp 				"more than one stream.\n");
34748df75f42SSarah Sharp 		xhci_free_command(xhci, config_cmd);
34758df75f42SSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
34768df75f42SSarah Sharp 		return -EINVAL;
34778df75f42SSarah Sharp 	}
34788df75f42SSarah Sharp 	vdev = xhci->devs[udev->slot_id];
347925985edcSLucas De Marchi 	/* Mark each endpoint as being in transition, so
34808df75f42SSarah Sharp 	 * xhci_urb_enqueue() will reject all URBs.
34818df75f42SSarah Sharp 	 */
34828df75f42SSarah Sharp 	for (i = 0; i < num_eps; i++) {
34838df75f42SSarah Sharp 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
34848df75f42SSarah Sharp 		vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
34858df75f42SSarah Sharp 	}
34868df75f42SSarah Sharp 	spin_unlock_irqrestore(&xhci->lock, flags);
34878df75f42SSarah Sharp 
34888df75f42SSarah Sharp 	/* Setup internal data structures and allocate HW data structures for
34898df75f42SSarah Sharp 	 * streams (but don't install the HW structures in the input context
34908df75f42SSarah Sharp 	 * until we're sure all memory allocation succeeded).
34918df75f42SSarah Sharp 	 */
34928df75f42SSarah Sharp 	xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
34938df75f42SSarah Sharp 	xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
34948df75f42SSarah Sharp 			num_stream_ctxs, num_streams);
34958df75f42SSarah Sharp 
34968df75f42SSarah Sharp 	for (i = 0; i < num_eps; i++) {
34978df75f42SSarah Sharp 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3498734d3dddSFelipe Balbi 		max_packet = usb_endpoint_maxp(&eps[i]->desc);
34998df75f42SSarah Sharp 		vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
35008df75f42SSarah Sharp 				num_stream_ctxs,
3501f9c589e1SMathias Nyman 				num_streams,
3502f9c589e1SMathias Nyman 				max_packet, mem_flags);
35038df75f42SSarah Sharp 		if (!vdev->eps[ep_index].stream_info)
35048df75f42SSarah Sharp 			goto cleanup;
35058df75f42SSarah Sharp 		/* Set maxPstreams in endpoint context and update deq ptr to
35068df75f42SSarah Sharp 		 * point to stream context array. FIXME
35078df75f42SSarah Sharp 		 */
35088df75f42SSarah Sharp 	}
35098df75f42SSarah Sharp 
35108df75f42SSarah Sharp 	/* Set up the input context for a configure endpoint command. */
35118df75f42SSarah Sharp 	for (i = 0; i < num_eps; i++) {
35128df75f42SSarah Sharp 		struct xhci_ep_ctx *ep_ctx;
35138df75f42SSarah Sharp 
35148df75f42SSarah Sharp 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
35158df75f42SSarah Sharp 		ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
35168df75f42SSarah Sharp 
35178df75f42SSarah Sharp 		xhci_endpoint_copy(xhci, config_cmd->in_ctx,
35188df75f42SSarah Sharp 				vdev->out_ctx, ep_index);
35198df75f42SSarah Sharp 		xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
35208df75f42SSarah Sharp 				vdev->eps[ep_index].stream_info);
35218df75f42SSarah Sharp 	}
35228df75f42SSarah Sharp 	/* Tell the HW to drop its old copy of the endpoint context info
35238df75f42SSarah Sharp 	 * and add the updated copy from the input context.
35248df75f42SSarah Sharp 	 */
35258df75f42SSarah Sharp 	xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
352692f8e767SSarah Sharp 			vdev->out_ctx, ctrl_ctx,
352792f8e767SSarah Sharp 			changed_ep_bitmask, changed_ep_bitmask);
35288df75f42SSarah Sharp 
35298df75f42SSarah Sharp 	/* Issue and wait for the configure endpoint command */
35308df75f42SSarah Sharp 	ret = xhci_configure_endpoint(xhci, udev, config_cmd,
35318df75f42SSarah Sharp 			false, false);
35328df75f42SSarah Sharp 
35338df75f42SSarah Sharp 	/* xHC rejected the configure endpoint command for some reason, so we
35348df75f42SSarah Sharp 	 * leave the old ring intact and free our internal streams data
35358df75f42SSarah Sharp 	 * structure.
35368df75f42SSarah Sharp 	 */
35378df75f42SSarah Sharp 	if (ret < 0)
35388df75f42SSarah Sharp 		goto cleanup;
35398df75f42SSarah Sharp 
35408df75f42SSarah Sharp 	spin_lock_irqsave(&xhci->lock, flags);
35418df75f42SSarah Sharp 	for (i = 0; i < num_eps; i++) {
35428df75f42SSarah Sharp 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
35438df75f42SSarah Sharp 		vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
35448df75f42SSarah Sharp 		xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
35458df75f42SSarah Sharp 			 udev->slot_id, ep_index);
35468df75f42SSarah Sharp 		vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
35478df75f42SSarah Sharp 	}
35488df75f42SSarah Sharp 	xhci_free_command(xhci, config_cmd);
35498df75f42SSarah Sharp 	spin_unlock_irqrestore(&xhci->lock, flags);
35508df75f42SSarah Sharp 
3551712da5fcSMathias Nyman 	for (i = 0; i < num_eps; i++) {
3552712da5fcSMathias Nyman 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3553712da5fcSMathias Nyman 		xhci_debugfs_create_stream_files(xhci, vdev, ep_index);
3554712da5fcSMathias Nyman 	}
35558df75f42SSarah Sharp 	/* Subtract 1 for stream 0, which drivers can't use */
35568df75f42SSarah Sharp 	return num_streams - 1;
35578df75f42SSarah Sharp 
35588df75f42SSarah Sharp cleanup:
35598df75f42SSarah Sharp 	/* If it didn't work, free the streams! */
35608df75f42SSarah Sharp 	for (i = 0; i < num_eps; i++) {
35618df75f42SSarah Sharp 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
35628df75f42SSarah Sharp 		xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
35638a007748SSarah Sharp 		vdev->eps[ep_index].stream_info = NULL;
35648df75f42SSarah Sharp 		/* FIXME Unset maxPstreams in endpoint context and
35658df75f42SSarah Sharp 		 * update deq ptr to point to normal string ring.
35668df75f42SSarah Sharp 		 */
35678df75f42SSarah Sharp 		vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
35688df75f42SSarah Sharp 		vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
35698df75f42SSarah Sharp 		xhci_endpoint_zero(xhci, vdev, eps[i]);
35708df75f42SSarah Sharp 	}
35718df75f42SSarah Sharp 	xhci_free_command(xhci, config_cmd);
35728df75f42SSarah Sharp 	return -ENOMEM;
35738df75f42SSarah Sharp }
35748df75f42SSarah Sharp 
35758df75f42SSarah Sharp /* Transition the endpoint from using streams to being a "normal" endpoint
35768df75f42SSarah Sharp  * without streams.
35778df75f42SSarah Sharp  *
35788df75f42SSarah Sharp  * Modify the endpoint context state, submit a configure endpoint command,
35798df75f42SSarah Sharp  * and free all endpoint rings for streams if that completes successfully.
35808df75f42SSarah Sharp  */
xhci_free_streams(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint ** eps,unsigned int num_eps,gfp_t mem_flags)35813969384cSLu Baolu static int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
35828df75f42SSarah Sharp 		struct usb_host_endpoint **eps, unsigned int num_eps,
35838df75f42SSarah Sharp 		gfp_t mem_flags)
35848df75f42SSarah Sharp {
35858df75f42SSarah Sharp 	int i, ret;
35868df75f42SSarah Sharp 	struct xhci_hcd *xhci;
35878df75f42SSarah Sharp 	struct xhci_virt_device *vdev;
35888df75f42SSarah Sharp 	struct xhci_command *command;
358992f8e767SSarah Sharp 	struct xhci_input_control_ctx *ctrl_ctx;
35908df75f42SSarah Sharp 	unsigned int ep_index;
35918df75f42SSarah Sharp 	unsigned long flags;
35928df75f42SSarah Sharp 	u32 changed_ep_bitmask;
35938df75f42SSarah Sharp 
35948df75f42SSarah Sharp 	xhci = hcd_to_xhci(hcd);
35958df75f42SSarah Sharp 	vdev = xhci->devs[udev->slot_id];
35968df75f42SSarah Sharp 
35978df75f42SSarah Sharp 	/* Set up a configure endpoint command to remove the streams rings */
35988df75f42SSarah Sharp 	spin_lock_irqsave(&xhci->lock, flags);
35998df75f42SSarah Sharp 	changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
36008df75f42SSarah Sharp 			udev, eps, num_eps);
36018df75f42SSarah Sharp 	if (changed_ep_bitmask == 0) {
36028df75f42SSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
36038df75f42SSarah Sharp 		return -EINVAL;
36048df75f42SSarah Sharp 	}
36058df75f42SSarah Sharp 
36068df75f42SSarah Sharp 	/* Use the xhci_command structure from the first endpoint.  We may have
36078df75f42SSarah Sharp 	 * allocated too many, but the driver may call xhci_free_streams() for
36088df75f42SSarah Sharp 	 * each endpoint it grouped into one call to xhci_alloc_streams().
36098df75f42SSarah Sharp 	 */
36108df75f42SSarah Sharp 	ep_index = xhci_get_endpoint_index(&eps[0]->desc);
36118df75f42SSarah Sharp 	command = vdev->eps[ep_index].stream_info->free_streams_command;
36124daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
361392f8e767SSarah Sharp 	if (!ctrl_ctx) {
36141f21569cSEmil Goode 		spin_unlock_irqrestore(&xhci->lock, flags);
361592f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
361692f8e767SSarah Sharp 				__func__);
361792f8e767SSarah Sharp 		return -EINVAL;
361892f8e767SSarah Sharp 	}
361992f8e767SSarah Sharp 
36208df75f42SSarah Sharp 	for (i = 0; i < num_eps; i++) {
36218df75f42SSarah Sharp 		struct xhci_ep_ctx *ep_ctx;
36228df75f42SSarah Sharp 
36238df75f42SSarah Sharp 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
36248df75f42SSarah Sharp 		ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
36258df75f42SSarah Sharp 		xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
36268df75f42SSarah Sharp 			EP_GETTING_NO_STREAMS;
36278df75f42SSarah Sharp 
36288df75f42SSarah Sharp 		xhci_endpoint_copy(xhci, command->in_ctx,
36298df75f42SSarah Sharp 				vdev->out_ctx, ep_index);
36304daf9df5SLin Wang 		xhci_setup_no_streams_ep_input_ctx(ep_ctx,
36318df75f42SSarah Sharp 				&vdev->eps[ep_index]);
36328df75f42SSarah Sharp 	}
36338df75f42SSarah Sharp 	xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
363492f8e767SSarah Sharp 			vdev->out_ctx, ctrl_ctx,
363592f8e767SSarah Sharp 			changed_ep_bitmask, changed_ep_bitmask);
36368df75f42SSarah Sharp 	spin_unlock_irqrestore(&xhci->lock, flags);
36378df75f42SSarah Sharp 
36388df75f42SSarah Sharp 	/* Issue and wait for the configure endpoint command,
36398df75f42SSarah Sharp 	 * which must succeed.
36408df75f42SSarah Sharp 	 */
36418df75f42SSarah Sharp 	ret = xhci_configure_endpoint(xhci, udev, command,
36428df75f42SSarah Sharp 			false, true);
36438df75f42SSarah Sharp 
36448df75f42SSarah Sharp 	/* xHC rejected the configure endpoint command for some reason, so we
36458df75f42SSarah Sharp 	 * leave the streams rings intact.
36468df75f42SSarah Sharp 	 */
36478df75f42SSarah Sharp 	if (ret < 0)
36488df75f42SSarah Sharp 		return ret;
36498df75f42SSarah Sharp 
36508df75f42SSarah Sharp 	spin_lock_irqsave(&xhci->lock, flags);
36518df75f42SSarah Sharp 	for (i = 0; i < num_eps; i++) {
36528df75f42SSarah Sharp 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
36538df75f42SSarah Sharp 		xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
36548a007748SSarah Sharp 		vdev->eps[ep_index].stream_info = NULL;
36558df75f42SSarah Sharp 		/* FIXME Unset maxPstreams in endpoint context and
36568df75f42SSarah Sharp 		 * update deq ptr to point to normal string ring.
36578df75f42SSarah Sharp 		 */
36588df75f42SSarah Sharp 		vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
36598df75f42SSarah Sharp 		vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
36608df75f42SSarah Sharp 	}
36618df75f42SSarah Sharp 	spin_unlock_irqrestore(&xhci->lock, flags);
36628df75f42SSarah Sharp 
36638df75f42SSarah Sharp 	return 0;
36648df75f42SSarah Sharp }
36658df75f42SSarah Sharp 
3666bc75fa38SAlex Chiang /*
36672cf95c18SSarah Sharp  * Deletes endpoint resources for endpoints that were active before a Reset
36682cf95c18SSarah Sharp  * Device command, or a Disable Slot command.  The Reset Device command leaves
36692cf95c18SSarah Sharp  * the control endpoint intact, whereas the Disable Slot command deletes it.
36702cf95c18SSarah Sharp  *
36712cf95c18SSarah Sharp  * Must be called with xhci->lock held.
36722cf95c18SSarah Sharp  */
xhci_free_device_endpoint_resources(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,bool drop_control_ep)36732cf95c18SSarah Sharp void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
36742cf95c18SSarah Sharp 	struct xhci_virt_device *virt_dev, bool drop_control_ep)
36752cf95c18SSarah Sharp {
36762cf95c18SSarah Sharp 	int i;
36772cf95c18SSarah Sharp 	unsigned int num_dropped_eps = 0;
36782cf95c18SSarah Sharp 	unsigned int drop_flags = 0;
36792cf95c18SSarah Sharp 
36802cf95c18SSarah Sharp 	for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
36812cf95c18SSarah Sharp 		if (virt_dev->eps[i].ring) {
36822cf95c18SSarah Sharp 			drop_flags |= 1 << i;
36832cf95c18SSarah Sharp 			num_dropped_eps++;
36842cf95c18SSarah Sharp 		}
36852cf95c18SSarah Sharp 	}
36862cf95c18SSarah Sharp 	xhci->num_active_eps -= num_dropped_eps;
36872cf95c18SSarah Sharp 	if (num_dropped_eps)
36884bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
36894bdfe4c3SXenia Ragiadakou 				"Dropped %u ep ctxs, flags = 0x%x, "
36904bdfe4c3SXenia Ragiadakou 				"%u now active.",
36912cf95c18SSarah Sharp 				num_dropped_eps, drop_flags,
36922cf95c18SSarah Sharp 				xhci->num_active_eps);
36932cf95c18SSarah Sharp }
36942cf95c18SSarah Sharp 
36952cf95c18SSarah Sharp /*
3696bc75fa38SAlex Chiang  * This submits a Reset Device Command, which will set the device state to 0,
3697bc75fa38SAlex Chiang  * set the device address to 0, and disable all the endpoints except the default
3698bc75fa38SAlex Chiang  * control endpoint.  The USB core should come back and call
3699bc75fa38SAlex Chiang  * xhci_address_device(), and then re-set up the configuration.  If this is
3700bc75fa38SAlex Chiang  * called because of a usb_reset_and_verify_device(), then the old alternate
3701bc75fa38SAlex Chiang  * settings will be re-installed through the normal bandwidth allocation
3702bc75fa38SAlex Chiang  * functions.
3703bc75fa38SAlex Chiang  *
3704bc75fa38SAlex Chiang  * Wait for the Reset Device command to finish.  Remove all structures
3705bc75fa38SAlex Chiang  * associated with the endpoints that were disabled.  Clear the input device
3706c5628a2aSMathias Nyman  * structure? Reset the control endpoint 0 max packet size?
3707f0615c45SAndiry Xu  *
3708f0615c45SAndiry Xu  * If the virt_dev to be reset does not exist or does not match the udev,
3709f0615c45SAndiry Xu  * it means the device is lost, possibly due to the xHC restore error and
3710f0615c45SAndiry Xu  * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3711f0615c45SAndiry Xu  * re-allocate the device.
3712bc75fa38SAlex Chiang  */
xhci_discover_or_reset_device(struct usb_hcd * hcd,struct usb_device * udev)37133969384cSLu Baolu static int xhci_discover_or_reset_device(struct usb_hcd *hcd,
37143969384cSLu Baolu 		struct usb_device *udev)
3715bc75fa38SAlex Chiang {
3716bc75fa38SAlex Chiang 	int ret, i;
3717bc75fa38SAlex Chiang 	unsigned long flags;
3718bc75fa38SAlex Chiang 	struct xhci_hcd *xhci;
3719bc75fa38SAlex Chiang 	unsigned int slot_id;
3720bc75fa38SAlex Chiang 	struct xhci_virt_device *virt_dev;
3721bc75fa38SAlex Chiang 	struct xhci_command *reset_device_cmd;
3722001fd382SMaarten Lankhorst 	struct xhci_slot_ctx *slot_ctx;
37232e27980eSSarah Sharp 	int old_active_eps = 0;
3724bc75fa38SAlex Chiang 
3725f0615c45SAndiry Xu 	ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3726bc75fa38SAlex Chiang 	if (ret <= 0)
3727bc75fa38SAlex Chiang 		return ret;
3728bc75fa38SAlex Chiang 	xhci = hcd_to_xhci(hcd);
3729bc75fa38SAlex Chiang 	slot_id = udev->slot_id;
3730bc75fa38SAlex Chiang 	virt_dev = xhci->devs[slot_id];
3731f0615c45SAndiry Xu 	if (!virt_dev) {
3732f0615c45SAndiry Xu 		xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3733f0615c45SAndiry Xu 				"not exist. Re-allocate the device\n", slot_id);
3734f0615c45SAndiry Xu 		ret = xhci_alloc_dev(hcd, udev);
3735f0615c45SAndiry Xu 		if (ret == 1)
3736f0615c45SAndiry Xu 			return 0;
3737f0615c45SAndiry Xu 		else
3738f0615c45SAndiry Xu 			return -EINVAL;
3739f0615c45SAndiry Xu 	}
3740f0615c45SAndiry Xu 
3741326124a0SBrian Campbell 	if (virt_dev->tt_info)
3742326124a0SBrian Campbell 		old_active_eps = virt_dev->tt_info->active_eps;
3743326124a0SBrian Campbell 
3744f0615c45SAndiry Xu 	if (virt_dev->udev != udev) {
3745f0615c45SAndiry Xu 		/* If the virt_dev and the udev does not match, this virt_dev
3746f0615c45SAndiry Xu 		 * may belong to another udev.
3747f0615c45SAndiry Xu 		 * Re-allocate the device.
3748f0615c45SAndiry Xu 		 */
3749f0615c45SAndiry Xu 		xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3750f0615c45SAndiry Xu 				"not match the udev. Re-allocate the device\n",
3751f0615c45SAndiry Xu 				slot_id);
3752f0615c45SAndiry Xu 		ret = xhci_alloc_dev(hcd, udev);
3753f0615c45SAndiry Xu 		if (ret == 1)
3754f0615c45SAndiry Xu 			return 0;
3755f0615c45SAndiry Xu 		else
3756f0615c45SAndiry Xu 			return -EINVAL;
3757f0615c45SAndiry Xu 	}
3758bc75fa38SAlex Chiang 
3759001fd382SMaarten Lankhorst 	/* If device is not setup, there is no point in resetting it */
3760001fd382SMaarten Lankhorst 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3761001fd382SMaarten Lankhorst 	if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3762001fd382SMaarten Lankhorst 						SLOT_STATE_DISABLED)
3763001fd382SMaarten Lankhorst 		return 0;
3764001fd382SMaarten Lankhorst 
376519a7d0d6SFelipe Balbi 	trace_xhci_discover_or_reset_device(slot_ctx);
376619a7d0d6SFelipe Balbi 
3767bc75fa38SAlex Chiang 	xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3768bc75fa38SAlex Chiang 	/* Allocate the command structure that holds the struct completion.
3769bc75fa38SAlex Chiang 	 * Assume we're in process context, since the normal device reset
3770bc75fa38SAlex Chiang 	 * process has to wait for the device anyway.  Storage devices are
3771bc75fa38SAlex Chiang 	 * reset as part of error handling, so use GFP_NOIO instead of
3772bc75fa38SAlex Chiang 	 * GFP_KERNEL.
3773bc75fa38SAlex Chiang 	 */
3774103afda0SMathias Nyman 	reset_device_cmd = xhci_alloc_command(xhci, true, GFP_NOIO);
3775bc75fa38SAlex Chiang 	if (!reset_device_cmd) {
3776bc75fa38SAlex Chiang 		xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3777bc75fa38SAlex Chiang 		return -ENOMEM;
3778bc75fa38SAlex Chiang 	}
3779bc75fa38SAlex Chiang 
3780bc75fa38SAlex Chiang 	/* Attempt to submit the Reset Device command to the command ring */
3781bc75fa38SAlex Chiang 	spin_lock_irqsave(&xhci->lock, flags);
37827a3783efSPaul Zimmerman 
3783ddba5cd0SMathias Nyman 	ret = xhci_queue_reset_device(xhci, reset_device_cmd, slot_id);
3784bc75fa38SAlex Chiang 	if (ret) {
3785bc75fa38SAlex Chiang 		xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3786bc75fa38SAlex Chiang 		spin_unlock_irqrestore(&xhci->lock, flags);
3787bc75fa38SAlex Chiang 		goto command_cleanup;
3788bc75fa38SAlex Chiang 	}
3789bc75fa38SAlex Chiang 	xhci_ring_cmd_db(xhci);
3790bc75fa38SAlex Chiang 	spin_unlock_irqrestore(&xhci->lock, flags);
3791bc75fa38SAlex Chiang 
3792bc75fa38SAlex Chiang 	/* Wait for the Reset Device command to finish */
3793c311e391SMathias Nyman 	wait_for_completion(reset_device_cmd->completion);
3794bc75fa38SAlex Chiang 
3795bc75fa38SAlex Chiang 	/* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3796bc75fa38SAlex Chiang 	 * unless we tried to reset a slot ID that wasn't enabled,
3797bc75fa38SAlex Chiang 	 * or the device wasn't in the addressed or configured state.
3798bc75fa38SAlex Chiang 	 */
3799bc75fa38SAlex Chiang 	ret = reset_device_cmd->status;
3800bc75fa38SAlex Chiang 	switch (ret) {
38010b7c105aSFelipe Balbi 	case COMP_COMMAND_ABORTED:
3802604d02a2SMathias Nyman 	case COMP_COMMAND_RING_STOPPED:
3803c311e391SMathias Nyman 		xhci_warn(xhci, "Timeout waiting for reset device command\n");
3804c311e391SMathias Nyman 		ret = -ETIME;
3805c311e391SMathias Nyman 		goto command_cleanup;
38060b7c105aSFelipe Balbi 	case COMP_SLOT_NOT_ENABLED_ERROR: /* 0.95 completion for bad slot ID */
38070b7c105aSFelipe Balbi 	case COMP_CONTEXT_STATE_ERROR: /* 0.96 completion code for same thing */
380838a532a6SXenia Ragiadakou 		xhci_dbg(xhci, "Can't reset device (slot ID %u) in %s state\n",
3809bc75fa38SAlex Chiang 				slot_id,
3810bc75fa38SAlex Chiang 				xhci_get_slot_state(xhci, virt_dev->out_ctx));
381138a532a6SXenia Ragiadakou 		xhci_dbg(xhci, "Not freeing device rings.\n");
3812bc75fa38SAlex Chiang 		/* Don't treat this as an error.  May change my mind later. */
3813bc75fa38SAlex Chiang 		ret = 0;
3814bc75fa38SAlex Chiang 		goto command_cleanup;
3815bc75fa38SAlex Chiang 	case COMP_SUCCESS:
3816bc75fa38SAlex Chiang 		xhci_dbg(xhci, "Successful reset device command.\n");
3817bc75fa38SAlex Chiang 		break;
3818bc75fa38SAlex Chiang 	default:
3819bc75fa38SAlex Chiang 		if (xhci_is_vendor_info_code(xhci, ret))
3820bc75fa38SAlex Chiang 			break;
3821bc75fa38SAlex Chiang 		xhci_warn(xhci, "Unknown completion code %u for "
3822bc75fa38SAlex Chiang 				"reset device command.\n", ret);
3823bc75fa38SAlex Chiang 		ret = -EINVAL;
3824bc75fa38SAlex Chiang 		goto command_cleanup;
3825bc75fa38SAlex Chiang 	}
3826bc75fa38SAlex Chiang 
38272cf95c18SSarah Sharp 	/* Free up host controller endpoint resources */
38282cf95c18SSarah Sharp 	if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
38292cf95c18SSarah Sharp 		spin_lock_irqsave(&xhci->lock, flags);
38302cf95c18SSarah Sharp 		/* Don't delete the default control endpoint resources */
38312cf95c18SSarah Sharp 		xhci_free_device_endpoint_resources(xhci, virt_dev, false);
38322cf95c18SSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
38332cf95c18SSarah Sharp 	}
38342cf95c18SSarah Sharp 
3835c5628a2aSMathias Nyman 	/* Everything but endpoint 0 is disabled, so free the rings. */
383698871e94SFelipe Balbi 	for (i = 1; i < 31; i++) {
38372dea75d9SDmitry Torokhov 		struct xhci_virt_ep *ep = &virt_dev->eps[i];
38382dea75d9SDmitry Torokhov 
38392dea75d9SDmitry Torokhov 		if (ep->ep_state & EP_HAS_STREAMS) {
3840df613834SHans de Goede 			xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
3841df613834SHans de Goede 					xhci_get_endpoint_address(i));
38422dea75d9SDmitry Torokhov 			xhci_free_stream_info(xhci, ep->stream_info);
38432dea75d9SDmitry Torokhov 			ep->stream_info = NULL;
38442dea75d9SDmitry Torokhov 			ep->ep_state &= ~EP_HAS_STREAMS;
38452dea75d9SDmitry Torokhov 		}
38462dea75d9SDmitry Torokhov 
38472dea75d9SDmitry Torokhov 		if (ep->ring) {
384802b6fdc2SLu Baolu 			xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
3849c5628a2aSMathias Nyman 			xhci_free_endpoint_ring(xhci, virt_dev, i);
3850bc75fa38SAlex Chiang 		}
38512e27980eSSarah Sharp 		if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
38522e27980eSSarah Sharp 			xhci_drop_ep_from_interval_table(xhci,
38532e27980eSSarah Sharp 					&virt_dev->eps[i].bw_info,
38542e27980eSSarah Sharp 					virt_dev->bw_table,
38552e27980eSSarah Sharp 					udev,
38562e27980eSSarah Sharp 					&virt_dev->eps[i],
38572e27980eSSarah Sharp 					virt_dev->tt_info);
38589af5d71dSSarah Sharp 		xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
38592dea75d9SDmitry Torokhov 	}
38602e27980eSSarah Sharp 	/* If necessary, update the number of active TTs on this root port */
38612e27980eSSarah Sharp 	xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
3862b8c3b718SMathias Nyman 	virt_dev->flags = 0;
3863bc75fa38SAlex Chiang 	ret = 0;
3864bc75fa38SAlex Chiang 
3865bc75fa38SAlex Chiang command_cleanup:
3866bc75fa38SAlex Chiang 	xhci_free_command(xhci, reset_device_cmd);
3867bc75fa38SAlex Chiang 	return ret;
3868bc75fa38SAlex Chiang }
3869bc75fa38SAlex Chiang 
3870bc75fa38SAlex Chiang /*
3871bc75fa38SAlex Chiang  * At this point, the struct usb_device is about to go away, the device has
3872bc75fa38SAlex Chiang  * disconnected, and all traffic has been stopped and the endpoints have been
3873bc75fa38SAlex Chiang  * disabled.  Free any HC data structures associated with that device.
3874bc75fa38SAlex Chiang  */
xhci_free_dev(struct usb_hcd * hcd,struct usb_device * udev)38753969384cSLu Baolu static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3876bc75fa38SAlex Chiang {
3877bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3878bc75fa38SAlex Chiang 	struct xhci_virt_device *virt_dev;
387919a7d0d6SFelipe Balbi 	struct xhci_slot_ctx *slot_ctx;
3880a2bc47c4SMathias Nyman 	unsigned long flags;
388164927730SAndiry Xu 	int i, ret;
3882ddba5cd0SMathias Nyman 
3883c8476fb8SShawn Nematbakhsh 	/*
3884c8476fb8SShawn Nematbakhsh 	 * We called pm_runtime_get_noresume when the device was attached.
3885c8476fb8SShawn Nematbakhsh 	 * Decrement the counter here to allow controller to runtime suspend
3886c8476fb8SShawn Nematbakhsh 	 * if no devices remain.
3887c8476fb8SShawn Nematbakhsh 	 */
3888c8476fb8SShawn Nematbakhsh 	if (xhci->quirks & XHCI_RESET_ON_RESUME)
3889e7ecf069SSarah Sharp 		pm_runtime_put_noidle(hcd->self.controller);
3890c8476fb8SShawn Nematbakhsh 
389164927730SAndiry Xu 	ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
38927bd89b40SSarah Sharp 	/* If the host is halted due to driver unload, we still need to free the
38937bd89b40SSarah Sharp 	 * device.
38947bd89b40SSarah Sharp 	 */
3895cd3f1790SLu Baolu 	if (ret <= 0 && ret != -ENODEV)
3896bc75fa38SAlex Chiang 		return;
389764927730SAndiry Xu 
3898bc75fa38SAlex Chiang 	virt_dev = xhci->devs[udev->slot_id];
389919a7d0d6SFelipe Balbi 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
390019a7d0d6SFelipe Balbi 	trace_xhci_free_dev(slot_ctx);
3901bc75fa38SAlex Chiang 
3902bc75fa38SAlex Chiang 	/* Stop any wayward timer functions (which may grab the lock) */
390325355e04SMathias Nyman 	for (i = 0; i < 31; i++)
39049983a5fcSMathias Nyman 		virt_dev->eps[i].ep_state &= ~EP_STOP_CMD_PENDING;
390544a182b9SMathias Nyman 	virt_dev->udev = NULL;
39067faac195SMathias Nyman 	xhci_disable_slot(xhci, udev->slot_id);
3907a2bc47c4SMathias Nyman 
3908a2bc47c4SMathias Nyman 	spin_lock_irqsave(&xhci->lock, flags);
390911ec7588SLu Baolu 	xhci_free_virt_device(xhci, udev->slot_id);
3910a2bc47c4SMathias Nyman 	spin_unlock_irqrestore(&xhci->lock, flags);
3911a2bc47c4SMathias Nyman 
3912f9e609b8SGuoqing Zhang }
3913f9e609b8SGuoqing Zhang 
xhci_disable_slot(struct xhci_hcd * xhci,u32 slot_id)3914cd3f1790SLu Baolu int xhci_disable_slot(struct xhci_hcd *xhci, u32 slot_id)
3915f9e609b8SGuoqing Zhang {
3916cd3f1790SLu Baolu 	struct xhci_command *command;
3917f9e609b8SGuoqing Zhang 	unsigned long flags;
3918f9e609b8SGuoqing Zhang 	u32 state;
391998d107b8SLinyu Yuan 	int ret;
3920f9e609b8SGuoqing Zhang 
39217faac195SMathias Nyman 	command = xhci_alloc_command(xhci, true, GFP_KERNEL);
3922f9e609b8SGuoqing Zhang 	if (!command)
3923f9e609b8SGuoqing Zhang 		return -ENOMEM;
3924f9e609b8SGuoqing Zhang 
39259334367cSIkjoon Jang 	xhci_debugfs_remove_slot(xhci, slot_id);
39269334367cSIkjoon Jang 
3927bc75fa38SAlex Chiang 	spin_lock_irqsave(&xhci->lock, flags);
3928bc75fa38SAlex Chiang 	/* Don't disable the slot if the host controller is dead. */
3929b0ba9720SXenia Ragiadakou 	state = readl(&xhci->op_regs->status);
39307bd89b40SSarah Sharp 	if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
39317bd89b40SSarah Sharp 			(xhci->xhc_state & XHCI_STATE_HALTED)) {
3932bc75fa38SAlex Chiang 		spin_unlock_irqrestore(&xhci->lock, flags);
3933ddba5cd0SMathias Nyman 		kfree(command);
3934dcabc76fSLu Baolu 		return -ENODEV;
3935bc75fa38SAlex Chiang 	}
3936bc75fa38SAlex Chiang 
3937f9e609b8SGuoqing Zhang 	ret = xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
3938f9e609b8SGuoqing Zhang 				slot_id);
3939f9e609b8SGuoqing Zhang 	if (ret) {
3940bc75fa38SAlex Chiang 		spin_unlock_irqrestore(&xhci->lock, flags);
3941cd3f1790SLu Baolu 		kfree(command);
3942f9e609b8SGuoqing Zhang 		return ret;
3943bc75fa38SAlex Chiang 	}
3944bc75fa38SAlex Chiang 	xhci_ring_cmd_db(xhci);
3945bc75fa38SAlex Chiang 	spin_unlock_irqrestore(&xhci->lock, flags);
39467faac195SMathias Nyman 
39477faac195SMathias Nyman 	wait_for_completion(command->completion);
39487faac195SMathias Nyman 
39497faac195SMathias Nyman 	if (command->status != COMP_SUCCESS)
39507faac195SMathias Nyman 		xhci_warn(xhci, "Unsuccessful disable slot %u command, status %d\n",
39517faac195SMathias Nyman 			  slot_id, command->status);
39527faac195SMathias Nyman 
39537faac195SMathias Nyman 	xhci_free_command(xhci, command);
39547faac195SMathias Nyman 
395598d107b8SLinyu Yuan 	return 0;
3956bc75fa38SAlex Chiang }
3957bc75fa38SAlex Chiang 
3958bc75fa38SAlex Chiang /*
39592cf95c18SSarah Sharp  * Checks if we have enough host controller resources for the default control
39602cf95c18SSarah Sharp  * endpoint.
39612cf95c18SSarah Sharp  *
39622cf95c18SSarah Sharp  * Must be called with xhci->lock held.
39632cf95c18SSarah Sharp  */
xhci_reserve_host_control_ep_resources(struct xhci_hcd * xhci)39642cf95c18SSarah Sharp static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
39652cf95c18SSarah Sharp {
39662cf95c18SSarah Sharp 	if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
39674bdfe4c3SXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
39684bdfe4c3SXenia Ragiadakou 				"Not enough ep ctxs: "
39694bdfe4c3SXenia Ragiadakou 				"%u active, need to add 1, limit is %u.",
39702cf95c18SSarah Sharp 				xhci->num_active_eps, xhci->limit_active_eps);
39712cf95c18SSarah Sharp 		return -ENOMEM;
39722cf95c18SSarah Sharp 	}
39732cf95c18SSarah Sharp 	xhci->num_active_eps += 1;
39744bdfe4c3SXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
39754bdfe4c3SXenia Ragiadakou 			"Adding 1 ep ctx, %u now active.",
39762cf95c18SSarah Sharp 			xhci->num_active_eps);
39772cf95c18SSarah Sharp 	return 0;
39782cf95c18SSarah Sharp }
39792cf95c18SSarah Sharp 
39802cf95c18SSarah Sharp 
39812cf95c18SSarah Sharp /*
3982bc75fa38SAlex Chiang  * Returns 0 if the xHC ran out of device slots, the Enable Slot command
3983bc75fa38SAlex Chiang  * timed out, or allocating memory failed.  Returns 1 on success.
3984bc75fa38SAlex Chiang  */
xhci_alloc_dev(struct usb_hcd * hcd,struct usb_device * udev)3985bc75fa38SAlex Chiang int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
3986bc75fa38SAlex Chiang {
3987bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
398819a7d0d6SFelipe Balbi 	struct xhci_virt_device *vdev;
398919a7d0d6SFelipe Balbi 	struct xhci_slot_ctx *slot_ctx;
3990bc75fa38SAlex Chiang 	unsigned long flags;
3991a00918d0SChris Bainbridge 	int ret, slot_id;
3992ddba5cd0SMathias Nyman 	struct xhci_command *command;
3993ddba5cd0SMathias Nyman 
3994103afda0SMathias Nyman 	command = xhci_alloc_command(xhci, true, GFP_KERNEL);
3995ddba5cd0SMathias Nyman 	if (!command)
3996ddba5cd0SMathias Nyman 		return 0;
3997bc75fa38SAlex Chiang 
3998bc75fa38SAlex Chiang 	spin_lock_irqsave(&xhci->lock, flags);
3999ddba5cd0SMathias Nyman 	ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
4000bc75fa38SAlex Chiang 	if (ret) {
4001bc75fa38SAlex Chiang 		spin_unlock_irqrestore(&xhci->lock, flags);
4002bc75fa38SAlex Chiang 		xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
400387e44f2aSLu Baolu 		xhci_free_command(xhci, command);
4004bc75fa38SAlex Chiang 		return 0;
4005bc75fa38SAlex Chiang 	}
4006bc75fa38SAlex Chiang 	xhci_ring_cmd_db(xhci);
4007bc75fa38SAlex Chiang 	spin_unlock_irqrestore(&xhci->lock, flags);
4008bc75fa38SAlex Chiang 
4009c311e391SMathias Nyman 	wait_for_completion(command->completion);
4010c2d3d49bSLu Baolu 	slot_id = command->slot_id;
4011bc75fa38SAlex Chiang 
4012a00918d0SChris Bainbridge 	if (!slot_id || command->status != COMP_SUCCESS) {
4013e11487f1SMathias Nyman 		xhci_err(xhci, "Error while assigning device slot ID: %s\n",
4014e11487f1SMathias Nyman 			 xhci_trb_comp_code_string(command->status));
4015be982038SSarah Sharp 		xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
4016be982038SSarah Sharp 				HCS_MAX_SLOTS(
4017be982038SSarah Sharp 					readl(&xhci->cap_regs->hcs_params1)));
401887e44f2aSLu Baolu 		xhci_free_command(xhci, command);
4019bc75fa38SAlex Chiang 		return 0;
4020bc75fa38SAlex Chiang 	}
40212cf95c18SSarah Sharp 
4022cd3f1790SLu Baolu 	xhci_free_command(xhci, command);
4023cd3f1790SLu Baolu 
40242cf95c18SSarah Sharp 	if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
40252cf95c18SSarah Sharp 		spin_lock_irqsave(&xhci->lock, flags);
40262cf95c18SSarah Sharp 		ret = xhci_reserve_host_control_ep_resources(xhci);
40272cf95c18SSarah Sharp 		if (ret) {
40282cf95c18SSarah Sharp 			spin_unlock_irqrestore(&xhci->lock, flags);
40292cf95c18SSarah Sharp 			xhci_warn(xhci, "Not enough host resources, "
40302cf95c18SSarah Sharp 					"active endpoint contexts = %u\n",
40312cf95c18SSarah Sharp 					xhci->num_active_eps);
40322cf95c18SSarah Sharp 			goto disable_slot;
40332cf95c18SSarah Sharp 		}
40342cf95c18SSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
40352cf95c18SSarah Sharp 	}
40362cf95c18SSarah Sharp 	/* Use GFP_NOIO, since this function can be called from
4037a6d940ddSSarah Sharp 	 * xhci_discover_or_reset_device(), which may be called as part of
4038a6d940ddSSarah Sharp 	 * mass storage driver error handling.
4039a6d940ddSSarah Sharp 	 */
4040a00918d0SChris Bainbridge 	if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) {
4041bc75fa38SAlex Chiang 		xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
40422cf95c18SSarah Sharp 		goto disable_slot;
4043bc75fa38SAlex Chiang 	}
404419a7d0d6SFelipe Balbi 	vdev = xhci->devs[slot_id];
404519a7d0d6SFelipe Balbi 	slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
404619a7d0d6SFelipe Balbi 	trace_xhci_alloc_dev(slot_ctx);
404719a7d0d6SFelipe Balbi 
4048a00918d0SChris Bainbridge 	udev->slot_id = slot_id;
4049c8476fb8SShawn Nematbakhsh 
405002b6fdc2SLu Baolu 	xhci_debugfs_create_slot(xhci, slot_id);
405102b6fdc2SLu Baolu 
4052c8476fb8SShawn Nematbakhsh 	/*
4053c8476fb8SShawn Nematbakhsh 	 * If resetting upon resume, we can't put the controller into runtime
4054c8476fb8SShawn Nematbakhsh 	 * suspend if there is a device attached.
4055c8476fb8SShawn Nematbakhsh 	 */
4056c8476fb8SShawn Nematbakhsh 	if (xhci->quirks & XHCI_RESET_ON_RESUME)
4057e7ecf069SSarah Sharp 		pm_runtime_get_noresume(hcd->self.controller);
4058c8476fb8SShawn Nematbakhsh 
4059bc75fa38SAlex Chiang 	/* Is this a LS or FS device under a HS hub? */
4060bc75fa38SAlex Chiang 	/* Hub or peripherial? */
4061bc75fa38SAlex Chiang 	return 1;
40622cf95c18SSarah Sharp 
40632cf95c18SSarah Sharp disable_slot:
40647faac195SMathias Nyman 	xhci_disable_slot(xhci, udev->slot_id);
406511ec7588SLu Baolu 	xhci_free_virt_device(xhci, udev->slot_id);
406611ec7588SLu Baolu 
406711ec7588SLu Baolu 	return 0;
4068bc75fa38SAlex Chiang }
4069bc75fa38SAlex Chiang 
4070a769154cSHardik Gajjar /**
4071a769154cSHardik Gajjar  * xhci_setup_device - issues an Address Device command to assign a unique
4072a769154cSHardik Gajjar  *			USB bus address.
4073a769154cSHardik Gajjar  * @hcd: USB host controller data structure.
4074a769154cSHardik Gajjar  * @udev: USB dev structure representing the connected device.
4075a769154cSHardik Gajjar  * @setup: Enum specifying setup mode: address only or with context.
4076a769154cSHardik Gajjar  * @timeout_ms: Max wait time (ms) for the command operation to complete.
4077a769154cSHardik Gajjar  *
4078a769154cSHardik Gajjar  * Return: 0 if successful; otherwise, negative error code.
4079bc75fa38SAlex Chiang  */
xhci_setup_device(struct usb_hcd * hcd,struct usb_device * udev,enum xhci_setup_dev setup,unsigned int timeout_ms)408048fc7dbdSDan Williams static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
4081a769154cSHardik Gajjar 			     enum xhci_setup_dev setup, unsigned int timeout_ms)
4082bc75fa38SAlex Chiang {
40836f8ffc0bSDan Williams 	const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
4084bc75fa38SAlex Chiang 	unsigned long flags;
4085bc75fa38SAlex Chiang 	struct xhci_virt_device *virt_dev;
4086bc75fa38SAlex Chiang 	int ret = 0;
4087bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4088bc75fa38SAlex Chiang 	struct xhci_slot_ctx *slot_ctx;
4089bc75fa38SAlex Chiang 	struct xhci_input_control_ctx *ctrl_ctx;
4090bc75fa38SAlex Chiang 	u64 temp_64;
4091a00918d0SChris Bainbridge 	struct xhci_command *command = NULL;
4092a00918d0SChris Bainbridge 
4093a00918d0SChris Bainbridge 	mutex_lock(&xhci->mutex);
4094bc75fa38SAlex Chiang 
409590797aeeSLu Baolu 	if (xhci->xhc_state) {	/* dying, removing or halted */
409690797aeeSLu Baolu 		ret = -ESHUTDOWN;
4097448116bfSRoger Quadros 		goto out;
409890797aeeSLu Baolu 	}
4099448116bfSRoger Quadros 
4100bc75fa38SAlex Chiang 	if (!udev->slot_id) {
410184a99f6fSXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_address,
410284a99f6fSXenia Ragiadakou 				"Bad Slot ID %d", udev->slot_id);
4103a00918d0SChris Bainbridge 		ret = -EINVAL;
4104a00918d0SChris Bainbridge 		goto out;
4105bc75fa38SAlex Chiang 	}
4106bc75fa38SAlex Chiang 
4107bc75fa38SAlex Chiang 	virt_dev = xhci->devs[udev->slot_id];
4108bc75fa38SAlex Chiang 
41097ed603ecSMatt Evans 	if (WARN_ON(!virt_dev)) {
41107ed603ecSMatt Evans 		/*
41117ed603ecSMatt Evans 		 * In plug/unplug torture test with an NEC controller,
41127ed603ecSMatt Evans 		 * a zero-dereference was observed once due to virt_dev = 0.
41137ed603ecSMatt Evans 		 * Print useful debug rather than crash if it is observed again!
41147ed603ecSMatt Evans 		 */
41157ed603ecSMatt Evans 		xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
41167ed603ecSMatt Evans 			udev->slot_id);
4117a00918d0SChris Bainbridge 		ret = -EINVAL;
4118a00918d0SChris Bainbridge 		goto out;
41197ed603ecSMatt Evans 	}
412019a7d0d6SFelipe Balbi 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
412119a7d0d6SFelipe Balbi 	trace_xhci_setup_device_slot(slot_ctx);
41227ed603ecSMatt Evans 
4123f161ead7SMathias Nyman 	if (setup == SETUP_CONTEXT_ONLY) {
4124f161ead7SMathias Nyman 		if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
4125f161ead7SMathias Nyman 		    SLOT_STATE_DEFAULT) {
4126f161ead7SMathias Nyman 			xhci_dbg(xhci, "Slot already in default state\n");
4127a00918d0SChris Bainbridge 			goto out;
4128f161ead7SMathias Nyman 		}
4129f161ead7SMathias Nyman 	}
4130f161ead7SMathias Nyman 
4131103afda0SMathias Nyman 	command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4132a00918d0SChris Bainbridge 	if (!command) {
4133a00918d0SChris Bainbridge 		ret = -ENOMEM;
4134a00918d0SChris Bainbridge 		goto out;
4135a00918d0SChris Bainbridge 	}
4136ddba5cd0SMathias Nyman 
4137ddba5cd0SMathias Nyman 	command->in_ctx = virt_dev->in_ctx;
4138a769154cSHardik Gajjar 	command->timeout_ms = timeout_ms;
4139ddba5cd0SMathias Nyman 
4140f0615c45SAndiry Xu 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
41414daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
414292f8e767SSarah Sharp 	if (!ctrl_ctx) {
414392f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
414492f8e767SSarah Sharp 				__func__);
4145a00918d0SChris Bainbridge 		ret = -EINVAL;
4146a00918d0SChris Bainbridge 		goto out;
414792f8e767SSarah Sharp 	}
4148f0615c45SAndiry Xu 	/*
4149f0615c45SAndiry Xu 	 * If this is the first Set Address since device plug-in or
4150f0615c45SAndiry Xu 	 * virt_device realloaction after a resume with an xHCI power loss,
4151f0615c45SAndiry Xu 	 * then set up the slot context.
4152f0615c45SAndiry Xu 	 */
4153f0615c45SAndiry Xu 	if (!slot_ctx->dev_info)
4154bc75fa38SAlex Chiang 		xhci_setup_addressable_virt_dev(xhci, udev);
4155f0615c45SAndiry Xu 	/* Otherwise, update the control endpoint ring enqueue pointer. */
41562d1ee590SSarah Sharp 	else
41572d1ee590SSarah Sharp 		xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
4158d31c285bSSarah Sharp 	ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
4159d31c285bSSarah Sharp 	ctrl_ctx->drop_flags = 0;
4160d31c285bSSarah Sharp 
41611d27fabeSXenia Ragiadakou 	trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
41620c052aabSXenia Ragiadakou 				le32_to_cpu(slot_ctx->dev_info) >> 27);
4163bc75fa38SAlex Chiang 
416490d6d573SMathias Nyman 	trace_xhci_address_ctrl_ctx(ctrl_ctx);
4165bc75fa38SAlex Chiang 	spin_lock_irqsave(&xhci->lock, flags);
4166a711edeeSFelipe Balbi 	trace_xhci_setup_device(virt_dev);
4167ddba5cd0SMathias Nyman 	ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
416848fc7dbdSDan Williams 					udev->slot_id, setup);
4169bc75fa38SAlex Chiang 	if (ret) {
4170bc75fa38SAlex Chiang 		spin_unlock_irqrestore(&xhci->lock, flags);
417184a99f6fSXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_address,
417284a99f6fSXenia Ragiadakou 				"FIXME: allocate a command ring segment");
4173a00918d0SChris Bainbridge 		goto out;
4174bc75fa38SAlex Chiang 	}
4175bc75fa38SAlex Chiang 	xhci_ring_cmd_db(xhci);
4176bc75fa38SAlex Chiang 	spin_unlock_irqrestore(&xhci->lock, flags);
4177bc75fa38SAlex Chiang 
4178bc75fa38SAlex Chiang 	/* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
4179c311e391SMathias Nyman 	wait_for_completion(command->completion);
4180c311e391SMathias Nyman 
4181bc75fa38SAlex Chiang 	/* FIXME: From section 4.3.4: "Software shall be responsible for timing
4182bc75fa38SAlex Chiang 	 * the SetAddress() "recovery interval" required by USB and aborting the
4183bc75fa38SAlex Chiang 	 * command on a timeout.
4184bc75fa38SAlex Chiang 	 */
41859ea1833eSMathias Nyman 	switch (command->status) {
41860b7c105aSFelipe Balbi 	case COMP_COMMAND_ABORTED:
4187604d02a2SMathias Nyman 	case COMP_COMMAND_RING_STOPPED:
4188c311e391SMathias Nyman 		xhci_warn(xhci, "Timeout while waiting for setup device command\n");
4189c311e391SMathias Nyman 		ret = -ETIME;
4190c311e391SMathias Nyman 		break;
41910b7c105aSFelipe Balbi 	case COMP_CONTEXT_STATE_ERROR:
41920b7c105aSFelipe Balbi 	case COMP_SLOT_NOT_ENABLED_ERROR:
41936f8ffc0bSDan Williams 		xhci_err(xhci, "Setup ERROR: setup %s command for slot %d.\n",
41946f8ffc0bSDan Williams 			 act, udev->slot_id);
4195bc75fa38SAlex Chiang 		ret = -EINVAL;
4196bc75fa38SAlex Chiang 		break;
41970b7c105aSFelipe Balbi 	case COMP_USB_TRANSACTION_ERROR:
41986f8ffc0bSDan Williams 		dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
4199651aaf36SLu Baolu 
4200651aaf36SLu Baolu 		mutex_unlock(&xhci->mutex);
4201651aaf36SLu Baolu 		ret = xhci_disable_slot(xhci, udev->slot_id);
42027faac195SMathias Nyman 		xhci_free_virt_device(xhci, udev->slot_id);
4203af8e119fSMathias Nyman 		if (!ret) {
4204af8e119fSMathias Nyman 			if (xhci_alloc_dev(hcd, udev) == 1)
4205af8e119fSMathias Nyman 				xhci_setup_addressable_virt_dev(xhci, udev);
4206af8e119fSMathias Nyman 		}
4207651aaf36SLu Baolu 		kfree(command->completion);
4208651aaf36SLu Baolu 		kfree(command);
4209651aaf36SLu Baolu 		return -EPROTO;
42100b7c105aSFelipe Balbi 	case COMP_INCOMPATIBLE_DEVICE_ERROR:
42116f8ffc0bSDan Williams 		dev_warn(&udev->dev,
42126f8ffc0bSDan Williams 			 "ERROR: Incompatible device for setup %s command\n", act);
4213f6ba6fe2SAlex He 		ret = -ENODEV;
4214f6ba6fe2SAlex He 		break;
4215bc75fa38SAlex Chiang 	case COMP_SUCCESS:
421684a99f6fSXenia Ragiadakou 		xhci_dbg_trace(xhci, trace_xhci_dbg_address,
42176f8ffc0bSDan Williams 			       "Successful setup %s command", act);
4218bc75fa38SAlex Chiang 		break;
4219bc75fa38SAlex Chiang 	default:
42206f8ffc0bSDan Williams 		xhci_err(xhci,
42216f8ffc0bSDan Williams 			 "ERROR: unexpected setup %s command completion code 0x%x.\n",
42229ea1833eSMathias Nyman 			 act, command->status);
42231d27fabeSXenia Ragiadakou 		trace_xhci_address_ctx(xhci, virt_dev->out_ctx, 1);
4224bc75fa38SAlex Chiang 		ret = -EINVAL;
4225bc75fa38SAlex Chiang 		break;
4226bc75fa38SAlex Chiang 	}
4227a00918d0SChris Bainbridge 	if (ret)
4228a00918d0SChris Bainbridge 		goto out;
4229f7b2e403SSarah Sharp 	temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
423084a99f6fSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_address,
423184a99f6fSXenia Ragiadakou 			"Op regs DCBAA ptr = %#016llx", temp_64);
423284a99f6fSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_address,
423384a99f6fSXenia Ragiadakou 		"Slot ID %d dcbaa entry @%p = %#016llx",
4234bc75fa38SAlex Chiang 		udev->slot_id,
4235bc75fa38SAlex Chiang 		&xhci->dcbaa->dev_context_ptrs[udev->slot_id],
4236bc75fa38SAlex Chiang 		(unsigned long long)
423728ccd296SMatt Evans 		le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
423884a99f6fSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_address,
423984a99f6fSXenia Ragiadakou 			"Output Context DMA address = %#08llx",
4240bc75fa38SAlex Chiang 			(unsigned long long)virt_dev->out_ctx->dma);
42411d27fabeSXenia Ragiadakou 	trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
42420c052aabSXenia Ragiadakou 				le32_to_cpu(slot_ctx->dev_info) >> 27);
4243bc75fa38SAlex Chiang 	/*
4244bc75fa38SAlex Chiang 	 * USB core uses address 1 for the roothubs, so we add one to the
4245bc75fa38SAlex Chiang 	 * address given back to us by the HC.
4246bc75fa38SAlex Chiang 	 */
42471d27fabeSXenia Ragiadakou 	trace_xhci_address_ctx(xhci, virt_dev->out_ctx,
42480c052aabSXenia Ragiadakou 				le32_to_cpu(slot_ctx->dev_info) >> 27);
4249bc75fa38SAlex Chiang 	/* Zero the input context control for later use */
4250bc75fa38SAlex Chiang 	ctrl_ctx->add_flags = 0;
4251bc75fa38SAlex Chiang 	ctrl_ctx->drop_flags = 0;
42524998f1efSJim Lin 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
42534998f1efSJim Lin 	udev->devaddr = (u8)(le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4254bc75fa38SAlex Chiang 
425584a99f6fSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4256a2cdc343SDan Williams 		       "Internal device address = %d",
4257a2cdc343SDan Williams 		       le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4258a00918d0SChris Bainbridge out:
4259a00918d0SChris Bainbridge 	mutex_unlock(&xhci->mutex);
426087e44f2aSLu Baolu 	if (command) {
426187e44f2aSLu Baolu 		kfree(command->completion);
4262ddba5cd0SMathias Nyman 		kfree(command);
426387e44f2aSLu Baolu 	}
4264a00918d0SChris Bainbridge 	return ret;
4265bc75fa38SAlex Chiang }
4266bc75fa38SAlex Chiang 
xhci_address_device(struct usb_hcd * hcd,struct usb_device * udev,unsigned int timeout_ms)4267a769154cSHardik Gajjar static int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev,
4268a769154cSHardik Gajjar 			       unsigned int timeout_ms)
426948fc7dbdSDan Williams {
4270a769154cSHardik Gajjar 	return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ADDRESS, timeout_ms);
427148fc7dbdSDan Williams }
427248fc7dbdSDan Williams 
xhci_enable_device(struct usb_hcd * hcd,struct usb_device * udev)42733969384cSLu Baolu static int xhci_enable_device(struct usb_hcd *hcd, struct usb_device *udev)
427448fc7dbdSDan Williams {
4275a769154cSHardik Gajjar 	return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ONLY,
4276a769154cSHardik Gajjar 				 XHCI_CMD_DEFAULT_TIMEOUT);
427748fc7dbdSDan Williams }
427848fc7dbdSDan Williams 
42793f5eb141SLan Tianyu /*
42803f5eb141SLan Tianyu  * Transfer the port index into real index in the HW port status
42813f5eb141SLan Tianyu  * registers. Caculate offset between the port's PORTSC register
42823f5eb141SLan Tianyu  * and port status base. Divide the number of per port register
42833f5eb141SLan Tianyu  * to get the real index. The raw port number bases 1.
42843f5eb141SLan Tianyu  */
xhci_find_raw_port_number(struct usb_hcd * hcd,int port1)42853f5eb141SLan Tianyu int xhci_find_raw_port_number(struct usb_hcd *hcd, int port1)
42863f5eb141SLan Tianyu {
428738986ffaSMathias Nyman 	struct xhci_hub *rhub;
42883f5eb141SLan Tianyu 
428938986ffaSMathias Nyman 	rhub = xhci_get_rhub(hcd);
429038986ffaSMathias Nyman 	return rhub->ports[port1 - 1]->hw_portnum + 1;
42913f5eb141SLan Tianyu }
42923f5eb141SLan Tianyu 
4293a558ccdcSMathias Nyman /*
4294a558ccdcSMathias Nyman  * Issue an Evaluate Context command to change the Maximum Exit Latency in the
4295a558ccdcSMathias Nyman  * slot context.  If that succeeds, store the new MEL in the xhci_virt_device.
4296a558ccdcSMathias Nyman  */
xhci_change_max_exit_latency(struct xhci_hcd * xhci,struct usb_device * udev,u16 max_exit_latency)4297d5c82febSOlof Johansson static int __maybe_unused xhci_change_max_exit_latency(struct xhci_hcd *xhci,
4298a558ccdcSMathias Nyman 			struct usb_device *udev, u16 max_exit_latency)
4299a558ccdcSMathias Nyman {
4300a558ccdcSMathias Nyman 	struct xhci_virt_device *virt_dev;
4301a558ccdcSMathias Nyman 	struct xhci_command *command;
4302a558ccdcSMathias Nyman 	struct xhci_input_control_ctx *ctrl_ctx;
4303a558ccdcSMathias Nyman 	struct xhci_slot_ctx *slot_ctx;
4304a558ccdcSMathias Nyman 	unsigned long flags;
4305a558ccdcSMathias Nyman 	int ret;
4306a558ccdcSMathias Nyman 
43075c2a380aSMathias Nyman 	command = xhci_alloc_command_with_ctx(xhci, true, GFP_KERNEL);
43085c2a380aSMathias Nyman 	if (!command)
43095c2a380aSMathias Nyman 		return -ENOMEM;
43105c2a380aSMathias Nyman 
4311a558ccdcSMathias Nyman 	spin_lock_irqsave(&xhci->lock, flags);
431296044694SMathias Nyman 
431396044694SMathias Nyman 	virt_dev = xhci->devs[udev->slot_id];
431496044694SMathias Nyman 
431596044694SMathias Nyman 	/*
431696044694SMathias Nyman 	 * virt_dev might not exists yet if xHC resumed from hibernate (S4) and
431796044694SMathias Nyman 	 * xHC was re-initialized. Exit latency will be set later after
431896044694SMathias Nyman 	 * hub_port_finish_reset() is done and xhci->devs[] are re-allocated
431996044694SMathias Nyman 	 */
432096044694SMathias Nyman 
432196044694SMathias Nyman 	if (!virt_dev || max_exit_latency == virt_dev->current_mel) {
4322a558ccdcSMathias Nyman 		spin_unlock_irqrestore(&xhci->lock, flags);
4323f6caea48SMathias Nyman 		xhci_free_command(xhci, command);
4324a558ccdcSMathias Nyman 		return 0;
4325a558ccdcSMathias Nyman 	}
4326a558ccdcSMathias Nyman 
4327a558ccdcSMathias Nyman 	/* Attempt to issue an Evaluate Context command to change the MEL. */
43284daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
432992f8e767SSarah Sharp 	if (!ctrl_ctx) {
433092f8e767SSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
43315c2a380aSMathias Nyman 		xhci_free_command(xhci, command);
433292f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
433392f8e767SSarah Sharp 				__func__);
433492f8e767SSarah Sharp 		return -ENOMEM;
433592f8e767SSarah Sharp 	}
433692f8e767SSarah Sharp 
4337a558ccdcSMathias Nyman 	xhci_slot_copy(xhci, command->in_ctx, virt_dev->out_ctx);
4338a558ccdcSMathias Nyman 	spin_unlock_irqrestore(&xhci->lock, flags);
4339a558ccdcSMathias Nyman 
4340a558ccdcSMathias Nyman 	ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4341a558ccdcSMathias Nyman 	slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
4342a558ccdcSMathias Nyman 	slot_ctx->dev_info2 &= cpu_to_le32(~((u32) MAX_EXIT));
4343a558ccdcSMathias Nyman 	slot_ctx->dev_info2 |= cpu_to_le32(max_exit_latency);
43444801d4eaSMathias Nyman 	slot_ctx->dev_state = 0;
4345a558ccdcSMathias Nyman 
43463a7fa5beSXenia Ragiadakou 	xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
43473a7fa5beSXenia Ragiadakou 			"Set up evaluate context for LPM MEL change.");
4348a558ccdcSMathias Nyman 
4349a558ccdcSMathias Nyman 	/* Issue and wait for the evaluate context command. */
4350a558ccdcSMathias Nyman 	ret = xhci_configure_endpoint(xhci, udev, command,
4351a558ccdcSMathias Nyman 			true, true);
4352a558ccdcSMathias Nyman 
4353a558ccdcSMathias Nyman 	if (!ret) {
4354a558ccdcSMathias Nyman 		spin_lock_irqsave(&xhci->lock, flags);
4355a558ccdcSMathias Nyman 		virt_dev->current_mel = max_exit_latency;
4356a558ccdcSMathias Nyman 		spin_unlock_irqrestore(&xhci->lock, flags);
4357a558ccdcSMathias Nyman 	}
43585c2a380aSMathias Nyman 
43595c2a380aSMathias Nyman 	xhci_free_command(xhci, command);
43605c2a380aSMathias Nyman 
4361a558ccdcSMathias Nyman 	return ret;
4362a558ccdcSMathias Nyman }
4363a558ccdcSMathias Nyman 
4364ceb6c9c8SRafael J. Wysocki #ifdef CONFIG_PM
43659574323cSAndiry Xu 
43669574323cSAndiry Xu /* BESL to HIRD Encoding array for USB2 LPM */
43679574323cSAndiry Xu static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
43689574323cSAndiry Xu 	3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
43699574323cSAndiry Xu 
43709574323cSAndiry Xu /* Calculate HIRD/BESL for USB2 PORTPMSC*/
xhci_calculate_hird_besl(struct xhci_hcd * xhci,struct usb_device * udev)4371f99298bfSAndiry Xu static int xhci_calculate_hird_besl(struct xhci_hcd *xhci,
4372f99298bfSAndiry Xu 					struct usb_device *udev)
43739574323cSAndiry Xu {
4374f99298bfSAndiry Xu 	int u2del, besl, besl_host;
4375f99298bfSAndiry Xu 	int besl_device = 0;
4376f99298bfSAndiry Xu 	u32 field;
43779574323cSAndiry Xu 
4378f99298bfSAndiry Xu 	u2del = HCS_U2_LATENCY(xhci->hcs_params3);
4379f99298bfSAndiry Xu 	field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4380f99298bfSAndiry Xu 
4381f99298bfSAndiry Xu 	if (field & USB_BESL_SUPPORT) {
4382f99298bfSAndiry Xu 		for (besl_host = 0; besl_host < 16; besl_host++) {
4383f99298bfSAndiry Xu 			if (xhci_besl_encoding[besl_host] >= u2del)
43849574323cSAndiry Xu 				break;
43859574323cSAndiry Xu 		}
4386f99298bfSAndiry Xu 		/* Use baseline BESL value as default */
4387f99298bfSAndiry Xu 		if (field & USB_BESL_BASELINE_VALID)
4388f99298bfSAndiry Xu 			besl_device = USB_GET_BESL_BASELINE(field);
4389f99298bfSAndiry Xu 		else if (field & USB_BESL_DEEP_VALID)
4390f99298bfSAndiry Xu 			besl_device = USB_GET_BESL_DEEP(field);
43919574323cSAndiry Xu 	} else {
43929574323cSAndiry Xu 		if (u2del <= 50)
4393f99298bfSAndiry Xu 			besl_host = 0;
43949574323cSAndiry Xu 		else
4395f99298bfSAndiry Xu 			besl_host = (u2del - 51) / 75 + 1;
43969574323cSAndiry Xu 	}
43979574323cSAndiry Xu 
4398f99298bfSAndiry Xu 	besl = besl_host + besl_device;
4399f99298bfSAndiry Xu 	if (besl > 15)
4400f99298bfSAndiry Xu 		besl = 15;
4401f99298bfSAndiry Xu 
4402f99298bfSAndiry Xu 	return besl;
44039574323cSAndiry Xu }
44049574323cSAndiry Xu 
4405a558ccdcSMathias Nyman /* Calculate BESLD, L1 timeout and HIRDM for USB2 PORTHLPMC */
xhci_calculate_usb2_hw_lpm_params(struct usb_device * udev)4406a558ccdcSMathias Nyman static int xhci_calculate_usb2_hw_lpm_params(struct usb_device *udev)
4407a558ccdcSMathias Nyman {
4408a558ccdcSMathias Nyman 	u32 field;
4409a558ccdcSMathias Nyman 	int l1;
4410a558ccdcSMathias Nyman 	int besld = 0;
4411a558ccdcSMathias Nyman 	int hirdm = 0;
4412a558ccdcSMathias Nyman 
4413a558ccdcSMathias Nyman 	field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4414a558ccdcSMathias Nyman 
4415a558ccdcSMathias Nyman 	/* xHCI l1 is set in steps of 256us, xHCI 1.0 section 5.4.11.2 */
441617f34867SMathias Nyman 	l1 = udev->l1_params.timeout / 256;
4417a558ccdcSMathias Nyman 
4418a558ccdcSMathias Nyman 	/* device has preferred BESLD */
4419a558ccdcSMathias Nyman 	if (field & USB_BESL_DEEP_VALID) {
4420a558ccdcSMathias Nyman 		besld = USB_GET_BESL_DEEP(field);
4421a558ccdcSMathias Nyman 		hirdm = 1;
4422a558ccdcSMathias Nyman 	}
4423a558ccdcSMathias Nyman 
4424a558ccdcSMathias Nyman 	return PORT_BESLD(besld) | PORT_L1_TIMEOUT(l1) | PORT_HIRDM(hirdm);
4425a558ccdcSMathias Nyman }
4426a558ccdcSMathias Nyman 
xhci_set_usb2_hardware_lpm(struct usb_hcd * hcd,struct usb_device * udev,int enable)44273969384cSLu Baolu static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
442865580b43SAndiry Xu 			struct usb_device *udev, int enable)
442965580b43SAndiry Xu {
443065580b43SAndiry Xu 	struct xhci_hcd	*xhci = hcd_to_xhci(hcd);
443138986ffaSMathias Nyman 	struct xhci_port **ports;
4432a558ccdcSMathias Nyman 	__le32 __iomem	*pm_addr, *hlpm_addr;
4433a558ccdcSMathias Nyman 	u32		pm_val, hlpm_val, field;
443465580b43SAndiry Xu 	unsigned int	port_num;
443565580b43SAndiry Xu 	unsigned long	flags;
4436a558ccdcSMathias Nyman 	int		hird, exit_latency;
4437a558ccdcSMathias Nyman 	int		ret;
443865580b43SAndiry Xu 
4439f0c472a6SKai-Heng Feng 	if (xhci->quirks & XHCI_HW_LPM_DISABLE)
4440f0c472a6SKai-Heng Feng 		return -EPERM;
4441f0c472a6SKai-Heng Feng 
4442b50107bbSMathias Nyman 	if (hcd->speed >= HCD_USB3 || !xhci->hw_lpm_support ||
444365580b43SAndiry Xu 			!udev->lpm_capable)
444465580b43SAndiry Xu 		return -EPERM;
444565580b43SAndiry Xu 
444665580b43SAndiry Xu 	if (!udev->parent || udev->parent->parent ||
444765580b43SAndiry Xu 			udev->descriptor.bDeviceClass == USB_CLASS_HUB)
444865580b43SAndiry Xu 		return -EPERM;
444965580b43SAndiry Xu 
445065580b43SAndiry Xu 	if (udev->usb2_hw_lpm_capable != 1)
445165580b43SAndiry Xu 		return -EPERM;
445265580b43SAndiry Xu 
445365580b43SAndiry Xu 	spin_lock_irqsave(&xhci->lock, flags);
445465580b43SAndiry Xu 
445538986ffaSMathias Nyman 	ports = xhci->usb2_rhub.ports;
445665580b43SAndiry Xu 	port_num = udev->portnum - 1;
445738986ffaSMathias Nyman 	pm_addr = ports[port_num]->addr + PORTPMSC;
4458b0ba9720SXenia Ragiadakou 	pm_val = readl(pm_addr);
445938986ffaSMathias Nyman 	hlpm_addr = ports[port_num]->addr + PORTHLPMC;
446065580b43SAndiry Xu 
446165580b43SAndiry Xu 	xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
4462654a55d3SLin Wang 			enable ? "enable" : "disable", port_num + 1);
446365580b43SAndiry Xu 
4464f0c472a6SKai-Heng Feng 	if (enable) {
4465a558ccdcSMathias Nyman 		/* Host supports BESL timeout instead of HIRD */
4466a558ccdcSMathias Nyman 		if (udev->usb2_hw_lpm_besl_capable) {
4467a558ccdcSMathias Nyman 			/* if device doesn't have a preferred BESL value use a
4468a558ccdcSMathias Nyman 			 * default one which works with mixed HIRD and BESL
4469a558ccdcSMathias Nyman 			 * systems. See XHCI_DEFAULT_BESL definition in xhci.h
4470a558ccdcSMathias Nyman 			 */
44717aa1bb2fSCarsten Schmid 			field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4472a558ccdcSMathias Nyman 			if ((field & USB_BESL_SUPPORT) &&
4473a558ccdcSMathias Nyman 			    (field & USB_BESL_BASELINE_VALID))
4474a558ccdcSMathias Nyman 				hird = USB_GET_BESL_BASELINE(field);
4475a558ccdcSMathias Nyman 			else
447617f34867SMathias Nyman 				hird = udev->l1_params.besl;
4477a558ccdcSMathias Nyman 
4478a558ccdcSMathias Nyman 			exit_latency = xhci_besl_encoding[hird];
4479a558ccdcSMathias Nyman 			spin_unlock_irqrestore(&xhci->lock, flags);
4480a558ccdcSMathias Nyman 
4481a558ccdcSMathias Nyman 			ret = xhci_change_max_exit_latency(xhci, udev,
4482a558ccdcSMathias Nyman 							   exit_latency);
4483a558ccdcSMathias Nyman 			if (ret < 0)
4484a558ccdcSMathias Nyman 				return ret;
4485a558ccdcSMathias Nyman 			spin_lock_irqsave(&xhci->lock, flags);
4486a558ccdcSMathias Nyman 
4487a558ccdcSMathias Nyman 			hlpm_val = xhci_calculate_usb2_hw_lpm_params(udev);
4488204b7793SXenia Ragiadakou 			writel(hlpm_val, hlpm_addr);
4489a558ccdcSMathias Nyman 			/* flush write */
4490b0ba9720SXenia Ragiadakou 			readl(hlpm_addr);
449165580b43SAndiry Xu 		} else {
4492a558ccdcSMathias Nyman 			hird = xhci_calculate_hird_besl(xhci, udev);
4493a558ccdcSMathias Nyman 		}
4494a558ccdcSMathias Nyman 
4495a558ccdcSMathias Nyman 		pm_val &= ~PORT_HIRD_MASK;
449658e21f73SSarah Sharp 		pm_val |= PORT_HIRD(hird) | PORT_RWE | PORT_L1DS(udev->slot_id);
4497204b7793SXenia Ragiadakou 		writel(pm_val, pm_addr);
4498b0ba9720SXenia Ragiadakou 		pm_val = readl(pm_addr);
4499a558ccdcSMathias Nyman 		pm_val |= PORT_HLE;
4500204b7793SXenia Ragiadakou 		writel(pm_val, pm_addr);
4501a558ccdcSMathias Nyman 		/* flush write */
4502b0ba9720SXenia Ragiadakou 		readl(pm_addr);
4503a558ccdcSMathias Nyman 	} else {
450458e21f73SSarah Sharp 		pm_val &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK | PORT_L1DS_MASK);
4505204b7793SXenia Ragiadakou 		writel(pm_val, pm_addr);
4506a558ccdcSMathias Nyman 		/* flush write */
4507b0ba9720SXenia Ragiadakou 		readl(pm_addr);
4508a558ccdcSMathias Nyman 		if (udev->usb2_hw_lpm_besl_capable) {
4509a558ccdcSMathias Nyman 			spin_unlock_irqrestore(&xhci->lock, flags);
4510a558ccdcSMathias Nyman 			xhci_change_max_exit_latency(xhci, udev, 0);
4511b3d71abdSKai-Heng Feng 			readl_poll_timeout(ports[port_num]->addr, pm_val,
4512b3d71abdSKai-Heng Feng 					   (pm_val & PORT_PLS_MASK) == XDEV_U0,
4513b3d71abdSKai-Heng Feng 					   100, 10000);
4514a558ccdcSMathias Nyman 			return 0;
4515a558ccdcSMathias Nyman 		}
451665580b43SAndiry Xu 	}
451765580b43SAndiry Xu 
451865580b43SAndiry Xu 	spin_unlock_irqrestore(&xhci->lock, flags);
451965580b43SAndiry Xu 	return 0;
452065580b43SAndiry Xu }
452165580b43SAndiry Xu 
xhci_update_device(struct usb_hcd * hcd,struct usb_device * udev)45223969384cSLu Baolu static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4523b01bcbf7SSarah Sharp {
4524b01bcbf7SSarah Sharp 	struct xhci_hcd	*xhci = hcd_to_xhci(hcd);
45256d3bc5e9SMathias Nyman 	struct xhci_port *port;
45266d3bc5e9SMathias Nyman 	u32 capability;
4527b01bcbf7SSarah Sharp 
4528948ce83fSMathias Nyman 	/* Check if USB3 device at root port is tunneled over USB4 */
4529948ce83fSMathias Nyman 	if (hcd->speed >= HCD_USB3 && !udev->parent->parent) {
4530948ce83fSMathias Nyman 		port = xhci->usb3_rhub.ports[udev->portnum - 1];
4531948ce83fSMathias Nyman 
4532f46a6e16SMathias Nyman 		udev->tunnel_mode = xhci_port_is_tunneled(xhci, port);
4533f46a6e16SMathias Nyman 		if (udev->tunnel_mode == USB_LINK_UNKNOWN)
4534f46a6e16SMathias Nyman 			dev_dbg(&udev->dev, "link tunnel state unknown\n");
4535f46a6e16SMathias Nyman 		else if (udev->tunnel_mode == USB_LINK_TUNNELED)
4536948ce83fSMathias Nyman 			dev_dbg(&udev->dev, "tunneled over USB4 link\n");
4537f46a6e16SMathias Nyman 		else if (udev->tunnel_mode == USB_LINK_NATIVE)
4538948ce83fSMathias Nyman 			dev_dbg(&udev->dev, "native USB 3.x link\n");
4539948ce83fSMathias Nyman 		return 0;
4540948ce83fSMathias Nyman 	}
4541948ce83fSMathias Nyman 
45426d3bc5e9SMathias Nyman 	if (hcd->speed >= HCD_USB3 || !udev->lpm_capable || !xhci->hw_lpm_support)
4543de68bab4SSarah Sharp 		return 0;
4544de68bab4SSarah Sharp 
4545de68bab4SSarah Sharp 	/* we only support lpm for non-hub device connected to root hub yet */
4546de68bab4SSarah Sharp 	if (!udev->parent || udev->parent->parent ||
4547de68bab4SSarah Sharp 			udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4548de68bab4SSarah Sharp 		return 0;
4549de68bab4SSarah Sharp 
45506d3bc5e9SMathias Nyman 	port = xhci->usb2_rhub.ports[udev->portnum - 1];
45516d3bc5e9SMathias Nyman 	capability = port->port_cap->protocol_caps;
45526d3bc5e9SMathias Nyman 
45536d3bc5e9SMathias Nyman 	if (capability & XHCI_HLC) {
4554b01bcbf7SSarah Sharp 		udev->usb2_hw_lpm_capable = 1;
455517f34867SMathias Nyman 		udev->l1_params.timeout = XHCI_L1_TIMEOUT;
455617f34867SMathias Nyman 		udev->l1_params.besl = XHCI_DEFAULT_BESL;
45576d3bc5e9SMathias Nyman 		if (capability & XHCI_BLC)
4558a558ccdcSMathias Nyman 			udev->usb2_hw_lpm_besl_capable = 1;
4559b01bcbf7SSarah Sharp 	}
4560b01bcbf7SSarah Sharp 
4561b01bcbf7SSarah Sharp 	return 0;
4562b01bcbf7SSarah Sharp }
4563b01bcbf7SSarah Sharp 
45643b3db026SSarah Sharp /*---------------------- USB 3.0 Link PM functions ------------------------*/
45653b3db026SSarah Sharp 
4566e3567d2cSSarah Sharp /* Service interval in nanoseconds = 2^(bInterval - 1) * 125us * 1000ns / 1us */
xhci_service_interval_to_ns(struct usb_endpoint_descriptor * desc)4567e3567d2cSSarah Sharp static unsigned long long xhci_service_interval_to_ns(
4568e3567d2cSSarah Sharp 		struct usb_endpoint_descriptor *desc)
4569e3567d2cSSarah Sharp {
457016b45fdfSOliver Neukum 	return (1ULL << (desc->bInterval - 1)) * 125 * 1000;
4571e3567d2cSSarah Sharp }
4572e3567d2cSSarah Sharp 
xhci_get_timeout_no_hub_lpm(struct usb_device * udev,enum usb3_link_state state)45733b3db026SSarah Sharp static u16 xhci_get_timeout_no_hub_lpm(struct usb_device *udev,
45743b3db026SSarah Sharp 		enum usb3_link_state state)
45753b3db026SSarah Sharp {
45763b3db026SSarah Sharp 	unsigned long long sel;
45773b3db026SSarah Sharp 	unsigned long long pel;
45783b3db026SSarah Sharp 	unsigned int max_sel_pel;
45793b3db026SSarah Sharp 	char *state_name;
45803b3db026SSarah Sharp 
45813b3db026SSarah Sharp 	switch (state) {
45823b3db026SSarah Sharp 	case USB3_LPM_U1:
45833b3db026SSarah Sharp 		/* Convert SEL and PEL stored in nanoseconds to microseconds */
45843b3db026SSarah Sharp 		sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
45853b3db026SSarah Sharp 		pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
45863b3db026SSarah Sharp 		max_sel_pel = USB3_LPM_MAX_U1_SEL_PEL;
45873b3db026SSarah Sharp 		state_name = "U1";
45883b3db026SSarah Sharp 		break;
45893b3db026SSarah Sharp 	case USB3_LPM_U2:
45903b3db026SSarah Sharp 		sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
45913b3db026SSarah Sharp 		pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
45923b3db026SSarah Sharp 		max_sel_pel = USB3_LPM_MAX_U2_SEL_PEL;
45933b3db026SSarah Sharp 		state_name = "U2";
45943b3db026SSarah Sharp 		break;
45953b3db026SSarah Sharp 	default:
45963b3db026SSarah Sharp 		dev_warn(&udev->dev, "%s: Can't get timeout for non-U1 or U2 state.\n",
45973b3db026SSarah Sharp 				__func__);
4598e25e62aeSSarah Sharp 		return USB3_LPM_DISABLED;
45993b3db026SSarah Sharp 	}
46003b3db026SSarah Sharp 
46013b3db026SSarah Sharp 	if (sel <= max_sel_pel && pel <= max_sel_pel)
46023b3db026SSarah Sharp 		return USB3_LPM_DEVICE_INITIATED;
46033b3db026SSarah Sharp 
46043b3db026SSarah Sharp 	if (sel > max_sel_pel)
46053b3db026SSarah Sharp 		dev_dbg(&udev->dev, "Device-initiated %s disabled "
46063b3db026SSarah Sharp 				"due to long SEL %llu ms\n",
46073b3db026SSarah Sharp 				state_name, sel);
46083b3db026SSarah Sharp 	else
46093b3db026SSarah Sharp 		dev_dbg(&udev->dev, "Device-initiated %s disabled "
461003e64e96SJoe Perches 				"due to long PEL %llu ms\n",
46113b3db026SSarah Sharp 				state_name, pel);
46123b3db026SSarah Sharp 	return USB3_LPM_DISABLED;
46133b3db026SSarah Sharp }
46143b3db026SSarah Sharp 
46159502c46cSPratyush Anand /* The U1 timeout should be the maximum of the following values:
4616e3567d2cSSarah Sharp  *  - For control endpoints, U1 system exit latency (SEL) * 3
4617e3567d2cSSarah Sharp  *  - For bulk endpoints, U1 SEL * 5
4618e3567d2cSSarah Sharp  *  - For interrupt endpoints:
4619e3567d2cSSarah Sharp  *    - Notification EPs, U1 SEL * 3
4620e3567d2cSSarah Sharp  *    - Periodic EPs, max(105% of bInterval, U1 SEL * 2)
4621e3567d2cSSarah Sharp  *  - For isochronous endpoints, max(105% of bInterval, U1 SEL * 2)
4622e3567d2cSSarah Sharp  */
xhci_calculate_intel_u1_timeout(struct usb_device * udev,struct usb_endpoint_descriptor * desc)46239502c46cSPratyush Anand static unsigned long long xhci_calculate_intel_u1_timeout(
46249502c46cSPratyush Anand 		struct usb_device *udev,
4625e3567d2cSSarah Sharp 		struct usb_endpoint_descriptor *desc)
4626e3567d2cSSarah Sharp {
4627e3567d2cSSarah Sharp 	unsigned long long timeout_ns;
4628e3567d2cSSarah Sharp 	int ep_type;
4629e3567d2cSSarah Sharp 	int intr_type;
4630e3567d2cSSarah Sharp 
4631e3567d2cSSarah Sharp 	ep_type = usb_endpoint_type(desc);
4632e3567d2cSSarah Sharp 	switch (ep_type) {
4633e3567d2cSSarah Sharp 	case USB_ENDPOINT_XFER_CONTROL:
4634e3567d2cSSarah Sharp 		timeout_ns = udev->u1_params.sel * 3;
4635e3567d2cSSarah Sharp 		break;
4636e3567d2cSSarah Sharp 	case USB_ENDPOINT_XFER_BULK:
4637e3567d2cSSarah Sharp 		timeout_ns = udev->u1_params.sel * 5;
4638e3567d2cSSarah Sharp 		break;
4639e3567d2cSSarah Sharp 	case USB_ENDPOINT_XFER_INT:
4640e3567d2cSSarah Sharp 		intr_type = usb_endpoint_interrupt_type(desc);
4641e3567d2cSSarah Sharp 		if (intr_type == USB_ENDPOINT_INTR_NOTIFICATION) {
4642e3567d2cSSarah Sharp 			timeout_ns = udev->u1_params.sel * 3;
4643e3567d2cSSarah Sharp 			break;
4644e3567d2cSSarah Sharp 		}
4645e3567d2cSSarah Sharp 		/* Otherwise the calculation is the same as isoc eps */
4646df561f66SGustavo A. R. Silva 		fallthrough;
4647e3567d2cSSarah Sharp 	case USB_ENDPOINT_XFER_ISOC:
4648e3567d2cSSarah Sharp 		timeout_ns = xhci_service_interval_to_ns(desc);
4649c88db160SSarah Sharp 		timeout_ns = DIV_ROUND_UP_ULL(timeout_ns * 105, 100);
4650e3567d2cSSarah Sharp 		if (timeout_ns < udev->u1_params.sel * 2)
4651e3567d2cSSarah Sharp 			timeout_ns = udev->u1_params.sel * 2;
4652e3567d2cSSarah Sharp 		break;
4653e3567d2cSSarah Sharp 	default:
4654e3567d2cSSarah Sharp 		return 0;
4655e3567d2cSSarah Sharp 	}
4656e3567d2cSSarah Sharp 
46579502c46cSPratyush Anand 	return timeout_ns;
46589502c46cSPratyush Anand }
46599502c46cSPratyush Anand 
46609502c46cSPratyush Anand /* Returns the hub-encoded U1 timeout value. */
xhci_calculate_u1_timeout(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_endpoint_descriptor * desc)46619502c46cSPratyush Anand static u16 xhci_calculate_u1_timeout(struct xhci_hcd *xhci,
46629502c46cSPratyush Anand 		struct usb_device *udev,
46639502c46cSPratyush Anand 		struct usb_endpoint_descriptor *desc)
46649502c46cSPratyush Anand {
46659502c46cSPratyush Anand 	unsigned long long timeout_ns;
46669502c46cSPratyush Anand 
46675d5323a6SMichael Grzeschik 	/* Prevent U1 if service interval is shorter than U1 exit latency */
46685d5323a6SMichael Grzeschik 	if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
46692847c46cSMathias Nyman 		if (xhci_service_interval_to_ns(desc) <= udev->u1_params.mel) {
46705d5323a6SMichael Grzeschik 			dev_dbg(&udev->dev, "Disable U1, ESIT shorter than exit latency\n");
46715d5323a6SMichael Grzeschik 			return USB3_LPM_DISABLED;
46725d5323a6SMichael Grzeschik 		}
46735d5323a6SMichael Grzeschik 	}
46745d5323a6SMichael Grzeschik 
4675d5e234ffSWeitao Wang 	if (xhci->quirks & (XHCI_INTEL_HOST | XHCI_ZHAOXIN_HOST))
46762847c46cSMathias Nyman 		timeout_ns = xhci_calculate_intel_u1_timeout(udev, desc);
46772847c46cSMathias Nyman 	else
46782847c46cSMathias Nyman 		timeout_ns = udev->u1_params.sel;
46792847c46cSMathias Nyman 
46809502c46cSPratyush Anand 	/* The U1 timeout is encoded in 1us intervals.
46819502c46cSPratyush Anand 	 * Don't return a timeout of zero, because that's USB3_LPM_DISABLED.
46829502c46cSPratyush Anand 	 */
4683e3567d2cSSarah Sharp 	if (timeout_ns == USB3_LPM_DISABLED)
46849502c46cSPratyush Anand 		timeout_ns = 1;
46859502c46cSPratyush Anand 	else
46869502c46cSPratyush Anand 		timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 1000);
4687e3567d2cSSarah Sharp 
4688e3567d2cSSarah Sharp 	/* If the necessary timeout value is bigger than what we can set in the
4689e3567d2cSSarah Sharp 	 * USB 3.0 hub, we have to disable hub-initiated U1.
4690e3567d2cSSarah Sharp 	 */
4691e3567d2cSSarah Sharp 	if (timeout_ns <= USB3_LPM_U1_MAX_TIMEOUT)
4692e3567d2cSSarah Sharp 		return timeout_ns;
4693e3567d2cSSarah Sharp 	dev_dbg(&udev->dev, "Hub-initiated U1 disabled "
4694e3567d2cSSarah Sharp 			"due to long timeout %llu ms\n", timeout_ns);
4695e3567d2cSSarah Sharp 	return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U1);
4696e3567d2cSSarah Sharp }
4697e3567d2cSSarah Sharp 
46989502c46cSPratyush Anand /* The U2 timeout should be the maximum of:
4699e3567d2cSSarah Sharp  *  - 10 ms (to avoid the bandwidth impact on the scheduler)
4700e3567d2cSSarah Sharp  *  - largest bInterval of any active periodic endpoint (to avoid going
4701e3567d2cSSarah Sharp  *    into lower power link states between intervals).
4702e3567d2cSSarah Sharp  *  - the U2 Exit Latency of the device
4703e3567d2cSSarah Sharp  */
xhci_calculate_intel_u2_timeout(struct usb_device * udev,struct usb_endpoint_descriptor * desc)47049502c46cSPratyush Anand static unsigned long long xhci_calculate_intel_u2_timeout(
47059502c46cSPratyush Anand 		struct usb_device *udev,
4706e3567d2cSSarah Sharp 		struct usb_endpoint_descriptor *desc)
4707e3567d2cSSarah Sharp {
4708e3567d2cSSarah Sharp 	unsigned long long timeout_ns;
4709e3567d2cSSarah Sharp 	unsigned long long u2_del_ns;
4710e3567d2cSSarah Sharp 
4711e3567d2cSSarah Sharp 	timeout_ns = 10 * 1000 * 1000;
4712e3567d2cSSarah Sharp 
4713e3567d2cSSarah Sharp 	if ((usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) &&
4714e3567d2cSSarah Sharp 			(xhci_service_interval_to_ns(desc) > timeout_ns))
4715e3567d2cSSarah Sharp 		timeout_ns = xhci_service_interval_to_ns(desc);
4716e3567d2cSSarah Sharp 
4717966e7a85SOliver Neukum 	u2_del_ns = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat) * 1000ULL;
4718e3567d2cSSarah Sharp 	if (u2_del_ns > timeout_ns)
4719e3567d2cSSarah Sharp 		timeout_ns = u2_del_ns;
4720e3567d2cSSarah Sharp 
47219502c46cSPratyush Anand 	return timeout_ns;
47229502c46cSPratyush Anand }
47239502c46cSPratyush Anand 
47249502c46cSPratyush Anand /* Returns the hub-encoded U2 timeout value. */
xhci_calculate_u2_timeout(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_endpoint_descriptor * desc)47259502c46cSPratyush Anand static u16 xhci_calculate_u2_timeout(struct xhci_hcd *xhci,
47269502c46cSPratyush Anand 		struct usb_device *udev,
47279502c46cSPratyush Anand 		struct usb_endpoint_descriptor *desc)
47289502c46cSPratyush Anand {
47299502c46cSPratyush Anand 	unsigned long long timeout_ns;
47309502c46cSPratyush Anand 
47315d5323a6SMichael Grzeschik 	/* Prevent U2 if service interval is shorter than U2 exit latency */
47325d5323a6SMichael Grzeschik 	if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
47332847c46cSMathias Nyman 		if (xhci_service_interval_to_ns(desc) <= udev->u2_params.mel) {
47345d5323a6SMichael Grzeschik 			dev_dbg(&udev->dev, "Disable U2, ESIT shorter than exit latency\n");
47355d5323a6SMichael Grzeschik 			return USB3_LPM_DISABLED;
47365d5323a6SMichael Grzeschik 		}
47375d5323a6SMichael Grzeschik 	}
47385d5323a6SMichael Grzeschik 
4739d5e234ffSWeitao Wang 	if (xhci->quirks & (XHCI_INTEL_HOST | XHCI_ZHAOXIN_HOST))
47402847c46cSMathias Nyman 		timeout_ns = xhci_calculate_intel_u2_timeout(udev, desc);
47412847c46cSMathias Nyman 	else
47422847c46cSMathias Nyman 		timeout_ns = udev->u2_params.sel;
47432847c46cSMathias Nyman 
4744e3567d2cSSarah Sharp 	/* The U2 timeout is encoded in 256us intervals */
4745c88db160SSarah Sharp 	timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 256 * 1000);
4746e3567d2cSSarah Sharp 	/* If the necessary timeout value is bigger than what we can set in the
4747e3567d2cSSarah Sharp 	 * USB 3.0 hub, we have to disable hub-initiated U2.
4748e3567d2cSSarah Sharp 	 */
4749e3567d2cSSarah Sharp 	if (timeout_ns <= USB3_LPM_U2_MAX_TIMEOUT)
4750e3567d2cSSarah Sharp 		return timeout_ns;
4751e3567d2cSSarah Sharp 	dev_dbg(&udev->dev, "Hub-initiated U2 disabled "
4752e3567d2cSSarah Sharp 			"due to long timeout %llu ms\n", timeout_ns);
4753e3567d2cSSarah Sharp 	return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U2);
4754e3567d2cSSarah Sharp }
4755e3567d2cSSarah Sharp 
xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_endpoint_descriptor * desc,enum usb3_link_state state,u16 * timeout)47563b3db026SSarah Sharp static u16 xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd *xhci,
47573b3db026SSarah Sharp 		struct usb_device *udev,
47583b3db026SSarah Sharp 		struct usb_endpoint_descriptor *desc,
47593b3db026SSarah Sharp 		enum usb3_link_state state,
47603b3db026SSarah Sharp 		u16 *timeout)
47613b3db026SSarah Sharp {
47629502c46cSPratyush Anand 	if (state == USB3_LPM_U1)
47639502c46cSPratyush Anand 		return xhci_calculate_u1_timeout(xhci, udev, desc);
47649502c46cSPratyush Anand 	else if (state == USB3_LPM_U2)
47659502c46cSPratyush Anand 		return xhci_calculate_u2_timeout(xhci, udev, desc);
4766e3567d2cSSarah Sharp 
47673b3db026SSarah Sharp 	return USB3_LPM_DISABLED;
47683b3db026SSarah Sharp }
47693b3db026SSarah Sharp 
xhci_update_timeout_for_endpoint(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_endpoint_descriptor * desc,enum usb3_link_state state,u16 * timeout)47703b3db026SSarah Sharp static int xhci_update_timeout_for_endpoint(struct xhci_hcd *xhci,
47713b3db026SSarah Sharp 		struct usb_device *udev,
47723b3db026SSarah Sharp 		struct usb_endpoint_descriptor *desc,
47733b3db026SSarah Sharp 		enum usb3_link_state state,
47743b3db026SSarah Sharp 		u16 *timeout)
47753b3db026SSarah Sharp {
47763b3db026SSarah Sharp 	u16 alt_timeout;
47773b3db026SSarah Sharp 
47783b3db026SSarah Sharp 	alt_timeout = xhci_call_host_update_timeout_for_endpoint(xhci, udev,
47793b3db026SSarah Sharp 		desc, state, timeout);
47803b3db026SSarah Sharp 
4781d500c63fSJan Schmidt 	/* If we found we can't enable hub-initiated LPM, and
47823b3db026SSarah Sharp 	 * the U1 or U2 exit latency was too high to allow
4783d500c63fSJan Schmidt 	 * device-initiated LPM as well, then we will disable LPM
4784d500c63fSJan Schmidt 	 * for this device, so stop searching any further.
47853b3db026SSarah Sharp 	 */
4786d500c63fSJan Schmidt 	if (alt_timeout == USB3_LPM_DISABLED) {
47873b3db026SSarah Sharp 		*timeout = alt_timeout;
47883b3db026SSarah Sharp 		return -E2BIG;
47893b3db026SSarah Sharp 	}
47903b3db026SSarah Sharp 	if (alt_timeout > *timeout)
47913b3db026SSarah Sharp 		*timeout = alt_timeout;
47923b3db026SSarah Sharp 	return 0;
47933b3db026SSarah Sharp }
47943b3db026SSarah Sharp 
xhci_update_timeout_for_interface(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_host_interface * alt,enum usb3_link_state state,u16 * timeout)47953b3db026SSarah Sharp static int xhci_update_timeout_for_interface(struct xhci_hcd *xhci,
47963b3db026SSarah Sharp 		struct usb_device *udev,
47973b3db026SSarah Sharp 		struct usb_host_interface *alt,
47983b3db026SSarah Sharp 		enum usb3_link_state state,
47993b3db026SSarah Sharp 		u16 *timeout)
48003b3db026SSarah Sharp {
48013b3db026SSarah Sharp 	int j;
48023b3db026SSarah Sharp 
48033b3db026SSarah Sharp 	for (j = 0; j < alt->desc.bNumEndpoints; j++) {
48043b3db026SSarah Sharp 		if (xhci_update_timeout_for_endpoint(xhci, udev,
48053b3db026SSarah Sharp 					&alt->endpoint[j].desc, state, timeout))
48063b3db026SSarah Sharp 			return -E2BIG;
48073b3db026SSarah Sharp 	}
48083b3db026SSarah Sharp 	return 0;
48093b3db026SSarah Sharp }
48103b3db026SSarah Sharp 
xhci_check_tier_policy(struct xhci_hcd * xhci,struct usb_device * udev,enum usb3_link_state state)48113b3db026SSarah Sharp static int xhci_check_tier_policy(struct xhci_hcd *xhci,
48123b3db026SSarah Sharp 		struct usb_device *udev,
48133b3db026SSarah Sharp 		enum usb3_link_state state)
48143b3db026SSarah Sharp {
4815d5e234ffSWeitao Wang 	struct usb_device *parent = udev->parent;
4816d5e234ffSWeitao Wang 	int tier = 1; /* roothub is tier1 */
4817d5e234ffSWeitao Wang 
4818d5e234ffSWeitao Wang 	while (parent) {
4819d5e234ffSWeitao Wang 		parent = parent->parent;
4820d5e234ffSWeitao Wang 		tier++;
4821d5e234ffSWeitao Wang 	}
4822d5e234ffSWeitao Wang 
4823d5e234ffSWeitao Wang 	if (xhci->quirks & XHCI_INTEL_HOST && tier > 3)
4824d5e234ffSWeitao Wang 		goto fail;
4825d5e234ffSWeitao Wang 	if (xhci->quirks & XHCI_ZHAOXIN_HOST && tier > 2)
4826d5e234ffSWeitao Wang 		goto fail;
4827d5e234ffSWeitao Wang 
48289502c46cSPratyush Anand 	return 0;
4829d5e234ffSWeitao Wang fail:
4830d5e234ffSWeitao Wang 	dev_dbg(&udev->dev, "Tier policy prevents U1/U2 LPM states for devices at tier %d\n",
4831d5e234ffSWeitao Wang 			tier);
4832d5e234ffSWeitao Wang 	return -E2BIG;
48333b3db026SSarah Sharp }
48343b3db026SSarah Sharp 
48353b3db026SSarah Sharp /* Returns the U1 or U2 timeout that should be enabled.
48363b3db026SSarah Sharp  * If the tier check or timeout setting functions return with a non-zero exit
48373b3db026SSarah Sharp  * code, that means the timeout value has been finalized and we shouldn't look
48383b3db026SSarah Sharp  * at any more endpoints.
48393b3db026SSarah Sharp  */
xhci_calculate_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)48403b3db026SSarah Sharp static u16 xhci_calculate_lpm_timeout(struct usb_hcd *hcd,
48413b3db026SSarah Sharp 			struct usb_device *udev, enum usb3_link_state state)
48423b3db026SSarah Sharp {
48433b3db026SSarah Sharp 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
48443b3db026SSarah Sharp 	struct usb_host_config *config;
48453b3db026SSarah Sharp 	char *state_name;
48463b3db026SSarah Sharp 	int i;
48473b3db026SSarah Sharp 	u16 timeout = USB3_LPM_DISABLED;
48483b3db026SSarah Sharp 
48493b3db026SSarah Sharp 	if (state == USB3_LPM_U1)
48503b3db026SSarah Sharp 		state_name = "U1";
48513b3db026SSarah Sharp 	else if (state == USB3_LPM_U2)
48523b3db026SSarah Sharp 		state_name = "U2";
48533b3db026SSarah Sharp 	else {
48543b3db026SSarah Sharp 		dev_warn(&udev->dev, "Can't enable unknown link state %i\n",
48553b3db026SSarah Sharp 				state);
48563b3db026SSarah Sharp 		return timeout;
48573b3db026SSarah Sharp 	}
48583b3db026SSarah Sharp 
48593b3db026SSarah Sharp 	/* Gather some information about the currently installed configuration
48603b3db026SSarah Sharp 	 * and alternate interface settings.
48613b3db026SSarah Sharp 	 */
48623b3db026SSarah Sharp 	if (xhci_update_timeout_for_endpoint(xhci, udev, &udev->ep0.desc,
48633b3db026SSarah Sharp 			state, &timeout))
48643b3db026SSarah Sharp 		return timeout;
48653b3db026SSarah Sharp 
48663b3db026SSarah Sharp 	config = udev->actconfig;
48673b3db026SSarah Sharp 	if (!config)
48683b3db026SSarah Sharp 		return timeout;
48693b3db026SSarah Sharp 
487064ba419bSXenia Ragiadakou 	for (i = 0; i < config->desc.bNumInterfaces; i++) {
48713b3db026SSarah Sharp 		struct usb_driver *driver;
48723b3db026SSarah Sharp 		struct usb_interface *intf = config->interface[i];
48733b3db026SSarah Sharp 
48743b3db026SSarah Sharp 		if (!intf)
48753b3db026SSarah Sharp 			continue;
48763b3db026SSarah Sharp 
48773b3db026SSarah Sharp 		/* Check if any currently bound drivers want hub-initiated LPM
48783b3db026SSarah Sharp 		 * disabled.
48793b3db026SSarah Sharp 		 */
48803b3db026SSarah Sharp 		if (intf->dev.driver) {
48813b3db026SSarah Sharp 			driver = to_usb_driver(intf->dev.driver);
48823b3db026SSarah Sharp 			if (driver && driver->disable_hub_initiated_lpm) {
4883cd9d9491SMathias Nyman 				dev_dbg(&udev->dev, "Hub-initiated %s disabled at request of driver %s\n",
48843b3db026SSarah Sharp 					state_name, driver->name);
4885cd9d9491SMathias Nyman 				timeout = xhci_get_timeout_no_hub_lpm(udev,
4886cd9d9491SMathias Nyman 								      state);
4887cd9d9491SMathias Nyman 				if (timeout == USB3_LPM_DISABLED)
4888cd9d9491SMathias Nyman 					return timeout;
48893b3db026SSarah Sharp 			}
48903b3db026SSarah Sharp 		}
48913b3db026SSarah Sharp 
48923b3db026SSarah Sharp 		/* Not sure how this could happen... */
48933b3db026SSarah Sharp 		if (!intf->cur_altsetting)
48943b3db026SSarah Sharp 			continue;
48953b3db026SSarah Sharp 
48963b3db026SSarah Sharp 		if (xhci_update_timeout_for_interface(xhci, udev,
48973b3db026SSarah Sharp 					intf->cur_altsetting,
48983b3db026SSarah Sharp 					state, &timeout))
48993b3db026SSarah Sharp 			return timeout;
49003b3db026SSarah Sharp 	}
49013b3db026SSarah Sharp 	return timeout;
49023b3db026SSarah Sharp }
49033b3db026SSarah Sharp 
calculate_max_exit_latency(struct usb_device * udev,enum usb3_link_state state_changed,u16 hub_encoded_timeout)49043b3db026SSarah Sharp static int calculate_max_exit_latency(struct usb_device *udev,
49053b3db026SSarah Sharp 		enum usb3_link_state state_changed,
49063b3db026SSarah Sharp 		u16 hub_encoded_timeout)
49073b3db026SSarah Sharp {
49083b3db026SSarah Sharp 	unsigned long long u1_mel_us = 0;
49093b3db026SSarah Sharp 	unsigned long long u2_mel_us = 0;
49103b3db026SSarah Sharp 	unsigned long long mel_us = 0;
49113b3db026SSarah Sharp 	bool disabling_u1;
49123b3db026SSarah Sharp 	bool disabling_u2;
49133b3db026SSarah Sharp 	bool enabling_u1;
49143b3db026SSarah Sharp 	bool enabling_u2;
49153b3db026SSarah Sharp 
49163b3db026SSarah Sharp 	disabling_u1 = (state_changed == USB3_LPM_U1 &&
49173b3db026SSarah Sharp 			hub_encoded_timeout == USB3_LPM_DISABLED);
49183b3db026SSarah Sharp 	disabling_u2 = (state_changed == USB3_LPM_U2 &&
49193b3db026SSarah Sharp 			hub_encoded_timeout == USB3_LPM_DISABLED);
49203b3db026SSarah Sharp 
49213b3db026SSarah Sharp 	enabling_u1 = (state_changed == USB3_LPM_U1 &&
49223b3db026SSarah Sharp 			hub_encoded_timeout != USB3_LPM_DISABLED);
49233b3db026SSarah Sharp 	enabling_u2 = (state_changed == USB3_LPM_U2 &&
49243b3db026SSarah Sharp 			hub_encoded_timeout != USB3_LPM_DISABLED);
49253b3db026SSarah Sharp 
49263b3db026SSarah Sharp 	/* If U1 was already enabled and we're not disabling it,
49273b3db026SSarah Sharp 	 * or we're going to enable U1, account for the U1 max exit latency.
49283b3db026SSarah Sharp 	 */
49293b3db026SSarah Sharp 	if ((udev->u1_params.timeout != USB3_LPM_DISABLED && !disabling_u1) ||
49303b3db026SSarah Sharp 			enabling_u1)
49313b3db026SSarah Sharp 		u1_mel_us = DIV_ROUND_UP(udev->u1_params.mel, 1000);
49323b3db026SSarah Sharp 	if ((udev->u2_params.timeout != USB3_LPM_DISABLED && !disabling_u2) ||
49333b3db026SSarah Sharp 			enabling_u2)
49343b3db026SSarah Sharp 		u2_mel_us = DIV_ROUND_UP(udev->u2_params.mel, 1000);
49353b3db026SSarah Sharp 
4936f28fb27eSChangcheng Deng 	mel_us = max(u1_mel_us, u2_mel_us);
4937f28fb27eSChangcheng Deng 
49383b3db026SSarah Sharp 	/* xHCI host controller max exit latency field is only 16 bits wide. */
49393b3db026SSarah Sharp 	if (mel_us > MAX_EXIT) {
49403b3db026SSarah Sharp 		dev_warn(&udev->dev, "Link PM max exit latency of %lluus "
49413b3db026SSarah Sharp 				"is too big.\n", mel_us);
49423b3db026SSarah Sharp 		return -E2BIG;
49433b3db026SSarah Sharp 	}
49443b3db026SSarah Sharp 	return mel_us;
49453b3db026SSarah Sharp }
49463b3db026SSarah Sharp 
49473b3db026SSarah Sharp /* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
xhci_enable_usb3_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)49483969384cSLu Baolu static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
49493b3db026SSarah Sharp 			struct usb_device *udev, enum usb3_link_state state)
49503b3db026SSarah Sharp {
49513b3db026SSarah Sharp 	struct xhci_hcd	*xhci;
49520522b9a1SMathias Nyman 	struct xhci_port *port;
49533b3db026SSarah Sharp 	u16 hub_encoded_timeout;
49543b3db026SSarah Sharp 	int mel;
49553b3db026SSarah Sharp 	int ret;
49563b3db026SSarah Sharp 
49573b3db026SSarah Sharp 	xhci = hcd_to_xhci(hcd);
49583b3db026SSarah Sharp 	/* The LPM timeout values are pretty host-controller specific, so don't
49593b3db026SSarah Sharp 	 * enable hub-initiated timeouts unless the vendor has provided
49603b3db026SSarah Sharp 	 * information about their timeout algorithm.
49613b3db026SSarah Sharp 	 */
49623b3db026SSarah Sharp 	if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
49633b3db026SSarah Sharp 			!xhci->devs[udev->slot_id])
49643b3db026SSarah Sharp 		return USB3_LPM_DISABLED;
49653b3db026SSarah Sharp 
4966424140d3SMathias Nyman 	if (xhci_check_tier_policy(xhci, udev, state) < 0)
4967424140d3SMathias Nyman 		return USB3_LPM_DISABLED;
4968424140d3SMathias Nyman 
49690522b9a1SMathias Nyman 	/* If connected to root port then check port can handle lpm */
49700522b9a1SMathias Nyman 	if (udev->parent && !udev->parent->parent) {
49710522b9a1SMathias Nyman 		port = xhci->usb3_rhub.ports[udev->portnum - 1];
49720522b9a1SMathias Nyman 		if (port->lpm_incapable)
49730522b9a1SMathias Nyman 			return USB3_LPM_DISABLED;
49740522b9a1SMathias Nyman 	}
49750522b9a1SMathias Nyman 
49763b3db026SSarah Sharp 	hub_encoded_timeout = xhci_calculate_lpm_timeout(hcd, udev, state);
49773b3db026SSarah Sharp 	mel = calculate_max_exit_latency(udev, state, hub_encoded_timeout);
49783b3db026SSarah Sharp 	if (mel < 0) {
49793b3db026SSarah Sharp 		/* Max Exit Latency is too big, disable LPM. */
49803b3db026SSarah Sharp 		hub_encoded_timeout = USB3_LPM_DISABLED;
49813b3db026SSarah Sharp 		mel = 0;
49823b3db026SSarah Sharp 	}
49833b3db026SSarah Sharp 
49843b3db026SSarah Sharp 	ret = xhci_change_max_exit_latency(xhci, udev, mel);
49853b3db026SSarah Sharp 	if (ret)
49863b3db026SSarah Sharp 		return ret;
49873b3db026SSarah Sharp 	return hub_encoded_timeout;
49883b3db026SSarah Sharp }
49893b3db026SSarah Sharp 
xhci_disable_usb3_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)49903969384cSLu Baolu static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
49913b3db026SSarah Sharp 			struct usb_device *udev, enum usb3_link_state state)
49923b3db026SSarah Sharp {
49933b3db026SSarah Sharp 	struct xhci_hcd	*xhci;
49943b3db026SSarah Sharp 	u16 mel;
49953b3db026SSarah Sharp 
49963b3db026SSarah Sharp 	xhci = hcd_to_xhci(hcd);
49973b3db026SSarah Sharp 	if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
49983b3db026SSarah Sharp 			!xhci->devs[udev->slot_id])
49993b3db026SSarah Sharp 		return 0;
50003b3db026SSarah Sharp 
50013b3db026SSarah Sharp 	mel = calculate_max_exit_latency(udev, state, USB3_LPM_DISABLED);
5002f1cda54cSSaurabh Karajgaonkar 	return xhci_change_max_exit_latency(xhci, udev, mel);
50033b3db026SSarah Sharp }
5004b01bcbf7SSarah Sharp #else /* CONFIG_PM */
5005b01bcbf7SSarah Sharp 
xhci_set_usb2_hardware_lpm(struct usb_hcd * hcd,struct usb_device * udev,int enable)50063969384cSLu Baolu static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
5007ceb6c9c8SRafael J. Wysocki 				struct usb_device *udev, int enable)
5008ceb6c9c8SRafael J. Wysocki {
5009ceb6c9c8SRafael J. Wysocki 	return 0;
5010ceb6c9c8SRafael J. Wysocki }
5011ceb6c9c8SRafael J. Wysocki 
xhci_update_device(struct usb_hcd * hcd,struct usb_device * udev)50123969384cSLu Baolu static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
5013ceb6c9c8SRafael J. Wysocki {
5014ceb6c9c8SRafael J. Wysocki 	return 0;
5015ceb6c9c8SRafael J. Wysocki }
5016ceb6c9c8SRafael J. Wysocki 
xhci_enable_usb3_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)50173969384cSLu Baolu static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
5018b01bcbf7SSarah Sharp 			struct usb_device *udev, enum usb3_link_state state)
5019b01bcbf7SSarah Sharp {
5020b01bcbf7SSarah Sharp 	return USB3_LPM_DISABLED;
5021b01bcbf7SSarah Sharp }
5022b01bcbf7SSarah Sharp 
xhci_disable_usb3_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)50233969384cSLu Baolu static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
5024b01bcbf7SSarah Sharp 			struct usb_device *udev, enum usb3_link_state state)
5025b01bcbf7SSarah Sharp {
5026b01bcbf7SSarah Sharp 	return 0;
5027b01bcbf7SSarah Sharp }
5028b01bcbf7SSarah Sharp #endif	/* CONFIG_PM */
5029b01bcbf7SSarah Sharp 
50303b3db026SSarah Sharp /*-------------------------------------------------------------------------*/
50313b3db026SSarah Sharp 
5032bc75fa38SAlex Chiang /* Once a hub descriptor is fetched for a device, we need to update the xHC's
5033bc75fa38SAlex Chiang  * internal data structures for the device.
5034bc75fa38SAlex Chiang  */
xhci_update_hub_device(struct usb_hcd * hcd,struct usb_device * hdev,struct usb_tt * tt,gfp_t mem_flags)503523a3b8d5SMathias Nyman int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
5036bc75fa38SAlex Chiang 			struct usb_tt *tt, gfp_t mem_flags)
5037bc75fa38SAlex Chiang {
5038bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5039bc75fa38SAlex Chiang 	struct xhci_virt_device *vdev;
5040bc75fa38SAlex Chiang 	struct xhci_command *config_cmd;
5041bc75fa38SAlex Chiang 	struct xhci_input_control_ctx *ctrl_ctx;
5042bc75fa38SAlex Chiang 	struct xhci_slot_ctx *slot_ctx;
5043bc75fa38SAlex Chiang 	unsigned long flags;
5044bc75fa38SAlex Chiang 	unsigned think_time;
5045bc75fa38SAlex Chiang 	int ret;
5046bc75fa38SAlex Chiang 
5047bc75fa38SAlex Chiang 	/* Ignore root hubs */
5048bc75fa38SAlex Chiang 	if (!hdev->parent)
5049bc75fa38SAlex Chiang 		return 0;
5050bc75fa38SAlex Chiang 
5051bc75fa38SAlex Chiang 	vdev = xhci->devs[hdev->slot_id];
5052bc75fa38SAlex Chiang 	if (!vdev) {
5053bc75fa38SAlex Chiang 		xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
5054bc75fa38SAlex Chiang 		return -EINVAL;
5055bc75fa38SAlex Chiang 	}
505674e0b564SLu Baolu 
505714d49b7aSMathias Nyman 	config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
505874e0b564SLu Baolu 	if (!config_cmd)
5059bc75fa38SAlex Chiang 		return -ENOMEM;
506074e0b564SLu Baolu 
50614daf9df5SLin Wang 	ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
506292f8e767SSarah Sharp 	if (!ctrl_ctx) {
506392f8e767SSarah Sharp 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
506492f8e767SSarah Sharp 				__func__);
506592f8e767SSarah Sharp 		xhci_free_command(xhci, config_cmd);
506692f8e767SSarah Sharp 		return -ENOMEM;
506792f8e767SSarah Sharp 	}
5068bc75fa38SAlex Chiang 
5069bc75fa38SAlex Chiang 	spin_lock_irqsave(&xhci->lock, flags);
5070839c817cSSarah Sharp 	if (hdev->speed == USB_SPEED_HIGH &&
5071839c817cSSarah Sharp 			xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
5072839c817cSSarah Sharp 		xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
5073839c817cSSarah Sharp 		xhci_free_command(xhci, config_cmd);
5074839c817cSSarah Sharp 		spin_unlock_irqrestore(&xhci->lock, flags);
5075839c817cSSarah Sharp 		return -ENOMEM;
5076839c817cSSarah Sharp 	}
5077839c817cSSarah Sharp 
5078bc75fa38SAlex Chiang 	xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
507928ccd296SMatt Evans 	ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
5080bc75fa38SAlex Chiang 	slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
508128ccd296SMatt Evans 	slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
5082096b110aSChunfeng Yun 	/*
5083096b110aSChunfeng Yun 	 * refer to section 6.2.2: MTT should be 0 for full speed hub,
5084096b110aSChunfeng Yun 	 * but it may be already set to 1 when setup an xHCI virtual
5085096b110aSChunfeng Yun 	 * device, so clear it anyway.
5086096b110aSChunfeng Yun 	 */
5087bc75fa38SAlex Chiang 	if (tt->multi)
508828ccd296SMatt Evans 		slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
5089096b110aSChunfeng Yun 	else if (hdev->speed == USB_SPEED_FULL)
5090096b110aSChunfeng Yun 		slot_ctx->dev_info &= cpu_to_le32(~DEV_MTT);
5091096b110aSChunfeng Yun 
5092bc75fa38SAlex Chiang 	if (xhci->hci_version > 0x95) {
5093bc75fa38SAlex Chiang 		xhci_dbg(xhci, "xHCI version %x needs hub "
5094bc75fa38SAlex Chiang 				"TT think time and number of ports\n",
5095bc75fa38SAlex Chiang 				(unsigned int) xhci->hci_version);
509628ccd296SMatt Evans 		slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
5097bc75fa38SAlex Chiang 		/* Set TT think time - convert from ns to FS bit times.
5098bc75fa38SAlex Chiang 		 * 0 = 8 FS bit times, 1 = 16 FS bit times,
5099bc75fa38SAlex Chiang 		 * 2 = 24 FS bit times, 3 = 32 FS bit times.
5100700b4173SAndiry Xu 		 *
5101700b4173SAndiry Xu 		 * xHCI 1.0: this field shall be 0 if the device is not a
5102700b4173SAndiry Xu 		 * High-spped hub.
5103bc75fa38SAlex Chiang 		 */
5104bc75fa38SAlex Chiang 		think_time = tt->think_time;
5105bc75fa38SAlex Chiang 		if (think_time != 0)
5106bc75fa38SAlex Chiang 			think_time = (think_time / 666) - 1;
5107700b4173SAndiry Xu 		if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
5108700b4173SAndiry Xu 			slot_ctx->tt_info |=
5109700b4173SAndiry Xu 				cpu_to_le32(TT_THINK_TIME(think_time));
5110bc75fa38SAlex Chiang 	} else {
5111bc75fa38SAlex Chiang 		xhci_dbg(xhci, "xHCI version %x doesn't need hub "
5112bc75fa38SAlex Chiang 				"TT think time or number of ports\n",
5113bc75fa38SAlex Chiang 				(unsigned int) xhci->hci_version);
5114bc75fa38SAlex Chiang 	}
5115bc75fa38SAlex Chiang 	slot_ctx->dev_state = 0;
5116bc75fa38SAlex Chiang 	spin_unlock_irqrestore(&xhci->lock, flags);
5117bc75fa38SAlex Chiang 
5118bc75fa38SAlex Chiang 	xhci_dbg(xhci, "Set up %s for hub device.\n",
5119bc75fa38SAlex Chiang 			(xhci->hci_version > 0x95) ?
5120bc75fa38SAlex Chiang 			"configure endpoint" : "evaluate context");
5121bc75fa38SAlex Chiang 
5122bc75fa38SAlex Chiang 	/* Issue and wait for the configure endpoint or
5123bc75fa38SAlex Chiang 	 * evaluate context command.
5124bc75fa38SAlex Chiang 	 */
5125bc75fa38SAlex Chiang 	if (xhci->hci_version > 0x95)
5126bc75fa38SAlex Chiang 		ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5127bc75fa38SAlex Chiang 				false, false);
5128bc75fa38SAlex Chiang 	else
5129bc75fa38SAlex Chiang 		ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5130bc75fa38SAlex Chiang 				true, false);
5131bc75fa38SAlex Chiang 
5132bc75fa38SAlex Chiang 	xhci_free_command(xhci, config_cmd);
5133bc75fa38SAlex Chiang 	return ret;
5134bc75fa38SAlex Chiang }
513523a3b8d5SMathias Nyman EXPORT_SYMBOL_GPL(xhci_update_hub_device);
5136bc75fa38SAlex Chiang 
xhci_get_frame(struct usb_hcd * hcd)51373969384cSLu Baolu static int xhci_get_frame(struct usb_hcd *hcd)
5138bc75fa38SAlex Chiang {
5139bc75fa38SAlex Chiang 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5140bc75fa38SAlex Chiang 	/* EHCI mods by the periodic size.  Why? */
5141b0ba9720SXenia Ragiadakou 	return readl(&xhci->run_regs->microframe_index) >> 3;
5142bc75fa38SAlex Chiang }
5143bc75fa38SAlex Chiang 
xhci_hcd_init_usb2_data(struct xhci_hcd * xhci,struct usb_hcd * hcd)514457f23cd0SHeiner Kallweit static void xhci_hcd_init_usb2_data(struct xhci_hcd *xhci, struct usb_hcd *hcd)
5145552e0c4fSSebastian Andrzej Siewior {
51469ea95eccSMathias Nyman 	xhci->usb2_rhub.hcd = hcd;
5147552e0c4fSSebastian Andrzej Siewior 	hcd->speed = HCD_USB2;
5148552e0c4fSSebastian Andrzej Siewior 	hcd->self.root_hub->speed = USB_SPEED_HIGH;
5149552e0c4fSSebastian Andrzej Siewior 	/*
5150552e0c4fSSebastian Andrzej Siewior 	 * USB 2.0 roothub under xHCI has an integrated TT,
5151552e0c4fSSebastian Andrzej Siewior 	 * (rate matching hub) as opposed to having an OHCI/UHCI
5152552e0c4fSSebastian Andrzej Siewior 	 * companion controller.
5153552e0c4fSSebastian Andrzej Siewior 	 */
5154552e0c4fSSebastian Andrzej Siewior 	hcd->has_tt = 1;
515557f23cd0SHeiner Kallweit }
515657f23cd0SHeiner Kallweit 
xhci_hcd_init_usb3_data(struct xhci_hcd * xhci,struct usb_hcd * hcd)515757f23cd0SHeiner Kallweit static void xhci_hcd_init_usb3_data(struct xhci_hcd *xhci, struct usb_hcd *hcd)
515857f23cd0SHeiner Kallweit {
515957f23cd0SHeiner Kallweit 	unsigned int minor_rev;
516057f23cd0SHeiner Kallweit 
51610ee78c10SMathias Nyman 	/*
516247f50d61SMathias Nyman 	 * Early xHCI 1.1 spec did not mention USB 3.1 capable hosts
516347f50d61SMathias Nyman 	 * should return 0x31 for sbrn, or that the minor revision
516447f50d61SMathias Nyman 	 * is a two digit BCD containig minor and sub-minor numbers.
516547f50d61SMathias Nyman 	 * This was later clarified in xHCI 1.2.
516647f50d61SMathias Nyman 	 *
516747f50d61SMathias Nyman 	 * Some USB 3.1 capable hosts therefore have sbrn 0x30, and
516847f50d61SMathias Nyman 	 * minor revision set to 0x1 instead of 0x10.
51690ee78c10SMathias Nyman 	 */
517047f50d61SMathias Nyman 	if (xhci->usb3_rhub.min_rev == 0x1)
517147f50d61SMathias Nyman 		minor_rev = 1;
517247f50d61SMathias Nyman 	else
5173ddd57980SMathias Nyman 		minor_rev = xhci->usb3_rhub.min_rev / 0x10;
5174ddd57980SMathias Nyman 
5175ddd57980SMathias Nyman 	switch (minor_rev) {
5176ddd57980SMathias Nyman 	case 2:
5177ddd57980SMathias Nyman 		hcd->speed = HCD_USB32;
5178ddd57980SMathias Nyman 		hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5179ddd57980SMathias Nyman 		hcd->self.root_hub->rx_lanes = 2;
5180ddd57980SMathias Nyman 		hcd->self.root_hub->tx_lanes = 2;
5181cd8d66cfSThinh Nguyen 		hcd->self.root_hub->ssp_rate = USB_SSP_GEN_2x2;
5182ddd57980SMathias Nyman 		break;
5183ddd57980SMathias Nyman 	case 1:
5184b50107bbSMathias Nyman 		hcd->speed = HCD_USB31;
51852c0e06f8SMathias Nyman 		hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5186cd8d66cfSThinh Nguyen 		hcd->self.root_hub->ssp_rate = USB_SSP_GEN_2x1;
5187ddd57980SMathias Nyman 		break;
5188b50107bbSMathias Nyman 	}
51890ee78c10SMathias Nyman 	xhci_info(xhci, "Host supports USB 3.%x %sSuperSpeed\n",
519057f23cd0SHeiner Kallweit 		  minor_rev, minor_rev ? "Enhanced " : "");
51910ee78c10SMathias Nyman 
51929ea95eccSMathias Nyman 	xhci->usb3_rhub.hcd = hcd;
519357f23cd0SHeiner Kallweit }
519457f23cd0SHeiner Kallweit 
xhci_gen_setup(struct usb_hcd * hcd,xhci_get_quirks_t get_quirks)519557f23cd0SHeiner Kallweit int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
519657f23cd0SHeiner Kallweit {
519757f23cd0SHeiner Kallweit 	struct xhci_hcd		*xhci;
519857f23cd0SHeiner Kallweit 	/*
519957f23cd0SHeiner Kallweit 	 * TODO: Check with DWC3 clients for sysdev according to
520057f23cd0SHeiner Kallweit 	 * quirks
5201552e0c4fSSebastian Andrzej Siewior 	 */
520257f23cd0SHeiner Kallweit 	struct device		*dev = hcd->self.sysdev;
520357f23cd0SHeiner Kallweit 	int			retval;
520457f23cd0SHeiner Kallweit 
520557f23cd0SHeiner Kallweit 	/* Accept arbitrarily long scatter-gather lists */
520657f23cd0SHeiner Kallweit 	hcd->self.sg_tablesize = ~0;
520757f23cd0SHeiner Kallweit 
520857f23cd0SHeiner Kallweit 	/* support to build packet from discontinuous buffers */
520957f23cd0SHeiner Kallweit 	hcd->self.no_sg_constraint = 1;
521057f23cd0SHeiner Kallweit 
521157f23cd0SHeiner Kallweit 	/* XHCI controllers don't stop the ep queue on short packets :| */
521257f23cd0SHeiner Kallweit 	hcd->self.no_stop_on_short = 1;
521357f23cd0SHeiner Kallweit 
521457f23cd0SHeiner Kallweit 	xhci = hcd_to_xhci(hcd);
521557f23cd0SHeiner Kallweit 
5216873f3236SHeiner Kallweit 	if (!usb_hcd_is_primary_hcd(hcd)) {
521757f23cd0SHeiner Kallweit 		xhci_hcd_init_usb3_data(xhci, hcd);
5218552e0c4fSSebastian Andrzej Siewior 		return 0;
5219552e0c4fSSebastian Andrzej Siewior 	}
5220552e0c4fSSebastian Andrzej Siewior 
5221a00918d0SChris Bainbridge 	mutex_init(&xhci->mutex);
522257f23cd0SHeiner Kallweit 	xhci->main_hcd = hcd;
5223552e0c4fSSebastian Andrzej Siewior 	xhci->cap_regs = hcd->regs;
5224552e0c4fSSebastian Andrzej Siewior 	xhci->op_regs = hcd->regs +
5225b0ba9720SXenia Ragiadakou 		HC_LENGTH(readl(&xhci->cap_regs->hc_capbase));
5226552e0c4fSSebastian Andrzej Siewior 	xhci->run_regs = hcd->regs +
5227b0ba9720SXenia Ragiadakou 		(readl(&xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
5228552e0c4fSSebastian Andrzej Siewior 	/* Cache read-only capability registers */
5229b0ba9720SXenia Ragiadakou 	xhci->hcs_params1 = readl(&xhci->cap_regs->hcs_params1);
5230b0ba9720SXenia Ragiadakou 	xhci->hcs_params2 = readl(&xhci->cap_regs->hcs_params2);
5231b0ba9720SXenia Ragiadakou 	xhci->hcs_params3 = readl(&xhci->cap_regs->hcs_params3);
5232c63d5757SLinyu Yuan 	xhci->hci_version = HC_VERSION(readl(&xhci->cap_regs->hc_capbase));
5233b0ba9720SXenia Ragiadakou 	xhci->hcc_params = readl(&xhci->cap_regs->hcc_params);
523404abb6deSLu Baolu 	if (xhci->hci_version > 0x100)
523504abb6deSLu Baolu 		xhci->hcc_params2 = readl(&xhci->cap_regs->hcc_params2);
5236552e0c4fSSebastian Andrzej Siewior 
5237b17a57f8SMathias Nyman 	/* xhci-plat or xhci-pci might have set max_interrupters already */
5238b17a57f8SMathias Nyman 	if ((!xhci->max_interrupters) ||
5239b17a57f8SMathias Nyman 	    xhci->max_interrupters > HCS_MAX_INTRS(xhci->hcs_params1))
5240b17a57f8SMathias Nyman 		xhci->max_interrupters = HCS_MAX_INTRS(xhci->hcs_params1);
5241b17a57f8SMathias Nyman 
5242757de492SMathias Nyman 	xhci->quirks |= quirks;
52434e6a1ee7STakashi Iwai 
52449b907c91SMathias Nyman 	if (get_quirks)
5245552e0c4fSSebastian Andrzej Siewior 		get_quirks(dev, xhci);
5246552e0c4fSSebastian Andrzej Siewior 
524707f3cb7cSGeorge Cherian 	/* In xhci controllers which follow xhci 1.0 spec gives a spurious
524807f3cb7cSGeorge Cherian 	 * success event after a short transfer. This quirk will ignore such
524907f3cb7cSGeorge Cherian 	 * spurious event.
525007f3cb7cSGeorge Cherian 	 */
525107f3cb7cSGeorge Cherian 	if (xhci->hci_version > 0x96)
525207f3cb7cSGeorge Cherian 		xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
525307f3cb7cSGeorge Cherian 
5254552e0c4fSSebastian Andrzej Siewior 	/* Make sure the HC is halted. */
5255552e0c4fSSebastian Andrzej Siewior 	retval = xhci_halt(xhci);
5256552e0c4fSSebastian Andrzej Siewior 	if (retval)
5257cd33a321SRoger Quadros 		return retval;
5258552e0c4fSSebastian Andrzej Siewior 
525912de0a35SMarc Zyngier 	xhci_zero_64b_regs(xhci);
526012de0a35SMarc Zyngier 
5261552e0c4fSSebastian Andrzej Siewior 	xhci_dbg(xhci, "Resetting HCD\n");
5262552e0c4fSSebastian Andrzej Siewior 	/* Reset the internal HC memory state and registers. */
526314073ce9SMathias Nyman 	retval = xhci_reset(xhci, XHCI_RESET_LONG_USEC);
5264552e0c4fSSebastian Andrzej Siewior 	if (retval)
5265cd33a321SRoger Quadros 		return retval;
5266552e0c4fSSebastian Andrzej Siewior 	xhci_dbg(xhci, "Reset complete\n");
5267552e0c4fSSebastian Andrzej Siewior 
52680a380be8SYoshihiro Shimoda 	/*
52690a380be8SYoshihiro Shimoda 	 * On some xHCI controllers (e.g. R-Car SoCs), the AC64 bit (bit 0)
52700a380be8SYoshihiro Shimoda 	 * of HCCPARAMS1 is set to 1. However, the xHCs don't support 64-bit
52710a380be8SYoshihiro Shimoda 	 * address memory pointers actually. So, this driver clears the AC64
52720a380be8SYoshihiro Shimoda 	 * bit of xhci->hcc_params to call dma_set_coherent_mask(dev,
52730a380be8SYoshihiro Shimoda 	 * DMA_BIT_MASK(32)) in this xhci_gen_setup().
52740a380be8SYoshihiro Shimoda 	 */
52750a380be8SYoshihiro Shimoda 	if (xhci->quirks & XHCI_NO_64BIT_SUPPORT)
52760a380be8SYoshihiro Shimoda 		xhci->hcc_params &= ~BIT(0);
52770a380be8SYoshihiro Shimoda 
5278c10cf118SXenia Ragiadakou 	/* Set dma_mask and coherent_dma_mask to 64-bits,
5279c10cf118SXenia Ragiadakou 	 * if xHC supports 64-bit addressing */
5280c10cf118SXenia Ragiadakou 	if (HCC_64BIT_ADDR(xhci->hcc_params) &&
5281c10cf118SXenia Ragiadakou 			!dma_set_mask(dev, DMA_BIT_MASK(64))) {
5282552e0c4fSSebastian Andrzej Siewior 		xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
5283c10cf118SXenia Ragiadakou 		dma_set_coherent_mask(dev, DMA_BIT_MASK(64));
5284fda182d8SDuc Dang 	} else {
5285fda182d8SDuc Dang 		/*
5286fda182d8SDuc Dang 		 * This is to avoid error in cases where a 32-bit USB
5287fda182d8SDuc Dang 		 * controller is used on a 64-bit capable system.
5288fda182d8SDuc Dang 		 */
5289fda182d8SDuc Dang 		retval = dma_set_mask(dev, DMA_BIT_MASK(32));
5290fda182d8SDuc Dang 		if (retval)
5291fda182d8SDuc Dang 			return retval;
5292fda182d8SDuc Dang 		xhci_dbg(xhci, "Enabling 32-bit DMA addresses.\n");
5293fda182d8SDuc Dang 		dma_set_coherent_mask(dev, DMA_BIT_MASK(32));
5294552e0c4fSSebastian Andrzej Siewior 	}
5295552e0c4fSSebastian Andrzej Siewior 
5296552e0c4fSSebastian Andrzej Siewior 	xhci_dbg(xhci, "Calling HCD init\n");
5297552e0c4fSSebastian Andrzej Siewior 	/* Initialize HCD and host controller data structures. */
5298552e0c4fSSebastian Andrzej Siewior 	retval = xhci_init(hcd);
5299552e0c4fSSebastian Andrzej Siewior 	if (retval)
5300cd33a321SRoger Quadros 		return retval;
5301552e0c4fSSebastian Andrzej Siewior 	xhci_dbg(xhci, "Called HCD init\n");
530299705092SHans de Goede 
5303873f3236SHeiner Kallweit 	if (xhci_hcd_is_usb3(hcd))
5304873f3236SHeiner Kallweit 		xhci_hcd_init_usb3_data(xhci, hcd);
5305873f3236SHeiner Kallweit 	else
5306873f3236SHeiner Kallweit 		xhci_hcd_init_usb2_data(xhci, hcd);
5307873f3236SHeiner Kallweit 
530836b68579SMarc Zyngier 	xhci_info(xhci, "hcc params 0x%08x hci version 0x%x quirks 0x%016llx\n",
530999705092SHans de Goede 		  xhci->hcc_params, xhci->hci_version, xhci->quirks);
531099705092SHans de Goede 
5311552e0c4fSSebastian Andrzej Siewior 	return 0;
5312552e0c4fSSebastian Andrzej Siewior }
5313436e8c7dSAndrew Bresticker EXPORT_SYMBOL_GPL(xhci_gen_setup);
5314552e0c4fSSebastian Andrzej Siewior 
xhci_clear_tt_buffer_complete(struct usb_hcd * hcd,struct usb_host_endpoint * ep)5315ef513be0SJim Lin static void xhci_clear_tt_buffer_complete(struct usb_hcd *hcd,
5316ef513be0SJim Lin 		struct usb_host_endpoint *ep)
5317ef513be0SJim Lin {
5318ef513be0SJim Lin 	struct xhci_hcd *xhci;
5319ef513be0SJim Lin 	struct usb_device *udev;
5320ef513be0SJim Lin 	unsigned int slot_id;
5321ef513be0SJim Lin 	unsigned int ep_index;
5322ef513be0SJim Lin 	unsigned long flags;
5323ef513be0SJim Lin 
5324ef513be0SJim Lin 	xhci = hcd_to_xhci(hcd);
532518b74067SMathias Nyman 
532618b74067SMathias Nyman 	spin_lock_irqsave(&xhci->lock, flags);
5327ef513be0SJim Lin 	udev = (struct usb_device *)ep->hcpriv;
5328ef513be0SJim Lin 	slot_id = udev->slot_id;
5329ef513be0SJim Lin 	ep_index = xhci_get_endpoint_index(&ep->desc);
5330ef513be0SJim Lin 
5331ef513be0SJim Lin 	xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_CLEARING_TT;
5332ef513be0SJim Lin 	xhci_ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
5333ef513be0SJim Lin 	spin_unlock_irqrestore(&xhci->lock, flags);
5334ef513be0SJim Lin }
5335ef513be0SJim Lin 
53361885d9a3SAndrew Bresticker static const struct hc_driver xhci_hc_driver = {
53371885d9a3SAndrew Bresticker 	.description =		"xhci-hcd",
53381885d9a3SAndrew Bresticker 	.product_desc =		"xHCI Host Controller",
533932479d4bSYoshihiro Shimoda 	.hcd_priv_size =	sizeof(struct xhci_hcd),
53401885d9a3SAndrew Bresticker 
53411885d9a3SAndrew Bresticker 	/*
53421885d9a3SAndrew Bresticker 	 * generic hardware linkage
53431885d9a3SAndrew Bresticker 	 */
53441885d9a3SAndrew Bresticker 	.irq =			xhci_irq,
534536dc0165SSuwan Kim 	.flags =		HCD_MEMORY | HCD_DMA | HCD_USB3 | HCD_SHARED |
534636dc0165SSuwan Kim 				HCD_BH,
53471885d9a3SAndrew Bresticker 
53481885d9a3SAndrew Bresticker 	/*
53491885d9a3SAndrew Bresticker 	 * basic lifecycle operations
53501885d9a3SAndrew Bresticker 	 */
53511885d9a3SAndrew Bresticker 	.reset =		NULL, /* set in xhci_init_driver() */
53521885d9a3SAndrew Bresticker 	.start =		xhci_run,
53531885d9a3SAndrew Bresticker 	.stop =			xhci_stop,
53541885d9a3SAndrew Bresticker 	.shutdown =		xhci_shutdown,
53551885d9a3SAndrew Bresticker 
53561885d9a3SAndrew Bresticker 	/*
53571885d9a3SAndrew Bresticker 	 * managing i/o requests and associated device resources
53581885d9a3SAndrew Bresticker 	 */
535933e39350SNicolas Saenz Julienne 	.map_urb_for_dma =      xhci_map_urb_for_dma,
53602017a1e5STejas Joglekar 	.unmap_urb_for_dma =    xhci_unmap_urb_for_dma,
53611885d9a3SAndrew Bresticker 	.urb_enqueue =		xhci_urb_enqueue,
53621885d9a3SAndrew Bresticker 	.urb_dequeue =		xhci_urb_dequeue,
53631885d9a3SAndrew Bresticker 	.alloc_dev =		xhci_alloc_dev,
53641885d9a3SAndrew Bresticker 	.free_dev =		xhci_free_dev,
53651885d9a3SAndrew Bresticker 	.alloc_streams =	xhci_alloc_streams,
53661885d9a3SAndrew Bresticker 	.free_streams =		xhci_free_streams,
53671885d9a3SAndrew Bresticker 	.add_endpoint =		xhci_add_endpoint,
53681885d9a3SAndrew Bresticker 	.drop_endpoint =	xhci_drop_endpoint,
536918b74067SMathias Nyman 	.endpoint_disable =	xhci_endpoint_disable,
53701885d9a3SAndrew Bresticker 	.endpoint_reset =	xhci_endpoint_reset,
53711885d9a3SAndrew Bresticker 	.check_bandwidth =	xhci_check_bandwidth,
53721885d9a3SAndrew Bresticker 	.reset_bandwidth =	xhci_reset_bandwidth,
53731885d9a3SAndrew Bresticker 	.address_device =	xhci_address_device,
53741885d9a3SAndrew Bresticker 	.enable_device =	xhci_enable_device,
53751885d9a3SAndrew Bresticker 	.update_hub_device =	xhci_update_hub_device,
53761885d9a3SAndrew Bresticker 	.reset_device =		xhci_discover_or_reset_device,
53771885d9a3SAndrew Bresticker 
53781885d9a3SAndrew Bresticker 	/*
53791885d9a3SAndrew Bresticker 	 * scheduling support
53801885d9a3SAndrew Bresticker 	 */
53811885d9a3SAndrew Bresticker 	.get_frame_number =	xhci_get_frame,
53821885d9a3SAndrew Bresticker 
53831885d9a3SAndrew Bresticker 	/*
53841885d9a3SAndrew Bresticker 	 * root hub support
53851885d9a3SAndrew Bresticker 	 */
53861885d9a3SAndrew Bresticker 	.hub_control =		xhci_hub_control,
53871885d9a3SAndrew Bresticker 	.hub_status_data =	xhci_hub_status_data,
53881885d9a3SAndrew Bresticker 	.bus_suspend =		xhci_bus_suspend,
53891885d9a3SAndrew Bresticker 	.bus_resume =		xhci_bus_resume,
53908f9cc83cSAlan Stern 	.get_resuming_ports =	xhci_get_resuming_ports,
53911885d9a3SAndrew Bresticker 
53921885d9a3SAndrew Bresticker 	/*
53931885d9a3SAndrew Bresticker 	 * call back when device connected and addressed
53941885d9a3SAndrew Bresticker 	 */
53951885d9a3SAndrew Bresticker 	.update_device =        xhci_update_device,
53961885d9a3SAndrew Bresticker 	.set_usb2_hw_lpm =	xhci_set_usb2_hardware_lpm,
53971885d9a3SAndrew Bresticker 	.enable_usb3_lpm_timeout =	xhci_enable_usb3_lpm_timeout,
53981885d9a3SAndrew Bresticker 	.disable_usb3_lpm_timeout =	xhci_disable_usb3_lpm_timeout,
53991885d9a3SAndrew Bresticker 	.find_raw_port_number =	xhci_find_raw_port_number,
5400ef513be0SJim Lin 	.clear_tt_buffer_complete = xhci_clear_tt_buffer_complete,
54011885d9a3SAndrew Bresticker };
54021885d9a3SAndrew Bresticker 
xhci_init_driver(struct hc_driver * drv,const struct xhci_driver_overrides * over)5403cd33a321SRoger Quadros void xhci_init_driver(struct hc_driver *drv,
5404cd33a321SRoger Quadros 		      const struct xhci_driver_overrides *over)
54051885d9a3SAndrew Bresticker {
5406cd33a321SRoger Quadros 	BUG_ON(!over);
5407cd33a321SRoger Quadros 
5408cd33a321SRoger Quadros 	/* Copy the generic table to drv then apply the overrides */
54091885d9a3SAndrew Bresticker 	*drv = xhci_hc_driver;
5410cd33a321SRoger Quadros 
5411cd33a321SRoger Quadros 	if (over) {
5412cd33a321SRoger Quadros 		drv->hcd_priv_size += over->extra_priv_size;
5413cd33a321SRoger Quadros 		if (over->reset)
5414cd33a321SRoger Quadros 			drv->reset = over->reset;
5415cd33a321SRoger Quadros 		if (over->start)
5416cd33a321SRoger Quadros 			drv->start = over->start;
541714295a15SChunfeng Yun 		if (over->add_endpoint)
541814295a15SChunfeng Yun 			drv->add_endpoint = over->add_endpoint;
541914295a15SChunfeng Yun 		if (over->drop_endpoint)
542014295a15SChunfeng Yun 			drv->drop_endpoint = over->drop_endpoint;
54211d69f9d9SIkjoon Jang 		if (over->check_bandwidth)
54221d69f9d9SIkjoon Jang 			drv->check_bandwidth = over->check_bandwidth;
54231d69f9d9SIkjoon Jang 		if (over->reset_bandwidth)
54241d69f9d9SIkjoon Jang 			drv->reset_bandwidth = over->reset_bandwidth;
542523a3b8d5SMathias Nyman 		if (over->update_hub_device)
542623a3b8d5SMathias Nyman 			drv->update_hub_device = over->update_hub_device;
5427592338ddSJim Lin 		if (over->hub_control)
5428592338ddSJim Lin 			drv->hub_control = over->hub_control;
5429cd33a321SRoger Quadros 	}
54301885d9a3SAndrew Bresticker }
54311885d9a3SAndrew Bresticker EXPORT_SYMBOL_GPL(xhci_init_driver);
54321885d9a3SAndrew Bresticker 
5433bc75fa38SAlex Chiang MODULE_DESCRIPTION(DRIVER_DESC);
5434bc75fa38SAlex Chiang MODULE_AUTHOR(DRIVER_AUTHOR);
5435bc75fa38SAlex Chiang MODULE_LICENSE("GPL");
5436bc75fa38SAlex Chiang 
xhci_hcd_init(void)5437bc75fa38SAlex Chiang static int __init xhci_hcd_init(void)
5438bc75fa38SAlex Chiang {
5439bc75fa38SAlex Chiang 	/*
5440bc75fa38SAlex Chiang 	 * Check the compiler generated sizes of structures that must be laid
5441bc75fa38SAlex Chiang 	 * out in specific ways for hardware access.
5442bc75fa38SAlex Chiang 	 */
5443bc75fa38SAlex Chiang 	BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
5444bc75fa38SAlex Chiang 	BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
5445bc75fa38SAlex Chiang 	BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
5446bc75fa38SAlex Chiang 	/* xhci_device_control has eight fields, and also
5447bc75fa38SAlex Chiang 	 * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
5448bc75fa38SAlex Chiang 	 */
5449bc75fa38SAlex Chiang 	BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
5450bc75fa38SAlex Chiang 	BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
5451bc75fa38SAlex Chiang 	BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
545204abb6deSLu Baolu 	BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 8*32/8);
5453bc75fa38SAlex Chiang 	BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
5454bc75fa38SAlex Chiang 	/* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
5455bc75fa38SAlex Chiang 	BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
54561eaf35e4SOliver Neukum 
54571eaf35e4SOliver Neukum 	if (usb_disabled())
54581eaf35e4SOliver Neukum 		return -ENODEV;
54591eaf35e4SOliver Neukum 
546002b6fdc2SLu Baolu 	xhci_debugfs_create_root();
54616aec5000SMathias Nyman 	xhci_dbc_init();
546202b6fdc2SLu Baolu 
5463bc75fa38SAlex Chiang 	return 0;
5464bc75fa38SAlex Chiang }
5465b04c846cSArthur Demchenkov 
5466b04c846cSArthur Demchenkov /*
5467b04c846cSArthur Demchenkov  * If an init function is provided, an exit function must also be provided
5468b04c846cSArthur Demchenkov  * to allow module unload.
5469b04c846cSArthur Demchenkov  */
xhci_hcd_fini(void)547002b6fdc2SLu Baolu static void __exit xhci_hcd_fini(void)
547102b6fdc2SLu Baolu {
547202b6fdc2SLu Baolu 	xhci_debugfs_remove_root();
54736aec5000SMathias Nyman 	xhci_dbc_exit();
547402b6fdc2SLu Baolu }
5475b04c846cSArthur Demchenkov 
5476bc75fa38SAlex Chiang module_init(xhci_hcd_init);
5477b04c846cSArthur Demchenkov module_exit(xhci_hcd_fini);
5478