xref: /linux/drivers/usb/host/xhci.c (revision aaa8f2e959341fd4a3ccf111500eb1e6176678e0)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * xHCI host controller driver
4  *
5  * Copyright (C) 2008 Intel Corp.
6  *
7  * Author: Sarah Sharp
8  * Some code borrowed from the Linux EHCI driver.
9  */
10 
11 #include <linux/jiffies.h>
12 #include <linux/pci.h>
13 #include <linux/iommu.h>
14 #include <linux/iopoll.h>
15 #include <linux/irq.h>
16 #include <linux/log2.h>
17 #include <linux/module.h>
18 #include <linux/moduleparam.h>
19 #include <linux/slab.h>
20 #include <linux/string_choices.h>
21 #include <linux/dmi.h>
22 #include <linux/dma-mapping.h>
23 #include <linux/usb/xhci-sideband.h>
24 
25 #include "xhci.h"
26 #include "xhci-trace.h"
27 #include "xhci-debugfs.h"
28 #include "xhci-dbgcap.h"
29 
30 #define DRIVER_AUTHOR "Sarah Sharp"
31 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
32 
33 #define	PORT_WAKE_BITS	(PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E)
34 
35 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
36 static int link_quirk;
37 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
38 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
39 
40 static unsigned long long quirks;
41 module_param(quirks, ullong, S_IRUGO);
42 MODULE_PARM_DESC(quirks, "Bit flags for quirks to be enabled as default");
43 
44 static bool td_on_ring(struct xhci_td *td, struct xhci_ring *ring)
45 {
46 	struct xhci_segment *seg;
47 
48 	if (!td || !td->start_seg)
49 		return false;
50 
51 	xhci_for_each_ring_seg(ring->first_seg, seg) {
52 		if (seg == td->start_seg)
53 			return true;
54 	}
55 
56 	return false;
57 }
58 
59 /*
60  * xhci_handshake - spin reading hc until handshake completes or fails
61  * @ptr: address of hc register to be read
62  * @mask: bits to look at in result of read
63  * @done: value of those bits when handshake succeeds
64  * @usec: timeout in microseconds
65  *
66  * Returns negative errno, or zero on success
67  *
68  * Success happens when the "mask" bits have the specified value (hardware
69  * handshake done).  There are two failure modes:  "usec" have passed (major
70  * hardware flakeout), or the register reads as all-ones (hardware removed).
71  */
72 int xhci_handshake(void __iomem *ptr, u32 mask, u32 done, u64 timeout_us)
73 {
74 	u32	result;
75 	int	ret;
76 
77 	ret = readl_poll_timeout_atomic(ptr, result,
78 					(result & mask) == done ||
79 					result == U32_MAX,
80 					1, timeout_us);
81 	if (result == U32_MAX)		/* card removed */
82 		return -ENODEV;
83 
84 	return ret;
85 }
86 
87 /*
88  * xhci_handshake_check_state - same as xhci_handshake but takes an additional
89  * exit_state parameter, and bails out with an error immediately when xhc_state
90  * has exit_state flag set.
91  */
92 int xhci_handshake_check_state(struct xhci_hcd *xhci, void __iomem *ptr,
93 		u32 mask, u32 done, int usec, unsigned int exit_state)
94 {
95 	u32	result;
96 	int	ret;
97 
98 	ret = readl_poll_timeout_atomic(ptr, result,
99 				(result & mask) == done ||
100 				result == U32_MAX ||
101 				xhci->xhc_state & exit_state,
102 				1, usec);
103 
104 	if (result == U32_MAX || xhci->xhc_state & exit_state)
105 		return -ENODEV;
106 
107 	return ret;
108 }
109 
110 /*
111  * Disable interrupts and begin the xHCI halting process.
112  */
113 void xhci_quiesce(struct xhci_hcd *xhci)
114 {
115 	u32 halted;
116 	u32 cmd;
117 	u32 mask;
118 
119 	mask = ~(XHCI_IRQS);
120 	halted = readl(&xhci->op_regs->status) & STS_HALT;
121 	if (!halted)
122 		mask &= ~CMD_RUN;
123 
124 	cmd = readl(&xhci->op_regs->command);
125 	cmd &= mask;
126 	writel(cmd, &xhci->op_regs->command);
127 }
128 
129 /*
130  * Force HC into halt state.
131  *
132  * Disable any IRQs and clear the run/stop bit.
133  * HC will complete any current and actively pipelined transactions, and
134  * should halt within 16 ms of the run/stop bit being cleared.
135  * Read HC Halted bit in the status register to see when the HC is finished.
136  */
137 int xhci_halt(struct xhci_hcd *xhci)
138 {
139 	int ret;
140 
141 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Halt the HC");
142 	xhci_quiesce(xhci);
143 
144 	ret = xhci_handshake(&xhci->op_regs->status,
145 			STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
146 	if (ret) {
147 		xhci_warn(xhci, "Host halt failed, %d\n", ret);
148 		return ret;
149 	}
150 
151 	xhci->xhc_state |= XHCI_STATE_HALTED;
152 	xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
153 
154 	return ret;
155 }
156 
157 /*
158  * Set the run bit and wait for the host to be running.
159  */
160 int xhci_start(struct xhci_hcd *xhci)
161 {
162 	u32 temp;
163 	int ret;
164 
165 	temp = readl(&xhci->op_regs->command);
166 	temp |= (CMD_RUN);
167 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Turn on HC, cmd = 0x%x.",
168 			temp);
169 	writel(temp, &xhci->op_regs->command);
170 
171 	/*
172 	 * Wait for the HCHalted Status bit to be 0 to indicate the host is
173 	 * running.
174 	 */
175 	ret = xhci_handshake(&xhci->op_regs->status,
176 			STS_HALT, 0, XHCI_MAX_HALT_USEC);
177 	if (ret == -ETIMEDOUT)
178 		xhci_err(xhci, "Host took too long to start, "
179 				"waited %u microseconds.\n",
180 				XHCI_MAX_HALT_USEC);
181 	if (!ret) {
182 		/* clear state flags. Including dying, halted or removing */
183 		xhci->xhc_state = 0;
184 		xhci->run_graceperiod = jiffies + msecs_to_jiffies(500);
185 	}
186 
187 	return ret;
188 }
189 
190 /*
191  * Reset a halted HC.
192  *
193  * This resets pipelines, timers, counters, state machines, etc.
194  * Transactions will be terminated immediately, and operational registers
195  * will be set to their defaults.
196  */
197 int xhci_reset(struct xhci_hcd *xhci, u64 timeout_us)
198 {
199 	u32 command;
200 	u32 state;
201 	int ret;
202 
203 	state = readl(&xhci->op_regs->status);
204 
205 	if (state == ~(u32)0) {
206 		xhci_warn(xhci, "Host not accessible, reset failed.\n");
207 		return -ENODEV;
208 	}
209 
210 	if ((state & STS_HALT) == 0) {
211 		xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
212 		return 0;
213 	}
214 
215 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Reset the HC");
216 	command = readl(&xhci->op_regs->command);
217 	command |= CMD_RESET;
218 	writel(command, &xhci->op_regs->command);
219 
220 	/* Existing Intel xHCI controllers require a delay of 1 mS,
221 	 * after setting the CMD_RESET bit, and before accessing any
222 	 * HC registers. This allows the HC to complete the
223 	 * reset operation and be ready for HC register access.
224 	 * Without this delay, the subsequent HC register access,
225 	 * may result in a system hang very rarely.
226 	 */
227 	if (xhci->quirks & XHCI_INTEL_HOST)
228 		udelay(1000);
229 
230 	ret = xhci_handshake_check_state(xhci, &xhci->op_regs->command,
231 				CMD_RESET, 0, timeout_us, XHCI_STATE_REMOVING);
232 	if (ret)
233 		return ret;
234 
235 	if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
236 		usb_asmedia_modifyflowcontrol(to_pci_dev(xhci_to_hcd(xhci)->self.controller));
237 
238 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
239 			 "Wait for controller to be ready for doorbell rings");
240 	/*
241 	 * xHCI cannot write to any doorbells or operational registers other
242 	 * than status until the "Controller Not Ready" flag is cleared.
243 	 */
244 	ret = xhci_handshake(&xhci->op_regs->status, STS_CNR, 0, timeout_us);
245 
246 	xhci->usb2_rhub.bus_state.port_c_suspend = 0;
247 	xhci->usb2_rhub.bus_state.suspended_ports = 0;
248 	xhci->usb2_rhub.bus_state.resuming_ports = 0;
249 	xhci->usb3_rhub.bus_state.port_c_suspend = 0;
250 	xhci->usb3_rhub.bus_state.suspended_ports = 0;
251 	xhci->usb3_rhub.bus_state.resuming_ports = 0;
252 
253 	return ret;
254 }
255 
256 static void xhci_zero_64b_regs(struct xhci_hcd *xhci)
257 {
258 	struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
259 	struct iommu_domain *domain;
260 	int err, i;
261 	u64 val;
262 	u32 intrs;
263 
264 	/*
265 	 * Some Renesas controllers get into a weird state if they are
266 	 * reset while programmed with 64bit addresses (they will preserve
267 	 * the top half of the address in internal, non visible
268 	 * registers). You end up with half the address coming from the
269 	 * kernel, and the other half coming from the firmware. Also,
270 	 * changing the programming leads to extra accesses even if the
271 	 * controller is supposed to be halted. The controller ends up with
272 	 * a fatal fault, and is then ripe for being properly reset.
273 	 *
274 	 * Special care is taken to only apply this if the device is behind
275 	 * an iommu. Doing anything when there is no iommu is definitely
276 	 * unsafe...
277 	 */
278 	domain = iommu_get_domain_for_dev(dev);
279 	if (!(xhci->quirks & XHCI_ZERO_64B_REGS) || !domain ||
280 	    domain->type == IOMMU_DOMAIN_IDENTITY)
281 		return;
282 
283 	xhci_info(xhci, "Zeroing 64bit base registers, expecting fault\n");
284 
285 	/* Clear HSEIE so that faults do not get signaled */
286 	val = readl(&xhci->op_regs->command);
287 	val &= ~CMD_HSEIE;
288 	writel(val, &xhci->op_regs->command);
289 
290 	/* Clear HSE (aka FATAL) */
291 	val = readl(&xhci->op_regs->status);
292 	val |= STS_FATAL;
293 	writel(val, &xhci->op_regs->status);
294 
295 	/* Now zero the registers, and brace for impact */
296 	val = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
297 	if (upper_32_bits(val))
298 		xhci_write_64(xhci, 0, &xhci->op_regs->dcbaa_ptr);
299 	val = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
300 	if (upper_32_bits(val))
301 		xhci_write_64(xhci, 0, &xhci->op_regs->cmd_ring);
302 
303 	intrs = min_t(u32, HCS_MAX_INTRS(xhci->hcs_params1),
304 		      ARRAY_SIZE(xhci->run_regs->ir_set));
305 
306 	for (i = 0; i < intrs; i++) {
307 		struct xhci_intr_reg __iomem *ir;
308 
309 		ir = &xhci->run_regs->ir_set[i];
310 		val = xhci_read_64(xhci, &ir->erst_base);
311 		if (upper_32_bits(val))
312 			xhci_write_64(xhci, 0, &ir->erst_base);
313 		val= xhci_read_64(xhci, &ir->erst_dequeue);
314 		if (upper_32_bits(val))
315 			xhci_write_64(xhci, 0, &ir->erst_dequeue);
316 	}
317 
318 	/* Wait for the fault to appear. It will be cleared on reset */
319 	err = xhci_handshake(&xhci->op_regs->status,
320 			     STS_FATAL, STS_FATAL,
321 			     XHCI_MAX_HALT_USEC);
322 	if (!err)
323 		xhci_info(xhci, "Fault detected\n");
324 }
325 
326 static int xhci_enable_interrupter(struct xhci_interrupter *ir)
327 {
328 	u32 iman;
329 
330 	if (!ir || !ir->ir_set)
331 		return -EINVAL;
332 
333 	iman = readl(&ir->ir_set->irq_pending);
334 	writel(ER_IRQ_ENABLE(iman), &ir->ir_set->irq_pending);
335 
336 	return 0;
337 }
338 
339 int xhci_disable_interrupter(struct xhci_interrupter *ir)
340 {
341 	u32 iman;
342 
343 	if (!ir || !ir->ir_set)
344 		return -EINVAL;
345 
346 	iman = readl(&ir->ir_set->irq_pending);
347 	writel(ER_IRQ_DISABLE(iman), &ir->ir_set->irq_pending);
348 
349 	return 0;
350 }
351 
352 /* interrupt moderation interval imod_interval in nanoseconds */
353 int xhci_set_interrupter_moderation(struct xhci_interrupter *ir,
354 				    u32 imod_interval)
355 {
356 	u32 imod;
357 
358 	if (!ir || !ir->ir_set || imod_interval > U16_MAX * 250)
359 		return -EINVAL;
360 
361 	imod = readl(&ir->ir_set->irq_control);
362 	imod &= ~ER_IRQ_INTERVAL_MASK;
363 	imod |= (imod_interval / 250) & ER_IRQ_INTERVAL_MASK;
364 	writel(imod, &ir->ir_set->irq_control);
365 
366 	return 0;
367 }
368 
369 static void compliance_mode_recovery(struct timer_list *t)
370 {
371 	struct xhci_hcd *xhci;
372 	struct usb_hcd *hcd;
373 	struct xhci_hub *rhub;
374 	u32 temp;
375 	int i;
376 
377 	xhci = from_timer(xhci, t, comp_mode_recovery_timer);
378 	rhub = &xhci->usb3_rhub;
379 	hcd = rhub->hcd;
380 
381 	if (!hcd)
382 		return;
383 
384 	for (i = 0; i < rhub->num_ports; i++) {
385 		temp = readl(rhub->ports[i]->addr);
386 		if ((temp & PORT_PLS_MASK) == USB_SS_PORT_LS_COMP_MOD) {
387 			/*
388 			 * Compliance Mode Detected. Letting USB Core
389 			 * handle the Warm Reset
390 			 */
391 			xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
392 					"Compliance mode detected->port %d",
393 					i + 1);
394 			xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
395 					"Attempting compliance mode recovery");
396 
397 			if (hcd->state == HC_STATE_SUSPENDED)
398 				usb_hcd_resume_root_hub(hcd);
399 
400 			usb_hcd_poll_rh_status(hcd);
401 		}
402 	}
403 
404 	if (xhci->port_status_u0 != ((1 << rhub->num_ports) - 1))
405 		mod_timer(&xhci->comp_mode_recovery_timer,
406 			jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
407 }
408 
409 /*
410  * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
411  * that causes ports behind that hardware to enter compliance mode sometimes.
412  * The quirk creates a timer that polls every 2 seconds the link state of
413  * each host controller's port and recovers it by issuing a Warm reset
414  * if Compliance mode is detected, otherwise the port will become "dead" (no
415  * device connections or disconnections will be detected anymore). Becasue no
416  * status event is generated when entering compliance mode (per xhci spec),
417  * this quirk is needed on systems that have the failing hardware installed.
418  */
419 static void compliance_mode_recovery_timer_init(struct xhci_hcd *xhci)
420 {
421 	xhci->port_status_u0 = 0;
422 	timer_setup(&xhci->comp_mode_recovery_timer, compliance_mode_recovery,
423 		    0);
424 	xhci->comp_mode_recovery_timer.expires = jiffies +
425 			msecs_to_jiffies(COMP_MODE_RCVRY_MSECS);
426 
427 	add_timer(&xhci->comp_mode_recovery_timer);
428 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
429 			"Compliance mode recovery timer initialized");
430 }
431 
432 /*
433  * This function identifies the systems that have installed the SN65LVPE502CP
434  * USB3.0 re-driver and that need the Compliance Mode Quirk.
435  * Systems:
436  * Vendor: Hewlett-Packard -> System Models: Z420, Z620 and Z820
437  */
438 static bool xhci_compliance_mode_recovery_timer_quirk_check(void)
439 {
440 	const char *dmi_product_name, *dmi_sys_vendor;
441 
442 	dmi_product_name = dmi_get_system_info(DMI_PRODUCT_NAME);
443 	dmi_sys_vendor = dmi_get_system_info(DMI_SYS_VENDOR);
444 	if (!dmi_product_name || !dmi_sys_vendor)
445 		return false;
446 
447 	if (!(strstr(dmi_sys_vendor, "Hewlett-Packard")))
448 		return false;
449 
450 	if (strstr(dmi_product_name, "Z420") ||
451 			strstr(dmi_product_name, "Z620") ||
452 			strstr(dmi_product_name, "Z820") ||
453 			strstr(dmi_product_name, "Z1 Workstation"))
454 		return true;
455 
456 	return false;
457 }
458 
459 static int xhci_all_ports_seen_u0(struct xhci_hcd *xhci)
460 {
461 	return (xhci->port_status_u0 == ((1 << xhci->usb3_rhub.num_ports) - 1));
462 }
463 
464 
465 /*
466  * Initialize memory for HCD and xHC (one-time init).
467  *
468  * Program the PAGESIZE register, initialize the device context array, create
469  * device contexts (?), set up a command ring segment (or two?), create event
470  * ring (one for now).
471  */
472 static int xhci_init(struct usb_hcd *hcd)
473 {
474 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
475 	int retval;
476 
477 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_init");
478 	spin_lock_init(&xhci->lock);
479 
480 	retval = xhci_mem_init(xhci, GFP_KERNEL);
481 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Finished xhci_init");
482 
483 	/* Initializing Compliance Mode Recovery Data If Needed */
484 	if (xhci_compliance_mode_recovery_timer_quirk_check()) {
485 		xhci->quirks |= XHCI_COMP_MODE_QUIRK;
486 		compliance_mode_recovery_timer_init(xhci);
487 	}
488 
489 	return retval;
490 }
491 
492 /*-------------------------------------------------------------------------*/
493 
494 static int xhci_run_finished(struct xhci_hcd *xhci)
495 {
496 	struct xhci_interrupter *ir = xhci->interrupters[0];
497 	unsigned long	flags;
498 	u32		temp;
499 
500 	/*
501 	 * Enable interrupts before starting the host (xhci 4.2 and 5.5.2).
502 	 * Protect the short window before host is running with a lock
503 	 */
504 	spin_lock_irqsave(&xhci->lock, flags);
505 
506 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Enable interrupts");
507 	temp = readl(&xhci->op_regs->command);
508 	temp |= (CMD_EIE);
509 	writel(temp, &xhci->op_regs->command);
510 
511 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Enable primary interrupter");
512 	xhci_enable_interrupter(ir);
513 
514 	if (xhci_start(xhci)) {
515 		xhci_halt(xhci);
516 		spin_unlock_irqrestore(&xhci->lock, flags);
517 		return -ENODEV;
518 	}
519 
520 	xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
521 
522 	if (xhci->quirks & XHCI_NEC_HOST)
523 		xhci_ring_cmd_db(xhci);
524 
525 	spin_unlock_irqrestore(&xhci->lock, flags);
526 
527 	return 0;
528 }
529 
530 /*
531  * Start the HC after it was halted.
532  *
533  * This function is called by the USB core when the HC driver is added.
534  * Its opposite is xhci_stop().
535  *
536  * xhci_init() must be called once before this function can be called.
537  * Reset the HC, enable device slot contexts, program DCBAAP, and
538  * set command ring pointer and event ring pointer.
539  *
540  * Setup MSI-X vectors and enable interrupts.
541  */
542 int xhci_run(struct usb_hcd *hcd)
543 {
544 	u64 temp_64;
545 	int ret;
546 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
547 	struct xhci_interrupter *ir = xhci->interrupters[0];
548 	/* Start the xHCI host controller running only after the USB 2.0 roothub
549 	 * is setup.
550 	 */
551 
552 	hcd->uses_new_polling = 1;
553 	if (hcd->msi_enabled)
554 		ir->ip_autoclear = true;
555 
556 	if (!usb_hcd_is_primary_hcd(hcd))
557 		return xhci_run_finished(xhci);
558 
559 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xhci_run");
560 
561 	temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
562 	temp_64 &= ERST_PTR_MASK;
563 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
564 			"ERST deq = 64'h%0lx", (long unsigned int) temp_64);
565 
566 	xhci_set_interrupter_moderation(ir, xhci->imod_interval);
567 
568 	if (xhci->quirks & XHCI_NEC_HOST) {
569 		struct xhci_command *command;
570 
571 		command = xhci_alloc_command(xhci, false, GFP_KERNEL);
572 		if (!command)
573 			return -ENOMEM;
574 
575 		ret = xhci_queue_vendor_command(xhci, command, 0, 0, 0,
576 				TRB_TYPE(TRB_NEC_GET_FW));
577 		if (ret)
578 			xhci_free_command(xhci, command);
579 	}
580 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
581 			"Finished %s for main hcd", __func__);
582 
583 	xhci_create_dbc_dev(xhci);
584 
585 	xhci_debugfs_init(xhci);
586 
587 	if (xhci_has_one_roothub(xhci))
588 		return xhci_run_finished(xhci);
589 
590 	set_bit(HCD_FLAG_DEFER_RH_REGISTER, &hcd->flags);
591 
592 	return 0;
593 }
594 EXPORT_SYMBOL_GPL(xhci_run);
595 
596 /*
597  * Stop xHCI driver.
598  *
599  * This function is called by the USB core when the HC driver is removed.
600  * Its opposite is xhci_run().
601  *
602  * Disable device contexts, disable IRQs, and quiesce the HC.
603  * Reset the HC, finish any completed transactions, and cleanup memory.
604  */
605 void xhci_stop(struct usb_hcd *hcd)
606 {
607 	u32 temp;
608 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
609 	struct xhci_interrupter *ir = xhci->interrupters[0];
610 
611 	mutex_lock(&xhci->mutex);
612 
613 	/* Only halt host and free memory after both hcds are removed */
614 	if (!usb_hcd_is_primary_hcd(hcd)) {
615 		mutex_unlock(&xhci->mutex);
616 		return;
617 	}
618 
619 	xhci_remove_dbc_dev(xhci);
620 
621 	spin_lock_irq(&xhci->lock);
622 	xhci->xhc_state |= XHCI_STATE_HALTED;
623 	xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
624 	xhci_halt(xhci);
625 	xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
626 	spin_unlock_irq(&xhci->lock);
627 
628 	/* Deleting Compliance Mode Recovery Timer */
629 	if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
630 			(!(xhci_all_ports_seen_u0(xhci)))) {
631 		timer_delete_sync(&xhci->comp_mode_recovery_timer);
632 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
633 				"%s: compliance mode recovery timer deleted",
634 				__func__);
635 	}
636 
637 	if (xhci->quirks & XHCI_AMD_PLL_FIX)
638 		usb_amd_dev_put();
639 
640 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
641 			"// Disabling event ring interrupts");
642 	temp = readl(&xhci->op_regs->status);
643 	writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
644 	xhci_disable_interrupter(ir);
645 
646 	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
647 	xhci_mem_cleanup(xhci);
648 	xhci_debugfs_exit(xhci);
649 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
650 			"xhci_stop completed - status = %x",
651 			readl(&xhci->op_regs->status));
652 	mutex_unlock(&xhci->mutex);
653 }
654 EXPORT_SYMBOL_GPL(xhci_stop);
655 
656 /*
657  * Shutdown HC (not bus-specific)
658  *
659  * This is called when the machine is rebooting or halting.  We assume that the
660  * machine will be powered off, and the HC's internal state will be reset.
661  * Don't bother to free memory.
662  *
663  * This will only ever be called with the main usb_hcd (the USB3 roothub).
664  */
665 void xhci_shutdown(struct usb_hcd *hcd)
666 {
667 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
668 
669 	if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
670 		usb_disable_xhci_ports(to_pci_dev(hcd->self.sysdev));
671 
672 	/* Don't poll the roothubs after shutdown. */
673 	xhci_dbg(xhci, "%s: stopping usb%d port polling.\n",
674 			__func__, hcd->self.busnum);
675 	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
676 	timer_delete_sync(&hcd->rh_timer);
677 
678 	if (xhci->shared_hcd) {
679 		clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
680 		timer_delete_sync(&xhci->shared_hcd->rh_timer);
681 	}
682 
683 	spin_lock_irq(&xhci->lock);
684 	xhci_halt(xhci);
685 
686 	/*
687 	 * Workaround for spurious wakeps at shutdown with HSW, and for boot
688 	 * firmware delay in ADL-P PCH if port are left in U3 at shutdown
689 	 */
690 	if (xhci->quirks & XHCI_SPURIOUS_WAKEUP ||
691 	    xhci->quirks & XHCI_RESET_TO_DEFAULT)
692 		xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
693 
694 	spin_unlock_irq(&xhci->lock);
695 
696 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
697 			"xhci_shutdown completed - status = %x",
698 			readl(&xhci->op_regs->status));
699 }
700 EXPORT_SYMBOL_GPL(xhci_shutdown);
701 
702 #ifdef CONFIG_PM
703 static void xhci_save_registers(struct xhci_hcd *xhci)
704 {
705 	struct xhci_interrupter *ir;
706 	unsigned int i;
707 
708 	xhci->s3.command = readl(&xhci->op_regs->command);
709 	xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
710 	xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
711 	xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
712 
713 	/* save both primary and all secondary interrupters */
714 	/* fixme, shold we lock  to prevent race with remove secondary interrupter? */
715 	for (i = 0; i < xhci->max_interrupters; i++) {
716 		ir = xhci->interrupters[i];
717 		if (!ir)
718 			continue;
719 
720 		ir->s3_erst_size = readl(&ir->ir_set->erst_size);
721 		ir->s3_erst_base = xhci_read_64(xhci, &ir->ir_set->erst_base);
722 		ir->s3_erst_dequeue = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
723 		ir->s3_irq_pending = readl(&ir->ir_set->irq_pending);
724 		ir->s3_irq_control = readl(&ir->ir_set->irq_control);
725 	}
726 }
727 
728 static void xhci_restore_registers(struct xhci_hcd *xhci)
729 {
730 	struct xhci_interrupter *ir;
731 	unsigned int i;
732 
733 	writel(xhci->s3.command, &xhci->op_regs->command);
734 	writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
735 	xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
736 	writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
737 
738 	/* FIXME should we lock to protect against freeing of interrupters */
739 	for (i = 0; i < xhci->max_interrupters; i++) {
740 		ir = xhci->interrupters[i];
741 		if (!ir)
742 			continue;
743 
744 		writel(ir->s3_erst_size, &ir->ir_set->erst_size);
745 		xhci_write_64(xhci, ir->s3_erst_base, &ir->ir_set->erst_base);
746 		xhci_write_64(xhci, ir->s3_erst_dequeue, &ir->ir_set->erst_dequeue);
747 		writel(ir->s3_irq_pending, &ir->ir_set->irq_pending);
748 		writel(ir->s3_irq_control, &ir->ir_set->irq_control);
749 	}
750 }
751 
752 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
753 {
754 	u64	val_64;
755 
756 	/* step 2: initialize command ring buffer */
757 	val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
758 	val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
759 		(xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
760 				      xhci->cmd_ring->dequeue) &
761 		 (u64) ~CMD_RING_RSVD_BITS) |
762 		xhci->cmd_ring->cycle_state;
763 	xhci_dbg_trace(xhci, trace_xhci_dbg_init,
764 			"// Setting command ring address to 0x%llx",
765 			(long unsigned long) val_64);
766 	xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
767 }
768 
769 /*
770  * The whole command ring must be cleared to zero when we suspend the host.
771  *
772  * The host doesn't save the command ring pointer in the suspend well, so we
773  * need to re-program it on resume.  Unfortunately, the pointer must be 64-byte
774  * aligned, because of the reserved bits in the command ring dequeue pointer
775  * register.  Therefore, we can't just set the dequeue pointer back in the
776  * middle of the ring (TRBs are 16-byte aligned).
777  */
778 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
779 {
780 	struct xhci_ring *ring;
781 	struct xhci_segment *seg;
782 
783 	ring = xhci->cmd_ring;
784 	xhci_for_each_ring_seg(ring->first_seg, seg) {
785 		/* erase all TRBs before the link */
786 		memset(seg->trbs, 0, sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
787 		/* clear link cycle bit */
788 		seg->trbs[TRBS_PER_SEGMENT - 1].link.control &= cpu_to_le32(~TRB_CYCLE);
789 	}
790 
791 	xhci_initialize_ring_info(ring);
792 	/*
793 	 * Reset the hardware dequeue pointer.
794 	 * Yes, this will need to be re-written after resume, but we're paranoid
795 	 * and want to make sure the hardware doesn't access bogus memory
796 	 * because, say, the BIOS or an SMI started the host without changing
797 	 * the command ring pointers.
798 	 */
799 	xhci_set_cmd_ring_deq(xhci);
800 }
801 
802 /*
803  * Disable port wake bits if do_wakeup is not set.
804  *
805  * Also clear a possible internal port wake state left hanging for ports that
806  * detected termination but never successfully enumerated (trained to 0U).
807  * Internal wake causes immediate xHCI wake after suspend. PORT_CSC write done
808  * at enumeration clears this wake, force one here as well for unconnected ports
809  */
810 
811 static void xhci_disable_hub_port_wake(struct xhci_hcd *xhci,
812 				       struct xhci_hub *rhub,
813 				       bool do_wakeup)
814 {
815 	unsigned long flags;
816 	u32 t1, t2, portsc;
817 	int i;
818 
819 	spin_lock_irqsave(&xhci->lock, flags);
820 
821 	for (i = 0; i < rhub->num_ports; i++) {
822 		portsc = readl(rhub->ports[i]->addr);
823 		t1 = xhci_port_state_to_neutral(portsc);
824 		t2 = t1;
825 
826 		/* clear wake bits if do_wake is not set */
827 		if (!do_wakeup)
828 			t2 &= ~PORT_WAKE_BITS;
829 
830 		/* Don't touch csc bit if connected or connect change is set */
831 		if (!(portsc & (PORT_CSC | PORT_CONNECT)))
832 			t2 |= PORT_CSC;
833 
834 		if (t1 != t2) {
835 			writel(t2, rhub->ports[i]->addr);
836 			xhci_dbg(xhci, "config port %d-%d wake bits, portsc: 0x%x, write: 0x%x\n",
837 				 rhub->hcd->self.busnum, i + 1, portsc, t2);
838 		}
839 	}
840 	spin_unlock_irqrestore(&xhci->lock, flags);
841 }
842 
843 static bool xhci_pending_portevent(struct xhci_hcd *xhci)
844 {
845 	struct xhci_port	**ports;
846 	int			port_index;
847 	u32			status;
848 	u32			portsc;
849 
850 	status = readl(&xhci->op_regs->status);
851 	if (status & STS_EINT)
852 		return true;
853 	/*
854 	 * Checking STS_EINT is not enough as there is a lag between a change
855 	 * bit being set and the Port Status Change Event that it generated
856 	 * being written to the Event Ring. See note in xhci 1.1 section 4.19.2.
857 	 */
858 
859 	port_index = xhci->usb2_rhub.num_ports;
860 	ports = xhci->usb2_rhub.ports;
861 	while (port_index--) {
862 		portsc = readl(ports[port_index]->addr);
863 		if (portsc & PORT_CHANGE_MASK ||
864 		    (portsc & PORT_PLS_MASK) == XDEV_RESUME)
865 			return true;
866 	}
867 	port_index = xhci->usb3_rhub.num_ports;
868 	ports = xhci->usb3_rhub.ports;
869 	while (port_index--) {
870 		portsc = readl(ports[port_index]->addr);
871 		if (portsc & (PORT_CHANGE_MASK | PORT_CAS) ||
872 		    (portsc & PORT_PLS_MASK) == XDEV_RESUME)
873 			return true;
874 	}
875 	return false;
876 }
877 
878 /*
879  * Stop HC (not bus-specific)
880  *
881  * This is called when the machine transition into S3/S4 mode.
882  *
883  */
884 int xhci_suspend(struct xhci_hcd *xhci, bool do_wakeup)
885 {
886 	int			rc = 0;
887 	unsigned int		delay = XHCI_MAX_HALT_USEC * 2;
888 	struct usb_hcd		*hcd = xhci_to_hcd(xhci);
889 	u32			command;
890 	u32			res;
891 
892 	if (!hcd->state)
893 		return 0;
894 
895 	if (hcd->state != HC_STATE_SUSPENDED ||
896 	    (xhci->shared_hcd && xhci->shared_hcd->state != HC_STATE_SUSPENDED))
897 		return -EINVAL;
898 
899 	/* Clear root port wake on bits if wakeup not allowed. */
900 	xhci_disable_hub_port_wake(xhci, &xhci->usb3_rhub, do_wakeup);
901 	xhci_disable_hub_port_wake(xhci, &xhci->usb2_rhub, do_wakeup);
902 
903 	if (!HCD_HW_ACCESSIBLE(hcd))
904 		return 0;
905 
906 	xhci_dbc_suspend(xhci);
907 
908 	/* Don't poll the roothubs on bus suspend. */
909 	xhci_dbg(xhci, "%s: stopping usb%d port polling.\n",
910 		 __func__, hcd->self.busnum);
911 	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
912 	timer_delete_sync(&hcd->rh_timer);
913 	if (xhci->shared_hcd) {
914 		clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
915 		timer_delete_sync(&xhci->shared_hcd->rh_timer);
916 	}
917 
918 	if (xhci->quirks & XHCI_SUSPEND_DELAY)
919 		usleep_range(1000, 1500);
920 
921 	spin_lock_irq(&xhci->lock);
922 	clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
923 	if (xhci->shared_hcd)
924 		clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
925 	/* step 1: stop endpoint */
926 	/* skipped assuming that port suspend has done */
927 
928 	/* step 2: clear Run/Stop bit */
929 	command = readl(&xhci->op_regs->command);
930 	command &= ~CMD_RUN;
931 	writel(command, &xhci->op_regs->command);
932 
933 	/* Some chips from Fresco Logic need an extraordinary delay */
934 	delay *= (xhci->quirks & XHCI_SLOW_SUSPEND) ? 10 : 1;
935 
936 	if (xhci_handshake(&xhci->op_regs->status,
937 		      STS_HALT, STS_HALT, delay)) {
938 		xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
939 		spin_unlock_irq(&xhci->lock);
940 		return -ETIMEDOUT;
941 	}
942 	xhci_clear_command_ring(xhci);
943 
944 	/* step 3: save registers */
945 	xhci_save_registers(xhci);
946 
947 	/* step 4: set CSS flag */
948 	command = readl(&xhci->op_regs->command);
949 	command |= CMD_CSS;
950 	writel(command, &xhci->op_regs->command);
951 	xhci->broken_suspend = 0;
952 	if (xhci_handshake(&xhci->op_regs->status,
953 				STS_SAVE, 0, 20 * 1000)) {
954 	/*
955 	 * AMD SNPS xHC 3.0 occasionally does not clear the
956 	 * SSS bit of USBSTS and when driver tries to poll
957 	 * to see if the xHC clears BIT(8) which never happens
958 	 * and driver assumes that controller is not responding
959 	 * and times out. To workaround this, its good to check
960 	 * if SRE and HCE bits are not set (as per xhci
961 	 * Section 5.4.2) and bypass the timeout.
962 	 */
963 		res = readl(&xhci->op_regs->status);
964 		if ((xhci->quirks & XHCI_SNPS_BROKEN_SUSPEND) &&
965 		    (((res & STS_SRE) == 0) &&
966 				((res & STS_HCE) == 0))) {
967 			xhci->broken_suspend = 1;
968 		} else {
969 			xhci_warn(xhci, "WARN: xHC save state timeout\n");
970 			spin_unlock_irq(&xhci->lock);
971 			return -ETIMEDOUT;
972 		}
973 	}
974 	spin_unlock_irq(&xhci->lock);
975 
976 	/*
977 	 * Deleting Compliance Mode Recovery Timer because the xHCI Host
978 	 * is about to be suspended.
979 	 */
980 	if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
981 			(!(xhci_all_ports_seen_u0(xhci)))) {
982 		timer_delete_sync(&xhci->comp_mode_recovery_timer);
983 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
984 				"%s: compliance mode recovery timer deleted",
985 				__func__);
986 	}
987 
988 	return rc;
989 }
990 EXPORT_SYMBOL_GPL(xhci_suspend);
991 
992 /*
993  * start xHC (not bus-specific)
994  *
995  * This is called when the machine transition from S3/S4 mode.
996  *
997  */
998 int xhci_resume(struct xhci_hcd *xhci, bool power_lost, bool is_auto_resume)
999 {
1000 	u32			command, temp = 0;
1001 	struct usb_hcd		*hcd = xhci_to_hcd(xhci);
1002 	int			retval = 0;
1003 	bool			comp_timer_running = false;
1004 	bool			pending_portevent = false;
1005 	bool			suspended_usb3_devs = false;
1006 
1007 	if (!hcd->state)
1008 		return 0;
1009 
1010 	/* Wait a bit if either of the roothubs need to settle from the
1011 	 * transition into bus suspend.
1012 	 */
1013 
1014 	if (time_before(jiffies, xhci->usb2_rhub.bus_state.next_statechange) ||
1015 	    time_before(jiffies, xhci->usb3_rhub.bus_state.next_statechange))
1016 		msleep(100);
1017 
1018 	set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1019 	if (xhci->shared_hcd)
1020 		set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1021 
1022 	spin_lock_irq(&xhci->lock);
1023 
1024 	if (xhci->quirks & XHCI_RESET_ON_RESUME || xhci->broken_suspend)
1025 		power_lost = true;
1026 
1027 	if (!power_lost) {
1028 		/*
1029 		 * Some controllers might lose power during suspend, so wait
1030 		 * for controller not ready bit to clear, just as in xHC init.
1031 		 */
1032 		retval = xhci_handshake(&xhci->op_regs->status,
1033 					STS_CNR, 0, 10 * 1000 * 1000);
1034 		if (retval) {
1035 			xhci_warn(xhci, "Controller not ready at resume %d\n",
1036 				  retval);
1037 			spin_unlock_irq(&xhci->lock);
1038 			return retval;
1039 		}
1040 		/* step 1: restore register */
1041 		xhci_restore_registers(xhci);
1042 		/* step 2: initialize command ring buffer */
1043 		xhci_set_cmd_ring_deq(xhci);
1044 		/* step 3: restore state and start state*/
1045 		/* step 3: set CRS flag */
1046 		command = readl(&xhci->op_regs->command);
1047 		command |= CMD_CRS;
1048 		writel(command, &xhci->op_regs->command);
1049 		/*
1050 		 * Some controllers take up to 55+ ms to complete the controller
1051 		 * restore so setting the timeout to 100ms. Xhci specification
1052 		 * doesn't mention any timeout value.
1053 		 */
1054 		if (xhci_handshake(&xhci->op_regs->status,
1055 			      STS_RESTORE, 0, 100 * 1000)) {
1056 			xhci_warn(xhci, "WARN: xHC restore state timeout\n");
1057 			spin_unlock_irq(&xhci->lock);
1058 			return -ETIMEDOUT;
1059 		}
1060 	}
1061 
1062 	temp = readl(&xhci->op_regs->status);
1063 
1064 	/* re-initialize the HC on Restore Error, or Host Controller Error */
1065 	if ((temp & (STS_SRE | STS_HCE)) &&
1066 	    !(xhci->xhc_state & XHCI_STATE_REMOVING)) {
1067 		if (!power_lost)
1068 			xhci_warn(xhci, "xHC error in resume, USBSTS 0x%x, Reinit\n", temp);
1069 		power_lost = true;
1070 	}
1071 
1072 	if (power_lost) {
1073 		if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1074 				!(xhci_all_ports_seen_u0(xhci))) {
1075 			timer_delete_sync(&xhci->comp_mode_recovery_timer);
1076 			xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1077 				"Compliance Mode Recovery Timer deleted!");
1078 		}
1079 
1080 		/* Let the USB core know _both_ roothubs lost power. */
1081 		usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1082 		if (xhci->shared_hcd)
1083 			usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
1084 
1085 		xhci_dbg(xhci, "Stop HCD\n");
1086 		xhci_halt(xhci);
1087 		xhci_zero_64b_regs(xhci);
1088 		retval = xhci_reset(xhci, XHCI_RESET_LONG_USEC);
1089 		spin_unlock_irq(&xhci->lock);
1090 		if (retval)
1091 			return retval;
1092 
1093 		xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1094 		temp = readl(&xhci->op_regs->status);
1095 		writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
1096 		xhci_disable_interrupter(xhci->interrupters[0]);
1097 
1098 		xhci_dbg(xhci, "cleaning up memory\n");
1099 		xhci_mem_cleanup(xhci);
1100 		xhci_debugfs_exit(xhci);
1101 		xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1102 			    readl(&xhci->op_regs->status));
1103 
1104 		/* USB core calls the PCI reinit and start functions twice:
1105 		 * first with the primary HCD, and then with the secondary HCD.
1106 		 * If we don't do the same, the host will never be started.
1107 		 */
1108 		xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1109 		retval = xhci_init(hcd);
1110 		if (retval)
1111 			return retval;
1112 		comp_timer_running = true;
1113 
1114 		xhci_dbg(xhci, "Start the primary HCD\n");
1115 		retval = xhci_run(hcd);
1116 		if (!retval && xhci->shared_hcd) {
1117 			xhci_dbg(xhci, "Start the secondary HCD\n");
1118 			retval = xhci_run(xhci->shared_hcd);
1119 		}
1120 		if (retval)
1121 			return retval;
1122 		/*
1123 		 * Resume roothubs unconditionally as PORTSC change bits are not
1124 		 * immediately visible after xHC reset
1125 		 */
1126 		hcd->state = HC_STATE_SUSPENDED;
1127 
1128 		if (xhci->shared_hcd) {
1129 			xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1130 			usb_hcd_resume_root_hub(xhci->shared_hcd);
1131 		}
1132 		usb_hcd_resume_root_hub(hcd);
1133 
1134 		goto done;
1135 	}
1136 
1137 	/* step 4: set Run/Stop bit */
1138 	command = readl(&xhci->op_regs->command);
1139 	command |= CMD_RUN;
1140 	writel(command, &xhci->op_regs->command);
1141 	xhci_handshake(&xhci->op_regs->status, STS_HALT,
1142 		  0, 250 * 1000);
1143 
1144 	/* step 5: walk topology and initialize portsc,
1145 	 * portpmsc and portli
1146 	 */
1147 	/* this is done in bus_resume */
1148 
1149 	/* step 6: restart each of the previously
1150 	 * Running endpoints by ringing their doorbells
1151 	 */
1152 
1153 	spin_unlock_irq(&xhci->lock);
1154 
1155 	xhci_dbc_resume(xhci);
1156 
1157 	if (retval == 0) {
1158 		/*
1159 		 * Resume roothubs only if there are pending events.
1160 		 * USB 3 devices resend U3 LFPS wake after a 100ms delay if
1161 		 * the first wake signalling failed, give it that chance if
1162 		 * there are suspended USB 3 devices.
1163 		 */
1164 		if (xhci->usb3_rhub.bus_state.suspended_ports ||
1165 		    xhci->usb3_rhub.bus_state.bus_suspended)
1166 			suspended_usb3_devs = true;
1167 
1168 		pending_portevent = xhci_pending_portevent(xhci);
1169 
1170 		if (suspended_usb3_devs && !pending_portevent && is_auto_resume) {
1171 			msleep(120);
1172 			pending_portevent = xhci_pending_portevent(xhci);
1173 		}
1174 
1175 		if (pending_portevent) {
1176 			if (xhci->shared_hcd)
1177 				usb_hcd_resume_root_hub(xhci->shared_hcd);
1178 			usb_hcd_resume_root_hub(hcd);
1179 		}
1180 	}
1181 done:
1182 	/*
1183 	 * If system is subject to the Quirk, Compliance Mode Timer needs to
1184 	 * be re-initialized Always after a system resume. Ports are subject
1185 	 * to suffer the Compliance Mode issue again. It doesn't matter if
1186 	 * ports have entered previously to U0 before system's suspension.
1187 	 */
1188 	if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
1189 		compliance_mode_recovery_timer_init(xhci);
1190 
1191 	if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
1192 		usb_asmedia_modifyflowcontrol(to_pci_dev(hcd->self.controller));
1193 
1194 	/* Re-enable port polling. */
1195 	xhci_dbg(xhci, "%s: starting usb%d port polling.\n",
1196 		 __func__, hcd->self.busnum);
1197 	if (xhci->shared_hcd) {
1198 		set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
1199 		usb_hcd_poll_rh_status(xhci->shared_hcd);
1200 	}
1201 	set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1202 	usb_hcd_poll_rh_status(hcd);
1203 
1204 	return retval;
1205 }
1206 EXPORT_SYMBOL_GPL(xhci_resume);
1207 #endif	/* CONFIG_PM */
1208 
1209 /*-------------------------------------------------------------------------*/
1210 
1211 static int xhci_map_temp_buffer(struct usb_hcd *hcd, struct urb *urb)
1212 {
1213 	void *temp;
1214 	int ret = 0;
1215 	unsigned int buf_len;
1216 	enum dma_data_direction dir;
1217 
1218 	dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1219 	buf_len = urb->transfer_buffer_length;
1220 
1221 	temp = kzalloc_node(buf_len, GFP_ATOMIC,
1222 			    dev_to_node(hcd->self.sysdev));
1223 	if (!temp)
1224 		return -ENOMEM;
1225 
1226 	if (usb_urb_dir_out(urb))
1227 		sg_pcopy_to_buffer(urb->sg, urb->num_sgs,
1228 				   temp, buf_len, 0);
1229 
1230 	urb->transfer_buffer = temp;
1231 	urb->transfer_dma = dma_map_single(hcd->self.sysdev,
1232 					   urb->transfer_buffer,
1233 					   urb->transfer_buffer_length,
1234 					   dir);
1235 
1236 	if (dma_mapping_error(hcd->self.sysdev,
1237 			      urb->transfer_dma)) {
1238 		ret = -EAGAIN;
1239 		kfree(temp);
1240 	} else {
1241 		urb->transfer_flags |= URB_DMA_MAP_SINGLE;
1242 	}
1243 
1244 	return ret;
1245 }
1246 
1247 static bool xhci_urb_temp_buffer_required(struct usb_hcd *hcd,
1248 					  struct urb *urb)
1249 {
1250 	bool ret = false;
1251 	unsigned int i;
1252 	unsigned int len = 0;
1253 	unsigned int trb_size;
1254 	unsigned int max_pkt;
1255 	struct scatterlist *sg;
1256 	struct scatterlist *tail_sg;
1257 
1258 	tail_sg = urb->sg;
1259 	max_pkt = usb_endpoint_maxp(&urb->ep->desc);
1260 
1261 	if (!urb->num_sgs)
1262 		return ret;
1263 
1264 	if (urb->dev->speed >= USB_SPEED_SUPER)
1265 		trb_size = TRB_CACHE_SIZE_SS;
1266 	else
1267 		trb_size = TRB_CACHE_SIZE_HS;
1268 
1269 	if (urb->transfer_buffer_length != 0 &&
1270 	    !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)) {
1271 		for_each_sg(urb->sg, sg, urb->num_sgs, i) {
1272 			len = len + sg->length;
1273 			if (i > trb_size - 2) {
1274 				len = len - tail_sg->length;
1275 				if (len < max_pkt) {
1276 					ret = true;
1277 					break;
1278 				}
1279 
1280 				tail_sg = sg_next(tail_sg);
1281 			}
1282 		}
1283 	}
1284 	return ret;
1285 }
1286 
1287 static void xhci_unmap_temp_buf(struct usb_hcd *hcd, struct urb *urb)
1288 {
1289 	unsigned int len;
1290 	unsigned int buf_len;
1291 	enum dma_data_direction dir;
1292 
1293 	dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1294 
1295 	buf_len = urb->transfer_buffer_length;
1296 
1297 	if (IS_ENABLED(CONFIG_HAS_DMA) &&
1298 	    (urb->transfer_flags & URB_DMA_MAP_SINGLE))
1299 		dma_unmap_single(hcd->self.sysdev,
1300 				 urb->transfer_dma,
1301 				 urb->transfer_buffer_length,
1302 				 dir);
1303 
1304 	if (usb_urb_dir_in(urb)) {
1305 		len = sg_pcopy_from_buffer(urb->sg, urb->num_sgs,
1306 					   urb->transfer_buffer,
1307 					   buf_len,
1308 					   0);
1309 		if (len != buf_len) {
1310 			xhci_dbg(hcd_to_xhci(hcd),
1311 				 "Copy from tmp buf to urb sg list failed\n");
1312 			urb->actual_length = len;
1313 		}
1314 	}
1315 	urb->transfer_flags &= ~URB_DMA_MAP_SINGLE;
1316 	kfree(urb->transfer_buffer);
1317 	urb->transfer_buffer = NULL;
1318 }
1319 
1320 /*
1321  * Bypass the DMA mapping if URB is suitable for Immediate Transfer (IDT),
1322  * we'll copy the actual data into the TRB address register. This is limited to
1323  * transfers up to 8 bytes on output endpoints of any kind with wMaxPacketSize
1324  * >= 8 bytes. If suitable for IDT only one Transfer TRB per TD is allowed.
1325  */
1326 static int xhci_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
1327 				gfp_t mem_flags)
1328 {
1329 	struct xhci_hcd *xhci;
1330 
1331 	xhci = hcd_to_xhci(hcd);
1332 
1333 	if (xhci_urb_suitable_for_idt(urb))
1334 		return 0;
1335 
1336 	if (xhci->quirks & XHCI_SG_TRB_CACHE_SIZE_QUIRK) {
1337 		if (xhci_urb_temp_buffer_required(hcd, urb))
1338 			return xhci_map_temp_buffer(hcd, urb);
1339 	}
1340 	return usb_hcd_map_urb_for_dma(hcd, urb, mem_flags);
1341 }
1342 
1343 static void xhci_unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
1344 {
1345 	struct xhci_hcd *xhci;
1346 	bool unmap_temp_buf = false;
1347 
1348 	xhci = hcd_to_xhci(hcd);
1349 
1350 	if (urb->num_sgs && (urb->transfer_flags & URB_DMA_MAP_SINGLE))
1351 		unmap_temp_buf = true;
1352 
1353 	if ((xhci->quirks & XHCI_SG_TRB_CACHE_SIZE_QUIRK) && unmap_temp_buf)
1354 		xhci_unmap_temp_buf(hcd, urb);
1355 	else
1356 		usb_hcd_unmap_urb_for_dma(hcd, urb);
1357 }
1358 
1359 /**
1360  * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1361  * HCDs.  Find the index for an endpoint given its descriptor.  Use the return
1362  * value to right shift 1 for the bitmask.
1363  *
1364  * Index  = (epnum * 2) + direction - 1,
1365  * where direction = 0 for OUT, 1 for IN.
1366  * For control endpoints, the IN index is used (OUT index is unused), so
1367  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1368  */
1369 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1370 {
1371 	unsigned int index;
1372 	if (usb_endpoint_xfer_control(desc))
1373 		index = (unsigned int) (usb_endpoint_num(desc)*2);
1374 	else
1375 		index = (unsigned int) (usb_endpoint_num(desc)*2) +
1376 			(usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1377 	return index;
1378 }
1379 EXPORT_SYMBOL_GPL(xhci_get_endpoint_index);
1380 
1381 /* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
1382  * address from the XHCI endpoint index.
1383  */
1384 static unsigned int xhci_get_endpoint_address(unsigned int ep_index)
1385 {
1386 	unsigned int number = DIV_ROUND_UP(ep_index, 2);
1387 	unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
1388 	return direction | number;
1389 }
1390 
1391 /* Find the flag for this endpoint (for use in the control context).  Use the
1392  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1393  * bit 1, etc.
1394  */
1395 static unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1396 {
1397 	return 1 << (xhci_get_endpoint_index(desc) + 1);
1398 }
1399 
1400 /* Compute the last valid endpoint context index.  Basically, this is the
1401  * endpoint index plus one.  For slot contexts with more than valid endpoint,
1402  * we find the most significant bit set in the added contexts flags.
1403  * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1404  * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1405  */
1406 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1407 {
1408 	return fls(added_ctxs) - 1;
1409 }
1410 
1411 /* Returns 1 if the arguments are OK;
1412  * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1413  */
1414 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1415 		struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1416 		const char *func) {
1417 	struct xhci_hcd	*xhci;
1418 	struct xhci_virt_device	*virt_dev;
1419 
1420 	if (!hcd || (check_ep && !ep) || !udev) {
1421 		pr_debug("xHCI %s called with invalid args\n", func);
1422 		return -EINVAL;
1423 	}
1424 	if (!udev->parent) {
1425 		pr_debug("xHCI %s called for root hub\n", func);
1426 		return 0;
1427 	}
1428 
1429 	xhci = hcd_to_xhci(hcd);
1430 	if (check_virt_dev) {
1431 		if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1432 			xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
1433 					func);
1434 			return -EINVAL;
1435 		}
1436 
1437 		virt_dev = xhci->devs[udev->slot_id];
1438 		if (virt_dev->udev != udev) {
1439 			xhci_dbg(xhci, "xHCI %s called with udev and "
1440 					  "virt_dev does not match\n", func);
1441 			return -EINVAL;
1442 		}
1443 	}
1444 
1445 	if (xhci->xhc_state & XHCI_STATE_HALTED)
1446 		return -ENODEV;
1447 
1448 	return 1;
1449 }
1450 
1451 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1452 		struct usb_device *udev, struct xhci_command *command,
1453 		bool ctx_change, bool must_succeed);
1454 
1455 /*
1456  * Full speed devices may have a max packet size greater than 8 bytes, but the
1457  * USB core doesn't know that until it reads the first 8 bytes of the
1458  * descriptor.  If the usb_device's max packet size changes after that point,
1459  * we need to issue an evaluate context command and wait on it.
1460  */
1461 static int xhci_check_ep0_maxpacket(struct xhci_hcd *xhci, struct xhci_virt_device *vdev)
1462 {
1463 	struct xhci_input_control_ctx *ctrl_ctx;
1464 	struct xhci_ep_ctx *ep_ctx;
1465 	struct xhci_command *command;
1466 	int max_packet_size;
1467 	int hw_max_packet_size;
1468 	int ret = 0;
1469 
1470 	ep_ctx = xhci_get_ep_ctx(xhci, vdev->out_ctx, 0);
1471 	hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1472 	max_packet_size = usb_endpoint_maxp(&vdev->udev->ep0.desc);
1473 
1474 	if (hw_max_packet_size == max_packet_size)
1475 		return 0;
1476 
1477 	switch (max_packet_size) {
1478 	case 8: case 16: case 32: case 64: case 9:
1479 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1480 				"Max Packet Size for ep 0 changed.");
1481 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1482 				"Max packet size in usb_device = %d",
1483 				max_packet_size);
1484 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1485 				"Max packet size in xHCI HW = %d",
1486 				hw_max_packet_size);
1487 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
1488 				"Issuing evaluate context command.");
1489 
1490 		command = xhci_alloc_command(xhci, true, GFP_KERNEL);
1491 		if (!command)
1492 			return -ENOMEM;
1493 
1494 		command->in_ctx = vdev->in_ctx;
1495 		ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
1496 		if (!ctrl_ctx) {
1497 			xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1498 					__func__);
1499 			ret = -ENOMEM;
1500 			break;
1501 		}
1502 		/* Set up the modified control endpoint 0 */
1503 		xhci_endpoint_copy(xhci, vdev->in_ctx, vdev->out_ctx, 0);
1504 
1505 		ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, 0);
1506 		ep_ctx->ep_info &= cpu_to_le32(~EP_STATE_MASK);/* must clear */
1507 		ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1508 		ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1509 
1510 		ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1511 		ctrl_ctx->drop_flags = 0;
1512 
1513 		ret = xhci_configure_endpoint(xhci, vdev->udev, command,
1514 					      true, false);
1515 		/* Clean up the input context for later use by bandwidth functions */
1516 		ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1517 		break;
1518 	default:
1519 		dev_dbg(&vdev->udev->dev, "incorrect max packet size %d for ep0\n",
1520 			max_packet_size);
1521 		return -EINVAL;
1522 	}
1523 
1524 	kfree(command->completion);
1525 	kfree(command);
1526 
1527 	return ret;
1528 }
1529 
1530 /*
1531  * non-error returns are a promise to giveback() the urb later
1532  * we drop ownership so next owner (or urb unlink) can get it
1533  */
1534 static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1535 {
1536 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1537 	unsigned long flags;
1538 	int ret = 0;
1539 	unsigned int slot_id, ep_index;
1540 	unsigned int *ep_state;
1541 	struct urb_priv	*urb_priv;
1542 	int num_tds;
1543 
1544 	ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1545 
1546 	if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1547 		num_tds = urb->number_of_packets;
1548 	else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
1549 	    urb->transfer_buffer_length > 0 &&
1550 	    urb->transfer_flags & URB_ZERO_PACKET &&
1551 	    !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
1552 		num_tds = 2;
1553 	else
1554 		num_tds = 1;
1555 
1556 	urb_priv = kzalloc(struct_size(urb_priv, td, num_tds), mem_flags);
1557 	if (!urb_priv)
1558 		return -ENOMEM;
1559 
1560 	urb_priv->num_tds = num_tds;
1561 	urb_priv->num_tds_done = 0;
1562 	urb->hcpriv = urb_priv;
1563 
1564 	trace_xhci_urb_enqueue(urb);
1565 
1566 	spin_lock_irqsave(&xhci->lock, flags);
1567 
1568 	ret = xhci_check_args(hcd, urb->dev, urb->ep,
1569 			      true, true, __func__);
1570 	if (ret <= 0) {
1571 		ret = ret ? ret : -EINVAL;
1572 		goto free_priv;
1573 	}
1574 
1575 	slot_id = urb->dev->slot_id;
1576 
1577 	if (!HCD_HW_ACCESSIBLE(hcd)) {
1578 		ret = -ESHUTDOWN;
1579 		goto free_priv;
1580 	}
1581 
1582 	if (xhci->devs[slot_id]->flags & VDEV_PORT_ERROR) {
1583 		xhci_dbg(xhci, "Can't queue urb, port error, link inactive\n");
1584 		ret = -ENODEV;
1585 		goto free_priv;
1586 	}
1587 
1588 	if (xhci->xhc_state & XHCI_STATE_DYING) {
1589 		xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n",
1590 			 urb->ep->desc.bEndpointAddress, urb);
1591 		ret = -ESHUTDOWN;
1592 		goto free_priv;
1593 	}
1594 
1595 	ep_state = &xhci->devs[slot_id]->eps[ep_index].ep_state;
1596 
1597 	if (*ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) {
1598 		xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n",
1599 			  *ep_state);
1600 		ret = -EINVAL;
1601 		goto free_priv;
1602 	}
1603 	if (*ep_state & EP_SOFT_CLEAR_TOGGLE) {
1604 		xhci_warn(xhci, "Can't enqueue URB while manually clearing toggle\n");
1605 		ret = -EINVAL;
1606 		goto free_priv;
1607 	}
1608 
1609 	/* Class driver might not be aware ep halted due to async URB giveback */
1610 	if (*ep_state & EP_STALLED)
1611 		dev_dbg(&urb->dev->dev, "URB %p queued before clearing halt\n",
1612 			urb);
1613 
1614 	switch (usb_endpoint_type(&urb->ep->desc)) {
1615 
1616 	case USB_ENDPOINT_XFER_CONTROL:
1617 		ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1618 					 slot_id, ep_index);
1619 		break;
1620 	case USB_ENDPOINT_XFER_BULK:
1621 		ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1622 					 slot_id, ep_index);
1623 		break;
1624 	case USB_ENDPOINT_XFER_INT:
1625 		ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1626 				slot_id, ep_index);
1627 		break;
1628 	case USB_ENDPOINT_XFER_ISOC:
1629 		ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1630 				slot_id, ep_index);
1631 	}
1632 
1633 	if (ret) {
1634 free_priv:
1635 		xhci_urb_free_priv(urb_priv);
1636 		urb->hcpriv = NULL;
1637 	}
1638 	spin_unlock_irqrestore(&xhci->lock, flags);
1639 	return ret;
1640 }
1641 
1642 /*
1643  * Remove the URB's TD from the endpoint ring.  This may cause the HC to stop
1644  * USB transfers, potentially stopping in the middle of a TRB buffer.  The HC
1645  * should pick up where it left off in the TD, unless a Set Transfer Ring
1646  * Dequeue Pointer is issued.
1647  *
1648  * The TRBs that make up the buffers for the canceled URB will be "removed" from
1649  * the ring.  Since the ring is a contiguous structure, they can't be physically
1650  * removed.  Instead, there are two options:
1651  *
1652  *  1) If the HC is in the middle of processing the URB to be canceled, we
1653  *     simply move the ring's dequeue pointer past those TRBs using the Set
1654  *     Transfer Ring Dequeue Pointer command.  This will be the common case,
1655  *     when drivers timeout on the last submitted URB and attempt to cancel.
1656  *
1657  *  2) If the HC is in the middle of a different TD, we turn the TRBs into a
1658  *     series of 1-TRB transfer no-op TDs.  (No-ops shouldn't be chained.)  The
1659  *     HC will need to invalidate the any TRBs it has cached after the stop
1660  *     endpoint command, as noted in the xHCI 0.95 errata.
1661  *
1662  *  3) The TD may have completed by the time the Stop Endpoint Command
1663  *     completes, so software needs to handle that case too.
1664  *
1665  * This function should protect against the TD enqueueing code ringing the
1666  * doorbell while this code is waiting for a Stop Endpoint command to complete.
1667  * It also needs to account for multiple cancellations on happening at the same
1668  * time for the same endpoint.
1669  *
1670  * Note that this function can be called in any context, or so says
1671  * usb_hcd_unlink_urb()
1672  */
1673 static int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1674 {
1675 	unsigned long flags;
1676 	int ret, i;
1677 	u32 temp;
1678 	struct xhci_hcd *xhci;
1679 	struct urb_priv	*urb_priv;
1680 	struct xhci_td *td;
1681 	unsigned int ep_index;
1682 	struct xhci_ring *ep_ring;
1683 	struct xhci_virt_ep *ep;
1684 	struct xhci_command *command;
1685 	struct xhci_virt_device *vdev;
1686 
1687 	xhci = hcd_to_xhci(hcd);
1688 	spin_lock_irqsave(&xhci->lock, flags);
1689 
1690 	trace_xhci_urb_dequeue(urb);
1691 
1692 	/* Make sure the URB hasn't completed or been unlinked already */
1693 	ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1694 	if (ret)
1695 		goto done;
1696 
1697 	/* give back URB now if we can't queue it for cancel */
1698 	vdev = xhci->devs[urb->dev->slot_id];
1699 	urb_priv = urb->hcpriv;
1700 	if (!vdev || !urb_priv)
1701 		goto err_giveback;
1702 
1703 	ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1704 	ep = &vdev->eps[ep_index];
1705 	ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1706 	if (!ep || !ep_ring)
1707 		goto err_giveback;
1708 
1709 	/* If xHC is dead take it down and return ALL URBs in xhci_hc_died() */
1710 	temp = readl(&xhci->op_regs->status);
1711 	if (temp == ~(u32)0 || xhci->xhc_state & XHCI_STATE_DYING) {
1712 		xhci_hc_died(xhci);
1713 		goto done;
1714 	}
1715 
1716 	/*
1717 	 * check ring is not re-allocated since URB was enqueued. If it is, then
1718 	 * make sure none of the ring related pointers in this URB private data
1719 	 * are touched, such as td_list, otherwise we overwrite freed data
1720 	 */
1721 	if (!td_on_ring(&urb_priv->td[0], ep_ring)) {
1722 		xhci_err(xhci, "Canceled URB td not found on endpoint ring");
1723 		for (i = urb_priv->num_tds_done; i < urb_priv->num_tds; i++) {
1724 			td = &urb_priv->td[i];
1725 			if (!list_empty(&td->cancelled_td_list))
1726 				list_del_init(&td->cancelled_td_list);
1727 		}
1728 		goto err_giveback;
1729 	}
1730 
1731 	if (xhci->xhc_state & XHCI_STATE_HALTED) {
1732 		xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1733 				"HC halted, freeing TD manually.");
1734 		for (i = urb_priv->num_tds_done;
1735 		     i < urb_priv->num_tds;
1736 		     i++) {
1737 			td = &urb_priv->td[i];
1738 			if (!list_empty(&td->td_list))
1739 				list_del_init(&td->td_list);
1740 			if (!list_empty(&td->cancelled_td_list))
1741 				list_del_init(&td->cancelled_td_list);
1742 		}
1743 		goto err_giveback;
1744 	}
1745 
1746 	i = urb_priv->num_tds_done;
1747 	if (i < urb_priv->num_tds)
1748 		xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1749 				"Cancel URB %p, dev %s, ep 0x%x, "
1750 				"starting at offset 0x%llx",
1751 				urb, urb->dev->devpath,
1752 				urb->ep->desc.bEndpointAddress,
1753 				(unsigned long long) xhci_trb_virt_to_dma(
1754 					urb_priv->td[i].start_seg,
1755 					urb_priv->td[i].start_trb));
1756 
1757 	for (; i < urb_priv->num_tds; i++) {
1758 		td = &urb_priv->td[i];
1759 		/* TD can already be on cancelled list if ep halted on it */
1760 		if (list_empty(&td->cancelled_td_list)) {
1761 			td->cancel_status = TD_DIRTY;
1762 			list_add_tail(&td->cancelled_td_list,
1763 				      &ep->cancelled_td_list);
1764 		}
1765 	}
1766 
1767 	/* These completion handlers will sort out cancelled TDs for us */
1768 	if (ep->ep_state & (EP_STOP_CMD_PENDING | EP_HALTED | SET_DEQ_PENDING)) {
1769 		xhci_dbg(xhci, "Not queuing Stop Endpoint on slot %d ep %d in state 0x%x\n",
1770 				urb->dev->slot_id, ep_index, ep->ep_state);
1771 		goto done;
1772 	}
1773 
1774 	/* In these cases no commands are pending but the endpoint is stopped */
1775 	if (ep->ep_state & (EP_CLEARING_TT | EP_STALLED)) {
1776 		/* and cancelled TDs can be given back right away */
1777 		xhci_dbg(xhci, "Invalidating TDs instantly on slot %d ep %d in state 0x%x\n",
1778 				urb->dev->slot_id, ep_index, ep->ep_state);
1779 		xhci_process_cancelled_tds(ep);
1780 	} else {
1781 		/* Otherwise, queue a new Stop Endpoint command */
1782 		command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
1783 		if (!command) {
1784 			ret = -ENOMEM;
1785 			goto done;
1786 		}
1787 		ep->stop_time = jiffies;
1788 		ep->ep_state |= EP_STOP_CMD_PENDING;
1789 		xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1790 					 ep_index, 0);
1791 		xhci_ring_cmd_db(xhci);
1792 	}
1793 done:
1794 	spin_unlock_irqrestore(&xhci->lock, flags);
1795 	return ret;
1796 
1797 err_giveback:
1798 	if (urb_priv)
1799 		xhci_urb_free_priv(urb_priv);
1800 	usb_hcd_unlink_urb_from_ep(hcd, urb);
1801 	spin_unlock_irqrestore(&xhci->lock, flags);
1802 	usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1803 	return ret;
1804 }
1805 
1806 /* Drop an endpoint from a new bandwidth configuration for this device.
1807  * Only one call to this function is allowed per endpoint before
1808  * check_bandwidth() or reset_bandwidth() must be called.
1809  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1810  * add the endpoint to the schedule with possibly new parameters denoted by a
1811  * different endpoint descriptor in usb_host_endpoint.
1812  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1813  * not allowed.
1814  *
1815  * The USB core will not allow URBs to be queued to an endpoint that is being
1816  * disabled, so there's no need for mutual exclusion to protect
1817  * the xhci->devs[slot_id] structure.
1818  */
1819 int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1820 		       struct usb_host_endpoint *ep)
1821 {
1822 	struct xhci_hcd *xhci;
1823 	struct xhci_container_ctx *in_ctx, *out_ctx;
1824 	struct xhci_input_control_ctx *ctrl_ctx;
1825 	unsigned int ep_index;
1826 	struct xhci_ep_ctx *ep_ctx;
1827 	u32 drop_flag;
1828 	u32 new_add_flags, new_drop_flags;
1829 	int ret;
1830 
1831 	ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1832 	if (ret <= 0)
1833 		return ret;
1834 	xhci = hcd_to_xhci(hcd);
1835 	if (xhci->xhc_state & XHCI_STATE_DYING)
1836 		return -ENODEV;
1837 
1838 	xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1839 	drop_flag = xhci_get_endpoint_flag(&ep->desc);
1840 	if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1841 		xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1842 				__func__, drop_flag);
1843 		return 0;
1844 	}
1845 
1846 	in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1847 	out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1848 	ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1849 	if (!ctrl_ctx) {
1850 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1851 				__func__);
1852 		return 0;
1853 	}
1854 
1855 	ep_index = xhci_get_endpoint_index(&ep->desc);
1856 	ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1857 	/* If the HC already knows the endpoint is disabled,
1858 	 * or the HCD has noted it is disabled, ignore this request
1859 	 */
1860 	if ((GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) ||
1861 	    le32_to_cpu(ctrl_ctx->drop_flags) &
1862 	    xhci_get_endpoint_flag(&ep->desc)) {
1863 		/* Do not warn when called after a usb_device_reset */
1864 		if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1865 			xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1866 				  __func__, ep);
1867 		return 0;
1868 	}
1869 
1870 	ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1871 	new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1872 
1873 	ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1874 	new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1875 
1876 	xhci_debugfs_remove_endpoint(xhci, xhci->devs[udev->slot_id], ep_index);
1877 
1878 	xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1879 
1880 	xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1881 			(unsigned int) ep->desc.bEndpointAddress,
1882 			udev->slot_id,
1883 			(unsigned int) new_drop_flags,
1884 			(unsigned int) new_add_flags);
1885 	return 0;
1886 }
1887 EXPORT_SYMBOL_GPL(xhci_drop_endpoint);
1888 
1889 /* Add an endpoint to a new possible bandwidth configuration for this device.
1890  * Only one call to this function is allowed per endpoint before
1891  * check_bandwidth() or reset_bandwidth() must be called.
1892  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1893  * add the endpoint to the schedule with possibly new parameters denoted by a
1894  * different endpoint descriptor in usb_host_endpoint.
1895  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1896  * not allowed.
1897  *
1898  * The USB core will not allow URBs to be queued to an endpoint until the
1899  * configuration or alt setting is installed in the device, so there's no need
1900  * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1901  */
1902 int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1903 		      struct usb_host_endpoint *ep)
1904 {
1905 	struct xhci_hcd *xhci;
1906 	struct xhci_container_ctx *in_ctx;
1907 	unsigned int ep_index;
1908 	struct xhci_input_control_ctx *ctrl_ctx;
1909 	struct xhci_ep_ctx *ep_ctx;
1910 	u32 added_ctxs;
1911 	u32 new_add_flags, new_drop_flags;
1912 	struct xhci_virt_device *virt_dev;
1913 	int ret = 0;
1914 
1915 	ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1916 	if (ret <= 0) {
1917 		/* So we won't queue a reset ep command for a root hub */
1918 		ep->hcpriv = NULL;
1919 		return ret;
1920 	}
1921 	xhci = hcd_to_xhci(hcd);
1922 	if (xhci->xhc_state & XHCI_STATE_DYING)
1923 		return -ENODEV;
1924 
1925 	added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1926 	if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1927 		/* FIXME when we have to issue an evaluate endpoint command to
1928 		 * deal with ep0 max packet size changing once we get the
1929 		 * descriptors
1930 		 */
1931 		xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1932 				__func__, added_ctxs);
1933 		return 0;
1934 	}
1935 
1936 	virt_dev = xhci->devs[udev->slot_id];
1937 	in_ctx = virt_dev->in_ctx;
1938 	ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1939 	if (!ctrl_ctx) {
1940 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1941 				__func__);
1942 		return 0;
1943 	}
1944 
1945 	ep_index = xhci_get_endpoint_index(&ep->desc);
1946 	/* If this endpoint is already in use, and the upper layers are trying
1947 	 * to add it again without dropping it, reject the addition.
1948 	 */
1949 	if (virt_dev->eps[ep_index].ring &&
1950 			!(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
1951 		xhci_warn(xhci, "Trying to add endpoint 0x%x "
1952 				"without dropping it.\n",
1953 				(unsigned int) ep->desc.bEndpointAddress);
1954 		return -EINVAL;
1955 	}
1956 
1957 	/* If the HCD has already noted the endpoint is enabled,
1958 	 * ignore this request.
1959 	 */
1960 	if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
1961 		xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1962 				__func__, ep);
1963 		return 0;
1964 	}
1965 
1966 	/*
1967 	 * Configuration and alternate setting changes must be done in
1968 	 * process context, not interrupt context (or so documenation
1969 	 * for usb_set_interface() and usb_set_configuration() claim).
1970 	 */
1971 	if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1972 		dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1973 				__func__, ep->desc.bEndpointAddress);
1974 		return -ENOMEM;
1975 	}
1976 
1977 	ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1978 	new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1979 
1980 	/* If xhci_endpoint_disable() was called for this endpoint, but the
1981 	 * xHC hasn't been notified yet through the check_bandwidth() call,
1982 	 * this re-adds a new state for the endpoint from the new endpoint
1983 	 * descriptors.  We must drop and re-add this endpoint, so we leave the
1984 	 * drop flags alone.
1985 	 */
1986 	new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1987 
1988 	/* Store the usb_device pointer for later use */
1989 	ep->hcpriv = udev;
1990 
1991 	ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, ep_index);
1992 	trace_xhci_add_endpoint(ep_ctx);
1993 
1994 	xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1995 			(unsigned int) ep->desc.bEndpointAddress,
1996 			udev->slot_id,
1997 			(unsigned int) new_drop_flags,
1998 			(unsigned int) new_add_flags);
1999 	return 0;
2000 }
2001 EXPORT_SYMBOL_GPL(xhci_add_endpoint);
2002 
2003 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
2004 {
2005 	struct xhci_input_control_ctx *ctrl_ctx;
2006 	struct xhci_ep_ctx *ep_ctx;
2007 	struct xhci_slot_ctx *slot_ctx;
2008 	int i;
2009 
2010 	ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
2011 	if (!ctrl_ctx) {
2012 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2013 				__func__);
2014 		return;
2015 	}
2016 
2017 	/* When a device's add flag and drop flag are zero, any subsequent
2018 	 * configure endpoint command will leave that endpoint's state
2019 	 * untouched.  Make sure we don't leave any old state in the input
2020 	 * endpoint contexts.
2021 	 */
2022 	ctrl_ctx->drop_flags = 0;
2023 	ctrl_ctx->add_flags = 0;
2024 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2025 	slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2026 	/* Endpoint 0 is always valid */
2027 	slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
2028 	for (i = 1; i < 31; i++) {
2029 		ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
2030 		ep_ctx->ep_info = 0;
2031 		ep_ctx->ep_info2 = 0;
2032 		ep_ctx->deq = 0;
2033 		ep_ctx->tx_info = 0;
2034 	}
2035 }
2036 
2037 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
2038 		struct usb_device *udev, u32 *cmd_status)
2039 {
2040 	int ret;
2041 
2042 	switch (*cmd_status) {
2043 	case COMP_COMMAND_ABORTED:
2044 	case COMP_COMMAND_RING_STOPPED:
2045 		xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
2046 		ret = -ETIME;
2047 		break;
2048 	case COMP_RESOURCE_ERROR:
2049 		dev_warn(&udev->dev,
2050 			 "Not enough host controller resources for new device state.\n");
2051 		ret = -ENOMEM;
2052 		/* FIXME: can we allocate more resources for the HC? */
2053 		break;
2054 	case COMP_BANDWIDTH_ERROR:
2055 	case COMP_SECONDARY_BANDWIDTH_ERROR:
2056 		dev_warn(&udev->dev,
2057 			 "Not enough bandwidth for new device state.\n");
2058 		ret = -ENOSPC;
2059 		/* FIXME: can we go back to the old state? */
2060 		break;
2061 	case COMP_TRB_ERROR:
2062 		/* the HCD set up something wrong */
2063 		dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
2064 				"add flag = 1, "
2065 				"and endpoint is not disabled.\n");
2066 		ret = -EINVAL;
2067 		break;
2068 	case COMP_INCOMPATIBLE_DEVICE_ERROR:
2069 		dev_warn(&udev->dev,
2070 			 "ERROR: Incompatible device for endpoint configure command.\n");
2071 		ret = -ENODEV;
2072 		break;
2073 	case COMP_SUCCESS:
2074 		xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2075 				"Successful Endpoint Configure command");
2076 		ret = 0;
2077 		break;
2078 	default:
2079 		xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2080 				*cmd_status);
2081 		ret = -EINVAL;
2082 		break;
2083 	}
2084 	return ret;
2085 }
2086 
2087 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
2088 		struct usb_device *udev, u32 *cmd_status)
2089 {
2090 	int ret;
2091 
2092 	switch (*cmd_status) {
2093 	case COMP_COMMAND_ABORTED:
2094 	case COMP_COMMAND_RING_STOPPED:
2095 		xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
2096 		ret = -ETIME;
2097 		break;
2098 	case COMP_PARAMETER_ERROR:
2099 		dev_warn(&udev->dev,
2100 			 "WARN: xHCI driver setup invalid evaluate context command.\n");
2101 		ret = -EINVAL;
2102 		break;
2103 	case COMP_SLOT_NOT_ENABLED_ERROR:
2104 		dev_warn(&udev->dev,
2105 			"WARN: slot not enabled for evaluate context command.\n");
2106 		ret = -EINVAL;
2107 		break;
2108 	case COMP_CONTEXT_STATE_ERROR:
2109 		dev_warn(&udev->dev,
2110 			"WARN: invalid context state for evaluate context command.\n");
2111 		ret = -EINVAL;
2112 		break;
2113 	case COMP_INCOMPATIBLE_DEVICE_ERROR:
2114 		dev_warn(&udev->dev,
2115 			"ERROR: Incompatible device for evaluate context command.\n");
2116 		ret = -ENODEV;
2117 		break;
2118 	case COMP_MAX_EXIT_LATENCY_TOO_LARGE_ERROR:
2119 		/* Max Exit Latency too large error */
2120 		dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
2121 		ret = -EINVAL;
2122 		break;
2123 	case COMP_SUCCESS:
2124 		xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2125 				"Successful evaluate context command");
2126 		ret = 0;
2127 		break;
2128 	default:
2129 		xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2130 			*cmd_status);
2131 		ret = -EINVAL;
2132 		break;
2133 	}
2134 	return ret;
2135 }
2136 
2137 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
2138 		struct xhci_input_control_ctx *ctrl_ctx)
2139 {
2140 	u32 valid_add_flags;
2141 	u32 valid_drop_flags;
2142 
2143 	/* Ignore the slot flag (bit 0), and the default control endpoint flag
2144 	 * (bit 1).  The default control endpoint is added during the Address
2145 	 * Device command and is never removed until the slot is disabled.
2146 	 */
2147 	valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2148 	valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2149 
2150 	/* Use hweight32 to count the number of ones in the add flags, or
2151 	 * number of endpoints added.  Don't count endpoints that are changed
2152 	 * (both added and dropped).
2153 	 */
2154 	return hweight32(valid_add_flags) -
2155 		hweight32(valid_add_flags & valid_drop_flags);
2156 }
2157 
2158 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
2159 		struct xhci_input_control_ctx *ctrl_ctx)
2160 {
2161 	u32 valid_add_flags;
2162 	u32 valid_drop_flags;
2163 
2164 	valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2165 	valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2166 
2167 	return hweight32(valid_drop_flags) -
2168 		hweight32(valid_add_flags & valid_drop_flags);
2169 }
2170 
2171 /*
2172  * We need to reserve the new number of endpoints before the configure endpoint
2173  * command completes.  We can't subtract the dropped endpoints from the number
2174  * of active endpoints until the command completes because we can oversubscribe
2175  * the host in this case:
2176  *
2177  *  - the first configure endpoint command drops more endpoints than it adds
2178  *  - a second configure endpoint command that adds more endpoints is queued
2179  *  - the first configure endpoint command fails, so the config is unchanged
2180  *  - the second command may succeed, even though there isn't enough resources
2181  *
2182  * Must be called with xhci->lock held.
2183  */
2184 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
2185 		struct xhci_input_control_ctx *ctrl_ctx)
2186 {
2187 	u32 added_eps;
2188 
2189 	added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2190 	if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
2191 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2192 				"Not enough ep ctxs: "
2193 				"%u active, need to add %u, limit is %u.",
2194 				xhci->num_active_eps, added_eps,
2195 				xhci->limit_active_eps);
2196 		return -ENOMEM;
2197 	}
2198 	xhci->num_active_eps += added_eps;
2199 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2200 			"Adding %u ep ctxs, %u now active.", added_eps,
2201 			xhci->num_active_eps);
2202 	return 0;
2203 }
2204 
2205 /*
2206  * The configure endpoint was failed by the xHC for some other reason, so we
2207  * need to revert the resources that failed configuration would have used.
2208  *
2209  * Must be called with xhci->lock held.
2210  */
2211 static void xhci_free_host_resources(struct xhci_hcd *xhci,
2212 		struct xhci_input_control_ctx *ctrl_ctx)
2213 {
2214 	u32 num_failed_eps;
2215 
2216 	num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2217 	xhci->num_active_eps -= num_failed_eps;
2218 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2219 			"Removing %u failed ep ctxs, %u now active.",
2220 			num_failed_eps,
2221 			xhci->num_active_eps);
2222 }
2223 
2224 /*
2225  * Now that the command has completed, clean up the active endpoint count by
2226  * subtracting out the endpoints that were dropped (but not changed).
2227  *
2228  * Must be called with xhci->lock held.
2229  */
2230 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
2231 		struct xhci_input_control_ctx *ctrl_ctx)
2232 {
2233 	u32 num_dropped_eps;
2234 
2235 	num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
2236 	xhci->num_active_eps -= num_dropped_eps;
2237 	if (num_dropped_eps)
2238 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2239 				"Removing %u dropped ep ctxs, %u now active.",
2240 				num_dropped_eps,
2241 				xhci->num_active_eps);
2242 }
2243 
2244 static unsigned int xhci_get_block_size(struct usb_device *udev)
2245 {
2246 	switch (udev->speed) {
2247 	case USB_SPEED_LOW:
2248 	case USB_SPEED_FULL:
2249 		return FS_BLOCK;
2250 	case USB_SPEED_HIGH:
2251 		return HS_BLOCK;
2252 	case USB_SPEED_SUPER:
2253 	case USB_SPEED_SUPER_PLUS:
2254 		return SS_BLOCK;
2255 	case USB_SPEED_UNKNOWN:
2256 	default:
2257 		/* Should never happen */
2258 		return 1;
2259 	}
2260 }
2261 
2262 static unsigned int
2263 xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
2264 {
2265 	if (interval_bw->overhead[LS_OVERHEAD_TYPE])
2266 		return LS_OVERHEAD;
2267 	if (interval_bw->overhead[FS_OVERHEAD_TYPE])
2268 		return FS_OVERHEAD;
2269 	return HS_OVERHEAD;
2270 }
2271 
2272 /* If we are changing a LS/FS device under a HS hub,
2273  * make sure (if we are activating a new TT) that the HS bus has enough
2274  * bandwidth for this new TT.
2275  */
2276 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2277 		struct xhci_virt_device *virt_dev,
2278 		int old_active_eps)
2279 {
2280 	struct xhci_interval_bw_table *bw_table;
2281 	struct xhci_tt_bw_info *tt_info;
2282 
2283 	/* Find the bandwidth table for the root port this TT is attached to. */
2284 	bw_table = &xhci->rh_bw[virt_dev->rhub_port->hw_portnum].bw_table;
2285 	tt_info = virt_dev->tt_info;
2286 	/* If this TT already had active endpoints, the bandwidth for this TT
2287 	 * has already been added.  Removing all periodic endpoints (and thus
2288 	 * making the TT enactive) will only decrease the bandwidth used.
2289 	 */
2290 	if (old_active_eps)
2291 		return 0;
2292 	if (old_active_eps == 0 && tt_info->active_eps != 0) {
2293 		if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2294 			return -ENOMEM;
2295 		return 0;
2296 	}
2297 	/* Not sure why we would have no new active endpoints...
2298 	 *
2299 	 * Maybe because of an Evaluate Context change for a hub update or a
2300 	 * control endpoint 0 max packet size change?
2301 	 * FIXME: skip the bandwidth calculation in that case.
2302 	 */
2303 	return 0;
2304 }
2305 
2306 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2307 		struct xhci_virt_device *virt_dev)
2308 {
2309 	unsigned int bw_reserved;
2310 
2311 	bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2312 	if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2313 		return -ENOMEM;
2314 
2315 	bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2316 	if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2317 		return -ENOMEM;
2318 
2319 	return 0;
2320 }
2321 
2322 /*
2323  * This algorithm is a very conservative estimate of the worst-case scheduling
2324  * scenario for any one interval.  The hardware dynamically schedules the
2325  * packets, so we can't tell which microframe could be the limiting factor in
2326  * the bandwidth scheduling.  This only takes into account periodic endpoints.
2327  *
2328  * Obviously, we can't solve an NP complete problem to find the minimum worst
2329  * case scenario.  Instead, we come up with an estimate that is no less than
2330  * the worst case bandwidth used for any one microframe, but may be an
2331  * over-estimate.
2332  *
2333  * We walk the requirements for each endpoint by interval, starting with the
2334  * smallest interval, and place packets in the schedule where there is only one
2335  * possible way to schedule packets for that interval.  In order to simplify
2336  * this algorithm, we record the largest max packet size for each interval, and
2337  * assume all packets will be that size.
2338  *
2339  * For interval 0, we obviously must schedule all packets for each interval.
2340  * The bandwidth for interval 0 is just the amount of data to be transmitted
2341  * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2342  * the number of packets).
2343  *
2344  * For interval 1, we have two possible microframes to schedule those packets
2345  * in.  For this algorithm, if we can schedule the same number of packets for
2346  * each possible scheduling opportunity (each microframe), we will do so.  The
2347  * remaining number of packets will be saved to be transmitted in the gaps in
2348  * the next interval's scheduling sequence.
2349  *
2350  * As we move those remaining packets to be scheduled with interval 2 packets,
2351  * we have to double the number of remaining packets to transmit.  This is
2352  * because the intervals are actually powers of 2, and we would be transmitting
2353  * the previous interval's packets twice in this interval.  We also have to be
2354  * sure that when we look at the largest max packet size for this interval, we
2355  * also look at the largest max packet size for the remaining packets and take
2356  * the greater of the two.
2357  *
2358  * The algorithm continues to evenly distribute packets in each scheduling
2359  * opportunity, and push the remaining packets out, until we get to the last
2360  * interval.  Then those packets and their associated overhead are just added
2361  * to the bandwidth used.
2362  */
2363 static int xhci_check_bw_table(struct xhci_hcd *xhci,
2364 		struct xhci_virt_device *virt_dev,
2365 		int old_active_eps)
2366 {
2367 	unsigned int bw_reserved;
2368 	unsigned int max_bandwidth;
2369 	unsigned int bw_used;
2370 	unsigned int block_size;
2371 	struct xhci_interval_bw_table *bw_table;
2372 	unsigned int packet_size = 0;
2373 	unsigned int overhead = 0;
2374 	unsigned int packets_transmitted = 0;
2375 	unsigned int packets_remaining = 0;
2376 	unsigned int i;
2377 
2378 	if (virt_dev->udev->speed >= USB_SPEED_SUPER)
2379 		return xhci_check_ss_bw(xhci, virt_dev);
2380 
2381 	if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2382 		max_bandwidth = HS_BW_LIMIT;
2383 		/* Convert percent of bus BW reserved to blocks reserved */
2384 		bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2385 	} else {
2386 		max_bandwidth = FS_BW_LIMIT;
2387 		bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2388 	}
2389 
2390 	bw_table = virt_dev->bw_table;
2391 	/* We need to translate the max packet size and max ESIT payloads into
2392 	 * the units the hardware uses.
2393 	 */
2394 	block_size = xhci_get_block_size(virt_dev->udev);
2395 
2396 	/* If we are manipulating a LS/FS device under a HS hub, double check
2397 	 * that the HS bus has enough bandwidth if we are activing a new TT.
2398 	 */
2399 	if (virt_dev->tt_info) {
2400 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2401 				"Recalculating BW for rootport %u",
2402 				virt_dev->rhub_port->hw_portnum + 1);
2403 		if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2404 			xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2405 					"newly activated TT.\n");
2406 			return -ENOMEM;
2407 		}
2408 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2409 				"Recalculating BW for TT slot %u port %u",
2410 				virt_dev->tt_info->slot_id,
2411 				virt_dev->tt_info->ttport);
2412 	} else {
2413 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2414 				"Recalculating BW for rootport %u",
2415 				virt_dev->rhub_port->hw_portnum + 1);
2416 	}
2417 
2418 	/* Add in how much bandwidth will be used for interval zero, or the
2419 	 * rounded max ESIT payload + number of packets * largest overhead.
2420 	 */
2421 	bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2422 		bw_table->interval_bw[0].num_packets *
2423 		xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2424 
2425 	for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2426 		unsigned int bw_added;
2427 		unsigned int largest_mps;
2428 		unsigned int interval_overhead;
2429 
2430 		/*
2431 		 * How many packets could we transmit in this interval?
2432 		 * If packets didn't fit in the previous interval, we will need
2433 		 * to transmit that many packets twice within this interval.
2434 		 */
2435 		packets_remaining = 2 * packets_remaining +
2436 			bw_table->interval_bw[i].num_packets;
2437 
2438 		/* Find the largest max packet size of this or the previous
2439 		 * interval.
2440 		 */
2441 		if (list_empty(&bw_table->interval_bw[i].endpoints))
2442 			largest_mps = 0;
2443 		else {
2444 			struct xhci_virt_ep *virt_ep;
2445 			struct list_head *ep_entry;
2446 
2447 			ep_entry = bw_table->interval_bw[i].endpoints.next;
2448 			virt_ep = list_entry(ep_entry,
2449 					struct xhci_virt_ep, bw_endpoint_list);
2450 			/* Convert to blocks, rounding up */
2451 			largest_mps = DIV_ROUND_UP(
2452 					virt_ep->bw_info.max_packet_size,
2453 					block_size);
2454 		}
2455 		if (largest_mps > packet_size)
2456 			packet_size = largest_mps;
2457 
2458 		/* Use the larger overhead of this or the previous interval. */
2459 		interval_overhead = xhci_get_largest_overhead(
2460 				&bw_table->interval_bw[i]);
2461 		if (interval_overhead > overhead)
2462 			overhead = interval_overhead;
2463 
2464 		/* How many packets can we evenly distribute across
2465 		 * (1 << (i + 1)) possible scheduling opportunities?
2466 		 */
2467 		packets_transmitted = packets_remaining >> (i + 1);
2468 
2469 		/* Add in the bandwidth used for those scheduled packets */
2470 		bw_added = packets_transmitted * (overhead + packet_size);
2471 
2472 		/* How many packets do we have remaining to transmit? */
2473 		packets_remaining = packets_remaining % (1 << (i + 1));
2474 
2475 		/* What largest max packet size should those packets have? */
2476 		/* If we've transmitted all packets, don't carry over the
2477 		 * largest packet size.
2478 		 */
2479 		if (packets_remaining == 0) {
2480 			packet_size = 0;
2481 			overhead = 0;
2482 		} else if (packets_transmitted > 0) {
2483 			/* Otherwise if we do have remaining packets, and we've
2484 			 * scheduled some packets in this interval, take the
2485 			 * largest max packet size from endpoints with this
2486 			 * interval.
2487 			 */
2488 			packet_size = largest_mps;
2489 			overhead = interval_overhead;
2490 		}
2491 		/* Otherwise carry over packet_size and overhead from the last
2492 		 * time we had a remainder.
2493 		 */
2494 		bw_used += bw_added;
2495 		if (bw_used > max_bandwidth) {
2496 			xhci_warn(xhci, "Not enough bandwidth. "
2497 					"Proposed: %u, Max: %u\n",
2498 				bw_used, max_bandwidth);
2499 			return -ENOMEM;
2500 		}
2501 	}
2502 	/*
2503 	 * Ok, we know we have some packets left over after even-handedly
2504 	 * scheduling interval 15.  We don't know which microframes they will
2505 	 * fit into, so we over-schedule and say they will be scheduled every
2506 	 * microframe.
2507 	 */
2508 	if (packets_remaining > 0)
2509 		bw_used += overhead + packet_size;
2510 
2511 	if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2512 		/* OK, we're manipulating a HS device attached to a
2513 		 * root port bandwidth domain.  Include the number of active TTs
2514 		 * in the bandwidth used.
2515 		 */
2516 		bw_used += TT_HS_OVERHEAD *
2517 			xhci->rh_bw[virt_dev->rhub_port->hw_portnum].num_active_tts;
2518 	}
2519 
2520 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2521 		"Final bandwidth: %u, Limit: %u, Reserved: %u, "
2522 		"Available: %u " "percent",
2523 		bw_used, max_bandwidth, bw_reserved,
2524 		(max_bandwidth - bw_used - bw_reserved) * 100 /
2525 		max_bandwidth);
2526 
2527 	bw_used += bw_reserved;
2528 	if (bw_used > max_bandwidth) {
2529 		xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2530 				bw_used, max_bandwidth);
2531 		return -ENOMEM;
2532 	}
2533 
2534 	bw_table->bw_used = bw_used;
2535 	return 0;
2536 }
2537 
2538 static bool xhci_is_async_ep(unsigned int ep_type)
2539 {
2540 	return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2541 					ep_type != ISOC_IN_EP &&
2542 					ep_type != INT_IN_EP);
2543 }
2544 
2545 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2546 {
2547 	return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
2548 }
2549 
2550 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2551 {
2552 	unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2553 
2554 	if (ep_bw->ep_interval == 0)
2555 		return SS_OVERHEAD_BURST +
2556 			(ep_bw->mult * ep_bw->num_packets *
2557 					(SS_OVERHEAD + mps));
2558 	return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2559 				(SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2560 				1 << ep_bw->ep_interval);
2561 
2562 }
2563 
2564 static void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2565 		struct xhci_bw_info *ep_bw,
2566 		struct xhci_interval_bw_table *bw_table,
2567 		struct usb_device *udev,
2568 		struct xhci_virt_ep *virt_ep,
2569 		struct xhci_tt_bw_info *tt_info)
2570 {
2571 	struct xhci_interval_bw	*interval_bw;
2572 	int normalized_interval;
2573 
2574 	if (xhci_is_async_ep(ep_bw->type))
2575 		return;
2576 
2577 	if (udev->speed >= USB_SPEED_SUPER) {
2578 		if (xhci_is_sync_in_ep(ep_bw->type))
2579 			xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2580 				xhci_get_ss_bw_consumed(ep_bw);
2581 		else
2582 			xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2583 				xhci_get_ss_bw_consumed(ep_bw);
2584 		return;
2585 	}
2586 
2587 	/* SuperSpeed endpoints never get added to intervals in the table, so
2588 	 * this check is only valid for HS/FS/LS devices.
2589 	 */
2590 	if (list_empty(&virt_ep->bw_endpoint_list))
2591 		return;
2592 	/* For LS/FS devices, we need to translate the interval expressed in
2593 	 * microframes to frames.
2594 	 */
2595 	if (udev->speed == USB_SPEED_HIGH)
2596 		normalized_interval = ep_bw->ep_interval;
2597 	else
2598 		normalized_interval = ep_bw->ep_interval - 3;
2599 
2600 	if (normalized_interval == 0)
2601 		bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2602 	interval_bw = &bw_table->interval_bw[normalized_interval];
2603 	interval_bw->num_packets -= ep_bw->num_packets;
2604 	switch (udev->speed) {
2605 	case USB_SPEED_LOW:
2606 		interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2607 		break;
2608 	case USB_SPEED_FULL:
2609 		interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2610 		break;
2611 	case USB_SPEED_HIGH:
2612 		interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2613 		break;
2614 	default:
2615 		/* Should never happen because only LS/FS/HS endpoints will get
2616 		 * added to the endpoint list.
2617 		 */
2618 		return;
2619 	}
2620 	if (tt_info)
2621 		tt_info->active_eps -= 1;
2622 	list_del_init(&virt_ep->bw_endpoint_list);
2623 }
2624 
2625 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2626 		struct xhci_bw_info *ep_bw,
2627 		struct xhci_interval_bw_table *bw_table,
2628 		struct usb_device *udev,
2629 		struct xhci_virt_ep *virt_ep,
2630 		struct xhci_tt_bw_info *tt_info)
2631 {
2632 	struct xhci_interval_bw	*interval_bw;
2633 	struct xhci_virt_ep *smaller_ep;
2634 	int normalized_interval;
2635 
2636 	if (xhci_is_async_ep(ep_bw->type))
2637 		return;
2638 
2639 	if (udev->speed == USB_SPEED_SUPER) {
2640 		if (xhci_is_sync_in_ep(ep_bw->type))
2641 			xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2642 				xhci_get_ss_bw_consumed(ep_bw);
2643 		else
2644 			xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2645 				xhci_get_ss_bw_consumed(ep_bw);
2646 		return;
2647 	}
2648 
2649 	/* For LS/FS devices, we need to translate the interval expressed in
2650 	 * microframes to frames.
2651 	 */
2652 	if (udev->speed == USB_SPEED_HIGH)
2653 		normalized_interval = ep_bw->ep_interval;
2654 	else
2655 		normalized_interval = ep_bw->ep_interval - 3;
2656 
2657 	if (normalized_interval == 0)
2658 		bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2659 	interval_bw = &bw_table->interval_bw[normalized_interval];
2660 	interval_bw->num_packets += ep_bw->num_packets;
2661 	switch (udev->speed) {
2662 	case USB_SPEED_LOW:
2663 		interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2664 		break;
2665 	case USB_SPEED_FULL:
2666 		interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2667 		break;
2668 	case USB_SPEED_HIGH:
2669 		interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2670 		break;
2671 	default:
2672 		/* Should never happen because only LS/FS/HS endpoints will get
2673 		 * added to the endpoint list.
2674 		 */
2675 		return;
2676 	}
2677 
2678 	if (tt_info)
2679 		tt_info->active_eps += 1;
2680 	/* Insert the endpoint into the list, largest max packet size first. */
2681 	list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2682 			bw_endpoint_list) {
2683 		if (ep_bw->max_packet_size >=
2684 				smaller_ep->bw_info.max_packet_size) {
2685 			/* Add the new ep before the smaller endpoint */
2686 			list_add_tail(&virt_ep->bw_endpoint_list,
2687 					&smaller_ep->bw_endpoint_list);
2688 			return;
2689 		}
2690 	}
2691 	/* Add the new endpoint at the end of the list. */
2692 	list_add_tail(&virt_ep->bw_endpoint_list,
2693 			&interval_bw->endpoints);
2694 }
2695 
2696 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2697 		struct xhci_virt_device *virt_dev,
2698 		int old_active_eps)
2699 {
2700 	struct xhci_root_port_bw_info *rh_bw_info;
2701 	if (!virt_dev->tt_info)
2702 		return;
2703 
2704 	rh_bw_info = &xhci->rh_bw[virt_dev->rhub_port->hw_portnum];
2705 	if (old_active_eps == 0 &&
2706 				virt_dev->tt_info->active_eps != 0) {
2707 		rh_bw_info->num_active_tts += 1;
2708 		rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2709 	} else if (old_active_eps != 0 &&
2710 				virt_dev->tt_info->active_eps == 0) {
2711 		rh_bw_info->num_active_tts -= 1;
2712 		rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2713 	}
2714 }
2715 
2716 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2717 		struct xhci_virt_device *virt_dev,
2718 		struct xhci_container_ctx *in_ctx)
2719 {
2720 	struct xhci_bw_info ep_bw_info[31];
2721 	int i;
2722 	struct xhci_input_control_ctx *ctrl_ctx;
2723 	int old_active_eps = 0;
2724 
2725 	if (virt_dev->tt_info)
2726 		old_active_eps = virt_dev->tt_info->active_eps;
2727 
2728 	ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2729 	if (!ctrl_ctx) {
2730 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2731 				__func__);
2732 		return -ENOMEM;
2733 	}
2734 
2735 	for (i = 0; i < 31; i++) {
2736 		if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2737 			continue;
2738 
2739 		/* Make a copy of the BW info in case we need to revert this */
2740 		memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2741 				sizeof(ep_bw_info[i]));
2742 		/* Drop the endpoint from the interval table if the endpoint is
2743 		 * being dropped or changed.
2744 		 */
2745 		if (EP_IS_DROPPED(ctrl_ctx, i))
2746 			xhci_drop_ep_from_interval_table(xhci,
2747 					&virt_dev->eps[i].bw_info,
2748 					virt_dev->bw_table,
2749 					virt_dev->udev,
2750 					&virt_dev->eps[i],
2751 					virt_dev->tt_info);
2752 	}
2753 	/* Overwrite the information stored in the endpoints' bw_info */
2754 	xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2755 	for (i = 0; i < 31; i++) {
2756 		/* Add any changed or added endpoints to the interval table */
2757 		if (EP_IS_ADDED(ctrl_ctx, i))
2758 			xhci_add_ep_to_interval_table(xhci,
2759 					&virt_dev->eps[i].bw_info,
2760 					virt_dev->bw_table,
2761 					virt_dev->udev,
2762 					&virt_dev->eps[i],
2763 					virt_dev->tt_info);
2764 	}
2765 
2766 	if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2767 		/* Ok, this fits in the bandwidth we have.
2768 		 * Update the number of active TTs.
2769 		 */
2770 		xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2771 		return 0;
2772 	}
2773 
2774 	/* We don't have enough bandwidth for this, revert the stored info. */
2775 	for (i = 0; i < 31; i++) {
2776 		if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2777 			continue;
2778 
2779 		/* Drop the new copies of any added or changed endpoints from
2780 		 * the interval table.
2781 		 */
2782 		if (EP_IS_ADDED(ctrl_ctx, i)) {
2783 			xhci_drop_ep_from_interval_table(xhci,
2784 					&virt_dev->eps[i].bw_info,
2785 					virt_dev->bw_table,
2786 					virt_dev->udev,
2787 					&virt_dev->eps[i],
2788 					virt_dev->tt_info);
2789 		}
2790 		/* Revert the endpoint back to its old information */
2791 		memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2792 				sizeof(ep_bw_info[i]));
2793 		/* Add any changed or dropped endpoints back into the table */
2794 		if (EP_IS_DROPPED(ctrl_ctx, i))
2795 			xhci_add_ep_to_interval_table(xhci,
2796 					&virt_dev->eps[i].bw_info,
2797 					virt_dev->bw_table,
2798 					virt_dev->udev,
2799 					&virt_dev->eps[i],
2800 					virt_dev->tt_info);
2801 	}
2802 	return -ENOMEM;
2803 }
2804 
2805 /*
2806  * Synchronous XHCI stop endpoint helper.  Issues the stop endpoint command and
2807  * waits for the command completion before returning.  This does not call
2808  * xhci_handle_cmd_stop_ep(), which has additional handling for 'context error'
2809  * cases, along with transfer ring cleanup.
2810  *
2811  * xhci_stop_endpoint_sync() is intended to be utilized by clients that manage
2812  * their own transfer ring, such as offload situations.
2813  */
2814 int xhci_stop_endpoint_sync(struct xhci_hcd *xhci, struct xhci_virt_ep *ep, int suspend,
2815 			    gfp_t gfp_flags)
2816 {
2817 	struct xhci_command *command;
2818 	unsigned long flags;
2819 	int ret;
2820 
2821 	command = xhci_alloc_command(xhci, true, gfp_flags);
2822 	if (!command)
2823 		return -ENOMEM;
2824 
2825 	spin_lock_irqsave(&xhci->lock, flags);
2826 	ret = xhci_queue_stop_endpoint(xhci, command, ep->vdev->slot_id,
2827 				       ep->ep_index, suspend);
2828 	if (ret < 0) {
2829 		spin_unlock_irqrestore(&xhci->lock, flags);
2830 		goto out;
2831 	}
2832 
2833 	xhci_ring_cmd_db(xhci);
2834 	spin_unlock_irqrestore(&xhci->lock, flags);
2835 
2836 	wait_for_completion(command->completion);
2837 
2838 	/* No handling for COMP_CONTEXT_STATE_ERROR done at command completion*/
2839 	if (command->status == COMP_COMMAND_ABORTED ||
2840 	    command->status == COMP_COMMAND_RING_STOPPED) {
2841 		xhci_warn(xhci, "Timeout while waiting for stop endpoint command\n");
2842 		ret = -ETIME;
2843 	}
2844 out:
2845 	xhci_free_command(xhci, command);
2846 
2847 	return ret;
2848 }
2849 EXPORT_SYMBOL_GPL(xhci_stop_endpoint_sync);
2850 
2851 /* Issue a configure endpoint command or evaluate context command
2852  * and wait for it to finish.
2853  */
2854 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2855 		struct usb_device *udev,
2856 		struct xhci_command *command,
2857 		bool ctx_change, bool must_succeed)
2858 {
2859 	int ret;
2860 	unsigned long flags;
2861 	struct xhci_input_control_ctx *ctrl_ctx;
2862 	struct xhci_virt_device *virt_dev;
2863 	struct xhci_slot_ctx *slot_ctx;
2864 
2865 	if (!command)
2866 		return -EINVAL;
2867 
2868 	spin_lock_irqsave(&xhci->lock, flags);
2869 
2870 	if (xhci->xhc_state & XHCI_STATE_DYING) {
2871 		spin_unlock_irqrestore(&xhci->lock, flags);
2872 		return -ESHUTDOWN;
2873 	}
2874 
2875 	virt_dev = xhci->devs[udev->slot_id];
2876 
2877 	ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2878 	if (!ctrl_ctx) {
2879 		spin_unlock_irqrestore(&xhci->lock, flags);
2880 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2881 				__func__);
2882 		return -ENOMEM;
2883 	}
2884 
2885 	if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2886 			xhci_reserve_host_resources(xhci, ctrl_ctx)) {
2887 		spin_unlock_irqrestore(&xhci->lock, flags);
2888 		xhci_warn(xhci, "Not enough host resources, "
2889 				"active endpoint contexts = %u\n",
2890 				xhci->num_active_eps);
2891 		return -ENOMEM;
2892 	}
2893 	if ((xhci->quirks & XHCI_SW_BW_CHECKING) && !ctx_change &&
2894 	    xhci_reserve_bandwidth(xhci, virt_dev, command->in_ctx)) {
2895 		if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2896 			xhci_free_host_resources(xhci, ctrl_ctx);
2897 		spin_unlock_irqrestore(&xhci->lock, flags);
2898 		xhci_warn(xhci, "Not enough bandwidth\n");
2899 		return -ENOMEM;
2900 	}
2901 
2902 	slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
2903 
2904 	trace_xhci_configure_endpoint_ctrl_ctx(ctrl_ctx);
2905 	trace_xhci_configure_endpoint(slot_ctx);
2906 
2907 	if (!ctx_change)
2908 		ret = xhci_queue_configure_endpoint(xhci, command,
2909 				command->in_ctx->dma,
2910 				udev->slot_id, must_succeed);
2911 	else
2912 		ret = xhci_queue_evaluate_context(xhci, command,
2913 				command->in_ctx->dma,
2914 				udev->slot_id, must_succeed);
2915 	if (ret < 0) {
2916 		if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2917 			xhci_free_host_resources(xhci, ctrl_ctx);
2918 		spin_unlock_irqrestore(&xhci->lock, flags);
2919 		xhci_dbg_trace(xhci,  trace_xhci_dbg_context_change,
2920 				"FIXME allocate a new ring segment");
2921 		return -ENOMEM;
2922 	}
2923 	xhci_ring_cmd_db(xhci);
2924 	spin_unlock_irqrestore(&xhci->lock, flags);
2925 
2926 	/* Wait for the configure endpoint command to complete */
2927 	wait_for_completion(command->completion);
2928 
2929 	if (!ctx_change)
2930 		ret = xhci_configure_endpoint_result(xhci, udev,
2931 						     &command->status);
2932 	else
2933 		ret = xhci_evaluate_context_result(xhci, udev,
2934 						   &command->status);
2935 
2936 	if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2937 		spin_lock_irqsave(&xhci->lock, flags);
2938 		/* If the command failed, remove the reserved resources.
2939 		 * Otherwise, clean up the estimate to include dropped eps.
2940 		 */
2941 		if (ret)
2942 			xhci_free_host_resources(xhci, ctrl_ctx);
2943 		else
2944 			xhci_finish_resource_reservation(xhci, ctrl_ctx);
2945 		spin_unlock_irqrestore(&xhci->lock, flags);
2946 	}
2947 	return ret;
2948 }
2949 
2950 static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
2951 	struct xhci_virt_device *vdev, int i)
2952 {
2953 	struct xhci_virt_ep *ep = &vdev->eps[i];
2954 
2955 	if (ep->ep_state & EP_HAS_STREAMS) {
2956 		xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
2957 				xhci_get_endpoint_address(i));
2958 		xhci_free_stream_info(xhci, ep->stream_info);
2959 		ep->stream_info = NULL;
2960 		ep->ep_state &= ~EP_HAS_STREAMS;
2961 	}
2962 }
2963 
2964 /* Called after one or more calls to xhci_add_endpoint() or
2965  * xhci_drop_endpoint().  If this call fails, the USB core is expected
2966  * to call xhci_reset_bandwidth().
2967  *
2968  * Since we are in the middle of changing either configuration or
2969  * installing a new alt setting, the USB core won't allow URBs to be
2970  * enqueued for any endpoint on the old config or interface.  Nothing
2971  * else should be touching the xhci->devs[slot_id] structure, so we
2972  * don't need to take the xhci->lock for manipulating that.
2973  */
2974 int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2975 {
2976 	int i;
2977 	int ret = 0;
2978 	struct xhci_hcd *xhci;
2979 	struct xhci_virt_device	*virt_dev;
2980 	struct xhci_input_control_ctx *ctrl_ctx;
2981 	struct xhci_slot_ctx *slot_ctx;
2982 	struct xhci_command *command;
2983 
2984 	ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2985 	if (ret <= 0)
2986 		return ret;
2987 	xhci = hcd_to_xhci(hcd);
2988 	if ((xhci->xhc_state & XHCI_STATE_DYING) ||
2989 		(xhci->xhc_state & XHCI_STATE_REMOVING))
2990 		return -ENODEV;
2991 
2992 	xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2993 	virt_dev = xhci->devs[udev->slot_id];
2994 
2995 	command = xhci_alloc_command(xhci, true, GFP_KERNEL);
2996 	if (!command)
2997 		return -ENOMEM;
2998 
2999 	command->in_ctx = virt_dev->in_ctx;
3000 
3001 	/* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
3002 	ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3003 	if (!ctrl_ctx) {
3004 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3005 				__func__);
3006 		ret = -ENOMEM;
3007 		goto command_cleanup;
3008 	}
3009 	ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
3010 	ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
3011 	ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
3012 
3013 	/* Don't issue the command if there's no endpoints to update. */
3014 	if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
3015 	    ctrl_ctx->drop_flags == 0) {
3016 		ret = 0;
3017 		goto command_cleanup;
3018 	}
3019 	/* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
3020 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
3021 	for (i = 31; i >= 1; i--) {
3022 		__le32 le32 = cpu_to_le32(BIT(i));
3023 
3024 		if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
3025 		    || (ctrl_ctx->add_flags & le32) || i == 1) {
3026 			slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
3027 			slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
3028 			break;
3029 		}
3030 	}
3031 
3032 	ret = xhci_configure_endpoint(xhci, udev, command,
3033 			false, false);
3034 	if (ret)
3035 		/* Callee should call reset_bandwidth() */
3036 		goto command_cleanup;
3037 
3038 	/* Free any rings that were dropped, but not changed. */
3039 	for (i = 1; i < 31; i++) {
3040 		if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
3041 		    !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
3042 			xhci_free_endpoint_ring(xhci, virt_dev, i);
3043 			xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
3044 		}
3045 	}
3046 	xhci_zero_in_ctx(xhci, virt_dev);
3047 	/*
3048 	 * Install any rings for completely new endpoints or changed endpoints,
3049 	 * and free any old rings from changed endpoints.
3050 	 */
3051 	for (i = 1; i < 31; i++) {
3052 		if (!virt_dev->eps[i].new_ring)
3053 			continue;
3054 		/* Only free the old ring if it exists.
3055 		 * It may not if this is the first add of an endpoint.
3056 		 */
3057 		if (virt_dev->eps[i].ring) {
3058 			xhci_free_endpoint_ring(xhci, virt_dev, i);
3059 		}
3060 		xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
3061 		virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
3062 		virt_dev->eps[i].new_ring = NULL;
3063 		xhci_debugfs_create_endpoint(xhci, virt_dev, i);
3064 	}
3065 command_cleanup:
3066 	kfree(command->completion);
3067 	kfree(command);
3068 
3069 	return ret;
3070 }
3071 EXPORT_SYMBOL_GPL(xhci_check_bandwidth);
3072 
3073 void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
3074 {
3075 	struct xhci_hcd *xhci;
3076 	struct xhci_virt_device	*virt_dev;
3077 	int i, ret;
3078 
3079 	ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3080 	if (ret <= 0)
3081 		return;
3082 	xhci = hcd_to_xhci(hcd);
3083 
3084 	xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
3085 	virt_dev = xhci->devs[udev->slot_id];
3086 	/* Free any rings allocated for added endpoints */
3087 	for (i = 0; i < 31; i++) {
3088 		if (virt_dev->eps[i].new_ring) {
3089 			xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
3090 			xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
3091 			virt_dev->eps[i].new_ring = NULL;
3092 		}
3093 	}
3094 	xhci_zero_in_ctx(xhci, virt_dev);
3095 }
3096 EXPORT_SYMBOL_GPL(xhci_reset_bandwidth);
3097 
3098 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
3099 		struct xhci_container_ctx *in_ctx,
3100 		struct xhci_container_ctx *out_ctx,
3101 		struct xhci_input_control_ctx *ctrl_ctx,
3102 		u32 add_flags, u32 drop_flags)
3103 {
3104 	ctrl_ctx->add_flags = cpu_to_le32(add_flags);
3105 	ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
3106 	xhci_slot_copy(xhci, in_ctx, out_ctx);
3107 	ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
3108 }
3109 
3110 static void xhci_endpoint_disable(struct usb_hcd *hcd,
3111 				  struct usb_host_endpoint *host_ep)
3112 {
3113 	struct xhci_hcd		*xhci;
3114 	struct xhci_virt_device	*vdev;
3115 	struct xhci_virt_ep	*ep;
3116 	struct usb_device	*udev;
3117 	unsigned long		flags;
3118 	unsigned int		ep_index;
3119 
3120 	xhci = hcd_to_xhci(hcd);
3121 rescan:
3122 	spin_lock_irqsave(&xhci->lock, flags);
3123 
3124 	udev = (struct usb_device *)host_ep->hcpriv;
3125 	if (!udev || !udev->slot_id)
3126 		goto done;
3127 
3128 	vdev = xhci->devs[udev->slot_id];
3129 	if (!vdev)
3130 		goto done;
3131 
3132 	ep_index = xhci_get_endpoint_index(&host_ep->desc);
3133 	ep = &vdev->eps[ep_index];
3134 
3135 	/* wait for hub_tt_work to finish clearing hub TT */
3136 	if (ep->ep_state & EP_CLEARING_TT) {
3137 		spin_unlock_irqrestore(&xhci->lock, flags);
3138 		schedule_timeout_uninterruptible(1);
3139 		goto rescan;
3140 	}
3141 
3142 	if (ep->ep_state)
3143 		xhci_dbg(xhci, "endpoint disable with ep_state 0x%x\n",
3144 			 ep->ep_state);
3145 done:
3146 	host_ep->hcpriv = NULL;
3147 	spin_unlock_irqrestore(&xhci->lock, flags);
3148 }
3149 
3150 /*
3151  * Called after usb core issues a clear halt control message.
3152  * The host side of the halt should already be cleared by a reset endpoint
3153  * command issued when the STALL event was received.
3154  *
3155  * The reset endpoint command may only be issued to endpoints in the halted
3156  * state. For software that wishes to reset the data toggle or sequence number
3157  * of an endpoint that isn't in the halted state this function will issue a
3158  * configure endpoint command with the Drop and Add bits set for the target
3159  * endpoint. Refer to the additional note in xhci spcification section 4.6.8.
3160  *
3161  * vdev may be lost due to xHC restore error and re-initialization during S3/S4
3162  * resume. A new vdev will be allocated later by xhci_discover_or_reset_device()
3163  */
3164 
3165 static void xhci_endpoint_reset(struct usb_hcd *hcd,
3166 		struct usb_host_endpoint *host_ep)
3167 {
3168 	struct xhci_hcd *xhci;
3169 	struct usb_device *udev;
3170 	struct xhci_virt_device *vdev;
3171 	struct xhci_virt_ep *ep;
3172 	struct xhci_input_control_ctx *ctrl_ctx;
3173 	struct xhci_command *stop_cmd, *cfg_cmd;
3174 	unsigned int ep_index;
3175 	unsigned long flags;
3176 	u32 ep_flag;
3177 	int err;
3178 
3179 	xhci = hcd_to_xhci(hcd);
3180 	ep_index = xhci_get_endpoint_index(&host_ep->desc);
3181 
3182 	/*
3183 	 * Usb core assumes a max packet value for ep0 on FS devices until the
3184 	 * real value is read from the descriptor. Core resets Ep0 if values
3185 	 * mismatch. Reconfigure the xhci ep0 endpoint context here in that case
3186 	 */
3187 	if (usb_endpoint_xfer_control(&host_ep->desc) && ep_index == 0) {
3188 
3189 		udev = container_of(host_ep, struct usb_device, ep0);
3190 		if (udev->speed != USB_SPEED_FULL || !udev->slot_id)
3191 			return;
3192 
3193 		vdev = xhci->devs[udev->slot_id];
3194 		if (!vdev || vdev->udev != udev)
3195 			return;
3196 
3197 		xhci_check_ep0_maxpacket(xhci, vdev);
3198 
3199 		/* Nothing else should be done here for ep0 during ep reset */
3200 		return;
3201 	}
3202 
3203 	if (!host_ep->hcpriv)
3204 		return;
3205 	udev = (struct usb_device *) host_ep->hcpriv;
3206 	vdev = xhci->devs[udev->slot_id];
3207 
3208 	if (!udev->slot_id || !vdev)
3209 		return;
3210 
3211 	ep = &vdev->eps[ep_index];
3212 
3213 	spin_lock_irqsave(&xhci->lock, flags);
3214 
3215 	ep->ep_state &= ~EP_STALLED;
3216 
3217 	/* Bail out if toggle is already being cleared by a endpoint reset */
3218 	if (ep->ep_state & EP_HARD_CLEAR_TOGGLE) {
3219 		ep->ep_state &= ~EP_HARD_CLEAR_TOGGLE;
3220 		spin_unlock_irqrestore(&xhci->lock, flags);
3221 		return;
3222 	}
3223 	spin_unlock_irqrestore(&xhci->lock, flags);
3224 	/* Only interrupt and bulk ep's use data toggle, USB2 spec 5.5.4-> */
3225 	if (usb_endpoint_xfer_control(&host_ep->desc) ||
3226 	    usb_endpoint_xfer_isoc(&host_ep->desc))
3227 		return;
3228 
3229 	ep_flag = xhci_get_endpoint_flag(&host_ep->desc);
3230 
3231 	if (ep_flag == SLOT_FLAG || ep_flag == EP0_FLAG)
3232 		return;
3233 
3234 	stop_cmd = xhci_alloc_command(xhci, true, GFP_NOWAIT);
3235 	if (!stop_cmd)
3236 		return;
3237 
3238 	cfg_cmd = xhci_alloc_command_with_ctx(xhci, true, GFP_NOWAIT);
3239 	if (!cfg_cmd)
3240 		goto cleanup;
3241 
3242 	spin_lock_irqsave(&xhci->lock, flags);
3243 
3244 	/* block queuing new trbs and ringing ep doorbell */
3245 	ep->ep_state |= EP_SOFT_CLEAR_TOGGLE;
3246 
3247 	/*
3248 	 * Make sure endpoint ring is empty before resetting the toggle/seq.
3249 	 * Driver is required to synchronously cancel all transfer request.
3250 	 * Stop the endpoint to force xHC to update the output context
3251 	 */
3252 
3253 	if (!list_empty(&ep->ring->td_list)) {
3254 		dev_err(&udev->dev, "EP not empty, refuse reset\n");
3255 		spin_unlock_irqrestore(&xhci->lock, flags);
3256 		xhci_free_command(xhci, cfg_cmd);
3257 		goto cleanup;
3258 	}
3259 
3260 	err = xhci_queue_stop_endpoint(xhci, stop_cmd, udev->slot_id,
3261 					ep_index, 0);
3262 	if (err < 0) {
3263 		spin_unlock_irqrestore(&xhci->lock, flags);
3264 		xhci_free_command(xhci, cfg_cmd);
3265 		xhci_dbg(xhci, "%s: Failed to queue stop ep command, %d ",
3266 				__func__, err);
3267 		goto cleanup;
3268 	}
3269 
3270 	xhci_ring_cmd_db(xhci);
3271 	spin_unlock_irqrestore(&xhci->lock, flags);
3272 
3273 	wait_for_completion(stop_cmd->completion);
3274 
3275 	spin_lock_irqsave(&xhci->lock, flags);
3276 
3277 	/* config ep command clears toggle if add and drop ep flags are set */
3278 	ctrl_ctx = xhci_get_input_control_ctx(cfg_cmd->in_ctx);
3279 	if (!ctrl_ctx) {
3280 		spin_unlock_irqrestore(&xhci->lock, flags);
3281 		xhci_free_command(xhci, cfg_cmd);
3282 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3283 				__func__);
3284 		goto cleanup;
3285 	}
3286 
3287 	xhci_setup_input_ctx_for_config_ep(xhci, cfg_cmd->in_ctx, vdev->out_ctx,
3288 					   ctrl_ctx, ep_flag, ep_flag);
3289 	xhci_endpoint_copy(xhci, cfg_cmd->in_ctx, vdev->out_ctx, ep_index);
3290 
3291 	err = xhci_queue_configure_endpoint(xhci, cfg_cmd, cfg_cmd->in_ctx->dma,
3292 				      udev->slot_id, false);
3293 	if (err < 0) {
3294 		spin_unlock_irqrestore(&xhci->lock, flags);
3295 		xhci_free_command(xhci, cfg_cmd);
3296 		xhci_dbg(xhci, "%s: Failed to queue config ep command, %d ",
3297 				__func__, err);
3298 		goto cleanup;
3299 	}
3300 
3301 	xhci_ring_cmd_db(xhci);
3302 	spin_unlock_irqrestore(&xhci->lock, flags);
3303 
3304 	wait_for_completion(cfg_cmd->completion);
3305 
3306 	xhci_free_command(xhci, cfg_cmd);
3307 cleanup:
3308 	xhci_free_command(xhci, stop_cmd);
3309 	spin_lock_irqsave(&xhci->lock, flags);
3310 	if (ep->ep_state & EP_SOFT_CLEAR_TOGGLE)
3311 		ep->ep_state &= ~EP_SOFT_CLEAR_TOGGLE;
3312 	spin_unlock_irqrestore(&xhci->lock, flags);
3313 }
3314 
3315 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
3316 		struct usb_device *udev, struct usb_host_endpoint *ep,
3317 		unsigned int slot_id)
3318 {
3319 	int ret;
3320 	unsigned int ep_index;
3321 	unsigned int ep_state;
3322 
3323 	if (!ep)
3324 		return -EINVAL;
3325 	ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
3326 	if (ret <= 0)
3327 		return ret ? ret : -EINVAL;
3328 	if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
3329 		xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
3330 				" descriptor for ep 0x%x does not support streams\n",
3331 				ep->desc.bEndpointAddress);
3332 		return -EINVAL;
3333 	}
3334 
3335 	ep_index = xhci_get_endpoint_index(&ep->desc);
3336 	ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3337 	if (ep_state & EP_HAS_STREAMS ||
3338 			ep_state & EP_GETTING_STREAMS) {
3339 		xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
3340 				"already has streams set up.\n",
3341 				ep->desc.bEndpointAddress);
3342 		xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
3343 				"dynamic stream context array reallocation.\n");
3344 		return -EINVAL;
3345 	}
3346 	if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
3347 		xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
3348 				"endpoint 0x%x; URBs are pending.\n",
3349 				ep->desc.bEndpointAddress);
3350 		return -EINVAL;
3351 	}
3352 	return 0;
3353 }
3354 
3355 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
3356 		unsigned int *num_streams, unsigned int *num_stream_ctxs)
3357 {
3358 	unsigned int max_streams;
3359 
3360 	/* The stream context array size must be a power of two */
3361 	*num_stream_ctxs = roundup_pow_of_two(*num_streams);
3362 	/*
3363 	 * Find out how many primary stream array entries the host controller
3364 	 * supports.  Later we may use secondary stream arrays (similar to 2nd
3365 	 * level page entries), but that's an optional feature for xHCI host
3366 	 * controllers. xHCs must support at least 4 stream IDs.
3367 	 */
3368 	max_streams = HCC_MAX_PSA(xhci->hcc_params);
3369 	if (*num_stream_ctxs > max_streams) {
3370 		xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
3371 				max_streams);
3372 		*num_stream_ctxs = max_streams;
3373 		*num_streams = max_streams;
3374 	}
3375 }
3376 
3377 /* Returns an error code if one of the endpoint already has streams.
3378  * This does not change any data structures, it only checks and gathers
3379  * information.
3380  */
3381 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
3382 		struct usb_device *udev,
3383 		struct usb_host_endpoint **eps, unsigned int num_eps,
3384 		unsigned int *num_streams, u32 *changed_ep_bitmask)
3385 {
3386 	unsigned int max_streams;
3387 	unsigned int endpoint_flag;
3388 	int i;
3389 	int ret;
3390 
3391 	for (i = 0; i < num_eps; i++) {
3392 		ret = xhci_check_streams_endpoint(xhci, udev,
3393 				eps[i], udev->slot_id);
3394 		if (ret < 0)
3395 			return ret;
3396 
3397 		max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
3398 		if (max_streams < (*num_streams - 1)) {
3399 			xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
3400 					eps[i]->desc.bEndpointAddress,
3401 					max_streams);
3402 			*num_streams = max_streams+1;
3403 		}
3404 
3405 		endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
3406 		if (*changed_ep_bitmask & endpoint_flag)
3407 			return -EINVAL;
3408 		*changed_ep_bitmask |= endpoint_flag;
3409 	}
3410 	return 0;
3411 }
3412 
3413 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
3414 		struct usb_device *udev,
3415 		struct usb_host_endpoint **eps, unsigned int num_eps)
3416 {
3417 	u32 changed_ep_bitmask = 0;
3418 	unsigned int slot_id;
3419 	unsigned int ep_index;
3420 	unsigned int ep_state;
3421 	int i;
3422 
3423 	slot_id = udev->slot_id;
3424 	if (!xhci->devs[slot_id])
3425 		return 0;
3426 
3427 	for (i = 0; i < num_eps; i++) {
3428 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3429 		ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3430 		/* Are streams already being freed for the endpoint? */
3431 		if (ep_state & EP_GETTING_NO_STREAMS) {
3432 			xhci_warn(xhci, "WARN Can't disable streams for "
3433 					"endpoint 0x%x, "
3434 					"streams are being disabled already\n",
3435 					eps[i]->desc.bEndpointAddress);
3436 			return 0;
3437 		}
3438 		/* Are there actually any streams to free? */
3439 		if (!(ep_state & EP_HAS_STREAMS) &&
3440 				!(ep_state & EP_GETTING_STREAMS)) {
3441 			xhci_warn(xhci, "WARN Can't disable streams for "
3442 					"endpoint 0x%x, "
3443 					"streams are already disabled!\n",
3444 					eps[i]->desc.bEndpointAddress);
3445 			xhci_warn(xhci, "WARN xhci_free_streams() called "
3446 					"with non-streams endpoint\n");
3447 			return 0;
3448 		}
3449 		changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
3450 	}
3451 	return changed_ep_bitmask;
3452 }
3453 
3454 /*
3455  * The USB device drivers use this function (through the HCD interface in USB
3456  * core) to prepare a set of bulk endpoints to use streams.  Streams are used to
3457  * coordinate mass storage command queueing across multiple endpoints (basically
3458  * a stream ID == a task ID).
3459  *
3460  * Setting up streams involves allocating the same size stream context array
3461  * for each endpoint and issuing a configure endpoint command for all endpoints.
3462  *
3463  * Don't allow the call to succeed if one endpoint only supports one stream
3464  * (which means it doesn't support streams at all).
3465  *
3466  * Drivers may get less stream IDs than they asked for, if the host controller
3467  * hardware or endpoints claim they can't support the number of requested
3468  * stream IDs.
3469  */
3470 static int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3471 		struct usb_host_endpoint **eps, unsigned int num_eps,
3472 		unsigned int num_streams, gfp_t mem_flags)
3473 {
3474 	int i, ret;
3475 	struct xhci_hcd *xhci;
3476 	struct xhci_virt_device *vdev;
3477 	struct xhci_command *config_cmd;
3478 	struct xhci_input_control_ctx *ctrl_ctx;
3479 	unsigned int ep_index;
3480 	unsigned int num_stream_ctxs;
3481 	unsigned int max_packet;
3482 	unsigned long flags;
3483 	u32 changed_ep_bitmask = 0;
3484 
3485 	if (!eps)
3486 		return -EINVAL;
3487 
3488 	/* Add one to the number of streams requested to account for
3489 	 * stream 0 that is reserved for xHCI usage.
3490 	 */
3491 	num_streams += 1;
3492 	xhci = hcd_to_xhci(hcd);
3493 	xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3494 			num_streams);
3495 
3496 	/* MaxPSASize value 0 (2 streams) means streams are not supported */
3497 	if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
3498 			HCC_MAX_PSA(xhci->hcc_params) < 4) {
3499 		xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3500 		return -ENOSYS;
3501 	}
3502 
3503 	config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
3504 	if (!config_cmd)
3505 		return -ENOMEM;
3506 
3507 	ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
3508 	if (!ctrl_ctx) {
3509 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3510 				__func__);
3511 		xhci_free_command(xhci, config_cmd);
3512 		return -ENOMEM;
3513 	}
3514 
3515 	/* Check to make sure all endpoints are not already configured for
3516 	 * streams.  While we're at it, find the maximum number of streams that
3517 	 * all the endpoints will support and check for duplicate endpoints.
3518 	 */
3519 	spin_lock_irqsave(&xhci->lock, flags);
3520 	ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3521 			num_eps, &num_streams, &changed_ep_bitmask);
3522 	if (ret < 0) {
3523 		xhci_free_command(xhci, config_cmd);
3524 		spin_unlock_irqrestore(&xhci->lock, flags);
3525 		return ret;
3526 	}
3527 	if (num_streams <= 1) {
3528 		xhci_warn(xhci, "WARN: endpoints can't handle "
3529 				"more than one stream.\n");
3530 		xhci_free_command(xhci, config_cmd);
3531 		spin_unlock_irqrestore(&xhci->lock, flags);
3532 		return -EINVAL;
3533 	}
3534 	vdev = xhci->devs[udev->slot_id];
3535 	/* Mark each endpoint as being in transition, so
3536 	 * xhci_urb_enqueue() will reject all URBs.
3537 	 */
3538 	for (i = 0; i < num_eps; i++) {
3539 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3540 		vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3541 	}
3542 	spin_unlock_irqrestore(&xhci->lock, flags);
3543 
3544 	/* Setup internal data structures and allocate HW data structures for
3545 	 * streams (but don't install the HW structures in the input context
3546 	 * until we're sure all memory allocation succeeded).
3547 	 */
3548 	xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3549 	xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3550 			num_stream_ctxs, num_streams);
3551 
3552 	for (i = 0; i < num_eps; i++) {
3553 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3554 		max_packet = usb_endpoint_maxp(&eps[i]->desc);
3555 		vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3556 				num_stream_ctxs,
3557 				num_streams,
3558 				max_packet, mem_flags);
3559 		if (!vdev->eps[ep_index].stream_info)
3560 			goto cleanup;
3561 		/* Set maxPstreams in endpoint context and update deq ptr to
3562 		 * point to stream context array. FIXME
3563 		 */
3564 	}
3565 
3566 	/* Set up the input context for a configure endpoint command. */
3567 	for (i = 0; i < num_eps; i++) {
3568 		struct xhci_ep_ctx *ep_ctx;
3569 
3570 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3571 		ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3572 
3573 		xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3574 				vdev->out_ctx, ep_index);
3575 		xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3576 				vdev->eps[ep_index].stream_info);
3577 	}
3578 	/* Tell the HW to drop its old copy of the endpoint context info
3579 	 * and add the updated copy from the input context.
3580 	 */
3581 	xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3582 			vdev->out_ctx, ctrl_ctx,
3583 			changed_ep_bitmask, changed_ep_bitmask);
3584 
3585 	/* Issue and wait for the configure endpoint command */
3586 	ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3587 			false, false);
3588 
3589 	/* xHC rejected the configure endpoint command for some reason, so we
3590 	 * leave the old ring intact and free our internal streams data
3591 	 * structure.
3592 	 */
3593 	if (ret < 0)
3594 		goto cleanup;
3595 
3596 	spin_lock_irqsave(&xhci->lock, flags);
3597 	for (i = 0; i < num_eps; i++) {
3598 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3599 		vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3600 		xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3601 			 udev->slot_id, ep_index);
3602 		vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3603 	}
3604 	xhci_free_command(xhci, config_cmd);
3605 	spin_unlock_irqrestore(&xhci->lock, flags);
3606 
3607 	for (i = 0; i < num_eps; i++) {
3608 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3609 		xhci_debugfs_create_stream_files(xhci, vdev, ep_index);
3610 	}
3611 	/* Subtract 1 for stream 0, which drivers can't use */
3612 	return num_streams - 1;
3613 
3614 cleanup:
3615 	/* If it didn't work, free the streams! */
3616 	for (i = 0; i < num_eps; i++) {
3617 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3618 		xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3619 		vdev->eps[ep_index].stream_info = NULL;
3620 		/* FIXME Unset maxPstreams in endpoint context and
3621 		 * update deq ptr to point to normal string ring.
3622 		 */
3623 		vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3624 		vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3625 		xhci_endpoint_zero(xhci, vdev, eps[i]);
3626 	}
3627 	xhci_free_command(xhci, config_cmd);
3628 	return -ENOMEM;
3629 }
3630 
3631 /* Transition the endpoint from using streams to being a "normal" endpoint
3632  * without streams.
3633  *
3634  * Modify the endpoint context state, submit a configure endpoint command,
3635  * and free all endpoint rings for streams if that completes successfully.
3636  */
3637 static int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3638 		struct usb_host_endpoint **eps, unsigned int num_eps,
3639 		gfp_t mem_flags)
3640 {
3641 	int i, ret;
3642 	struct xhci_hcd *xhci;
3643 	struct xhci_virt_device *vdev;
3644 	struct xhci_command *command;
3645 	struct xhci_input_control_ctx *ctrl_ctx;
3646 	unsigned int ep_index;
3647 	unsigned long flags;
3648 	u32 changed_ep_bitmask;
3649 
3650 	xhci = hcd_to_xhci(hcd);
3651 	vdev = xhci->devs[udev->slot_id];
3652 
3653 	/* Set up a configure endpoint command to remove the streams rings */
3654 	spin_lock_irqsave(&xhci->lock, flags);
3655 	changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3656 			udev, eps, num_eps);
3657 	if (changed_ep_bitmask == 0) {
3658 		spin_unlock_irqrestore(&xhci->lock, flags);
3659 		return -EINVAL;
3660 	}
3661 
3662 	/* Use the xhci_command structure from the first endpoint.  We may have
3663 	 * allocated too many, but the driver may call xhci_free_streams() for
3664 	 * each endpoint it grouped into one call to xhci_alloc_streams().
3665 	 */
3666 	ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3667 	command = vdev->eps[ep_index].stream_info->free_streams_command;
3668 	ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3669 	if (!ctrl_ctx) {
3670 		spin_unlock_irqrestore(&xhci->lock, flags);
3671 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3672 				__func__);
3673 		return -EINVAL;
3674 	}
3675 
3676 	for (i = 0; i < num_eps; i++) {
3677 		struct xhci_ep_ctx *ep_ctx;
3678 
3679 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3680 		ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3681 		xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3682 			EP_GETTING_NO_STREAMS;
3683 
3684 		xhci_endpoint_copy(xhci, command->in_ctx,
3685 				vdev->out_ctx, ep_index);
3686 		xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3687 				&vdev->eps[ep_index]);
3688 	}
3689 	xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3690 			vdev->out_ctx, ctrl_ctx,
3691 			changed_ep_bitmask, changed_ep_bitmask);
3692 	spin_unlock_irqrestore(&xhci->lock, flags);
3693 
3694 	/* Issue and wait for the configure endpoint command,
3695 	 * which must succeed.
3696 	 */
3697 	ret = xhci_configure_endpoint(xhci, udev, command,
3698 			false, true);
3699 
3700 	/* xHC rejected the configure endpoint command for some reason, so we
3701 	 * leave the streams rings intact.
3702 	 */
3703 	if (ret < 0)
3704 		return ret;
3705 
3706 	spin_lock_irqsave(&xhci->lock, flags);
3707 	for (i = 0; i < num_eps; i++) {
3708 		ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3709 		xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3710 		vdev->eps[ep_index].stream_info = NULL;
3711 		/* FIXME Unset maxPstreams in endpoint context and
3712 		 * update deq ptr to point to normal string ring.
3713 		 */
3714 		vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3715 		vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3716 	}
3717 	spin_unlock_irqrestore(&xhci->lock, flags);
3718 
3719 	return 0;
3720 }
3721 
3722 /*
3723  * Deletes endpoint resources for endpoints that were active before a Reset
3724  * Device command, or a Disable Slot command.  The Reset Device command leaves
3725  * the control endpoint intact, whereas the Disable Slot command deletes it.
3726  *
3727  * Must be called with xhci->lock held.
3728  */
3729 void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3730 	struct xhci_virt_device *virt_dev, bool drop_control_ep)
3731 {
3732 	int i;
3733 	unsigned int num_dropped_eps = 0;
3734 	unsigned int drop_flags = 0;
3735 
3736 	for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3737 		if (virt_dev->eps[i].ring) {
3738 			drop_flags |= 1 << i;
3739 			num_dropped_eps++;
3740 		}
3741 	}
3742 	xhci->num_active_eps -= num_dropped_eps;
3743 	if (num_dropped_eps)
3744 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3745 				"Dropped %u ep ctxs, flags = 0x%x, "
3746 				"%u now active.",
3747 				num_dropped_eps, drop_flags,
3748 				xhci->num_active_eps);
3749 }
3750 
3751 static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev);
3752 
3753 /*
3754  * This submits a Reset Device Command, which will set the device state to 0,
3755  * set the device address to 0, and disable all the endpoints except the default
3756  * control endpoint.  The USB core should come back and call
3757  * xhci_address_device(), and then re-set up the configuration.  If this is
3758  * called because of a usb_reset_and_verify_device(), then the old alternate
3759  * settings will be re-installed through the normal bandwidth allocation
3760  * functions.
3761  *
3762  * Wait for the Reset Device command to finish.  Remove all structures
3763  * associated with the endpoints that were disabled.  Clear the input device
3764  * structure? Reset the control endpoint 0 max packet size?
3765  *
3766  * If the virt_dev to be reset does not exist or does not match the udev,
3767  * it means the device is lost, possibly due to the xHC restore error and
3768  * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3769  * re-allocate the device.
3770  */
3771 static int xhci_discover_or_reset_device(struct usb_hcd *hcd,
3772 		struct usb_device *udev)
3773 {
3774 	int ret, i;
3775 	unsigned long flags;
3776 	struct xhci_hcd *xhci;
3777 	unsigned int slot_id;
3778 	struct xhci_virt_device *virt_dev;
3779 	struct xhci_command *reset_device_cmd;
3780 	struct xhci_slot_ctx *slot_ctx;
3781 	int old_active_eps = 0;
3782 
3783 	ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3784 	if (ret <= 0)
3785 		return ret;
3786 	xhci = hcd_to_xhci(hcd);
3787 	slot_id = udev->slot_id;
3788 	virt_dev = xhci->devs[slot_id];
3789 	if (!virt_dev) {
3790 		xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3791 				"not exist. Re-allocate the device\n", slot_id);
3792 		ret = xhci_alloc_dev(hcd, udev);
3793 		if (ret == 1)
3794 			return 0;
3795 		else
3796 			return -EINVAL;
3797 	}
3798 
3799 	if (virt_dev->tt_info)
3800 		old_active_eps = virt_dev->tt_info->active_eps;
3801 
3802 	if (virt_dev->udev != udev) {
3803 		/* If the virt_dev and the udev does not match, this virt_dev
3804 		 * may belong to another udev.
3805 		 * Re-allocate the device.
3806 		 */
3807 		xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3808 				"not match the udev. Re-allocate the device\n",
3809 				slot_id);
3810 		ret = xhci_alloc_dev(hcd, udev);
3811 		if (ret == 1)
3812 			return 0;
3813 		else
3814 			return -EINVAL;
3815 	}
3816 
3817 	/* If device is not setup, there is no point in resetting it */
3818 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3819 	if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3820 						SLOT_STATE_DISABLED)
3821 		return 0;
3822 
3823 	if (xhci->quirks & XHCI_ETRON_HOST) {
3824 		/*
3825 		 * Obtaining a new device slot to inform the xHCI host that
3826 		 * the USB device has been reset.
3827 		 */
3828 		ret = xhci_disable_slot(xhci, udev->slot_id);
3829 		xhci_free_virt_device(xhci, udev->slot_id);
3830 		if (!ret) {
3831 			ret = xhci_alloc_dev(hcd, udev);
3832 			if (ret == 1)
3833 				ret = 0;
3834 			else
3835 				ret = -EINVAL;
3836 		}
3837 		return ret;
3838 	}
3839 
3840 	trace_xhci_discover_or_reset_device(slot_ctx);
3841 
3842 	xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3843 	/* Allocate the command structure that holds the struct completion.
3844 	 * Assume we're in process context, since the normal device reset
3845 	 * process has to wait for the device anyway.  Storage devices are
3846 	 * reset as part of error handling, so use GFP_NOIO instead of
3847 	 * GFP_KERNEL.
3848 	 */
3849 	reset_device_cmd = xhci_alloc_command(xhci, true, GFP_NOIO);
3850 	if (!reset_device_cmd) {
3851 		xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3852 		return -ENOMEM;
3853 	}
3854 
3855 	/* Attempt to submit the Reset Device command to the command ring */
3856 	spin_lock_irqsave(&xhci->lock, flags);
3857 
3858 	ret = xhci_queue_reset_device(xhci, reset_device_cmd, slot_id);
3859 	if (ret) {
3860 		xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3861 		spin_unlock_irqrestore(&xhci->lock, flags);
3862 		goto command_cleanup;
3863 	}
3864 	xhci_ring_cmd_db(xhci);
3865 	spin_unlock_irqrestore(&xhci->lock, flags);
3866 
3867 	/* Wait for the Reset Device command to finish */
3868 	wait_for_completion(reset_device_cmd->completion);
3869 
3870 	/* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3871 	 * unless we tried to reset a slot ID that wasn't enabled,
3872 	 * or the device wasn't in the addressed or configured state.
3873 	 */
3874 	ret = reset_device_cmd->status;
3875 	switch (ret) {
3876 	case COMP_COMMAND_ABORTED:
3877 	case COMP_COMMAND_RING_STOPPED:
3878 		xhci_warn(xhci, "Timeout waiting for reset device command\n");
3879 		ret = -ETIME;
3880 		goto command_cleanup;
3881 	case COMP_SLOT_NOT_ENABLED_ERROR: /* 0.95 completion for bad slot ID */
3882 	case COMP_CONTEXT_STATE_ERROR: /* 0.96 completion code for same thing */
3883 		xhci_dbg(xhci, "Can't reset device (slot ID %u) in %s state\n",
3884 				slot_id,
3885 				xhci_get_slot_state(xhci, virt_dev->out_ctx));
3886 		xhci_dbg(xhci, "Not freeing device rings.\n");
3887 		/* Don't treat this as an error.  May change my mind later. */
3888 		ret = 0;
3889 		goto command_cleanup;
3890 	case COMP_SUCCESS:
3891 		xhci_dbg(xhci, "Successful reset device command.\n");
3892 		break;
3893 	default:
3894 		if (xhci_is_vendor_info_code(xhci, ret))
3895 			break;
3896 		xhci_warn(xhci, "Unknown completion code %u for "
3897 				"reset device command.\n", ret);
3898 		ret = -EINVAL;
3899 		goto command_cleanup;
3900 	}
3901 
3902 	/* Free up host controller endpoint resources */
3903 	if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3904 		spin_lock_irqsave(&xhci->lock, flags);
3905 		/* Don't delete the default control endpoint resources */
3906 		xhci_free_device_endpoint_resources(xhci, virt_dev, false);
3907 		spin_unlock_irqrestore(&xhci->lock, flags);
3908 	}
3909 
3910 	/* Everything but endpoint 0 is disabled, so free the rings. */
3911 	for (i = 1; i < 31; i++) {
3912 		struct xhci_virt_ep *ep = &virt_dev->eps[i];
3913 
3914 		if (ep->ep_state & EP_HAS_STREAMS) {
3915 			xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
3916 					xhci_get_endpoint_address(i));
3917 			xhci_free_stream_info(xhci, ep->stream_info);
3918 			ep->stream_info = NULL;
3919 			ep->ep_state &= ~EP_HAS_STREAMS;
3920 		}
3921 
3922 		if (ep->ring) {
3923 			if (ep->sideband)
3924 				xhci_sideband_notify_ep_ring_free(ep->sideband, i);
3925 			xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
3926 			xhci_free_endpoint_ring(xhci, virt_dev, i);
3927 		}
3928 		if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
3929 			xhci_drop_ep_from_interval_table(xhci,
3930 					&virt_dev->eps[i].bw_info,
3931 					virt_dev->bw_table,
3932 					udev,
3933 					&virt_dev->eps[i],
3934 					virt_dev->tt_info);
3935 		xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
3936 	}
3937 	/* If necessary, update the number of active TTs on this root port */
3938 	xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
3939 	virt_dev->flags = 0;
3940 	ret = 0;
3941 
3942 command_cleanup:
3943 	xhci_free_command(xhci, reset_device_cmd);
3944 	return ret;
3945 }
3946 
3947 /*
3948  * At this point, the struct usb_device is about to go away, the device has
3949  * disconnected, and all traffic has been stopped and the endpoints have been
3950  * disabled.  Free any HC data structures associated with that device.
3951  */
3952 static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3953 {
3954 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3955 	struct xhci_virt_device *virt_dev;
3956 	struct xhci_slot_ctx *slot_ctx;
3957 	unsigned long flags;
3958 	int i, ret;
3959 
3960 	/*
3961 	 * We called pm_runtime_get_noresume when the device was attached.
3962 	 * Decrement the counter here to allow controller to runtime suspend
3963 	 * if no devices remain.
3964 	 */
3965 	if (xhci->quirks & XHCI_RESET_ON_RESUME)
3966 		pm_runtime_put_noidle(hcd->self.controller);
3967 
3968 	ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3969 	/* If the host is halted due to driver unload, we still need to free the
3970 	 * device.
3971 	 */
3972 	if (ret <= 0 && ret != -ENODEV)
3973 		return;
3974 
3975 	virt_dev = xhci->devs[udev->slot_id];
3976 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3977 	trace_xhci_free_dev(slot_ctx);
3978 
3979 	/* Stop any wayward timer functions (which may grab the lock) */
3980 	for (i = 0; i < 31; i++)
3981 		virt_dev->eps[i].ep_state &= ~EP_STOP_CMD_PENDING;
3982 	virt_dev->udev = NULL;
3983 	xhci_disable_slot(xhci, udev->slot_id);
3984 
3985 	spin_lock_irqsave(&xhci->lock, flags);
3986 	xhci_free_virt_device(xhci, udev->slot_id);
3987 	spin_unlock_irqrestore(&xhci->lock, flags);
3988 
3989 }
3990 
3991 int xhci_disable_slot(struct xhci_hcd *xhci, u32 slot_id)
3992 {
3993 	struct xhci_command *command;
3994 	unsigned long flags;
3995 	u32 state;
3996 	int ret;
3997 
3998 	command = xhci_alloc_command(xhci, true, GFP_KERNEL);
3999 	if (!command)
4000 		return -ENOMEM;
4001 
4002 	xhci_debugfs_remove_slot(xhci, slot_id);
4003 
4004 	spin_lock_irqsave(&xhci->lock, flags);
4005 	/* Don't disable the slot if the host controller is dead. */
4006 	state = readl(&xhci->op_regs->status);
4007 	if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
4008 			(xhci->xhc_state & XHCI_STATE_HALTED)) {
4009 		spin_unlock_irqrestore(&xhci->lock, flags);
4010 		kfree(command);
4011 		return -ENODEV;
4012 	}
4013 
4014 	ret = xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
4015 				slot_id);
4016 	if (ret) {
4017 		spin_unlock_irqrestore(&xhci->lock, flags);
4018 		kfree(command);
4019 		return ret;
4020 	}
4021 	xhci_ring_cmd_db(xhci);
4022 	spin_unlock_irqrestore(&xhci->lock, flags);
4023 
4024 	wait_for_completion(command->completion);
4025 
4026 	if (command->status != COMP_SUCCESS)
4027 		xhci_warn(xhci, "Unsuccessful disable slot %u command, status %d\n",
4028 			  slot_id, command->status);
4029 
4030 	xhci_free_command(xhci, command);
4031 
4032 	return 0;
4033 }
4034 
4035 /*
4036  * Checks if we have enough host controller resources for the default control
4037  * endpoint.
4038  *
4039  * Must be called with xhci->lock held.
4040  */
4041 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
4042 {
4043 	if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
4044 		xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
4045 				"Not enough ep ctxs: "
4046 				"%u active, need to add 1, limit is %u.",
4047 				xhci->num_active_eps, xhci->limit_active_eps);
4048 		return -ENOMEM;
4049 	}
4050 	xhci->num_active_eps += 1;
4051 	xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
4052 			"Adding 1 ep ctx, %u now active.",
4053 			xhci->num_active_eps);
4054 	return 0;
4055 }
4056 
4057 
4058 /*
4059  * Returns 0 if the xHC ran out of device slots, the Enable Slot command
4060  * timed out, or allocating memory failed.  Returns 1 on success.
4061  */
4062 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
4063 {
4064 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4065 	struct xhci_virt_device *vdev;
4066 	struct xhci_slot_ctx *slot_ctx;
4067 	unsigned long flags;
4068 	int ret, slot_id;
4069 	struct xhci_command *command;
4070 
4071 	command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4072 	if (!command)
4073 		return 0;
4074 
4075 	spin_lock_irqsave(&xhci->lock, flags);
4076 	ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
4077 	if (ret) {
4078 		spin_unlock_irqrestore(&xhci->lock, flags);
4079 		xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
4080 		xhci_free_command(xhci, command);
4081 		return 0;
4082 	}
4083 	xhci_ring_cmd_db(xhci);
4084 	spin_unlock_irqrestore(&xhci->lock, flags);
4085 
4086 	wait_for_completion(command->completion);
4087 	slot_id = command->slot_id;
4088 
4089 	if (!slot_id || command->status != COMP_SUCCESS) {
4090 		xhci_err(xhci, "Error while assigning device slot ID: %s\n",
4091 			 xhci_trb_comp_code_string(command->status));
4092 		xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
4093 				HCS_MAX_SLOTS(
4094 					readl(&xhci->cap_regs->hcs_params1)));
4095 		xhci_free_command(xhci, command);
4096 		return 0;
4097 	}
4098 
4099 	xhci_free_command(xhci, command);
4100 
4101 	if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
4102 		spin_lock_irqsave(&xhci->lock, flags);
4103 		ret = xhci_reserve_host_control_ep_resources(xhci);
4104 		if (ret) {
4105 			spin_unlock_irqrestore(&xhci->lock, flags);
4106 			xhci_warn(xhci, "Not enough host resources, "
4107 					"active endpoint contexts = %u\n",
4108 					xhci->num_active_eps);
4109 			goto disable_slot;
4110 		}
4111 		spin_unlock_irqrestore(&xhci->lock, flags);
4112 	}
4113 	/* Use GFP_NOIO, since this function can be called from
4114 	 * xhci_discover_or_reset_device(), which may be called as part of
4115 	 * mass storage driver error handling.
4116 	 */
4117 	if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) {
4118 		xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
4119 		goto disable_slot;
4120 	}
4121 	vdev = xhci->devs[slot_id];
4122 	slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
4123 	trace_xhci_alloc_dev(slot_ctx);
4124 
4125 	udev->slot_id = slot_id;
4126 
4127 	xhci_debugfs_create_slot(xhci, slot_id);
4128 
4129 	/*
4130 	 * If resetting upon resume, we can't put the controller into runtime
4131 	 * suspend if there is a device attached.
4132 	 */
4133 	if (xhci->quirks & XHCI_RESET_ON_RESUME)
4134 		pm_runtime_get_noresume(hcd->self.controller);
4135 
4136 	/* Is this a LS or FS device under a HS hub? */
4137 	/* Hub or peripherial? */
4138 	return 1;
4139 
4140 disable_slot:
4141 	xhci_disable_slot(xhci, udev->slot_id);
4142 	xhci_free_virt_device(xhci, udev->slot_id);
4143 
4144 	return 0;
4145 }
4146 
4147 /**
4148  * xhci_setup_device - issues an Address Device command to assign a unique
4149  *			USB bus address.
4150  * @hcd: USB host controller data structure.
4151  * @udev: USB dev structure representing the connected device.
4152  * @setup: Enum specifying setup mode: address only or with context.
4153  * @timeout_ms: Max wait time (ms) for the command operation to complete.
4154  *
4155  * Return: 0 if successful; otherwise, negative error code.
4156  */
4157 static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
4158 			     enum xhci_setup_dev setup, unsigned int timeout_ms)
4159 {
4160 	const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
4161 	unsigned long flags;
4162 	struct xhci_virt_device *virt_dev;
4163 	int ret = 0;
4164 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4165 	struct xhci_slot_ctx *slot_ctx;
4166 	struct xhci_input_control_ctx *ctrl_ctx;
4167 	u64 temp_64;
4168 	struct xhci_command *command = NULL;
4169 
4170 	mutex_lock(&xhci->mutex);
4171 
4172 	if (xhci->xhc_state) {	/* dying, removing or halted */
4173 		ret = -ESHUTDOWN;
4174 		goto out;
4175 	}
4176 
4177 	if (!udev->slot_id) {
4178 		xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4179 				"Bad Slot ID %d", udev->slot_id);
4180 		ret = -EINVAL;
4181 		goto out;
4182 	}
4183 
4184 	virt_dev = xhci->devs[udev->slot_id];
4185 
4186 	if (WARN_ON(!virt_dev)) {
4187 		/*
4188 		 * In plug/unplug torture test with an NEC controller,
4189 		 * a zero-dereference was observed once due to virt_dev = 0.
4190 		 * Print useful debug rather than crash if it is observed again!
4191 		 */
4192 		xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
4193 			udev->slot_id);
4194 		ret = -EINVAL;
4195 		goto out;
4196 	}
4197 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4198 	trace_xhci_setup_device_slot(slot_ctx);
4199 
4200 	if (setup == SETUP_CONTEXT_ONLY) {
4201 		if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
4202 		    SLOT_STATE_DEFAULT) {
4203 			xhci_dbg(xhci, "Slot already in default state\n");
4204 			goto out;
4205 		}
4206 	}
4207 
4208 	command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4209 	if (!command) {
4210 		ret = -ENOMEM;
4211 		goto out;
4212 	}
4213 
4214 	command->in_ctx = virt_dev->in_ctx;
4215 	command->timeout_ms = timeout_ms;
4216 
4217 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
4218 	ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
4219 	if (!ctrl_ctx) {
4220 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4221 				__func__);
4222 		ret = -EINVAL;
4223 		goto out;
4224 	}
4225 	/*
4226 	 * If this is the first Set Address since device plug-in or
4227 	 * virt_device realloaction after a resume with an xHCI power loss,
4228 	 * then set up the slot context.
4229 	 */
4230 	if (!slot_ctx->dev_info)
4231 		xhci_setup_addressable_virt_dev(xhci, udev);
4232 	/* Otherwise, update the control endpoint ring enqueue pointer. */
4233 	else
4234 		xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
4235 	ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
4236 	ctrl_ctx->drop_flags = 0;
4237 
4238 	trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4239 				le32_to_cpu(slot_ctx->dev_info) >> 27);
4240 
4241 	trace_xhci_address_ctrl_ctx(ctrl_ctx);
4242 	spin_lock_irqsave(&xhci->lock, flags);
4243 	trace_xhci_setup_device(virt_dev);
4244 	ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
4245 					udev->slot_id, setup);
4246 	if (ret) {
4247 		spin_unlock_irqrestore(&xhci->lock, flags);
4248 		xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4249 				"FIXME: allocate a command ring segment");
4250 		goto out;
4251 	}
4252 	xhci_ring_cmd_db(xhci);
4253 	spin_unlock_irqrestore(&xhci->lock, flags);
4254 
4255 	/* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
4256 	wait_for_completion(command->completion);
4257 
4258 	/* FIXME: From section 4.3.4: "Software shall be responsible for timing
4259 	 * the SetAddress() "recovery interval" required by USB and aborting the
4260 	 * command on a timeout.
4261 	 */
4262 	switch (command->status) {
4263 	case COMP_COMMAND_ABORTED:
4264 	case COMP_COMMAND_RING_STOPPED:
4265 		xhci_warn(xhci, "Timeout while waiting for setup device command\n");
4266 		ret = -ETIME;
4267 		break;
4268 	case COMP_CONTEXT_STATE_ERROR:
4269 	case COMP_SLOT_NOT_ENABLED_ERROR:
4270 		xhci_err(xhci, "Setup ERROR: setup %s command for slot %d.\n",
4271 			 act, udev->slot_id);
4272 		ret = -EINVAL;
4273 		break;
4274 	case COMP_USB_TRANSACTION_ERROR:
4275 		dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
4276 
4277 		mutex_unlock(&xhci->mutex);
4278 		ret = xhci_disable_slot(xhci, udev->slot_id);
4279 		xhci_free_virt_device(xhci, udev->slot_id);
4280 		if (!ret) {
4281 			if (xhci_alloc_dev(hcd, udev) == 1)
4282 				xhci_setup_addressable_virt_dev(xhci, udev);
4283 		}
4284 		kfree(command->completion);
4285 		kfree(command);
4286 		return -EPROTO;
4287 	case COMP_INCOMPATIBLE_DEVICE_ERROR:
4288 		dev_warn(&udev->dev,
4289 			 "ERROR: Incompatible device for setup %s command\n", act);
4290 		ret = -ENODEV;
4291 		break;
4292 	case COMP_SUCCESS:
4293 		xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4294 			       "Successful setup %s command", act);
4295 		break;
4296 	default:
4297 		xhci_err(xhci,
4298 			 "ERROR: unexpected setup %s command completion code 0x%x.\n",
4299 			 act, command->status);
4300 		trace_xhci_address_ctx(xhci, virt_dev->out_ctx, 1);
4301 		ret = -EINVAL;
4302 		break;
4303 	}
4304 	if (ret)
4305 		goto out;
4306 	temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
4307 	xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4308 			"Op regs DCBAA ptr = %#016llx", temp_64);
4309 	xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4310 		"Slot ID %d dcbaa entry @%p = %#016llx",
4311 		udev->slot_id,
4312 		&xhci->dcbaa->dev_context_ptrs[udev->slot_id],
4313 		(unsigned long long)
4314 		le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
4315 	xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4316 			"Output Context DMA address = %#08llx",
4317 			(unsigned long long)virt_dev->out_ctx->dma);
4318 	trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4319 				le32_to_cpu(slot_ctx->dev_info) >> 27);
4320 	/*
4321 	 * USB core uses address 1 for the roothubs, so we add one to the
4322 	 * address given back to us by the HC.
4323 	 */
4324 	trace_xhci_address_ctx(xhci, virt_dev->out_ctx,
4325 				le32_to_cpu(slot_ctx->dev_info) >> 27);
4326 	/* Zero the input context control for later use */
4327 	ctrl_ctx->add_flags = 0;
4328 	ctrl_ctx->drop_flags = 0;
4329 	slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4330 	udev->devaddr = (u8)(le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4331 
4332 	xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4333 		       "Internal device address = %d",
4334 		       le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4335 out:
4336 	mutex_unlock(&xhci->mutex);
4337 	if (command) {
4338 		kfree(command->completion);
4339 		kfree(command);
4340 	}
4341 	return ret;
4342 }
4343 
4344 static int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev,
4345 			       unsigned int timeout_ms)
4346 {
4347 	return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ADDRESS, timeout_ms);
4348 }
4349 
4350 static int xhci_enable_device(struct usb_hcd *hcd, struct usb_device *udev)
4351 {
4352 	return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ONLY,
4353 				 XHCI_CMD_DEFAULT_TIMEOUT);
4354 }
4355 
4356 /*
4357  * Transfer the port index into real index in the HW port status
4358  * registers. Caculate offset between the port's PORTSC register
4359  * and port status base. Divide the number of per port register
4360  * to get the real index. The raw port number bases 1.
4361  */
4362 int xhci_find_raw_port_number(struct usb_hcd *hcd, int port1)
4363 {
4364 	struct xhci_hub *rhub;
4365 
4366 	rhub = xhci_get_rhub(hcd);
4367 	return rhub->ports[port1 - 1]->hw_portnum + 1;
4368 }
4369 
4370 /*
4371  * Issue an Evaluate Context command to change the Maximum Exit Latency in the
4372  * slot context.  If that succeeds, store the new MEL in the xhci_virt_device.
4373  */
4374 static int __maybe_unused xhci_change_max_exit_latency(struct xhci_hcd *xhci,
4375 			struct usb_device *udev, u16 max_exit_latency)
4376 {
4377 	struct xhci_virt_device *virt_dev;
4378 	struct xhci_command *command;
4379 	struct xhci_input_control_ctx *ctrl_ctx;
4380 	struct xhci_slot_ctx *slot_ctx;
4381 	unsigned long flags;
4382 	int ret;
4383 
4384 	command = xhci_alloc_command_with_ctx(xhci, true, GFP_KERNEL);
4385 	if (!command)
4386 		return -ENOMEM;
4387 
4388 	spin_lock_irqsave(&xhci->lock, flags);
4389 
4390 	virt_dev = xhci->devs[udev->slot_id];
4391 
4392 	/*
4393 	 * virt_dev might not exists yet if xHC resumed from hibernate (S4) and
4394 	 * xHC was re-initialized. Exit latency will be set later after
4395 	 * hub_port_finish_reset() is done and xhci->devs[] are re-allocated
4396 	 */
4397 
4398 	if (!virt_dev || max_exit_latency == virt_dev->current_mel) {
4399 		spin_unlock_irqrestore(&xhci->lock, flags);
4400 		xhci_free_command(xhci, command);
4401 		return 0;
4402 	}
4403 
4404 	/* Attempt to issue an Evaluate Context command to change the MEL. */
4405 	ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
4406 	if (!ctrl_ctx) {
4407 		spin_unlock_irqrestore(&xhci->lock, flags);
4408 		xhci_free_command(xhci, command);
4409 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4410 				__func__);
4411 		return -ENOMEM;
4412 	}
4413 
4414 	xhci_slot_copy(xhci, command->in_ctx, virt_dev->out_ctx);
4415 	spin_unlock_irqrestore(&xhci->lock, flags);
4416 
4417 	ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4418 	slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
4419 	slot_ctx->dev_info2 &= cpu_to_le32(~((u32) MAX_EXIT));
4420 	slot_ctx->dev_info2 |= cpu_to_le32(max_exit_latency);
4421 	slot_ctx->dev_state = 0;
4422 
4423 	xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
4424 			"Set up evaluate context for LPM MEL change.");
4425 
4426 	/* Issue and wait for the evaluate context command. */
4427 	ret = xhci_configure_endpoint(xhci, udev, command,
4428 			true, true);
4429 
4430 	if (!ret) {
4431 		spin_lock_irqsave(&xhci->lock, flags);
4432 		virt_dev->current_mel = max_exit_latency;
4433 		spin_unlock_irqrestore(&xhci->lock, flags);
4434 	}
4435 
4436 	xhci_free_command(xhci, command);
4437 
4438 	return ret;
4439 }
4440 
4441 #ifdef CONFIG_PM
4442 
4443 /* BESL to HIRD Encoding array for USB2 LPM */
4444 static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
4445 	3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
4446 
4447 /* Calculate HIRD/BESL for USB2 PORTPMSC*/
4448 static int xhci_calculate_hird_besl(struct xhci_hcd *xhci,
4449 					struct usb_device *udev)
4450 {
4451 	int u2del, besl, besl_host;
4452 	int besl_device = 0;
4453 	u32 field;
4454 
4455 	u2del = HCS_U2_LATENCY(xhci->hcs_params3);
4456 	field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4457 
4458 	if (field & USB_BESL_SUPPORT) {
4459 		for (besl_host = 0; besl_host < 16; besl_host++) {
4460 			if (xhci_besl_encoding[besl_host] >= u2del)
4461 				break;
4462 		}
4463 		/* Use baseline BESL value as default */
4464 		if (field & USB_BESL_BASELINE_VALID)
4465 			besl_device = USB_GET_BESL_BASELINE(field);
4466 		else if (field & USB_BESL_DEEP_VALID)
4467 			besl_device = USB_GET_BESL_DEEP(field);
4468 	} else {
4469 		if (u2del <= 50)
4470 			besl_host = 0;
4471 		else
4472 			besl_host = (u2del - 51) / 75 + 1;
4473 	}
4474 
4475 	besl = besl_host + besl_device;
4476 	if (besl > 15)
4477 		besl = 15;
4478 
4479 	return besl;
4480 }
4481 
4482 /* Calculate BESLD, L1 timeout and HIRDM for USB2 PORTHLPMC */
4483 static int xhci_calculate_usb2_hw_lpm_params(struct usb_device *udev)
4484 {
4485 	u32 field;
4486 	int l1;
4487 	int besld = 0;
4488 	int hirdm = 0;
4489 
4490 	field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4491 
4492 	/* xHCI l1 is set in steps of 256us, xHCI 1.0 section 5.4.11.2 */
4493 	l1 = udev->l1_params.timeout / 256;
4494 
4495 	/* device has preferred BESLD */
4496 	if (field & USB_BESL_DEEP_VALID) {
4497 		besld = USB_GET_BESL_DEEP(field);
4498 		hirdm = 1;
4499 	}
4500 
4501 	return PORT_BESLD(besld) | PORT_L1_TIMEOUT(l1) | PORT_HIRDM(hirdm);
4502 }
4503 
4504 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4505 			struct usb_device *udev, int enable)
4506 {
4507 	struct xhci_hcd	*xhci = hcd_to_xhci(hcd);
4508 	struct xhci_port **ports;
4509 	__le32 __iomem	*pm_addr, *hlpm_addr;
4510 	u32		pm_val, hlpm_val, field;
4511 	unsigned int	port_num;
4512 	unsigned long	flags;
4513 	int		hird, exit_latency;
4514 	int		ret;
4515 
4516 	if (xhci->quirks & XHCI_HW_LPM_DISABLE)
4517 		return -EPERM;
4518 
4519 	if (hcd->speed >= HCD_USB3 || !xhci->hw_lpm_support ||
4520 			!udev->lpm_capable)
4521 		return -EPERM;
4522 
4523 	if (!udev->parent || udev->parent->parent ||
4524 			udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4525 		return -EPERM;
4526 
4527 	if (udev->usb2_hw_lpm_capable != 1)
4528 		return -EPERM;
4529 
4530 	spin_lock_irqsave(&xhci->lock, flags);
4531 
4532 	ports = xhci->usb2_rhub.ports;
4533 	port_num = udev->portnum - 1;
4534 	pm_addr = ports[port_num]->addr + PORTPMSC;
4535 	pm_val = readl(pm_addr);
4536 	hlpm_addr = ports[port_num]->addr + PORTHLPMC;
4537 
4538 	xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
4539 		 str_enable_disable(enable), port_num + 1);
4540 
4541 	if (enable) {
4542 		/* Host supports BESL timeout instead of HIRD */
4543 		if (udev->usb2_hw_lpm_besl_capable) {
4544 			/* if device doesn't have a preferred BESL value use a
4545 			 * default one which works with mixed HIRD and BESL
4546 			 * systems. See XHCI_DEFAULT_BESL definition in xhci.h
4547 			 */
4548 			field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4549 			if ((field & USB_BESL_SUPPORT) &&
4550 			    (field & USB_BESL_BASELINE_VALID))
4551 				hird = USB_GET_BESL_BASELINE(field);
4552 			else
4553 				hird = udev->l1_params.besl;
4554 
4555 			exit_latency = xhci_besl_encoding[hird];
4556 			spin_unlock_irqrestore(&xhci->lock, flags);
4557 
4558 			ret = xhci_change_max_exit_latency(xhci, udev,
4559 							   exit_latency);
4560 			if (ret < 0)
4561 				return ret;
4562 			spin_lock_irqsave(&xhci->lock, flags);
4563 
4564 			hlpm_val = xhci_calculate_usb2_hw_lpm_params(udev);
4565 			writel(hlpm_val, hlpm_addr);
4566 			/* flush write */
4567 			readl(hlpm_addr);
4568 		} else {
4569 			hird = xhci_calculate_hird_besl(xhci, udev);
4570 		}
4571 
4572 		pm_val &= ~PORT_HIRD_MASK;
4573 		pm_val |= PORT_HIRD(hird) | PORT_RWE | PORT_L1DS(udev->slot_id);
4574 		writel(pm_val, pm_addr);
4575 		pm_val = readl(pm_addr);
4576 		pm_val |= PORT_HLE;
4577 		writel(pm_val, pm_addr);
4578 		/* flush write */
4579 		readl(pm_addr);
4580 	} else {
4581 		pm_val &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK | PORT_L1DS_MASK);
4582 		writel(pm_val, pm_addr);
4583 		/* flush write */
4584 		readl(pm_addr);
4585 		if (udev->usb2_hw_lpm_besl_capable) {
4586 			spin_unlock_irqrestore(&xhci->lock, flags);
4587 			xhci_change_max_exit_latency(xhci, udev, 0);
4588 			readl_poll_timeout(ports[port_num]->addr, pm_val,
4589 					   (pm_val & PORT_PLS_MASK) == XDEV_U0,
4590 					   100, 10000);
4591 			return 0;
4592 		}
4593 	}
4594 
4595 	spin_unlock_irqrestore(&xhci->lock, flags);
4596 	return 0;
4597 }
4598 
4599 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4600 {
4601 	struct xhci_hcd	*xhci = hcd_to_xhci(hcd);
4602 	struct xhci_port *port;
4603 	u32 capability;
4604 
4605 	/* Check if USB3 device at root port is tunneled over USB4 */
4606 	if (hcd->speed >= HCD_USB3 && !udev->parent->parent) {
4607 		port = xhci->usb3_rhub.ports[udev->portnum - 1];
4608 
4609 		udev->tunnel_mode = xhci_port_is_tunneled(xhci, port);
4610 		if (udev->tunnel_mode == USB_LINK_UNKNOWN)
4611 			dev_dbg(&udev->dev, "link tunnel state unknown\n");
4612 		else if (udev->tunnel_mode == USB_LINK_TUNNELED)
4613 			dev_dbg(&udev->dev, "tunneled over USB4 link\n");
4614 		else if (udev->tunnel_mode == USB_LINK_NATIVE)
4615 			dev_dbg(&udev->dev, "native USB 3.x link\n");
4616 		return 0;
4617 	}
4618 
4619 	if (hcd->speed >= HCD_USB3 || !udev->lpm_capable || !xhci->hw_lpm_support)
4620 		return 0;
4621 
4622 	/* we only support lpm for non-hub device connected to root hub yet */
4623 	if (!udev->parent || udev->parent->parent ||
4624 			udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4625 		return 0;
4626 
4627 	port = xhci->usb2_rhub.ports[udev->portnum - 1];
4628 	capability = port->port_cap->protocol_caps;
4629 
4630 	if (capability & XHCI_HLC) {
4631 		udev->usb2_hw_lpm_capable = 1;
4632 		udev->l1_params.timeout = XHCI_L1_TIMEOUT;
4633 		udev->l1_params.besl = XHCI_DEFAULT_BESL;
4634 		if (capability & XHCI_BLC)
4635 			udev->usb2_hw_lpm_besl_capable = 1;
4636 	}
4637 
4638 	return 0;
4639 }
4640 
4641 /*---------------------- USB 3.0 Link PM functions ------------------------*/
4642 
4643 /* Service interval in nanoseconds = 2^(bInterval - 1) * 125us * 1000ns / 1us */
4644 static unsigned long long xhci_service_interval_to_ns(
4645 		struct usb_endpoint_descriptor *desc)
4646 {
4647 	return (1ULL << (desc->bInterval - 1)) * 125 * 1000;
4648 }
4649 
4650 static u16 xhci_get_timeout_no_hub_lpm(struct usb_device *udev,
4651 		enum usb3_link_state state)
4652 {
4653 	unsigned long long sel;
4654 	unsigned long long pel;
4655 	unsigned int max_sel_pel;
4656 	char *state_name;
4657 
4658 	switch (state) {
4659 	case USB3_LPM_U1:
4660 		/* Convert SEL and PEL stored in nanoseconds to microseconds */
4661 		sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4662 		pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4663 		max_sel_pel = USB3_LPM_MAX_U1_SEL_PEL;
4664 		state_name = "U1";
4665 		break;
4666 	case USB3_LPM_U2:
4667 		sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4668 		pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4669 		max_sel_pel = USB3_LPM_MAX_U2_SEL_PEL;
4670 		state_name = "U2";
4671 		break;
4672 	default:
4673 		dev_warn(&udev->dev, "%s: Can't get timeout for non-U1 or U2 state.\n",
4674 				__func__);
4675 		return USB3_LPM_DISABLED;
4676 	}
4677 
4678 	if (sel <= max_sel_pel && pel <= max_sel_pel)
4679 		return USB3_LPM_DEVICE_INITIATED;
4680 
4681 	if (sel > max_sel_pel)
4682 		dev_dbg(&udev->dev, "Device-initiated %s disabled "
4683 				"due to long SEL %llu ms\n",
4684 				state_name, sel);
4685 	else
4686 		dev_dbg(&udev->dev, "Device-initiated %s disabled "
4687 				"due to long PEL %llu ms\n",
4688 				state_name, pel);
4689 	return USB3_LPM_DISABLED;
4690 }
4691 
4692 /* The U1 timeout should be the maximum of the following values:
4693  *  - For control endpoints, U1 system exit latency (SEL) * 3
4694  *  - For bulk endpoints, U1 SEL * 5
4695  *  - For interrupt endpoints:
4696  *    - Notification EPs, U1 SEL * 3
4697  *    - Periodic EPs, max(105% of bInterval, U1 SEL * 2)
4698  *  - For isochronous endpoints, max(105% of bInterval, U1 SEL * 2)
4699  */
4700 static unsigned long long xhci_calculate_intel_u1_timeout(
4701 		struct usb_device *udev,
4702 		struct usb_endpoint_descriptor *desc)
4703 {
4704 	unsigned long long timeout_ns;
4705 	int ep_type;
4706 	int intr_type;
4707 
4708 	ep_type = usb_endpoint_type(desc);
4709 	switch (ep_type) {
4710 	case USB_ENDPOINT_XFER_CONTROL:
4711 		timeout_ns = udev->u1_params.sel * 3;
4712 		break;
4713 	case USB_ENDPOINT_XFER_BULK:
4714 		timeout_ns = udev->u1_params.sel * 5;
4715 		break;
4716 	case USB_ENDPOINT_XFER_INT:
4717 		intr_type = usb_endpoint_interrupt_type(desc);
4718 		if (intr_type == USB_ENDPOINT_INTR_NOTIFICATION) {
4719 			timeout_ns = udev->u1_params.sel * 3;
4720 			break;
4721 		}
4722 		/* Otherwise the calculation is the same as isoc eps */
4723 		fallthrough;
4724 	case USB_ENDPOINT_XFER_ISOC:
4725 		timeout_ns = xhci_service_interval_to_ns(desc);
4726 		timeout_ns = DIV_ROUND_UP_ULL(timeout_ns * 105, 100);
4727 		if (timeout_ns < udev->u1_params.sel * 2)
4728 			timeout_ns = udev->u1_params.sel * 2;
4729 		break;
4730 	default:
4731 		return 0;
4732 	}
4733 
4734 	return timeout_ns;
4735 }
4736 
4737 /* Returns the hub-encoded U1 timeout value. */
4738 static u16 xhci_calculate_u1_timeout(struct xhci_hcd *xhci,
4739 		struct usb_device *udev,
4740 		struct usb_endpoint_descriptor *desc)
4741 {
4742 	unsigned long long timeout_ns;
4743 
4744 	/* Prevent U1 if service interval is shorter than U1 exit latency */
4745 	if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4746 		if (xhci_service_interval_to_ns(desc) <= udev->u1_params.mel) {
4747 			dev_dbg(&udev->dev, "Disable U1, ESIT shorter than exit latency\n");
4748 			return USB3_LPM_DISABLED;
4749 		}
4750 	}
4751 
4752 	if (xhci->quirks & (XHCI_INTEL_HOST | XHCI_ZHAOXIN_HOST))
4753 		timeout_ns = xhci_calculate_intel_u1_timeout(udev, desc);
4754 	else
4755 		timeout_ns = udev->u1_params.sel;
4756 
4757 	/* The U1 timeout is encoded in 1us intervals.
4758 	 * Don't return a timeout of zero, because that's USB3_LPM_DISABLED.
4759 	 */
4760 	if (timeout_ns == USB3_LPM_DISABLED)
4761 		timeout_ns = 1;
4762 	else
4763 		timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 1000);
4764 
4765 	/* If the necessary timeout value is bigger than what we can set in the
4766 	 * USB 3.0 hub, we have to disable hub-initiated U1.
4767 	 */
4768 	if (timeout_ns <= USB3_LPM_U1_MAX_TIMEOUT)
4769 		return timeout_ns;
4770 	dev_dbg(&udev->dev, "Hub-initiated U1 disabled due to long timeout %lluus\n",
4771 		timeout_ns);
4772 	return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U1);
4773 }
4774 
4775 /* The U2 timeout should be the maximum of:
4776  *  - 10 ms (to avoid the bandwidth impact on the scheduler)
4777  *  - largest bInterval of any active periodic endpoint (to avoid going
4778  *    into lower power link states between intervals).
4779  *  - the U2 Exit Latency of the device
4780  */
4781 static unsigned long long xhci_calculate_intel_u2_timeout(
4782 		struct usb_device *udev,
4783 		struct usb_endpoint_descriptor *desc)
4784 {
4785 	unsigned long long timeout_ns;
4786 	unsigned long long u2_del_ns;
4787 
4788 	timeout_ns = 10 * 1000 * 1000;
4789 
4790 	if ((usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) &&
4791 			(xhci_service_interval_to_ns(desc) > timeout_ns))
4792 		timeout_ns = xhci_service_interval_to_ns(desc);
4793 
4794 	u2_del_ns = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat) * 1000ULL;
4795 	if (u2_del_ns > timeout_ns)
4796 		timeout_ns = u2_del_ns;
4797 
4798 	return timeout_ns;
4799 }
4800 
4801 /* Returns the hub-encoded U2 timeout value. */
4802 static u16 xhci_calculate_u2_timeout(struct xhci_hcd *xhci,
4803 		struct usb_device *udev,
4804 		struct usb_endpoint_descriptor *desc)
4805 {
4806 	unsigned long long timeout_ns;
4807 
4808 	/* Prevent U2 if service interval is shorter than U2 exit latency */
4809 	if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4810 		if (xhci_service_interval_to_ns(desc) <= udev->u2_params.mel) {
4811 			dev_dbg(&udev->dev, "Disable U2, ESIT shorter than exit latency\n");
4812 			return USB3_LPM_DISABLED;
4813 		}
4814 	}
4815 
4816 	if (xhci->quirks & (XHCI_INTEL_HOST | XHCI_ZHAOXIN_HOST))
4817 		timeout_ns = xhci_calculate_intel_u2_timeout(udev, desc);
4818 	else
4819 		timeout_ns = udev->u2_params.sel;
4820 
4821 	/* The U2 timeout is encoded in 256us intervals */
4822 	timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 256 * 1000);
4823 	/* If the necessary timeout value is bigger than what we can set in the
4824 	 * USB 3.0 hub, we have to disable hub-initiated U2.
4825 	 */
4826 	if (timeout_ns <= USB3_LPM_U2_MAX_TIMEOUT)
4827 		return timeout_ns;
4828 	dev_dbg(&udev->dev, "Hub-initiated U2 disabled due to long timeout %lluus\n",
4829 		timeout_ns * 256);
4830 	return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U2);
4831 }
4832 
4833 static u16 xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4834 		struct usb_device *udev,
4835 		struct usb_endpoint_descriptor *desc,
4836 		enum usb3_link_state state,
4837 		u16 *timeout)
4838 {
4839 	if (state == USB3_LPM_U1)
4840 		return xhci_calculate_u1_timeout(xhci, udev, desc);
4841 	else if (state == USB3_LPM_U2)
4842 		return xhci_calculate_u2_timeout(xhci, udev, desc);
4843 
4844 	return USB3_LPM_DISABLED;
4845 }
4846 
4847 static int xhci_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4848 		struct usb_device *udev,
4849 		struct usb_endpoint_descriptor *desc,
4850 		enum usb3_link_state state,
4851 		u16 *timeout)
4852 {
4853 	u16 alt_timeout;
4854 
4855 	alt_timeout = xhci_call_host_update_timeout_for_endpoint(xhci, udev,
4856 		desc, state, timeout);
4857 
4858 	/* If we found we can't enable hub-initiated LPM, and
4859 	 * the U1 or U2 exit latency was too high to allow
4860 	 * device-initiated LPM as well, then we will disable LPM
4861 	 * for this device, so stop searching any further.
4862 	 */
4863 	if (alt_timeout == USB3_LPM_DISABLED) {
4864 		*timeout = alt_timeout;
4865 		return -E2BIG;
4866 	}
4867 	if (alt_timeout > *timeout)
4868 		*timeout = alt_timeout;
4869 	return 0;
4870 }
4871 
4872 static int xhci_update_timeout_for_interface(struct xhci_hcd *xhci,
4873 		struct usb_device *udev,
4874 		struct usb_host_interface *alt,
4875 		enum usb3_link_state state,
4876 		u16 *timeout)
4877 {
4878 	int j;
4879 
4880 	for (j = 0; j < alt->desc.bNumEndpoints; j++) {
4881 		if (xhci_update_timeout_for_endpoint(xhci, udev,
4882 					&alt->endpoint[j].desc, state, timeout))
4883 			return -E2BIG;
4884 	}
4885 	return 0;
4886 }
4887 
4888 static int xhci_check_tier_policy(struct xhci_hcd *xhci,
4889 		struct usb_device *udev,
4890 		enum usb3_link_state state)
4891 {
4892 	struct usb_device *parent = udev->parent;
4893 	int tier = 1; /* roothub is tier1 */
4894 
4895 	while (parent) {
4896 		parent = parent->parent;
4897 		tier++;
4898 	}
4899 
4900 	if (xhci->quirks & XHCI_INTEL_HOST && tier > 3)
4901 		goto fail;
4902 	if (xhci->quirks & XHCI_ZHAOXIN_HOST && tier > 2)
4903 		goto fail;
4904 
4905 	return 0;
4906 fail:
4907 	dev_dbg(&udev->dev, "Tier policy prevents U1/U2 LPM states for devices at tier %d\n",
4908 			tier);
4909 	return -E2BIG;
4910 }
4911 
4912 /* Returns the U1 or U2 timeout that should be enabled.
4913  * If the tier check or timeout setting functions return with a non-zero exit
4914  * code, that means the timeout value has been finalized and we shouldn't look
4915  * at any more endpoints.
4916  */
4917 static u16 xhci_calculate_lpm_timeout(struct usb_hcd *hcd,
4918 			struct usb_device *udev, enum usb3_link_state state)
4919 {
4920 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4921 	struct usb_host_config *config;
4922 	char *state_name;
4923 	int i;
4924 	u16 timeout = USB3_LPM_DISABLED;
4925 
4926 	if (state == USB3_LPM_U1)
4927 		state_name = "U1";
4928 	else if (state == USB3_LPM_U2)
4929 		state_name = "U2";
4930 	else {
4931 		dev_warn(&udev->dev, "Can't enable unknown link state %i\n",
4932 				state);
4933 		return timeout;
4934 	}
4935 
4936 	/* Gather some information about the currently installed configuration
4937 	 * and alternate interface settings.
4938 	 */
4939 	if (xhci_update_timeout_for_endpoint(xhci, udev, &udev->ep0.desc,
4940 			state, &timeout))
4941 		return timeout;
4942 
4943 	config = udev->actconfig;
4944 	if (!config)
4945 		return timeout;
4946 
4947 	for (i = 0; i < config->desc.bNumInterfaces; i++) {
4948 		struct usb_driver *driver;
4949 		struct usb_interface *intf = config->interface[i];
4950 
4951 		if (!intf)
4952 			continue;
4953 
4954 		/* Check if any currently bound drivers want hub-initiated LPM
4955 		 * disabled.
4956 		 */
4957 		if (intf->dev.driver) {
4958 			driver = to_usb_driver(intf->dev.driver);
4959 			if (driver && driver->disable_hub_initiated_lpm) {
4960 				dev_dbg(&udev->dev, "Hub-initiated %s disabled at request of driver %s\n",
4961 					state_name, driver->name);
4962 				timeout = xhci_get_timeout_no_hub_lpm(udev,
4963 								      state);
4964 				if (timeout == USB3_LPM_DISABLED)
4965 					return timeout;
4966 			}
4967 		}
4968 
4969 		/* Not sure how this could happen... */
4970 		if (!intf->cur_altsetting)
4971 			continue;
4972 
4973 		if (xhci_update_timeout_for_interface(xhci, udev,
4974 					intf->cur_altsetting,
4975 					state, &timeout))
4976 			return timeout;
4977 	}
4978 	return timeout;
4979 }
4980 
4981 static int calculate_max_exit_latency(struct usb_device *udev,
4982 		enum usb3_link_state state_changed,
4983 		u16 hub_encoded_timeout)
4984 {
4985 	unsigned long long u1_mel_us = 0;
4986 	unsigned long long u2_mel_us = 0;
4987 	unsigned long long mel_us = 0;
4988 	bool disabling_u1;
4989 	bool disabling_u2;
4990 	bool enabling_u1;
4991 	bool enabling_u2;
4992 
4993 	disabling_u1 = (state_changed == USB3_LPM_U1 &&
4994 			hub_encoded_timeout == USB3_LPM_DISABLED);
4995 	disabling_u2 = (state_changed == USB3_LPM_U2 &&
4996 			hub_encoded_timeout == USB3_LPM_DISABLED);
4997 
4998 	enabling_u1 = (state_changed == USB3_LPM_U1 &&
4999 			hub_encoded_timeout != USB3_LPM_DISABLED);
5000 	enabling_u2 = (state_changed == USB3_LPM_U2 &&
5001 			hub_encoded_timeout != USB3_LPM_DISABLED);
5002 
5003 	/* If U1 was already enabled and we're not disabling it,
5004 	 * or we're going to enable U1, account for the U1 max exit latency.
5005 	 */
5006 	if ((udev->u1_params.timeout != USB3_LPM_DISABLED && !disabling_u1) ||
5007 			enabling_u1)
5008 		u1_mel_us = DIV_ROUND_UP(udev->u1_params.mel, 1000);
5009 	if ((udev->u2_params.timeout != USB3_LPM_DISABLED && !disabling_u2) ||
5010 			enabling_u2)
5011 		u2_mel_us = DIV_ROUND_UP(udev->u2_params.mel, 1000);
5012 
5013 	mel_us = max(u1_mel_us, u2_mel_us);
5014 
5015 	/* xHCI host controller max exit latency field is only 16 bits wide. */
5016 	if (mel_us > MAX_EXIT) {
5017 		dev_warn(&udev->dev, "Link PM max exit latency of %lluus "
5018 				"is too big.\n", mel_us);
5019 		return -E2BIG;
5020 	}
5021 	return mel_us;
5022 }
5023 
5024 /* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
5025 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
5026 			struct usb_device *udev, enum usb3_link_state state)
5027 {
5028 	struct xhci_hcd	*xhci;
5029 	struct xhci_port *port;
5030 	u16 hub_encoded_timeout;
5031 	int mel;
5032 	int ret;
5033 
5034 	xhci = hcd_to_xhci(hcd);
5035 	/* The LPM timeout values are pretty host-controller specific, so don't
5036 	 * enable hub-initiated timeouts unless the vendor has provided
5037 	 * information about their timeout algorithm.
5038 	 */
5039 	if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
5040 			!xhci->devs[udev->slot_id])
5041 		return USB3_LPM_DISABLED;
5042 
5043 	if (xhci_check_tier_policy(xhci, udev, state) < 0)
5044 		return USB3_LPM_DISABLED;
5045 
5046 	/* If connected to root port then check port can handle lpm */
5047 	if (udev->parent && !udev->parent->parent) {
5048 		port = xhci->usb3_rhub.ports[udev->portnum - 1];
5049 		if (port->lpm_incapable)
5050 			return USB3_LPM_DISABLED;
5051 	}
5052 
5053 	hub_encoded_timeout = xhci_calculate_lpm_timeout(hcd, udev, state);
5054 	mel = calculate_max_exit_latency(udev, state, hub_encoded_timeout);
5055 	if (mel < 0) {
5056 		/* Max Exit Latency is too big, disable LPM. */
5057 		hub_encoded_timeout = USB3_LPM_DISABLED;
5058 		mel = 0;
5059 	}
5060 
5061 	ret = xhci_change_max_exit_latency(xhci, udev, mel);
5062 	if (ret)
5063 		return ret;
5064 	return hub_encoded_timeout;
5065 }
5066 
5067 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
5068 			struct usb_device *udev, enum usb3_link_state state)
5069 {
5070 	struct xhci_hcd	*xhci;
5071 	u16 mel;
5072 
5073 	xhci = hcd_to_xhci(hcd);
5074 	if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
5075 			!xhci->devs[udev->slot_id])
5076 		return 0;
5077 
5078 	mel = calculate_max_exit_latency(udev, state, USB3_LPM_DISABLED);
5079 	return xhci_change_max_exit_latency(xhci, udev, mel);
5080 }
5081 #else /* CONFIG_PM */
5082 
5083 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
5084 				struct usb_device *udev, int enable)
5085 {
5086 	return 0;
5087 }
5088 
5089 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
5090 {
5091 	return 0;
5092 }
5093 
5094 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
5095 			struct usb_device *udev, enum usb3_link_state state)
5096 {
5097 	return USB3_LPM_DISABLED;
5098 }
5099 
5100 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
5101 			struct usb_device *udev, enum usb3_link_state state)
5102 {
5103 	return 0;
5104 }
5105 #endif	/* CONFIG_PM */
5106 
5107 /*-------------------------------------------------------------------------*/
5108 
5109 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
5110  * internal data structures for the device.
5111  */
5112 int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
5113 			struct usb_tt *tt, gfp_t mem_flags)
5114 {
5115 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5116 	struct xhci_virt_device *vdev;
5117 	struct xhci_command *config_cmd;
5118 	struct xhci_input_control_ctx *ctrl_ctx;
5119 	struct xhci_slot_ctx *slot_ctx;
5120 	unsigned long flags;
5121 	unsigned think_time;
5122 	int ret;
5123 
5124 	/* Ignore root hubs */
5125 	if (!hdev->parent)
5126 		return 0;
5127 
5128 	vdev = xhci->devs[hdev->slot_id];
5129 	if (!vdev) {
5130 		xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
5131 		return -EINVAL;
5132 	}
5133 
5134 	config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
5135 	if (!config_cmd)
5136 		return -ENOMEM;
5137 
5138 	ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
5139 	if (!ctrl_ctx) {
5140 		xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
5141 				__func__);
5142 		xhci_free_command(xhci, config_cmd);
5143 		return -ENOMEM;
5144 	}
5145 
5146 	spin_lock_irqsave(&xhci->lock, flags);
5147 	if (hdev->speed == USB_SPEED_HIGH &&
5148 			xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
5149 		xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
5150 		xhci_free_command(xhci, config_cmd);
5151 		spin_unlock_irqrestore(&xhci->lock, flags);
5152 		return -ENOMEM;
5153 	}
5154 
5155 	xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
5156 	ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
5157 	slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
5158 	slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
5159 	/*
5160 	 * refer to section 6.2.2: MTT should be 0 for full speed hub,
5161 	 * but it may be already set to 1 when setup an xHCI virtual
5162 	 * device, so clear it anyway.
5163 	 */
5164 	if (tt->multi)
5165 		slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
5166 	else if (hdev->speed == USB_SPEED_FULL)
5167 		slot_ctx->dev_info &= cpu_to_le32(~DEV_MTT);
5168 
5169 	if (xhci->hci_version > 0x95) {
5170 		xhci_dbg(xhci, "xHCI version %x needs hub "
5171 				"TT think time and number of ports\n",
5172 				(unsigned int) xhci->hci_version);
5173 		slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
5174 		/* Set TT think time - convert from ns to FS bit times.
5175 		 * 0 = 8 FS bit times, 1 = 16 FS bit times,
5176 		 * 2 = 24 FS bit times, 3 = 32 FS bit times.
5177 		 *
5178 		 * xHCI 1.0: this field shall be 0 if the device is not a
5179 		 * High-spped hub.
5180 		 */
5181 		think_time = tt->think_time;
5182 		if (think_time != 0)
5183 			think_time = (think_time / 666) - 1;
5184 		if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
5185 			slot_ctx->tt_info |=
5186 				cpu_to_le32(TT_THINK_TIME(think_time));
5187 	} else {
5188 		xhci_dbg(xhci, "xHCI version %x doesn't need hub "
5189 				"TT think time or number of ports\n",
5190 				(unsigned int) xhci->hci_version);
5191 	}
5192 	slot_ctx->dev_state = 0;
5193 	spin_unlock_irqrestore(&xhci->lock, flags);
5194 
5195 	xhci_dbg(xhci, "Set up %s for hub device.\n",
5196 			(xhci->hci_version > 0x95) ?
5197 			"configure endpoint" : "evaluate context");
5198 
5199 	/* Issue and wait for the configure endpoint or
5200 	 * evaluate context command.
5201 	 */
5202 	if (xhci->hci_version > 0x95)
5203 		ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5204 				false, false);
5205 	else
5206 		ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5207 				true, false);
5208 
5209 	xhci_free_command(xhci, config_cmd);
5210 	return ret;
5211 }
5212 EXPORT_SYMBOL_GPL(xhci_update_hub_device);
5213 
5214 static int xhci_get_frame(struct usb_hcd *hcd)
5215 {
5216 	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5217 	/* EHCI mods by the periodic size.  Why? */
5218 	return readl(&xhci->run_regs->microframe_index) >> 3;
5219 }
5220 
5221 static void xhci_hcd_init_usb2_data(struct xhci_hcd *xhci, struct usb_hcd *hcd)
5222 {
5223 	xhci->usb2_rhub.hcd = hcd;
5224 	hcd->speed = HCD_USB2;
5225 	hcd->self.root_hub->speed = USB_SPEED_HIGH;
5226 	/*
5227 	 * USB 2.0 roothub under xHCI has an integrated TT,
5228 	 * (rate matching hub) as opposed to having an OHCI/UHCI
5229 	 * companion controller.
5230 	 */
5231 	hcd->has_tt = 1;
5232 }
5233 
5234 static void xhci_hcd_init_usb3_data(struct xhci_hcd *xhci, struct usb_hcd *hcd)
5235 {
5236 	unsigned int minor_rev;
5237 
5238 	/*
5239 	 * Early xHCI 1.1 spec did not mention USB 3.1 capable hosts
5240 	 * should return 0x31 for sbrn, or that the minor revision
5241 	 * is a two digit BCD containig minor and sub-minor numbers.
5242 	 * This was later clarified in xHCI 1.2.
5243 	 *
5244 	 * Some USB 3.1 capable hosts therefore have sbrn 0x30, and
5245 	 * minor revision set to 0x1 instead of 0x10.
5246 	 */
5247 	if (xhci->usb3_rhub.min_rev == 0x1)
5248 		minor_rev = 1;
5249 	else
5250 		minor_rev = xhci->usb3_rhub.min_rev / 0x10;
5251 
5252 	switch (minor_rev) {
5253 	case 2:
5254 		hcd->speed = HCD_USB32;
5255 		hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5256 		hcd->self.root_hub->rx_lanes = 2;
5257 		hcd->self.root_hub->tx_lanes = 2;
5258 		hcd->self.root_hub->ssp_rate = USB_SSP_GEN_2x2;
5259 		break;
5260 	case 1:
5261 		hcd->speed = HCD_USB31;
5262 		hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5263 		hcd->self.root_hub->ssp_rate = USB_SSP_GEN_2x1;
5264 		break;
5265 	}
5266 	xhci_info(xhci, "Host supports USB 3.%x %sSuperSpeed\n",
5267 		  minor_rev, minor_rev ? "Enhanced " : "");
5268 
5269 	xhci->usb3_rhub.hcd = hcd;
5270 }
5271 
5272 int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
5273 {
5274 	struct xhci_hcd		*xhci;
5275 	/*
5276 	 * TODO: Check with DWC3 clients for sysdev according to
5277 	 * quirks
5278 	 */
5279 	struct device		*dev = hcd->self.sysdev;
5280 	int			retval;
5281 
5282 	/* Accept arbitrarily long scatter-gather lists */
5283 	hcd->self.sg_tablesize = ~0;
5284 
5285 	/* support to build packet from discontinuous buffers */
5286 	hcd->self.no_sg_constraint = 1;
5287 
5288 	/* XHCI controllers don't stop the ep queue on short packets :| */
5289 	hcd->self.no_stop_on_short = 1;
5290 
5291 	xhci = hcd_to_xhci(hcd);
5292 
5293 	if (!usb_hcd_is_primary_hcd(hcd)) {
5294 		xhci_hcd_init_usb3_data(xhci, hcd);
5295 		return 0;
5296 	}
5297 
5298 	mutex_init(&xhci->mutex);
5299 	xhci->main_hcd = hcd;
5300 	xhci->cap_regs = hcd->regs;
5301 	xhci->op_regs = hcd->regs +
5302 		HC_LENGTH(readl(&xhci->cap_regs->hc_capbase));
5303 	xhci->run_regs = hcd->regs +
5304 		(readl(&xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
5305 	/* Cache read-only capability registers */
5306 	xhci->hcs_params1 = readl(&xhci->cap_regs->hcs_params1);
5307 	xhci->hcs_params2 = readl(&xhci->cap_regs->hcs_params2);
5308 	xhci->hcs_params3 = readl(&xhci->cap_regs->hcs_params3);
5309 	xhci->hci_version = HC_VERSION(readl(&xhci->cap_regs->hc_capbase));
5310 	xhci->hcc_params = readl(&xhci->cap_regs->hcc_params);
5311 	if (xhci->hci_version > 0x100)
5312 		xhci->hcc_params2 = readl(&xhci->cap_regs->hcc_params2);
5313 
5314 	/* xhci-plat or xhci-pci might have set max_interrupters already */
5315 	if ((!xhci->max_interrupters) ||
5316 	    xhci->max_interrupters > HCS_MAX_INTRS(xhci->hcs_params1))
5317 		xhci->max_interrupters = HCS_MAX_INTRS(xhci->hcs_params1);
5318 
5319 	xhci->quirks |= quirks;
5320 
5321 	if (get_quirks)
5322 		get_quirks(dev, xhci);
5323 
5324 	/* In xhci controllers which follow xhci 1.0 spec gives a spurious
5325 	 * success event after a short transfer. This quirk will ignore such
5326 	 * spurious event.
5327 	 */
5328 	if (xhci->hci_version > 0x96)
5329 		xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
5330 
5331 	if (xhci->hci_version == 0x95 && link_quirk) {
5332 		xhci_dbg(xhci, "QUIRK: Not clearing Link TRB chain bits");
5333 		xhci->quirks |= XHCI_LINK_TRB_QUIRK;
5334 	}
5335 
5336 	/* Make sure the HC is halted. */
5337 	retval = xhci_halt(xhci);
5338 	if (retval)
5339 		return retval;
5340 
5341 	xhci_zero_64b_regs(xhci);
5342 
5343 	xhci_dbg(xhci, "Resetting HCD\n");
5344 	/* Reset the internal HC memory state and registers. */
5345 	retval = xhci_reset(xhci, XHCI_RESET_LONG_USEC);
5346 	if (retval)
5347 		return retval;
5348 	xhci_dbg(xhci, "Reset complete\n");
5349 
5350 	/*
5351 	 * On some xHCI controllers (e.g. R-Car SoCs), the AC64 bit (bit 0)
5352 	 * of HCCPARAMS1 is set to 1. However, the xHCs don't support 64-bit
5353 	 * address memory pointers actually. So, this driver clears the AC64
5354 	 * bit of xhci->hcc_params to call dma_set_coherent_mask(dev,
5355 	 * DMA_BIT_MASK(32)) in this xhci_gen_setup().
5356 	 */
5357 	if (xhci->quirks & XHCI_NO_64BIT_SUPPORT)
5358 		xhci->hcc_params &= ~BIT(0);
5359 
5360 	/* Set dma_mask and coherent_dma_mask to 64-bits,
5361 	 * if xHC supports 64-bit addressing */
5362 	if (HCC_64BIT_ADDR(xhci->hcc_params) &&
5363 			!dma_set_mask(dev, DMA_BIT_MASK(64))) {
5364 		xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
5365 		dma_set_coherent_mask(dev, DMA_BIT_MASK(64));
5366 	} else {
5367 		/*
5368 		 * This is to avoid error in cases where a 32-bit USB
5369 		 * controller is used on a 64-bit capable system.
5370 		 */
5371 		retval = dma_set_mask(dev, DMA_BIT_MASK(32));
5372 		if (retval)
5373 			return retval;
5374 		xhci_dbg(xhci, "Enabling 32-bit DMA addresses.\n");
5375 		dma_set_coherent_mask(dev, DMA_BIT_MASK(32));
5376 	}
5377 
5378 	xhci_dbg(xhci, "Calling HCD init\n");
5379 	/* Initialize HCD and host controller data structures. */
5380 	retval = xhci_init(hcd);
5381 	if (retval)
5382 		return retval;
5383 	xhci_dbg(xhci, "Called HCD init\n");
5384 
5385 	if (xhci_hcd_is_usb3(hcd))
5386 		xhci_hcd_init_usb3_data(xhci, hcd);
5387 	else
5388 		xhci_hcd_init_usb2_data(xhci, hcd);
5389 
5390 	xhci_info(xhci, "hcc params 0x%08x hci version 0x%x quirks 0x%016llx\n",
5391 		  xhci->hcc_params, xhci->hci_version, xhci->quirks);
5392 
5393 	return 0;
5394 }
5395 EXPORT_SYMBOL_GPL(xhci_gen_setup);
5396 
5397 static void xhci_clear_tt_buffer_complete(struct usb_hcd *hcd,
5398 		struct usb_host_endpoint *ep)
5399 {
5400 	struct xhci_hcd *xhci;
5401 	struct usb_device *udev;
5402 	unsigned int slot_id;
5403 	unsigned int ep_index;
5404 	unsigned long flags;
5405 
5406 	xhci = hcd_to_xhci(hcd);
5407 
5408 	spin_lock_irqsave(&xhci->lock, flags);
5409 	udev = (struct usb_device *)ep->hcpriv;
5410 	slot_id = udev->slot_id;
5411 	ep_index = xhci_get_endpoint_index(&ep->desc);
5412 
5413 	xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_CLEARING_TT;
5414 	xhci_ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
5415 	spin_unlock_irqrestore(&xhci->lock, flags);
5416 }
5417 
5418 static const struct hc_driver xhci_hc_driver = {
5419 	.description =		"xhci-hcd",
5420 	.product_desc =		"xHCI Host Controller",
5421 	.hcd_priv_size =	sizeof(struct xhci_hcd),
5422 
5423 	/*
5424 	 * generic hardware linkage
5425 	 */
5426 	.irq =			xhci_irq,
5427 	.flags =		HCD_MEMORY | HCD_DMA | HCD_USB3 | HCD_SHARED |
5428 				HCD_BH,
5429 
5430 	/*
5431 	 * basic lifecycle operations
5432 	 */
5433 	.reset =		NULL, /* set in xhci_init_driver() */
5434 	.start =		xhci_run,
5435 	.stop =			xhci_stop,
5436 	.shutdown =		xhci_shutdown,
5437 
5438 	/*
5439 	 * managing i/o requests and associated device resources
5440 	 */
5441 	.map_urb_for_dma =      xhci_map_urb_for_dma,
5442 	.unmap_urb_for_dma =    xhci_unmap_urb_for_dma,
5443 	.urb_enqueue =		xhci_urb_enqueue,
5444 	.urb_dequeue =		xhci_urb_dequeue,
5445 	.alloc_dev =		xhci_alloc_dev,
5446 	.free_dev =		xhci_free_dev,
5447 	.alloc_streams =	xhci_alloc_streams,
5448 	.free_streams =		xhci_free_streams,
5449 	.add_endpoint =		xhci_add_endpoint,
5450 	.drop_endpoint =	xhci_drop_endpoint,
5451 	.endpoint_disable =	xhci_endpoint_disable,
5452 	.endpoint_reset =	xhci_endpoint_reset,
5453 	.check_bandwidth =	xhci_check_bandwidth,
5454 	.reset_bandwidth =	xhci_reset_bandwidth,
5455 	.address_device =	xhci_address_device,
5456 	.enable_device =	xhci_enable_device,
5457 	.update_hub_device =	xhci_update_hub_device,
5458 	.reset_device =		xhci_discover_or_reset_device,
5459 
5460 	/*
5461 	 * scheduling support
5462 	 */
5463 	.get_frame_number =	xhci_get_frame,
5464 
5465 	/*
5466 	 * root hub support
5467 	 */
5468 	.hub_control =		xhci_hub_control,
5469 	.hub_status_data =	xhci_hub_status_data,
5470 	.bus_suspend =		xhci_bus_suspend,
5471 	.bus_resume =		xhci_bus_resume,
5472 	.get_resuming_ports =	xhci_get_resuming_ports,
5473 
5474 	/*
5475 	 * call back when device connected and addressed
5476 	 */
5477 	.update_device =        xhci_update_device,
5478 	.set_usb2_hw_lpm =	xhci_set_usb2_hardware_lpm,
5479 	.enable_usb3_lpm_timeout =	xhci_enable_usb3_lpm_timeout,
5480 	.disable_usb3_lpm_timeout =	xhci_disable_usb3_lpm_timeout,
5481 	.find_raw_port_number =	xhci_find_raw_port_number,
5482 	.clear_tt_buffer_complete = xhci_clear_tt_buffer_complete,
5483 };
5484 
5485 void xhci_init_driver(struct hc_driver *drv,
5486 		      const struct xhci_driver_overrides *over)
5487 {
5488 	BUG_ON(!over);
5489 
5490 	/* Copy the generic table to drv then apply the overrides */
5491 	*drv = xhci_hc_driver;
5492 
5493 	if (over) {
5494 		drv->hcd_priv_size += over->extra_priv_size;
5495 		if (over->reset)
5496 			drv->reset = over->reset;
5497 		if (over->start)
5498 			drv->start = over->start;
5499 		if (over->add_endpoint)
5500 			drv->add_endpoint = over->add_endpoint;
5501 		if (over->drop_endpoint)
5502 			drv->drop_endpoint = over->drop_endpoint;
5503 		if (over->check_bandwidth)
5504 			drv->check_bandwidth = over->check_bandwidth;
5505 		if (over->reset_bandwidth)
5506 			drv->reset_bandwidth = over->reset_bandwidth;
5507 		if (over->update_hub_device)
5508 			drv->update_hub_device = over->update_hub_device;
5509 		if (over->hub_control)
5510 			drv->hub_control = over->hub_control;
5511 	}
5512 }
5513 EXPORT_SYMBOL_GPL(xhci_init_driver);
5514 
5515 MODULE_DESCRIPTION(DRIVER_DESC);
5516 MODULE_AUTHOR(DRIVER_AUTHOR);
5517 MODULE_LICENSE("GPL");
5518 
5519 static int __init xhci_hcd_init(void)
5520 {
5521 	/*
5522 	 * Check the compiler generated sizes of structures that must be laid
5523 	 * out in specific ways for hardware access.
5524 	 */
5525 	BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
5526 	BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
5527 	BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
5528 	/* xhci_device_control has eight fields, and also
5529 	 * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
5530 	 */
5531 	BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
5532 	BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
5533 	BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
5534 	BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 8*32/8);
5535 	BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
5536 	/* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
5537 	BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
5538 
5539 	if (usb_disabled())
5540 		return -ENODEV;
5541 
5542 	xhci_debugfs_create_root();
5543 	xhci_dbc_init();
5544 
5545 	return 0;
5546 }
5547 
5548 /*
5549  * If an init function is provided, an exit function must also be provided
5550  * to allow module unload.
5551  */
5552 static void __exit xhci_hcd_fini(void)
5553 {
5554 	xhci_debugfs_remove_root();
5555 	xhci_dbc_exit();
5556 }
5557 
5558 module_init(xhci_hcd_init);
5559 module_exit(xhci_hcd_fini);
5560