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