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