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