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