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