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