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