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