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