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