blob: 505da4999e208fc4114e0df4c437e6ad553d170f [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;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001094
1095 if (!hcd->state)
1096 return 0;
1097
1098 /* Wait a bit if either of the roothubs need to settle from the
1099 * transition into bus suspend.
1100 */
David Brazdil0f672f62019-12-10 10:32:29 +00001101
1102 if (time_before(jiffies, xhci->usb2_rhub.bus_state.next_statechange) ||
1103 time_before(jiffies, xhci->usb3_rhub.bus_state.next_statechange))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001104 msleep(100);
1105
1106 set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1107 set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1108
1109 spin_lock_irq(&xhci->lock);
1110 if ((xhci->quirks & XHCI_RESET_ON_RESUME) || xhci->broken_suspend)
1111 hibernated = true;
1112
1113 if (!hibernated) {
David Brazdil0f672f62019-12-10 10:32:29 +00001114 /*
1115 * Some controllers might lose power during suspend, so wait
1116 * for controller not ready bit to clear, just as in xHC init.
1117 */
1118 retval = xhci_handshake(&xhci->op_regs->status,
1119 STS_CNR, 0, 10 * 1000 * 1000);
1120 if (retval) {
1121 xhci_warn(xhci, "Controller not ready at resume %d\n",
1122 retval);
1123 spin_unlock_irq(&xhci->lock);
1124 return retval;
1125 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001126 /* step 1: restore register */
1127 xhci_restore_registers(xhci);
1128 /* step 2: initialize command ring buffer */
1129 xhci_set_cmd_ring_deq(xhci);
1130 /* step 3: restore state and start state*/
1131 /* step 3: set CRS flag */
1132 command = readl(&xhci->op_regs->command);
1133 command |= CMD_CRS;
1134 writel(command, &xhci->op_regs->command);
1135 /*
1136 * Some controllers take up to 55+ ms to complete the controller
1137 * restore so setting the timeout to 100ms. Xhci specification
1138 * doesn't mention any timeout value.
1139 */
1140 if (xhci_handshake(&xhci->op_regs->status,
1141 STS_RESTORE, 0, 100 * 1000)) {
1142 xhci_warn(xhci, "WARN: xHC restore state timeout\n");
1143 spin_unlock_irq(&xhci->lock);
1144 return -ETIMEDOUT;
1145 }
1146 temp = readl(&xhci->op_regs->status);
1147 }
1148
1149 /* If restore operation fails, re-initialize the HC during resume */
1150 if ((temp & STS_SRE) || hibernated) {
1151
1152 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
1153 !(xhci_all_ports_seen_u0(xhci))) {
1154 del_timer_sync(&xhci->comp_mode_recovery_timer);
1155 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1156 "Compliance Mode Recovery Timer deleted!");
1157 }
1158
1159 /* Let the USB core know _both_ roothubs lost power. */
1160 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1161 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
1162
1163 xhci_dbg(xhci, "Stop HCD\n");
1164 xhci_halt(xhci);
1165 xhci_zero_64b_regs(xhci);
Olivier Deprez0e641232021-09-23 10:07:05 +02001166 retval = xhci_reset(xhci);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001167 spin_unlock_irq(&xhci->lock);
Olivier Deprez0e641232021-09-23 10:07:05 +02001168 if (retval)
1169 return retval;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001170 xhci_cleanup_msix(xhci);
1171
1172 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1173 temp = readl(&xhci->op_regs->status);
1174 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
1175 temp = readl(&xhci->ir_set->irq_pending);
1176 writel(ER_IRQ_DISABLE(temp), &xhci->ir_set->irq_pending);
1177
1178 xhci_dbg(xhci, "cleaning up memory\n");
1179 xhci_mem_cleanup(xhci);
1180 xhci_debugfs_exit(xhci);
1181 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
1182 readl(&xhci->op_regs->status));
1183
1184 /* USB core calls the PCI reinit and start functions twice:
1185 * first with the primary HCD, and then with the secondary HCD.
1186 * If we don't do the same, the host will never be started.
1187 */
1188 if (!usb_hcd_is_primary_hcd(hcd))
1189 secondary_hcd = hcd;
1190 else
1191 secondary_hcd = xhci->shared_hcd;
1192
1193 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1194 retval = xhci_init(hcd->primary_hcd);
1195 if (retval)
1196 return retval;
1197 comp_timer_running = true;
1198
1199 xhci_dbg(xhci, "Start the primary HCD\n");
1200 retval = xhci_run(hcd->primary_hcd);
1201 if (!retval) {
1202 xhci_dbg(xhci, "Start the secondary HCD\n");
1203 retval = xhci_run(secondary_hcd);
1204 }
1205 hcd->state = HC_STATE_SUSPENDED;
1206 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1207 goto done;
1208 }
1209
1210 /* step 4: set Run/Stop bit */
1211 command = readl(&xhci->op_regs->command);
1212 command |= CMD_RUN;
1213 writel(command, &xhci->op_regs->command);
1214 xhci_handshake(&xhci->op_regs->status, STS_HALT,
1215 0, 250 * 1000);
1216
1217 /* step 5: walk topology and initialize portsc,
1218 * portpmsc and portli
1219 */
1220 /* this is done in bus_resume */
1221
1222 /* step 6: restart each of the previously
1223 * Running endpoints by ringing their doorbells
1224 */
1225
1226 spin_unlock_irq(&xhci->lock);
1227
1228 xhci_dbc_resume(xhci);
1229
1230 done:
1231 if (retval == 0) {
Olivier Deprez0e641232021-09-23 10:07:05 +02001232 /*
1233 * Resume roothubs only if there are pending events.
1234 * USB 3 devices resend U3 LFPS wake after a 100ms delay if
1235 * the first wake signalling failed, give it that chance.
1236 */
1237 pending_portevent = xhci_pending_portevent(xhci);
1238 if (!pending_portevent) {
1239 msleep(120);
1240 pending_portevent = xhci_pending_portevent(xhci);
1241 }
1242
1243 if (pending_portevent) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001244 usb_hcd_resume_root_hub(xhci->shared_hcd);
1245 usb_hcd_resume_root_hub(hcd);
1246 }
1247 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001248 /*
1249 * If system is subject to the Quirk, Compliance Mode Timer needs to
1250 * be re-initialized Always after a system resume. Ports are subject
1251 * to suffer the Compliance Mode issue again. It doesn't matter if
1252 * ports have entered previously to U0 before system's suspension.
1253 */
1254 if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) && !comp_timer_running)
1255 compliance_mode_recovery_timer_init(xhci);
1256
1257 if (xhci->quirks & XHCI_ASMEDIA_MODIFY_FLOWCONTROL)
1258 usb_asmedia_modifyflowcontrol(to_pci_dev(hcd->self.controller));
1259
1260 /* Re-enable port polling. */
1261 xhci_dbg(xhci, "%s: starting port polling.\n", __func__);
1262 set_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
1263 usb_hcd_poll_rh_status(xhci->shared_hcd);
1264 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1265 usb_hcd_poll_rh_status(hcd);
1266
1267 return retval;
1268}
1269EXPORT_SYMBOL_GPL(xhci_resume);
1270#endif /* CONFIG_PM */
1271
1272/*-------------------------------------------------------------------------*/
1273
David Brazdil0f672f62019-12-10 10:32:29 +00001274/*
1275 * Bypass the DMA mapping if URB is suitable for Immediate Transfer (IDT),
1276 * we'll copy the actual data into the TRB address register. This is limited to
1277 * transfers up to 8 bytes on output endpoints of any kind with wMaxPacketSize
1278 * >= 8 bytes. If suitable for IDT only one Transfer TRB per TD is allowed.
1279 */
1280static int xhci_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
1281 gfp_t mem_flags)
1282{
1283 if (xhci_urb_suitable_for_idt(urb))
1284 return 0;
1285
1286 return usb_hcd_map_urb_for_dma(hcd, urb, mem_flags);
1287}
1288
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001289/**
1290 * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1291 * HCDs. Find the index for an endpoint given its descriptor. Use the return
1292 * value to right shift 1 for the bitmask.
1293 *
1294 * Index = (epnum * 2) + direction - 1,
1295 * where direction = 0 for OUT, 1 for IN.
1296 * For control endpoints, the IN index is used (OUT index is unused), so
1297 * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1298 */
1299unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1300{
1301 unsigned int index;
1302 if (usb_endpoint_xfer_control(desc))
1303 index = (unsigned int) (usb_endpoint_num(desc)*2);
1304 else
1305 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1306 (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1307 return index;
1308}
1309
1310/* The reverse operation to xhci_get_endpoint_index. Calculate the USB endpoint
1311 * address from the XHCI endpoint index.
1312 */
1313unsigned int xhci_get_endpoint_address(unsigned int ep_index)
1314{
1315 unsigned int number = DIV_ROUND_UP(ep_index, 2);
1316 unsigned int direction = ep_index % 2 ? USB_DIR_OUT : USB_DIR_IN;
1317 return direction | number;
1318}
1319
1320/* Find the flag for this endpoint (for use in the control context). Use the
1321 * endpoint index to create a bitmask. The slot context is bit 0, endpoint 0 is
1322 * bit 1, etc.
1323 */
1324static unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1325{
1326 return 1 << (xhci_get_endpoint_index(desc) + 1);
1327}
1328
1329/* Find the flag for this endpoint (for use in the control context). Use the
1330 * endpoint index to create a bitmask. The slot context is bit 0, endpoint 0 is
1331 * bit 1, etc.
1332 */
1333static unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
1334{
1335 return 1 << (ep_index + 1);
1336}
1337
1338/* Compute the last valid endpoint context index. Basically, this is the
1339 * endpoint index plus one. For slot contexts with more than valid endpoint,
1340 * we find the most significant bit set in the added contexts flags.
1341 * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1342 * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1343 */
1344unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1345{
1346 return fls(added_ctxs) - 1;
1347}
1348
1349/* Returns 1 if the arguments are OK;
1350 * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1351 */
1352static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1353 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1354 const char *func) {
1355 struct xhci_hcd *xhci;
1356 struct xhci_virt_device *virt_dev;
1357
1358 if (!hcd || (check_ep && !ep) || !udev) {
1359 pr_debug("xHCI %s called with invalid args\n", func);
1360 return -EINVAL;
1361 }
1362 if (!udev->parent) {
1363 pr_debug("xHCI %s called for root hub\n", func);
1364 return 0;
1365 }
1366
1367 xhci = hcd_to_xhci(hcd);
1368 if (check_virt_dev) {
1369 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1370 xhci_dbg(xhci, "xHCI %s called with unaddressed device\n",
1371 func);
1372 return -EINVAL;
1373 }
1374
1375 virt_dev = xhci->devs[udev->slot_id];
1376 if (virt_dev->udev != udev) {
1377 xhci_dbg(xhci, "xHCI %s called with udev and "
1378 "virt_dev does not match\n", func);
1379 return -EINVAL;
1380 }
1381 }
1382
1383 if (xhci->xhc_state & XHCI_STATE_HALTED)
1384 return -ENODEV;
1385
1386 return 1;
1387}
1388
1389static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1390 struct usb_device *udev, struct xhci_command *command,
1391 bool ctx_change, bool must_succeed);
1392
1393/*
1394 * Full speed devices may have a max packet size greater than 8 bytes, but the
1395 * USB core doesn't know that until it reads the first 8 bytes of the
1396 * descriptor. If the usb_device's max packet size changes after that point,
1397 * we need to issue an evaluate context command and wait on it.
1398 */
1399static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
Olivier Deprez0e641232021-09-23 10:07:05 +02001400 unsigned int ep_index, struct urb *urb, gfp_t mem_flags)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001401{
1402 struct xhci_container_ctx *out_ctx;
1403 struct xhci_input_control_ctx *ctrl_ctx;
1404 struct xhci_ep_ctx *ep_ctx;
1405 struct xhci_command *command;
1406 int max_packet_size;
1407 int hw_max_packet_size;
1408 int ret = 0;
1409
1410 out_ctx = xhci->devs[slot_id]->out_ctx;
1411 ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1412 hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1413 max_packet_size = usb_endpoint_maxp(&urb->dev->ep0.desc);
1414 if (hw_max_packet_size != max_packet_size) {
1415 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1416 "Max Packet Size for ep 0 changed.");
1417 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1418 "Max packet size in usb_device = %d",
1419 max_packet_size);
1420 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1421 "Max packet size in xHCI HW = %d",
1422 hw_max_packet_size);
1423 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1424 "Issuing evaluate context command.");
1425
1426 /* Set up the input context flags for the command */
1427 /* FIXME: This won't work if a non-default control endpoint
1428 * changes max packet sizes.
1429 */
1430
Olivier Deprez0e641232021-09-23 10:07:05 +02001431 command = xhci_alloc_command(xhci, true, mem_flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001432 if (!command)
1433 return -ENOMEM;
1434
1435 command->in_ctx = xhci->devs[slot_id]->in_ctx;
1436 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
1437 if (!ctrl_ctx) {
1438 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1439 __func__);
1440 ret = -ENOMEM;
1441 goto command_cleanup;
1442 }
1443 /* Set up the modified control endpoint 0 */
1444 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1445 xhci->devs[slot_id]->out_ctx, ep_index);
1446
1447 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
Olivier Deprez0e641232021-09-23 10:07:05 +02001448 ep_ctx->ep_info &= cpu_to_le32(~EP_STATE_MASK);/* must clear */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001449 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1450 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1451
1452 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1453 ctrl_ctx->drop_flags = 0;
1454
1455 ret = xhci_configure_endpoint(xhci, urb->dev, command,
1456 true, false);
1457
1458 /* Clean up the input context for later use by bandwidth
1459 * functions.
1460 */
1461 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1462command_cleanup:
1463 kfree(command->completion);
1464 kfree(command);
1465 }
1466 return ret;
1467}
1468
1469/*
1470 * non-error returns are a promise to giveback() the urb later
1471 * we drop ownership so next owner (or urb unlink) can get it
1472 */
1473static int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1474{
1475 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1476 unsigned long flags;
1477 int ret = 0;
1478 unsigned int slot_id, ep_index;
1479 unsigned int *ep_state;
1480 struct urb_priv *urb_priv;
1481 int num_tds;
1482
1483 if (!urb || xhci_check_args(hcd, urb->dev, urb->ep,
1484 true, true, __func__) <= 0)
1485 return -EINVAL;
1486
1487 slot_id = urb->dev->slot_id;
1488 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1489 ep_state = &xhci->devs[slot_id]->eps[ep_index].ep_state;
1490
1491 if (!HCD_HW_ACCESSIBLE(hcd)) {
1492 if (!in_interrupt())
1493 xhci_dbg(xhci, "urb submitted during PCI suspend\n");
1494 return -ESHUTDOWN;
1495 }
David Brazdil0f672f62019-12-10 10:32:29 +00001496 if (xhci->devs[slot_id]->flags & VDEV_PORT_ERROR) {
1497 xhci_dbg(xhci, "Can't queue urb, port error, link inactive\n");
1498 return -ENODEV;
1499 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001500
1501 if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1502 num_tds = urb->number_of_packets;
1503 else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
1504 urb->transfer_buffer_length > 0 &&
1505 urb->transfer_flags & URB_ZERO_PACKET &&
1506 !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
1507 num_tds = 2;
1508 else
1509 num_tds = 1;
1510
David Brazdil0f672f62019-12-10 10:32:29 +00001511 urb_priv = kzalloc(struct_size(urb_priv, td, num_tds), mem_flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001512 if (!urb_priv)
1513 return -ENOMEM;
1514
1515 urb_priv->num_tds = num_tds;
1516 urb_priv->num_tds_done = 0;
1517 urb->hcpriv = urb_priv;
1518
1519 trace_xhci_urb_enqueue(urb);
1520
1521 if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1522 /* Check to see if the max packet size for the default control
1523 * endpoint changed during FS device enumeration
1524 */
1525 if (urb->dev->speed == USB_SPEED_FULL) {
1526 ret = xhci_check_maxpacket(xhci, slot_id,
Olivier Deprez0e641232021-09-23 10:07:05 +02001527 ep_index, urb, mem_flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001528 if (ret < 0) {
1529 xhci_urb_free_priv(urb_priv);
1530 urb->hcpriv = NULL;
1531 return ret;
1532 }
1533 }
1534 }
1535
1536 spin_lock_irqsave(&xhci->lock, flags);
1537
1538 if (xhci->xhc_state & XHCI_STATE_DYING) {
1539 xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for non-responsive xHCI host.\n",
1540 urb->ep->desc.bEndpointAddress, urb);
1541 ret = -ESHUTDOWN;
1542 goto free_priv;
1543 }
1544 if (*ep_state & (EP_GETTING_STREAMS | EP_GETTING_NO_STREAMS)) {
1545 xhci_warn(xhci, "WARN: Can't enqueue URB, ep in streams transition state %x\n",
1546 *ep_state);
1547 ret = -EINVAL;
1548 goto free_priv;
1549 }
1550 if (*ep_state & EP_SOFT_CLEAR_TOGGLE) {
1551 xhci_warn(xhci, "Can't enqueue URB while manually clearing toggle\n");
1552 ret = -EINVAL;
1553 goto free_priv;
1554 }
1555
1556 switch (usb_endpoint_type(&urb->ep->desc)) {
1557
1558 case USB_ENDPOINT_XFER_CONTROL:
1559 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1560 slot_id, ep_index);
1561 break;
1562 case USB_ENDPOINT_XFER_BULK:
1563 ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1564 slot_id, ep_index);
1565 break;
1566 case USB_ENDPOINT_XFER_INT:
1567 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1568 slot_id, ep_index);
1569 break;
1570 case USB_ENDPOINT_XFER_ISOC:
1571 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1572 slot_id, ep_index);
1573 }
1574
1575 if (ret) {
1576free_priv:
1577 xhci_urb_free_priv(urb_priv);
1578 urb->hcpriv = NULL;
1579 }
1580 spin_unlock_irqrestore(&xhci->lock, flags);
1581 return ret;
1582}
1583
1584/*
1585 * Remove the URB's TD from the endpoint ring. This may cause the HC to stop
1586 * USB transfers, potentially stopping in the middle of a TRB buffer. The HC
1587 * should pick up where it left off in the TD, unless a Set Transfer Ring
1588 * Dequeue Pointer is issued.
1589 *
1590 * The TRBs that make up the buffers for the canceled URB will be "removed" from
1591 * the ring. Since the ring is a contiguous structure, they can't be physically
1592 * removed. Instead, there are two options:
1593 *
1594 * 1) If the HC is in the middle of processing the URB to be canceled, we
1595 * simply move the ring's dequeue pointer past those TRBs using the Set
1596 * Transfer Ring Dequeue Pointer command. This will be the common case,
1597 * when drivers timeout on the last submitted URB and attempt to cancel.
1598 *
1599 * 2) If the HC is in the middle of a different TD, we turn the TRBs into a
1600 * series of 1-TRB transfer no-op TDs. (No-ops shouldn't be chained.) The
1601 * HC will need to invalidate the any TRBs it has cached after the stop
1602 * endpoint command, as noted in the xHCI 0.95 errata.
1603 *
1604 * 3) The TD may have completed by the time the Stop Endpoint Command
1605 * completes, so software needs to handle that case too.
1606 *
1607 * This function should protect against the TD enqueueing code ringing the
1608 * doorbell while this code is waiting for a Stop Endpoint command to complete.
1609 * It also needs to account for multiple cancellations on happening at the same
1610 * time for the same endpoint.
1611 *
1612 * Note that this function can be called in any context, or so says
1613 * usb_hcd_unlink_urb()
1614 */
1615static int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1616{
1617 unsigned long flags;
1618 int ret, i;
1619 u32 temp;
1620 struct xhci_hcd *xhci;
1621 struct urb_priv *urb_priv;
1622 struct xhci_td *td;
1623 unsigned int ep_index;
1624 struct xhci_ring *ep_ring;
1625 struct xhci_virt_ep *ep;
1626 struct xhci_command *command;
1627 struct xhci_virt_device *vdev;
1628
1629 xhci = hcd_to_xhci(hcd);
1630 spin_lock_irqsave(&xhci->lock, flags);
1631
1632 trace_xhci_urb_dequeue(urb);
1633
1634 /* Make sure the URB hasn't completed or been unlinked already */
1635 ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1636 if (ret)
1637 goto done;
1638
1639 /* give back URB now if we can't queue it for cancel */
1640 vdev = xhci->devs[urb->dev->slot_id];
1641 urb_priv = urb->hcpriv;
1642 if (!vdev || !urb_priv)
1643 goto err_giveback;
1644
1645 ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1646 ep = &vdev->eps[ep_index];
1647 ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1648 if (!ep || !ep_ring)
1649 goto err_giveback;
1650
1651 /* If xHC is dead take it down and return ALL URBs in xhci_hc_died() */
1652 temp = readl(&xhci->op_regs->status);
1653 if (temp == ~(u32)0 || xhci->xhc_state & XHCI_STATE_DYING) {
1654 xhci_hc_died(xhci);
1655 goto done;
1656 }
1657
1658 /*
1659 * check ring is not re-allocated since URB was enqueued. If it is, then
1660 * make sure none of the ring related pointers in this URB private data
1661 * are touched, such as td_list, otherwise we overwrite freed data
1662 */
1663 if (!td_on_ring(&urb_priv->td[0], ep_ring)) {
1664 xhci_err(xhci, "Canceled URB td not found on endpoint ring");
1665 for (i = urb_priv->num_tds_done; i < urb_priv->num_tds; i++) {
1666 td = &urb_priv->td[i];
1667 if (!list_empty(&td->cancelled_td_list))
1668 list_del_init(&td->cancelled_td_list);
1669 }
1670 goto err_giveback;
1671 }
1672
1673 if (xhci->xhc_state & XHCI_STATE_HALTED) {
1674 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1675 "HC halted, freeing TD manually.");
1676 for (i = urb_priv->num_tds_done;
1677 i < urb_priv->num_tds;
1678 i++) {
1679 td = &urb_priv->td[i];
1680 if (!list_empty(&td->td_list))
1681 list_del_init(&td->td_list);
1682 if (!list_empty(&td->cancelled_td_list))
1683 list_del_init(&td->cancelled_td_list);
1684 }
1685 goto err_giveback;
1686 }
1687
1688 i = urb_priv->num_tds_done;
1689 if (i < urb_priv->num_tds)
1690 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1691 "Cancel URB %p, dev %s, ep 0x%x, "
1692 "starting at offset 0x%llx",
1693 urb, urb->dev->devpath,
1694 urb->ep->desc.bEndpointAddress,
1695 (unsigned long long) xhci_trb_virt_to_dma(
1696 urb_priv->td[i].start_seg,
1697 urb_priv->td[i].first_trb));
1698
1699 for (; i < urb_priv->num_tds; i++) {
1700 td = &urb_priv->td[i];
1701 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1702 }
1703
1704 /* Queue a stop endpoint command, but only if this is
1705 * the first cancellation to be handled.
1706 */
1707 if (!(ep->ep_state & EP_STOP_CMD_PENDING)) {
1708 command = xhci_alloc_command(xhci, false, GFP_ATOMIC);
1709 if (!command) {
1710 ret = -ENOMEM;
1711 goto done;
1712 }
1713 ep->ep_state |= EP_STOP_CMD_PENDING;
1714 ep->stop_cmd_timer.expires = jiffies +
1715 XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1716 add_timer(&ep->stop_cmd_timer);
1717 xhci_queue_stop_endpoint(xhci, command, urb->dev->slot_id,
1718 ep_index, 0);
1719 xhci_ring_cmd_db(xhci);
1720 }
1721done:
1722 spin_unlock_irqrestore(&xhci->lock, flags);
1723 return ret;
1724
1725err_giveback:
1726 if (urb_priv)
1727 xhci_urb_free_priv(urb_priv);
1728 usb_hcd_unlink_urb_from_ep(hcd, urb);
1729 spin_unlock_irqrestore(&xhci->lock, flags);
1730 usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1731 return ret;
1732}
1733
1734/* Drop an endpoint from a new bandwidth configuration for this device.
1735 * Only one call to this function is allowed per endpoint before
1736 * check_bandwidth() or reset_bandwidth() must be called.
1737 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1738 * add the endpoint to the schedule with possibly new parameters denoted by a
1739 * different endpoint descriptor in usb_host_endpoint.
1740 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1741 * not allowed.
1742 *
1743 * The USB core will not allow URBs to be queued to an endpoint that is being
1744 * disabled, so there's no need for mutual exclusion to protect
1745 * the xhci->devs[slot_id] structure.
1746 */
1747static int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1748 struct usb_host_endpoint *ep)
1749{
1750 struct xhci_hcd *xhci;
1751 struct xhci_container_ctx *in_ctx, *out_ctx;
1752 struct xhci_input_control_ctx *ctrl_ctx;
1753 unsigned int ep_index;
1754 struct xhci_ep_ctx *ep_ctx;
1755 u32 drop_flag;
1756 u32 new_add_flags, new_drop_flags;
1757 int ret;
1758
1759 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1760 if (ret <= 0)
1761 return ret;
1762 xhci = hcd_to_xhci(hcd);
1763 if (xhci->xhc_state & XHCI_STATE_DYING)
1764 return -ENODEV;
1765
1766 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1767 drop_flag = xhci_get_endpoint_flag(&ep->desc);
1768 if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1769 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1770 __func__, drop_flag);
1771 return 0;
1772 }
1773
1774 in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1775 out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1776 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1777 if (!ctrl_ctx) {
1778 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1779 __func__);
1780 return 0;
1781 }
1782
1783 ep_index = xhci_get_endpoint_index(&ep->desc);
1784 ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1785 /* If the HC already knows the endpoint is disabled,
1786 * or the HCD has noted it is disabled, ignore this request
1787 */
1788 if ((GET_EP_CTX_STATE(ep_ctx) == EP_STATE_DISABLED) ||
1789 le32_to_cpu(ctrl_ctx->drop_flags) &
1790 xhci_get_endpoint_flag(&ep->desc)) {
1791 /* Do not warn when called after a usb_device_reset */
1792 if (xhci->devs[udev->slot_id]->eps[ep_index].ring != NULL)
1793 xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1794 __func__, ep);
1795 return 0;
1796 }
1797
1798 ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1799 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1800
1801 ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1802 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1803
1804 xhci_debugfs_remove_endpoint(xhci, xhci->devs[udev->slot_id], ep_index);
1805
1806 xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1807
1808 if (xhci->quirks & XHCI_MTK_HOST)
1809 xhci_mtk_drop_ep_quirk(hcd, udev, ep);
1810
1811 xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1812 (unsigned int) ep->desc.bEndpointAddress,
1813 udev->slot_id,
1814 (unsigned int) new_drop_flags,
1815 (unsigned int) new_add_flags);
1816 return 0;
1817}
1818
1819/* Add an endpoint to a new possible bandwidth configuration for this device.
1820 * Only one call to this function is allowed per endpoint before
1821 * check_bandwidth() or reset_bandwidth() must be called.
1822 * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1823 * add the endpoint to the schedule with possibly new parameters denoted by a
1824 * different endpoint descriptor in usb_host_endpoint.
1825 * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1826 * not allowed.
1827 *
1828 * The USB core will not allow URBs to be queued to an endpoint until the
1829 * configuration or alt setting is installed in the device, so there's no need
1830 * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1831 */
1832static int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1833 struct usb_host_endpoint *ep)
1834{
1835 struct xhci_hcd *xhci;
1836 struct xhci_container_ctx *in_ctx;
1837 unsigned int ep_index;
1838 struct xhci_input_control_ctx *ctrl_ctx;
David Brazdil0f672f62019-12-10 10:32:29 +00001839 struct xhci_ep_ctx *ep_ctx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001840 u32 added_ctxs;
1841 u32 new_add_flags, new_drop_flags;
1842 struct xhci_virt_device *virt_dev;
1843 int ret = 0;
1844
1845 ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1846 if (ret <= 0) {
1847 /* So we won't queue a reset ep command for a root hub */
1848 ep->hcpriv = NULL;
1849 return ret;
1850 }
1851 xhci = hcd_to_xhci(hcd);
1852 if (xhci->xhc_state & XHCI_STATE_DYING)
1853 return -ENODEV;
1854
1855 added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1856 if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1857 /* FIXME when we have to issue an evaluate endpoint command to
1858 * deal with ep0 max packet size changing once we get the
1859 * descriptors
1860 */
1861 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1862 __func__, added_ctxs);
1863 return 0;
1864 }
1865
1866 virt_dev = xhci->devs[udev->slot_id];
1867 in_ctx = virt_dev->in_ctx;
1868 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1869 if (!ctrl_ctx) {
1870 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1871 __func__);
1872 return 0;
1873 }
1874
1875 ep_index = xhci_get_endpoint_index(&ep->desc);
1876 /* If this endpoint is already in use, and the upper layers are trying
1877 * to add it again without dropping it, reject the addition.
1878 */
1879 if (virt_dev->eps[ep_index].ring &&
1880 !(le32_to_cpu(ctrl_ctx->drop_flags) & added_ctxs)) {
1881 xhci_warn(xhci, "Trying to add endpoint 0x%x "
1882 "without dropping it.\n",
1883 (unsigned int) ep->desc.bEndpointAddress);
1884 return -EINVAL;
1885 }
1886
1887 /* If the HCD has already noted the endpoint is enabled,
1888 * ignore this request.
1889 */
1890 if (le32_to_cpu(ctrl_ctx->add_flags) & added_ctxs) {
1891 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1892 __func__, ep);
1893 return 0;
1894 }
1895
1896 /*
1897 * Configuration and alternate setting changes must be done in
1898 * process context, not interrupt context (or so documenation
1899 * for usb_set_interface() and usb_set_configuration() claim).
1900 */
1901 if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1902 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1903 __func__, ep->desc.bEndpointAddress);
1904 return -ENOMEM;
1905 }
1906
1907 if (xhci->quirks & XHCI_MTK_HOST) {
1908 ret = xhci_mtk_add_ep_quirk(hcd, udev, ep);
1909 if (ret < 0) {
1910 xhci_ring_free(xhci, virt_dev->eps[ep_index].new_ring);
1911 virt_dev->eps[ep_index].new_ring = NULL;
1912 return ret;
1913 }
1914 }
1915
1916 ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1917 new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1918
1919 /* If xhci_endpoint_disable() was called for this endpoint, but the
1920 * xHC hasn't been notified yet through the check_bandwidth() call,
1921 * this re-adds a new state for the endpoint from the new endpoint
1922 * descriptors. We must drop and re-add this endpoint, so we leave the
1923 * drop flags alone.
1924 */
1925 new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1926
1927 /* Store the usb_device pointer for later use */
1928 ep->hcpriv = udev;
1929
David Brazdil0f672f62019-12-10 10:32:29 +00001930 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, ep_index);
1931 trace_xhci_add_endpoint(ep_ctx);
1932
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001933 xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x\n",
1934 (unsigned int) ep->desc.bEndpointAddress,
1935 udev->slot_id,
1936 (unsigned int) new_drop_flags,
1937 (unsigned int) new_add_flags);
1938 return 0;
1939}
1940
1941static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1942{
1943 struct xhci_input_control_ctx *ctrl_ctx;
1944 struct xhci_ep_ctx *ep_ctx;
1945 struct xhci_slot_ctx *slot_ctx;
1946 int i;
1947
1948 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
1949 if (!ctrl_ctx) {
1950 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
1951 __func__);
1952 return;
1953 }
1954
1955 /* When a device's add flag and drop flag are zero, any subsequent
1956 * configure endpoint command will leave that endpoint's state
1957 * untouched. Make sure we don't leave any old state in the input
1958 * endpoint contexts.
1959 */
1960 ctrl_ctx->drop_flags = 0;
1961 ctrl_ctx->add_flags = 0;
1962 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1963 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1964 /* Endpoint 0 is always valid */
1965 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
1966 for (i = 1; i < 31; i++) {
1967 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1968 ep_ctx->ep_info = 0;
1969 ep_ctx->ep_info2 = 0;
1970 ep_ctx->deq = 0;
1971 ep_ctx->tx_info = 0;
1972 }
1973}
1974
1975static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1976 struct usb_device *udev, u32 *cmd_status)
1977{
1978 int ret;
1979
1980 switch (*cmd_status) {
1981 case COMP_COMMAND_ABORTED:
1982 case COMP_COMMAND_RING_STOPPED:
1983 xhci_warn(xhci, "Timeout while waiting for configure endpoint command\n");
1984 ret = -ETIME;
1985 break;
1986 case COMP_RESOURCE_ERROR:
1987 dev_warn(&udev->dev,
1988 "Not enough host controller resources for new device state.\n");
1989 ret = -ENOMEM;
1990 /* FIXME: can we allocate more resources for the HC? */
1991 break;
1992 case COMP_BANDWIDTH_ERROR:
1993 case COMP_SECONDARY_BANDWIDTH_ERROR:
1994 dev_warn(&udev->dev,
1995 "Not enough bandwidth for new device state.\n");
1996 ret = -ENOSPC;
1997 /* FIXME: can we go back to the old state? */
1998 break;
1999 case COMP_TRB_ERROR:
2000 /* the HCD set up something wrong */
2001 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
2002 "add flag = 1, "
2003 "and endpoint is not disabled.\n");
2004 ret = -EINVAL;
2005 break;
2006 case COMP_INCOMPATIBLE_DEVICE_ERROR:
2007 dev_warn(&udev->dev,
2008 "ERROR: Incompatible device for endpoint configure command.\n");
2009 ret = -ENODEV;
2010 break;
2011 case COMP_SUCCESS:
2012 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2013 "Successful Endpoint Configure command");
2014 ret = 0;
2015 break;
2016 default:
2017 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2018 *cmd_status);
2019 ret = -EINVAL;
2020 break;
2021 }
2022 return ret;
2023}
2024
2025static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
2026 struct usb_device *udev, u32 *cmd_status)
2027{
2028 int ret;
2029
2030 switch (*cmd_status) {
2031 case COMP_COMMAND_ABORTED:
2032 case COMP_COMMAND_RING_STOPPED:
2033 xhci_warn(xhci, "Timeout while waiting for evaluate context command\n");
2034 ret = -ETIME;
2035 break;
2036 case COMP_PARAMETER_ERROR:
2037 dev_warn(&udev->dev,
2038 "WARN: xHCI driver setup invalid evaluate context command.\n");
2039 ret = -EINVAL;
2040 break;
2041 case COMP_SLOT_NOT_ENABLED_ERROR:
2042 dev_warn(&udev->dev,
2043 "WARN: slot not enabled for evaluate context command.\n");
2044 ret = -EINVAL;
2045 break;
2046 case COMP_CONTEXT_STATE_ERROR:
2047 dev_warn(&udev->dev,
2048 "WARN: invalid context state for evaluate context command.\n");
2049 ret = -EINVAL;
2050 break;
2051 case COMP_INCOMPATIBLE_DEVICE_ERROR:
2052 dev_warn(&udev->dev,
2053 "ERROR: Incompatible device for evaluate context command.\n");
2054 ret = -ENODEV;
2055 break;
2056 case COMP_MAX_EXIT_LATENCY_TOO_LARGE_ERROR:
2057 /* Max Exit Latency too large error */
2058 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
2059 ret = -EINVAL;
2060 break;
2061 case COMP_SUCCESS:
2062 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2063 "Successful evaluate context command");
2064 ret = 0;
2065 break;
2066 default:
2067 xhci_err(xhci, "ERROR: unexpected command completion code 0x%x.\n",
2068 *cmd_status);
2069 ret = -EINVAL;
2070 break;
2071 }
2072 return ret;
2073}
2074
2075static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
2076 struct xhci_input_control_ctx *ctrl_ctx)
2077{
2078 u32 valid_add_flags;
2079 u32 valid_drop_flags;
2080
2081 /* Ignore the slot flag (bit 0), and the default control endpoint flag
2082 * (bit 1). The default control endpoint is added during the Address
2083 * Device command and is never removed until the slot is disabled.
2084 */
2085 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2086 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2087
2088 /* Use hweight32 to count the number of ones in the add flags, or
2089 * number of endpoints added. Don't count endpoints that are changed
2090 * (both added and dropped).
2091 */
2092 return hweight32(valid_add_flags) -
2093 hweight32(valid_add_flags & valid_drop_flags);
2094}
2095
2096static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
2097 struct xhci_input_control_ctx *ctrl_ctx)
2098{
2099 u32 valid_add_flags;
2100 u32 valid_drop_flags;
2101
2102 valid_add_flags = le32_to_cpu(ctrl_ctx->add_flags) >> 2;
2103 valid_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags) >> 2;
2104
2105 return hweight32(valid_drop_flags) -
2106 hweight32(valid_add_flags & valid_drop_flags);
2107}
2108
2109/*
2110 * We need to reserve the new number of endpoints before the configure endpoint
2111 * command completes. We can't subtract the dropped endpoints from the number
2112 * of active endpoints until the command completes because we can oversubscribe
2113 * the host in this case:
2114 *
2115 * - the first configure endpoint command drops more endpoints than it adds
2116 * - a second configure endpoint command that adds more endpoints is queued
2117 * - the first configure endpoint command fails, so the config is unchanged
2118 * - the second command may succeed, even though there isn't enough resources
2119 *
2120 * Must be called with xhci->lock held.
2121 */
2122static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
2123 struct xhci_input_control_ctx *ctrl_ctx)
2124{
2125 u32 added_eps;
2126
2127 added_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2128 if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
2129 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2130 "Not enough ep ctxs: "
2131 "%u active, need to add %u, limit is %u.",
2132 xhci->num_active_eps, added_eps,
2133 xhci->limit_active_eps);
2134 return -ENOMEM;
2135 }
2136 xhci->num_active_eps += added_eps;
2137 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2138 "Adding %u ep ctxs, %u now active.", added_eps,
2139 xhci->num_active_eps);
2140 return 0;
2141}
2142
2143/*
2144 * The configure endpoint was failed by the xHC for some other reason, so we
2145 * need to revert the resources that failed configuration would have used.
2146 *
2147 * Must be called with xhci->lock held.
2148 */
2149static void xhci_free_host_resources(struct xhci_hcd *xhci,
2150 struct xhci_input_control_ctx *ctrl_ctx)
2151{
2152 u32 num_failed_eps;
2153
2154 num_failed_eps = xhci_count_num_new_endpoints(xhci, ctrl_ctx);
2155 xhci->num_active_eps -= num_failed_eps;
2156 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2157 "Removing %u failed ep ctxs, %u now active.",
2158 num_failed_eps,
2159 xhci->num_active_eps);
2160}
2161
2162/*
2163 * Now that the command has completed, clean up the active endpoint count by
2164 * subtracting out the endpoints that were dropped (but not changed).
2165 *
2166 * Must be called with xhci->lock held.
2167 */
2168static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
2169 struct xhci_input_control_ctx *ctrl_ctx)
2170{
2171 u32 num_dropped_eps;
2172
2173 num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, ctrl_ctx);
2174 xhci->num_active_eps -= num_dropped_eps;
2175 if (num_dropped_eps)
2176 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2177 "Removing %u dropped ep ctxs, %u now active.",
2178 num_dropped_eps,
2179 xhci->num_active_eps);
2180}
2181
2182static unsigned int xhci_get_block_size(struct usb_device *udev)
2183{
2184 switch (udev->speed) {
2185 case USB_SPEED_LOW:
2186 case USB_SPEED_FULL:
2187 return FS_BLOCK;
2188 case USB_SPEED_HIGH:
2189 return HS_BLOCK;
2190 case USB_SPEED_SUPER:
2191 case USB_SPEED_SUPER_PLUS:
2192 return SS_BLOCK;
2193 case USB_SPEED_UNKNOWN:
2194 case USB_SPEED_WIRELESS:
2195 default:
2196 /* Should never happen */
2197 return 1;
2198 }
2199}
2200
2201static unsigned int
2202xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
2203{
2204 if (interval_bw->overhead[LS_OVERHEAD_TYPE])
2205 return LS_OVERHEAD;
2206 if (interval_bw->overhead[FS_OVERHEAD_TYPE])
2207 return FS_OVERHEAD;
2208 return HS_OVERHEAD;
2209}
2210
2211/* If we are changing a LS/FS device under a HS hub,
2212 * make sure (if we are activating a new TT) that the HS bus has enough
2213 * bandwidth for this new TT.
2214 */
2215static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
2216 struct xhci_virt_device *virt_dev,
2217 int old_active_eps)
2218{
2219 struct xhci_interval_bw_table *bw_table;
2220 struct xhci_tt_bw_info *tt_info;
2221
2222 /* Find the bandwidth table for the root port this TT is attached to. */
2223 bw_table = &xhci->rh_bw[virt_dev->real_port - 1].bw_table;
2224 tt_info = virt_dev->tt_info;
2225 /* If this TT already had active endpoints, the bandwidth for this TT
2226 * has already been added. Removing all periodic endpoints (and thus
2227 * making the TT enactive) will only decrease the bandwidth used.
2228 */
2229 if (old_active_eps)
2230 return 0;
2231 if (old_active_eps == 0 && tt_info->active_eps != 0) {
2232 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
2233 return -ENOMEM;
2234 return 0;
2235 }
2236 /* Not sure why we would have no new active endpoints...
2237 *
2238 * Maybe because of an Evaluate Context change for a hub update or a
2239 * control endpoint 0 max packet size change?
2240 * FIXME: skip the bandwidth calculation in that case.
2241 */
2242 return 0;
2243}
2244
2245static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2246 struct xhci_virt_device *virt_dev)
2247{
2248 unsigned int bw_reserved;
2249
2250 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2251 if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2252 return -ENOMEM;
2253
2254 bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2255 if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2256 return -ENOMEM;
2257
2258 return 0;
2259}
2260
2261/*
2262 * This algorithm is a very conservative estimate of the worst-case scheduling
2263 * scenario for any one interval. The hardware dynamically schedules the
2264 * packets, so we can't tell which microframe could be the limiting factor in
2265 * the bandwidth scheduling. This only takes into account periodic endpoints.
2266 *
2267 * Obviously, we can't solve an NP complete problem to find the minimum worst
2268 * case scenario. Instead, we come up with an estimate that is no less than
2269 * the worst case bandwidth used for any one microframe, but may be an
2270 * over-estimate.
2271 *
2272 * We walk the requirements for each endpoint by interval, starting with the
2273 * smallest interval, and place packets in the schedule where there is only one
2274 * possible way to schedule packets for that interval. In order to simplify
2275 * this algorithm, we record the largest max packet size for each interval, and
2276 * assume all packets will be that size.
2277 *
2278 * For interval 0, we obviously must schedule all packets for each interval.
2279 * The bandwidth for interval 0 is just the amount of data to be transmitted
2280 * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2281 * the number of packets).
2282 *
2283 * For interval 1, we have two possible microframes to schedule those packets
2284 * in. For this algorithm, if we can schedule the same number of packets for
2285 * each possible scheduling opportunity (each microframe), we will do so. The
2286 * remaining number of packets will be saved to be transmitted in the gaps in
2287 * the next interval's scheduling sequence.
2288 *
2289 * As we move those remaining packets to be scheduled with interval 2 packets,
2290 * we have to double the number of remaining packets to transmit. This is
2291 * because the intervals are actually powers of 2, and we would be transmitting
2292 * the previous interval's packets twice in this interval. We also have to be
2293 * sure that when we look at the largest max packet size for this interval, we
2294 * also look at the largest max packet size for the remaining packets and take
2295 * the greater of the two.
2296 *
2297 * The algorithm continues to evenly distribute packets in each scheduling
2298 * opportunity, and push the remaining packets out, until we get to the last
2299 * interval. Then those packets and their associated overhead are just added
2300 * to the bandwidth used.
2301 */
2302static int xhci_check_bw_table(struct xhci_hcd *xhci,
2303 struct xhci_virt_device *virt_dev,
2304 int old_active_eps)
2305{
2306 unsigned int bw_reserved;
2307 unsigned int max_bandwidth;
2308 unsigned int bw_used;
2309 unsigned int block_size;
2310 struct xhci_interval_bw_table *bw_table;
2311 unsigned int packet_size = 0;
2312 unsigned int overhead = 0;
2313 unsigned int packets_transmitted = 0;
2314 unsigned int packets_remaining = 0;
2315 unsigned int i;
2316
2317 if (virt_dev->udev->speed >= USB_SPEED_SUPER)
2318 return xhci_check_ss_bw(xhci, virt_dev);
2319
2320 if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2321 max_bandwidth = HS_BW_LIMIT;
2322 /* Convert percent of bus BW reserved to blocks reserved */
2323 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2324 } else {
2325 max_bandwidth = FS_BW_LIMIT;
2326 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2327 }
2328
2329 bw_table = virt_dev->bw_table;
2330 /* We need to translate the max packet size and max ESIT payloads into
2331 * the units the hardware uses.
2332 */
2333 block_size = xhci_get_block_size(virt_dev->udev);
2334
2335 /* If we are manipulating a LS/FS device under a HS hub, double check
2336 * that the HS bus has enough bandwidth if we are activing a new TT.
2337 */
2338 if (virt_dev->tt_info) {
2339 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2340 "Recalculating BW for rootport %u",
2341 virt_dev->real_port);
2342 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2343 xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2344 "newly activated TT.\n");
2345 return -ENOMEM;
2346 }
2347 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2348 "Recalculating BW for TT slot %u port %u",
2349 virt_dev->tt_info->slot_id,
2350 virt_dev->tt_info->ttport);
2351 } else {
2352 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2353 "Recalculating BW for rootport %u",
2354 virt_dev->real_port);
2355 }
2356
2357 /* Add in how much bandwidth will be used for interval zero, or the
2358 * rounded max ESIT payload + number of packets * largest overhead.
2359 */
2360 bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2361 bw_table->interval_bw[0].num_packets *
2362 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2363
2364 for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2365 unsigned int bw_added;
2366 unsigned int largest_mps;
2367 unsigned int interval_overhead;
2368
2369 /*
2370 * How many packets could we transmit in this interval?
2371 * If packets didn't fit in the previous interval, we will need
2372 * to transmit that many packets twice within this interval.
2373 */
2374 packets_remaining = 2 * packets_remaining +
2375 bw_table->interval_bw[i].num_packets;
2376
2377 /* Find the largest max packet size of this or the previous
2378 * interval.
2379 */
2380 if (list_empty(&bw_table->interval_bw[i].endpoints))
2381 largest_mps = 0;
2382 else {
2383 struct xhci_virt_ep *virt_ep;
2384 struct list_head *ep_entry;
2385
2386 ep_entry = bw_table->interval_bw[i].endpoints.next;
2387 virt_ep = list_entry(ep_entry,
2388 struct xhci_virt_ep, bw_endpoint_list);
2389 /* Convert to blocks, rounding up */
2390 largest_mps = DIV_ROUND_UP(
2391 virt_ep->bw_info.max_packet_size,
2392 block_size);
2393 }
2394 if (largest_mps > packet_size)
2395 packet_size = largest_mps;
2396
2397 /* Use the larger overhead of this or the previous interval. */
2398 interval_overhead = xhci_get_largest_overhead(
2399 &bw_table->interval_bw[i]);
2400 if (interval_overhead > overhead)
2401 overhead = interval_overhead;
2402
2403 /* How many packets can we evenly distribute across
2404 * (1 << (i + 1)) possible scheduling opportunities?
2405 */
2406 packets_transmitted = packets_remaining >> (i + 1);
2407
2408 /* Add in the bandwidth used for those scheduled packets */
2409 bw_added = packets_transmitted * (overhead + packet_size);
2410
2411 /* How many packets do we have remaining to transmit? */
2412 packets_remaining = packets_remaining % (1 << (i + 1));
2413
2414 /* What largest max packet size should those packets have? */
2415 /* If we've transmitted all packets, don't carry over the
2416 * largest packet size.
2417 */
2418 if (packets_remaining == 0) {
2419 packet_size = 0;
2420 overhead = 0;
2421 } else if (packets_transmitted > 0) {
2422 /* Otherwise if we do have remaining packets, and we've
2423 * scheduled some packets in this interval, take the
2424 * largest max packet size from endpoints with this
2425 * interval.
2426 */
2427 packet_size = largest_mps;
2428 overhead = interval_overhead;
2429 }
2430 /* Otherwise carry over packet_size and overhead from the last
2431 * time we had a remainder.
2432 */
2433 bw_used += bw_added;
2434 if (bw_used > max_bandwidth) {
2435 xhci_warn(xhci, "Not enough bandwidth. "
2436 "Proposed: %u, Max: %u\n",
2437 bw_used, max_bandwidth);
2438 return -ENOMEM;
2439 }
2440 }
2441 /*
2442 * Ok, we know we have some packets left over after even-handedly
2443 * scheduling interval 15. We don't know which microframes they will
2444 * fit into, so we over-schedule and say they will be scheduled every
2445 * microframe.
2446 */
2447 if (packets_remaining > 0)
2448 bw_used += overhead + packet_size;
2449
2450 if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2451 unsigned int port_index = virt_dev->real_port - 1;
2452
2453 /* OK, we're manipulating a HS device attached to a
2454 * root port bandwidth domain. Include the number of active TTs
2455 * in the bandwidth used.
2456 */
2457 bw_used += TT_HS_OVERHEAD *
2458 xhci->rh_bw[port_index].num_active_tts;
2459 }
2460
2461 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
2462 "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2463 "Available: %u " "percent",
2464 bw_used, max_bandwidth, bw_reserved,
2465 (max_bandwidth - bw_used - bw_reserved) * 100 /
2466 max_bandwidth);
2467
2468 bw_used += bw_reserved;
2469 if (bw_used > max_bandwidth) {
2470 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2471 bw_used, max_bandwidth);
2472 return -ENOMEM;
2473 }
2474
2475 bw_table->bw_used = bw_used;
2476 return 0;
2477}
2478
2479static bool xhci_is_async_ep(unsigned int ep_type)
2480{
2481 return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2482 ep_type != ISOC_IN_EP &&
2483 ep_type != INT_IN_EP);
2484}
2485
2486static bool xhci_is_sync_in_ep(unsigned int ep_type)
2487{
2488 return (ep_type == ISOC_IN_EP || ep_type == INT_IN_EP);
2489}
2490
2491static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2492{
2493 unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2494
2495 if (ep_bw->ep_interval == 0)
2496 return SS_OVERHEAD_BURST +
2497 (ep_bw->mult * ep_bw->num_packets *
2498 (SS_OVERHEAD + mps));
2499 return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2500 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2501 1 << ep_bw->ep_interval);
2502
2503}
2504
2505static void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2506 struct xhci_bw_info *ep_bw,
2507 struct xhci_interval_bw_table *bw_table,
2508 struct usb_device *udev,
2509 struct xhci_virt_ep *virt_ep,
2510 struct xhci_tt_bw_info *tt_info)
2511{
2512 struct xhci_interval_bw *interval_bw;
2513 int normalized_interval;
2514
2515 if (xhci_is_async_ep(ep_bw->type))
2516 return;
2517
2518 if (udev->speed >= USB_SPEED_SUPER) {
2519 if (xhci_is_sync_in_ep(ep_bw->type))
2520 xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2521 xhci_get_ss_bw_consumed(ep_bw);
2522 else
2523 xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2524 xhci_get_ss_bw_consumed(ep_bw);
2525 return;
2526 }
2527
2528 /* SuperSpeed endpoints never get added to intervals in the table, so
2529 * this check is only valid for HS/FS/LS devices.
2530 */
2531 if (list_empty(&virt_ep->bw_endpoint_list))
2532 return;
2533 /* For LS/FS devices, we need to translate the interval expressed in
2534 * microframes to frames.
2535 */
2536 if (udev->speed == USB_SPEED_HIGH)
2537 normalized_interval = ep_bw->ep_interval;
2538 else
2539 normalized_interval = ep_bw->ep_interval - 3;
2540
2541 if (normalized_interval == 0)
2542 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2543 interval_bw = &bw_table->interval_bw[normalized_interval];
2544 interval_bw->num_packets -= ep_bw->num_packets;
2545 switch (udev->speed) {
2546 case USB_SPEED_LOW:
2547 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2548 break;
2549 case USB_SPEED_FULL:
2550 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2551 break;
2552 case USB_SPEED_HIGH:
2553 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2554 break;
2555 case USB_SPEED_SUPER:
2556 case USB_SPEED_SUPER_PLUS:
2557 case USB_SPEED_UNKNOWN:
2558 case USB_SPEED_WIRELESS:
2559 /* Should never happen because only LS/FS/HS endpoints will get
2560 * added to the endpoint list.
2561 */
2562 return;
2563 }
2564 if (tt_info)
2565 tt_info->active_eps -= 1;
2566 list_del_init(&virt_ep->bw_endpoint_list);
2567}
2568
2569static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2570 struct xhci_bw_info *ep_bw,
2571 struct xhci_interval_bw_table *bw_table,
2572 struct usb_device *udev,
2573 struct xhci_virt_ep *virt_ep,
2574 struct xhci_tt_bw_info *tt_info)
2575{
2576 struct xhci_interval_bw *interval_bw;
2577 struct xhci_virt_ep *smaller_ep;
2578 int normalized_interval;
2579
2580 if (xhci_is_async_ep(ep_bw->type))
2581 return;
2582
2583 if (udev->speed == USB_SPEED_SUPER) {
2584 if (xhci_is_sync_in_ep(ep_bw->type))
2585 xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2586 xhci_get_ss_bw_consumed(ep_bw);
2587 else
2588 xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2589 xhci_get_ss_bw_consumed(ep_bw);
2590 return;
2591 }
2592
2593 /* For LS/FS devices, we need to translate the interval expressed in
2594 * microframes to frames.
2595 */
2596 if (udev->speed == USB_SPEED_HIGH)
2597 normalized_interval = ep_bw->ep_interval;
2598 else
2599 normalized_interval = ep_bw->ep_interval - 3;
2600
2601 if (normalized_interval == 0)
2602 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2603 interval_bw = &bw_table->interval_bw[normalized_interval];
2604 interval_bw->num_packets += ep_bw->num_packets;
2605 switch (udev->speed) {
2606 case USB_SPEED_LOW:
2607 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2608 break;
2609 case USB_SPEED_FULL:
2610 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2611 break;
2612 case USB_SPEED_HIGH:
2613 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2614 break;
2615 case USB_SPEED_SUPER:
2616 case USB_SPEED_SUPER_PLUS:
2617 case USB_SPEED_UNKNOWN:
2618 case USB_SPEED_WIRELESS:
2619 /* Should never happen because only LS/FS/HS endpoints will get
2620 * added to the endpoint list.
2621 */
2622 return;
2623 }
2624
2625 if (tt_info)
2626 tt_info->active_eps += 1;
2627 /* Insert the endpoint into the list, largest max packet size first. */
2628 list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2629 bw_endpoint_list) {
2630 if (ep_bw->max_packet_size >=
2631 smaller_ep->bw_info.max_packet_size) {
2632 /* Add the new ep before the smaller endpoint */
2633 list_add_tail(&virt_ep->bw_endpoint_list,
2634 &smaller_ep->bw_endpoint_list);
2635 return;
2636 }
2637 }
2638 /* Add the new endpoint at the end of the list. */
2639 list_add_tail(&virt_ep->bw_endpoint_list,
2640 &interval_bw->endpoints);
2641}
2642
2643void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2644 struct xhci_virt_device *virt_dev,
2645 int old_active_eps)
2646{
2647 struct xhci_root_port_bw_info *rh_bw_info;
2648 if (!virt_dev->tt_info)
2649 return;
2650
2651 rh_bw_info = &xhci->rh_bw[virt_dev->real_port - 1];
2652 if (old_active_eps == 0 &&
2653 virt_dev->tt_info->active_eps != 0) {
2654 rh_bw_info->num_active_tts += 1;
2655 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2656 } else if (old_active_eps != 0 &&
2657 virt_dev->tt_info->active_eps == 0) {
2658 rh_bw_info->num_active_tts -= 1;
2659 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2660 }
2661}
2662
2663static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2664 struct xhci_virt_device *virt_dev,
2665 struct xhci_container_ctx *in_ctx)
2666{
2667 struct xhci_bw_info ep_bw_info[31];
2668 int i;
2669 struct xhci_input_control_ctx *ctrl_ctx;
2670 int old_active_eps = 0;
2671
2672 if (virt_dev->tt_info)
2673 old_active_eps = virt_dev->tt_info->active_eps;
2674
2675 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
2676 if (!ctrl_ctx) {
2677 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2678 __func__);
2679 return -ENOMEM;
2680 }
2681
2682 for (i = 0; i < 31; i++) {
2683 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2684 continue;
2685
2686 /* Make a copy of the BW info in case we need to revert this */
2687 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2688 sizeof(ep_bw_info[i]));
2689 /* Drop the endpoint from the interval table if the endpoint is
2690 * being dropped or changed.
2691 */
2692 if (EP_IS_DROPPED(ctrl_ctx, i))
2693 xhci_drop_ep_from_interval_table(xhci,
2694 &virt_dev->eps[i].bw_info,
2695 virt_dev->bw_table,
2696 virt_dev->udev,
2697 &virt_dev->eps[i],
2698 virt_dev->tt_info);
2699 }
2700 /* Overwrite the information stored in the endpoints' bw_info */
2701 xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2702 for (i = 0; i < 31; i++) {
2703 /* Add any changed or added endpoints to the interval table */
2704 if (EP_IS_ADDED(ctrl_ctx, i))
2705 xhci_add_ep_to_interval_table(xhci,
2706 &virt_dev->eps[i].bw_info,
2707 virt_dev->bw_table,
2708 virt_dev->udev,
2709 &virt_dev->eps[i],
2710 virt_dev->tt_info);
2711 }
2712
2713 if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2714 /* Ok, this fits in the bandwidth we have.
2715 * Update the number of active TTs.
2716 */
2717 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2718 return 0;
2719 }
2720
2721 /* We don't have enough bandwidth for this, revert the stored info. */
2722 for (i = 0; i < 31; i++) {
2723 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2724 continue;
2725
2726 /* Drop the new copies of any added or changed endpoints from
2727 * the interval table.
2728 */
2729 if (EP_IS_ADDED(ctrl_ctx, i)) {
2730 xhci_drop_ep_from_interval_table(xhci,
2731 &virt_dev->eps[i].bw_info,
2732 virt_dev->bw_table,
2733 virt_dev->udev,
2734 &virt_dev->eps[i],
2735 virt_dev->tt_info);
2736 }
2737 /* Revert the endpoint back to its old information */
2738 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2739 sizeof(ep_bw_info[i]));
2740 /* Add any changed or dropped endpoints back into the table */
2741 if (EP_IS_DROPPED(ctrl_ctx, i))
2742 xhci_add_ep_to_interval_table(xhci,
2743 &virt_dev->eps[i].bw_info,
2744 virt_dev->bw_table,
2745 virt_dev->udev,
2746 &virt_dev->eps[i],
2747 virt_dev->tt_info);
2748 }
2749 return -ENOMEM;
2750}
2751
2752
2753/* Issue a configure endpoint command or evaluate context command
2754 * and wait for it to finish.
2755 */
2756static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2757 struct usb_device *udev,
2758 struct xhci_command *command,
2759 bool ctx_change, bool must_succeed)
2760{
2761 int ret;
2762 unsigned long flags;
2763 struct xhci_input_control_ctx *ctrl_ctx;
2764 struct xhci_virt_device *virt_dev;
2765 struct xhci_slot_ctx *slot_ctx;
2766
2767 if (!command)
2768 return -EINVAL;
2769
2770 spin_lock_irqsave(&xhci->lock, flags);
2771
2772 if (xhci->xhc_state & XHCI_STATE_DYING) {
2773 spin_unlock_irqrestore(&xhci->lock, flags);
2774 return -ESHUTDOWN;
2775 }
2776
2777 virt_dev = xhci->devs[udev->slot_id];
2778
2779 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2780 if (!ctrl_ctx) {
2781 spin_unlock_irqrestore(&xhci->lock, flags);
2782 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2783 __func__);
2784 return -ENOMEM;
2785 }
2786
2787 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2788 xhci_reserve_host_resources(xhci, ctrl_ctx)) {
2789 spin_unlock_irqrestore(&xhci->lock, flags);
2790 xhci_warn(xhci, "Not enough host resources, "
2791 "active endpoint contexts = %u\n",
2792 xhci->num_active_eps);
2793 return -ENOMEM;
2794 }
2795 if ((xhci->quirks & XHCI_SW_BW_CHECKING) &&
2796 xhci_reserve_bandwidth(xhci, virt_dev, command->in_ctx)) {
2797 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2798 xhci_free_host_resources(xhci, ctrl_ctx);
2799 spin_unlock_irqrestore(&xhci->lock, flags);
2800 xhci_warn(xhci, "Not enough bandwidth\n");
2801 return -ENOMEM;
2802 }
2803
2804 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
David Brazdil0f672f62019-12-10 10:32:29 +00002805
2806 trace_xhci_configure_endpoint_ctrl_ctx(ctrl_ctx);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002807 trace_xhci_configure_endpoint(slot_ctx);
2808
2809 if (!ctx_change)
2810 ret = xhci_queue_configure_endpoint(xhci, command,
2811 command->in_ctx->dma,
2812 udev->slot_id, must_succeed);
2813 else
2814 ret = xhci_queue_evaluate_context(xhci, command,
2815 command->in_ctx->dma,
2816 udev->slot_id, must_succeed);
2817 if (ret < 0) {
2818 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2819 xhci_free_host_resources(xhci, ctrl_ctx);
2820 spin_unlock_irqrestore(&xhci->lock, flags);
2821 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
2822 "FIXME allocate a new ring segment");
2823 return -ENOMEM;
2824 }
2825 xhci_ring_cmd_db(xhci);
2826 spin_unlock_irqrestore(&xhci->lock, flags);
2827
2828 /* Wait for the configure endpoint command to complete */
2829 wait_for_completion(command->completion);
2830
2831 if (!ctx_change)
2832 ret = xhci_configure_endpoint_result(xhci, udev,
2833 &command->status);
2834 else
2835 ret = xhci_evaluate_context_result(xhci, udev,
2836 &command->status);
2837
2838 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2839 spin_lock_irqsave(&xhci->lock, flags);
2840 /* If the command failed, remove the reserved resources.
2841 * Otherwise, clean up the estimate to include dropped eps.
2842 */
2843 if (ret)
2844 xhci_free_host_resources(xhci, ctrl_ctx);
2845 else
2846 xhci_finish_resource_reservation(xhci, ctrl_ctx);
2847 spin_unlock_irqrestore(&xhci->lock, flags);
2848 }
2849 return ret;
2850}
2851
2852static void xhci_check_bw_drop_ep_streams(struct xhci_hcd *xhci,
2853 struct xhci_virt_device *vdev, int i)
2854{
2855 struct xhci_virt_ep *ep = &vdev->eps[i];
2856
2857 if (ep->ep_state & EP_HAS_STREAMS) {
2858 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on set_interface, freeing streams.\n",
2859 xhci_get_endpoint_address(i));
2860 xhci_free_stream_info(xhci, ep->stream_info);
2861 ep->stream_info = NULL;
2862 ep->ep_state &= ~EP_HAS_STREAMS;
2863 }
2864}
2865
2866/* Called after one or more calls to xhci_add_endpoint() or
2867 * xhci_drop_endpoint(). If this call fails, the USB core is expected
2868 * to call xhci_reset_bandwidth().
2869 *
2870 * Since we are in the middle of changing either configuration or
2871 * installing a new alt setting, the USB core won't allow URBs to be
2872 * enqueued for any endpoint on the old config or interface. Nothing
2873 * else should be touching the xhci->devs[slot_id] structure, so we
2874 * don't need to take the xhci->lock for manipulating that.
2875 */
Olivier Deprez0e641232021-09-23 10:07:05 +02002876int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002877{
2878 int i;
2879 int ret = 0;
2880 struct xhci_hcd *xhci;
2881 struct xhci_virt_device *virt_dev;
2882 struct xhci_input_control_ctx *ctrl_ctx;
2883 struct xhci_slot_ctx *slot_ctx;
2884 struct xhci_command *command;
2885
2886 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2887 if (ret <= 0)
2888 return ret;
2889 xhci = hcd_to_xhci(hcd);
2890 if ((xhci->xhc_state & XHCI_STATE_DYING) ||
2891 (xhci->xhc_state & XHCI_STATE_REMOVING))
2892 return -ENODEV;
2893
2894 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2895 virt_dev = xhci->devs[udev->slot_id];
2896
2897 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
2898 if (!command)
2899 return -ENOMEM;
2900
2901 command->in_ctx = virt_dev->in_ctx;
2902
2903 /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
2904 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
2905 if (!ctrl_ctx) {
2906 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
2907 __func__);
2908 ret = -ENOMEM;
2909 goto command_cleanup;
2910 }
2911 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2912 ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
2913 ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
2914
2915 /* Don't issue the command if there's no endpoints to update. */
2916 if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2917 ctrl_ctx->drop_flags == 0) {
2918 ret = 0;
2919 goto command_cleanup;
2920 }
2921 /* Fix up Context Entries field. Minimum value is EP0 == BIT(1). */
2922 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2923 for (i = 31; i >= 1; i--) {
2924 __le32 le32 = cpu_to_le32(BIT(i));
2925
2926 if ((virt_dev->eps[i-1].ring && !(ctrl_ctx->drop_flags & le32))
2927 || (ctrl_ctx->add_flags & le32) || i == 1) {
2928 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
2929 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(i));
2930 break;
2931 }
2932 }
2933
2934 ret = xhci_configure_endpoint(xhci, udev, command,
2935 false, false);
2936 if (ret)
2937 /* Callee should call reset_bandwidth() */
2938 goto command_cleanup;
2939
2940 /* Free any rings that were dropped, but not changed. */
2941 for (i = 1; i < 31; i++) {
2942 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2943 !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1)))) {
2944 xhci_free_endpoint_ring(xhci, virt_dev, i);
2945 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2946 }
2947 }
2948 xhci_zero_in_ctx(xhci, virt_dev);
2949 /*
2950 * Install any rings for completely new endpoints or changed endpoints,
2951 * and free any old rings from changed endpoints.
2952 */
2953 for (i = 1; i < 31; i++) {
2954 if (!virt_dev->eps[i].new_ring)
2955 continue;
2956 /* Only free the old ring if it exists.
2957 * It may not if this is the first add of an endpoint.
2958 */
2959 if (virt_dev->eps[i].ring) {
2960 xhci_free_endpoint_ring(xhci, virt_dev, i);
2961 }
2962 xhci_check_bw_drop_ep_streams(xhci, virt_dev, i);
2963 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
2964 virt_dev->eps[i].new_ring = NULL;
Olivier Deprez0e641232021-09-23 10:07:05 +02002965 xhci_debugfs_create_endpoint(xhci, virt_dev, i);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002966 }
2967command_cleanup:
2968 kfree(command->completion);
2969 kfree(command);
2970
2971 return ret;
2972}
2973
Olivier Deprez0e641232021-09-23 10:07:05 +02002974void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002975{
2976 struct xhci_hcd *xhci;
2977 struct xhci_virt_device *virt_dev;
2978 int i, ret;
2979
2980 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2981 if (ret <= 0)
2982 return;
2983 xhci = hcd_to_xhci(hcd);
2984
2985 xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2986 virt_dev = xhci->devs[udev->slot_id];
2987 /* Free any rings allocated for added endpoints */
2988 for (i = 0; i < 31; i++) {
2989 if (virt_dev->eps[i].new_ring) {
2990 xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
2991 xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
2992 virt_dev->eps[i].new_ring = NULL;
2993 }
2994 }
2995 xhci_zero_in_ctx(xhci, virt_dev);
2996}
2997
2998static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
2999 struct xhci_container_ctx *in_ctx,
3000 struct xhci_container_ctx *out_ctx,
3001 struct xhci_input_control_ctx *ctrl_ctx,
3002 u32 add_flags, u32 drop_flags)
3003{
3004 ctrl_ctx->add_flags = cpu_to_le32(add_flags);
3005 ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
3006 xhci_slot_copy(xhci, in_ctx, out_ctx);
3007 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
3008}
3009
3010static void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
3011 unsigned int slot_id, unsigned int ep_index,
3012 struct xhci_dequeue_state *deq_state)
3013{
3014 struct xhci_input_control_ctx *ctrl_ctx;
3015 struct xhci_container_ctx *in_ctx;
3016 struct xhci_ep_ctx *ep_ctx;
3017 u32 added_ctxs;
3018 dma_addr_t addr;
3019
3020 in_ctx = xhci->devs[slot_id]->in_ctx;
3021 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
3022 if (!ctrl_ctx) {
3023 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3024 __func__);
3025 return;
3026 }
3027
3028 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
3029 xhci->devs[slot_id]->out_ctx, ep_index);
3030 ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
3031 addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
3032 deq_state->new_deq_ptr);
3033 if (addr == 0) {
3034 xhci_warn(xhci, "WARN Cannot submit config ep after "
3035 "reset ep command\n");
3036 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
3037 deq_state->new_deq_seg,
3038 deq_state->new_deq_ptr);
3039 return;
3040 }
3041 ep_ctx->deq = cpu_to_le64(addr | deq_state->new_cycle_state);
3042
3043 added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
3044 xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
3045 xhci->devs[slot_id]->out_ctx, ctrl_ctx,
3046 added_ctxs, added_ctxs);
3047}
3048
Olivier Deprez0e641232021-09-23 10:07:05 +02003049void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci, unsigned int slot_id,
3050 unsigned int ep_index, unsigned int stream_id,
3051 struct xhci_td *td)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003052{
3053 struct xhci_dequeue_state deq_state;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003054
3055 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
3056 "Cleaning up stalled endpoint ring");
3057 /* We need to move the HW's dequeue pointer past this TD,
3058 * or it will attempt to resend it on the next doorbell ring.
3059 */
Olivier Deprez0e641232021-09-23 10:07:05 +02003060 xhci_find_new_dequeue_state(xhci, slot_id, ep_index, stream_id, td,
3061 &deq_state);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003062
3063 if (!deq_state.new_deq_ptr || !deq_state.new_deq_seg)
3064 return;
3065
3066 /* HW with the reset endpoint quirk will use the saved dequeue state to
3067 * issue a configure endpoint command later.
3068 */
3069 if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
3070 xhci_dbg_trace(xhci, trace_xhci_dbg_reset_ep,
3071 "Queueing new dequeue state");
Olivier Deprez0e641232021-09-23 10:07:05 +02003072 xhci_queue_new_dequeue_state(xhci, slot_id,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003073 ep_index, &deq_state);
3074 } else {
3075 /* Better hope no one uses the input context between now and the
3076 * reset endpoint completion!
3077 * XXX: No idea how this hardware will react when stream rings
3078 * are enabled.
3079 */
3080 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3081 "Setting up input context for "
3082 "configure endpoint command");
Olivier Deprez0e641232021-09-23 10:07:05 +02003083 xhci_setup_input_ctx_for_quirk(xhci, slot_id,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003084 ep_index, &deq_state);
3085 }
3086}
3087
David Brazdil0f672f62019-12-10 10:32:29 +00003088static void xhci_endpoint_disable(struct usb_hcd *hcd,
3089 struct usb_host_endpoint *host_ep)
3090{
3091 struct xhci_hcd *xhci;
3092 struct xhci_virt_device *vdev;
3093 struct xhci_virt_ep *ep;
3094 struct usb_device *udev;
3095 unsigned long flags;
3096 unsigned int ep_index;
3097
3098 xhci = hcd_to_xhci(hcd);
3099rescan:
3100 spin_lock_irqsave(&xhci->lock, flags);
3101
3102 udev = (struct usb_device *)host_ep->hcpriv;
3103 if (!udev || !udev->slot_id)
3104 goto done;
3105
3106 vdev = xhci->devs[udev->slot_id];
3107 if (!vdev)
3108 goto done;
3109
3110 ep_index = xhci_get_endpoint_index(&host_ep->desc);
3111 ep = &vdev->eps[ep_index];
3112 if (!ep)
3113 goto done;
3114
3115 /* wait for hub_tt_work to finish clearing hub TT */
3116 if (ep->ep_state & EP_CLEARING_TT) {
3117 spin_unlock_irqrestore(&xhci->lock, flags);
3118 schedule_timeout_uninterruptible(1);
3119 goto rescan;
3120 }
3121
3122 if (ep->ep_state)
3123 xhci_dbg(xhci, "endpoint disable with ep_state 0x%x\n",
3124 ep->ep_state);
3125done:
3126 host_ep->hcpriv = NULL;
3127 spin_unlock_irqrestore(&xhci->lock, flags);
3128}
3129
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003130/*
3131 * Called after usb core issues a clear halt control message.
3132 * The host side of the halt should already be cleared by a reset endpoint
3133 * command issued when the STALL event was received.
3134 *
3135 * The reset endpoint command may only be issued to endpoints in the halted
3136 * state. For software that wishes to reset the data toggle or sequence number
3137 * of an endpoint that isn't in the halted state this function will issue a
3138 * configure endpoint command with the Drop and Add bits set for the target
3139 * endpoint. Refer to the additional note in xhci spcification section 4.6.8.
3140 */
3141
3142static void xhci_endpoint_reset(struct usb_hcd *hcd,
3143 struct usb_host_endpoint *host_ep)
3144{
3145 struct xhci_hcd *xhci;
3146 struct usb_device *udev;
3147 struct xhci_virt_device *vdev;
3148 struct xhci_virt_ep *ep;
3149 struct xhci_input_control_ctx *ctrl_ctx;
3150 struct xhci_command *stop_cmd, *cfg_cmd;
3151 unsigned int ep_index;
3152 unsigned long flags;
3153 u32 ep_flag;
David Brazdil0f672f62019-12-10 10:32:29 +00003154 int err;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003155
3156 xhci = hcd_to_xhci(hcd);
3157 if (!host_ep->hcpriv)
3158 return;
3159 udev = (struct usb_device *) host_ep->hcpriv;
3160 vdev = xhci->devs[udev->slot_id];
David Brazdil0f672f62019-12-10 10:32:29 +00003161
3162 /*
3163 * vdev may be lost due to xHC restore error and re-initialization
3164 * during S3/S4 resume. A new vdev will be allocated later by
3165 * xhci_discover_or_reset_device()
3166 */
3167 if (!udev->slot_id || !vdev)
3168 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003169 ep_index = xhci_get_endpoint_index(&host_ep->desc);
3170 ep = &vdev->eps[ep_index];
David Brazdil0f672f62019-12-10 10:32:29 +00003171 if (!ep)
3172 return;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003173
3174 /* Bail out if toggle is already being cleared by a endpoint reset */
3175 if (ep->ep_state & EP_HARD_CLEAR_TOGGLE) {
3176 ep->ep_state &= ~EP_HARD_CLEAR_TOGGLE;
3177 return;
3178 }
3179 /* Only interrupt and bulk ep's use data toggle, USB2 spec 5.5.4-> */
3180 if (usb_endpoint_xfer_control(&host_ep->desc) ||
3181 usb_endpoint_xfer_isoc(&host_ep->desc))
3182 return;
3183
3184 ep_flag = xhci_get_endpoint_flag(&host_ep->desc);
3185
3186 if (ep_flag == SLOT_FLAG || ep_flag == EP0_FLAG)
3187 return;
3188
3189 stop_cmd = xhci_alloc_command(xhci, true, GFP_NOWAIT);
3190 if (!stop_cmd)
3191 return;
3192
3193 cfg_cmd = xhci_alloc_command_with_ctx(xhci, true, GFP_NOWAIT);
3194 if (!cfg_cmd)
3195 goto cleanup;
3196
3197 spin_lock_irqsave(&xhci->lock, flags);
3198
3199 /* block queuing new trbs and ringing ep doorbell */
3200 ep->ep_state |= EP_SOFT_CLEAR_TOGGLE;
3201
3202 /*
3203 * Make sure endpoint ring is empty before resetting the toggle/seq.
3204 * Driver is required to synchronously cancel all transfer request.
3205 * Stop the endpoint to force xHC to update the output context
3206 */
3207
3208 if (!list_empty(&ep->ring->td_list)) {
3209 dev_err(&udev->dev, "EP not empty, refuse reset\n");
3210 spin_unlock_irqrestore(&xhci->lock, flags);
3211 xhci_free_command(xhci, cfg_cmd);
3212 goto cleanup;
3213 }
David Brazdil0f672f62019-12-10 10:32:29 +00003214
3215 err = xhci_queue_stop_endpoint(xhci, stop_cmd, udev->slot_id,
3216 ep_index, 0);
3217 if (err < 0) {
3218 spin_unlock_irqrestore(&xhci->lock, flags);
3219 xhci_free_command(xhci, cfg_cmd);
3220 xhci_dbg(xhci, "%s: Failed to queue stop ep command, %d ",
3221 __func__, err);
3222 goto cleanup;
3223 }
3224
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003225 xhci_ring_cmd_db(xhci);
3226 spin_unlock_irqrestore(&xhci->lock, flags);
3227
3228 wait_for_completion(stop_cmd->completion);
3229
3230 spin_lock_irqsave(&xhci->lock, flags);
3231
3232 /* config ep command clears toggle if add and drop ep flags are set */
3233 ctrl_ctx = xhci_get_input_control_ctx(cfg_cmd->in_ctx);
Olivier Deprez0e641232021-09-23 10:07:05 +02003234 if (!ctrl_ctx) {
3235 spin_unlock_irqrestore(&xhci->lock, flags);
3236 xhci_free_command(xhci, cfg_cmd);
3237 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3238 __func__);
3239 goto cleanup;
3240 }
3241
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003242 xhci_setup_input_ctx_for_config_ep(xhci, cfg_cmd->in_ctx, vdev->out_ctx,
3243 ctrl_ctx, ep_flag, ep_flag);
3244 xhci_endpoint_copy(xhci, cfg_cmd->in_ctx, vdev->out_ctx, ep_index);
3245
David Brazdil0f672f62019-12-10 10:32:29 +00003246 err = xhci_queue_configure_endpoint(xhci, cfg_cmd, cfg_cmd->in_ctx->dma,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003247 udev->slot_id, false);
David Brazdil0f672f62019-12-10 10:32:29 +00003248 if (err < 0) {
3249 spin_unlock_irqrestore(&xhci->lock, flags);
3250 xhci_free_command(xhci, cfg_cmd);
3251 xhci_dbg(xhci, "%s: Failed to queue config ep command, %d ",
3252 __func__, err);
3253 goto cleanup;
3254 }
3255
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003256 xhci_ring_cmd_db(xhci);
3257 spin_unlock_irqrestore(&xhci->lock, flags);
3258
3259 wait_for_completion(cfg_cmd->completion);
3260
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003261 xhci_free_command(xhci, cfg_cmd);
3262cleanup:
3263 xhci_free_command(xhci, stop_cmd);
Olivier Deprez0e641232021-09-23 10:07:05 +02003264 if (ep->ep_state & EP_SOFT_CLEAR_TOGGLE)
3265 ep->ep_state &= ~EP_SOFT_CLEAR_TOGGLE;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003266}
3267
3268static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
3269 struct usb_device *udev, struct usb_host_endpoint *ep,
3270 unsigned int slot_id)
3271{
3272 int ret;
3273 unsigned int ep_index;
3274 unsigned int ep_state;
3275
3276 if (!ep)
3277 return -EINVAL;
3278 ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
3279 if (ret <= 0)
3280 return -EINVAL;
3281 if (usb_ss_max_streams(&ep->ss_ep_comp) == 0) {
3282 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
3283 " descriptor for ep 0x%x does not support streams\n",
3284 ep->desc.bEndpointAddress);
3285 return -EINVAL;
3286 }
3287
3288 ep_index = xhci_get_endpoint_index(&ep->desc);
3289 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3290 if (ep_state & EP_HAS_STREAMS ||
3291 ep_state & EP_GETTING_STREAMS) {
3292 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
3293 "already has streams set up.\n",
3294 ep->desc.bEndpointAddress);
3295 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
3296 "dynamic stream context array reallocation.\n");
3297 return -EINVAL;
3298 }
3299 if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
3300 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
3301 "endpoint 0x%x; URBs are pending.\n",
3302 ep->desc.bEndpointAddress);
3303 return -EINVAL;
3304 }
3305 return 0;
3306}
3307
3308static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
3309 unsigned int *num_streams, unsigned int *num_stream_ctxs)
3310{
3311 unsigned int max_streams;
3312
3313 /* The stream context array size must be a power of two */
3314 *num_stream_ctxs = roundup_pow_of_two(*num_streams);
3315 /*
3316 * Find out how many primary stream array entries the host controller
3317 * supports. Later we may use secondary stream arrays (similar to 2nd
3318 * level page entries), but that's an optional feature for xHCI host
3319 * controllers. xHCs must support at least 4 stream IDs.
3320 */
3321 max_streams = HCC_MAX_PSA(xhci->hcc_params);
3322 if (*num_stream_ctxs > max_streams) {
3323 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
3324 max_streams);
3325 *num_stream_ctxs = max_streams;
3326 *num_streams = max_streams;
3327 }
3328}
3329
3330/* Returns an error code if one of the endpoint already has streams.
3331 * This does not change any data structures, it only checks and gathers
3332 * information.
3333 */
3334static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
3335 struct usb_device *udev,
3336 struct usb_host_endpoint **eps, unsigned int num_eps,
3337 unsigned int *num_streams, u32 *changed_ep_bitmask)
3338{
3339 unsigned int max_streams;
3340 unsigned int endpoint_flag;
3341 int i;
3342 int ret;
3343
3344 for (i = 0; i < num_eps; i++) {
3345 ret = xhci_check_streams_endpoint(xhci, udev,
3346 eps[i], udev->slot_id);
3347 if (ret < 0)
3348 return ret;
3349
3350 max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
3351 if (max_streams < (*num_streams - 1)) {
3352 xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
3353 eps[i]->desc.bEndpointAddress,
3354 max_streams);
3355 *num_streams = max_streams+1;
3356 }
3357
3358 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
3359 if (*changed_ep_bitmask & endpoint_flag)
3360 return -EINVAL;
3361 *changed_ep_bitmask |= endpoint_flag;
3362 }
3363 return 0;
3364}
3365
3366static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
3367 struct usb_device *udev,
3368 struct usb_host_endpoint **eps, unsigned int num_eps)
3369{
3370 u32 changed_ep_bitmask = 0;
3371 unsigned int slot_id;
3372 unsigned int ep_index;
3373 unsigned int ep_state;
3374 int i;
3375
3376 slot_id = udev->slot_id;
3377 if (!xhci->devs[slot_id])
3378 return 0;
3379
3380 for (i = 0; i < num_eps; i++) {
3381 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3382 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
3383 /* Are streams already being freed for the endpoint? */
3384 if (ep_state & EP_GETTING_NO_STREAMS) {
3385 xhci_warn(xhci, "WARN Can't disable streams for "
3386 "endpoint 0x%x, "
3387 "streams are being disabled already\n",
3388 eps[i]->desc.bEndpointAddress);
3389 return 0;
3390 }
3391 /* Are there actually any streams to free? */
3392 if (!(ep_state & EP_HAS_STREAMS) &&
3393 !(ep_state & EP_GETTING_STREAMS)) {
3394 xhci_warn(xhci, "WARN Can't disable streams for "
3395 "endpoint 0x%x, "
3396 "streams are already disabled!\n",
3397 eps[i]->desc.bEndpointAddress);
3398 xhci_warn(xhci, "WARN xhci_free_streams() called "
3399 "with non-streams endpoint\n");
3400 return 0;
3401 }
3402 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
3403 }
3404 return changed_ep_bitmask;
3405}
3406
3407/*
3408 * The USB device drivers use this function (through the HCD interface in USB
3409 * core) to prepare a set of bulk endpoints to use streams. Streams are used to
3410 * coordinate mass storage command queueing across multiple endpoints (basically
3411 * a stream ID == a task ID).
3412 *
3413 * Setting up streams involves allocating the same size stream context array
3414 * for each endpoint and issuing a configure endpoint command for all endpoints.
3415 *
3416 * Don't allow the call to succeed if one endpoint only supports one stream
3417 * (which means it doesn't support streams at all).
3418 *
3419 * Drivers may get less stream IDs than they asked for, if the host controller
3420 * hardware or endpoints claim they can't support the number of requested
3421 * stream IDs.
3422 */
3423static int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3424 struct usb_host_endpoint **eps, unsigned int num_eps,
3425 unsigned int num_streams, gfp_t mem_flags)
3426{
3427 int i, ret;
3428 struct xhci_hcd *xhci;
3429 struct xhci_virt_device *vdev;
3430 struct xhci_command *config_cmd;
3431 struct xhci_input_control_ctx *ctrl_ctx;
3432 unsigned int ep_index;
3433 unsigned int num_stream_ctxs;
3434 unsigned int max_packet;
3435 unsigned long flags;
3436 u32 changed_ep_bitmask = 0;
3437
3438 if (!eps)
3439 return -EINVAL;
3440
3441 /* Add one to the number of streams requested to account for
3442 * stream 0 that is reserved for xHCI usage.
3443 */
3444 num_streams += 1;
3445 xhci = hcd_to_xhci(hcd);
3446 xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3447 num_streams);
3448
3449 /* MaxPSASize value 0 (2 streams) means streams are not supported */
3450 if ((xhci->quirks & XHCI_BROKEN_STREAMS) ||
3451 HCC_MAX_PSA(xhci->hcc_params) < 4) {
3452 xhci_dbg(xhci, "xHCI controller does not support streams.\n");
3453 return -ENOSYS;
3454 }
3455
3456 config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
3457 if (!config_cmd)
3458 return -ENOMEM;
3459
3460 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
3461 if (!ctrl_ctx) {
3462 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3463 __func__);
3464 xhci_free_command(xhci, config_cmd);
3465 return -ENOMEM;
3466 }
3467
3468 /* Check to make sure all endpoints are not already configured for
3469 * streams. While we're at it, find the maximum number of streams that
3470 * all the endpoints will support and check for duplicate endpoints.
3471 */
3472 spin_lock_irqsave(&xhci->lock, flags);
3473 ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3474 num_eps, &num_streams, &changed_ep_bitmask);
3475 if (ret < 0) {
3476 xhci_free_command(xhci, config_cmd);
3477 spin_unlock_irqrestore(&xhci->lock, flags);
3478 return ret;
3479 }
3480 if (num_streams <= 1) {
3481 xhci_warn(xhci, "WARN: endpoints can't handle "
3482 "more than one stream.\n");
3483 xhci_free_command(xhci, config_cmd);
3484 spin_unlock_irqrestore(&xhci->lock, flags);
3485 return -EINVAL;
3486 }
3487 vdev = xhci->devs[udev->slot_id];
3488 /* Mark each endpoint as being in transition, so
3489 * xhci_urb_enqueue() will reject all URBs.
3490 */
3491 for (i = 0; i < num_eps; i++) {
3492 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3493 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3494 }
3495 spin_unlock_irqrestore(&xhci->lock, flags);
3496
3497 /* Setup internal data structures and allocate HW data structures for
3498 * streams (but don't install the HW structures in the input context
3499 * until we're sure all memory allocation succeeded).
3500 */
3501 xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3502 xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3503 num_stream_ctxs, num_streams);
3504
3505 for (i = 0; i < num_eps; i++) {
3506 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3507 max_packet = usb_endpoint_maxp(&eps[i]->desc);
3508 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3509 num_stream_ctxs,
3510 num_streams,
3511 max_packet, mem_flags);
3512 if (!vdev->eps[ep_index].stream_info)
3513 goto cleanup;
3514 /* Set maxPstreams in endpoint context and update deq ptr to
3515 * point to stream context array. FIXME
3516 */
3517 }
3518
3519 /* Set up the input context for a configure endpoint command. */
3520 for (i = 0; i < num_eps; i++) {
3521 struct xhci_ep_ctx *ep_ctx;
3522
3523 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3524 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3525
3526 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3527 vdev->out_ctx, ep_index);
3528 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3529 vdev->eps[ep_index].stream_info);
3530 }
3531 /* Tell the HW to drop its old copy of the endpoint context info
3532 * and add the updated copy from the input context.
3533 */
3534 xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3535 vdev->out_ctx, ctrl_ctx,
3536 changed_ep_bitmask, changed_ep_bitmask);
3537
3538 /* Issue and wait for the configure endpoint command */
3539 ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3540 false, false);
3541
3542 /* xHC rejected the configure endpoint command for some reason, so we
3543 * leave the old ring intact and free our internal streams data
3544 * structure.
3545 */
3546 if (ret < 0)
3547 goto cleanup;
3548
3549 spin_lock_irqsave(&xhci->lock, flags);
3550 for (i = 0; i < num_eps; i++) {
3551 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3552 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3553 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3554 udev->slot_id, ep_index);
3555 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3556 }
3557 xhci_free_command(xhci, config_cmd);
3558 spin_unlock_irqrestore(&xhci->lock, flags);
3559
3560 /* Subtract 1 for stream 0, which drivers can't use */
3561 return num_streams - 1;
3562
3563cleanup:
3564 /* If it didn't work, free the streams! */
3565 for (i = 0; i < num_eps; i++) {
3566 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3567 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3568 vdev->eps[ep_index].stream_info = NULL;
3569 /* FIXME Unset maxPstreams in endpoint context and
3570 * update deq ptr to point to normal string ring.
3571 */
3572 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3573 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3574 xhci_endpoint_zero(xhci, vdev, eps[i]);
3575 }
3576 xhci_free_command(xhci, config_cmd);
3577 return -ENOMEM;
3578}
3579
3580/* Transition the endpoint from using streams to being a "normal" endpoint
3581 * without streams.
3582 *
3583 * Modify the endpoint context state, submit a configure endpoint command,
3584 * and free all endpoint rings for streams if that completes successfully.
3585 */
3586static int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3587 struct usb_host_endpoint **eps, unsigned int num_eps,
3588 gfp_t mem_flags)
3589{
3590 int i, ret;
3591 struct xhci_hcd *xhci;
3592 struct xhci_virt_device *vdev;
3593 struct xhci_command *command;
3594 struct xhci_input_control_ctx *ctrl_ctx;
3595 unsigned int ep_index;
3596 unsigned long flags;
3597 u32 changed_ep_bitmask;
3598
3599 xhci = hcd_to_xhci(hcd);
3600 vdev = xhci->devs[udev->slot_id];
3601
3602 /* Set up a configure endpoint command to remove the streams rings */
3603 spin_lock_irqsave(&xhci->lock, flags);
3604 changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3605 udev, eps, num_eps);
3606 if (changed_ep_bitmask == 0) {
3607 spin_unlock_irqrestore(&xhci->lock, flags);
3608 return -EINVAL;
3609 }
3610
3611 /* Use the xhci_command structure from the first endpoint. We may have
3612 * allocated too many, but the driver may call xhci_free_streams() for
3613 * each endpoint it grouped into one call to xhci_alloc_streams().
3614 */
3615 ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3616 command = vdev->eps[ep_index].stream_info->free_streams_command;
3617 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
3618 if (!ctrl_ctx) {
3619 spin_unlock_irqrestore(&xhci->lock, flags);
3620 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
3621 __func__);
3622 return -EINVAL;
3623 }
3624
3625 for (i = 0; i < num_eps; i++) {
3626 struct xhci_ep_ctx *ep_ctx;
3627
3628 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3629 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3630 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3631 EP_GETTING_NO_STREAMS;
3632
3633 xhci_endpoint_copy(xhci, command->in_ctx,
3634 vdev->out_ctx, ep_index);
3635 xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3636 &vdev->eps[ep_index]);
3637 }
3638 xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3639 vdev->out_ctx, ctrl_ctx,
3640 changed_ep_bitmask, changed_ep_bitmask);
3641 spin_unlock_irqrestore(&xhci->lock, flags);
3642
3643 /* Issue and wait for the configure endpoint command,
3644 * which must succeed.
3645 */
3646 ret = xhci_configure_endpoint(xhci, udev, command,
3647 false, true);
3648
3649 /* xHC rejected the configure endpoint command for some reason, so we
3650 * leave the streams rings intact.
3651 */
3652 if (ret < 0)
3653 return ret;
3654
3655 spin_lock_irqsave(&xhci->lock, flags);
3656 for (i = 0; i < num_eps; i++) {
3657 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3658 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3659 vdev->eps[ep_index].stream_info = NULL;
3660 /* FIXME Unset maxPstreams in endpoint context and
3661 * update deq ptr to point to normal string ring.
3662 */
3663 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3664 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3665 }
3666 spin_unlock_irqrestore(&xhci->lock, flags);
3667
3668 return 0;
3669}
3670
3671/*
3672 * Deletes endpoint resources for endpoints that were active before a Reset
3673 * Device command, or a Disable Slot command. The Reset Device command leaves
3674 * the control endpoint intact, whereas the Disable Slot command deletes it.
3675 *
3676 * Must be called with xhci->lock held.
3677 */
3678void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3679 struct xhci_virt_device *virt_dev, bool drop_control_ep)
3680{
3681 int i;
3682 unsigned int num_dropped_eps = 0;
3683 unsigned int drop_flags = 0;
3684
3685 for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3686 if (virt_dev->eps[i].ring) {
3687 drop_flags |= 1 << i;
3688 num_dropped_eps++;
3689 }
3690 }
3691 xhci->num_active_eps -= num_dropped_eps;
3692 if (num_dropped_eps)
3693 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3694 "Dropped %u ep ctxs, flags = 0x%x, "
3695 "%u now active.",
3696 num_dropped_eps, drop_flags,
3697 xhci->num_active_eps);
3698}
3699
3700/*
3701 * This submits a Reset Device Command, which will set the device state to 0,
3702 * set the device address to 0, and disable all the endpoints except the default
3703 * control endpoint. The USB core should come back and call
3704 * xhci_address_device(), and then re-set up the configuration. If this is
3705 * called because of a usb_reset_and_verify_device(), then the old alternate
3706 * settings will be re-installed through the normal bandwidth allocation
3707 * functions.
3708 *
3709 * Wait for the Reset Device command to finish. Remove all structures
3710 * associated with the endpoints that were disabled. Clear the input device
3711 * structure? Reset the control endpoint 0 max packet size?
3712 *
3713 * If the virt_dev to be reset does not exist or does not match the udev,
3714 * it means the device is lost, possibly due to the xHC restore error and
3715 * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3716 * re-allocate the device.
3717 */
3718static int xhci_discover_or_reset_device(struct usb_hcd *hcd,
3719 struct usb_device *udev)
3720{
3721 int ret, i;
3722 unsigned long flags;
3723 struct xhci_hcd *xhci;
3724 unsigned int slot_id;
3725 struct xhci_virt_device *virt_dev;
3726 struct xhci_command *reset_device_cmd;
3727 struct xhci_slot_ctx *slot_ctx;
3728 int old_active_eps = 0;
3729
3730 ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3731 if (ret <= 0)
3732 return ret;
3733 xhci = hcd_to_xhci(hcd);
3734 slot_id = udev->slot_id;
3735 virt_dev = xhci->devs[slot_id];
3736 if (!virt_dev) {
3737 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3738 "not exist. Re-allocate the device\n", slot_id);
3739 ret = xhci_alloc_dev(hcd, udev);
3740 if (ret == 1)
3741 return 0;
3742 else
3743 return -EINVAL;
3744 }
3745
3746 if (virt_dev->tt_info)
3747 old_active_eps = virt_dev->tt_info->active_eps;
3748
3749 if (virt_dev->udev != udev) {
3750 /* If the virt_dev and the udev does not match, this virt_dev
3751 * may belong to another udev.
3752 * Re-allocate the device.
3753 */
3754 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3755 "not match the udev. Re-allocate the device\n",
3756 slot_id);
3757 ret = xhci_alloc_dev(hcd, udev);
3758 if (ret == 1)
3759 return 0;
3760 else
3761 return -EINVAL;
3762 }
3763
3764 /* If device is not setup, there is no point in resetting it */
3765 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3766 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3767 SLOT_STATE_DISABLED)
3768 return 0;
3769
3770 trace_xhci_discover_or_reset_device(slot_ctx);
3771
3772 xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3773 /* Allocate the command structure that holds the struct completion.
3774 * Assume we're in process context, since the normal device reset
3775 * process has to wait for the device anyway. Storage devices are
3776 * reset as part of error handling, so use GFP_NOIO instead of
3777 * GFP_KERNEL.
3778 */
3779 reset_device_cmd = xhci_alloc_command(xhci, true, GFP_NOIO);
3780 if (!reset_device_cmd) {
3781 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3782 return -ENOMEM;
3783 }
3784
3785 /* Attempt to submit the Reset Device command to the command ring */
3786 spin_lock_irqsave(&xhci->lock, flags);
3787
3788 ret = xhci_queue_reset_device(xhci, reset_device_cmd, slot_id);
3789 if (ret) {
3790 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3791 spin_unlock_irqrestore(&xhci->lock, flags);
3792 goto command_cleanup;
3793 }
3794 xhci_ring_cmd_db(xhci);
3795 spin_unlock_irqrestore(&xhci->lock, flags);
3796
3797 /* Wait for the Reset Device command to finish */
3798 wait_for_completion(reset_device_cmd->completion);
3799
3800 /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3801 * unless we tried to reset a slot ID that wasn't enabled,
3802 * or the device wasn't in the addressed or configured state.
3803 */
3804 ret = reset_device_cmd->status;
3805 switch (ret) {
3806 case COMP_COMMAND_ABORTED:
3807 case COMP_COMMAND_RING_STOPPED:
3808 xhci_warn(xhci, "Timeout waiting for reset device command\n");
3809 ret = -ETIME;
3810 goto command_cleanup;
3811 case COMP_SLOT_NOT_ENABLED_ERROR: /* 0.95 completion for bad slot ID */
3812 case COMP_CONTEXT_STATE_ERROR: /* 0.96 completion code for same thing */
3813 xhci_dbg(xhci, "Can't reset device (slot ID %u) in %s state\n",
3814 slot_id,
3815 xhci_get_slot_state(xhci, virt_dev->out_ctx));
3816 xhci_dbg(xhci, "Not freeing device rings.\n");
3817 /* Don't treat this as an error. May change my mind later. */
3818 ret = 0;
3819 goto command_cleanup;
3820 case COMP_SUCCESS:
3821 xhci_dbg(xhci, "Successful reset device command.\n");
3822 break;
3823 default:
3824 if (xhci_is_vendor_info_code(xhci, ret))
3825 break;
3826 xhci_warn(xhci, "Unknown completion code %u for "
3827 "reset device command.\n", ret);
3828 ret = -EINVAL;
3829 goto command_cleanup;
3830 }
3831
3832 /* Free up host controller endpoint resources */
3833 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3834 spin_lock_irqsave(&xhci->lock, flags);
3835 /* Don't delete the default control endpoint resources */
3836 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
3837 spin_unlock_irqrestore(&xhci->lock, flags);
3838 }
3839
3840 /* Everything but endpoint 0 is disabled, so free the rings. */
3841 for (i = 1; i < 31; i++) {
3842 struct xhci_virt_ep *ep = &virt_dev->eps[i];
3843
3844 if (ep->ep_state & EP_HAS_STREAMS) {
3845 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
3846 xhci_get_endpoint_address(i));
3847 xhci_free_stream_info(xhci, ep->stream_info);
3848 ep->stream_info = NULL;
3849 ep->ep_state &= ~EP_HAS_STREAMS;
3850 }
3851
3852 if (ep->ring) {
3853 xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
3854 xhci_free_endpoint_ring(xhci, virt_dev, i);
3855 }
3856 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
3857 xhci_drop_ep_from_interval_table(xhci,
3858 &virt_dev->eps[i].bw_info,
3859 virt_dev->bw_table,
3860 udev,
3861 &virt_dev->eps[i],
3862 virt_dev->tt_info);
3863 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
3864 }
3865 /* If necessary, update the number of active TTs on this root port */
3866 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
David Brazdil0f672f62019-12-10 10:32:29 +00003867 virt_dev->flags = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003868 ret = 0;
3869
3870command_cleanup:
3871 xhci_free_command(xhci, reset_device_cmd);
3872 return ret;
3873}
3874
3875/*
3876 * At this point, the struct usb_device is about to go away, the device has
3877 * disconnected, and all traffic has been stopped and the endpoints have been
3878 * disabled. Free any HC data structures associated with that device.
3879 */
3880static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3881{
3882 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3883 struct xhci_virt_device *virt_dev;
3884 struct xhci_slot_ctx *slot_ctx;
3885 int i, ret;
3886
3887#ifndef CONFIG_USB_DEFAULT_PERSIST
3888 /*
3889 * We called pm_runtime_get_noresume when the device was attached.
3890 * Decrement the counter here to allow controller to runtime suspend
3891 * if no devices remain.
3892 */
3893 if (xhci->quirks & XHCI_RESET_ON_RESUME)
3894 pm_runtime_put_noidle(hcd->self.controller);
3895#endif
3896
3897 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3898 /* If the host is halted due to driver unload, we still need to free the
3899 * device.
3900 */
3901 if (ret <= 0 && ret != -ENODEV)
3902 return;
3903
3904 virt_dev = xhci->devs[udev->slot_id];
3905 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3906 trace_xhci_free_dev(slot_ctx);
3907
3908 /* Stop any wayward timer functions (which may grab the lock) */
3909 for (i = 0; i < 31; i++) {
3910 virt_dev->eps[i].ep_state &= ~EP_STOP_CMD_PENDING;
3911 del_timer_sync(&virt_dev->eps[i].stop_cmd_timer);
3912 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003913 virt_dev->udev = NULL;
3914 ret = xhci_disable_slot(xhci, udev->slot_id);
3915 if (ret)
3916 xhci_free_virt_device(xhci, udev->slot_id);
3917}
3918
3919int xhci_disable_slot(struct xhci_hcd *xhci, u32 slot_id)
3920{
3921 struct xhci_command *command;
3922 unsigned long flags;
3923 u32 state;
3924 int ret = 0;
3925
3926 command = xhci_alloc_command(xhci, false, GFP_KERNEL);
3927 if (!command)
3928 return -ENOMEM;
3929
David Brazdil0f672f62019-12-10 10:32:29 +00003930 xhci_debugfs_remove_slot(xhci, slot_id);
3931
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003932 spin_lock_irqsave(&xhci->lock, flags);
3933 /* Don't disable the slot if the host controller is dead. */
3934 state = readl(&xhci->op_regs->status);
3935 if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
3936 (xhci->xhc_state & XHCI_STATE_HALTED)) {
3937 spin_unlock_irqrestore(&xhci->lock, flags);
3938 kfree(command);
3939 return -ENODEV;
3940 }
3941
3942 ret = xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
3943 slot_id);
3944 if (ret) {
3945 spin_unlock_irqrestore(&xhci->lock, flags);
3946 kfree(command);
3947 return ret;
3948 }
3949 xhci_ring_cmd_db(xhci);
3950 spin_unlock_irqrestore(&xhci->lock, flags);
3951 return ret;
3952}
3953
3954/*
3955 * Checks if we have enough host controller resources for the default control
3956 * endpoint.
3957 *
3958 * Must be called with xhci->lock held.
3959 */
3960static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
3961{
3962 if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
3963 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3964 "Not enough ep ctxs: "
3965 "%u active, need to add 1, limit is %u.",
3966 xhci->num_active_eps, xhci->limit_active_eps);
3967 return -ENOMEM;
3968 }
3969 xhci->num_active_eps += 1;
3970 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
3971 "Adding 1 ep ctx, %u now active.",
3972 xhci->num_active_eps);
3973 return 0;
3974}
3975
3976
3977/*
3978 * Returns 0 if the xHC ran out of device slots, the Enable Slot command
3979 * timed out, or allocating memory failed. Returns 1 on success.
3980 */
3981int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
3982{
3983 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3984 struct xhci_virt_device *vdev;
3985 struct xhci_slot_ctx *slot_ctx;
3986 unsigned long flags;
3987 int ret, slot_id;
3988 struct xhci_command *command;
3989
3990 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
3991 if (!command)
3992 return 0;
3993
3994 spin_lock_irqsave(&xhci->lock, flags);
3995 ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
3996 if (ret) {
3997 spin_unlock_irqrestore(&xhci->lock, flags);
3998 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3999 xhci_free_command(xhci, command);
4000 return 0;
4001 }
4002 xhci_ring_cmd_db(xhci);
4003 spin_unlock_irqrestore(&xhci->lock, flags);
4004
4005 wait_for_completion(command->completion);
4006 slot_id = command->slot_id;
4007
4008 if (!slot_id || command->status != COMP_SUCCESS) {
4009 xhci_err(xhci, "Error while assigning device slot ID\n");
4010 xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
4011 HCS_MAX_SLOTS(
4012 readl(&xhci->cap_regs->hcs_params1)));
4013 xhci_free_command(xhci, command);
4014 return 0;
4015 }
4016
4017 xhci_free_command(xhci, command);
4018
4019 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
4020 spin_lock_irqsave(&xhci->lock, flags);
4021 ret = xhci_reserve_host_control_ep_resources(xhci);
4022 if (ret) {
4023 spin_unlock_irqrestore(&xhci->lock, flags);
4024 xhci_warn(xhci, "Not enough host resources, "
4025 "active endpoint contexts = %u\n",
4026 xhci->num_active_eps);
4027 goto disable_slot;
4028 }
4029 spin_unlock_irqrestore(&xhci->lock, flags);
4030 }
4031 /* Use GFP_NOIO, since this function can be called from
4032 * xhci_discover_or_reset_device(), which may be called as part of
4033 * mass storage driver error handling.
4034 */
4035 if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) {
4036 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
4037 goto disable_slot;
4038 }
4039 vdev = xhci->devs[slot_id];
4040 slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
4041 trace_xhci_alloc_dev(slot_ctx);
4042
4043 udev->slot_id = slot_id;
4044
4045 xhci_debugfs_create_slot(xhci, slot_id);
4046
4047#ifndef CONFIG_USB_DEFAULT_PERSIST
4048 /*
4049 * If resetting upon resume, we can't put the controller into runtime
4050 * suspend if there is a device attached.
4051 */
4052 if (xhci->quirks & XHCI_RESET_ON_RESUME)
4053 pm_runtime_get_noresume(hcd->self.controller);
4054#endif
4055
4056 /* Is this a LS or FS device under a HS hub? */
4057 /* Hub or peripherial? */
4058 return 1;
4059
4060disable_slot:
4061 ret = xhci_disable_slot(xhci, udev->slot_id);
4062 if (ret)
4063 xhci_free_virt_device(xhci, udev->slot_id);
4064
4065 return 0;
4066}
4067
4068/*
4069 * Issue an Address Device command and optionally send a corresponding
4070 * SetAddress request to the device.
4071 */
4072static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
4073 enum xhci_setup_dev setup)
4074{
4075 const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
4076 unsigned long flags;
4077 struct xhci_virt_device *virt_dev;
4078 int ret = 0;
4079 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4080 struct xhci_slot_ctx *slot_ctx;
4081 struct xhci_input_control_ctx *ctrl_ctx;
4082 u64 temp_64;
4083 struct xhci_command *command = NULL;
4084
4085 mutex_lock(&xhci->mutex);
4086
4087 if (xhci->xhc_state) { /* dying, removing or halted */
4088 ret = -ESHUTDOWN;
4089 goto out;
4090 }
4091
4092 if (!udev->slot_id) {
4093 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4094 "Bad Slot ID %d", udev->slot_id);
4095 ret = -EINVAL;
4096 goto out;
4097 }
4098
4099 virt_dev = xhci->devs[udev->slot_id];
4100
4101 if (WARN_ON(!virt_dev)) {
4102 /*
4103 * In plug/unplug torture test with an NEC controller,
4104 * a zero-dereference was observed once due to virt_dev = 0.
4105 * Print useful debug rather than crash if it is observed again!
4106 */
4107 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
4108 udev->slot_id);
4109 ret = -EINVAL;
4110 goto out;
4111 }
4112 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4113 trace_xhci_setup_device_slot(slot_ctx);
4114
4115 if (setup == SETUP_CONTEXT_ONLY) {
4116 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
4117 SLOT_STATE_DEFAULT) {
4118 xhci_dbg(xhci, "Slot already in default state\n");
4119 goto out;
4120 }
4121 }
4122
4123 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4124 if (!command) {
4125 ret = -ENOMEM;
4126 goto out;
4127 }
4128
4129 command->in_ctx = virt_dev->in_ctx;
4130
4131 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
4132 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
4133 if (!ctrl_ctx) {
4134 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4135 __func__);
4136 ret = -EINVAL;
4137 goto out;
4138 }
4139 /*
4140 * If this is the first Set Address since device plug-in or
4141 * virt_device realloaction after a resume with an xHCI power loss,
4142 * then set up the slot context.
4143 */
4144 if (!slot_ctx->dev_info)
4145 xhci_setup_addressable_virt_dev(xhci, udev);
4146 /* Otherwise, update the control endpoint ring enqueue pointer. */
4147 else
4148 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
4149 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
4150 ctrl_ctx->drop_flags = 0;
4151
4152 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4153 le32_to_cpu(slot_ctx->dev_info) >> 27);
4154
David Brazdil0f672f62019-12-10 10:32:29 +00004155 trace_xhci_address_ctrl_ctx(ctrl_ctx);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004156 spin_lock_irqsave(&xhci->lock, flags);
4157 trace_xhci_setup_device(virt_dev);
4158 ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
4159 udev->slot_id, setup);
4160 if (ret) {
4161 spin_unlock_irqrestore(&xhci->lock, flags);
4162 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4163 "FIXME: allocate a command ring segment");
4164 goto out;
4165 }
4166 xhci_ring_cmd_db(xhci);
4167 spin_unlock_irqrestore(&xhci->lock, flags);
4168
4169 /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
4170 wait_for_completion(command->completion);
4171
4172 /* FIXME: From section 4.3.4: "Software shall be responsible for timing
4173 * the SetAddress() "recovery interval" required by USB and aborting the
4174 * command on a timeout.
4175 */
4176 switch (command->status) {
4177 case COMP_COMMAND_ABORTED:
4178 case COMP_COMMAND_RING_STOPPED:
4179 xhci_warn(xhci, "Timeout while waiting for setup device command\n");
4180 ret = -ETIME;
4181 break;
4182 case COMP_CONTEXT_STATE_ERROR:
4183 case COMP_SLOT_NOT_ENABLED_ERROR:
4184 xhci_err(xhci, "Setup ERROR: setup %s command for slot %d.\n",
4185 act, udev->slot_id);
4186 ret = -EINVAL;
4187 break;
4188 case COMP_USB_TRANSACTION_ERROR:
4189 dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
4190
4191 mutex_unlock(&xhci->mutex);
4192 ret = xhci_disable_slot(xhci, udev->slot_id);
4193 if (!ret)
4194 xhci_alloc_dev(hcd, udev);
4195 kfree(command->completion);
4196 kfree(command);
4197 return -EPROTO;
4198 case COMP_INCOMPATIBLE_DEVICE_ERROR:
4199 dev_warn(&udev->dev,
4200 "ERROR: Incompatible device for setup %s command\n", act);
4201 ret = -ENODEV;
4202 break;
4203 case COMP_SUCCESS:
4204 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4205 "Successful setup %s command", act);
4206 break;
4207 default:
4208 xhci_err(xhci,
4209 "ERROR: unexpected setup %s command completion code 0x%x.\n",
4210 act, command->status);
4211 trace_xhci_address_ctx(xhci, virt_dev->out_ctx, 1);
4212 ret = -EINVAL;
4213 break;
4214 }
4215 if (ret)
4216 goto out;
4217 temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
4218 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4219 "Op regs DCBAA ptr = %#016llx", temp_64);
4220 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4221 "Slot ID %d dcbaa entry @%p = %#016llx",
4222 udev->slot_id,
4223 &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
4224 (unsigned long long)
4225 le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
4226 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4227 "Output Context DMA address = %#08llx",
4228 (unsigned long long)virt_dev->out_ctx->dma);
4229 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4230 le32_to_cpu(slot_ctx->dev_info) >> 27);
4231 /*
4232 * USB core uses address 1 for the roothubs, so we add one to the
4233 * address given back to us by the HC.
4234 */
4235 trace_xhci_address_ctx(xhci, virt_dev->out_ctx,
4236 le32_to_cpu(slot_ctx->dev_info) >> 27);
4237 /* Zero the input context control for later use */
4238 ctrl_ctx->add_flags = 0;
4239 ctrl_ctx->drop_flags = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00004240 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4241 udev->devaddr = (u8)(le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004242
4243 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4244 "Internal device address = %d",
4245 le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4246out:
4247 mutex_unlock(&xhci->mutex);
4248 if (command) {
4249 kfree(command->completion);
4250 kfree(command);
4251 }
4252 return ret;
4253}
4254
4255static int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev)
4256{
4257 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ADDRESS);
4258}
4259
4260static int xhci_enable_device(struct usb_hcd *hcd, struct usb_device *udev)
4261{
4262 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ONLY);
4263}
4264
4265/*
4266 * Transfer the port index into real index in the HW port status
4267 * registers. Caculate offset between the port's PORTSC register
4268 * and port status base. Divide the number of per port register
4269 * to get the real index. The raw port number bases 1.
4270 */
4271int xhci_find_raw_port_number(struct usb_hcd *hcd, int port1)
4272{
4273 struct xhci_hub *rhub;
4274
4275 rhub = xhci_get_rhub(hcd);
4276 return rhub->ports[port1 - 1]->hw_portnum + 1;
4277}
4278
4279/*
4280 * Issue an Evaluate Context command to change the Maximum Exit Latency in the
4281 * slot context. If that succeeds, store the new MEL in the xhci_virt_device.
4282 */
4283static int __maybe_unused xhci_change_max_exit_latency(struct xhci_hcd *xhci,
4284 struct usb_device *udev, u16 max_exit_latency)
4285{
4286 struct xhci_virt_device *virt_dev;
4287 struct xhci_command *command;
4288 struct xhci_input_control_ctx *ctrl_ctx;
4289 struct xhci_slot_ctx *slot_ctx;
4290 unsigned long flags;
4291 int ret;
4292
4293 spin_lock_irqsave(&xhci->lock, flags);
4294
4295 virt_dev = xhci->devs[udev->slot_id];
4296
4297 /*
4298 * virt_dev might not exists yet if xHC resumed from hibernate (S4) and
4299 * xHC was re-initialized. Exit latency will be set later after
4300 * hub_port_finish_reset() is done and xhci->devs[] are re-allocated
4301 */
4302
4303 if (!virt_dev || max_exit_latency == virt_dev->current_mel) {
4304 spin_unlock_irqrestore(&xhci->lock, flags);
4305 return 0;
4306 }
4307
4308 /* Attempt to issue an Evaluate Context command to change the MEL. */
4309 command = xhci->lpm_command;
4310 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
4311 if (!ctrl_ctx) {
4312 spin_unlock_irqrestore(&xhci->lock, flags);
4313 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4314 __func__);
4315 return -ENOMEM;
4316 }
4317
4318 xhci_slot_copy(xhci, command->in_ctx, virt_dev->out_ctx);
4319 spin_unlock_irqrestore(&xhci->lock, flags);
4320
4321 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4322 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
4323 slot_ctx->dev_info2 &= cpu_to_le32(~((u32) MAX_EXIT));
4324 slot_ctx->dev_info2 |= cpu_to_le32(max_exit_latency);
4325 slot_ctx->dev_state = 0;
4326
4327 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
4328 "Set up evaluate context for LPM MEL change.");
4329
4330 /* Issue and wait for the evaluate context command. */
4331 ret = xhci_configure_endpoint(xhci, udev, command,
4332 true, true);
4333
4334 if (!ret) {
4335 spin_lock_irqsave(&xhci->lock, flags);
4336 virt_dev->current_mel = max_exit_latency;
4337 spin_unlock_irqrestore(&xhci->lock, flags);
4338 }
4339 return ret;
4340}
4341
4342#ifdef CONFIG_PM
4343
4344/* BESL to HIRD Encoding array for USB2 LPM */
4345static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
4346 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
4347
4348/* Calculate HIRD/BESL for USB2 PORTPMSC*/
4349static int xhci_calculate_hird_besl(struct xhci_hcd *xhci,
4350 struct usb_device *udev)
4351{
4352 int u2del, besl, besl_host;
4353 int besl_device = 0;
4354 u32 field;
4355
4356 u2del = HCS_U2_LATENCY(xhci->hcs_params3);
4357 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4358
4359 if (field & USB_BESL_SUPPORT) {
4360 for (besl_host = 0; besl_host < 16; besl_host++) {
4361 if (xhci_besl_encoding[besl_host] >= u2del)
4362 break;
4363 }
4364 /* Use baseline BESL value as default */
4365 if (field & USB_BESL_BASELINE_VALID)
4366 besl_device = USB_GET_BESL_BASELINE(field);
4367 else if (field & USB_BESL_DEEP_VALID)
4368 besl_device = USB_GET_BESL_DEEP(field);
4369 } else {
4370 if (u2del <= 50)
4371 besl_host = 0;
4372 else
4373 besl_host = (u2del - 51) / 75 + 1;
4374 }
4375
4376 besl = besl_host + besl_device;
4377 if (besl > 15)
4378 besl = 15;
4379
4380 return besl;
4381}
4382
4383/* Calculate BESLD, L1 timeout and HIRDM for USB2 PORTHLPMC */
4384static int xhci_calculate_usb2_hw_lpm_params(struct usb_device *udev)
4385{
4386 u32 field;
4387 int l1;
4388 int besld = 0;
4389 int hirdm = 0;
4390
4391 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4392
4393 /* xHCI l1 is set in steps of 256us, xHCI 1.0 section 5.4.11.2 */
4394 l1 = udev->l1_params.timeout / 256;
4395
4396 /* device has preferred BESLD */
4397 if (field & USB_BESL_DEEP_VALID) {
4398 besld = USB_GET_BESL_DEEP(field);
4399 hirdm = 1;
4400 }
4401
4402 return PORT_BESLD(besld) | PORT_L1_TIMEOUT(l1) | PORT_HIRDM(hirdm);
4403}
4404
4405static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4406 struct usb_device *udev, int enable)
4407{
4408 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4409 struct xhci_port **ports;
4410 __le32 __iomem *pm_addr, *hlpm_addr;
4411 u32 pm_val, hlpm_val, field;
4412 unsigned int port_num;
4413 unsigned long flags;
4414 int hird, exit_latency;
4415 int ret;
4416
Olivier Deprez0e641232021-09-23 10:07:05 +02004417 if (xhci->quirks & XHCI_HW_LPM_DISABLE)
4418 return -EPERM;
4419
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004420 if (hcd->speed >= HCD_USB3 || !xhci->hw_lpm_support ||
4421 !udev->lpm_capable)
4422 return -EPERM;
4423
4424 if (!udev->parent || udev->parent->parent ||
4425 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4426 return -EPERM;
4427
4428 if (udev->usb2_hw_lpm_capable != 1)
4429 return -EPERM;
4430
4431 spin_lock_irqsave(&xhci->lock, flags);
4432
4433 ports = xhci->usb2_rhub.ports;
4434 port_num = udev->portnum - 1;
4435 pm_addr = ports[port_num]->addr + PORTPMSC;
4436 pm_val = readl(pm_addr);
4437 hlpm_addr = ports[port_num]->addr + PORTHLPMC;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004438
4439 xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
4440 enable ? "enable" : "disable", port_num + 1);
4441
Olivier Deprez0e641232021-09-23 10:07:05 +02004442 if (enable) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004443 /* Host supports BESL timeout instead of HIRD */
4444 if (udev->usb2_hw_lpm_besl_capable) {
4445 /* if device doesn't have a preferred BESL value use a
4446 * default one which works with mixed HIRD and BESL
4447 * systems. See XHCI_DEFAULT_BESL definition in xhci.h
4448 */
David Brazdil0f672f62019-12-10 10:32:29 +00004449 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004450 if ((field & USB_BESL_SUPPORT) &&
4451 (field & USB_BESL_BASELINE_VALID))
4452 hird = USB_GET_BESL_BASELINE(field);
4453 else
4454 hird = udev->l1_params.besl;
4455
4456 exit_latency = xhci_besl_encoding[hird];
4457 spin_unlock_irqrestore(&xhci->lock, flags);
4458
4459 /* USB 3.0 code dedicate one xhci->lpm_command->in_ctx
4460 * input context for link powermanagement evaluate
4461 * context commands. It is protected by hcd->bandwidth
4462 * mutex and is shared by all devices. We need to set
4463 * the max ext latency in USB 2 BESL LPM as well, so
4464 * use the same mutex and xhci_change_max_exit_latency()
4465 */
4466 mutex_lock(hcd->bandwidth_mutex);
4467 ret = xhci_change_max_exit_latency(xhci, udev,
4468 exit_latency);
4469 mutex_unlock(hcd->bandwidth_mutex);
4470
4471 if (ret < 0)
4472 return ret;
4473 spin_lock_irqsave(&xhci->lock, flags);
4474
4475 hlpm_val = xhci_calculate_usb2_hw_lpm_params(udev);
4476 writel(hlpm_val, hlpm_addr);
4477 /* flush write */
4478 readl(hlpm_addr);
4479 } else {
4480 hird = xhci_calculate_hird_besl(xhci, udev);
4481 }
4482
4483 pm_val &= ~PORT_HIRD_MASK;
4484 pm_val |= PORT_HIRD(hird) | PORT_RWE | PORT_L1DS(udev->slot_id);
4485 writel(pm_val, pm_addr);
4486 pm_val = readl(pm_addr);
4487 pm_val |= PORT_HLE;
4488 writel(pm_val, pm_addr);
4489 /* flush write */
4490 readl(pm_addr);
4491 } else {
4492 pm_val &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK | PORT_L1DS_MASK);
4493 writel(pm_val, pm_addr);
4494 /* flush write */
4495 readl(pm_addr);
4496 if (udev->usb2_hw_lpm_besl_capable) {
4497 spin_unlock_irqrestore(&xhci->lock, flags);
4498 mutex_lock(hcd->bandwidth_mutex);
4499 xhci_change_max_exit_latency(xhci, udev, 0);
4500 mutex_unlock(hcd->bandwidth_mutex);
Olivier Deprez0e641232021-09-23 10:07:05 +02004501 readl_poll_timeout(ports[port_num]->addr, pm_val,
4502 (pm_val & PORT_PLS_MASK) == XDEV_U0,
4503 100, 10000);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004504 return 0;
4505 }
4506 }
4507
4508 spin_unlock_irqrestore(&xhci->lock, flags);
4509 return 0;
4510}
4511
4512/* check if a usb2 port supports a given extened capability protocol
4513 * only USB2 ports extended protocol capability values are cached.
4514 * Return 1 if capability is supported
4515 */
4516static int xhci_check_usb2_port_capability(struct xhci_hcd *xhci, int port,
4517 unsigned capability)
4518{
4519 u32 port_offset, port_count;
4520 int i;
4521
4522 for (i = 0; i < xhci->num_ext_caps; i++) {
4523 if (xhci->ext_caps[i] & capability) {
4524 /* port offsets starts at 1 */
4525 port_offset = XHCI_EXT_PORT_OFF(xhci->ext_caps[i]) - 1;
4526 port_count = XHCI_EXT_PORT_COUNT(xhci->ext_caps[i]);
4527 if (port >= port_offset &&
4528 port < port_offset + port_count)
4529 return 1;
4530 }
4531 }
4532 return 0;
4533}
4534
4535static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4536{
4537 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4538 int portnum = udev->portnum - 1;
4539
David Brazdil0f672f62019-12-10 10:32:29 +00004540 if (hcd->speed >= HCD_USB3 || !udev->lpm_capable)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004541 return 0;
4542
4543 /* we only support lpm for non-hub device connected to root hub yet */
4544 if (!udev->parent || udev->parent->parent ||
4545 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4546 return 0;
4547
4548 if (xhci->hw_lpm_support == 1 &&
4549 xhci_check_usb2_port_capability(
4550 xhci, portnum, XHCI_HLC)) {
4551 udev->usb2_hw_lpm_capable = 1;
4552 udev->l1_params.timeout = XHCI_L1_TIMEOUT;
4553 udev->l1_params.besl = XHCI_DEFAULT_BESL;
4554 if (xhci_check_usb2_port_capability(xhci, portnum,
4555 XHCI_BLC))
4556 udev->usb2_hw_lpm_besl_capable = 1;
4557 }
4558
4559 return 0;
4560}
4561
4562/*---------------------- USB 3.0 Link PM functions ------------------------*/
4563
4564/* Service interval in nanoseconds = 2^(bInterval - 1) * 125us * 1000ns / 1us */
4565static unsigned long long xhci_service_interval_to_ns(
4566 struct usb_endpoint_descriptor *desc)
4567{
4568 return (1ULL << (desc->bInterval - 1)) * 125 * 1000;
4569}
4570
4571static u16 xhci_get_timeout_no_hub_lpm(struct usb_device *udev,
4572 enum usb3_link_state state)
4573{
4574 unsigned long long sel;
4575 unsigned long long pel;
4576 unsigned int max_sel_pel;
4577 char *state_name;
4578
4579 switch (state) {
4580 case USB3_LPM_U1:
4581 /* Convert SEL and PEL stored in nanoseconds to microseconds */
4582 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4583 pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4584 max_sel_pel = USB3_LPM_MAX_U1_SEL_PEL;
4585 state_name = "U1";
4586 break;
4587 case USB3_LPM_U2:
4588 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4589 pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4590 max_sel_pel = USB3_LPM_MAX_U2_SEL_PEL;
4591 state_name = "U2";
4592 break;
4593 default:
4594 dev_warn(&udev->dev, "%s: Can't get timeout for non-U1 or U2 state.\n",
4595 __func__);
4596 return USB3_LPM_DISABLED;
4597 }
4598
4599 if (sel <= max_sel_pel && pel <= max_sel_pel)
4600 return USB3_LPM_DEVICE_INITIATED;
4601
4602 if (sel > max_sel_pel)
4603 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4604 "due to long SEL %llu ms\n",
4605 state_name, sel);
4606 else
4607 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4608 "due to long PEL %llu ms\n",
4609 state_name, pel);
4610 return USB3_LPM_DISABLED;
4611}
4612
4613/* The U1 timeout should be the maximum of the following values:
4614 * - For control endpoints, U1 system exit latency (SEL) * 3
4615 * - For bulk endpoints, U1 SEL * 5
4616 * - For interrupt endpoints:
4617 * - Notification EPs, U1 SEL * 3
4618 * - Periodic EPs, max(105% of bInterval, U1 SEL * 2)
4619 * - For isochronous endpoints, max(105% of bInterval, U1 SEL * 2)
4620 */
4621static unsigned long long xhci_calculate_intel_u1_timeout(
4622 struct usb_device *udev,
4623 struct usb_endpoint_descriptor *desc)
4624{
4625 unsigned long long timeout_ns;
4626 int ep_type;
4627 int intr_type;
4628
4629 ep_type = usb_endpoint_type(desc);
4630 switch (ep_type) {
4631 case USB_ENDPOINT_XFER_CONTROL:
4632 timeout_ns = udev->u1_params.sel * 3;
4633 break;
4634 case USB_ENDPOINT_XFER_BULK:
4635 timeout_ns = udev->u1_params.sel * 5;
4636 break;
4637 case USB_ENDPOINT_XFER_INT:
4638 intr_type = usb_endpoint_interrupt_type(desc);
4639 if (intr_type == USB_ENDPOINT_INTR_NOTIFICATION) {
4640 timeout_ns = udev->u1_params.sel * 3;
4641 break;
4642 }
4643 /* Otherwise the calculation is the same as isoc eps */
4644 /* fall through */
4645 case USB_ENDPOINT_XFER_ISOC:
4646 timeout_ns = xhci_service_interval_to_ns(desc);
4647 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns * 105, 100);
4648 if (timeout_ns < udev->u1_params.sel * 2)
4649 timeout_ns = udev->u1_params.sel * 2;
4650 break;
4651 default:
4652 return 0;
4653 }
4654
4655 return timeout_ns;
4656}
4657
4658/* Returns the hub-encoded U1 timeout value. */
4659static u16 xhci_calculate_u1_timeout(struct xhci_hcd *xhci,
4660 struct usb_device *udev,
4661 struct usb_endpoint_descriptor *desc)
4662{
4663 unsigned long long timeout_ns;
4664
4665 /* Prevent U1 if service interval is shorter than U1 exit latency */
4666 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4667 if (xhci_service_interval_to_ns(desc) <= udev->u1_params.mel) {
4668 dev_dbg(&udev->dev, "Disable U1, ESIT shorter than exit latency\n");
4669 return USB3_LPM_DISABLED;
4670 }
4671 }
4672
4673 if (xhci->quirks & XHCI_INTEL_HOST)
4674 timeout_ns = xhci_calculate_intel_u1_timeout(udev, desc);
4675 else
4676 timeout_ns = udev->u1_params.sel;
4677
4678 /* The U1 timeout is encoded in 1us intervals.
4679 * Don't return a timeout of zero, because that's USB3_LPM_DISABLED.
4680 */
4681 if (timeout_ns == USB3_LPM_DISABLED)
4682 timeout_ns = 1;
4683 else
4684 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 1000);
4685
4686 /* If the necessary timeout value is bigger than what we can set in the
4687 * USB 3.0 hub, we have to disable hub-initiated U1.
4688 */
4689 if (timeout_ns <= USB3_LPM_U1_MAX_TIMEOUT)
4690 return timeout_ns;
4691 dev_dbg(&udev->dev, "Hub-initiated U1 disabled "
4692 "due to long timeout %llu ms\n", timeout_ns);
4693 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U1);
4694}
4695
4696/* The U2 timeout should be the maximum of:
4697 * - 10 ms (to avoid the bandwidth impact on the scheduler)
4698 * - largest bInterval of any active periodic endpoint (to avoid going
4699 * into lower power link states between intervals).
4700 * - the U2 Exit Latency of the device
4701 */
4702static unsigned long long xhci_calculate_intel_u2_timeout(
4703 struct usb_device *udev,
4704 struct usb_endpoint_descriptor *desc)
4705{
4706 unsigned long long timeout_ns;
4707 unsigned long long u2_del_ns;
4708
4709 timeout_ns = 10 * 1000 * 1000;
4710
4711 if ((usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) &&
4712 (xhci_service_interval_to_ns(desc) > timeout_ns))
4713 timeout_ns = xhci_service_interval_to_ns(desc);
4714
4715 u2_del_ns = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat) * 1000ULL;
4716 if (u2_del_ns > timeout_ns)
4717 timeout_ns = u2_del_ns;
4718
4719 return timeout_ns;
4720}
4721
4722/* Returns the hub-encoded U2 timeout value. */
4723static u16 xhci_calculate_u2_timeout(struct xhci_hcd *xhci,
4724 struct usb_device *udev,
4725 struct usb_endpoint_descriptor *desc)
4726{
4727 unsigned long long timeout_ns;
4728
4729 /* Prevent U2 if service interval is shorter than U2 exit latency */
4730 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4731 if (xhci_service_interval_to_ns(desc) <= udev->u2_params.mel) {
4732 dev_dbg(&udev->dev, "Disable U2, ESIT shorter than exit latency\n");
4733 return USB3_LPM_DISABLED;
4734 }
4735 }
4736
4737 if (xhci->quirks & XHCI_INTEL_HOST)
4738 timeout_ns = xhci_calculate_intel_u2_timeout(udev, desc);
4739 else
4740 timeout_ns = udev->u2_params.sel;
4741
4742 /* The U2 timeout is encoded in 256us intervals */
4743 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 256 * 1000);
4744 /* If the necessary timeout value is bigger than what we can set in the
4745 * USB 3.0 hub, we have to disable hub-initiated U2.
4746 */
4747 if (timeout_ns <= USB3_LPM_U2_MAX_TIMEOUT)
4748 return timeout_ns;
4749 dev_dbg(&udev->dev, "Hub-initiated U2 disabled "
4750 "due to long timeout %llu ms\n", timeout_ns);
4751 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U2);
4752}
4753
4754static u16 xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4755 struct usb_device *udev,
4756 struct usb_endpoint_descriptor *desc,
4757 enum usb3_link_state state,
4758 u16 *timeout)
4759{
4760 if (state == USB3_LPM_U1)
4761 return xhci_calculate_u1_timeout(xhci, udev, desc);
4762 else if (state == USB3_LPM_U2)
4763 return xhci_calculate_u2_timeout(xhci, udev, desc);
4764
4765 return USB3_LPM_DISABLED;
4766}
4767
4768static int xhci_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4769 struct usb_device *udev,
4770 struct usb_endpoint_descriptor *desc,
4771 enum usb3_link_state state,
4772 u16 *timeout)
4773{
4774 u16 alt_timeout;
4775
4776 alt_timeout = xhci_call_host_update_timeout_for_endpoint(xhci, udev,
4777 desc, state, timeout);
4778
David Brazdil0f672f62019-12-10 10:32:29 +00004779 /* If we found we can't enable hub-initiated LPM, and
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004780 * the U1 or U2 exit latency was too high to allow
David Brazdil0f672f62019-12-10 10:32:29 +00004781 * device-initiated LPM as well, then we will disable LPM
4782 * for this device, so stop searching any further.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004783 */
David Brazdil0f672f62019-12-10 10:32:29 +00004784 if (alt_timeout == USB3_LPM_DISABLED) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004785 *timeout = alt_timeout;
4786 return -E2BIG;
4787 }
4788 if (alt_timeout > *timeout)
4789 *timeout = alt_timeout;
4790 return 0;
4791}
4792
4793static int xhci_update_timeout_for_interface(struct xhci_hcd *xhci,
4794 struct usb_device *udev,
4795 struct usb_host_interface *alt,
4796 enum usb3_link_state state,
4797 u16 *timeout)
4798{
4799 int j;
4800
4801 for (j = 0; j < alt->desc.bNumEndpoints; j++) {
4802 if (xhci_update_timeout_for_endpoint(xhci, udev,
4803 &alt->endpoint[j].desc, state, timeout))
4804 return -E2BIG;
4805 continue;
4806 }
4807 return 0;
4808}
4809
4810static int xhci_check_intel_tier_policy(struct usb_device *udev,
4811 enum usb3_link_state state)
4812{
4813 struct usb_device *parent;
4814 unsigned int num_hubs;
4815
4816 if (state == USB3_LPM_U2)
4817 return 0;
4818
4819 /* Don't enable U1 if the device is on a 2nd tier hub or lower. */
4820 for (parent = udev->parent, num_hubs = 0; parent->parent;
4821 parent = parent->parent)
4822 num_hubs++;
4823
4824 if (num_hubs < 2)
4825 return 0;
4826
4827 dev_dbg(&udev->dev, "Disabling U1 link state for device"
4828 " below second-tier hub.\n");
4829 dev_dbg(&udev->dev, "Plug device into first-tier hub "
4830 "to decrease power consumption.\n");
4831 return -E2BIG;
4832}
4833
4834static int xhci_check_tier_policy(struct xhci_hcd *xhci,
4835 struct usb_device *udev,
4836 enum usb3_link_state state)
4837{
4838 if (xhci->quirks & XHCI_INTEL_HOST)
4839 return xhci_check_intel_tier_policy(udev, state);
4840 else
4841 return 0;
4842}
4843
4844/* Returns the U1 or U2 timeout that should be enabled.
4845 * If the tier check or timeout setting functions return with a non-zero exit
4846 * code, that means the timeout value has been finalized and we shouldn't look
4847 * at any more endpoints.
4848 */
4849static u16 xhci_calculate_lpm_timeout(struct usb_hcd *hcd,
4850 struct usb_device *udev, enum usb3_link_state state)
4851{
4852 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4853 struct usb_host_config *config;
4854 char *state_name;
4855 int i;
4856 u16 timeout = USB3_LPM_DISABLED;
4857
4858 if (state == USB3_LPM_U1)
4859 state_name = "U1";
4860 else if (state == USB3_LPM_U2)
4861 state_name = "U2";
4862 else {
4863 dev_warn(&udev->dev, "Can't enable unknown link state %i\n",
4864 state);
4865 return timeout;
4866 }
4867
4868 if (xhci_check_tier_policy(xhci, udev, state) < 0)
4869 return timeout;
4870
4871 /* Gather some information about the currently installed configuration
4872 * and alternate interface settings.
4873 */
4874 if (xhci_update_timeout_for_endpoint(xhci, udev, &udev->ep0.desc,
4875 state, &timeout))
4876 return timeout;
4877
4878 config = udev->actconfig;
4879 if (!config)
4880 return timeout;
4881
4882 for (i = 0; i < config->desc.bNumInterfaces; i++) {
4883 struct usb_driver *driver;
4884 struct usb_interface *intf = config->interface[i];
4885
4886 if (!intf)
4887 continue;
4888
4889 /* Check if any currently bound drivers want hub-initiated LPM
4890 * disabled.
4891 */
4892 if (intf->dev.driver) {
4893 driver = to_usb_driver(intf->dev.driver);
4894 if (driver && driver->disable_hub_initiated_lpm) {
David Brazdil0f672f62019-12-10 10:32:29 +00004895 dev_dbg(&udev->dev, "Hub-initiated %s disabled at request of driver %s\n",
4896 state_name, driver->name);
4897 timeout = xhci_get_timeout_no_hub_lpm(udev,
4898 state);
4899 if (timeout == USB3_LPM_DISABLED)
4900 return timeout;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004901 }
4902 }
4903
4904 /* Not sure how this could happen... */
4905 if (!intf->cur_altsetting)
4906 continue;
4907
4908 if (xhci_update_timeout_for_interface(xhci, udev,
4909 intf->cur_altsetting,
4910 state, &timeout))
4911 return timeout;
4912 }
4913 return timeout;
4914}
4915
4916static int calculate_max_exit_latency(struct usb_device *udev,
4917 enum usb3_link_state state_changed,
4918 u16 hub_encoded_timeout)
4919{
4920 unsigned long long u1_mel_us = 0;
4921 unsigned long long u2_mel_us = 0;
4922 unsigned long long mel_us = 0;
4923 bool disabling_u1;
4924 bool disabling_u2;
4925 bool enabling_u1;
4926 bool enabling_u2;
4927
4928 disabling_u1 = (state_changed == USB3_LPM_U1 &&
4929 hub_encoded_timeout == USB3_LPM_DISABLED);
4930 disabling_u2 = (state_changed == USB3_LPM_U2 &&
4931 hub_encoded_timeout == USB3_LPM_DISABLED);
4932
4933 enabling_u1 = (state_changed == USB3_LPM_U1 &&
4934 hub_encoded_timeout != USB3_LPM_DISABLED);
4935 enabling_u2 = (state_changed == USB3_LPM_U2 &&
4936 hub_encoded_timeout != USB3_LPM_DISABLED);
4937
4938 /* If U1 was already enabled and we're not disabling it,
4939 * or we're going to enable U1, account for the U1 max exit latency.
4940 */
4941 if ((udev->u1_params.timeout != USB3_LPM_DISABLED && !disabling_u1) ||
4942 enabling_u1)
4943 u1_mel_us = DIV_ROUND_UP(udev->u1_params.mel, 1000);
4944 if ((udev->u2_params.timeout != USB3_LPM_DISABLED && !disabling_u2) ||
4945 enabling_u2)
4946 u2_mel_us = DIV_ROUND_UP(udev->u2_params.mel, 1000);
4947
4948 if (u1_mel_us > u2_mel_us)
4949 mel_us = u1_mel_us;
4950 else
4951 mel_us = u2_mel_us;
4952 /* xHCI host controller max exit latency field is only 16 bits wide. */
4953 if (mel_us > MAX_EXIT) {
4954 dev_warn(&udev->dev, "Link PM max exit latency of %lluus "
4955 "is too big.\n", mel_us);
4956 return -E2BIG;
4957 }
4958 return mel_us;
4959}
4960
4961/* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
4962static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
4963 struct usb_device *udev, enum usb3_link_state state)
4964{
4965 struct xhci_hcd *xhci;
4966 u16 hub_encoded_timeout;
4967 int mel;
4968 int ret;
4969
4970 xhci = hcd_to_xhci(hcd);
4971 /* The LPM timeout values are pretty host-controller specific, so don't
4972 * enable hub-initiated timeouts unless the vendor has provided
4973 * information about their timeout algorithm.
4974 */
4975 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
4976 !xhci->devs[udev->slot_id])
4977 return USB3_LPM_DISABLED;
4978
4979 hub_encoded_timeout = xhci_calculate_lpm_timeout(hcd, udev, state);
4980 mel = calculate_max_exit_latency(udev, state, hub_encoded_timeout);
4981 if (mel < 0) {
4982 /* Max Exit Latency is too big, disable LPM. */
4983 hub_encoded_timeout = USB3_LPM_DISABLED;
4984 mel = 0;
4985 }
4986
4987 ret = xhci_change_max_exit_latency(xhci, udev, mel);
4988 if (ret)
4989 return ret;
4990 return hub_encoded_timeout;
4991}
4992
4993static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
4994 struct usb_device *udev, enum usb3_link_state state)
4995{
4996 struct xhci_hcd *xhci;
4997 u16 mel;
4998
4999 xhci = hcd_to_xhci(hcd);
5000 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
5001 !xhci->devs[udev->slot_id])
5002 return 0;
5003
5004 mel = calculate_max_exit_latency(udev, state, USB3_LPM_DISABLED);
5005 return xhci_change_max_exit_latency(xhci, udev, mel);
5006}
5007#else /* CONFIG_PM */
5008
5009static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
5010 struct usb_device *udev, int enable)
5011{
5012 return 0;
5013}
5014
5015static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
5016{
5017 return 0;
5018}
5019
5020static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
5021 struct usb_device *udev, enum usb3_link_state state)
5022{
5023 return USB3_LPM_DISABLED;
5024}
5025
5026static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
5027 struct usb_device *udev, enum usb3_link_state state)
5028{
5029 return 0;
5030}
5031#endif /* CONFIG_PM */
5032
5033/*-------------------------------------------------------------------------*/
5034
5035/* Once a hub descriptor is fetched for a device, we need to update the xHC's
5036 * internal data structures for the device.
5037 */
5038static int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
5039 struct usb_tt *tt, gfp_t mem_flags)
5040{
5041 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5042 struct xhci_virt_device *vdev;
5043 struct xhci_command *config_cmd;
5044 struct xhci_input_control_ctx *ctrl_ctx;
5045 struct xhci_slot_ctx *slot_ctx;
5046 unsigned long flags;
5047 unsigned think_time;
5048 int ret;
5049
5050 /* Ignore root hubs */
5051 if (!hdev->parent)
5052 return 0;
5053
5054 vdev = xhci->devs[hdev->slot_id];
5055 if (!vdev) {
5056 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
5057 return -EINVAL;
5058 }
5059
5060 config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
5061 if (!config_cmd)
5062 return -ENOMEM;
5063
5064 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
5065 if (!ctrl_ctx) {
5066 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
5067 __func__);
5068 xhci_free_command(xhci, config_cmd);
5069 return -ENOMEM;
5070 }
5071
5072 spin_lock_irqsave(&xhci->lock, flags);
5073 if (hdev->speed == USB_SPEED_HIGH &&
5074 xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
5075 xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
5076 xhci_free_command(xhci, config_cmd);
5077 spin_unlock_irqrestore(&xhci->lock, flags);
5078 return -ENOMEM;
5079 }
5080
5081 xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
5082 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
5083 slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
5084 slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
5085 /*
5086 * refer to section 6.2.2: MTT should be 0 for full speed hub,
5087 * but it may be already set to 1 when setup an xHCI virtual
5088 * device, so clear it anyway.
5089 */
5090 if (tt->multi)
5091 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
5092 else if (hdev->speed == USB_SPEED_FULL)
5093 slot_ctx->dev_info &= cpu_to_le32(~DEV_MTT);
5094
5095 if (xhci->hci_version > 0x95) {
5096 xhci_dbg(xhci, "xHCI version %x needs hub "
5097 "TT think time and number of ports\n",
5098 (unsigned int) xhci->hci_version);
5099 slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
5100 /* Set TT think time - convert from ns to FS bit times.
5101 * 0 = 8 FS bit times, 1 = 16 FS bit times,
5102 * 2 = 24 FS bit times, 3 = 32 FS bit times.
5103 *
5104 * xHCI 1.0: this field shall be 0 if the device is not a
5105 * High-spped hub.
5106 */
5107 think_time = tt->think_time;
5108 if (think_time != 0)
5109 think_time = (think_time / 666) - 1;
5110 if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
5111 slot_ctx->tt_info |=
5112 cpu_to_le32(TT_THINK_TIME(think_time));
5113 } else {
5114 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
5115 "TT think time or number of ports\n",
5116 (unsigned int) xhci->hci_version);
5117 }
5118 slot_ctx->dev_state = 0;
5119 spin_unlock_irqrestore(&xhci->lock, flags);
5120
5121 xhci_dbg(xhci, "Set up %s for hub device.\n",
5122 (xhci->hci_version > 0x95) ?
5123 "configure endpoint" : "evaluate context");
5124
5125 /* Issue and wait for the configure endpoint or
5126 * evaluate context command.
5127 */
5128 if (xhci->hci_version > 0x95)
5129 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5130 false, false);
5131 else
5132 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5133 true, false);
5134
5135 xhci_free_command(xhci, config_cmd);
5136 return ret;
5137}
5138
5139static int xhci_get_frame(struct usb_hcd *hcd)
5140{
5141 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5142 /* EHCI mods by the periodic size. Why? */
5143 return readl(&xhci->run_regs->microframe_index) >> 3;
5144}
5145
5146int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
5147{
5148 struct xhci_hcd *xhci;
5149 /*
5150 * TODO: Check with DWC3 clients for sysdev according to
5151 * quirks
5152 */
5153 struct device *dev = hcd->self.sysdev;
5154 unsigned int minor_rev;
5155 int retval;
5156
5157 /* Accept arbitrarily long scatter-gather lists */
5158 hcd->self.sg_tablesize = ~0;
5159
5160 /* support to build packet from discontinuous buffers */
5161 hcd->self.no_sg_constraint = 1;
5162
5163 /* XHCI controllers don't stop the ep queue on short packets :| */
5164 hcd->self.no_stop_on_short = 1;
5165
5166 xhci = hcd_to_xhci(hcd);
5167
5168 if (usb_hcd_is_primary_hcd(hcd)) {
5169 xhci->main_hcd = hcd;
5170 xhci->usb2_rhub.hcd = hcd;
5171 /* Mark the first roothub as being USB 2.0.
5172 * The xHCI driver will register the USB 3.0 roothub.
5173 */
5174 hcd->speed = HCD_USB2;
5175 hcd->self.root_hub->speed = USB_SPEED_HIGH;
5176 /*
5177 * USB 2.0 roothub under xHCI has an integrated TT,
5178 * (rate matching hub) as opposed to having an OHCI/UHCI
5179 * companion controller.
5180 */
5181 hcd->has_tt = 1;
5182 } else {
5183 /*
David Brazdil0f672f62019-12-10 10:32:29 +00005184 * Early xHCI 1.1 spec did not mention USB 3.1 capable hosts
5185 * should return 0x31 for sbrn, or that the minor revision
5186 * is a two digit BCD containig minor and sub-minor numbers.
5187 * This was later clarified in xHCI 1.2.
5188 *
5189 * Some USB 3.1 capable hosts therefore have sbrn 0x30, and
5190 * minor revision set to 0x1 instead of 0x10.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005191 */
David Brazdil0f672f62019-12-10 10:32:29 +00005192 if (xhci->usb3_rhub.min_rev == 0x1)
5193 minor_rev = 1;
5194 else
5195 minor_rev = xhci->usb3_rhub.min_rev / 0x10;
5196
5197 switch (minor_rev) {
5198 case 2:
5199 hcd->speed = HCD_USB32;
5200 hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5201 hcd->self.root_hub->rx_lanes = 2;
5202 hcd->self.root_hub->tx_lanes = 2;
5203 break;
5204 case 1:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005205 hcd->speed = HCD_USB31;
5206 hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
David Brazdil0f672f62019-12-10 10:32:29 +00005207 break;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005208 }
David Brazdil0f672f62019-12-10 10:32:29 +00005209 xhci_info(xhci, "Host supports USB 3.%x %sSuperSpeed\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005210 minor_rev,
David Brazdil0f672f62019-12-10 10:32:29 +00005211 minor_rev ? "Enhanced " : "");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005212
5213 xhci->usb3_rhub.hcd = hcd;
5214 /* xHCI private pointer was set in xhci_pci_probe for the second
5215 * registered roothub.
5216 */
5217 return 0;
5218 }
5219
5220 mutex_init(&xhci->mutex);
5221 xhci->cap_regs = hcd->regs;
5222 xhci->op_regs = hcd->regs +
5223 HC_LENGTH(readl(&xhci->cap_regs->hc_capbase));
5224 xhci->run_regs = hcd->regs +
5225 (readl(&xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
5226 /* Cache read-only capability registers */
5227 xhci->hcs_params1 = readl(&xhci->cap_regs->hcs_params1);
5228 xhci->hcs_params2 = readl(&xhci->cap_regs->hcs_params2);
5229 xhci->hcs_params3 = readl(&xhci->cap_regs->hcs_params3);
5230 xhci->hcc_params = readl(&xhci->cap_regs->hc_capbase);
5231 xhci->hci_version = HC_VERSION(xhci->hcc_params);
5232 xhci->hcc_params = readl(&xhci->cap_regs->hcc_params);
5233 if (xhci->hci_version > 0x100)
5234 xhci->hcc_params2 = readl(&xhci->cap_regs->hcc_params2);
5235
5236 xhci->quirks |= quirks;
5237
5238 get_quirks(dev, xhci);
5239
5240 /* In xhci controllers which follow xhci 1.0 spec gives a spurious
5241 * success event after a short transfer. This quirk will ignore such
5242 * spurious event.
5243 */
5244 if (xhci->hci_version > 0x96)
5245 xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
5246
5247 /* Make sure the HC is halted. */
5248 retval = xhci_halt(xhci);
5249 if (retval)
5250 return retval;
5251
5252 xhci_zero_64b_regs(xhci);
5253
5254 xhci_dbg(xhci, "Resetting HCD\n");
5255 /* Reset the internal HC memory state and registers. */
5256 retval = xhci_reset(xhci);
5257 if (retval)
5258 return retval;
5259 xhci_dbg(xhci, "Reset complete\n");
5260
5261 /*
5262 * On some xHCI controllers (e.g. R-Car SoCs), the AC64 bit (bit 0)
5263 * of HCCPARAMS1 is set to 1. However, the xHCs don't support 64-bit
5264 * address memory pointers actually. So, this driver clears the AC64
5265 * bit of xhci->hcc_params to call dma_set_coherent_mask(dev,
5266 * DMA_BIT_MASK(32)) in this xhci_gen_setup().
5267 */
5268 if (xhci->quirks & XHCI_NO_64BIT_SUPPORT)
5269 xhci->hcc_params &= ~BIT(0);
5270
5271 /* Set dma_mask and coherent_dma_mask to 64-bits,
5272 * if xHC supports 64-bit addressing */
5273 if (HCC_64BIT_ADDR(xhci->hcc_params) &&
5274 !dma_set_mask(dev, DMA_BIT_MASK(64))) {
5275 xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
5276 dma_set_coherent_mask(dev, DMA_BIT_MASK(64));
5277 } else {
5278 /*
5279 * This is to avoid error in cases where a 32-bit USB
5280 * controller is used on a 64-bit capable system.
5281 */
5282 retval = dma_set_mask(dev, DMA_BIT_MASK(32));
5283 if (retval)
5284 return retval;
5285 xhci_dbg(xhci, "Enabling 32-bit DMA addresses.\n");
5286 dma_set_coherent_mask(dev, DMA_BIT_MASK(32));
5287 }
5288
5289 xhci_dbg(xhci, "Calling HCD init\n");
5290 /* Initialize HCD and host controller data structures. */
5291 retval = xhci_init(hcd);
5292 if (retval)
5293 return retval;
5294 xhci_dbg(xhci, "Called HCD init\n");
5295
5296 xhci_info(xhci, "hcc params 0x%08x hci version 0x%x quirks 0x%016llx\n",
5297 xhci->hcc_params, xhci->hci_version, xhci->quirks);
5298
5299 return 0;
5300}
5301EXPORT_SYMBOL_GPL(xhci_gen_setup);
5302
David Brazdil0f672f62019-12-10 10:32:29 +00005303static void xhci_clear_tt_buffer_complete(struct usb_hcd *hcd,
5304 struct usb_host_endpoint *ep)
5305{
5306 struct xhci_hcd *xhci;
5307 struct usb_device *udev;
5308 unsigned int slot_id;
5309 unsigned int ep_index;
5310 unsigned long flags;
5311
5312 xhci = hcd_to_xhci(hcd);
5313
5314 spin_lock_irqsave(&xhci->lock, flags);
5315 udev = (struct usb_device *)ep->hcpriv;
5316 slot_id = udev->slot_id;
5317 ep_index = xhci_get_endpoint_index(&ep->desc);
5318
5319 xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_CLEARING_TT;
5320 xhci_ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
5321 spin_unlock_irqrestore(&xhci->lock, flags);
5322}
5323
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005324static const struct hc_driver xhci_hc_driver = {
5325 .description = "xhci-hcd",
5326 .product_desc = "xHCI Host Controller",
5327 .hcd_priv_size = sizeof(struct xhci_hcd),
5328
5329 /*
5330 * generic hardware linkage
5331 */
5332 .irq = xhci_irq,
David Brazdil0f672f62019-12-10 10:32:29 +00005333 .flags = HCD_MEMORY | HCD_DMA | HCD_USB3 | HCD_SHARED,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005334
5335 /*
5336 * basic lifecycle operations
5337 */
5338 .reset = NULL, /* set in xhci_init_driver() */
5339 .start = xhci_run,
5340 .stop = xhci_stop,
5341 .shutdown = xhci_shutdown,
5342
5343 /*
5344 * managing i/o requests and associated device resources
5345 */
David Brazdil0f672f62019-12-10 10:32:29 +00005346 .map_urb_for_dma = xhci_map_urb_for_dma,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005347 .urb_enqueue = xhci_urb_enqueue,
5348 .urb_dequeue = xhci_urb_dequeue,
5349 .alloc_dev = xhci_alloc_dev,
5350 .free_dev = xhci_free_dev,
5351 .alloc_streams = xhci_alloc_streams,
5352 .free_streams = xhci_free_streams,
5353 .add_endpoint = xhci_add_endpoint,
5354 .drop_endpoint = xhci_drop_endpoint,
David Brazdil0f672f62019-12-10 10:32:29 +00005355 .endpoint_disable = xhci_endpoint_disable,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005356 .endpoint_reset = xhci_endpoint_reset,
5357 .check_bandwidth = xhci_check_bandwidth,
5358 .reset_bandwidth = xhci_reset_bandwidth,
5359 .address_device = xhci_address_device,
5360 .enable_device = xhci_enable_device,
5361 .update_hub_device = xhci_update_hub_device,
5362 .reset_device = xhci_discover_or_reset_device,
5363
5364 /*
5365 * scheduling support
5366 */
5367 .get_frame_number = xhci_get_frame,
5368
5369 /*
5370 * root hub support
5371 */
5372 .hub_control = xhci_hub_control,
5373 .hub_status_data = xhci_hub_status_data,
5374 .bus_suspend = xhci_bus_suspend,
5375 .bus_resume = xhci_bus_resume,
5376 .get_resuming_ports = xhci_get_resuming_ports,
5377
5378 /*
5379 * call back when device connected and addressed
5380 */
5381 .update_device = xhci_update_device,
5382 .set_usb2_hw_lpm = xhci_set_usb2_hardware_lpm,
5383 .enable_usb3_lpm_timeout = xhci_enable_usb3_lpm_timeout,
5384 .disable_usb3_lpm_timeout = xhci_disable_usb3_lpm_timeout,
5385 .find_raw_port_number = xhci_find_raw_port_number,
David Brazdil0f672f62019-12-10 10:32:29 +00005386 .clear_tt_buffer_complete = xhci_clear_tt_buffer_complete,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005387};
5388
5389void xhci_init_driver(struct hc_driver *drv,
5390 const struct xhci_driver_overrides *over)
5391{
5392 BUG_ON(!over);
5393
5394 /* Copy the generic table to drv then apply the overrides */
5395 *drv = xhci_hc_driver;
5396
5397 if (over) {
5398 drv->hcd_priv_size += over->extra_priv_size;
5399 if (over->reset)
5400 drv->reset = over->reset;
5401 if (over->start)
5402 drv->start = over->start;
Olivier Deprez0e641232021-09-23 10:07:05 +02005403 if (over->check_bandwidth)
5404 drv->check_bandwidth = over->check_bandwidth;
5405 if (over->reset_bandwidth)
5406 drv->reset_bandwidth = over->reset_bandwidth;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005407 }
5408}
5409EXPORT_SYMBOL_GPL(xhci_init_driver);
5410
5411MODULE_DESCRIPTION(DRIVER_DESC);
5412MODULE_AUTHOR(DRIVER_AUTHOR);
5413MODULE_LICENSE("GPL");
5414
5415static int __init xhci_hcd_init(void)
5416{
5417 /*
5418 * Check the compiler generated sizes of structures that must be laid
5419 * out in specific ways for hardware access.
5420 */
5421 BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
5422 BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
5423 BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
5424 /* xhci_device_control has eight fields, and also
5425 * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
5426 */
5427 BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
5428 BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
5429 BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
5430 BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 8*32/8);
5431 BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
5432 /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
5433 BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
5434
5435 if (usb_disabled())
5436 return -ENODEV;
5437
5438 xhci_debugfs_create_root();
5439
5440 return 0;
5441}
5442
5443/*
5444 * If an init function is provided, an exit function must also be provided
5445 * to allow module unload.
5446 */
5447static void __exit xhci_hcd_fini(void)
5448{
5449 xhci_debugfs_remove_root();
5450}
5451
5452module_init(xhci_hcd_init);
5453module_exit(xhci_hcd_fini);