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