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