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