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 */
36 static int link_quirk;
37 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
38 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
39
40 static unsigned long long quirks;
41 module_param(quirks, ullong, S_IRUGO);
42 MODULE_PARM_DESC(quirks, "Bit flags for quirks to be enabled as default");
43
td_on_ring(struct xhci_td * td,struct xhci_ring * ring)44 static 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 */
xhci_handshake(void __iomem * ptr,u32 mask,u32 done,u64 timeout_us)72 int 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 */
xhci_quiesce(struct xhci_hcd * xhci)90 void xhci_quiesce(struct xhci_hcd *xhci)
91 {
92 u32 halted;
93 u32 cmd;
94 u32 mask;
95
96 mask = ~(XHCI_IRQS);
97 halted = readl(&xhci->op_regs->status) & STS_HALT;
98 if (!halted)
99 mask &= ~CMD_RUN;
100
101 cmd = readl(&xhci->op_regs->command);
102 cmd &= mask;
103 writel(cmd, &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 */
xhci_halt(struct xhci_hcd * xhci)114 int xhci_halt(struct xhci_hcd *xhci)
115 {
116 int ret;
117
118 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Halt the HC");
119 xhci_quiesce(xhci);
120
121 ret = xhci_handshake(&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 */
xhci_start(struct xhci_hcd * xhci)138 int xhci_start(struct xhci_hcd *xhci)
139 {
140 u32 temp;
141 int ret;
142
143 temp = readl(&xhci->op_regs->command);
144 temp |= (CMD_RUN);
145 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "// Turn on HC, cmd = 0x%x.",
146 temp);
147 writel(temp, &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(&xhci->op_regs->status,
154 STS_HALT, 0, XHCI_MAX_HALT_USEC);
155 if (ret == -ETIMEDOUT)
156 xhci_err(xhci, "Host took too long to start, "
157 "waited %u microseconds.\n",
158 XHCI_MAX_HALT_USEC);
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(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 */
xhci_reset(struct xhci_hcd * xhci,u64 timeout_us)175 int xhci_reset(struct xhci_hcd *xhci, u64 timeout_us)
176 {
177 u32 command;
178 u32 state;
179 int ret;
180
181 state = readl(&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_xhci_dbg_init, "// Reset the HC");
195 command = readl(&xhci->op_regs->command);
196 command |= CMD_RESET;
197 writel(command, &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(1000);
208
209 ret = xhci_handshake(&xhci->op_regs->command, CMD_RESET, 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_xhci_dbg_init,
217 "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(&xhci->op_regs->status, STS_CNR, 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
xhci_zero_64b_regs(struct xhci_hcd * xhci)234 static 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(&xhci->op_regs->command);
265 val &= ~CMD_HSEIE;
266 writel(val, &xhci->op_regs->command);
267
268 /* Clear HSE (aka FATAL) */
269 val = readl(&xhci->op_regs->status);
270 val |= STS_FATAL;
271 writel(val, &xhci->op_regs->status);
272
273 /* Now zero the registers, and brace for impact */
274 val = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
275 if (upper_32_bits(val))
276 xhci_write_64(xhci, 0, &xhci->op_regs->dcbaa_ptr);
277 val = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
278 if (upper_32_bits(val))
279 xhci_write_64(xhci, 0, &xhci->op_regs->cmd_ring);
280
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, &ir->erst_base);
289 if (upper_32_bits(val))
290 xhci_write_64(xhci, 0, &ir->erst_base);
291 val= xhci_read_64(xhci, &ir->erst_dequeue);
292 if (upper_32_bits(val))
293 xhci_write_64(xhci, 0, &ir->erst_dequeue);
294 }
295
296 /* Wait for the fault to appear. It will be cleared on reset */
297 err = xhci_handshake(&xhci->op_regs->status,
298 STS_FATAL, STS_FATAL,
299 XHCI_MAX_HALT_USEC);
300 if (!err)
301 xhci_info(xhci, "Fault detected\n");
302 }
303
xhci_enable_interrupter(struct xhci_interrupter * ir)304 int 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(&ir->ir_set->iman);
312 iman &= ~IMAN_IP;
313 iman |= IMAN_IE;
314 writel(iman, &ir->ir_set->iman);
315
316 /* Read operation to guarantee the write has been flushed from posted buffers */
317 readl(&ir->ir_set->iman);
318 return 0;
319 }
320
xhci_disable_interrupter(struct xhci_hcd * xhci,struct xhci_interrupter * ir)321 int 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(&ir->ir_set->iman);
329 iman &= ~IMAN_IP;
330 iman &= ~IMAN_IE;
331 writel(iman, &ir->ir_set->iman);
332
333 iman = readl(&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 */
xhci_set_interrupter_moderation(struct xhci_interrupter * ir,u32 imod_interval)341 int 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(&ir->ir_set->imod);
353 imod &= ~IMODI_MASK;
354 imod |= imod_interval;
355 writel(imod, &ir->ir_set->imod);
356
357 return 0;
358 }
359
compliance_mode_recovery(struct timer_list * t)360 static 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(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_xhci_dbg_quirks,
383 "Compliance mode detected->port %d",
384 i + 1);
385 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
386 "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(&xhci->comp_mode_recovery_timer,
397 jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
398 }
399
400 /*
401 * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
402 * that causes ports behind that hardware to enter compliance mode sometimes.
403 * The quirk creates a timer that polls every 2 seconds the link state of
404 * each host controller's port and recovers it by issuing a Warm reset
405 * if Compliance mode is detected, otherwise the port will become "dead" (no
406 * device connections or disconnections will be detected anymore). Becasue no
407 * status event is generated when entering compliance mode (per xhci spec),
408 * this quirk is needed on systems that have the failing hardware installed.
409 */
compliance_mode_recovery_timer_init(struct xhci_hcd * xhci)410 static 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(&xhci->comp_mode_recovery_timer);
419 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
420 "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 */
xhci_compliance_mode_recovery_timer_quirk_check(void)429 static 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(DMI_PRODUCT_NAME);
434 dmi_sys_vendor = dmi_get_system_info(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
xhci_all_ports_seen_u0(struct xhci_hcd * xhci)450 static 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
xhci_hcd_page_size(struct xhci_hcd * xhci)455 static void xhci_hcd_page_size(struct xhci_hcd *xhci)
456 {
457 u32 page_size;
458
459 page_size = readl(&xhci->op_regs->page_size) & XHCI_PAGE_SIZE_MASK;
460 if (!is_power_of_2(page_size)) {
461 xhci_warn(xhci, "Invalid page size register = 0x%x\n", page_size);
462 /* Fallback to 4K page size, since that's common */
463 page_size = 1;
464 }
465
466 xhci->page_size = page_size << 12;
467 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "HCD page size set to %iK",
468 xhci->page_size >> 10);
469 }
470
xhci_enable_max_dev_slots(struct xhci_hcd * xhci)471 static void xhci_enable_max_dev_slots(struct xhci_hcd *xhci)
472 {
473 u32 config_reg;
474 u32 max_slots;
475
476 max_slots = HCS_MAX_SLOTS(xhci->hcs_params1);
477 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "xHC can handle at most %d device slots",
478 max_slots);
479
480 config_reg = readl(&xhci->op_regs->config_reg);
481 config_reg &= ~HCS_SLOTS_MASK;
482 config_reg |= max_slots;
483
484 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Setting Max device slots reg = 0x%x",
485 config_reg);
486 writel(config_reg, &xhci->op_regs->config_reg);
487 }
488
xhci_set_cmd_ring_deq(struct xhci_hcd * xhci)489 static 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(xhci->cmd_ring->deq_seg, xhci->cmd_ring->dequeue);
495 deq_dma &= CMD_RING_PTR_MASK;
496
497 crcr = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
498 crcr &= ~CMD_RING_PTR_MASK;
499 crcr |= deq_dma;
500
501 crcr &= ~CMD_RING_CYCLE;
502 crcr |= xhci->cmd_ring->cycle_state;
503
504 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Setting command ring address to 0x%llx", crcr);
505 xhci_write_64(xhci, crcr, &xhci->op_regs->cmd_ring);
506 }
507
xhci_set_doorbell_ptr(struct xhci_hcd * xhci)508 static void xhci_set_doorbell_ptr(struct xhci_hcd *xhci)
509 {
510 u32 offset;
511
512 offset = readl(&xhci->cap_regs->db_off) & DBOFF_MASK;
513 xhci->dba = (void __iomem *)xhci->cap_regs + offset;
514 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
515 "Doorbell array is located at offset 0x%x from cap regs base addr", offset);
516 }
517
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 */
xhci_set_dev_notifications(struct xhci_hcd * xhci)522 static void xhci_set_dev_notifications(struct xhci_hcd *xhci)
523 {
524 u32 dev_notf;
525
526 dev_notf = readl(&xhci->op_regs->dev_notification);
527 dev_notf &= ~DEV_NOTE_MASK;
528 dev_notf |= DEV_NOTE_FWAKE;
529 writel(dev_notf, &xhci->op_regs->dev_notification);
530 }
531
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 */
xhci_init(struct usb_hcd * hcd)539 static 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_xhci_dbg_init, "Starting %s", __func__);
545 spin_lock_init(&xhci->lock);
546
547 INIT_LIST_HEAD(&xhci->cmd_list);
548 INIT_DELAYED_WORK(&xhci->cmd_timer, xhci_handle_command_timeout);
549 init_completion(&xhci->cmd_ring_stop_completion);
550 xhci_hcd_page_size(xhci);
551 memset(xhci->devs, 0, MAX_HC_SLOTS * sizeof(*xhci->devs));
552
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, xhci->dcbaa->dma, &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, 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_xhci_dbg_init, "Finished %s", __func__);
583 return 0;
584 }
585
586 /*-------------------------------------------------------------------------*/
587
xhci_run_finished(struct xhci_hcd * xhci)588 static 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_xhci_dbg_init, "Enable interrupts");
601 temp = readl(&xhci->op_regs->command);
602 temp |= (CMD_EIE);
603 writel(temp, &xhci->op_regs->command);
604
605 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Enable primary interrupter");
606 xhci_enable_interrupter(ir);
607
608 if (xhci_start(xhci)) {
609 xhci_halt(xhci);
610 spin_unlock_irqrestore(&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(&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 */
xhci_run(struct usb_hcd * hcd)636 int 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_xhci_dbg_init, "xhci_run");
654
655 temp_64 = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
656 temp_64 &= ERST_PTR_MASK;
657 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
658 "ERST deq = 64'h%0lx", (long unsigned int) temp_64);
659
660 xhci_set_interrupter_moderation(ir, xhci->imod_interval);
661
662 if (xhci->quirks & XHCI_NEC_HOST) {
663 struct xhci_command *command;
664
665 command = xhci_alloc_command(xhci, false, GFP_KERNEL);
666 if (!command)
667 return -ENOMEM;
668
669 ret = xhci_queue_vendor_command(xhci, command, 0, 0, 0,
670 TRB_TYPE(TRB_NEC_GET_FW));
671 if (ret)
672 xhci_free_command(xhci, command);
673 }
674 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
675 "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, &hcd->flags);
685
686 return 0;
687 }
688 EXPORT_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 */
xhci_stop(struct usb_hcd * hcd)699 void 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(&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(&xhci->mutex);
710 return;
711 }
712
713 xhci_remove_dbc_dev(xhci);
714
715 spin_lock_irq(&xhci->lock);
716 xhci->xhc_state |= XHCI_STATE_HALTED;
717 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
718 xhci_halt(xhci);
719 xhci_reset(xhci, XHCI_RESET_SHORT_USEC);
720 spin_unlock_irq(&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(&xhci->comp_mode_recovery_timer);
726 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
727 "%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_xhci_dbg_init,
735 "// Disabling event ring interrupts");
736 temp = readl(&xhci->op_regs->status);
737 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
738 xhci_disable_interrupter(xhci, ir);
739
740 xhci_dbg_trace(xhci, trace_xhci_dbg_init, "cleaning up memory");
741 xhci_mem_cleanup(xhci);
742 xhci_debugfs_exit(xhci);
743 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
744 "xhci_stop completed - status = %x",
745 readl(&xhci->op_regs->status));
746 mutex_unlock(&xhci->mutex);
747 }
748 EXPORT_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 */
xhci_shutdown(struct usb_hcd * hcd)759 void 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, &hcd->flags);
770 timer_delete_sync(&hcd->rh_timer);
771
772 if (xhci->shared_hcd) {
773 clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
774 timer_delete_sync(&xhci->shared_hcd->rh_timer);
775 }
776
777 spin_lock_irq(&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(&xhci->lock);
789
790 xhci_dbg_trace(xhci, trace_xhci_dbg_init,
791 "xhci_shutdown completed - status = %x",
792 readl(&xhci->op_regs->status));
793 }
794 EXPORT_SYMBOL_GPL(xhci_shutdown);
795
796 #ifdef CONFIG_PM
xhci_save_registers(struct xhci_hcd * xhci)797 static void xhci_save_registers(struct xhci_hcd *xhci)
798 {
799 struct xhci_interrupter *ir;
800 unsigned int i;
801
802 xhci->s3.command = readl(&xhci->op_regs->command);
803 xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
804 xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
805 xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);
806
807 /* save both primary and all secondary interrupters */
808 /* fixme, shold we lock to prevent race with remove secondary interrupter? */
809 for (i = 0; i < xhci->max_interrupters; i++) {
810 ir = xhci->interrupters[i];
811 if (!ir)
812 continue;
813
814 ir->s3_erst_size = readl(&ir->ir_set->erst_size);
815 ir->s3_erst_base = xhci_read_64(xhci, &ir->ir_set->erst_base);
816 ir->s3_erst_dequeue = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
817 ir->s3_iman = readl(&ir->ir_set->iman);
818 ir->s3_imod = readl(&ir->ir_set->imod);
819 }
820 }
821
xhci_restore_registers(struct xhci_hcd * xhci)822 static void xhci_restore_registers(struct xhci_hcd *xhci)
823 {
824 struct xhci_interrupter *ir;
825 unsigned int i;
826
827 writel(xhci->s3.command, &xhci->op_regs->command);
828 writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
829 xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
830 writel(xhci->s3.config_reg, &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(ir->s3_erst_size, &ir->ir_set->erst_size);
839 xhci_write_64(xhci, ir->s3_erst_base, &ir->ir_set->erst_base);
840 xhci_write_64(xhci, ir->s3_erst_dequeue, &ir->ir_set->erst_dequeue);
841 writel(ir->s3_iman, &ir->ir_set->iman);
842 writel(ir->s3_imod, &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 */
xhci_clear_command_ring(struct xhci_hcd * xhci)855 static 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(seg->trbs, 0, 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
xhci_disable_hub_port_wake(struct xhci_hcd * xhci,struct xhci_hub * rhub,bool do_wakeup)888 static 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(rhub->ports[i]->addr);
900 t1 = xhci_port_state_to_neutral(portsc);
901 t2 = t1;
902
903 /* clear wake bits if do_wake is not set */
904 if (!do_wakeup)
905 t2 &= ~PORT_WAKE_BITS;
906
907 /* Don't touch csc bit if connected or connect change is set */
908 if (!(portsc & (PORT_CSC | PORT_CONNECT)))
909 t2 |= PORT_CSC;
910
911 if (t1 != t2) {
912 writel(t2, rhub->ports[i]->addr);
913 xhci_dbg(xhci, "config port %d-%d wake bits, portsc: 0x%x, write: 0x%x\n",
914 rhub->hcd->self.busnum, i + 1, portsc, t2);
915 }
916 }
917 spin_unlock_irqrestore(&xhci->lock, flags);
918 }
919
xhci_pending_portevent(struct xhci_hcd * xhci)920 static bool xhci_pending_portevent(struct xhci_hcd *xhci)
921 {
922 struct xhci_port **ports;
923 int port_index;
924 u32 status;
925 u32 portsc;
926
927 status = readl(&xhci->op_regs->status);
928 if (status & STS_EINT)
929 return true;
930 /*
931 * Checking STS_EINT is not enough as there is a lag between a change
932 * bit being set and the Port Status Change Event that it generated
933 * being written to the Event Ring. See note in xhci 1.1 section 4.19.2.
934 */
935
936 port_index = xhci->usb2_rhub.num_ports;
937 ports = xhci->usb2_rhub.ports;
938 while (port_index--) {
939 portsc = readl(ports[port_index]->addr);
940 if (portsc & PORT_CHANGE_MASK ||
941 (portsc & PORT_PLS_MASK) == XDEV_RESUME)
942 return true;
943 }
944 port_index = xhci->usb3_rhub.num_ports;
945 ports = xhci->usb3_rhub.ports;
946 while (port_index--) {
947 portsc = readl(ports[port_index]->addr);
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 */
xhci_suspend(struct xhci_hcd * xhci,bool do_wakeup)961 int 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, &xhci->usb3_rhub, do_wakeup);
978 xhci_disable_hub_port_wake(xhci, &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, &hcd->flags);
989 timer_delete_sync(&hcd->rh_timer);
990 if (xhci->shared_hcd) {
991 clear_bit(HCD_FLAG_POLL_RH, &xhci->shared_hcd->flags);
992 timer_delete_sync(&xhci->shared_hcd->rh_timer);
993 }
994
995 if (xhci->quirks & XHCI_SUSPEND_DELAY)
996 usleep_range(1000, 1500);
997
998 spin_lock_irq(&xhci->lock);
999 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1000 if (xhci->shared_hcd)
1001 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &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(&xhci->op_regs->command);
1007 command &= ~CMD_RUN;
1008 writel(command, &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(&xhci->op_regs->status,
1014 STS_HALT, STS_HALT, delay)) {
1015 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
1016 spin_unlock_irq(&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(&xhci->op_regs->command);
1026 command |= CMD_CSS;
1027 writel(command, &xhci->op_regs->command);
1028 xhci->broken_suspend = 0;
1029 if (xhci_handshake(&xhci->op_regs->status,
1030 STS_SAVE, 0, 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(&xhci->op_regs->status);
1041 if ((xhci->quirks & XHCI_SNPS_BROKEN_SUSPEND) &&
1042 (((res & STS_SRE) == 0) &&
1043 ((res & STS_HCE) == 0))) {
1044 xhci->broken_suspend = 1;
1045 } else {
1046 xhci_warn(xhci, "WARN: xHC save state timeout\n");
1047 spin_unlock_irq(&xhci->lock);
1048 return -ETIMEDOUT;
1049 }
1050 }
1051 spin_unlock_irq(&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(&xhci->comp_mode_recovery_timer);
1060 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1061 "%s: compliance mode recovery timer deleted",
1062 __func__);
1063 }
1064
1065 return rc;
1066 }
1067 EXPORT_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 */
xhci_resume(struct xhci_hcd * xhci,bool power_lost,bool is_auto_resume)1075 int 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(100);
1094
1095 set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
1096 if (xhci->shared_hcd)
1097 set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
1098
1099 spin_lock_irq(&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(&xhci->op_regs->status,
1110 STS_CNR, 0, 10 * 1000 * 1000);
1111 if (retval) {
1112 xhci_warn(xhci, "Controller not ready at resume %d\n",
1113 retval);
1114 spin_unlock_irq(&xhci->lock);
1115 return retval;
1116 }
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(&xhci->op_regs->command);
1124 command |= CMD_CRS;
1125 writel(command, &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(&xhci->op_regs->status,
1132 STS_RESTORE, 0, 100 * 1000)) {
1133 xhci_warn(xhci, "WARN: xHC restore state timeout\n");
1134 spin_unlock_irq(&xhci->lock);
1135 return -ETIMEDOUT;
1136 }
1137 }
1138
1139 temp = readl(&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(&xhci->comp_mode_recovery_timer);
1153 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
1154 "Compliance Mode Recovery Timer deleted!");
1155 }
1156
1157 /* Let the USB core know _both_ roothubs lost power. */
1158 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
1159 if (xhci->shared_hcd)
1160 usb_root_hub_lost_power(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(&xhci->lock);
1170 if (retval)
1171 return retval;
1172
1173 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
1174 temp = readl(&xhci->op_regs->status);
1175 writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
1176 xhci_disable_interrupter(xhci, 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(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(&xhci->op_regs->command);
1219 command |= CMD_RUN;
1220 writel(command, &xhci->op_regs->command);
1221 xhci_handshake(&xhci->op_regs->status, STS_HALT,
1222 0, 250 * 1000);
1223
1224 /* step 5: walk topology and initialize portsc,
1225 * portpmsc and portli
1226 */
1227 /* this is done in bus_resume */
1228
1229 /* step 6: restart each of the previously
1230 * Running endpoints by ringing their doorbells
1231 */
1232
1233 spin_unlock_irq(&xhci->lock);
1234
1235 xhci_dbc_resume(xhci);
1236
1237 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(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(xhci->shared_hcd);
1258 usb_hcd_resume_root_hub(hcd);
1259 }
1260 }
1261 done:
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, &xhci->shared_hcd->flags);
1279 usb_hcd_poll_rh_status(xhci->shared_hcd);
1280 }
1281 set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
1282 usb_hcd_poll_rh_status(hcd);
1283
1284 return retval;
1285 }
1286 EXPORT_SYMBOL_GPL(xhci_resume);
1287 #endif /* CONFIG_PM */
1288
1289 /*-------------------------------------------------------------------------*/
1290
xhci_map_temp_buffer(struct usb_hcd * hcd,struct urb * urb)1291 static 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(urb->sg, urb->num_sgs,
1308 temp, buf_len, 0);
1309
1310 urb->transfer_buffer = temp;
1311 urb->transfer_dma = dma_map_single(hcd->self.sysdev,
1312 urb->transfer_buffer,
1313 urb->transfer_buffer_length,
1314 dir);
1315
1316 if (dma_mapping_error(hcd->self.sysdev,
1317 urb->transfer_dma)) {
1318 ret = -EAGAIN;
1319 kfree(temp);
1320 } else {
1321 urb->transfer_flags |= URB_DMA_MAP_SINGLE;
1322 }
1323
1324 return ret;
1325 }
1326
xhci_urb_temp_buffer_required(struct usb_hcd * hcd,struct urb * urb)1327 static 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(urb->dev, 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(tail_sg);
1361 }
1362 }
1363 }
1364 return ret;
1365 }
1366
xhci_unmap_temp_buf(struct usb_hcd * hcd,struct urb * urb)1367 static 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(urb->sg, urb->num_sgs,
1386 urb->transfer_buffer,
1387 buf_len,
1388 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(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 */
xhci_map_urb_for_dma(struct usb_hcd * hcd,struct urb * urb,gfp_t mem_flags)1406 static 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
xhci_unmap_urb_for_dma(struct usb_hcd * hcd,struct urb * urb)1423 static 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 */
xhci_get_endpoint_index(struct usb_endpoint_descriptor * desc)1450 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1451 {
1452 unsigned int index;
1453 if (usb_endpoint_xfer_control(desc))
1454 index = (unsigned int) (usb_endpoint_num(desc)*2);
1455 else
1456 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1457 (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1458 return index;
1459 }
1460 EXPORT_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 */
xhci_get_endpoint_address(unsigned int ep_index)1465 static 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 */
xhci_get_endpoint_flag(struct usb_endpoint_descriptor * desc)1476 static 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 */
xhci_last_valid_endpoint(u32 added_ctxs)1487 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1488 {
1489 return fls(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 */
xhci_check_args(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint * ep,int check_ep,bool check_virt_dev,const char * func)1495 static 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
1532 static 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 */
xhci_check_ep0_maxpacket(struct xhci_hcd * xhci,struct xhci_virt_device * vdev)1542 static 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, vdev->out_ctx, 0);
1552 hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1553 max_packet_size = usb_endpoint_maxp(&vdev->udev->ep0.desc);
1554
1555 if (hw_max_packet_size == max_packet_size)
1556 return 0;
1557
1558 switch (max_packet_size) {
1559 case 8: case 16: case 32: case 64: case 9:
1560 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1561 "Max Packet Size for ep 0 changed.");
1562 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1563 "Max packet size in usb_device = %d",
1564 max_packet_size);
1565 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1566 "Max packet size in xHCI HW = %d",
1567 hw_max_packet_size);
1568 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
1569 "Issuing evaluate context command.");
1570
1571 command = xhci_alloc_command(xhci, 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(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, vdev->in_ctx, vdev->out_ctx, 0);
1585
1586 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, 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, vdev->udev, command,
1595 true, 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(command->completion);
1606 kfree(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 */
xhci_urb_enqueue(struct usb_hcd * hcd,struct urb * urb,gfp_t mem_flags)1615 static 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(&urb->ep->desc))
1628 num_tds = urb->number_of_packets;
1629 else if (usb_endpoint_is_bulk_out(&urb->ep->desc) &&
1630 urb->transfer_buffer_length > 0 &&
1631 urb->transfer_flags & URB_ZERO_PACKET &&
1632 !(urb->transfer_buffer_length % usb_endpoint_maxp(&urb->ep->desc)))
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, urb->dev, urb->ep,
1650 true, true, __func__);
1651 if (ret <= 0) {
1652 ret = ret ? ret : -EINVAL;
1653 goto free_priv;
1654 }
1655
1656 slot_id = urb->dev->slot_id;
1657
1658 if (!HCD_HW_ACCESSIBLE(hcd)) {
1659 ret = -ESHUTDOWN;
1660 goto free_priv;
1661 }
1662
1663 if (xhci->devs[slot_id]->flags & VDEV_PORT_ERROR) {
1664 xhci_dbg(xhci, "Can't queue urb, port error, link inactive\n");
1665 ret = -ENODEV;
1666 goto free_priv;
1667 }
1668
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(&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) {
1710 free_priv:
1711 xhci_urb_free_priv(urb_priv);
1712 urb->hcpriv = NULL;
1713 }
1714 spin_unlock_irqrestore(&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 */
xhci_urb_dequeue(struct usb_hcd * hcd,struct urb * urb,int status)1749 static 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(&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(&urb_priv->td[0], ep_ring)) {
1798 xhci_err(xhci, "Canceled URB td not found on endpoint ring");
1799 for (i = urb_priv->num_tds_done; i < urb_priv->num_tds; i++) {
1800 td = &urb_priv->td[i];
1801 if (!list_empty(&td->cancelled_td_list))
1802 list_del_init(&td->cancelled_td_list);
1803 }
1804 goto err_giveback;
1805 }
1806
1807 if (xhci->xhc_state & XHCI_STATE_HALTED) {
1808 xhci_dbg_trace(xhci, trace_xhci_dbg_cancel_urb,
1809 "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(&td->td_list))
1815 list_del_init(&td->td_list);
1816 if (!list_empty(&td->cancelled_td_list))
1817 list_del_init(&td->cancelled_td_list);
1818 }
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_xhci_dbg_cancel_urb,
1825 "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 urb_priv->td[i].start_seg,
1831 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(&td->cancelled_td_list)) {
1837 td->cancel_status = TD_DIRTY;
1838 list_add_tail(&td->cancelled_td_list,
1839 &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, 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, command, urb->dev->slot_id,
1866 ep_index, 0);
1867 xhci_ring_cmd_db(xhci);
1868 }
1869 done:
1870 spin_unlock_irqrestore(&xhci->lock, flags);
1871 return ret;
1872
1873 err_giveback:
1874 if (urb_priv)
1875 xhci_urb_free_priv(urb_priv);
1876 usb_hcd_unlink_urb_from_ep(hcd, urb);
1877 spin_unlock_irqrestore(&xhci->lock, flags);
1878 usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1879 return ret;
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 */
xhci_drop_endpoint(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint * ep)1895 int 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, 1, true, __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(&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(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, 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(&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, xhci->devs[udev->slot_id], ep_index);
1953
1954 xhci_endpoint_zero(xhci, 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 }
1963 EXPORT_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 */
xhci_add_endpoint(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint * ep)1978 int 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, 1, true, __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(&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(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, virt_dev->in_ctx, ep_index);
2068 trace_xhci_add_endpoint(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 }
2077 EXPORT_SYMBOL_GPL(xhci_add_endpoint);
2078
xhci_zero_in_ctx(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev)2079 static 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(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, 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, virt_dev->in_ctx, 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
xhci_configure_endpoint_result(struct xhci_hcd * xhci,struct usb_device * udev,u32 * cmd_status)2113 static 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_xhci_dbg_context_change,
2151 "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
xhci_evaluate_context_result(struct xhci_hcd * xhci,struct usb_device * udev,u32 * cmd_status)2163 static 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_xhci_dbg_context_change,
2201 "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
xhci_count_num_new_endpoints(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)2213 static 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
xhci_count_num_dropped_endpoints(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)2234 static 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 */
xhci_reserve_host_resources(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)2260 static 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_xhci_dbg_quirks,
2268 "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_xhci_dbg_quirks,
2276 "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 */
xhci_free_host_resources(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)2287 static 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_xhci_dbg_quirks,
2295 "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 */
xhci_finish_resource_reservation(struct xhci_hcd * xhci,struct xhci_input_control_ctx * ctrl_ctx)2306 static 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_xhci_dbg_quirks,
2315 "Removing %u dropped ep ctxs, %u now active.",
2316 num_dropped_eps,
2317 xhci->num_active_eps);
2318 }
2319
xhci_get_block_size(struct usb_device * udev)2320 static 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
2338 static unsigned int
xhci_get_largest_overhead(struct xhci_interval_bw * interval_bw)2339 xhci_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 */
xhci_check_tt_bw_table(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,int old_active_eps)2352 static 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
xhci_check_ss_bw(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev)2382 static 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 */
xhci_check_bw_table(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,int old_active_eps)2439 static 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(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_xhci_dbg_quirks,
2477 "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_xhci_dbg_quirks,
2485 "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_xhci_dbg_quirks,
2490 "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(&bw_table->interval_bw[0]);
2500
2501 for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2502 unsigned int bw_added;
2503 unsigned int largest_mps;
2504 unsigned int interval_overhead;
2505
2506 /*
2507 * How many packets could we transmit in this interval?
2508 * If packets didn't fit in the previous interval, we will need
2509 * to transmit that many packets twice within this interval.
2510 */
2511 packets_remaining = 2 * packets_remaining +
2512 bw_table->interval_bw[i].num_packets;
2513
2514 /* Find the largest max packet size of this or the previous
2515 * interval.
2516 */
2517 if (list_empty(&bw_table->interval_bw[i].endpoints))
2518 largest_mps = 0;
2519 else {
2520 struct xhci_virt_ep *virt_ep;
2521 struct list_head *ep_entry;
2522
2523 ep_entry = bw_table->interval_bw[i].endpoints.next;
2524 virt_ep = list_entry(ep_entry,
2525 struct xhci_virt_ep, bw_endpoint_list);
2526 /* Convert to blocks, rounding up */
2527 largest_mps = DIV_ROUND_UP(
2528 virt_ep->bw_info.max_packet_size,
2529 block_size);
2530 }
2531 if (largest_mps > packet_size)
2532 packet_size = largest_mps;
2533
2534 /* Use the larger overhead of this or the previous interval. */
2535 interval_overhead = xhci_get_largest_overhead(
2536 &bw_table->interval_bw[i]);
2537 if (interval_overhead > overhead)
2538 overhead = interval_overhead;
2539
2540 /* How many packets can we evenly distribute across
2541 * (1 << (i + 1)) possible scheduling opportunities?
2542 */
2543 packets_transmitted = packets_remaining >> (i + 1);
2544
2545 /* Add in the bandwidth used for those scheduled packets */
2546 bw_added = packets_transmitted * (overhead + packet_size);
2547
2548 /* How many packets do we have remaining to transmit? */
2549 packets_remaining = packets_remaining % (1 << (i + 1));
2550
2551 /* What largest max packet size should those packets have? */
2552 /* If we've transmitted all packets, don't carry over the
2553 * largest packet size.
2554 */
2555 if (packets_remaining == 0) {
2556 packet_size = 0;
2557 overhead = 0;
2558 } else if (packets_transmitted > 0) {
2559 /* Otherwise if we do have remaining packets, and we've
2560 * scheduled some packets in this interval, take the
2561 * largest max packet size from endpoints with this
2562 * interval.
2563 */
2564 packet_size = largest_mps;
2565 overhead = interval_overhead;
2566 }
2567 /* Otherwise carry over packet_size and overhead from the last
2568 * time we had a remainder.
2569 */
2570 bw_used += bw_added;
2571 if (bw_used > max_bandwidth) {
2572 xhci_warn(xhci, "Not enough bandwidth. "
2573 "Proposed: %u, Max: %u\n",
2574 bw_used, max_bandwidth);
2575 return -ENOMEM;
2576 }
2577 }
2578 /*
2579 * Ok, we know we have some packets left over after even-handedly
2580 * scheduling interval 15. We don't know which microframes they will
2581 * fit into, so we over-schedule and say they will be scheduled every
2582 * microframe.
2583 */
2584 if (packets_remaining > 0)
2585 bw_used += overhead + packet_size;
2586
2587 if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
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_xhci_dbg_quirks,
2597 "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
xhci_is_async_ep(unsigned int ep_type)2614 static 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
xhci_is_sync_in_ep(unsigned int ep_type)2621 static 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
xhci_get_ss_bw_consumed(struct xhci_bw_info * ep_bw)2626 static 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
xhci_drop_ep_from_interval_table(struct xhci_hcd * xhci,struct xhci_bw_info * ep_bw,struct xhci_interval_bw_table * bw_table,struct usb_device * udev,struct xhci_virt_ep * virt_ep,struct xhci_tt_bw_info * tt_info)2640 static 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_bw->type))
2651 return;
2652
2653 if (udev->speed >= USB_SPEED_SUPER) {
2654 if (xhci_is_sync_in_ep(ep_bw->type))
2655 xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2656 xhci_get_ss_bw_consumed(ep_bw);
2657 else
2658 xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2659 xhci_get_ss_bw_consumed(ep_bw);
2660 return;
2661 }
2662
2663 /* SuperSpeed endpoints never get added to intervals in the table, so
2664 * this check is only valid for HS/FS/LS devices.
2665 */
2666 if (list_empty(&virt_ep->bw_endpoint_list))
2667 return;
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(&virt_ep->bw_endpoint_list);
2699 }
2700
xhci_add_ep_to_interval_table(struct xhci_hcd * xhci,struct xhci_bw_info * ep_bw,struct xhci_interval_bw_table * bw_table,struct usb_device * udev,struct xhci_virt_ep * virt_ep,struct xhci_tt_bw_info * tt_info)2701 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2702 struct xhci_bw_info *ep_bw,
2703 struct xhci_interval_bw_table *bw_table,
2704 struct usb_device *udev,
2705 struct xhci_virt_ep *virt_ep,
2706 struct xhci_tt_bw_info *tt_info)
2707 {
2708 struct xhci_interval_bw *interval_bw;
2709 struct xhci_virt_ep *smaller_ep;
2710 int normalized_interval;
2711
2712 if (xhci_is_async_ep(ep_bw->type))
2713 return;
2714
2715 if (udev->speed == USB_SPEED_SUPER) {
2716 if (xhci_is_sync_in_ep(ep_bw->type))
2717 xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2718 xhci_get_ss_bw_consumed(ep_bw);
2719 else
2720 xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2721 xhci_get_ss_bw_consumed(ep_bw);
2722 return;
2723 }
2724
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(&virt_ep->bw_endpoint_list,
2763 &smaller_ep->bw_endpoint_list);
2764 return;
2765 }
2766 }
2767 /* Add the new endpoint at the end of the list. */
2768 list_add_tail(&virt_ep->bw_endpoint_list,
2769 &interval_bw->endpoints);
2770 }
2771
xhci_update_tt_active_eps(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,int old_active_eps)2772 void 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
xhci_reserve_bandwidth(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,struct xhci_container_ctx * in_ctx)2792 static 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(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(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2817 sizeof(ep_bw_info[i]));
2818 /* Drop the endpoint from the interval table if the endpoint is
2819 * being dropped or changed.
2820 */
2821 if (EP_IS_DROPPED(ctrl_ctx, i))
2822 xhci_drop_ep_from_interval_table(xhci,
2823 &virt_dev->eps[i].bw_info,
2824 virt_dev->bw_table,
2825 virt_dev->udev,
2826 &virt_dev->eps[i],
2827 virt_dev->tt_info);
2828 }
2829 /* Overwrite the information stored in the endpoints' bw_info */
2830 xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2831 for (i = 0; i < 31; i++) {
2832 /* Add any changed or added endpoints to the interval table */
2833 if (EP_IS_ADDED(ctrl_ctx, i))
2834 xhci_add_ep_to_interval_table(xhci,
2835 &virt_dev->eps[i].bw_info,
2836 virt_dev->bw_table,
2837 virt_dev->udev,
2838 &virt_dev->eps[i],
2839 virt_dev->tt_info);
2840 }
2841
2842 if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2843 /* Ok, this fits in the bandwidth we have.
2844 * Update the number of active TTs.
2845 */
2846 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2847 return 0;
2848 }
2849
2850 /* We don't have enough bandwidth for this, revert the stored info. */
2851 for (i = 0; i < 31; i++) {
2852 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2853 continue;
2854
2855 /* Drop the new copies of any added or changed endpoints from
2856 * the interval table.
2857 */
2858 if (EP_IS_ADDED(ctrl_ctx, i)) {
2859 xhci_drop_ep_from_interval_table(xhci,
2860 &virt_dev->eps[i].bw_info,
2861 virt_dev->bw_table,
2862 virt_dev->udev,
2863 &virt_dev->eps[i],
2864 virt_dev->tt_info);
2865 }
2866 /* Revert the endpoint back to its old information */
2867 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2868 sizeof(ep_bw_info[i]));
2869 /* Add any changed or dropped endpoints back into the table */
2870 if (EP_IS_DROPPED(ctrl_ctx, i))
2871 xhci_add_ep_to_interval_table(xhci,
2872 &virt_dev->eps[i].bw_info,
2873 virt_dev->bw_table,
2874 virt_dev->udev,
2875 &virt_dev->eps[i],
2876 virt_dev->tt_info);
2877 }
2878 return -ENOMEM;
2879 }
2880
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 */
xhci_stop_endpoint_sync(struct xhci_hcd * xhci,struct xhci_virt_ep * ep,int suspend,gfp_t gfp_flags)2890 int xhci_stop_endpoint_sync(struct xhci_hcd *xhci, struct xhci_virt_ep *ep, int suspend,
2891 gfp_t gfp_flags)
2892 {
2893 struct xhci_command *command;
2894 unsigned long flags;
2895 int ret;
2896
2897 command = xhci_alloc_command(xhci, true, gfp_flags);
2898 if (!command)
2899 return -ENOMEM;
2900
2901 spin_lock_irqsave(&xhci->lock, flags);
2902 ret = xhci_queue_stop_endpoint(xhci, command, ep->vdev->slot_id,
2903 ep->ep_index, suspend);
2904 if (ret < 0) {
2905 spin_unlock_irqrestore(&xhci->lock, flags);
2906 goto out;
2907 }
2908
2909 xhci_ring_cmd_db(xhci);
2910 spin_unlock_irqrestore(&xhci->lock, flags);
2911
2912 wait_for_completion(command->completion);
2913
2914 /* No handling for COMP_CONTEXT_STATE_ERROR done at command completion*/
2915 if (command->status == COMP_COMMAND_ABORTED ||
2916 command->status == COMP_COMMAND_RING_STOPPED) {
2917 xhci_warn(xhci, "Timeout while waiting for stop endpoint command\n");
2918 ret = -ETIME;
2919 }
2920 out:
2921 xhci_free_command(xhci, command);
2922
2923 return ret;
2924 }
2925 EXPORT_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 */
xhci_usb_endpoint_maxp(struct usb_device * udev,struct usb_host_endpoint * host_ep)2933 int 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, host_ep))
2937 return le16_to_cpu(host_ep->eusb2_isoc_ep_comp.wMaxPacketSize);
2938 return usb_endpoint_maxp(&host_ep->desc);
2939 }
2940
2941 /* Issue a configure endpoint command or evaluate context command
2942 * and wait for it to finish.
2943 */
xhci_configure_endpoint(struct xhci_hcd * xhci,struct usb_device * udev,struct xhci_command * command,bool ctx_change,bool must_succeed)2944 static 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(&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(command->in_ctx);
2968 if (!ctrl_ctx) {
2969 spin_unlock_irqrestore(&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(&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, command->in_ctx)) {
2985 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2986 xhci_free_host_resources(xhci, ctrl_ctx);
2987 spin_unlock_irqrestore(&xhci->lock, flags);
2988 xhci_warn(xhci, "Not enough bandwidth\n");
2989 return -ENOMEM;
2990 }
2991
2992 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
2993
2994 trace_xhci_configure_endpoint_ctrl_ctx(ctrl_ctx);
2995 trace_xhci_configure_endpoint(slot_ctx);
2996
2997 if (!ctx_change)
2998 ret = xhci_queue_configure_endpoint(xhci, command,
2999 command->in_ctx->dma,
3000 udev->slot_id, must_succeed);
3001 else
3002 ret = xhci_queue_evaluate_context(xhci, command,
3003 command->in_ctx->dma,
3004 udev->slot_id, 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(&xhci->lock, flags);
3009 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
3010 "FIXME allocate a new ring segment");
3011 return -ENOMEM;
3012 }
3013 xhci_ring_cmd_db(xhci);
3014 spin_unlock_irqrestore(&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 &command->status);
3022 else
3023 ret = xhci_evaluate_context_result(xhci, udev,
3024 &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(&xhci->lock, flags);
3036 }
3037 return ret;
3038 }
3039
xhci_check_bw_drop_ep_streams(struct xhci_hcd * xhci,struct xhci_virt_device * vdev,int i)3040 static 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, 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 */
xhci_check_bandwidth(struct usb_hcd * hcd,struct usb_device * udev)3064 int 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, 0, true, __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, 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(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, 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 false, 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, i);
3133 xhci_check_bw_drop_ep_streams(xhci, 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, i);
3149 }
3150 xhci_check_bw_drop_ep_streams(xhci, 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, i);
3154 }
3155 command_cleanup:
3156 kfree(command->completion);
3157 kfree(command);
3158
3159 return ret;
3160 }
3161 EXPORT_SYMBOL_GPL(xhci_check_bandwidth);
3162
xhci_reset_bandwidth(struct usb_hcd * hcd,struct usb_device * udev)3163 void 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, 0, true, __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, i);
3180 xhci_ring_free(xhci, 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 }
3186 EXPORT_SYMBOL_GPL(xhci_reset_bandwidth);
3187
3188 /* Get the available bandwidth of the ports under the xhci roothub */
xhci_get_port_bandwidth(struct xhci_hcd * xhci,struct xhci_container_ctx * ctx,u8 dev_speed)3189 int 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, 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, ctx->dma, dev_speed, 0);
3209 if (ret) {
3210 spin_unlock_irqrestore(&xhci->lock, flags);
3211 goto err_out;
3212 }
3213 xhci_ring_cmd_db(xhci);
3214 spin_unlock_irqrestore(&xhci->lock, flags);
3215
3216 wait_for_completion(cmd->completion);
3217 err_out:
3218 kfree(cmd->completion);
3219 kfree(cmd);
3220
3221 return ret;
3222 }
3223
xhci_setup_input_ctx_for_config_ep(struct xhci_hcd * xhci,struct xhci_container_ctx * in_ctx,struct xhci_container_ctx * out_ctx,struct xhci_input_control_ctx * ctrl_ctx,u32 add_flags,u32 drop_flags)3224 static 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
xhci_endpoint_disable(struct usb_hcd * hcd,struct usb_host_endpoint * host_ep)3236 static 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);
3247 rescan:
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(&xhci->lock, flags);
3264 schedule_timeout_uninterruptible(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);
3271 done:
3272 host_ep->hcpriv = NULL;
3273 spin_unlock_irqrestore(&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
xhci_endpoint_reset(struct usb_hcd * hcd,struct usb_host_endpoint * host_ep)3291 static 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(&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(&xhci->lock, flags);
3344 return;
3345 }
3346 spin_unlock_irqrestore(&xhci->lock, flags);
3347 /* Only interrupt and bulk ep's use data toggle, USB2 spec 5.5.4-> */
3348 if (usb_endpoint_xfer_control(&host_ep->desc) ||
3349 usb_endpoint_xfer_isoc(&host_ep->desc))
3350 return;
3351
3352 ep_flag = xhci_get_endpoint_flag(&host_ep->desc);
3353
3354 if (ep_flag == SLOT_FLAG || ep_flag == EP0_FLAG)
3355 return;
3356
3357 stop_cmd = xhci_alloc_command(xhci, true, GFP_NOWAIT);
3358 if (!stop_cmd)
3359 return;
3360
3361 cfg_cmd = xhci_alloc_command_with_ctx(xhci, 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(&ep->ring->td_list)) {
3377 dev_err(&udev->dev, "EP not empty, refuse reset\n");
3378 spin_unlock_irqrestore(&xhci->lock, flags);
3379 xhci_free_command(xhci, cfg_cmd);
3380 goto cleanup;
3381 }
3382
3383 err = xhci_queue_stop_endpoint(xhci, stop_cmd, udev->slot_id,
3384 ep_index, 0);
3385 if (err < 0) {
3386 spin_unlock_irqrestore(&xhci->lock, flags);
3387 xhci_free_command(xhci, 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(&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(cfg_cmd->in_ctx);
3402 if (!ctrl_ctx) {
3403 spin_unlock_irqrestore(&xhci->lock, flags);
3404 xhci_free_command(xhci, 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, cfg_cmd->in_ctx, vdev->out_ctx,
3411 ctrl_ctx, ep_flag, ep_flag);
3412 xhci_endpoint_copy(xhci, cfg_cmd->in_ctx, vdev->out_ctx, ep_index);
3413
3414 err = xhci_queue_configure_endpoint(xhci, cfg_cmd, cfg_cmd->in_ctx->dma,
3415 udev->slot_id, false);
3416 if (err < 0) {
3417 spin_unlock_irqrestore(&xhci->lock, flags);
3418 xhci_free_command(xhci, 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(&xhci->lock, flags);
3426
3427 wait_for_completion(cfg_cmd->completion);
3428
3429 xhci_free_command(xhci, cfg_cmd);
3430 cleanup:
3431 xhci_free_command(xhci, 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(&xhci->lock, flags);
3436 }
3437
xhci_check_streams_endpoint(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_host_endpoint * ep,unsigned int slot_id)3438 static 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(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
3449 if (ret <= 0)
3450 return ret ? ret : -EINVAL;
3451 if (usb_ss_max_streams(&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(&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
xhci_calculate_streams_entries(struct xhci_hcd * xhci,unsigned int * num_streams,unsigned int * num_stream_ctxs)3478 static 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 */
xhci_calculate_streams_and_bitmask(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_host_endpoint ** eps,unsigned int num_eps,unsigned int * num_streams,u32 * changed_ep_bitmask)3504 static 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 eps[i], udev->slot_id);
3517 if (ret < 0)
3518 return ret;
3519
3520 max_streams = usb_ss_max_streams(&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(&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
xhci_calculate_no_streams_bitmask(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_host_endpoint ** eps,unsigned int num_eps)3536 static 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(&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 */
xhci_alloc_streams(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint ** eps,unsigned int num_eps,unsigned int num_streams,gfp_t mem_flags)3593 static 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, true, mem_flags);
3627 if (!config_cmd)
3628 return -ENOMEM;
3629
3630 ctrl_ctx = xhci_get_input_control_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, 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, &changed_ep_bitmask);
3645 if (ret < 0) {
3646 xhci_free_command(xhci, config_cmd);
3647 spin_unlock_irqrestore(&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, config_cmd);
3654 spin_unlock_irqrestore(&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(&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_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(&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, 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, config_cmd->in_ctx, ep_index);
3695
3696 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3697 vdev->out_ctx, ep_index);
3698 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3699 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, config_cmd->in_ctx,
3705 vdev->out_ctx, ctrl_ctx,
3706 changed_ep_bitmask, changed_ep_bitmask);
3707
3708 /* Issue and wait for the configure endpoint command */
3709 ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3710 false, 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, config_cmd);
3728 spin_unlock_irqrestore(&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, vdev, ep_index);
3733 }
3734 /* Subtract 1 for stream 0, which drivers can't use */
3735 return num_streams - 1;
3736
3737 cleanup:
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, 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, vdev, eps[i]);
3749 }
3750 xhci_free_command(xhci, 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 */
xhci_free_streams(struct usb_hcd * hcd,struct usb_device * udev,struct usb_host_endpoint ** eps,unsigned int num_eps,gfp_t mem_flags)3760 static 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(&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(command->in_ctx);
3792 if (!ctrl_ctx) {
3793 spin_unlock_irqrestore(&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, 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, command->in_ctx,
3808 vdev->out_ctx, ep_index);
3809 xhci_setup_no_streams_ep_input_ctx(ep_ctx,
3810 &vdev->eps[ep_index]);
3811 }
3812 xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3813 vdev->out_ctx, ctrl_ctx,
3814 changed_ep_bitmask, changed_ep_bitmask);
3815 spin_unlock_irqrestore(&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 false, 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, 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(&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 */
xhci_free_device_endpoint_resources(struct xhci_hcd * xhci,struct xhci_virt_device * virt_dev,bool drop_control_ep)3852 void 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_xhci_dbg_quirks,
3868 "Dropped %u ep ctxs, flags = 0x%x, "
3869 "%u now active.",
3870 num_dropped_eps, drop_flags,
3871 xhci->num_active_eps);
3872 }
3873
3874 static 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 */
xhci_discover_or_reset_device(struct usb_hcd * hcd,struct usb_device * udev)3894 static 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, 0, false, __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, 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, 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(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, 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, reset_device_cmd, slot_id);
3981 if (ret) {
3982 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3983 spin_unlock_irqrestore(&xhci->lock, flags);
3984 goto command_cleanup;
3985 }
3986 xhci_ring_cmd_db(xhci);
3987 spin_unlock_irqrestore(&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 virt_dev->flags = 0;
4011 ret = 0;
4012 goto command_cleanup;
4013 case COMP_SUCCESS:
4014 xhci_dbg(xhci, "Successful reset device command.\n");
4015 break;
4016 default:
4017 if (xhci_is_vendor_info_code(xhci, ret))
4018 break;
4019 xhci_warn(xhci, "Unknown completion code %u for "
4020 "reset device command.\n", ret);
4021 ret = -EINVAL;
4022 goto command_cleanup;
4023 }
4024
4025 /* Free up host controller endpoint resources */
4026 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
4027 spin_lock_irqsave(&xhci->lock, flags);
4028 /* Don't delete the default control endpoint resources */
4029 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
4030 spin_unlock_irqrestore(&xhci->lock, flags);
4031 }
4032
4033 /* Everything but endpoint 0 is disabled, so free the rings. */
4034 for (i = 1; i < 31; i++) {
4035 struct xhci_virt_ep *ep = &virt_dev->eps[i];
4036
4037 if (ep->ep_state & EP_HAS_STREAMS) {
4038 xhci_warn(xhci, "WARN: endpoint 0x%02x has streams on device reset, freeing streams.\n",
4039 xhci_get_endpoint_address(i));
4040 xhci_free_stream_info(xhci, ep->stream_info);
4041 ep->stream_info = NULL;
4042 ep->ep_state &= ~EP_HAS_STREAMS;
4043 }
4044
4045 if (ep->ring) {
4046 if (ep->sideband)
4047 xhci_sideband_notify_ep_ring_free(ep->sideband, i);
4048 xhci_debugfs_remove_endpoint(xhci, virt_dev, i);
4049 xhci_free_endpoint_ring(xhci, virt_dev, i);
4050 }
4051 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
4052 xhci_drop_ep_from_interval_table(xhci,
4053 &virt_dev->eps[i].bw_info,
4054 virt_dev->bw_table,
4055 udev,
4056 &virt_dev->eps[i],
4057 virt_dev->tt_info);
4058 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
4059 }
4060 /* If necessary, update the number of active TTs on this root port */
4061 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
4062 virt_dev->flags = 0;
4063 ret = 0;
4064
4065 command_cleanup:
4066 xhci_free_command(xhci, reset_device_cmd);
4067 return ret;
4068 }
4069
4070 /*
4071 * At this point, the struct usb_device is about to go away, the device has
4072 * disconnected, and all traffic has been stopped and the endpoints have been
4073 * disabled. Free any HC data structures associated with that device.
4074 */
xhci_free_dev(struct usb_hcd * hcd,struct usb_device * udev)4075 static void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
4076 {
4077 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4078 struct xhci_virt_device *virt_dev;
4079 struct xhci_slot_ctx *slot_ctx;
4080 unsigned long flags;
4081 int i, ret;
4082
4083 /*
4084 * We called pm_runtime_get_noresume when the device was attached.
4085 * Decrement the counter here to allow controller to runtime suspend
4086 * if no devices remain.
4087 */
4088 if (xhci->quirks & XHCI_RESET_ON_RESUME)
4089 pm_runtime_put_noidle(hcd->self.controller);
4090
4091 ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
4092 /* If the host is halted due to driver unload, we still need to free the
4093 * device.
4094 */
4095 if (ret <= 0 && ret != -ENODEV)
4096 return;
4097
4098 virt_dev = xhci->devs[udev->slot_id];
4099 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4100 trace_xhci_free_dev(slot_ctx);
4101
4102 /* Stop any wayward timer functions (which may grab the lock) */
4103 for (i = 0; i < 31; i++)
4104 virt_dev->eps[i].ep_state &= ~EP_STOP_CMD_PENDING;
4105 virt_dev->udev = NULL;
4106 xhci_disable_slot(xhci, udev->slot_id);
4107
4108 spin_lock_irqsave(&xhci->lock, flags);
4109 xhci_free_virt_device(xhci, virt_dev, udev->slot_id);
4110 spin_unlock_irqrestore(&xhci->lock, flags);
4111
4112 }
4113
xhci_disable_slot(struct xhci_hcd * xhci,u32 slot_id)4114 int xhci_disable_slot(struct xhci_hcd *xhci, u32 slot_id)
4115 {
4116 struct xhci_command *command;
4117 unsigned long flags;
4118 u32 state;
4119 int ret;
4120
4121 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4122 if (!command)
4123 return -ENOMEM;
4124
4125 xhci_debugfs_remove_slot(xhci, slot_id);
4126
4127 spin_lock_irqsave(&xhci->lock, flags);
4128 /* Don't disable the slot if the host controller is dead. */
4129 state = readl(&xhci->op_regs->status);
4130 if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
4131 (xhci->xhc_state & XHCI_STATE_HALTED)) {
4132 spin_unlock_irqrestore(&xhci->lock, flags);
4133 kfree(command);
4134 return -ENODEV;
4135 }
4136
4137 ret = xhci_queue_slot_control(xhci, command, TRB_DISABLE_SLOT,
4138 slot_id);
4139 if (ret) {
4140 spin_unlock_irqrestore(&xhci->lock, flags);
4141 kfree(command);
4142 return ret;
4143 }
4144 xhci_ring_cmd_db(xhci);
4145 spin_unlock_irqrestore(&xhci->lock, flags);
4146
4147 wait_for_completion(command->completion);
4148
4149 if (command->status != COMP_SUCCESS)
4150 xhci_warn(xhci, "Unsuccessful disable slot %u command, status %d\n",
4151 slot_id, command->status);
4152
4153 xhci_free_command(xhci, command);
4154
4155 return 0;
4156 }
4157
xhci_disable_and_free_slot(struct xhci_hcd * xhci,u32 slot_id)4158 int xhci_disable_and_free_slot(struct xhci_hcd *xhci, u32 slot_id)
4159 {
4160 struct xhci_virt_device *vdev = xhci->devs[slot_id];
4161 int ret;
4162
4163 ret = xhci_disable_slot(xhci, slot_id);
4164 xhci_free_virt_device(xhci, vdev, slot_id);
4165 return ret;
4166 }
4167
4168 /*
4169 * Checks if we have enough host controller resources for the default control
4170 * endpoint.
4171 *
4172 * Must be called with xhci->lock held.
4173 */
xhci_reserve_host_control_ep_resources(struct xhci_hcd * xhci)4174 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
4175 {
4176 if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
4177 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
4178 "Not enough ep ctxs: "
4179 "%u active, need to add 1, limit is %u.",
4180 xhci->num_active_eps, xhci->limit_active_eps);
4181 return -ENOMEM;
4182 }
4183 xhci->num_active_eps += 1;
4184 xhci_dbg_trace(xhci, trace_xhci_dbg_quirks,
4185 "Adding 1 ep ctx, %u now active.",
4186 xhci->num_active_eps);
4187 return 0;
4188 }
4189
4190
4191 /*
4192 * Returns 0 if the xHC ran out of device slots, the Enable Slot command
4193 * timed out, or allocating memory failed. Returns 1 on success.
4194 */
xhci_alloc_dev(struct usb_hcd * hcd,struct usb_device * udev)4195 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
4196 {
4197 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4198 struct xhci_virt_device *vdev;
4199 struct xhci_slot_ctx *slot_ctx;
4200 unsigned long flags;
4201 int ret, slot_id;
4202 struct xhci_command *command;
4203
4204 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4205 if (!command)
4206 return 0;
4207
4208 spin_lock_irqsave(&xhci->lock, flags);
4209 ret = xhci_queue_slot_control(xhci, command, TRB_ENABLE_SLOT, 0);
4210 if (ret) {
4211 spin_unlock_irqrestore(&xhci->lock, flags);
4212 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
4213 xhci_free_command(xhci, command);
4214 return 0;
4215 }
4216 xhci_ring_cmd_db(xhci);
4217 spin_unlock_irqrestore(&xhci->lock, flags);
4218
4219 wait_for_completion(command->completion);
4220 slot_id = command->slot_id;
4221
4222 if (!slot_id || command->status != COMP_SUCCESS) {
4223 xhci_err(xhci, "Error while assigning device slot ID: %s\n",
4224 xhci_trb_comp_code_string(command->status));
4225 xhci_err(xhci, "Max number of devices this xHCI host supports is %u.\n",
4226 HCS_MAX_SLOTS(
4227 readl(&xhci->cap_regs->hcs_params1)));
4228 xhci_free_command(xhci, command);
4229 return 0;
4230 }
4231
4232 xhci_free_command(xhci, command);
4233
4234 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
4235 spin_lock_irqsave(&xhci->lock, flags);
4236 ret = xhci_reserve_host_control_ep_resources(xhci);
4237 if (ret) {
4238 spin_unlock_irqrestore(&xhci->lock, flags);
4239 xhci_warn(xhci, "Not enough host resources, "
4240 "active endpoint contexts = %u\n",
4241 xhci->num_active_eps);
4242 goto disable_slot;
4243 }
4244 spin_unlock_irqrestore(&xhci->lock, flags);
4245 }
4246 /* Use GFP_NOIO, since this function can be called from
4247 * xhci_discover_or_reset_device(), which may be called as part of
4248 * mass storage driver error handling.
4249 */
4250 if (!xhci_alloc_virt_device(xhci, slot_id, udev, GFP_NOIO)) {
4251 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
4252 goto disable_slot;
4253 }
4254 vdev = xhci->devs[slot_id];
4255 slot_ctx = xhci_get_slot_ctx(xhci, vdev->out_ctx);
4256 trace_xhci_alloc_dev(slot_ctx);
4257
4258 udev->slot_id = slot_id;
4259
4260 xhci_debugfs_create_slot(xhci, slot_id);
4261
4262 /*
4263 * If resetting upon resume, we can't put the controller into runtime
4264 * suspend if there is a device attached.
4265 */
4266 if (xhci->quirks & XHCI_RESET_ON_RESUME)
4267 pm_runtime_get_noresume(hcd->self.controller);
4268
4269 /* Is this a LS or FS device under a HS hub? */
4270 /* Hub or peripherial? */
4271 return 1;
4272
4273 disable_slot:
4274 xhci_disable_and_free_slot(xhci, udev->slot_id);
4275
4276 return 0;
4277 }
4278
4279 /**
4280 * xhci_setup_device - issues an Address Device command to assign a unique
4281 * USB bus address.
4282 * @hcd: USB host controller data structure.
4283 * @udev: USB dev structure representing the connected device.
4284 * @setup: Enum specifying setup mode: address only or with context.
4285 * @timeout_ms: Max wait time (ms) for the command operation to complete.
4286 *
4287 * Return: 0 if successful; otherwise, negative error code.
4288 */
xhci_setup_device(struct usb_hcd * hcd,struct usb_device * udev,enum xhci_setup_dev setup,unsigned int timeout_ms)4289 static int xhci_setup_device(struct usb_hcd *hcd, struct usb_device *udev,
4290 enum xhci_setup_dev setup, unsigned int timeout_ms)
4291 {
4292 const char *act = setup == SETUP_CONTEXT_ONLY ? "context" : "address";
4293 unsigned long flags;
4294 struct xhci_virt_device *virt_dev;
4295 int ret = 0;
4296 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4297 struct xhci_slot_ctx *slot_ctx;
4298 struct xhci_input_control_ctx *ctrl_ctx;
4299 u64 temp_64;
4300 struct xhci_command *command = NULL;
4301
4302 mutex_lock(&xhci->mutex);
4303
4304 if (xhci->xhc_state) { /* dying, removing or halted */
4305 ret = -ESHUTDOWN;
4306 goto out;
4307 }
4308
4309 if (!udev->slot_id) {
4310 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4311 "Bad Slot ID %d", udev->slot_id);
4312 ret = -EINVAL;
4313 goto out;
4314 }
4315
4316 virt_dev = xhci->devs[udev->slot_id];
4317
4318 if (WARN_ON(!virt_dev)) {
4319 /*
4320 * In plug/unplug torture test with an NEC controller,
4321 * a zero-dereference was observed once due to virt_dev = 0.
4322 * Print useful debug rather than crash if it is observed again!
4323 */
4324 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
4325 udev->slot_id);
4326 ret = -EINVAL;
4327 goto out;
4328 }
4329 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4330 trace_xhci_setup_device_slot(slot_ctx);
4331
4332 if (setup == SETUP_CONTEXT_ONLY) {
4333 if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
4334 SLOT_STATE_DEFAULT) {
4335 xhci_dbg(xhci, "Slot already in default state\n");
4336 goto out;
4337 }
4338 }
4339
4340 command = xhci_alloc_command(xhci, true, GFP_KERNEL);
4341 if (!command) {
4342 ret = -ENOMEM;
4343 goto out;
4344 }
4345
4346 command->in_ctx = virt_dev->in_ctx;
4347 command->timeout_ms = timeout_ms;
4348
4349 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
4350 ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
4351 if (!ctrl_ctx) {
4352 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4353 __func__);
4354 ret = -EINVAL;
4355 goto out;
4356 }
4357 /*
4358 * If this is the first Set Address since device plug-in or
4359 * virt_device realloaction after a resume with an xHCI power loss,
4360 * then set up the slot context.
4361 */
4362 if (!slot_ctx->dev_info)
4363 xhci_setup_addressable_virt_dev(xhci, udev);
4364 /* Otherwise, update the control endpoint ring enqueue pointer. */
4365 else
4366 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
4367 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
4368 ctrl_ctx->drop_flags = 0;
4369
4370 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4371 le32_to_cpu(slot_ctx->dev_info) >> 27);
4372
4373 trace_xhci_address_ctrl_ctx(ctrl_ctx);
4374 spin_lock_irqsave(&xhci->lock, flags);
4375 trace_xhci_setup_device(virt_dev);
4376 ret = xhci_queue_address_device(xhci, command, virt_dev->in_ctx->dma,
4377 udev->slot_id, setup);
4378 if (ret) {
4379 spin_unlock_irqrestore(&xhci->lock, flags);
4380 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4381 "FIXME: allocate a command ring segment");
4382 goto out;
4383 }
4384 xhci_ring_cmd_db(xhci);
4385 spin_unlock_irqrestore(&xhci->lock, flags);
4386
4387 /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
4388 wait_for_completion(command->completion);
4389
4390 /* FIXME: From section 4.3.4: "Software shall be responsible for timing
4391 * the SetAddress() "recovery interval" required by USB and aborting the
4392 * command on a timeout.
4393 */
4394 switch (command->status) {
4395 case COMP_COMMAND_ABORTED:
4396 case COMP_COMMAND_RING_STOPPED:
4397 xhci_warn(xhci, "Timeout while waiting for setup device command\n");
4398 ret = -ETIME;
4399 break;
4400 case COMP_CONTEXT_STATE_ERROR:
4401 case COMP_SLOT_NOT_ENABLED_ERROR:
4402 xhci_err(xhci, "Setup ERROR: setup %s command for slot %d.\n",
4403 act, udev->slot_id);
4404 ret = -EINVAL;
4405 break;
4406 case COMP_USB_TRANSACTION_ERROR:
4407 dev_warn(&udev->dev, "Device not responding to setup %s.\n", act);
4408
4409 mutex_unlock(&xhci->mutex);
4410 ret = xhci_disable_and_free_slot(xhci, udev->slot_id);
4411 if (!ret) {
4412 if (xhci_alloc_dev(hcd, udev) == 1)
4413 xhci_setup_addressable_virt_dev(xhci, udev);
4414 }
4415 kfree(command->completion);
4416 kfree(command);
4417 return -EPROTO;
4418 case COMP_INCOMPATIBLE_DEVICE_ERROR:
4419 dev_warn(&udev->dev,
4420 "ERROR: Incompatible device for setup %s command\n", act);
4421 ret = -ENODEV;
4422 break;
4423 case COMP_SUCCESS:
4424 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4425 "Successful setup %s command", act);
4426 break;
4427 default:
4428 xhci_err(xhci,
4429 "ERROR: unexpected setup %s command completion code 0x%x.\n",
4430 act, command->status);
4431 trace_xhci_address_ctx(xhci, virt_dev->out_ctx, 1);
4432 ret = -EINVAL;
4433 break;
4434 }
4435 if (ret)
4436 goto out;
4437 temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
4438 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4439 "Op regs DCBAA ptr = %#016llx", temp_64);
4440 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4441 "Slot ID %d dcbaa entry @%p = %#016llx",
4442 udev->slot_id,
4443 &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
4444 (unsigned long long)
4445 le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
4446 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4447 "Output Context DMA address = %#08llx",
4448 (unsigned long long)virt_dev->out_ctx->dma);
4449 trace_xhci_address_ctx(xhci, virt_dev->in_ctx,
4450 le32_to_cpu(slot_ctx->dev_info) >> 27);
4451 /*
4452 * USB core uses address 1 for the roothubs, so we add one to the
4453 * address given back to us by the HC.
4454 */
4455 trace_xhci_address_ctx(xhci, virt_dev->out_ctx,
4456 le32_to_cpu(slot_ctx->dev_info) >> 27);
4457 /* Zero the input context control for later use */
4458 ctrl_ctx->add_flags = 0;
4459 ctrl_ctx->drop_flags = 0;
4460 slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
4461 udev->devaddr = (u8)(le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4462
4463 xhci_dbg_trace(xhci, trace_xhci_dbg_address,
4464 "Internal device address = %d",
4465 le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
4466 out:
4467 mutex_unlock(&xhci->mutex);
4468 if (command) {
4469 kfree(command->completion);
4470 kfree(command);
4471 }
4472 return ret;
4473 }
4474
xhci_address_device(struct usb_hcd * hcd,struct usb_device * udev,unsigned int timeout_ms)4475 static int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev,
4476 unsigned int timeout_ms)
4477 {
4478 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ADDRESS, timeout_ms);
4479 }
4480
xhci_enable_device(struct usb_hcd * hcd,struct usb_device * udev)4481 static int xhci_enable_device(struct usb_hcd *hcd, struct usb_device *udev)
4482 {
4483 return xhci_setup_device(hcd, udev, SETUP_CONTEXT_ONLY,
4484 XHCI_CMD_DEFAULT_TIMEOUT);
4485 }
4486
4487 /*
4488 * Transfer the port index into real index in the HW port status
4489 * registers. Caculate offset between the port's PORTSC register
4490 * and port status base. Divide the number of per port register
4491 * to get the real index. The raw port number bases 1.
4492 */
xhci_find_raw_port_number(struct usb_hcd * hcd,int port1)4493 int xhci_find_raw_port_number(struct usb_hcd *hcd, int port1)
4494 {
4495 struct xhci_hub *rhub;
4496
4497 rhub = xhci_get_rhub(hcd);
4498 return rhub->ports[port1 - 1]->hw_portnum + 1;
4499 }
4500
4501 /*
4502 * Issue an Evaluate Context command to change the Maximum Exit Latency in the
4503 * slot context. If that succeeds, store the new MEL in the xhci_virt_device.
4504 */
xhci_change_max_exit_latency(struct xhci_hcd * xhci,struct usb_device * udev,u16 max_exit_latency)4505 static int __maybe_unused xhci_change_max_exit_latency(struct xhci_hcd *xhci,
4506 struct usb_device *udev, u16 max_exit_latency)
4507 {
4508 struct xhci_virt_device *virt_dev;
4509 struct xhci_command *command;
4510 struct xhci_input_control_ctx *ctrl_ctx;
4511 struct xhci_slot_ctx *slot_ctx;
4512 unsigned long flags;
4513 int ret;
4514
4515 command = xhci_alloc_command_with_ctx(xhci, true, GFP_KERNEL);
4516 if (!command)
4517 return -ENOMEM;
4518
4519 spin_lock_irqsave(&xhci->lock, flags);
4520
4521 virt_dev = xhci->devs[udev->slot_id];
4522
4523 /*
4524 * virt_dev might not exists yet if xHC resumed from hibernate (S4) and
4525 * xHC was re-initialized. Exit latency will be set later after
4526 * hub_port_finish_reset() is done and xhci->devs[] are re-allocated
4527 */
4528
4529 if (!virt_dev || max_exit_latency == virt_dev->current_mel) {
4530 spin_unlock_irqrestore(&xhci->lock, flags);
4531 xhci_free_command(xhci, command);
4532 return 0;
4533 }
4534
4535 /* Attempt to issue an Evaluate Context command to change the MEL. */
4536 ctrl_ctx = xhci_get_input_control_ctx(command->in_ctx);
4537 if (!ctrl_ctx) {
4538 spin_unlock_irqrestore(&xhci->lock, flags);
4539 xhci_free_command(xhci, command);
4540 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
4541 __func__);
4542 return -ENOMEM;
4543 }
4544
4545 xhci_slot_copy(xhci, command->in_ctx, virt_dev->out_ctx);
4546 spin_unlock_irqrestore(&xhci->lock, flags);
4547
4548 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4549 slot_ctx = xhci_get_slot_ctx(xhci, command->in_ctx);
4550 slot_ctx->dev_info2 &= cpu_to_le32(~((u32) MAX_EXIT));
4551 slot_ctx->dev_info2 |= cpu_to_le32(max_exit_latency);
4552 slot_ctx->dev_state = 0;
4553
4554 xhci_dbg_trace(xhci, trace_xhci_dbg_context_change,
4555 "Set up evaluate context for LPM MEL change.");
4556
4557 /* Issue and wait for the evaluate context command. */
4558 ret = xhci_configure_endpoint(xhci, udev, command,
4559 true, true);
4560
4561 if (!ret) {
4562 spin_lock_irqsave(&xhci->lock, flags);
4563 virt_dev->current_mel = max_exit_latency;
4564 spin_unlock_irqrestore(&xhci->lock, flags);
4565 }
4566
4567 xhci_free_command(xhci, command);
4568
4569 return ret;
4570 }
4571
4572 #ifdef CONFIG_PM
4573
4574 /* BESL to HIRD Encoding array for USB2 LPM */
4575 static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
4576 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
4577
4578 /* Calculate HIRD/BESL for USB2 PORTPMSC*/
xhci_calculate_hird_besl(struct xhci_hcd * xhci,struct usb_device * udev)4579 static int xhci_calculate_hird_besl(struct xhci_hcd *xhci,
4580 struct usb_device *udev)
4581 {
4582 int u2del, besl, besl_host;
4583 int besl_device = 0;
4584 u32 field;
4585
4586 u2del = HCS_U2_LATENCY(xhci->hcs_params3);
4587 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4588
4589 if (field & USB_BESL_SUPPORT) {
4590 for (besl_host = 0; besl_host < 16; besl_host++) {
4591 if (xhci_besl_encoding[besl_host] >= u2del)
4592 break;
4593 }
4594 /* Use baseline BESL value as default */
4595 if (field & USB_BESL_BASELINE_VALID)
4596 besl_device = USB_GET_BESL_BASELINE(field);
4597 else if (field & USB_BESL_DEEP_VALID)
4598 besl_device = USB_GET_BESL_DEEP(field);
4599 } else {
4600 if (u2del <= 50)
4601 besl_host = 0;
4602 else
4603 besl_host = (u2del - 51) / 75 + 1;
4604 }
4605
4606 besl = besl_host + besl_device;
4607 if (besl > 15)
4608 besl = 15;
4609
4610 return besl;
4611 }
4612
4613 /* Calculate BESLD, L1 timeout and HIRDM for USB2 PORTHLPMC */
xhci_calculate_usb2_hw_lpm_params(struct usb_device * udev)4614 static int xhci_calculate_usb2_hw_lpm_params(struct usb_device *udev)
4615 {
4616 u32 field;
4617 int l1;
4618 int besld = 0;
4619 int hirdm = 0;
4620
4621 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4622
4623 /* xHCI l1 is set in steps of 256us, xHCI 1.0 section 5.4.11.2 */
4624 l1 = udev->l1_params.timeout / 256;
4625
4626 /* device has preferred BESLD */
4627 if (field & USB_BESL_DEEP_VALID) {
4628 besld = USB_GET_BESL_DEEP(field);
4629 hirdm = 1;
4630 }
4631
4632 return PORT_BESLD(besld) | PORT_L1_TIMEOUT(l1) | PORT_HIRDM(hirdm);
4633 }
4634
xhci_set_usb2_hardware_lpm(struct usb_hcd * hcd,struct usb_device * udev,int enable)4635 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
4636 struct usb_device *udev, int enable)
4637 {
4638 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4639 struct xhci_port **ports;
4640 __le32 __iomem *pm_addr, *hlpm_addr;
4641 u32 pm_val, hlpm_val, field;
4642 unsigned int port_num;
4643 unsigned long flags;
4644 int hird, exit_latency;
4645 int ret;
4646
4647 if (xhci->quirks & XHCI_HW_LPM_DISABLE)
4648 return -EPERM;
4649
4650 if (hcd->speed >= HCD_USB3 || !xhci->hw_lpm_support ||
4651 !udev->lpm_capable)
4652 return -EPERM;
4653
4654 if (!udev->parent || udev->parent->parent ||
4655 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4656 return -EPERM;
4657
4658 if (udev->usb2_hw_lpm_capable != 1)
4659 return -EPERM;
4660
4661 spin_lock_irqsave(&xhci->lock, flags);
4662
4663 ports = xhci->usb2_rhub.ports;
4664 port_num = udev->portnum - 1;
4665 pm_addr = ports[port_num]->addr + PORTPMSC;
4666 pm_val = readl(pm_addr);
4667 hlpm_addr = ports[port_num]->addr + PORTHLPMC;
4668
4669 xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
4670 str_enable_disable(enable), port_num + 1);
4671
4672 if (enable) {
4673 /* Host supports BESL timeout instead of HIRD */
4674 if (udev->usb2_hw_lpm_besl_capable) {
4675 /* if device doesn't have a preferred BESL value use a
4676 * default one which works with mixed HIRD and BESL
4677 * systems. See XHCI_DEFAULT_BESL definition in xhci.h
4678 */
4679 field = le32_to_cpu(udev->bos->ext_cap->bmAttributes);
4680 if ((field & USB_BESL_SUPPORT) &&
4681 (field & USB_BESL_BASELINE_VALID))
4682 hird = USB_GET_BESL_BASELINE(field);
4683 else
4684 hird = udev->l1_params.besl;
4685
4686 exit_latency = xhci_besl_encoding[hird];
4687 spin_unlock_irqrestore(&xhci->lock, flags);
4688
4689 ret = xhci_change_max_exit_latency(xhci, udev,
4690 exit_latency);
4691 if (ret < 0)
4692 return ret;
4693 spin_lock_irqsave(&xhci->lock, flags);
4694
4695 hlpm_val = xhci_calculate_usb2_hw_lpm_params(udev);
4696 writel(hlpm_val, hlpm_addr);
4697 /* flush write */
4698 readl(hlpm_addr);
4699 } else {
4700 hird = xhci_calculate_hird_besl(xhci, udev);
4701 }
4702
4703 pm_val &= ~PORT_HIRD_MASK;
4704 pm_val |= PORT_HIRD(hird) | PORT_RWE | PORT_L1DS(udev->slot_id);
4705 writel(pm_val, pm_addr);
4706 pm_val = readl(pm_addr);
4707 pm_val |= PORT_HLE;
4708 writel(pm_val, pm_addr);
4709 /* flush write */
4710 readl(pm_addr);
4711 } else {
4712 pm_val &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK | PORT_L1DS_MASK);
4713 writel(pm_val, pm_addr);
4714 /* flush write */
4715 readl(pm_addr);
4716 if (udev->usb2_hw_lpm_besl_capable) {
4717 spin_unlock_irqrestore(&xhci->lock, flags);
4718 xhci_change_max_exit_latency(xhci, udev, 0);
4719 readl_poll_timeout(ports[port_num]->addr, pm_val,
4720 (pm_val & PORT_PLS_MASK) == XDEV_U0,
4721 100, 10000);
4722 return 0;
4723 }
4724 }
4725
4726 spin_unlock_irqrestore(&xhci->lock, flags);
4727 return 0;
4728 }
4729
xhci_update_device(struct usb_hcd * hcd,struct usb_device * udev)4730 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
4731 {
4732 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4733 struct xhci_port *port;
4734 u32 capability;
4735
4736 /* Check if USB3 device at root port is tunneled over USB4 */
4737 if (hcd->speed >= HCD_USB3 && !udev->parent->parent) {
4738 port = xhci->usb3_rhub.ports[udev->portnum - 1];
4739
4740 udev->tunnel_mode = xhci_port_is_tunneled(xhci, port);
4741 if (udev->tunnel_mode == USB_LINK_UNKNOWN)
4742 dev_dbg(&udev->dev, "link tunnel state unknown\n");
4743 else if (udev->tunnel_mode == USB_LINK_TUNNELED)
4744 dev_dbg(&udev->dev, "tunneled over USB4 link\n");
4745 else if (udev->tunnel_mode == USB_LINK_NATIVE)
4746 dev_dbg(&udev->dev, "native USB 3.x link\n");
4747 return 0;
4748 }
4749
4750 if (hcd->speed >= HCD_USB3 || !udev->lpm_capable || !xhci->hw_lpm_support)
4751 return 0;
4752
4753 /* we only support lpm for non-hub device connected to root hub yet */
4754 if (!udev->parent || udev->parent->parent ||
4755 udev->descriptor.bDeviceClass == USB_CLASS_HUB)
4756 return 0;
4757
4758 port = xhci->usb2_rhub.ports[udev->portnum - 1];
4759 capability = port->port_cap->protocol_caps;
4760
4761 if (capability & XHCI_HLC) {
4762 udev->usb2_hw_lpm_capable = 1;
4763 udev->l1_params.timeout = XHCI_L1_TIMEOUT;
4764 udev->l1_params.besl = XHCI_DEFAULT_BESL;
4765 if (capability & XHCI_BLC)
4766 udev->usb2_hw_lpm_besl_capable = 1;
4767 }
4768
4769 return 0;
4770 }
4771
4772 /*---------------------- USB 3.0 Link PM functions ------------------------*/
4773
4774 /* Service interval in nanoseconds = 2^(bInterval - 1) * 125us * 1000ns / 1us */
xhci_service_interval_to_ns(struct usb_endpoint_descriptor * desc)4775 static unsigned long long xhci_service_interval_to_ns(
4776 struct usb_endpoint_descriptor *desc)
4777 {
4778 return (1ULL << (desc->bInterval - 1)) * 125 * 1000;
4779 }
4780
xhci_get_timeout_no_hub_lpm(struct usb_device * udev,enum usb3_link_state state)4781 static u16 xhci_get_timeout_no_hub_lpm(struct usb_device *udev,
4782 enum usb3_link_state state)
4783 {
4784 unsigned long long sel;
4785 unsigned long long pel;
4786 unsigned int max_sel_pel;
4787 char *state_name;
4788
4789 switch (state) {
4790 case USB3_LPM_U1:
4791 /* Convert SEL and PEL stored in nanoseconds to microseconds */
4792 sel = DIV_ROUND_UP(udev->u1_params.sel, 1000);
4793 pel = DIV_ROUND_UP(udev->u1_params.pel, 1000);
4794 max_sel_pel = USB3_LPM_MAX_U1_SEL_PEL;
4795 state_name = "U1";
4796 break;
4797 case USB3_LPM_U2:
4798 sel = DIV_ROUND_UP(udev->u2_params.sel, 1000);
4799 pel = DIV_ROUND_UP(udev->u2_params.pel, 1000);
4800 max_sel_pel = USB3_LPM_MAX_U2_SEL_PEL;
4801 state_name = "U2";
4802 break;
4803 default:
4804 dev_warn(&udev->dev, "%s: Can't get timeout for non-U1 or U2 state.\n",
4805 __func__);
4806 return USB3_LPM_DISABLED;
4807 }
4808
4809 if (sel <= max_sel_pel && pel <= max_sel_pel)
4810 return USB3_LPM_DEVICE_INITIATED;
4811
4812 if (sel > max_sel_pel)
4813 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4814 "due to long SEL %llu ms\n",
4815 state_name, sel);
4816 else
4817 dev_dbg(&udev->dev, "Device-initiated %s disabled "
4818 "due to long PEL %llu ms\n",
4819 state_name, pel);
4820 return USB3_LPM_DISABLED;
4821 }
4822
4823 /* The U1 timeout should be the maximum of the following values:
4824 * - For control endpoints, U1 system exit latency (SEL) * 3
4825 * - For bulk endpoints, U1 SEL * 5
4826 * - For interrupt endpoints:
4827 * - Notification EPs, U1 SEL * 3
4828 * - Periodic EPs, max(105% of bInterval, U1 SEL * 2)
4829 * - For isochronous endpoints, max(105% of bInterval, U1 SEL * 2)
4830 */
xhci_calculate_intel_u1_timeout(struct usb_device * udev,struct usb_endpoint_descriptor * desc)4831 static unsigned long long xhci_calculate_intel_u1_timeout(
4832 struct usb_device *udev,
4833 struct usb_endpoint_descriptor *desc)
4834 {
4835 unsigned long long timeout_ns;
4836 int ep_type;
4837 int intr_type;
4838
4839 ep_type = usb_endpoint_type(desc);
4840 switch (ep_type) {
4841 case USB_ENDPOINT_XFER_CONTROL:
4842 timeout_ns = udev->u1_params.sel * 3;
4843 break;
4844 case USB_ENDPOINT_XFER_BULK:
4845 timeout_ns = udev->u1_params.sel * 5;
4846 break;
4847 case USB_ENDPOINT_XFER_INT:
4848 intr_type = usb_endpoint_interrupt_type(desc);
4849 if (intr_type == USB_ENDPOINT_INTR_NOTIFICATION) {
4850 timeout_ns = udev->u1_params.sel * 3;
4851 break;
4852 }
4853 /* Otherwise the calculation is the same as isoc eps */
4854 fallthrough;
4855 case USB_ENDPOINT_XFER_ISOC:
4856 timeout_ns = xhci_service_interval_to_ns(desc);
4857 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns * 105, 100);
4858 if (timeout_ns < udev->u1_params.sel * 2)
4859 timeout_ns = udev->u1_params.sel * 2;
4860 break;
4861 default:
4862 return 0;
4863 }
4864
4865 return timeout_ns;
4866 }
4867
4868 /* Returns the hub-encoded U1 timeout value. */
xhci_calculate_u1_timeout(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_endpoint_descriptor * desc)4869 static u16 xhci_calculate_u1_timeout(struct xhci_hcd *xhci,
4870 struct usb_device *udev,
4871 struct usb_endpoint_descriptor *desc)
4872 {
4873 unsigned long long timeout_ns;
4874
4875 /* Prevent U1 if service interval is shorter than U1 exit latency */
4876 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4877 if (xhci_service_interval_to_ns(desc) <= udev->u1_params.mel) {
4878 dev_dbg(&udev->dev, "Disable U1, ESIT shorter than exit latency\n");
4879 return USB3_LPM_DISABLED;
4880 }
4881 }
4882
4883 if (xhci->quirks & (XHCI_INTEL_HOST | XHCI_ZHAOXIN_HOST))
4884 timeout_ns = xhci_calculate_intel_u1_timeout(udev, desc);
4885 else
4886 timeout_ns = udev->u1_params.sel;
4887
4888 /* The U1 timeout is encoded in 1us intervals.
4889 * Don't return a timeout of zero, because that's USB3_LPM_DISABLED.
4890 */
4891 if (timeout_ns == USB3_LPM_DISABLED)
4892 timeout_ns = 1;
4893 else
4894 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 1000);
4895
4896 /* If the necessary timeout value is bigger than what we can set in the
4897 * USB 3.0 hub, we have to disable hub-initiated U1.
4898 */
4899 if (timeout_ns <= USB3_LPM_U1_MAX_TIMEOUT)
4900 return timeout_ns;
4901 dev_dbg(&udev->dev, "Hub-initiated U1 disabled due to long timeout %lluus\n",
4902 timeout_ns);
4903 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U1);
4904 }
4905
4906 /* The U2 timeout should be the maximum of:
4907 * - 10 ms (to avoid the bandwidth impact on the scheduler)
4908 * - largest bInterval of any active periodic endpoint (to avoid going
4909 * into lower power link states between intervals).
4910 * - the U2 Exit Latency of the device
4911 */
xhci_calculate_intel_u2_timeout(struct usb_device * udev,struct usb_endpoint_descriptor * desc)4912 static unsigned long long xhci_calculate_intel_u2_timeout(
4913 struct usb_device *udev,
4914 struct usb_endpoint_descriptor *desc)
4915 {
4916 unsigned long long timeout_ns;
4917 unsigned long long u2_del_ns;
4918
4919 timeout_ns = 10 * 1000 * 1000;
4920
4921 if ((usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) &&
4922 (xhci_service_interval_to_ns(desc) > timeout_ns))
4923 timeout_ns = xhci_service_interval_to_ns(desc);
4924
4925 u2_del_ns = le16_to_cpu(udev->bos->ss_cap->bU2DevExitLat) * 1000ULL;
4926 if (u2_del_ns > timeout_ns)
4927 timeout_ns = u2_del_ns;
4928
4929 return timeout_ns;
4930 }
4931
4932 /* Returns the hub-encoded U2 timeout value. */
xhci_calculate_u2_timeout(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_endpoint_descriptor * desc)4933 static u16 xhci_calculate_u2_timeout(struct xhci_hcd *xhci,
4934 struct usb_device *udev,
4935 struct usb_endpoint_descriptor *desc)
4936 {
4937 unsigned long long timeout_ns;
4938
4939 /* Prevent U2 if service interval is shorter than U2 exit latency */
4940 if (usb_endpoint_xfer_int(desc) || usb_endpoint_xfer_isoc(desc)) {
4941 if (xhci_service_interval_to_ns(desc) <= udev->u2_params.mel) {
4942 dev_dbg(&udev->dev, "Disable U2, ESIT shorter than exit latency\n");
4943 return USB3_LPM_DISABLED;
4944 }
4945 }
4946
4947 if (xhci->quirks & (XHCI_INTEL_HOST | XHCI_ZHAOXIN_HOST))
4948 timeout_ns = xhci_calculate_intel_u2_timeout(udev, desc);
4949 else
4950 timeout_ns = udev->u2_params.sel;
4951
4952 /* The U2 timeout is encoded in 256us intervals */
4953 timeout_ns = DIV_ROUND_UP_ULL(timeout_ns, 256 * 1000);
4954 /* If the necessary timeout value is bigger than what we can set in the
4955 * USB 3.0 hub, we have to disable hub-initiated U2.
4956 */
4957 if (timeout_ns <= USB3_LPM_U2_MAX_TIMEOUT)
4958 return timeout_ns;
4959 dev_dbg(&udev->dev, "Hub-initiated U2 disabled due to long timeout %lluus\n",
4960 timeout_ns * 256);
4961 return xhci_get_timeout_no_hub_lpm(udev, USB3_LPM_U2);
4962 }
4963
xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_endpoint_descriptor * desc,enum usb3_link_state state,u16 * timeout)4964 static u16 xhci_call_host_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4965 struct usb_device *udev,
4966 struct usb_endpoint_descriptor *desc,
4967 enum usb3_link_state state,
4968 u16 *timeout)
4969 {
4970 if (state == USB3_LPM_U1)
4971 return xhci_calculate_u1_timeout(xhci, udev, desc);
4972 else if (state == USB3_LPM_U2)
4973 return xhci_calculate_u2_timeout(xhci, udev, desc);
4974
4975 return USB3_LPM_DISABLED;
4976 }
4977
xhci_update_timeout_for_endpoint(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_endpoint_descriptor * desc,enum usb3_link_state state,u16 * timeout)4978 static int xhci_update_timeout_for_endpoint(struct xhci_hcd *xhci,
4979 struct usb_device *udev,
4980 struct usb_endpoint_descriptor *desc,
4981 enum usb3_link_state state,
4982 u16 *timeout)
4983 {
4984 u16 alt_timeout;
4985
4986 alt_timeout = xhci_call_host_update_timeout_for_endpoint(xhci, udev,
4987 desc, state, timeout);
4988
4989 /* If we found we can't enable hub-initiated LPM, and
4990 * the U1 or U2 exit latency was too high to allow
4991 * device-initiated LPM as well, then we will disable LPM
4992 * for this device, so stop searching any further.
4993 */
4994 if (alt_timeout == USB3_LPM_DISABLED) {
4995 *timeout = alt_timeout;
4996 return -E2BIG;
4997 }
4998 if (alt_timeout > *timeout)
4999 *timeout = alt_timeout;
5000 return 0;
5001 }
5002
xhci_update_timeout_for_interface(struct xhci_hcd * xhci,struct usb_device * udev,struct usb_host_interface * alt,enum usb3_link_state state,u16 * timeout)5003 static int xhci_update_timeout_for_interface(struct xhci_hcd *xhci,
5004 struct usb_device *udev,
5005 struct usb_host_interface *alt,
5006 enum usb3_link_state state,
5007 u16 *timeout)
5008 {
5009 int j;
5010
5011 for (j = 0; j < alt->desc.bNumEndpoints; j++) {
5012 if (xhci_update_timeout_for_endpoint(xhci, udev,
5013 &alt->endpoint[j].desc, state, timeout))
5014 return -E2BIG;
5015 }
5016 return 0;
5017 }
5018
xhci_check_tier_policy(struct xhci_hcd * xhci,struct usb_device * udev,enum usb3_link_state state)5019 static int xhci_check_tier_policy(struct xhci_hcd *xhci,
5020 struct usb_device *udev,
5021 enum usb3_link_state state)
5022 {
5023 struct usb_device *parent = udev->parent;
5024 int tier = 1; /* roothub is tier1 */
5025
5026 while (parent) {
5027 parent = parent->parent;
5028 tier++;
5029 }
5030
5031 if (xhci->quirks & XHCI_INTEL_HOST && tier > 3)
5032 goto fail;
5033 if (xhci->quirks & XHCI_ZHAOXIN_HOST && tier > 2)
5034 goto fail;
5035
5036 return 0;
5037 fail:
5038 dev_dbg(&udev->dev, "Tier policy prevents U1/U2 LPM states for devices at tier %d\n",
5039 tier);
5040 return -E2BIG;
5041 }
5042
5043 /* Returns the U1 or U2 timeout that should be enabled.
5044 * If the tier check or timeout setting functions return with a non-zero exit
5045 * code, that means the timeout value has been finalized and we shouldn't look
5046 * at any more endpoints.
5047 */
xhci_calculate_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)5048 static u16 xhci_calculate_lpm_timeout(struct usb_hcd *hcd,
5049 struct usb_device *udev, enum usb3_link_state state)
5050 {
5051 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5052 struct usb_host_config *config;
5053 char *state_name;
5054 int i;
5055 u16 timeout = USB3_LPM_DISABLED;
5056
5057 if (state == USB3_LPM_U1)
5058 state_name = "U1";
5059 else if (state == USB3_LPM_U2)
5060 state_name = "U2";
5061 else {
5062 dev_warn(&udev->dev, "Can't enable unknown link state %i\n",
5063 state);
5064 return timeout;
5065 }
5066
5067 /* Gather some information about the currently installed configuration
5068 * and alternate interface settings.
5069 */
5070 if (xhci_update_timeout_for_endpoint(xhci, udev, &udev->ep0.desc,
5071 state, &timeout))
5072 return timeout;
5073
5074 config = udev->actconfig;
5075 if (!config)
5076 return timeout;
5077
5078 for (i = 0; i < config->desc.bNumInterfaces; i++) {
5079 struct usb_driver *driver;
5080 struct usb_interface *intf = config->interface[i];
5081
5082 if (!intf)
5083 continue;
5084
5085 /* Check if any currently bound drivers want hub-initiated LPM
5086 * disabled.
5087 */
5088 if (intf->dev.driver) {
5089 driver = to_usb_driver(intf->dev.driver);
5090 if (driver && driver->disable_hub_initiated_lpm) {
5091 dev_dbg(&udev->dev, "Hub-initiated %s disabled at request of driver %s\n",
5092 state_name, driver->name);
5093 timeout = xhci_get_timeout_no_hub_lpm(udev,
5094 state);
5095 if (timeout == USB3_LPM_DISABLED)
5096 return timeout;
5097 }
5098 }
5099
5100 /* Not sure how this could happen... */
5101 if (!intf->cur_altsetting)
5102 continue;
5103
5104 if (xhci_update_timeout_for_interface(xhci, udev,
5105 intf->cur_altsetting,
5106 state, &timeout))
5107 return timeout;
5108 }
5109 return timeout;
5110 }
5111
calculate_max_exit_latency(struct usb_device * udev,enum usb3_link_state state_changed,u16 hub_encoded_timeout)5112 static int calculate_max_exit_latency(struct usb_device *udev,
5113 enum usb3_link_state state_changed,
5114 u16 hub_encoded_timeout)
5115 {
5116 unsigned long long u1_mel_us = 0;
5117 unsigned long long u2_mel_us = 0;
5118 unsigned long long mel_us = 0;
5119 bool disabling_u1;
5120 bool disabling_u2;
5121 bool enabling_u1;
5122 bool enabling_u2;
5123
5124 disabling_u1 = (state_changed == USB3_LPM_U1 &&
5125 hub_encoded_timeout == USB3_LPM_DISABLED);
5126 disabling_u2 = (state_changed == USB3_LPM_U2 &&
5127 hub_encoded_timeout == USB3_LPM_DISABLED);
5128
5129 enabling_u1 = (state_changed == USB3_LPM_U1 &&
5130 hub_encoded_timeout != USB3_LPM_DISABLED);
5131 enabling_u2 = (state_changed == USB3_LPM_U2 &&
5132 hub_encoded_timeout != USB3_LPM_DISABLED);
5133
5134 /* If U1 was already enabled and we're not disabling it,
5135 * or we're going to enable U1, account for the U1 max exit latency.
5136 */
5137 if ((udev->u1_params.timeout != USB3_LPM_DISABLED && !disabling_u1) ||
5138 enabling_u1)
5139 u1_mel_us = DIV_ROUND_UP(udev->u1_params.mel, 1000);
5140 if ((udev->u2_params.timeout != USB3_LPM_DISABLED && !disabling_u2) ||
5141 enabling_u2)
5142 u2_mel_us = DIV_ROUND_UP(udev->u2_params.mel, 1000);
5143
5144 mel_us = max(u1_mel_us, u2_mel_us);
5145
5146 /* xHCI host controller max exit latency field is only 16 bits wide. */
5147 if (mel_us > MAX_EXIT) {
5148 dev_warn(&udev->dev, "Link PM max exit latency of %lluus "
5149 "is too big.\n", mel_us);
5150 return -E2BIG;
5151 }
5152 return mel_us;
5153 }
5154
5155 /* Returns the USB3 hub-encoded value for the U1/U2 timeout. */
xhci_enable_usb3_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)5156 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
5157 struct usb_device *udev, enum usb3_link_state state)
5158 {
5159 struct xhci_hcd *xhci;
5160 struct xhci_port *port;
5161 u16 hub_encoded_timeout;
5162 int mel;
5163 int ret;
5164
5165 xhci = hcd_to_xhci(hcd);
5166 /* The LPM timeout values are pretty host-controller specific, so don't
5167 * enable hub-initiated timeouts unless the vendor has provided
5168 * information about their timeout algorithm.
5169 */
5170 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
5171 !xhci->devs[udev->slot_id])
5172 return USB3_LPM_DISABLED;
5173
5174 if (xhci_check_tier_policy(xhci, udev, state) < 0)
5175 return USB3_LPM_DISABLED;
5176
5177 /* If connected to root port then check port can handle lpm */
5178 if (udev->parent && !udev->parent->parent) {
5179 port = xhci->usb3_rhub.ports[udev->portnum - 1];
5180 if (port->lpm_incapable)
5181 return USB3_LPM_DISABLED;
5182 }
5183
5184 hub_encoded_timeout = xhci_calculate_lpm_timeout(hcd, udev, state);
5185 mel = calculate_max_exit_latency(udev, state, hub_encoded_timeout);
5186 if (mel < 0) {
5187 /* Max Exit Latency is too big, disable LPM. */
5188 hub_encoded_timeout = USB3_LPM_DISABLED;
5189 mel = 0;
5190 }
5191
5192 ret = xhci_change_max_exit_latency(xhci, udev, mel);
5193 if (ret)
5194 return ret;
5195 return hub_encoded_timeout;
5196 }
5197
xhci_disable_usb3_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)5198 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
5199 struct usb_device *udev, enum usb3_link_state state)
5200 {
5201 struct xhci_hcd *xhci;
5202 u16 mel;
5203
5204 xhci = hcd_to_xhci(hcd);
5205 if (!xhci || !(xhci->quirks & XHCI_LPM_SUPPORT) ||
5206 !xhci->devs[udev->slot_id])
5207 return 0;
5208
5209 mel = calculate_max_exit_latency(udev, state, USB3_LPM_DISABLED);
5210 return xhci_change_max_exit_latency(xhci, udev, mel);
5211 }
5212 #else /* CONFIG_PM */
5213
xhci_set_usb2_hardware_lpm(struct usb_hcd * hcd,struct usb_device * udev,int enable)5214 static int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
5215 struct usb_device *udev, int enable)
5216 {
5217 return 0;
5218 }
5219
xhci_update_device(struct usb_hcd * hcd,struct usb_device * udev)5220 static int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
5221 {
5222 return 0;
5223 }
5224
xhci_enable_usb3_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)5225 static int xhci_enable_usb3_lpm_timeout(struct usb_hcd *hcd,
5226 struct usb_device *udev, enum usb3_link_state state)
5227 {
5228 return USB3_LPM_DISABLED;
5229 }
5230
xhci_disable_usb3_lpm_timeout(struct usb_hcd * hcd,struct usb_device * udev,enum usb3_link_state state)5231 static int xhci_disable_usb3_lpm_timeout(struct usb_hcd *hcd,
5232 struct usb_device *udev, enum usb3_link_state state)
5233 {
5234 return 0;
5235 }
5236 #endif /* CONFIG_PM */
5237
5238 /*-------------------------------------------------------------------------*/
5239
5240 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
5241 * internal data structures for the device.
5242 */
xhci_update_hub_device(struct usb_hcd * hcd,struct usb_device * hdev,struct usb_tt * tt,gfp_t mem_flags)5243 int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
5244 struct usb_tt *tt, gfp_t mem_flags)
5245 {
5246 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5247 struct xhci_virt_device *vdev;
5248 struct xhci_command *config_cmd;
5249 struct xhci_input_control_ctx *ctrl_ctx;
5250 struct xhci_slot_ctx *slot_ctx;
5251 unsigned long flags;
5252 unsigned think_time;
5253 int ret;
5254
5255 /* Ignore root hubs */
5256 if (!hdev->parent)
5257 return 0;
5258
5259 vdev = xhci->devs[hdev->slot_id];
5260 if (!vdev) {
5261 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
5262 return -EINVAL;
5263 }
5264
5265 config_cmd = xhci_alloc_command_with_ctx(xhci, true, mem_flags);
5266 if (!config_cmd)
5267 return -ENOMEM;
5268
5269 ctrl_ctx = xhci_get_input_control_ctx(config_cmd->in_ctx);
5270 if (!ctrl_ctx) {
5271 xhci_warn(xhci, "%s: Could not get input context, bad type.\n",
5272 __func__);
5273 xhci_free_command(xhci, config_cmd);
5274 return -ENOMEM;
5275 }
5276
5277 spin_lock_irqsave(&xhci->lock, flags);
5278 if (hdev->speed == USB_SPEED_HIGH &&
5279 xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
5280 xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
5281 xhci_free_command(xhci, config_cmd);
5282 spin_unlock_irqrestore(&xhci->lock, flags);
5283 return -ENOMEM;
5284 }
5285
5286 xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
5287 ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
5288 slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
5289 slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
5290 /*
5291 * refer to section 6.2.2: MTT should be 0 for full speed hub,
5292 * but it may be already set to 1 when setup an xHCI virtual
5293 * device, so clear it anyway.
5294 */
5295 if (tt->multi)
5296 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
5297 else if (hdev->speed == USB_SPEED_FULL)
5298 slot_ctx->dev_info &= cpu_to_le32(~DEV_MTT);
5299
5300 if (xhci->hci_version > 0x95) {
5301 xhci_dbg(xhci, "xHCI version %x needs hub "
5302 "TT think time and number of ports\n",
5303 (unsigned int) xhci->hci_version);
5304 slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
5305 /* Set TT think time - convert from ns to FS bit times.
5306 * 0 = 8 FS bit times, 1 = 16 FS bit times,
5307 * 2 = 24 FS bit times, 3 = 32 FS bit times.
5308 *
5309 * xHCI 1.0: this field shall be 0 if the device is not a
5310 * High-spped hub.
5311 */
5312 think_time = tt->think_time;
5313 if (think_time != 0)
5314 think_time = (think_time / 666) - 1;
5315 if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
5316 slot_ctx->tt_info |=
5317 cpu_to_le32(TT_THINK_TIME(think_time));
5318 } else {
5319 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
5320 "TT think time or number of ports\n",
5321 (unsigned int) xhci->hci_version);
5322 }
5323 slot_ctx->dev_state = 0;
5324 spin_unlock_irqrestore(&xhci->lock, flags);
5325
5326 xhci_dbg(xhci, "Set up %s for hub device.\n",
5327 (xhci->hci_version > 0x95) ?
5328 "configure endpoint" : "evaluate context");
5329
5330 /* Issue and wait for the configure endpoint or
5331 * evaluate context command.
5332 */
5333 if (xhci->hci_version > 0x95)
5334 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5335 false, false);
5336 else
5337 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
5338 true, false);
5339
5340 xhci_free_command(xhci, config_cmd);
5341 return ret;
5342 }
5343 EXPORT_SYMBOL_GPL(xhci_update_hub_device);
5344
xhci_get_frame(struct usb_hcd * hcd)5345 static int xhci_get_frame(struct usb_hcd *hcd)
5346 {
5347 struct xhci_hcd *xhci = hcd_to_xhci(hcd);
5348 /* EHCI mods by the periodic size. Why? */
5349 return readl(&xhci->run_regs->microframe_index) >> 3;
5350 }
5351
xhci_hcd_init_usb2_data(struct xhci_hcd * xhci,struct usb_hcd * hcd)5352 static void xhci_hcd_init_usb2_data(struct xhci_hcd *xhci, struct usb_hcd *hcd)
5353 {
5354 xhci->usb2_rhub.hcd = hcd;
5355 hcd->speed = HCD_USB2;
5356 hcd->self.root_hub->speed = USB_SPEED_HIGH;
5357 /*
5358 * USB 2.0 roothub under xHCI has an integrated TT,
5359 * (rate matching hub) as opposed to having an OHCI/UHCI
5360 * companion controller.
5361 */
5362 hcd->has_tt = 1;
5363 }
5364
xhci_hcd_init_usb3_data(struct xhci_hcd * xhci,struct usb_hcd * hcd)5365 static void xhci_hcd_init_usb3_data(struct xhci_hcd *xhci, struct usb_hcd *hcd)
5366 {
5367 unsigned int minor_rev;
5368
5369 /*
5370 * Early xHCI 1.1 spec did not mention USB 3.1 capable hosts
5371 * should return 0x31 for sbrn, or that the minor revision
5372 * is a two digit BCD containig minor and sub-minor numbers.
5373 * This was later clarified in xHCI 1.2.
5374 *
5375 * Some USB 3.1 capable hosts therefore have sbrn 0x30, and
5376 * minor revision set to 0x1 instead of 0x10.
5377 */
5378 if (xhci->usb3_rhub.min_rev == 0x1)
5379 minor_rev = 1;
5380 else
5381 minor_rev = xhci->usb3_rhub.min_rev / 0x10;
5382
5383 switch (minor_rev) {
5384 case 2:
5385 hcd->speed = HCD_USB32;
5386 hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5387 hcd->self.root_hub->rx_lanes = 2;
5388 hcd->self.root_hub->tx_lanes = 2;
5389 hcd->self.root_hub->ssp_rate = USB_SSP_GEN_2x2;
5390 break;
5391 case 1:
5392 hcd->speed = HCD_USB31;
5393 hcd->self.root_hub->speed = USB_SPEED_SUPER_PLUS;
5394 hcd->self.root_hub->ssp_rate = USB_SSP_GEN_2x1;
5395 break;
5396 }
5397 xhci_info(xhci, "Host supports USB 3.%x %sSuperSpeed\n",
5398 minor_rev, minor_rev ? "Enhanced " : "");
5399
5400 xhci->usb3_rhub.hcd = hcd;
5401 }
5402
xhci_gen_setup(struct usb_hcd * hcd,xhci_get_quirks_t get_quirks)5403 int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
5404 {
5405 struct xhci_hcd *xhci;
5406 /*
5407 * TODO: Check with DWC3 clients for sysdev according to
5408 * quirks
5409 */
5410 struct device *dev = hcd->self.sysdev;
5411 int retval;
5412
5413 /* Accept arbitrarily long scatter-gather lists */
5414 hcd->self.sg_tablesize = ~0;
5415
5416 /* support to build packet from discontinuous buffers */
5417 hcd->self.no_sg_constraint = 1;
5418
5419 /* XHCI controllers don't stop the ep queue on short packets :| */
5420 hcd->self.no_stop_on_short = 1;
5421
5422 xhci = hcd_to_xhci(hcd);
5423
5424 if (!usb_hcd_is_primary_hcd(hcd)) {
5425 xhci_hcd_init_usb3_data(xhci, hcd);
5426 return 0;
5427 }
5428
5429 mutex_init(&xhci->mutex);
5430 xhci->main_hcd = hcd;
5431 xhci->cap_regs = hcd->regs;
5432 xhci->op_regs = hcd->regs +
5433 HC_LENGTH(readl(&xhci->cap_regs->hc_capbase));
5434 xhci->run_regs = hcd->regs +
5435 (readl(&xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
5436 /* Cache read-only capability registers */
5437 xhci->hcs_params1 = readl(&xhci->cap_regs->hcs_params1);
5438 xhci->hcs_params2 = readl(&xhci->cap_regs->hcs_params2);
5439 xhci->hcs_params3 = readl(&xhci->cap_regs->hcs_params3);
5440 xhci->hci_version = HC_VERSION(readl(&xhci->cap_regs->hc_capbase));
5441 xhci->hcc_params = readl(&xhci->cap_regs->hcc_params);
5442 if (xhci->hci_version > 0x100)
5443 xhci->hcc_params2 = readl(&xhci->cap_regs->hcc_params2);
5444
5445 /* xhci-plat or xhci-pci might have set max_interrupters already */
5446 if ((!xhci->max_interrupters) ||
5447 xhci->max_interrupters > HCS_MAX_INTRS(xhci->hcs_params1))
5448 xhci->max_interrupters = HCS_MAX_INTRS(xhci->hcs_params1);
5449
5450 xhci->quirks |= quirks;
5451
5452 if (get_quirks)
5453 get_quirks(dev, xhci);
5454
5455 /* In xhci controllers which follow xhci 1.0 spec gives a spurious
5456 * success event after a short transfer. This quirk will ignore such
5457 * spurious event.
5458 */
5459 if (xhci->hci_version > 0x96)
5460 xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
5461
5462 if (xhci->hci_version == 0x95 && link_quirk) {
5463 xhci_dbg(xhci, "QUIRK: Not clearing Link TRB chain bits");
5464 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
5465 }
5466
5467 /* Make sure the HC is halted. */
5468 retval = xhci_halt(xhci);
5469 if (retval)
5470 return retval;
5471
5472 xhci_zero_64b_regs(xhci);
5473
5474 xhci_dbg(xhci, "Resetting HCD\n");
5475 /* Reset the internal HC memory state and registers. */
5476 retval = xhci_reset(xhci, XHCI_RESET_LONG_USEC);
5477 if (retval)
5478 return retval;
5479 xhci_dbg(xhci, "Reset complete\n");
5480
5481 /*
5482 * On some xHCI controllers (e.g. R-Car SoCs), the AC64 bit (bit 0)
5483 * of HCCPARAMS1 is set to 1. However, the xHCs don't support 64-bit
5484 * address memory pointers actually. So, this driver clears the AC64
5485 * bit of xhci->hcc_params to call dma_set_coherent_mask(dev,
5486 * DMA_BIT_MASK(32)) in this xhci_gen_setup().
5487 */
5488 if (xhci->quirks & XHCI_NO_64BIT_SUPPORT)
5489 xhci->hcc_params &= ~BIT(0);
5490
5491 /* Set dma_mask and coherent_dma_mask to 64-bits,
5492 * if xHC supports 64-bit addressing */
5493 if (HCC_64BIT_ADDR(xhci->hcc_params) &&
5494 !dma_set_mask(dev, DMA_BIT_MASK(64))) {
5495 xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
5496 dma_set_coherent_mask(dev, DMA_BIT_MASK(64));
5497 } else {
5498 /*
5499 * This is to avoid error in cases where a 32-bit USB
5500 * controller is used on a 64-bit capable system.
5501 */
5502 retval = dma_set_mask(dev, DMA_BIT_MASK(32));
5503 if (retval)
5504 return retval;
5505 xhci_dbg(xhci, "Enabling 32-bit DMA addresses.\n");
5506 dma_set_coherent_mask(dev, DMA_BIT_MASK(32));
5507 }
5508
5509 xhci_dbg(xhci, "Calling HCD init\n");
5510 /* Initialize HCD and host controller data structures. */
5511 retval = xhci_init(hcd);
5512 if (retval)
5513 return retval;
5514 xhci_dbg(xhci, "Called HCD init\n");
5515
5516 if (xhci_hcd_is_usb3(hcd))
5517 xhci_hcd_init_usb3_data(xhci, hcd);
5518 else
5519 xhci_hcd_init_usb2_data(xhci, hcd);
5520
5521 xhci_info(xhci, "hcc params 0x%08x hci version 0x%x quirks 0x%016llx\n",
5522 xhci->hcc_params, xhci->hci_version, xhci->quirks);
5523
5524 return 0;
5525 }
5526 EXPORT_SYMBOL_GPL(xhci_gen_setup);
5527
xhci_clear_tt_buffer_complete(struct usb_hcd * hcd,struct usb_host_endpoint * ep)5528 static void xhci_clear_tt_buffer_complete(struct usb_hcd *hcd,
5529 struct usb_host_endpoint *ep)
5530 {
5531 struct xhci_hcd *xhci;
5532 struct usb_device *udev;
5533 unsigned int slot_id;
5534 unsigned int ep_index;
5535 unsigned long flags;
5536
5537 xhci = hcd_to_xhci(hcd);
5538
5539 spin_lock_irqsave(&xhci->lock, flags);
5540 udev = (struct usb_device *)ep->hcpriv;
5541 slot_id = udev->slot_id;
5542 ep_index = xhci_get_endpoint_index(&ep->desc);
5543
5544 xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_CLEARING_TT;
5545 xhci_ring_doorbell_for_active_rings(xhci, slot_id, ep_index);
5546 spin_unlock_irqrestore(&xhci->lock, flags);
5547 }
5548
5549 static const struct hc_driver xhci_hc_driver = {
5550 .description = "xhci-hcd",
5551 .product_desc = "xHCI Host Controller",
5552 .hcd_priv_size = sizeof(struct xhci_hcd),
5553
5554 /*
5555 * generic hardware linkage
5556 */
5557 .irq = xhci_irq,
5558 .flags = HCD_MEMORY | HCD_DMA | HCD_USB3 | HCD_SHARED |
5559 HCD_BH,
5560
5561 /*
5562 * basic lifecycle operations
5563 */
5564 .reset = NULL, /* set in xhci_init_driver() */
5565 .start = xhci_run,
5566 .stop = xhci_stop,
5567 .shutdown = xhci_shutdown,
5568
5569 /*
5570 * managing i/o requests and associated device resources
5571 */
5572 .map_urb_for_dma = xhci_map_urb_for_dma,
5573 .unmap_urb_for_dma = xhci_unmap_urb_for_dma,
5574 .urb_enqueue = xhci_urb_enqueue,
5575 .urb_dequeue = xhci_urb_dequeue,
5576 .alloc_dev = xhci_alloc_dev,
5577 .free_dev = xhci_free_dev,
5578 .alloc_streams = xhci_alloc_streams,
5579 .free_streams = xhci_free_streams,
5580 .add_endpoint = xhci_add_endpoint,
5581 .drop_endpoint = xhci_drop_endpoint,
5582 .endpoint_disable = xhci_endpoint_disable,
5583 .endpoint_reset = xhci_endpoint_reset,
5584 .check_bandwidth = xhci_check_bandwidth,
5585 .reset_bandwidth = xhci_reset_bandwidth,
5586 .address_device = xhci_address_device,
5587 .enable_device = xhci_enable_device,
5588 .update_hub_device = xhci_update_hub_device,
5589 .reset_device = xhci_discover_or_reset_device,
5590
5591 /*
5592 * scheduling support
5593 */
5594 .get_frame_number = xhci_get_frame,
5595
5596 /*
5597 * root hub support
5598 */
5599 .hub_control = xhci_hub_control,
5600 .hub_status_data = xhci_hub_status_data,
5601 .bus_suspend = xhci_bus_suspend,
5602 .bus_resume = xhci_bus_resume,
5603 .get_resuming_ports = xhci_get_resuming_ports,
5604
5605 /*
5606 * call back when device connected and addressed
5607 */
5608 .update_device = xhci_update_device,
5609 .set_usb2_hw_lpm = xhci_set_usb2_hardware_lpm,
5610 .enable_usb3_lpm_timeout = xhci_enable_usb3_lpm_timeout,
5611 .disable_usb3_lpm_timeout = xhci_disable_usb3_lpm_timeout,
5612 .find_raw_port_number = xhci_find_raw_port_number,
5613 .clear_tt_buffer_complete = xhci_clear_tt_buffer_complete,
5614 };
5615
xhci_init_driver(struct hc_driver * drv,const struct xhci_driver_overrides * over)5616 void xhci_init_driver(struct hc_driver *drv,
5617 const struct xhci_driver_overrides *over)
5618 {
5619 BUG_ON(!over);
5620
5621 /* Copy the generic table to drv then apply the overrides */
5622 *drv = xhci_hc_driver;
5623
5624 if (over) {
5625 drv->hcd_priv_size += over->extra_priv_size;
5626 if (over->reset)
5627 drv->reset = over->reset;
5628 if (over->start)
5629 drv->start = over->start;
5630 if (over->add_endpoint)
5631 drv->add_endpoint = over->add_endpoint;
5632 if (over->drop_endpoint)
5633 drv->drop_endpoint = over->drop_endpoint;
5634 if (over->check_bandwidth)
5635 drv->check_bandwidth = over->check_bandwidth;
5636 if (over->reset_bandwidth)
5637 drv->reset_bandwidth = over->reset_bandwidth;
5638 if (over->update_hub_device)
5639 drv->update_hub_device = over->update_hub_device;
5640 if (over->hub_control)
5641 drv->hub_control = over->hub_control;
5642 }
5643 }
5644 EXPORT_SYMBOL_GPL(xhci_init_driver);
5645
5646 MODULE_DESCRIPTION(DRIVER_DESC);
5647 MODULE_AUTHOR(DRIVER_AUTHOR);
5648 MODULE_LICENSE("GPL");
5649
xhci_hcd_init(void)5650 static int __init xhci_hcd_init(void)
5651 {
5652 /*
5653 * Check the compiler generated sizes of structures that must be laid
5654 * out in specific ways for hardware access.
5655 */
5656 BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
5657 BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
5658 BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
5659 /* xhci_device_control has eight fields, and also
5660 * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
5661 */
5662 BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
5663 BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
5664 BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
5665 BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 8*32/8);
5666 BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
5667 /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
5668 BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
5669
5670 if (usb_disabled())
5671 return -ENODEV;
5672
5673 xhci_debugfs_create_root();
5674 xhci_dbc_init();
5675
5676 return 0;
5677 }
5678
5679 /*
5680 * If an init function is provided, an exit function must also be provided
5681 * to allow module unload.
5682 */
xhci_hcd_fini(void)5683 static void __exit xhci_hcd_fini(void)
5684 {
5685 xhci_debugfs_remove_root();
5686 xhci_dbc_exit();
5687 }
5688
5689 module_init(xhci_hcd_init);
5690 module_exit(xhci_hcd_fini);
5691