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