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