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