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