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