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