usb: host: xhci: Fix Null pointer dereferencing with 71c731a for non-x86 systems
[pandora-kernel.git] / drivers / usb / host / xhci.c
1 /*
2  * xHCI host controller driver
3  *
4  * Copyright (C) 2008 Intel Corp.
5  *
6  * Author: Sarah Sharp
7  * Some code borrowed from the Linux EHCI driver.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16  * for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22
23 #include <linux/pci.h>
24 #include <linux/irq.h>
25 #include <linux/log2.h>
26 #include <linux/module.h>
27 #include <linux/moduleparam.h>
28 #include <linux/slab.h>
29 #include <linux/dmi.h>
30
31 #include "xhci.h"
32
33 #define DRIVER_AUTHOR "Sarah Sharp"
34 #define DRIVER_DESC "'eXtensible' Host Controller (xHC) Driver"
35
36 /* Some 0.95 hardware can't handle the chain bit on a Link TRB being cleared */
37 static int link_quirk;
38 module_param(link_quirk, int, S_IRUGO | S_IWUSR);
39 MODULE_PARM_DESC(link_quirk, "Don't clear the chain bit on a link TRB");
40
41 /* TODO: copied from ehci-hcd.c - can this be refactored? */
42 /*
43  * handshake - spin reading hc until handshake completes or fails
44  * @ptr: address of hc register to be read
45  * @mask: bits to look at in result of read
46  * @done: value of those bits when handshake succeeds
47  * @usec: timeout in microseconds
48  *
49  * Returns negative errno, or zero on success
50  *
51  * Success happens when the "mask" bits have the specified value (hardware
52  * handshake done).  There are two failure modes:  "usec" have passed (major
53  * hardware flakeout), or the register reads as all-ones (hardware removed).
54  */
55 int handshake(struct xhci_hcd *xhci, void __iomem *ptr,
56                       u32 mask, u32 done, int usec)
57 {
58         u32     result;
59
60         do {
61                 result = xhci_readl(xhci, ptr);
62                 if (result == ~(u32)0)          /* card removed */
63                         return -ENODEV;
64                 result &= mask;
65                 if (result == done)
66                         return 0;
67                 udelay(1);
68                 usec--;
69         } while (usec > 0);
70         return -ETIMEDOUT;
71 }
72
73 /*
74  * Disable interrupts and begin the xHCI halting process.
75  */
76 void xhci_quiesce(struct xhci_hcd *xhci)
77 {
78         u32 halted;
79         u32 cmd;
80         u32 mask;
81
82         mask = ~(XHCI_IRQS);
83         halted = xhci_readl(xhci, &xhci->op_regs->status) & STS_HALT;
84         if (!halted)
85                 mask &= ~CMD_RUN;
86
87         cmd = xhci_readl(xhci, &xhci->op_regs->command);
88         cmd &= mask;
89         xhci_writel(xhci, cmd, &xhci->op_regs->command);
90 }
91
92 /*
93  * Force HC into halt state.
94  *
95  * Disable any IRQs and clear the run/stop bit.
96  * HC will complete any current and actively pipelined transactions, and
97  * should halt within 16 ms of the run/stop bit being cleared.
98  * Read HC Halted bit in the status register to see when the HC is finished.
99  */
100 int xhci_halt(struct xhci_hcd *xhci)
101 {
102         int ret;
103         xhci_dbg(xhci, "// Halt the HC\n");
104         xhci_quiesce(xhci);
105
106         ret = handshake(xhci, &xhci->op_regs->status,
107                         STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
108         if (!ret) {
109                 xhci->xhc_state |= XHCI_STATE_HALTED;
110                 xhci->cmd_ring_state = CMD_RING_STATE_STOPPED;
111         } else
112                 xhci_warn(xhci, "Host not halted after %u microseconds.\n",
113                                 XHCI_MAX_HALT_USEC);
114         return ret;
115 }
116
117 /*
118  * Set the run bit and wait for the host to be running.
119  */
120 static int xhci_start(struct xhci_hcd *xhci)
121 {
122         u32 temp;
123         int ret;
124
125         temp = xhci_readl(xhci, &xhci->op_regs->command);
126         temp |= (CMD_RUN);
127         xhci_dbg(xhci, "// Turn on HC, cmd = 0x%x.\n",
128                         temp);
129         xhci_writel(xhci, temp, &xhci->op_regs->command);
130
131         /*
132          * Wait for the HCHalted Status bit to be 0 to indicate the host is
133          * running.
134          */
135         ret = handshake(xhci, &xhci->op_regs->status,
136                         STS_HALT, 0, XHCI_MAX_HALT_USEC);
137         if (ret == -ETIMEDOUT)
138                 xhci_err(xhci, "Host took too long to start, "
139                                 "waited %u microseconds.\n",
140                                 XHCI_MAX_HALT_USEC);
141         if (!ret)
142                 xhci->xhc_state &= ~XHCI_STATE_HALTED;
143         return ret;
144 }
145
146 /*
147  * Reset a halted HC.
148  *
149  * This resets pipelines, timers, counters, state machines, etc.
150  * Transactions will be terminated immediately, and operational registers
151  * will be set to their defaults.
152  */
153 int xhci_reset(struct xhci_hcd *xhci)
154 {
155         u32 command;
156         u32 state;
157         int ret;
158
159         state = xhci_readl(xhci, &xhci->op_regs->status);
160         if ((state & STS_HALT) == 0) {
161                 xhci_warn(xhci, "Host controller not halted, aborting reset.\n");
162                 return 0;
163         }
164
165         xhci_dbg(xhci, "// Reset the HC\n");
166         command = xhci_readl(xhci, &xhci->op_regs->command);
167         command |= CMD_RESET;
168         xhci_writel(xhci, command, &xhci->op_regs->command);
169
170         ret = handshake(xhci, &xhci->op_regs->command,
171                         CMD_RESET, 0, 10 * 1000 * 1000);
172         if (ret)
173                 return ret;
174
175         xhci_dbg(xhci, "Wait for controller to be ready for doorbell rings\n");
176         /*
177          * xHCI cannot write to any doorbells or operational registers other
178          * than status until the "Controller Not Ready" flag is cleared.
179          */
180         return handshake(xhci, &xhci->op_regs->status,
181                          STS_CNR, 0, 10 * 1000 * 1000);
182 }
183
184 #ifdef CONFIG_PCI
185 static int xhci_free_msi(struct xhci_hcd *xhci)
186 {
187         int i;
188
189         if (!xhci->msix_entries)
190                 return -EINVAL;
191
192         for (i = 0; i < xhci->msix_count; i++)
193                 if (xhci->msix_entries[i].vector)
194                         free_irq(xhci->msix_entries[i].vector,
195                                         xhci_to_hcd(xhci));
196         return 0;
197 }
198
199 /*
200  * Set up MSI
201  */
202 static int xhci_setup_msi(struct xhci_hcd *xhci)
203 {
204         int ret;
205         struct pci_dev  *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
206
207         ret = pci_enable_msi(pdev);
208         if (ret) {
209                 xhci_err(xhci, "failed to allocate MSI entry\n");
210                 return ret;
211         }
212
213         ret = request_irq(pdev->irq, (irq_handler_t)xhci_msi_irq,
214                                 0, "xhci_hcd", xhci_to_hcd(xhci));
215         if (ret) {
216                 xhci_err(xhci, "disable MSI interrupt\n");
217                 pci_disable_msi(pdev);
218         }
219
220         return ret;
221 }
222
223 /*
224  * Free IRQs
225  * free all IRQs request
226  */
227 static void xhci_free_irq(struct xhci_hcd *xhci)
228 {
229         struct pci_dev *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
230         int ret;
231
232         /* return if using legacy interrupt */
233         if (xhci_to_hcd(xhci)->irq >= 0)
234                 return;
235
236         ret = xhci_free_msi(xhci);
237         if (!ret)
238                 return;
239         if (pdev->irq >= 0)
240                 free_irq(pdev->irq, xhci_to_hcd(xhci));
241
242         return;
243 }
244
245 /*
246  * Set up MSI-X
247  */
248 static int xhci_setup_msix(struct xhci_hcd *xhci)
249 {
250         int i, ret = 0;
251         struct usb_hcd *hcd = xhci_to_hcd(xhci);
252         struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
253
254         /*
255          * calculate number of msi-x vectors supported.
256          * - HCS_MAX_INTRS: the max number of interrupts the host can handle,
257          *   with max number of interrupters based on the xhci HCSPARAMS1.
258          * - num_online_cpus: maximum msi-x vectors per CPUs core.
259          *   Add additional 1 vector to ensure always available interrupt.
260          */
261         xhci->msix_count = min(num_online_cpus() + 1,
262                                 HCS_MAX_INTRS(xhci->hcs_params1));
263
264         xhci->msix_entries =
265                 kmalloc((sizeof(struct msix_entry))*xhci->msix_count,
266                                 GFP_KERNEL);
267         if (!xhci->msix_entries) {
268                 xhci_err(xhci, "Failed to allocate MSI-X entries\n");
269                 return -ENOMEM;
270         }
271
272         for (i = 0; i < xhci->msix_count; i++) {
273                 xhci->msix_entries[i].entry = i;
274                 xhci->msix_entries[i].vector = 0;
275         }
276
277         ret = pci_enable_msix(pdev, xhci->msix_entries, xhci->msix_count);
278         if (ret) {
279                 xhci_err(xhci, "Failed to enable MSI-X\n");
280                 goto free_entries;
281         }
282
283         for (i = 0; i < xhci->msix_count; i++) {
284                 ret = request_irq(xhci->msix_entries[i].vector,
285                                 (irq_handler_t)xhci_msi_irq,
286                                 0, "xhci_hcd", xhci_to_hcd(xhci));
287                 if (ret)
288                         goto disable_msix;
289         }
290
291         hcd->msix_enabled = 1;
292         return ret;
293
294 disable_msix:
295         xhci_err(xhci, "disable MSI-X interrupt\n");
296         xhci_free_irq(xhci);
297         pci_disable_msix(pdev);
298 free_entries:
299         kfree(xhci->msix_entries);
300         xhci->msix_entries = NULL;
301         return ret;
302 }
303
304 /* Free any IRQs and disable MSI-X */
305 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
306 {
307         struct usb_hcd *hcd = xhci_to_hcd(xhci);
308         struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
309
310         xhci_free_irq(xhci);
311
312         if (xhci->msix_entries) {
313                 pci_disable_msix(pdev);
314                 kfree(xhci->msix_entries);
315                 xhci->msix_entries = NULL;
316         } else {
317                 pci_disable_msi(pdev);
318         }
319
320         hcd->msix_enabled = 0;
321         return;
322 }
323
324 static void xhci_msix_sync_irqs(struct xhci_hcd *xhci)
325 {
326         int i;
327
328         if (xhci->msix_entries) {
329                 for (i = 0; i < xhci->msix_count; i++)
330                         synchronize_irq(xhci->msix_entries[i].vector);
331         }
332 }
333
334 static int xhci_try_enable_msi(struct usb_hcd *hcd)
335 {
336         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
337         struct pci_dev  *pdev = to_pci_dev(xhci_to_hcd(xhci)->self.controller);
338         int ret;
339
340         /*
341          * Some Fresco Logic host controllers advertise MSI, but fail to
342          * generate interrupts.  Don't even try to enable MSI.
343          */
344         if (xhci->quirks & XHCI_BROKEN_MSI)
345                 return 0;
346
347         /* unregister the legacy interrupt */
348         if (hcd->irq)
349                 free_irq(hcd->irq, hcd);
350         hcd->irq = -1;
351
352         ret = xhci_setup_msix(xhci);
353         if (ret)
354                 /* fall back to msi*/
355                 ret = xhci_setup_msi(xhci);
356
357         if (!ret)
358                 /* hcd->irq is -1, we have MSI */
359                 return 0;
360
361         if (!pdev->irq) {
362                 xhci_err(xhci, "No msi-x/msi found and no IRQ in BIOS\n");
363                 return -EINVAL;
364         }
365
366         /* fall back to legacy interrupt*/
367         ret = request_irq(pdev->irq, &usb_hcd_irq, IRQF_SHARED,
368                         hcd->irq_descr, hcd);
369         if (ret) {
370                 xhci_err(xhci, "request interrupt %d failed\n",
371                                 pdev->irq);
372                 return ret;
373         }
374         hcd->irq = pdev->irq;
375         return 0;
376 }
377
378 #else
379
380 static int xhci_try_enable_msi(struct usb_hcd *hcd)
381 {
382         return 0;
383 }
384
385 static void xhci_cleanup_msix(struct xhci_hcd *xhci)
386 {
387 }
388
389 static void xhci_msix_sync_irqs(struct xhci_hcd *xhci)
390 {
391 }
392
393 #endif
394
395 static void compliance_mode_recovery(unsigned long arg)
396 {
397         struct xhci_hcd *xhci;
398         struct usb_hcd *hcd;
399         u32 temp;
400         int i;
401
402         xhci = (struct xhci_hcd *)arg;
403
404         for (i = 0; i < xhci->num_usb3_ports; i++) {
405                 temp = xhci_readl(xhci, xhci->usb3_ports[i]);
406                 if ((temp & PORT_PLS_MASK) == USB_SS_PORT_LS_COMP_MOD) {
407                         /*
408                          * Compliance Mode Detected. Letting USB Core
409                          * handle the Warm Reset
410                          */
411                         xhci_dbg(xhci, "Compliance Mode Detected->Port %d!\n",
412                                         i + 1);
413                         xhci_dbg(xhci, "Attempting Recovery routine!\n");
414                         hcd = xhci->shared_hcd;
415
416                         if (hcd->state == HC_STATE_SUSPENDED)
417                                 usb_hcd_resume_root_hub(hcd);
418
419                         usb_hcd_poll_rh_status(hcd);
420                 }
421         }
422
423         if (xhci->port_status_u0 != ((1 << xhci->num_usb3_ports)-1))
424                 mod_timer(&xhci->comp_mode_recovery_timer,
425                         jiffies + msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
426 }
427
428 /*
429  * Quirk to work around issue generated by the SN65LVPE502CP USB3.0 re-driver
430  * that causes ports behind that hardware to enter compliance mode sometimes.
431  * The quirk creates a timer that polls every 2 seconds the link state of
432  * each host controller's port and recovers it by issuing a Warm reset
433  * if Compliance mode is detected, otherwise the port will become "dead" (no
434  * device connections or disconnections will be detected anymore). Becasue no
435  * status event is generated when entering compliance mode (per xhci spec),
436  * this quirk is needed on systems that have the failing hardware installed.
437  */
438 static void compliance_mode_recovery_timer_init(struct xhci_hcd *xhci)
439 {
440         xhci->port_status_u0 = 0;
441         init_timer(&xhci->comp_mode_recovery_timer);
442
443         xhci->comp_mode_recovery_timer.data = (unsigned long) xhci;
444         xhci->comp_mode_recovery_timer.function = compliance_mode_recovery;
445         xhci->comp_mode_recovery_timer.expires = jiffies +
446                         msecs_to_jiffies(COMP_MODE_RCVRY_MSECS);
447
448         set_timer_slack(&xhci->comp_mode_recovery_timer,
449                         msecs_to_jiffies(COMP_MODE_RCVRY_MSECS));
450         add_timer(&xhci->comp_mode_recovery_timer);
451         xhci_dbg(xhci, "Compliance Mode Recovery Timer Initialized.\n");
452 }
453
454 /*
455  * This function identifies the systems that have installed the SN65LVPE502CP
456  * USB3.0 re-driver and that need the Compliance Mode Quirk.
457  * Systems:
458  * Vendor: Hewlett-Packard -> System Models: Z420, Z620 and Z820
459  */
460 static bool compliance_mode_recovery_timer_quirk_check(void)
461 {
462         const char *dmi_product_name, *dmi_sys_vendor;
463
464         dmi_product_name = dmi_get_system_info(DMI_PRODUCT_NAME);
465         dmi_sys_vendor = dmi_get_system_info(DMI_SYS_VENDOR);
466         if (!dmi_product_name || !dmi_sys_vendor)
467                 return false;
468
469         if (!(strstr(dmi_sys_vendor, "Hewlett-Packard")))
470                 return false;
471
472         if (strstr(dmi_product_name, "Z420") ||
473                         strstr(dmi_product_name, "Z620") ||
474                         strstr(dmi_product_name, "Z820"))
475                 return true;
476
477         return false;
478 }
479
480 static int xhci_all_ports_seen_u0(struct xhci_hcd *xhci)
481 {
482         return (xhci->port_status_u0 == ((1 << xhci->num_usb3_ports)-1));
483 }
484
485
486 /*
487  * Initialize memory for HCD and xHC (one-time init).
488  *
489  * Program the PAGESIZE register, initialize the device context array, create
490  * device contexts (?), set up a command ring segment (or two?), create event
491  * ring (one for now).
492  */
493 int xhci_init(struct usb_hcd *hcd)
494 {
495         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
496         int retval = 0;
497
498         xhci_dbg(xhci, "xhci_init\n");
499         spin_lock_init(&xhci->lock);
500         if (xhci->hci_version == 0x95 && link_quirk) {
501                 xhci_dbg(xhci, "QUIRK: Not clearing Link TRB chain bits.\n");
502                 xhci->quirks |= XHCI_LINK_TRB_QUIRK;
503         } else {
504                 xhci_dbg(xhci, "xHCI doesn't need link TRB QUIRK\n");
505         }
506         retval = xhci_mem_init(xhci, GFP_KERNEL);
507         xhci_dbg(xhci, "Finished xhci_init\n");
508
509         /* Initializing Compliance Mode Recovery Data If Needed */
510         if (compliance_mode_recovery_timer_quirk_check()) {
511                 xhci->quirks |= XHCI_COMP_MODE_QUIRK;
512                 compliance_mode_recovery_timer_init(xhci);
513         }
514
515         return retval;
516 }
517
518 /*-------------------------------------------------------------------------*/
519
520
521 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
522 static void xhci_event_ring_work(unsigned long arg)
523 {
524         unsigned long flags;
525         int temp;
526         u64 temp_64;
527         struct xhci_hcd *xhci = (struct xhci_hcd *) arg;
528         int i, j;
529
530         xhci_dbg(xhci, "Poll event ring: %lu\n", jiffies);
531
532         spin_lock_irqsave(&xhci->lock, flags);
533         temp = xhci_readl(xhci, &xhci->op_regs->status);
534         xhci_dbg(xhci, "op reg status = 0x%x\n", temp);
535         if (temp == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
536                         (xhci->xhc_state & XHCI_STATE_HALTED)) {
537                 xhci_dbg(xhci, "HW died, polling stopped.\n");
538                 spin_unlock_irqrestore(&xhci->lock, flags);
539                 return;
540         }
541
542         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
543         xhci_dbg(xhci, "ir_set 0 pending = 0x%x\n", temp);
544         xhci_dbg(xhci, "HC error bitmask = 0x%x\n", xhci->error_bitmask);
545         xhci->error_bitmask = 0;
546         xhci_dbg(xhci, "Event ring:\n");
547         xhci_debug_segment(xhci, xhci->event_ring->deq_seg);
548         xhci_dbg_ring_ptrs(xhci, xhci->event_ring);
549         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
550         temp_64 &= ~ERST_PTR_MASK;
551         xhci_dbg(xhci, "ERST deq = 64'h%0lx\n", (long unsigned int) temp_64);
552         xhci_dbg(xhci, "Command ring:\n");
553         xhci_debug_segment(xhci, xhci->cmd_ring->deq_seg);
554         xhci_dbg_ring_ptrs(xhci, xhci->cmd_ring);
555         xhci_dbg_cmd_ptrs(xhci);
556         for (i = 0; i < MAX_HC_SLOTS; ++i) {
557                 if (!xhci->devs[i])
558                         continue;
559                 for (j = 0; j < 31; ++j) {
560                         xhci_dbg_ep_rings(xhci, i, j, &xhci->devs[i]->eps[j]);
561                 }
562         }
563         spin_unlock_irqrestore(&xhci->lock, flags);
564
565         if (!xhci->zombie)
566                 mod_timer(&xhci->event_ring_timer, jiffies + POLL_TIMEOUT * HZ);
567         else
568                 xhci_dbg(xhci, "Quit polling the event ring.\n");
569 }
570 #endif
571
572 static int xhci_run_finished(struct xhci_hcd *xhci)
573 {
574         if (xhci_start(xhci)) {
575                 xhci_halt(xhci);
576                 return -ENODEV;
577         }
578         xhci->shared_hcd->state = HC_STATE_RUNNING;
579         xhci->cmd_ring_state = CMD_RING_STATE_RUNNING;
580
581         if (xhci->quirks & XHCI_NEC_HOST)
582                 xhci_ring_cmd_db(xhci);
583
584         xhci_dbg(xhci, "Finished xhci_run for USB3 roothub\n");
585         return 0;
586 }
587
588 /*
589  * Start the HC after it was halted.
590  *
591  * This function is called by the USB core when the HC driver is added.
592  * Its opposite is xhci_stop().
593  *
594  * xhci_init() must be called once before this function can be called.
595  * Reset the HC, enable device slot contexts, program DCBAAP, and
596  * set command ring pointer and event ring pointer.
597  *
598  * Setup MSI-X vectors and enable interrupts.
599  */
600 int xhci_run(struct usb_hcd *hcd)
601 {
602         u32 temp;
603         u64 temp_64;
604         int ret;
605         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
606
607         /* Start the xHCI host controller running only after the USB 2.0 roothub
608          * is setup.
609          */
610
611         hcd->uses_new_polling = 1;
612         if (!usb_hcd_is_primary_hcd(hcd))
613                 return xhci_run_finished(xhci);
614
615         xhci_dbg(xhci, "xhci_run\n");
616
617         ret = xhci_try_enable_msi(hcd);
618         if (ret)
619                 return ret;
620
621 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
622         init_timer(&xhci->event_ring_timer);
623         xhci->event_ring_timer.data = (unsigned long) xhci;
624         xhci->event_ring_timer.function = xhci_event_ring_work;
625         /* Poll the event ring */
626         xhci->event_ring_timer.expires = jiffies + POLL_TIMEOUT * HZ;
627         xhci->zombie = 0;
628         xhci_dbg(xhci, "Setting event ring polling timer\n");
629         add_timer(&xhci->event_ring_timer);
630 #endif
631
632         xhci_dbg(xhci, "Command ring memory map follows:\n");
633         xhci_debug_ring(xhci, xhci->cmd_ring);
634         xhci_dbg_ring_ptrs(xhci, xhci->cmd_ring);
635         xhci_dbg_cmd_ptrs(xhci);
636
637         xhci_dbg(xhci, "ERST memory map follows:\n");
638         xhci_dbg_erst(xhci, &xhci->erst);
639         xhci_dbg(xhci, "Event ring:\n");
640         xhci_debug_ring(xhci, xhci->event_ring);
641         xhci_dbg_ring_ptrs(xhci, xhci->event_ring);
642         temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
643         temp_64 &= ~ERST_PTR_MASK;
644         xhci_dbg(xhci, "ERST deq = 64'h%0lx\n", (long unsigned int) temp_64);
645
646         xhci_dbg(xhci, "// Set the interrupt modulation register\n");
647         temp = xhci_readl(xhci, &xhci->ir_set->irq_control);
648         temp &= ~ER_IRQ_INTERVAL_MASK;
649         temp |= (u32) 160;
650         xhci_writel(xhci, temp, &xhci->ir_set->irq_control);
651
652         /* Set the HCD state before we enable the irqs */
653         temp = xhci_readl(xhci, &xhci->op_regs->command);
654         temp |= (CMD_EIE);
655         xhci_dbg(xhci, "// Enable interrupts, cmd = 0x%x.\n",
656                         temp);
657         xhci_writel(xhci, temp, &xhci->op_regs->command);
658
659         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
660         xhci_dbg(xhci, "// Enabling event ring interrupter %p by writing 0x%x to irq_pending\n",
661                         xhci->ir_set, (unsigned int) ER_IRQ_ENABLE(temp));
662         xhci_writel(xhci, ER_IRQ_ENABLE(temp),
663                         &xhci->ir_set->irq_pending);
664         xhci_print_ir_set(xhci, 0);
665
666         if (xhci->quirks & XHCI_NEC_HOST)
667                 xhci_queue_vendor_command(xhci, 0, 0, 0,
668                                 TRB_TYPE(TRB_NEC_GET_FW));
669
670         xhci_dbg(xhci, "Finished xhci_run for USB2 roothub\n");
671         return 0;
672 }
673
674 static void xhci_only_stop_hcd(struct usb_hcd *hcd)
675 {
676         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
677
678         spin_lock_irq(&xhci->lock);
679         xhci_halt(xhci);
680
681         /* The shared_hcd is going to be deallocated shortly (the USB core only
682          * calls this function when allocation fails in usb_add_hcd(), or
683          * usb_remove_hcd() is called).  So we need to unset xHCI's pointer.
684          */
685         xhci->shared_hcd = NULL;
686         spin_unlock_irq(&xhci->lock);
687 }
688
689 /*
690  * Stop xHCI driver.
691  *
692  * This function is called by the USB core when the HC driver is removed.
693  * Its opposite is xhci_run().
694  *
695  * Disable device contexts, disable IRQs, and quiesce the HC.
696  * Reset the HC, finish any completed transactions, and cleanup memory.
697  */
698 void xhci_stop(struct usb_hcd *hcd)
699 {
700         u32 temp;
701         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
702
703         if (!usb_hcd_is_primary_hcd(hcd)) {
704                 xhci_only_stop_hcd(xhci->shared_hcd);
705                 return;
706         }
707
708         spin_lock_irq(&xhci->lock);
709         /* Make sure the xHC is halted for a USB3 roothub
710          * (xhci_stop() could be called as part of failed init).
711          */
712         xhci_halt(xhci);
713         xhci_reset(xhci);
714         spin_unlock_irq(&xhci->lock);
715
716         xhci_cleanup_msix(xhci);
717
718 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
719         /* Tell the event ring poll function not to reschedule */
720         xhci->zombie = 1;
721         del_timer_sync(&xhci->event_ring_timer);
722 #endif
723
724         /* Deleting Compliance Mode Recovery Timer */
725         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
726                         (!(xhci_all_ports_seen_u0(xhci))))
727                 del_timer_sync(&xhci->comp_mode_recovery_timer);
728
729         if (xhci->quirks & XHCI_AMD_PLL_FIX)
730                 usb_amd_dev_put();
731
732         xhci_dbg(xhci, "// Disabling event ring interrupts\n");
733         temp = xhci_readl(xhci, &xhci->op_regs->status);
734         xhci_writel(xhci, temp & ~STS_EINT, &xhci->op_regs->status);
735         temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
736         xhci_writel(xhci, ER_IRQ_DISABLE(temp),
737                         &xhci->ir_set->irq_pending);
738         xhci_print_ir_set(xhci, 0);
739
740         xhci_dbg(xhci, "cleaning up memory\n");
741         xhci_mem_cleanup(xhci);
742         xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
743                     xhci_readl(xhci, &xhci->op_regs->status));
744 }
745
746 /*
747  * Shutdown HC (not bus-specific)
748  *
749  * This is called when the machine is rebooting or halting.  We assume that the
750  * machine will be powered off, and the HC's internal state will be reset.
751  * Don't bother to free memory.
752  *
753  * This will only ever be called with the main usb_hcd (the USB3 roothub).
754  */
755 void xhci_shutdown(struct usb_hcd *hcd)
756 {
757         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
758
759         if (xhci->quirks & XHCI_SPURIOUS_REBOOT)
760                 usb_disable_xhci_ports(to_pci_dev(hcd->self.controller));
761
762         spin_lock_irq(&xhci->lock);
763         xhci_halt(xhci);
764         spin_unlock_irq(&xhci->lock);
765
766         xhci_cleanup_msix(xhci);
767
768         xhci_dbg(xhci, "xhci_shutdown completed - status = %x\n",
769                     xhci_readl(xhci, &xhci->op_regs->status));
770 }
771
772 #ifdef CONFIG_PM
773 static void xhci_save_registers(struct xhci_hcd *xhci)
774 {
775         xhci->s3.command = xhci_readl(xhci, &xhci->op_regs->command);
776         xhci->s3.dev_nt = xhci_readl(xhci, &xhci->op_regs->dev_notification);
777         xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
778         xhci->s3.config_reg = xhci_readl(xhci, &xhci->op_regs->config_reg);
779         xhci->s3.erst_size = xhci_readl(xhci, &xhci->ir_set->erst_size);
780         xhci->s3.erst_base = xhci_read_64(xhci, &xhci->ir_set->erst_base);
781         xhci->s3.erst_dequeue = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
782         xhci->s3.irq_pending = xhci_readl(xhci, &xhci->ir_set->irq_pending);
783         xhci->s3.irq_control = xhci_readl(xhci, &xhci->ir_set->irq_control);
784 }
785
786 static void xhci_restore_registers(struct xhci_hcd *xhci)
787 {
788         xhci_writel(xhci, xhci->s3.command, &xhci->op_regs->command);
789         xhci_writel(xhci, xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
790         xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
791         xhci_writel(xhci, xhci->s3.config_reg, &xhci->op_regs->config_reg);
792         xhci_writel(xhci, xhci->s3.erst_size, &xhci->ir_set->erst_size);
793         xhci_write_64(xhci, xhci->s3.erst_base, &xhci->ir_set->erst_base);
794         xhci_write_64(xhci, xhci->s3.erst_dequeue, &xhci->ir_set->erst_dequeue);
795         xhci_writel(xhci, xhci->s3.irq_pending, &xhci->ir_set->irq_pending);
796         xhci_writel(xhci, xhci->s3.irq_control, &xhci->ir_set->irq_control);
797 }
798
799 static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
800 {
801         u64     val_64;
802
803         /* step 2: initialize command ring buffer */
804         val_64 = xhci_read_64(xhci, &xhci->op_regs->cmd_ring);
805         val_64 = (val_64 & (u64) CMD_RING_RSVD_BITS) |
806                 (xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg,
807                                       xhci->cmd_ring->dequeue) &
808                  (u64) ~CMD_RING_RSVD_BITS) |
809                 xhci->cmd_ring->cycle_state;
810         xhci_dbg(xhci, "// Setting command ring address to 0x%llx\n",
811                         (long unsigned long) val_64);
812         xhci_write_64(xhci, val_64, &xhci->op_regs->cmd_ring);
813 }
814
815 /*
816  * The whole command ring must be cleared to zero when we suspend the host.
817  *
818  * The host doesn't save the command ring pointer in the suspend well, so we
819  * need to re-program it on resume.  Unfortunately, the pointer must be 64-byte
820  * aligned, because of the reserved bits in the command ring dequeue pointer
821  * register.  Therefore, we can't just set the dequeue pointer back in the
822  * middle of the ring (TRBs are 16-byte aligned).
823  */
824 static void xhci_clear_command_ring(struct xhci_hcd *xhci)
825 {
826         struct xhci_ring *ring;
827         struct xhci_segment *seg;
828
829         ring = xhci->cmd_ring;
830         seg = ring->deq_seg;
831         do {
832                 memset(seg->trbs, 0,
833                         sizeof(union xhci_trb) * (TRBS_PER_SEGMENT - 1));
834                 seg->trbs[TRBS_PER_SEGMENT - 1].link.control &=
835                         cpu_to_le32(~TRB_CYCLE);
836                 seg = seg->next;
837         } while (seg != ring->deq_seg);
838
839         /* Reset the software enqueue and dequeue pointers */
840         ring->deq_seg = ring->first_seg;
841         ring->dequeue = ring->first_seg->trbs;
842         ring->enq_seg = ring->deq_seg;
843         ring->enqueue = ring->dequeue;
844
845         /*
846          * Ring is now zeroed, so the HW should look for change of ownership
847          * when the cycle bit is set to 1.
848          */
849         ring->cycle_state = 1;
850
851         /*
852          * Reset the hardware dequeue pointer.
853          * Yes, this will need to be re-written after resume, but we're paranoid
854          * and want to make sure the hardware doesn't access bogus memory
855          * because, say, the BIOS or an SMI started the host without changing
856          * the command ring pointers.
857          */
858         xhci_set_cmd_ring_deq(xhci);
859 }
860
861 /*
862  * Stop HC (not bus-specific)
863  *
864  * This is called when the machine transition into S3/S4 mode.
865  *
866  */
867 int xhci_suspend(struct xhci_hcd *xhci)
868 {
869         int                     rc = 0;
870         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
871         u32                     command;
872
873         spin_lock_irq(&xhci->lock);
874         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
875         clear_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
876         /* step 1: stop endpoint */
877         /* skipped assuming that port suspend has done */
878
879         /* step 2: clear Run/Stop bit */
880         command = xhci_readl(xhci, &xhci->op_regs->command);
881         command &= ~CMD_RUN;
882         xhci_writel(xhci, command, &xhci->op_regs->command);
883         if (handshake(xhci, &xhci->op_regs->status,
884                       STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC)) {
885                 xhci_warn(xhci, "WARN: xHC CMD_RUN timeout\n");
886                 spin_unlock_irq(&xhci->lock);
887                 return -ETIMEDOUT;
888         }
889         xhci_clear_command_ring(xhci);
890
891         /* step 3: save registers */
892         xhci_save_registers(xhci);
893
894         /* step 4: set CSS flag */
895         command = xhci_readl(xhci, &xhci->op_regs->command);
896         command |= CMD_CSS;
897         xhci_writel(xhci, command, &xhci->op_regs->command);
898         if (handshake(xhci, &xhci->op_regs->status, STS_SAVE, 0, 10 * 1000)) {
899                 xhci_warn(xhci, "WARN: xHC save state timeout\n");
900                 spin_unlock_irq(&xhci->lock);
901                 return -ETIMEDOUT;
902         }
903         spin_unlock_irq(&xhci->lock);
904
905         /*
906          * Deleting Compliance Mode Recovery Timer because the xHCI Host
907          * is about to be suspended.
908          */
909         if ((xhci->quirks & XHCI_COMP_MODE_QUIRK) &&
910                         (!(xhci_all_ports_seen_u0(xhci)))) {
911                 del_timer_sync(&xhci->comp_mode_recovery_timer);
912                 xhci_dbg(xhci, "Compliance Mode Recovery Timer Deleted!\n");
913         }
914
915         /* step 5: remove core well power */
916         /* synchronize irq when using MSI-X */
917         xhci_msix_sync_irqs(xhci);
918
919         return rc;
920 }
921
922 /*
923  * start xHC (not bus-specific)
924  *
925  * This is called when the machine transition from S3/S4 mode.
926  *
927  */
928 int xhci_resume(struct xhci_hcd *xhci, bool hibernated)
929 {
930         u32                     command, temp = 0;
931         struct usb_hcd          *hcd = xhci_to_hcd(xhci);
932         struct usb_hcd          *secondary_hcd;
933         int                     retval = 0;
934
935         /* Wait a bit if either of the roothubs need to settle from the
936          * transition into bus suspend.
937          */
938         if (time_before(jiffies, xhci->bus_state[0].next_statechange) ||
939                         time_before(jiffies,
940                                 xhci->bus_state[1].next_statechange))
941                 msleep(100);
942
943         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
944         set_bit(HCD_FLAG_HW_ACCESSIBLE, &xhci->shared_hcd->flags);
945
946         spin_lock_irq(&xhci->lock);
947         if (xhci->quirks & XHCI_RESET_ON_RESUME)
948                 hibernated = true;
949
950         if (!hibernated) {
951                 /* step 1: restore register */
952                 xhci_restore_registers(xhci);
953                 /* step 2: initialize command ring buffer */
954                 xhci_set_cmd_ring_deq(xhci);
955                 /* step 3: restore state and start state*/
956                 /* step 3: set CRS flag */
957                 command = xhci_readl(xhci, &xhci->op_regs->command);
958                 command |= CMD_CRS;
959                 xhci_writel(xhci, command, &xhci->op_regs->command);
960                 if (handshake(xhci, &xhci->op_regs->status,
961                               STS_RESTORE, 0, 10 * 1000)) {
962                         xhci_warn(xhci, "WARN: xHC restore state timeout\n");
963                         spin_unlock_irq(&xhci->lock);
964                         return -ETIMEDOUT;
965                 }
966                 temp = xhci_readl(xhci, &xhci->op_regs->status);
967         }
968
969         /* If restore operation fails, re-initialize the HC during resume */
970         if ((temp & STS_SRE) || hibernated) {
971                 /* Let the USB core know _both_ roothubs lost power. */
972                 usb_root_hub_lost_power(xhci->main_hcd->self.root_hub);
973                 usb_root_hub_lost_power(xhci->shared_hcd->self.root_hub);
974
975                 xhci_dbg(xhci, "Stop HCD\n");
976                 xhci_halt(xhci);
977                 xhci_reset(xhci);
978                 spin_unlock_irq(&xhci->lock);
979                 xhci_cleanup_msix(xhci);
980
981 #ifdef CONFIG_USB_XHCI_HCD_DEBUGGING
982                 /* Tell the event ring poll function not to reschedule */
983                 xhci->zombie = 1;
984                 del_timer_sync(&xhci->event_ring_timer);
985 #endif
986
987                 xhci_dbg(xhci, "// Disabling event ring interrupts\n");
988                 temp = xhci_readl(xhci, &xhci->op_regs->status);
989                 xhci_writel(xhci, temp & ~STS_EINT, &xhci->op_regs->status);
990                 temp = xhci_readl(xhci, &xhci->ir_set->irq_pending);
991                 xhci_writel(xhci, ER_IRQ_DISABLE(temp),
992                                 &xhci->ir_set->irq_pending);
993                 xhci_print_ir_set(xhci, 0);
994
995                 xhci_dbg(xhci, "cleaning up memory\n");
996                 xhci_mem_cleanup(xhci);
997                 xhci_dbg(xhci, "xhci_stop completed - status = %x\n",
998                             xhci_readl(xhci, &xhci->op_regs->status));
999
1000                 /* USB core calls the PCI reinit and start functions twice:
1001                  * first with the primary HCD, and then with the secondary HCD.
1002                  * If we don't do the same, the host will never be started.
1003                  */
1004                 if (!usb_hcd_is_primary_hcd(hcd))
1005                         secondary_hcd = hcd;
1006                 else
1007                         secondary_hcd = xhci->shared_hcd;
1008
1009                 xhci_dbg(xhci, "Initialize the xhci_hcd\n");
1010                 retval = xhci_init(hcd->primary_hcd);
1011                 if (retval)
1012                         return retval;
1013                 xhci_dbg(xhci, "Start the primary HCD\n");
1014                 retval = xhci_run(hcd->primary_hcd);
1015                 if (!retval) {
1016                         xhci_dbg(xhci, "Start the secondary HCD\n");
1017                         retval = xhci_run(secondary_hcd);
1018                 }
1019                 hcd->state = HC_STATE_SUSPENDED;
1020                 xhci->shared_hcd->state = HC_STATE_SUSPENDED;
1021                 goto done;
1022         }
1023
1024         /* step 4: set Run/Stop bit */
1025         command = xhci_readl(xhci, &xhci->op_regs->command);
1026         command |= CMD_RUN;
1027         xhci_writel(xhci, command, &xhci->op_regs->command);
1028         handshake(xhci, &xhci->op_regs->status, STS_HALT,
1029                   0, 250 * 1000);
1030
1031         /* step 5: walk topology and initialize portsc,
1032          * portpmsc and portli
1033          */
1034         /* this is done in bus_resume */
1035
1036         /* step 6: restart each of the previously
1037          * Running endpoints by ringing their doorbells
1038          */
1039
1040         spin_unlock_irq(&xhci->lock);
1041
1042  done:
1043         if (retval == 0) {
1044                 usb_hcd_resume_root_hub(hcd);
1045                 usb_hcd_resume_root_hub(xhci->shared_hcd);
1046         }
1047
1048         /*
1049          * If system is subject to the Quirk, Compliance Mode Timer needs to
1050          * be re-initialized Always after a system resume. Ports are subject
1051          * to suffer the Compliance Mode issue again. It doesn't matter if
1052          * ports have entered previously to U0 before system's suspension.
1053          */
1054         if (xhci->quirks & XHCI_COMP_MODE_QUIRK)
1055                 compliance_mode_recovery_timer_init(xhci);
1056
1057         return retval;
1058 }
1059 #endif  /* CONFIG_PM */
1060
1061 /*-------------------------------------------------------------------------*/
1062
1063 /**
1064  * xhci_get_endpoint_index - Used for passing endpoint bitmasks between the core and
1065  * HCDs.  Find the index for an endpoint given its descriptor.  Use the return
1066  * value to right shift 1 for the bitmask.
1067  *
1068  * Index  = (epnum * 2) + direction - 1,
1069  * where direction = 0 for OUT, 1 for IN.
1070  * For control endpoints, the IN index is used (OUT index is unused), so
1071  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
1072  */
1073 unsigned int xhci_get_endpoint_index(struct usb_endpoint_descriptor *desc)
1074 {
1075         unsigned int index;
1076         if (usb_endpoint_xfer_control(desc))
1077                 index = (unsigned int) (usb_endpoint_num(desc)*2);
1078         else
1079                 index = (unsigned int) (usb_endpoint_num(desc)*2) +
1080                         (usb_endpoint_dir_in(desc) ? 1 : 0) - 1;
1081         return index;
1082 }
1083
1084 /* Find the flag for this endpoint (for use in the control context).  Use the
1085  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1086  * bit 1, etc.
1087  */
1088 unsigned int xhci_get_endpoint_flag(struct usb_endpoint_descriptor *desc)
1089 {
1090         return 1 << (xhci_get_endpoint_index(desc) + 1);
1091 }
1092
1093 /* Find the flag for this endpoint (for use in the control context).  Use the
1094  * endpoint index to create a bitmask.  The slot context is bit 0, endpoint 0 is
1095  * bit 1, etc.
1096  */
1097 unsigned int xhci_get_endpoint_flag_from_index(unsigned int ep_index)
1098 {
1099         return 1 << (ep_index + 1);
1100 }
1101
1102 /* Compute the last valid endpoint context index.  Basically, this is the
1103  * endpoint index plus one.  For slot contexts with more than valid endpoint,
1104  * we find the most significant bit set in the added contexts flags.
1105  * e.g. ep 1 IN (with epnum 0x81) => added_ctxs = 0b1000
1106  * fls(0b1000) = 4, but the endpoint context index is 3, so subtract one.
1107  */
1108 unsigned int xhci_last_valid_endpoint(u32 added_ctxs)
1109 {
1110         return fls(added_ctxs) - 1;
1111 }
1112
1113 /* Returns 1 if the arguments are OK;
1114  * returns 0 this is a root hub; returns -EINVAL for NULL pointers.
1115  */
1116 static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
1117                 struct usb_host_endpoint *ep, int check_ep, bool check_virt_dev,
1118                 const char *func) {
1119         struct xhci_hcd *xhci;
1120         struct xhci_virt_device *virt_dev;
1121
1122         if (!hcd || (check_ep && !ep) || !udev) {
1123                 printk(KERN_DEBUG "xHCI %s called with invalid args\n",
1124                                 func);
1125                 return -EINVAL;
1126         }
1127         if (!udev->parent) {
1128                 printk(KERN_DEBUG "xHCI %s called for root hub\n",
1129                                 func);
1130                 return 0;
1131         }
1132
1133         xhci = hcd_to_xhci(hcd);
1134         if (xhci->xhc_state & XHCI_STATE_HALTED)
1135                 return -ENODEV;
1136
1137         if (check_virt_dev) {
1138                 if (!udev->slot_id || !xhci->devs[udev->slot_id]) {
1139                         printk(KERN_DEBUG "xHCI %s called with unaddressed "
1140                                                 "device\n", func);
1141                         return -EINVAL;
1142                 }
1143
1144                 virt_dev = xhci->devs[udev->slot_id];
1145                 if (virt_dev->udev != udev) {
1146                         printk(KERN_DEBUG "xHCI %s called with udev and "
1147                                           "virt_dev does not match\n", func);
1148                         return -EINVAL;
1149                 }
1150         }
1151
1152         return 1;
1153 }
1154
1155 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
1156                 struct usb_device *udev, struct xhci_command *command,
1157                 bool ctx_change, bool must_succeed);
1158
1159 /*
1160  * Full speed devices may have a max packet size greater than 8 bytes, but the
1161  * USB core doesn't know that until it reads the first 8 bytes of the
1162  * descriptor.  If the usb_device's max packet size changes after that point,
1163  * we need to issue an evaluate context command and wait on it.
1164  */
1165 static int xhci_check_maxpacket(struct xhci_hcd *xhci, unsigned int slot_id,
1166                 unsigned int ep_index, struct urb *urb)
1167 {
1168         struct xhci_container_ctx *in_ctx;
1169         struct xhci_container_ctx *out_ctx;
1170         struct xhci_input_control_ctx *ctrl_ctx;
1171         struct xhci_ep_ctx *ep_ctx;
1172         int max_packet_size;
1173         int hw_max_packet_size;
1174         int ret = 0;
1175
1176         out_ctx = xhci->devs[slot_id]->out_ctx;
1177         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1178         hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
1179         max_packet_size = usb_endpoint_maxp(&urb->dev->ep0.desc);
1180         if (hw_max_packet_size != max_packet_size) {
1181                 xhci_dbg(xhci, "Max Packet Size for ep 0 changed.\n");
1182                 xhci_dbg(xhci, "Max packet size in usb_device = %d\n",
1183                                 max_packet_size);
1184                 xhci_dbg(xhci, "Max packet size in xHCI HW = %d\n",
1185                                 hw_max_packet_size);
1186                 xhci_dbg(xhci, "Issuing evaluate context command.\n");
1187
1188                 /* Set up the modified control endpoint 0 */
1189                 xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
1190                                 xhci->devs[slot_id]->out_ctx, ep_index);
1191                 in_ctx = xhci->devs[slot_id]->in_ctx;
1192                 ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
1193                 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
1194                 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
1195
1196                 /* Set up the input context flags for the command */
1197                 /* FIXME: This won't work if a non-default control endpoint
1198                  * changes max packet sizes.
1199                  */
1200                 ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1201                 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
1202                 ctrl_ctx->drop_flags = 0;
1203
1204                 xhci_dbg(xhci, "Slot %d input context\n", slot_id);
1205                 xhci_dbg_ctx(xhci, in_ctx, ep_index);
1206                 xhci_dbg(xhci, "Slot %d output context\n", slot_id);
1207                 xhci_dbg_ctx(xhci, out_ctx, ep_index);
1208
1209                 ret = xhci_configure_endpoint(xhci, urb->dev, NULL,
1210                                 true, false);
1211
1212                 /* Clean up the input context for later use by bandwidth
1213                  * functions.
1214                  */
1215                 ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1216         }
1217         return ret;
1218 }
1219
1220 /*
1221  * non-error returns are a promise to giveback() the urb later
1222  * we drop ownership so next owner (or urb unlink) can get it
1223  */
1224 int xhci_urb_enqueue(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags)
1225 {
1226         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
1227         struct xhci_td *buffer;
1228         unsigned long flags;
1229         int ret = 0;
1230         unsigned int slot_id, ep_index;
1231         struct urb_priv *urb_priv;
1232         int size, i;
1233
1234         if (!urb || xhci_check_args(hcd, urb->dev, urb->ep,
1235                                         true, true, __func__) <= 0)
1236                 return -EINVAL;
1237
1238         slot_id = urb->dev->slot_id;
1239         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1240
1241         if (!HCD_HW_ACCESSIBLE(hcd)) {
1242                 if (!in_interrupt())
1243                         xhci_dbg(xhci, "urb submitted during PCI suspend\n");
1244                 ret = -ESHUTDOWN;
1245                 goto exit;
1246         }
1247
1248         if (usb_endpoint_xfer_isoc(&urb->ep->desc))
1249                 size = urb->number_of_packets;
1250         else
1251                 size = 1;
1252
1253         urb_priv = kzalloc(sizeof(struct urb_priv) +
1254                                   size * sizeof(struct xhci_td *), mem_flags);
1255         if (!urb_priv)
1256                 return -ENOMEM;
1257
1258         buffer = kzalloc(size * sizeof(struct xhci_td), mem_flags);
1259         if (!buffer) {
1260                 kfree(urb_priv);
1261                 return -ENOMEM;
1262         }
1263
1264         for (i = 0; i < size; i++) {
1265                 urb_priv->td[i] = buffer;
1266                 buffer++;
1267         }
1268
1269         urb_priv->length = size;
1270         urb_priv->td_cnt = 0;
1271         urb->hcpriv = urb_priv;
1272
1273         if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1274                 /* Check to see if the max packet size for the default control
1275                  * endpoint changed during FS device enumeration
1276                  */
1277                 if (urb->dev->speed == USB_SPEED_FULL) {
1278                         ret = xhci_check_maxpacket(xhci, slot_id,
1279                                         ep_index, urb);
1280                         if (ret < 0) {
1281                                 xhci_urb_free_priv(xhci, urb_priv);
1282                                 urb->hcpriv = NULL;
1283                                 return ret;
1284                         }
1285                 }
1286
1287                 /* We have a spinlock and interrupts disabled, so we must pass
1288                  * atomic context to this function, which may allocate memory.
1289                  */
1290                 spin_lock_irqsave(&xhci->lock, flags);
1291                 if (xhci->xhc_state & XHCI_STATE_DYING)
1292                         goto dying;
1293                 ret = xhci_queue_ctrl_tx(xhci, GFP_ATOMIC, urb,
1294                                 slot_id, ep_index);
1295                 if (ret)
1296                         goto free_priv;
1297                 spin_unlock_irqrestore(&xhci->lock, flags);
1298         } else if (usb_endpoint_xfer_bulk(&urb->ep->desc)) {
1299                 spin_lock_irqsave(&xhci->lock, flags);
1300                 if (xhci->xhc_state & XHCI_STATE_DYING)
1301                         goto dying;
1302                 if (xhci->devs[slot_id]->eps[ep_index].ep_state &
1303                                 EP_GETTING_STREAMS) {
1304                         xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
1305                                         "is transitioning to using streams.\n");
1306                         ret = -EINVAL;
1307                 } else if (xhci->devs[slot_id]->eps[ep_index].ep_state &
1308                                 EP_GETTING_NO_STREAMS) {
1309                         xhci_warn(xhci, "WARN: Can't enqueue URB while bulk ep "
1310                                         "is transitioning to "
1311                                         "not having streams.\n");
1312                         ret = -EINVAL;
1313                 } else {
1314                         ret = xhci_queue_bulk_tx(xhci, GFP_ATOMIC, urb,
1315                                         slot_id, ep_index);
1316                 }
1317                 if (ret)
1318                         goto free_priv;
1319                 spin_unlock_irqrestore(&xhci->lock, flags);
1320         } else if (usb_endpoint_xfer_int(&urb->ep->desc)) {
1321                 spin_lock_irqsave(&xhci->lock, flags);
1322                 if (xhci->xhc_state & XHCI_STATE_DYING)
1323                         goto dying;
1324                 ret = xhci_queue_intr_tx(xhci, GFP_ATOMIC, urb,
1325                                 slot_id, ep_index);
1326                 if (ret)
1327                         goto free_priv;
1328                 spin_unlock_irqrestore(&xhci->lock, flags);
1329         } else {
1330                 spin_lock_irqsave(&xhci->lock, flags);
1331                 if (xhci->xhc_state & XHCI_STATE_DYING)
1332                         goto dying;
1333                 ret = xhci_queue_isoc_tx_prepare(xhci, GFP_ATOMIC, urb,
1334                                 slot_id, ep_index);
1335                 if (ret)
1336                         goto free_priv;
1337                 spin_unlock_irqrestore(&xhci->lock, flags);
1338         }
1339 exit:
1340         return ret;
1341 dying:
1342         xhci_dbg(xhci, "Ep 0x%x: URB %p submitted for "
1343                         "non-responsive xHCI host.\n",
1344                         urb->ep->desc.bEndpointAddress, urb);
1345         ret = -ESHUTDOWN;
1346 free_priv:
1347         xhci_urb_free_priv(xhci, urb_priv);
1348         urb->hcpriv = NULL;
1349         spin_unlock_irqrestore(&xhci->lock, flags);
1350         return ret;
1351 }
1352
1353 /* Get the right ring for the given URB.
1354  * If the endpoint supports streams, boundary check the URB's stream ID.
1355  * If the endpoint doesn't support streams, return the singular endpoint ring.
1356  */
1357 static struct xhci_ring *xhci_urb_to_transfer_ring(struct xhci_hcd *xhci,
1358                 struct urb *urb)
1359 {
1360         unsigned int slot_id;
1361         unsigned int ep_index;
1362         unsigned int stream_id;
1363         struct xhci_virt_ep *ep;
1364
1365         slot_id = urb->dev->slot_id;
1366         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1367         stream_id = urb->stream_id;
1368         ep = &xhci->devs[slot_id]->eps[ep_index];
1369         /* Common case: no streams */
1370         if (!(ep->ep_state & EP_HAS_STREAMS))
1371                 return ep->ring;
1372
1373         if (stream_id == 0) {
1374                 xhci_warn(xhci,
1375                                 "WARN: Slot ID %u, ep index %u has streams, "
1376                                 "but URB has no stream ID.\n",
1377                                 slot_id, ep_index);
1378                 return NULL;
1379         }
1380
1381         if (stream_id < ep->stream_info->num_streams)
1382                 return ep->stream_info->stream_rings[stream_id];
1383
1384         xhci_warn(xhci,
1385                         "WARN: Slot ID %u, ep index %u has "
1386                         "stream IDs 1 to %u allocated, "
1387                         "but stream ID %u is requested.\n",
1388                         slot_id, ep_index,
1389                         ep->stream_info->num_streams - 1,
1390                         stream_id);
1391         return NULL;
1392 }
1393
1394 /*
1395  * Remove the URB's TD from the endpoint ring.  This may cause the HC to stop
1396  * USB transfers, potentially stopping in the middle of a TRB buffer.  The HC
1397  * should pick up where it left off in the TD, unless a Set Transfer Ring
1398  * Dequeue Pointer is issued.
1399  *
1400  * The TRBs that make up the buffers for the canceled URB will be "removed" from
1401  * the ring.  Since the ring is a contiguous structure, they can't be physically
1402  * removed.  Instead, there are two options:
1403  *
1404  *  1) If the HC is in the middle of processing the URB to be canceled, we
1405  *     simply move the ring's dequeue pointer past those TRBs using the Set
1406  *     Transfer Ring Dequeue Pointer command.  This will be the common case,
1407  *     when drivers timeout on the last submitted URB and attempt to cancel.
1408  *
1409  *  2) If the HC is in the middle of a different TD, we turn the TRBs into a
1410  *     series of 1-TRB transfer no-op TDs.  (No-ops shouldn't be chained.)  The
1411  *     HC will need to invalidate the any TRBs it has cached after the stop
1412  *     endpoint command, as noted in the xHCI 0.95 errata.
1413  *
1414  *  3) The TD may have completed by the time the Stop Endpoint Command
1415  *     completes, so software needs to handle that case too.
1416  *
1417  * This function should protect against the TD enqueueing code ringing the
1418  * doorbell while this code is waiting for a Stop Endpoint command to complete.
1419  * It also needs to account for multiple cancellations on happening at the same
1420  * time for the same endpoint.
1421  *
1422  * Note that this function can be called in any context, or so says
1423  * usb_hcd_unlink_urb()
1424  */
1425 int xhci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1426 {
1427         unsigned long flags;
1428         int ret, i;
1429         u32 temp;
1430         struct xhci_hcd *xhci;
1431         struct urb_priv *urb_priv;
1432         struct xhci_td *td;
1433         unsigned int ep_index;
1434         struct xhci_ring *ep_ring;
1435         struct xhci_virt_ep *ep;
1436
1437         xhci = hcd_to_xhci(hcd);
1438         spin_lock_irqsave(&xhci->lock, flags);
1439         /* Make sure the URB hasn't completed or been unlinked already */
1440         ret = usb_hcd_check_unlink_urb(hcd, urb, status);
1441         if (ret || !urb->hcpriv)
1442                 goto done;
1443         temp = xhci_readl(xhci, &xhci->op_regs->status);
1444         if (temp == 0xffffffff || (xhci->xhc_state & XHCI_STATE_HALTED)) {
1445                 xhci_dbg(xhci, "HW died, freeing TD.\n");
1446                 urb_priv = urb->hcpriv;
1447                 for (i = urb_priv->td_cnt; i < urb_priv->length; i++) {
1448                         td = urb_priv->td[i];
1449                         if (!list_empty(&td->td_list))
1450                                 list_del_init(&td->td_list);
1451                         if (!list_empty(&td->cancelled_td_list))
1452                                 list_del_init(&td->cancelled_td_list);
1453                 }
1454
1455                 usb_hcd_unlink_urb_from_ep(hcd, urb);
1456                 spin_unlock_irqrestore(&xhci->lock, flags);
1457                 usb_hcd_giveback_urb(hcd, urb, -ESHUTDOWN);
1458                 xhci_urb_free_priv(xhci, urb_priv);
1459                 return ret;
1460         }
1461         if ((xhci->xhc_state & XHCI_STATE_DYING) ||
1462                         (xhci->xhc_state & XHCI_STATE_HALTED)) {
1463                 xhci_dbg(xhci, "Ep 0x%x: URB %p to be canceled on "
1464                                 "non-responsive xHCI host.\n",
1465                                 urb->ep->desc.bEndpointAddress, urb);
1466                 /* Let the stop endpoint command watchdog timer (which set this
1467                  * state) finish cleaning up the endpoint TD lists.  We must
1468                  * have caught it in the middle of dropping a lock and giving
1469                  * back an URB.
1470                  */
1471                 goto done;
1472         }
1473
1474         xhci_dbg(xhci, "Cancel URB %p\n", urb);
1475         xhci_dbg(xhci, "Event ring:\n");
1476         xhci_debug_ring(xhci, xhci->event_ring);
1477         ep_index = xhci_get_endpoint_index(&urb->ep->desc);
1478         ep = &xhci->devs[urb->dev->slot_id]->eps[ep_index];
1479         ep_ring = xhci_urb_to_transfer_ring(xhci, urb);
1480         if (!ep_ring) {
1481                 ret = -EINVAL;
1482                 goto done;
1483         }
1484
1485         xhci_dbg(xhci, "Endpoint ring:\n");
1486         xhci_debug_ring(xhci, ep_ring);
1487
1488         urb_priv = urb->hcpriv;
1489
1490         for (i = urb_priv->td_cnt; i < urb_priv->length; i++) {
1491                 td = urb_priv->td[i];
1492                 list_add_tail(&td->cancelled_td_list, &ep->cancelled_td_list);
1493         }
1494
1495         /* Queue a stop endpoint command, but only if this is
1496          * the first cancellation to be handled.
1497          */
1498         if (!(ep->ep_state & EP_HALT_PENDING)) {
1499                 ep->ep_state |= EP_HALT_PENDING;
1500                 ep->stop_cmds_pending++;
1501                 ep->stop_cmd_timer.expires = jiffies +
1502                         XHCI_STOP_EP_CMD_TIMEOUT * HZ;
1503                 add_timer(&ep->stop_cmd_timer);
1504                 xhci_queue_stop_endpoint(xhci, urb->dev->slot_id, ep_index, 0);
1505                 xhci_ring_cmd_db(xhci);
1506         }
1507 done:
1508         spin_unlock_irqrestore(&xhci->lock, flags);
1509         return ret;
1510 }
1511
1512 /* Drop an endpoint from a new bandwidth configuration for this device.
1513  * Only one call to this function is allowed per endpoint before
1514  * check_bandwidth() or reset_bandwidth() must be called.
1515  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1516  * add the endpoint to the schedule with possibly new parameters denoted by a
1517  * different endpoint descriptor in usb_host_endpoint.
1518  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1519  * not allowed.
1520  *
1521  * The USB core will not allow URBs to be queued to an endpoint that is being
1522  * disabled, so there's no need for mutual exclusion to protect
1523  * the xhci->devs[slot_id] structure.
1524  */
1525 int xhci_drop_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1526                 struct usb_host_endpoint *ep)
1527 {
1528         struct xhci_hcd *xhci;
1529         struct xhci_container_ctx *in_ctx, *out_ctx;
1530         struct xhci_input_control_ctx *ctrl_ctx;
1531         struct xhci_slot_ctx *slot_ctx;
1532         unsigned int last_ctx;
1533         unsigned int ep_index;
1534         struct xhci_ep_ctx *ep_ctx;
1535         u32 drop_flag;
1536         u32 new_add_flags, new_drop_flags, new_slot_info;
1537         int ret;
1538
1539         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1540         if (ret <= 0)
1541                 return ret;
1542         xhci = hcd_to_xhci(hcd);
1543         if (xhci->xhc_state & XHCI_STATE_DYING)
1544                 return -ENODEV;
1545
1546         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
1547         drop_flag = xhci_get_endpoint_flag(&ep->desc);
1548         if (drop_flag == SLOT_FLAG || drop_flag == EP0_FLAG) {
1549                 xhci_dbg(xhci, "xHCI %s - can't drop slot or ep 0 %#x\n",
1550                                 __func__, drop_flag);
1551                 return 0;
1552         }
1553
1554         in_ctx = xhci->devs[udev->slot_id]->in_ctx;
1555         out_ctx = xhci->devs[udev->slot_id]->out_ctx;
1556         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1557         ep_index = xhci_get_endpoint_index(&ep->desc);
1558         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1559         /* If the HC already knows the endpoint is disabled,
1560          * or the HCD has noted it is disabled, ignore this request
1561          */
1562         if (((ep_ctx->ep_info & cpu_to_le32(EP_STATE_MASK)) ==
1563              cpu_to_le32(EP_STATE_DISABLED)) ||
1564             le32_to_cpu(ctrl_ctx->drop_flags) &
1565             xhci_get_endpoint_flag(&ep->desc)) {
1566                 xhci_warn(xhci, "xHCI %s called with disabled ep %p\n",
1567                                 __func__, ep);
1568                 return 0;
1569         }
1570
1571         ctrl_ctx->drop_flags |= cpu_to_le32(drop_flag);
1572         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1573
1574         ctrl_ctx->add_flags &= cpu_to_le32(~drop_flag);
1575         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1576
1577         last_ctx = xhci_last_valid_endpoint(le32_to_cpu(ctrl_ctx->add_flags));
1578         slot_ctx = xhci_get_slot_ctx(xhci, in_ctx);
1579         /* Update the last valid endpoint context, if we deleted the last one */
1580         if ((le32_to_cpu(slot_ctx->dev_info) & LAST_CTX_MASK) >
1581             LAST_CTX(last_ctx)) {
1582                 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1583                 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(last_ctx));
1584         }
1585         new_slot_info = le32_to_cpu(slot_ctx->dev_info);
1586
1587         xhci_endpoint_zero(xhci, xhci->devs[udev->slot_id], ep);
1588
1589         xhci_dbg(xhci, "drop ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x, new slot info = %#x\n",
1590                         (unsigned int) ep->desc.bEndpointAddress,
1591                         udev->slot_id,
1592                         (unsigned int) new_drop_flags,
1593                         (unsigned int) new_add_flags,
1594                         (unsigned int) new_slot_info);
1595         return 0;
1596 }
1597
1598 /* Add an endpoint to a new possible bandwidth configuration for this device.
1599  * Only one call to this function is allowed per endpoint before
1600  * check_bandwidth() or reset_bandwidth() must be called.
1601  * A call to xhci_drop_endpoint() followed by a call to xhci_add_endpoint() will
1602  * add the endpoint to the schedule with possibly new parameters denoted by a
1603  * different endpoint descriptor in usb_host_endpoint.
1604  * A call to xhci_add_endpoint() followed by a call to xhci_drop_endpoint() is
1605  * not allowed.
1606  *
1607  * The USB core will not allow URBs to be queued to an endpoint until the
1608  * configuration or alt setting is installed in the device, so there's no need
1609  * for mutual exclusion to protect the xhci->devs[slot_id] structure.
1610  */
1611 int xhci_add_endpoint(struct usb_hcd *hcd, struct usb_device *udev,
1612                 struct usb_host_endpoint *ep)
1613 {
1614         struct xhci_hcd *xhci;
1615         struct xhci_container_ctx *in_ctx, *out_ctx;
1616         unsigned int ep_index;
1617         struct xhci_ep_ctx *ep_ctx;
1618         struct xhci_slot_ctx *slot_ctx;
1619         struct xhci_input_control_ctx *ctrl_ctx;
1620         u32 added_ctxs;
1621         unsigned int last_ctx;
1622         u32 new_add_flags, new_drop_flags, new_slot_info;
1623         struct xhci_virt_device *virt_dev;
1624         int ret = 0;
1625
1626         ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
1627         if (ret <= 0) {
1628                 /* So we won't queue a reset ep command for a root hub */
1629                 ep->hcpriv = NULL;
1630                 return ret;
1631         }
1632         xhci = hcd_to_xhci(hcd);
1633         if (xhci->xhc_state & XHCI_STATE_DYING)
1634                 return -ENODEV;
1635
1636         added_ctxs = xhci_get_endpoint_flag(&ep->desc);
1637         last_ctx = xhci_last_valid_endpoint(added_ctxs);
1638         if (added_ctxs == SLOT_FLAG || added_ctxs == EP0_FLAG) {
1639                 /* FIXME when we have to issue an evaluate endpoint command to
1640                  * deal with ep0 max packet size changing once we get the
1641                  * descriptors
1642                  */
1643                 xhci_dbg(xhci, "xHCI %s - can't add slot or ep 0 %#x\n",
1644                                 __func__, added_ctxs);
1645                 return 0;
1646         }
1647
1648         virt_dev = xhci->devs[udev->slot_id];
1649         in_ctx = virt_dev->in_ctx;
1650         out_ctx = virt_dev->out_ctx;
1651         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1652         ep_index = xhci_get_endpoint_index(&ep->desc);
1653         ep_ctx = xhci_get_ep_ctx(xhci, out_ctx, ep_index);
1654
1655         /* If this endpoint is already in use, and the upper layers are trying
1656          * to add it again without dropping it, reject the addition.
1657          */
1658         if (virt_dev->eps[ep_index].ring &&
1659                         !(le32_to_cpu(ctrl_ctx->drop_flags) &
1660                                 xhci_get_endpoint_flag(&ep->desc))) {
1661                 xhci_warn(xhci, "Trying to add endpoint 0x%x "
1662                                 "without dropping it.\n",
1663                                 (unsigned int) ep->desc.bEndpointAddress);
1664                 return -EINVAL;
1665         }
1666
1667         /* If the HCD has already noted the endpoint is enabled,
1668          * ignore this request.
1669          */
1670         if (le32_to_cpu(ctrl_ctx->add_flags) &
1671             xhci_get_endpoint_flag(&ep->desc)) {
1672                 xhci_warn(xhci, "xHCI %s called with enabled ep %p\n",
1673                                 __func__, ep);
1674                 return 0;
1675         }
1676
1677         /*
1678          * Configuration and alternate setting changes must be done in
1679          * process context, not interrupt context (or so documenation
1680          * for usb_set_interface() and usb_set_configuration() claim).
1681          */
1682         if (xhci_endpoint_init(xhci, virt_dev, udev, ep, GFP_NOIO) < 0) {
1683                 dev_dbg(&udev->dev, "%s - could not initialize ep %#x\n",
1684                                 __func__, ep->desc.bEndpointAddress);
1685                 return -ENOMEM;
1686         }
1687
1688         ctrl_ctx->add_flags |= cpu_to_le32(added_ctxs);
1689         new_add_flags = le32_to_cpu(ctrl_ctx->add_flags);
1690
1691         /* If xhci_endpoint_disable() was called for this endpoint, but the
1692          * xHC hasn't been notified yet through the check_bandwidth() call,
1693          * this re-adds a new state for the endpoint from the new endpoint
1694          * descriptors.  We must drop and re-add this endpoint, so we leave the
1695          * drop flags alone.
1696          */
1697         new_drop_flags = le32_to_cpu(ctrl_ctx->drop_flags);
1698
1699         slot_ctx = xhci_get_slot_ctx(xhci, in_ctx);
1700         /* Update the last valid endpoint context, if we just added one past */
1701         if ((le32_to_cpu(slot_ctx->dev_info) & LAST_CTX_MASK) <
1702             LAST_CTX(last_ctx)) {
1703                 slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1704                 slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(last_ctx));
1705         }
1706         new_slot_info = le32_to_cpu(slot_ctx->dev_info);
1707
1708         /* Store the usb_device pointer for later use */
1709         ep->hcpriv = udev;
1710
1711         xhci_dbg(xhci, "add ep 0x%x, slot id %d, new drop flags = %#x, new add flags = %#x, new slot info = %#x\n",
1712                         (unsigned int) ep->desc.bEndpointAddress,
1713                         udev->slot_id,
1714                         (unsigned int) new_drop_flags,
1715                         (unsigned int) new_add_flags,
1716                         (unsigned int) new_slot_info);
1717         return 0;
1718 }
1719
1720 static void xhci_zero_in_ctx(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev)
1721 {
1722         struct xhci_input_control_ctx *ctrl_ctx;
1723         struct xhci_ep_ctx *ep_ctx;
1724         struct xhci_slot_ctx *slot_ctx;
1725         int i;
1726
1727         /* When a device's add flag and drop flag are zero, any subsequent
1728          * configure endpoint command will leave that endpoint's state
1729          * untouched.  Make sure we don't leave any old state in the input
1730          * endpoint contexts.
1731          */
1732         ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx);
1733         ctrl_ctx->drop_flags = 0;
1734         ctrl_ctx->add_flags = 0;
1735         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
1736         slot_ctx->dev_info &= cpu_to_le32(~LAST_CTX_MASK);
1737         /* Endpoint 0 is always valid */
1738         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(1));
1739         for (i = 1; i < 31; ++i) {
1740                 ep_ctx = xhci_get_ep_ctx(xhci, virt_dev->in_ctx, i);
1741                 ep_ctx->ep_info = 0;
1742                 ep_ctx->ep_info2 = 0;
1743                 ep_ctx->deq = 0;
1744                 ep_ctx->tx_info = 0;
1745         }
1746 }
1747
1748 static int xhci_configure_endpoint_result(struct xhci_hcd *xhci,
1749                 struct usb_device *udev, u32 *cmd_status)
1750 {
1751         int ret;
1752
1753         switch (*cmd_status) {
1754         case COMP_ENOMEM:
1755                 dev_warn(&udev->dev, "Not enough host controller resources "
1756                                 "for new device state.\n");
1757                 ret = -ENOMEM;
1758                 /* FIXME: can we allocate more resources for the HC? */
1759                 break;
1760         case COMP_BW_ERR:
1761         case COMP_2ND_BW_ERR:
1762                 dev_warn(&udev->dev, "Not enough bandwidth "
1763                                 "for new device state.\n");
1764                 ret = -ENOSPC;
1765                 /* FIXME: can we go back to the old state? */
1766                 break;
1767         case COMP_TRB_ERR:
1768                 /* the HCD set up something wrong */
1769                 dev_warn(&udev->dev, "ERROR: Endpoint drop flag = 0, "
1770                                 "add flag = 1, "
1771                                 "and endpoint is not disabled.\n");
1772                 ret = -EINVAL;
1773                 break;
1774         case COMP_DEV_ERR:
1775                 dev_warn(&udev->dev, "ERROR: Incompatible device for endpoint "
1776                                 "configure command.\n");
1777                 ret = -ENODEV;
1778                 break;
1779         case COMP_SUCCESS:
1780                 dev_dbg(&udev->dev, "Successful Endpoint Configure command\n");
1781                 ret = 0;
1782                 break;
1783         default:
1784                 xhci_err(xhci, "ERROR: unexpected command completion "
1785                                 "code 0x%x.\n", *cmd_status);
1786                 ret = -EINVAL;
1787                 break;
1788         }
1789         return ret;
1790 }
1791
1792 static int xhci_evaluate_context_result(struct xhci_hcd *xhci,
1793                 struct usb_device *udev, u32 *cmd_status)
1794 {
1795         int ret;
1796         struct xhci_virt_device *virt_dev = xhci->devs[udev->slot_id];
1797
1798         switch (*cmd_status) {
1799         case COMP_EINVAL:
1800                 dev_warn(&udev->dev, "WARN: xHCI driver setup invalid evaluate "
1801                                 "context command.\n");
1802                 ret = -EINVAL;
1803                 break;
1804         case COMP_EBADSLT:
1805                 dev_warn(&udev->dev, "WARN: slot not enabled for"
1806                                 "evaluate context command.\n");
1807         case COMP_CTX_STATE:
1808                 dev_warn(&udev->dev, "WARN: invalid context state for "
1809                                 "evaluate context command.\n");
1810                 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 1);
1811                 ret = -EINVAL;
1812                 break;
1813         case COMP_DEV_ERR:
1814                 dev_warn(&udev->dev, "ERROR: Incompatible device for evaluate "
1815                                 "context command.\n");
1816                 ret = -ENODEV;
1817                 break;
1818         case COMP_MEL_ERR:
1819                 /* Max Exit Latency too large error */
1820                 dev_warn(&udev->dev, "WARN: Max Exit Latency too large\n");
1821                 ret = -EINVAL;
1822                 break;
1823         case COMP_SUCCESS:
1824                 dev_dbg(&udev->dev, "Successful evaluate context command\n");
1825                 ret = 0;
1826                 break;
1827         default:
1828                 xhci_err(xhci, "ERROR: unexpected command completion "
1829                                 "code 0x%x.\n", *cmd_status);
1830                 ret = -EINVAL;
1831                 break;
1832         }
1833         return ret;
1834 }
1835
1836 static u32 xhci_count_num_new_endpoints(struct xhci_hcd *xhci,
1837                 struct xhci_container_ctx *in_ctx)
1838 {
1839         struct xhci_input_control_ctx *ctrl_ctx;
1840         u32 valid_add_flags;
1841         u32 valid_drop_flags;
1842
1843         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1844         /* Ignore the slot flag (bit 0), and the default control endpoint flag
1845          * (bit 1).  The default control endpoint is added during the Address
1846          * Device command and is never removed until the slot is disabled.
1847          */
1848         valid_add_flags = ctrl_ctx->add_flags >> 2;
1849         valid_drop_flags = ctrl_ctx->drop_flags >> 2;
1850
1851         /* Use hweight32 to count the number of ones in the add flags, or
1852          * number of endpoints added.  Don't count endpoints that are changed
1853          * (both added and dropped).
1854          */
1855         return hweight32(valid_add_flags) -
1856                 hweight32(valid_add_flags & valid_drop_flags);
1857 }
1858
1859 static unsigned int xhci_count_num_dropped_endpoints(struct xhci_hcd *xhci,
1860                 struct xhci_container_ctx *in_ctx)
1861 {
1862         struct xhci_input_control_ctx *ctrl_ctx;
1863         u32 valid_add_flags;
1864         u32 valid_drop_flags;
1865
1866         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
1867         valid_add_flags = ctrl_ctx->add_flags >> 2;
1868         valid_drop_flags = ctrl_ctx->drop_flags >> 2;
1869
1870         return hweight32(valid_drop_flags) -
1871                 hweight32(valid_add_flags & valid_drop_flags);
1872 }
1873
1874 /*
1875  * We need to reserve the new number of endpoints before the configure endpoint
1876  * command completes.  We can't subtract the dropped endpoints from the number
1877  * of active endpoints until the command completes because we can oversubscribe
1878  * the host in this case:
1879  *
1880  *  - the first configure endpoint command drops more endpoints than it adds
1881  *  - a second configure endpoint command that adds more endpoints is queued
1882  *  - the first configure endpoint command fails, so the config is unchanged
1883  *  - the second command may succeed, even though there isn't enough resources
1884  *
1885  * Must be called with xhci->lock held.
1886  */
1887 static int xhci_reserve_host_resources(struct xhci_hcd *xhci,
1888                 struct xhci_container_ctx *in_ctx)
1889 {
1890         u32 added_eps;
1891
1892         added_eps = xhci_count_num_new_endpoints(xhci, in_ctx);
1893         if (xhci->num_active_eps + added_eps > xhci->limit_active_eps) {
1894                 xhci_dbg(xhci, "Not enough ep ctxs: "
1895                                 "%u active, need to add %u, limit is %u.\n",
1896                                 xhci->num_active_eps, added_eps,
1897                                 xhci->limit_active_eps);
1898                 return -ENOMEM;
1899         }
1900         xhci->num_active_eps += added_eps;
1901         xhci_dbg(xhci, "Adding %u ep ctxs, %u now active.\n", added_eps,
1902                         xhci->num_active_eps);
1903         return 0;
1904 }
1905
1906 /*
1907  * The configure endpoint was failed by the xHC for some other reason, so we
1908  * need to revert the resources that failed configuration would have used.
1909  *
1910  * Must be called with xhci->lock held.
1911  */
1912 static void xhci_free_host_resources(struct xhci_hcd *xhci,
1913                 struct xhci_container_ctx *in_ctx)
1914 {
1915         u32 num_failed_eps;
1916
1917         num_failed_eps = xhci_count_num_new_endpoints(xhci, in_ctx);
1918         xhci->num_active_eps -= num_failed_eps;
1919         xhci_dbg(xhci, "Removing %u failed ep ctxs, %u now active.\n",
1920                         num_failed_eps,
1921                         xhci->num_active_eps);
1922 }
1923
1924 /*
1925  * Now that the command has completed, clean up the active endpoint count by
1926  * subtracting out the endpoints that were dropped (but not changed).
1927  *
1928  * Must be called with xhci->lock held.
1929  */
1930 static void xhci_finish_resource_reservation(struct xhci_hcd *xhci,
1931                 struct xhci_container_ctx *in_ctx)
1932 {
1933         u32 num_dropped_eps;
1934
1935         num_dropped_eps = xhci_count_num_dropped_endpoints(xhci, in_ctx);
1936         xhci->num_active_eps -= num_dropped_eps;
1937         if (num_dropped_eps)
1938                 xhci_dbg(xhci, "Removing %u dropped ep ctxs, %u now active.\n",
1939                                 num_dropped_eps,
1940                                 xhci->num_active_eps);
1941 }
1942
1943 unsigned int xhci_get_block_size(struct usb_device *udev)
1944 {
1945         switch (udev->speed) {
1946         case USB_SPEED_LOW:
1947         case USB_SPEED_FULL:
1948                 return FS_BLOCK;
1949         case USB_SPEED_HIGH:
1950                 return HS_BLOCK;
1951         case USB_SPEED_SUPER:
1952                 return SS_BLOCK;
1953         case USB_SPEED_UNKNOWN:
1954         case USB_SPEED_WIRELESS:
1955         default:
1956                 /* Should never happen */
1957                 return 1;
1958         }
1959 }
1960
1961 unsigned int xhci_get_largest_overhead(struct xhci_interval_bw *interval_bw)
1962 {
1963         if (interval_bw->overhead[LS_OVERHEAD_TYPE])
1964                 return LS_OVERHEAD;
1965         if (interval_bw->overhead[FS_OVERHEAD_TYPE])
1966                 return FS_OVERHEAD;
1967         return HS_OVERHEAD;
1968 }
1969
1970 /* If we are changing a LS/FS device under a HS hub,
1971  * make sure (if we are activating a new TT) that the HS bus has enough
1972  * bandwidth for this new TT.
1973  */
1974 static int xhci_check_tt_bw_table(struct xhci_hcd *xhci,
1975                 struct xhci_virt_device *virt_dev,
1976                 int old_active_eps)
1977 {
1978         struct xhci_interval_bw_table *bw_table;
1979         struct xhci_tt_bw_info *tt_info;
1980
1981         /* Find the bandwidth table for the root port this TT is attached to. */
1982         bw_table = &xhci->rh_bw[virt_dev->real_port - 1].bw_table;
1983         tt_info = virt_dev->tt_info;
1984         /* If this TT already had active endpoints, the bandwidth for this TT
1985          * has already been added.  Removing all periodic endpoints (and thus
1986          * making the TT enactive) will only decrease the bandwidth used.
1987          */
1988         if (old_active_eps)
1989                 return 0;
1990         if (old_active_eps == 0 && tt_info->active_eps != 0) {
1991                 if (bw_table->bw_used + TT_HS_OVERHEAD > HS_BW_LIMIT)
1992                         return -ENOMEM;
1993                 return 0;
1994         }
1995         /* Not sure why we would have no new active endpoints...
1996          *
1997          * Maybe because of an Evaluate Context change for a hub update or a
1998          * control endpoint 0 max packet size change?
1999          * FIXME: skip the bandwidth calculation in that case.
2000          */
2001         return 0;
2002 }
2003
2004 static int xhci_check_ss_bw(struct xhci_hcd *xhci,
2005                 struct xhci_virt_device *virt_dev)
2006 {
2007         unsigned int bw_reserved;
2008
2009         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_IN, 100);
2010         if (virt_dev->bw_table->ss_bw_in > (SS_BW_LIMIT_IN - bw_reserved))
2011                 return -ENOMEM;
2012
2013         bw_reserved = DIV_ROUND_UP(SS_BW_RESERVED*SS_BW_LIMIT_OUT, 100);
2014         if (virt_dev->bw_table->ss_bw_out > (SS_BW_LIMIT_OUT - bw_reserved))
2015                 return -ENOMEM;
2016
2017         return 0;
2018 }
2019
2020 /*
2021  * This algorithm is a very conservative estimate of the worst-case scheduling
2022  * scenario for any one interval.  The hardware dynamically schedules the
2023  * packets, so we can't tell which microframe could be the limiting factor in
2024  * the bandwidth scheduling.  This only takes into account periodic endpoints.
2025  *
2026  * Obviously, we can't solve an NP complete problem to find the minimum worst
2027  * case scenario.  Instead, we come up with an estimate that is no less than
2028  * the worst case bandwidth used for any one microframe, but may be an
2029  * over-estimate.
2030  *
2031  * We walk the requirements for each endpoint by interval, starting with the
2032  * smallest interval, and place packets in the schedule where there is only one
2033  * possible way to schedule packets for that interval.  In order to simplify
2034  * this algorithm, we record the largest max packet size for each interval, and
2035  * assume all packets will be that size.
2036  *
2037  * For interval 0, we obviously must schedule all packets for each interval.
2038  * The bandwidth for interval 0 is just the amount of data to be transmitted
2039  * (the sum of all max ESIT payload sizes, plus any overhead per packet times
2040  * the number of packets).
2041  *
2042  * For interval 1, we have two possible microframes to schedule those packets
2043  * in.  For this algorithm, if we can schedule the same number of packets for
2044  * each possible scheduling opportunity (each microframe), we will do so.  The
2045  * remaining number of packets will be saved to be transmitted in the gaps in
2046  * the next interval's scheduling sequence.
2047  *
2048  * As we move those remaining packets to be scheduled with interval 2 packets,
2049  * we have to double the number of remaining packets to transmit.  This is
2050  * because the intervals are actually powers of 2, and we would be transmitting
2051  * the previous interval's packets twice in this interval.  We also have to be
2052  * sure that when we look at the largest max packet size for this interval, we
2053  * also look at the largest max packet size for the remaining packets and take
2054  * the greater of the two.
2055  *
2056  * The algorithm continues to evenly distribute packets in each scheduling
2057  * opportunity, and push the remaining packets out, until we get to the last
2058  * interval.  Then those packets and their associated overhead are just added
2059  * to the bandwidth used.
2060  */
2061 static int xhci_check_bw_table(struct xhci_hcd *xhci,
2062                 struct xhci_virt_device *virt_dev,
2063                 int old_active_eps)
2064 {
2065         unsigned int bw_reserved;
2066         unsigned int max_bandwidth;
2067         unsigned int bw_used;
2068         unsigned int block_size;
2069         struct xhci_interval_bw_table *bw_table;
2070         unsigned int packet_size = 0;
2071         unsigned int overhead = 0;
2072         unsigned int packets_transmitted = 0;
2073         unsigned int packets_remaining = 0;
2074         unsigned int i;
2075
2076         if (virt_dev->udev->speed == USB_SPEED_SUPER)
2077                 return xhci_check_ss_bw(xhci, virt_dev);
2078
2079         if (virt_dev->udev->speed == USB_SPEED_HIGH) {
2080                 max_bandwidth = HS_BW_LIMIT;
2081                 /* Convert percent of bus BW reserved to blocks reserved */
2082                 bw_reserved = DIV_ROUND_UP(HS_BW_RESERVED * max_bandwidth, 100);
2083         } else {
2084                 max_bandwidth = FS_BW_LIMIT;
2085                 bw_reserved = DIV_ROUND_UP(FS_BW_RESERVED * max_bandwidth, 100);
2086         }
2087
2088         bw_table = virt_dev->bw_table;
2089         /* We need to translate the max packet size and max ESIT payloads into
2090          * the units the hardware uses.
2091          */
2092         block_size = xhci_get_block_size(virt_dev->udev);
2093
2094         /* If we are manipulating a LS/FS device under a HS hub, double check
2095          * that the HS bus has enough bandwidth if we are activing a new TT.
2096          */
2097         if (virt_dev->tt_info) {
2098                 xhci_dbg(xhci, "Recalculating BW for rootport %u\n",
2099                                 virt_dev->real_port);
2100                 if (xhci_check_tt_bw_table(xhci, virt_dev, old_active_eps)) {
2101                         xhci_warn(xhci, "Not enough bandwidth on HS bus for "
2102                                         "newly activated TT.\n");
2103                         return -ENOMEM;
2104                 }
2105                 xhci_dbg(xhci, "Recalculating BW for TT slot %u port %u\n",
2106                                 virt_dev->tt_info->slot_id,
2107                                 virt_dev->tt_info->ttport);
2108         } else {
2109                 xhci_dbg(xhci, "Recalculating BW for rootport %u\n",
2110                                 virt_dev->real_port);
2111         }
2112
2113         /* Add in how much bandwidth will be used for interval zero, or the
2114          * rounded max ESIT payload + number of packets * largest overhead.
2115          */
2116         bw_used = DIV_ROUND_UP(bw_table->interval0_esit_payload, block_size) +
2117                 bw_table->interval_bw[0].num_packets *
2118                 xhci_get_largest_overhead(&bw_table->interval_bw[0]);
2119
2120         for (i = 1; i < XHCI_MAX_INTERVAL; i++) {
2121                 unsigned int bw_added;
2122                 unsigned int largest_mps;
2123                 unsigned int interval_overhead;
2124
2125                 /*
2126                  * How many packets could we transmit in this interval?
2127                  * If packets didn't fit in the previous interval, we will need
2128                  * to transmit that many packets twice within this interval.
2129                  */
2130                 packets_remaining = 2 * packets_remaining +
2131                         bw_table->interval_bw[i].num_packets;
2132
2133                 /* Find the largest max packet size of this or the previous
2134                  * interval.
2135                  */
2136                 if (list_empty(&bw_table->interval_bw[i].endpoints))
2137                         largest_mps = 0;
2138                 else {
2139                         struct xhci_virt_ep *virt_ep;
2140                         struct list_head *ep_entry;
2141
2142                         ep_entry = bw_table->interval_bw[i].endpoints.next;
2143                         virt_ep = list_entry(ep_entry,
2144                                         struct xhci_virt_ep, bw_endpoint_list);
2145                         /* Convert to blocks, rounding up */
2146                         largest_mps = DIV_ROUND_UP(
2147                                         virt_ep->bw_info.max_packet_size,
2148                                         block_size);
2149                 }
2150                 if (largest_mps > packet_size)
2151                         packet_size = largest_mps;
2152
2153                 /* Use the larger overhead of this or the previous interval. */
2154                 interval_overhead = xhci_get_largest_overhead(
2155                                 &bw_table->interval_bw[i]);
2156                 if (interval_overhead > overhead)
2157                         overhead = interval_overhead;
2158
2159                 /* How many packets can we evenly distribute across
2160                  * (1 << (i + 1)) possible scheduling opportunities?
2161                  */
2162                 packets_transmitted = packets_remaining >> (i + 1);
2163
2164                 /* Add in the bandwidth used for those scheduled packets */
2165                 bw_added = packets_transmitted * (overhead + packet_size);
2166
2167                 /* How many packets do we have remaining to transmit? */
2168                 packets_remaining = packets_remaining % (1 << (i + 1));
2169
2170                 /* What largest max packet size should those packets have? */
2171                 /* If we've transmitted all packets, don't carry over the
2172                  * largest packet size.
2173                  */
2174                 if (packets_remaining == 0) {
2175                         packet_size = 0;
2176                         overhead = 0;
2177                 } else if (packets_transmitted > 0) {
2178                         /* Otherwise if we do have remaining packets, and we've
2179                          * scheduled some packets in this interval, take the
2180                          * largest max packet size from endpoints with this
2181                          * interval.
2182                          */
2183                         packet_size = largest_mps;
2184                         overhead = interval_overhead;
2185                 }
2186                 /* Otherwise carry over packet_size and overhead from the last
2187                  * time we had a remainder.
2188                  */
2189                 bw_used += bw_added;
2190                 if (bw_used > max_bandwidth) {
2191                         xhci_warn(xhci, "Not enough bandwidth. "
2192                                         "Proposed: %u, Max: %u\n",
2193                                 bw_used, max_bandwidth);
2194                         return -ENOMEM;
2195                 }
2196         }
2197         /*
2198          * Ok, we know we have some packets left over after even-handedly
2199          * scheduling interval 15.  We don't know which microframes they will
2200          * fit into, so we over-schedule and say they will be scheduled every
2201          * microframe.
2202          */
2203         if (packets_remaining > 0)
2204                 bw_used += overhead + packet_size;
2205
2206         if (!virt_dev->tt_info && virt_dev->udev->speed == USB_SPEED_HIGH) {
2207                 unsigned int port_index = virt_dev->real_port - 1;
2208
2209                 /* OK, we're manipulating a HS device attached to a
2210                  * root port bandwidth domain.  Include the number of active TTs
2211                  * in the bandwidth used.
2212                  */
2213                 bw_used += TT_HS_OVERHEAD *
2214                         xhci->rh_bw[port_index].num_active_tts;
2215         }
2216
2217         xhci_dbg(xhci, "Final bandwidth: %u, Limit: %u, Reserved: %u, "
2218                 "Available: %u " "percent\n",
2219                 bw_used, max_bandwidth, bw_reserved,
2220                 (max_bandwidth - bw_used - bw_reserved) * 100 /
2221                 max_bandwidth);
2222
2223         bw_used += bw_reserved;
2224         if (bw_used > max_bandwidth) {
2225                 xhci_warn(xhci, "Not enough bandwidth. Proposed: %u, Max: %u\n",
2226                                 bw_used, max_bandwidth);
2227                 return -ENOMEM;
2228         }
2229
2230         bw_table->bw_used = bw_used;
2231         return 0;
2232 }
2233
2234 static bool xhci_is_async_ep(unsigned int ep_type)
2235 {
2236         return (ep_type != ISOC_OUT_EP && ep_type != INT_OUT_EP &&
2237                                         ep_type != ISOC_IN_EP &&
2238                                         ep_type != INT_IN_EP);
2239 }
2240
2241 static bool xhci_is_sync_in_ep(unsigned int ep_type)
2242 {
2243         return (ep_type == ISOC_IN_EP || ep_type != INT_IN_EP);
2244 }
2245
2246 static unsigned int xhci_get_ss_bw_consumed(struct xhci_bw_info *ep_bw)
2247 {
2248         unsigned int mps = DIV_ROUND_UP(ep_bw->max_packet_size, SS_BLOCK);
2249
2250         if (ep_bw->ep_interval == 0)
2251                 return SS_OVERHEAD_BURST +
2252                         (ep_bw->mult * ep_bw->num_packets *
2253                                         (SS_OVERHEAD + mps));
2254         return DIV_ROUND_UP(ep_bw->mult * ep_bw->num_packets *
2255                                 (SS_OVERHEAD + mps + SS_OVERHEAD_BURST),
2256                                 1 << ep_bw->ep_interval);
2257
2258 }
2259
2260 void xhci_drop_ep_from_interval_table(struct xhci_hcd *xhci,
2261                 struct xhci_bw_info *ep_bw,
2262                 struct xhci_interval_bw_table *bw_table,
2263                 struct usb_device *udev,
2264                 struct xhci_virt_ep *virt_ep,
2265                 struct xhci_tt_bw_info *tt_info)
2266 {
2267         struct xhci_interval_bw *interval_bw;
2268         int normalized_interval;
2269
2270         if (xhci_is_async_ep(ep_bw->type))
2271                 return;
2272
2273         if (udev->speed == USB_SPEED_SUPER) {
2274                 if (xhci_is_sync_in_ep(ep_bw->type))
2275                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in -=
2276                                 xhci_get_ss_bw_consumed(ep_bw);
2277                 else
2278                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out -=
2279                                 xhci_get_ss_bw_consumed(ep_bw);
2280                 return;
2281         }
2282
2283         /* SuperSpeed endpoints never get added to intervals in the table, so
2284          * this check is only valid for HS/FS/LS devices.
2285          */
2286         if (list_empty(&virt_ep->bw_endpoint_list))
2287                 return;
2288         /* For LS/FS devices, we need to translate the interval expressed in
2289          * microframes to frames.
2290          */
2291         if (udev->speed == USB_SPEED_HIGH)
2292                 normalized_interval = ep_bw->ep_interval;
2293         else
2294                 normalized_interval = ep_bw->ep_interval - 3;
2295
2296         if (normalized_interval == 0)
2297                 bw_table->interval0_esit_payload -= ep_bw->max_esit_payload;
2298         interval_bw = &bw_table->interval_bw[normalized_interval];
2299         interval_bw->num_packets -= ep_bw->num_packets;
2300         switch (udev->speed) {
2301         case USB_SPEED_LOW:
2302                 interval_bw->overhead[LS_OVERHEAD_TYPE] -= 1;
2303                 break;
2304         case USB_SPEED_FULL:
2305                 interval_bw->overhead[FS_OVERHEAD_TYPE] -= 1;
2306                 break;
2307         case USB_SPEED_HIGH:
2308                 interval_bw->overhead[HS_OVERHEAD_TYPE] -= 1;
2309                 break;
2310         case USB_SPEED_SUPER:
2311         case USB_SPEED_UNKNOWN:
2312         case USB_SPEED_WIRELESS:
2313                 /* Should never happen because only LS/FS/HS endpoints will get
2314                  * added to the endpoint list.
2315                  */
2316                 return;
2317         }
2318         if (tt_info)
2319                 tt_info->active_eps -= 1;
2320         list_del_init(&virt_ep->bw_endpoint_list);
2321 }
2322
2323 static void xhci_add_ep_to_interval_table(struct xhci_hcd *xhci,
2324                 struct xhci_bw_info *ep_bw,
2325                 struct xhci_interval_bw_table *bw_table,
2326                 struct usb_device *udev,
2327                 struct xhci_virt_ep *virt_ep,
2328                 struct xhci_tt_bw_info *tt_info)
2329 {
2330         struct xhci_interval_bw *interval_bw;
2331         struct xhci_virt_ep *smaller_ep;
2332         int normalized_interval;
2333
2334         if (xhci_is_async_ep(ep_bw->type))
2335                 return;
2336
2337         if (udev->speed == USB_SPEED_SUPER) {
2338                 if (xhci_is_sync_in_ep(ep_bw->type))
2339                         xhci->devs[udev->slot_id]->bw_table->ss_bw_in +=
2340                                 xhci_get_ss_bw_consumed(ep_bw);
2341                 else
2342                         xhci->devs[udev->slot_id]->bw_table->ss_bw_out +=
2343                                 xhci_get_ss_bw_consumed(ep_bw);
2344                 return;
2345         }
2346
2347         /* For LS/FS devices, we need to translate the interval expressed in
2348          * microframes to frames.
2349          */
2350         if (udev->speed == USB_SPEED_HIGH)
2351                 normalized_interval = ep_bw->ep_interval;
2352         else
2353                 normalized_interval = ep_bw->ep_interval - 3;
2354
2355         if (normalized_interval == 0)
2356                 bw_table->interval0_esit_payload += ep_bw->max_esit_payload;
2357         interval_bw = &bw_table->interval_bw[normalized_interval];
2358         interval_bw->num_packets += ep_bw->num_packets;
2359         switch (udev->speed) {
2360         case USB_SPEED_LOW:
2361                 interval_bw->overhead[LS_OVERHEAD_TYPE] += 1;
2362                 break;
2363         case USB_SPEED_FULL:
2364                 interval_bw->overhead[FS_OVERHEAD_TYPE] += 1;
2365                 break;
2366         case USB_SPEED_HIGH:
2367                 interval_bw->overhead[HS_OVERHEAD_TYPE] += 1;
2368                 break;
2369         case USB_SPEED_SUPER:
2370         case USB_SPEED_UNKNOWN:
2371         case USB_SPEED_WIRELESS:
2372                 /* Should never happen because only LS/FS/HS endpoints will get
2373                  * added to the endpoint list.
2374                  */
2375                 return;
2376         }
2377
2378         if (tt_info)
2379                 tt_info->active_eps += 1;
2380         /* Insert the endpoint into the list, largest max packet size first. */
2381         list_for_each_entry(smaller_ep, &interval_bw->endpoints,
2382                         bw_endpoint_list) {
2383                 if (ep_bw->max_packet_size >=
2384                                 smaller_ep->bw_info.max_packet_size) {
2385                         /* Add the new ep before the smaller endpoint */
2386                         list_add_tail(&virt_ep->bw_endpoint_list,
2387                                         &smaller_ep->bw_endpoint_list);
2388                         return;
2389                 }
2390         }
2391         /* Add the new endpoint at the end of the list. */
2392         list_add_tail(&virt_ep->bw_endpoint_list,
2393                         &interval_bw->endpoints);
2394 }
2395
2396 void xhci_update_tt_active_eps(struct xhci_hcd *xhci,
2397                 struct xhci_virt_device *virt_dev,
2398                 int old_active_eps)
2399 {
2400         struct xhci_root_port_bw_info *rh_bw_info;
2401         if (!virt_dev->tt_info)
2402                 return;
2403
2404         rh_bw_info = &xhci->rh_bw[virt_dev->real_port - 1];
2405         if (old_active_eps == 0 &&
2406                                 virt_dev->tt_info->active_eps != 0) {
2407                 rh_bw_info->num_active_tts += 1;
2408                 rh_bw_info->bw_table.bw_used += TT_HS_OVERHEAD;
2409         } else if (old_active_eps != 0 &&
2410                                 virt_dev->tt_info->active_eps == 0) {
2411                 rh_bw_info->num_active_tts -= 1;
2412                 rh_bw_info->bw_table.bw_used -= TT_HS_OVERHEAD;
2413         }
2414 }
2415
2416 static int xhci_reserve_bandwidth(struct xhci_hcd *xhci,
2417                 struct xhci_virt_device *virt_dev,
2418                 struct xhci_container_ctx *in_ctx)
2419 {
2420         struct xhci_bw_info ep_bw_info[31];
2421         int i;
2422         struct xhci_input_control_ctx *ctrl_ctx;
2423         int old_active_eps = 0;
2424
2425         if (virt_dev->tt_info)
2426                 old_active_eps = virt_dev->tt_info->active_eps;
2427
2428         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
2429
2430         for (i = 0; i < 31; i++) {
2431                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2432                         continue;
2433
2434                 /* Make a copy of the BW info in case we need to revert this */
2435                 memcpy(&ep_bw_info[i], &virt_dev->eps[i].bw_info,
2436                                 sizeof(ep_bw_info[i]));
2437                 /* Drop the endpoint from the interval table if the endpoint is
2438                  * being dropped or changed.
2439                  */
2440                 if (EP_IS_DROPPED(ctrl_ctx, i))
2441                         xhci_drop_ep_from_interval_table(xhci,
2442                                         &virt_dev->eps[i].bw_info,
2443                                         virt_dev->bw_table,
2444                                         virt_dev->udev,
2445                                         &virt_dev->eps[i],
2446                                         virt_dev->tt_info);
2447         }
2448         /* Overwrite the information stored in the endpoints' bw_info */
2449         xhci_update_bw_info(xhci, virt_dev->in_ctx, ctrl_ctx, virt_dev);
2450         for (i = 0; i < 31; i++) {
2451                 /* Add any changed or added endpoints to the interval table */
2452                 if (EP_IS_ADDED(ctrl_ctx, i))
2453                         xhci_add_ep_to_interval_table(xhci,
2454                                         &virt_dev->eps[i].bw_info,
2455                                         virt_dev->bw_table,
2456                                         virt_dev->udev,
2457                                         &virt_dev->eps[i],
2458                                         virt_dev->tt_info);
2459         }
2460
2461         if (!xhci_check_bw_table(xhci, virt_dev, old_active_eps)) {
2462                 /* Ok, this fits in the bandwidth we have.
2463                  * Update the number of active TTs.
2464                  */
2465                 xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
2466                 return 0;
2467         }
2468
2469         /* We don't have enough bandwidth for this, revert the stored info. */
2470         for (i = 0; i < 31; i++) {
2471                 if (!EP_IS_ADDED(ctrl_ctx, i) && !EP_IS_DROPPED(ctrl_ctx, i))
2472                         continue;
2473
2474                 /* Drop the new copies of any added or changed endpoints from
2475                  * the interval table.
2476                  */
2477                 if (EP_IS_ADDED(ctrl_ctx, i)) {
2478                         xhci_drop_ep_from_interval_table(xhci,
2479                                         &virt_dev->eps[i].bw_info,
2480                                         virt_dev->bw_table,
2481                                         virt_dev->udev,
2482                                         &virt_dev->eps[i],
2483                                         virt_dev->tt_info);
2484                 }
2485                 /* Revert the endpoint back to its old information */
2486                 memcpy(&virt_dev->eps[i].bw_info, &ep_bw_info[i],
2487                                 sizeof(ep_bw_info[i]));
2488                 /* Add any changed or dropped endpoints back into the table */
2489                 if (EP_IS_DROPPED(ctrl_ctx, i))
2490                         xhci_add_ep_to_interval_table(xhci,
2491                                         &virt_dev->eps[i].bw_info,
2492                                         virt_dev->bw_table,
2493                                         virt_dev->udev,
2494                                         &virt_dev->eps[i],
2495                                         virt_dev->tt_info);
2496         }
2497         return -ENOMEM;
2498 }
2499
2500
2501 /* Issue a configure endpoint command or evaluate context command
2502  * and wait for it to finish.
2503  */
2504 static int xhci_configure_endpoint(struct xhci_hcd *xhci,
2505                 struct usb_device *udev,
2506                 struct xhci_command *command,
2507                 bool ctx_change, bool must_succeed)
2508 {
2509         int ret;
2510         int timeleft;
2511         unsigned long flags;
2512         struct xhci_container_ctx *in_ctx;
2513         struct completion *cmd_completion;
2514         u32 *cmd_status;
2515         struct xhci_virt_device *virt_dev;
2516         union xhci_trb *cmd_trb;
2517
2518         spin_lock_irqsave(&xhci->lock, flags);
2519         virt_dev = xhci->devs[udev->slot_id];
2520
2521         if (command)
2522                 in_ctx = command->in_ctx;
2523         else
2524                 in_ctx = virt_dev->in_ctx;
2525
2526         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK) &&
2527                         xhci_reserve_host_resources(xhci, in_ctx)) {
2528                 spin_unlock_irqrestore(&xhci->lock, flags);
2529                 xhci_warn(xhci, "Not enough host resources, "
2530                                 "active endpoint contexts = %u\n",
2531                                 xhci->num_active_eps);
2532                 return -ENOMEM;
2533         }
2534         if ((xhci->quirks & XHCI_SW_BW_CHECKING) &&
2535                         xhci_reserve_bandwidth(xhci, virt_dev, in_ctx)) {
2536                 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2537                         xhci_free_host_resources(xhci, in_ctx);
2538                 spin_unlock_irqrestore(&xhci->lock, flags);
2539                 xhci_warn(xhci, "Not enough bandwidth\n");
2540                 return -ENOMEM;
2541         }
2542
2543         if (command) {
2544                 cmd_completion = command->completion;
2545                 cmd_status = &command->status;
2546                 command->command_trb = xhci->cmd_ring->enqueue;
2547
2548                 /* Enqueue pointer can be left pointing to the link TRB,
2549                  * we must handle that
2550                  */
2551                 if (TRB_TYPE_LINK_LE32(command->command_trb->link.control))
2552                         command->command_trb =
2553                                 xhci->cmd_ring->enq_seg->next->trbs;
2554
2555                 list_add_tail(&command->cmd_list, &virt_dev->cmd_list);
2556         } else {
2557                 cmd_completion = &virt_dev->cmd_completion;
2558                 cmd_status = &virt_dev->cmd_status;
2559         }
2560         init_completion(cmd_completion);
2561
2562         cmd_trb = xhci->cmd_ring->dequeue;
2563         if (!ctx_change)
2564                 ret = xhci_queue_configure_endpoint(xhci, in_ctx->dma,
2565                                 udev->slot_id, must_succeed);
2566         else
2567                 ret = xhci_queue_evaluate_context(xhci, in_ctx->dma,
2568                                 udev->slot_id);
2569         if (ret < 0) {
2570                 if (command)
2571                         list_del(&command->cmd_list);
2572                 if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK))
2573                         xhci_free_host_resources(xhci, in_ctx);
2574                 spin_unlock_irqrestore(&xhci->lock, flags);
2575                 xhci_dbg(xhci, "FIXME allocate a new ring segment\n");
2576                 return -ENOMEM;
2577         }
2578         xhci_ring_cmd_db(xhci);
2579         spin_unlock_irqrestore(&xhci->lock, flags);
2580
2581         /* Wait for the configure endpoint command to complete */
2582         timeleft = wait_for_completion_interruptible_timeout(
2583                         cmd_completion,
2584                         XHCI_CMD_DEFAULT_TIMEOUT);
2585         if (timeleft <= 0) {
2586                 xhci_warn(xhci, "%s while waiting for %s command\n",
2587                                 timeleft == 0 ? "Timeout" : "Signal",
2588                                 ctx_change == 0 ?
2589                                         "configure endpoint" :
2590                                         "evaluate context");
2591                 /* cancel the configure endpoint command */
2592                 ret = xhci_cancel_cmd(xhci, command, cmd_trb);
2593                 if (ret < 0)
2594                         return ret;
2595                 return -ETIME;
2596         }
2597
2598         if (!ctx_change)
2599                 ret = xhci_configure_endpoint_result(xhci, udev, cmd_status);
2600         else
2601                 ret = xhci_evaluate_context_result(xhci, udev, cmd_status);
2602
2603         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
2604                 spin_lock_irqsave(&xhci->lock, flags);
2605                 /* If the command failed, remove the reserved resources.
2606                  * Otherwise, clean up the estimate to include dropped eps.
2607                  */
2608                 if (ret)
2609                         xhci_free_host_resources(xhci, in_ctx);
2610                 else
2611                         xhci_finish_resource_reservation(xhci, in_ctx);
2612                 spin_unlock_irqrestore(&xhci->lock, flags);
2613         }
2614         return ret;
2615 }
2616
2617 /* Called after one or more calls to xhci_add_endpoint() or
2618  * xhci_drop_endpoint().  If this call fails, the USB core is expected
2619  * to call xhci_reset_bandwidth().
2620  *
2621  * Since we are in the middle of changing either configuration or
2622  * installing a new alt setting, the USB core won't allow URBs to be
2623  * enqueued for any endpoint on the old config or interface.  Nothing
2624  * else should be touching the xhci->devs[slot_id] structure, so we
2625  * don't need to take the xhci->lock for manipulating that.
2626  */
2627 int xhci_check_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2628 {
2629         int i;
2630         int ret = 0;
2631         struct xhci_hcd *xhci;
2632         struct xhci_virt_device *virt_dev;
2633         struct xhci_input_control_ctx *ctrl_ctx;
2634         struct xhci_slot_ctx *slot_ctx;
2635
2636         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2637         if (ret <= 0)
2638                 return ret;
2639         xhci = hcd_to_xhci(hcd);
2640         if (xhci->xhc_state & XHCI_STATE_DYING)
2641                 return -ENODEV;
2642
2643         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2644         virt_dev = xhci->devs[udev->slot_id];
2645
2646         /* See section 4.6.6 - A0 = 1; A1 = D0 = D1 = 0 */
2647         ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx);
2648         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2649         ctrl_ctx->add_flags &= cpu_to_le32(~EP0_FLAG);
2650         ctrl_ctx->drop_flags &= cpu_to_le32(~(SLOT_FLAG | EP0_FLAG));
2651
2652         /* Don't issue the command if there's no endpoints to update. */
2653         if (ctrl_ctx->add_flags == cpu_to_le32(SLOT_FLAG) &&
2654                         ctrl_ctx->drop_flags == 0)
2655                 return 0;
2656
2657         xhci_dbg(xhci, "New Input Control Context:\n");
2658         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
2659         xhci_dbg_ctx(xhci, virt_dev->in_ctx,
2660                      LAST_CTX_TO_EP_NUM(le32_to_cpu(slot_ctx->dev_info)));
2661
2662         ret = xhci_configure_endpoint(xhci, udev, NULL,
2663                         false, false);
2664         if (ret) {
2665                 /* Callee should call reset_bandwidth() */
2666                 return ret;
2667         }
2668
2669         xhci_dbg(xhci, "Output context after successful config ep cmd:\n");
2670         xhci_dbg_ctx(xhci, virt_dev->out_ctx,
2671                      LAST_CTX_TO_EP_NUM(le32_to_cpu(slot_ctx->dev_info)));
2672
2673         /* Free any rings that were dropped, but not changed. */
2674         for (i = 1; i < 31; ++i) {
2675                 if ((le32_to_cpu(ctrl_ctx->drop_flags) & (1 << (i + 1))) &&
2676                     !(le32_to_cpu(ctrl_ctx->add_flags) & (1 << (i + 1))))
2677                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
2678         }
2679         xhci_zero_in_ctx(xhci, virt_dev);
2680         /*
2681          * Install any rings for completely new endpoints or changed endpoints,
2682          * and free or cache any old rings from changed endpoints.
2683          */
2684         for (i = 1; i < 31; ++i) {
2685                 if (!virt_dev->eps[i].new_ring)
2686                         continue;
2687                 /* Only cache or free the old ring if it exists.
2688                  * It may not if this is the first add of an endpoint.
2689                  */
2690                 if (virt_dev->eps[i].ring) {
2691                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
2692                 }
2693                 virt_dev->eps[i].ring = virt_dev->eps[i].new_ring;
2694                 virt_dev->eps[i].new_ring = NULL;
2695         }
2696
2697         return ret;
2698 }
2699
2700 void xhci_reset_bandwidth(struct usb_hcd *hcd, struct usb_device *udev)
2701 {
2702         struct xhci_hcd *xhci;
2703         struct xhci_virt_device *virt_dev;
2704         int i, ret;
2705
2706         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
2707         if (ret <= 0)
2708                 return;
2709         xhci = hcd_to_xhci(hcd);
2710
2711         xhci_dbg(xhci, "%s called for udev %p\n", __func__, udev);
2712         virt_dev = xhci->devs[udev->slot_id];
2713         /* Free any rings allocated for added endpoints */
2714         for (i = 0; i < 31; ++i) {
2715                 if (virt_dev->eps[i].new_ring) {
2716                         xhci_ring_free(xhci, virt_dev->eps[i].new_ring);
2717                         virt_dev->eps[i].new_ring = NULL;
2718                 }
2719         }
2720         xhci_zero_in_ctx(xhci, virt_dev);
2721 }
2722
2723 static void xhci_setup_input_ctx_for_config_ep(struct xhci_hcd *xhci,
2724                 struct xhci_container_ctx *in_ctx,
2725                 struct xhci_container_ctx *out_ctx,
2726                 u32 add_flags, u32 drop_flags)
2727 {
2728         struct xhci_input_control_ctx *ctrl_ctx;
2729         ctrl_ctx = xhci_get_input_control_ctx(xhci, in_ctx);
2730         ctrl_ctx->add_flags = cpu_to_le32(add_flags);
2731         ctrl_ctx->drop_flags = cpu_to_le32(drop_flags);
2732         xhci_slot_copy(xhci, in_ctx, out_ctx);
2733         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
2734
2735         xhci_dbg(xhci, "Input Context:\n");
2736         xhci_dbg_ctx(xhci, in_ctx, xhci_last_valid_endpoint(add_flags));
2737 }
2738
2739 static void xhci_setup_input_ctx_for_quirk(struct xhci_hcd *xhci,
2740                 unsigned int slot_id, unsigned int ep_index,
2741                 struct xhci_dequeue_state *deq_state)
2742 {
2743         struct xhci_container_ctx *in_ctx;
2744         struct xhci_ep_ctx *ep_ctx;
2745         u32 added_ctxs;
2746         dma_addr_t addr;
2747
2748         xhci_endpoint_copy(xhci, xhci->devs[slot_id]->in_ctx,
2749                         xhci->devs[slot_id]->out_ctx, ep_index);
2750         in_ctx = xhci->devs[slot_id]->in_ctx;
2751         ep_ctx = xhci_get_ep_ctx(xhci, in_ctx, ep_index);
2752         addr = xhci_trb_virt_to_dma(deq_state->new_deq_seg,
2753                         deq_state->new_deq_ptr);
2754         if (addr == 0) {
2755                 xhci_warn(xhci, "WARN Cannot submit config ep after "
2756                                 "reset ep command\n");
2757                 xhci_warn(xhci, "WARN deq seg = %p, deq ptr = %p\n",
2758                                 deq_state->new_deq_seg,
2759                                 deq_state->new_deq_ptr);
2760                 return;
2761         }
2762         ep_ctx->deq = cpu_to_le64(addr | deq_state->new_cycle_state);
2763
2764         added_ctxs = xhci_get_endpoint_flag_from_index(ep_index);
2765         xhci_setup_input_ctx_for_config_ep(xhci, xhci->devs[slot_id]->in_ctx,
2766                         xhci->devs[slot_id]->out_ctx, added_ctxs, added_ctxs);
2767 }
2768
2769 void xhci_cleanup_stalled_ring(struct xhci_hcd *xhci,
2770                 struct usb_device *udev, unsigned int ep_index)
2771 {
2772         struct xhci_dequeue_state deq_state;
2773         struct xhci_virt_ep *ep;
2774
2775         xhci_dbg(xhci, "Cleaning up stalled endpoint ring\n");
2776         ep = &xhci->devs[udev->slot_id]->eps[ep_index];
2777         /* We need to move the HW's dequeue pointer past this TD,
2778          * or it will attempt to resend it on the next doorbell ring.
2779          */
2780         xhci_find_new_dequeue_state(xhci, udev->slot_id,
2781                         ep_index, ep->stopped_stream, ep->stopped_td,
2782                         &deq_state);
2783
2784         /* HW with the reset endpoint quirk will use the saved dequeue state to
2785          * issue a configure endpoint command later.
2786          */
2787         if (!(xhci->quirks & XHCI_RESET_EP_QUIRK)) {
2788                 xhci_dbg(xhci, "Queueing new dequeue state\n");
2789                 xhci_queue_new_dequeue_state(xhci, udev->slot_id,
2790                                 ep_index, ep->stopped_stream, &deq_state);
2791         } else {
2792                 /* Better hope no one uses the input context between now and the
2793                  * reset endpoint completion!
2794                  * XXX: No idea how this hardware will react when stream rings
2795                  * are enabled.
2796                  */
2797                 xhci_dbg(xhci, "Setting up input context for "
2798                                 "configure endpoint command\n");
2799                 xhci_setup_input_ctx_for_quirk(xhci, udev->slot_id,
2800                                 ep_index, &deq_state);
2801         }
2802 }
2803
2804 /* Deal with stalled endpoints.  The core should have sent the control message
2805  * to clear the halt condition.  However, we need to make the xHCI hardware
2806  * reset its sequence number, since a device will expect a sequence number of
2807  * zero after the halt condition is cleared.
2808  * Context: in_interrupt
2809  */
2810 void xhci_endpoint_reset(struct usb_hcd *hcd,
2811                 struct usb_host_endpoint *ep)
2812 {
2813         struct xhci_hcd *xhci;
2814         struct usb_device *udev;
2815         unsigned int ep_index;
2816         unsigned long flags;
2817         int ret;
2818         struct xhci_virt_ep *virt_ep;
2819
2820         xhci = hcd_to_xhci(hcd);
2821         udev = (struct usb_device *) ep->hcpriv;
2822         /* Called with a root hub endpoint (or an endpoint that wasn't added
2823          * with xhci_add_endpoint()
2824          */
2825         if (!ep->hcpriv)
2826                 return;
2827         ep_index = xhci_get_endpoint_index(&ep->desc);
2828         virt_ep = &xhci->devs[udev->slot_id]->eps[ep_index];
2829         if (!virt_ep->stopped_td) {
2830                 xhci_dbg(xhci, "Endpoint 0x%x not halted, refusing to reset.\n",
2831                                 ep->desc.bEndpointAddress);
2832                 return;
2833         }
2834         if (usb_endpoint_xfer_control(&ep->desc)) {
2835                 xhci_dbg(xhci, "Control endpoint stall already handled.\n");
2836                 return;
2837         }
2838
2839         xhci_dbg(xhci, "Queueing reset endpoint command\n");
2840         spin_lock_irqsave(&xhci->lock, flags);
2841         ret = xhci_queue_reset_ep(xhci, udev->slot_id, ep_index);
2842         /*
2843          * Can't change the ring dequeue pointer until it's transitioned to the
2844          * stopped state, which is only upon a successful reset endpoint
2845          * command.  Better hope that last command worked!
2846          */
2847         if (!ret) {
2848                 xhci_cleanup_stalled_ring(xhci, udev, ep_index);
2849                 kfree(virt_ep->stopped_td);
2850                 xhci_ring_cmd_db(xhci);
2851         }
2852         virt_ep->stopped_td = NULL;
2853         virt_ep->stopped_trb = NULL;
2854         virt_ep->stopped_stream = 0;
2855         spin_unlock_irqrestore(&xhci->lock, flags);
2856
2857         if (ret)
2858                 xhci_warn(xhci, "FIXME allocate a new ring segment\n");
2859 }
2860
2861 static int xhci_check_streams_endpoint(struct xhci_hcd *xhci,
2862                 struct usb_device *udev, struct usb_host_endpoint *ep,
2863                 unsigned int slot_id)
2864 {
2865         int ret;
2866         unsigned int ep_index;
2867         unsigned int ep_state;
2868
2869         if (!ep)
2870                 return -EINVAL;
2871         ret = xhci_check_args(xhci_to_hcd(xhci), udev, ep, 1, true, __func__);
2872         if (ret <= 0)
2873                 return -EINVAL;
2874         if (ep->ss_ep_comp.bmAttributes == 0) {
2875                 xhci_warn(xhci, "WARN: SuperSpeed Endpoint Companion"
2876                                 " descriptor for ep 0x%x does not support streams\n",
2877                                 ep->desc.bEndpointAddress);
2878                 return -EINVAL;
2879         }
2880
2881         ep_index = xhci_get_endpoint_index(&ep->desc);
2882         ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
2883         if (ep_state & EP_HAS_STREAMS ||
2884                         ep_state & EP_GETTING_STREAMS) {
2885                 xhci_warn(xhci, "WARN: SuperSpeed bulk endpoint 0x%x "
2886                                 "already has streams set up.\n",
2887                                 ep->desc.bEndpointAddress);
2888                 xhci_warn(xhci, "Send email to xHCI maintainer and ask for "
2889                                 "dynamic stream context array reallocation.\n");
2890                 return -EINVAL;
2891         }
2892         if (!list_empty(&xhci->devs[slot_id]->eps[ep_index].ring->td_list)) {
2893                 xhci_warn(xhci, "Cannot setup streams for SuperSpeed bulk "
2894                                 "endpoint 0x%x; URBs are pending.\n",
2895                                 ep->desc.bEndpointAddress);
2896                 return -EINVAL;
2897         }
2898         return 0;
2899 }
2900
2901 static void xhci_calculate_streams_entries(struct xhci_hcd *xhci,
2902                 unsigned int *num_streams, unsigned int *num_stream_ctxs)
2903 {
2904         unsigned int max_streams;
2905
2906         /* The stream context array size must be a power of two */
2907         *num_stream_ctxs = roundup_pow_of_two(*num_streams);
2908         /*
2909          * Find out how many primary stream array entries the host controller
2910          * supports.  Later we may use secondary stream arrays (similar to 2nd
2911          * level page entries), but that's an optional feature for xHCI host
2912          * controllers. xHCs must support at least 4 stream IDs.
2913          */
2914         max_streams = HCC_MAX_PSA(xhci->hcc_params);
2915         if (*num_stream_ctxs > max_streams) {
2916                 xhci_dbg(xhci, "xHCI HW only supports %u stream ctx entries.\n",
2917                                 max_streams);
2918                 *num_stream_ctxs = max_streams;
2919                 *num_streams = max_streams;
2920         }
2921 }
2922
2923 /* Returns an error code if one of the endpoint already has streams.
2924  * This does not change any data structures, it only checks and gathers
2925  * information.
2926  */
2927 static int xhci_calculate_streams_and_bitmask(struct xhci_hcd *xhci,
2928                 struct usb_device *udev,
2929                 struct usb_host_endpoint **eps, unsigned int num_eps,
2930                 unsigned int *num_streams, u32 *changed_ep_bitmask)
2931 {
2932         unsigned int max_streams;
2933         unsigned int endpoint_flag;
2934         int i;
2935         int ret;
2936
2937         for (i = 0; i < num_eps; i++) {
2938                 ret = xhci_check_streams_endpoint(xhci, udev,
2939                                 eps[i], udev->slot_id);
2940                 if (ret < 0)
2941                         return ret;
2942
2943                 max_streams = usb_ss_max_streams(&eps[i]->ss_ep_comp);
2944                 if (max_streams < (*num_streams - 1)) {
2945                         xhci_dbg(xhci, "Ep 0x%x only supports %u stream IDs.\n",
2946                                         eps[i]->desc.bEndpointAddress,
2947                                         max_streams);
2948                         *num_streams = max_streams+1;
2949                 }
2950
2951                 endpoint_flag = xhci_get_endpoint_flag(&eps[i]->desc);
2952                 if (*changed_ep_bitmask & endpoint_flag)
2953                         return -EINVAL;
2954                 *changed_ep_bitmask |= endpoint_flag;
2955         }
2956         return 0;
2957 }
2958
2959 static u32 xhci_calculate_no_streams_bitmask(struct xhci_hcd *xhci,
2960                 struct usb_device *udev,
2961                 struct usb_host_endpoint **eps, unsigned int num_eps)
2962 {
2963         u32 changed_ep_bitmask = 0;
2964         unsigned int slot_id;
2965         unsigned int ep_index;
2966         unsigned int ep_state;
2967         int i;
2968
2969         slot_id = udev->slot_id;
2970         if (!xhci->devs[slot_id])
2971                 return 0;
2972
2973         for (i = 0; i < num_eps; i++) {
2974                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
2975                 ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state;
2976                 /* Are streams already being freed for the endpoint? */
2977                 if (ep_state & EP_GETTING_NO_STREAMS) {
2978                         xhci_warn(xhci, "WARN Can't disable streams for "
2979                                         "endpoint 0x%x\n, "
2980                                         "streams are being disabled already.",
2981                                         eps[i]->desc.bEndpointAddress);
2982                         return 0;
2983                 }
2984                 /* Are there actually any streams to free? */
2985                 if (!(ep_state & EP_HAS_STREAMS) &&
2986                                 !(ep_state & EP_GETTING_STREAMS)) {
2987                         xhci_warn(xhci, "WARN Can't disable streams for "
2988                                         "endpoint 0x%x\n, "
2989                                         "streams are already disabled!",
2990                                         eps[i]->desc.bEndpointAddress);
2991                         xhci_warn(xhci, "WARN xhci_free_streams() called "
2992                                         "with non-streams endpoint\n");
2993                         return 0;
2994                 }
2995                 changed_ep_bitmask |= xhci_get_endpoint_flag(&eps[i]->desc);
2996         }
2997         return changed_ep_bitmask;
2998 }
2999
3000 /*
3001  * The USB device drivers use this function (though the HCD interface in USB
3002  * core) to prepare a set of bulk endpoints to use streams.  Streams are used to
3003  * coordinate mass storage command queueing across multiple endpoints (basically
3004  * a stream ID == a task ID).
3005  *
3006  * Setting up streams involves allocating the same size stream context array
3007  * for each endpoint and issuing a configure endpoint command for all endpoints.
3008  *
3009  * Don't allow the call to succeed if one endpoint only supports one stream
3010  * (which means it doesn't support streams at all).
3011  *
3012  * Drivers may get less stream IDs than they asked for, if the host controller
3013  * hardware or endpoints claim they can't support the number of requested
3014  * stream IDs.
3015  */
3016 int xhci_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
3017                 struct usb_host_endpoint **eps, unsigned int num_eps,
3018                 unsigned int num_streams, gfp_t mem_flags)
3019 {
3020         int i, ret;
3021         struct xhci_hcd *xhci;
3022         struct xhci_virt_device *vdev;
3023         struct xhci_command *config_cmd;
3024         unsigned int ep_index;
3025         unsigned int num_stream_ctxs;
3026         unsigned long flags;
3027         u32 changed_ep_bitmask = 0;
3028
3029         if (!eps)
3030                 return -EINVAL;
3031
3032         /* Add one to the number of streams requested to account for
3033          * stream 0 that is reserved for xHCI usage.
3034          */
3035         num_streams += 1;
3036         xhci = hcd_to_xhci(hcd);
3037         xhci_dbg(xhci, "Driver wants %u stream IDs (including stream 0).\n",
3038                         num_streams);
3039
3040         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
3041         if (!config_cmd) {
3042                 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
3043                 return -ENOMEM;
3044         }
3045
3046         /* Check to make sure all endpoints are not already configured for
3047          * streams.  While we're at it, find the maximum number of streams that
3048          * all the endpoints will support and check for duplicate endpoints.
3049          */
3050         spin_lock_irqsave(&xhci->lock, flags);
3051         ret = xhci_calculate_streams_and_bitmask(xhci, udev, eps,
3052                         num_eps, &num_streams, &changed_ep_bitmask);
3053         if (ret < 0) {
3054                 xhci_free_command(xhci, config_cmd);
3055                 spin_unlock_irqrestore(&xhci->lock, flags);
3056                 return ret;
3057         }
3058         if (num_streams <= 1) {
3059                 xhci_warn(xhci, "WARN: endpoints can't handle "
3060                                 "more than one stream.\n");
3061                 xhci_free_command(xhci, config_cmd);
3062                 spin_unlock_irqrestore(&xhci->lock, flags);
3063                 return -EINVAL;
3064         }
3065         vdev = xhci->devs[udev->slot_id];
3066         /* Mark each endpoint as being in transition, so
3067          * xhci_urb_enqueue() will reject all URBs.
3068          */
3069         for (i = 0; i < num_eps; i++) {
3070                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3071                 vdev->eps[ep_index].ep_state |= EP_GETTING_STREAMS;
3072         }
3073         spin_unlock_irqrestore(&xhci->lock, flags);
3074
3075         /* Setup internal data structures and allocate HW data structures for
3076          * streams (but don't install the HW structures in the input context
3077          * until we're sure all memory allocation succeeded).
3078          */
3079         xhci_calculate_streams_entries(xhci, &num_streams, &num_stream_ctxs);
3080         xhci_dbg(xhci, "Need %u stream ctx entries for %u stream IDs.\n",
3081                         num_stream_ctxs, num_streams);
3082
3083         for (i = 0; i < num_eps; i++) {
3084                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3085                 vdev->eps[ep_index].stream_info = xhci_alloc_stream_info(xhci,
3086                                 num_stream_ctxs,
3087                                 num_streams, mem_flags);
3088                 if (!vdev->eps[ep_index].stream_info)
3089                         goto cleanup;
3090                 /* Set maxPstreams in endpoint context and update deq ptr to
3091                  * point to stream context array. FIXME
3092                  */
3093         }
3094
3095         /* Set up the input context for a configure endpoint command. */
3096         for (i = 0; i < num_eps; i++) {
3097                 struct xhci_ep_ctx *ep_ctx;
3098
3099                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3100                 ep_ctx = xhci_get_ep_ctx(xhci, config_cmd->in_ctx, ep_index);
3101
3102                 xhci_endpoint_copy(xhci, config_cmd->in_ctx,
3103                                 vdev->out_ctx, ep_index);
3104                 xhci_setup_streams_ep_input_ctx(xhci, ep_ctx,
3105                                 vdev->eps[ep_index].stream_info);
3106         }
3107         /* Tell the HW to drop its old copy of the endpoint context info
3108          * and add the updated copy from the input context.
3109          */
3110         xhci_setup_input_ctx_for_config_ep(xhci, config_cmd->in_ctx,
3111                         vdev->out_ctx, changed_ep_bitmask, changed_ep_bitmask);
3112
3113         /* Issue and wait for the configure endpoint command */
3114         ret = xhci_configure_endpoint(xhci, udev, config_cmd,
3115                         false, false);
3116
3117         /* xHC rejected the configure endpoint command for some reason, so we
3118          * leave the old ring intact and free our internal streams data
3119          * structure.
3120          */
3121         if (ret < 0)
3122                 goto cleanup;
3123
3124         spin_lock_irqsave(&xhci->lock, flags);
3125         for (i = 0; i < num_eps; i++) {
3126                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3127                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3128                 xhci_dbg(xhci, "Slot %u ep ctx %u now has streams.\n",
3129                          udev->slot_id, ep_index);
3130                 vdev->eps[ep_index].ep_state |= EP_HAS_STREAMS;
3131         }
3132         xhci_free_command(xhci, config_cmd);
3133         spin_unlock_irqrestore(&xhci->lock, flags);
3134
3135         /* Subtract 1 for stream 0, which drivers can't use */
3136         return num_streams - 1;
3137
3138 cleanup:
3139         /* If it didn't work, free the streams! */
3140         for (i = 0; i < num_eps; i++) {
3141                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3142                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3143                 vdev->eps[ep_index].stream_info = NULL;
3144                 /* FIXME Unset maxPstreams in endpoint context and
3145                  * update deq ptr to point to normal string ring.
3146                  */
3147                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_STREAMS;
3148                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3149                 xhci_endpoint_zero(xhci, vdev, eps[i]);
3150         }
3151         xhci_free_command(xhci, config_cmd);
3152         return -ENOMEM;
3153 }
3154
3155 /* Transition the endpoint from using streams to being a "normal" endpoint
3156  * without streams.
3157  *
3158  * Modify the endpoint context state, submit a configure endpoint command,
3159  * and free all endpoint rings for streams if that completes successfully.
3160  */
3161 int xhci_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
3162                 struct usb_host_endpoint **eps, unsigned int num_eps,
3163                 gfp_t mem_flags)
3164 {
3165         int i, ret;
3166         struct xhci_hcd *xhci;
3167         struct xhci_virt_device *vdev;
3168         struct xhci_command *command;
3169         unsigned int ep_index;
3170         unsigned long flags;
3171         u32 changed_ep_bitmask;
3172
3173         xhci = hcd_to_xhci(hcd);
3174         vdev = xhci->devs[udev->slot_id];
3175
3176         /* Set up a configure endpoint command to remove the streams rings */
3177         spin_lock_irqsave(&xhci->lock, flags);
3178         changed_ep_bitmask = xhci_calculate_no_streams_bitmask(xhci,
3179                         udev, eps, num_eps);
3180         if (changed_ep_bitmask == 0) {
3181                 spin_unlock_irqrestore(&xhci->lock, flags);
3182                 return -EINVAL;
3183         }
3184
3185         /* Use the xhci_command structure from the first endpoint.  We may have
3186          * allocated too many, but the driver may call xhci_free_streams() for
3187          * each endpoint it grouped into one call to xhci_alloc_streams().
3188          */
3189         ep_index = xhci_get_endpoint_index(&eps[0]->desc);
3190         command = vdev->eps[ep_index].stream_info->free_streams_command;
3191         for (i = 0; i < num_eps; i++) {
3192                 struct xhci_ep_ctx *ep_ctx;
3193
3194                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3195                 ep_ctx = xhci_get_ep_ctx(xhci, command->in_ctx, ep_index);
3196                 xhci->devs[udev->slot_id]->eps[ep_index].ep_state |=
3197                         EP_GETTING_NO_STREAMS;
3198
3199                 xhci_endpoint_copy(xhci, command->in_ctx,
3200                                 vdev->out_ctx, ep_index);
3201                 xhci_setup_no_streams_ep_input_ctx(xhci, ep_ctx,
3202                                 &vdev->eps[ep_index]);
3203         }
3204         xhci_setup_input_ctx_for_config_ep(xhci, command->in_ctx,
3205                         vdev->out_ctx, changed_ep_bitmask, changed_ep_bitmask);
3206         spin_unlock_irqrestore(&xhci->lock, flags);
3207
3208         /* Issue and wait for the configure endpoint command,
3209          * which must succeed.
3210          */
3211         ret = xhci_configure_endpoint(xhci, udev, command,
3212                         false, true);
3213
3214         /* xHC rejected the configure endpoint command for some reason, so we
3215          * leave the streams rings intact.
3216          */
3217         if (ret < 0)
3218                 return ret;
3219
3220         spin_lock_irqsave(&xhci->lock, flags);
3221         for (i = 0; i < num_eps; i++) {
3222                 ep_index = xhci_get_endpoint_index(&eps[i]->desc);
3223                 xhci_free_stream_info(xhci, vdev->eps[ep_index].stream_info);
3224                 vdev->eps[ep_index].stream_info = NULL;
3225                 /* FIXME Unset maxPstreams in endpoint context and
3226                  * update deq ptr to point to normal string ring.
3227                  */
3228                 vdev->eps[ep_index].ep_state &= ~EP_GETTING_NO_STREAMS;
3229                 vdev->eps[ep_index].ep_state &= ~EP_HAS_STREAMS;
3230         }
3231         spin_unlock_irqrestore(&xhci->lock, flags);
3232
3233         return 0;
3234 }
3235
3236 /*
3237  * Deletes endpoint resources for endpoints that were active before a Reset
3238  * Device command, or a Disable Slot command.  The Reset Device command leaves
3239  * the control endpoint intact, whereas the Disable Slot command deletes it.
3240  *
3241  * Must be called with xhci->lock held.
3242  */
3243 void xhci_free_device_endpoint_resources(struct xhci_hcd *xhci,
3244         struct xhci_virt_device *virt_dev, bool drop_control_ep)
3245 {
3246         int i;
3247         unsigned int num_dropped_eps = 0;
3248         unsigned int drop_flags = 0;
3249
3250         for (i = (drop_control_ep ? 0 : 1); i < 31; i++) {
3251                 if (virt_dev->eps[i].ring) {
3252                         drop_flags |= 1 << i;
3253                         num_dropped_eps++;
3254                 }
3255         }
3256         xhci->num_active_eps -= num_dropped_eps;
3257         if (num_dropped_eps)
3258                 xhci_dbg(xhci, "Dropped %u ep ctxs, flags = 0x%x, "
3259                                 "%u now active.\n",
3260                                 num_dropped_eps, drop_flags,
3261                                 xhci->num_active_eps);
3262 }
3263
3264 /*
3265  * This submits a Reset Device Command, which will set the device state to 0,
3266  * set the device address to 0, and disable all the endpoints except the default
3267  * control endpoint.  The USB core should come back and call
3268  * xhci_address_device(), and then re-set up the configuration.  If this is
3269  * called because of a usb_reset_and_verify_device(), then the old alternate
3270  * settings will be re-installed through the normal bandwidth allocation
3271  * functions.
3272  *
3273  * Wait for the Reset Device command to finish.  Remove all structures
3274  * associated with the endpoints that were disabled.  Clear the input device
3275  * structure?  Cache the rings?  Reset the control endpoint 0 max packet size?
3276  *
3277  * If the virt_dev to be reset does not exist or does not match the udev,
3278  * it means the device is lost, possibly due to the xHC restore error and
3279  * re-initialization during S3/S4. In this case, call xhci_alloc_dev() to
3280  * re-allocate the device.
3281  */
3282 int xhci_discover_or_reset_device(struct usb_hcd *hcd, struct usb_device *udev)
3283 {
3284         int ret, i;
3285         unsigned long flags;
3286         struct xhci_hcd *xhci;
3287         unsigned int slot_id;
3288         struct xhci_virt_device *virt_dev;
3289         struct xhci_command *reset_device_cmd;
3290         int timeleft;
3291         int last_freed_endpoint;
3292         struct xhci_slot_ctx *slot_ctx;
3293         int old_active_eps = 0;
3294
3295         ret = xhci_check_args(hcd, udev, NULL, 0, false, __func__);
3296         if (ret <= 0)
3297                 return ret;
3298         xhci = hcd_to_xhci(hcd);
3299         slot_id = udev->slot_id;
3300         virt_dev = xhci->devs[slot_id];
3301         if (!virt_dev) {
3302                 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3303                                 "not exist. Re-allocate the device\n", slot_id);
3304                 ret = xhci_alloc_dev(hcd, udev);
3305                 if (ret == 1)
3306                         return 0;
3307                 else
3308                         return -EINVAL;
3309         }
3310
3311         if (virt_dev->udev != udev) {
3312                 /* If the virt_dev and the udev does not match, this virt_dev
3313                  * may belong to another udev.
3314                  * Re-allocate the device.
3315                  */
3316                 xhci_dbg(xhci, "The device to be reset with slot ID %u does "
3317                                 "not match the udev. Re-allocate the device\n",
3318                                 slot_id);
3319                 ret = xhci_alloc_dev(hcd, udev);
3320                 if (ret == 1)
3321                         return 0;
3322                 else
3323                         return -EINVAL;
3324         }
3325
3326         /* If device is not setup, there is no point in resetting it */
3327         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3328         if (GET_SLOT_STATE(le32_to_cpu(slot_ctx->dev_state)) ==
3329                                                 SLOT_STATE_DISABLED)
3330                 return 0;
3331
3332         xhci_dbg(xhci, "Resetting device with slot ID %u\n", slot_id);
3333         /* Allocate the command structure that holds the struct completion.
3334          * Assume we're in process context, since the normal device reset
3335          * process has to wait for the device anyway.  Storage devices are
3336          * reset as part of error handling, so use GFP_NOIO instead of
3337          * GFP_KERNEL.
3338          */
3339         reset_device_cmd = xhci_alloc_command(xhci, false, true, GFP_NOIO);
3340         if (!reset_device_cmd) {
3341                 xhci_dbg(xhci, "Couldn't allocate command structure.\n");
3342                 return -ENOMEM;
3343         }
3344
3345         /* Attempt to submit the Reset Device command to the command ring */
3346         spin_lock_irqsave(&xhci->lock, flags);
3347         reset_device_cmd->command_trb = xhci->cmd_ring->enqueue;
3348
3349         /* Enqueue pointer can be left pointing to the link TRB,
3350          * we must handle that
3351          */
3352         if (TRB_TYPE_LINK_LE32(reset_device_cmd->command_trb->link.control))
3353                 reset_device_cmd->command_trb =
3354                         xhci->cmd_ring->enq_seg->next->trbs;
3355
3356         list_add_tail(&reset_device_cmd->cmd_list, &virt_dev->cmd_list);
3357         ret = xhci_queue_reset_device(xhci, slot_id);
3358         if (ret) {
3359                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3360                 list_del(&reset_device_cmd->cmd_list);
3361                 spin_unlock_irqrestore(&xhci->lock, flags);
3362                 goto command_cleanup;
3363         }
3364         xhci_ring_cmd_db(xhci);
3365         spin_unlock_irqrestore(&xhci->lock, flags);
3366
3367         /* Wait for the Reset Device command to finish */
3368         timeleft = wait_for_completion_interruptible_timeout(
3369                         reset_device_cmd->completion,
3370                         USB_CTRL_SET_TIMEOUT);
3371         if (timeleft <= 0) {
3372                 xhci_warn(xhci, "%s while waiting for reset device command\n",
3373                                 timeleft == 0 ? "Timeout" : "Signal");
3374                 spin_lock_irqsave(&xhci->lock, flags);
3375                 /* The timeout might have raced with the event ring handler, so
3376                  * only delete from the list if the item isn't poisoned.
3377                  */
3378                 if (reset_device_cmd->cmd_list.next != LIST_POISON1)
3379                         list_del(&reset_device_cmd->cmd_list);
3380                 spin_unlock_irqrestore(&xhci->lock, flags);
3381                 ret = -ETIME;
3382                 goto command_cleanup;
3383         }
3384
3385         /* The Reset Device command can't fail, according to the 0.95/0.96 spec,
3386          * unless we tried to reset a slot ID that wasn't enabled,
3387          * or the device wasn't in the addressed or configured state.
3388          */
3389         ret = reset_device_cmd->status;
3390         switch (ret) {
3391         case COMP_EBADSLT: /* 0.95 completion code for bad slot ID */
3392         case COMP_CTX_STATE: /* 0.96 completion code for same thing */
3393                 xhci_info(xhci, "Can't reset device (slot ID %u) in %s state\n",
3394                                 slot_id,
3395                                 xhci_get_slot_state(xhci, virt_dev->out_ctx));
3396                 xhci_info(xhci, "Not freeing device rings.\n");
3397                 /* Don't treat this as an error.  May change my mind later. */
3398                 ret = 0;
3399                 goto command_cleanup;
3400         case COMP_SUCCESS:
3401                 xhci_dbg(xhci, "Successful reset device command.\n");
3402                 break;
3403         default:
3404                 if (xhci_is_vendor_info_code(xhci, ret))
3405                         break;
3406                 xhci_warn(xhci, "Unknown completion code %u for "
3407                                 "reset device command.\n", ret);
3408                 ret = -EINVAL;
3409                 goto command_cleanup;
3410         }
3411
3412         /* Free up host controller endpoint resources */
3413         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3414                 spin_lock_irqsave(&xhci->lock, flags);
3415                 /* Don't delete the default control endpoint resources */
3416                 xhci_free_device_endpoint_resources(xhci, virt_dev, false);
3417                 spin_unlock_irqrestore(&xhci->lock, flags);
3418         }
3419
3420         /* Everything but endpoint 0 is disabled, so free or cache the rings. */
3421         last_freed_endpoint = 1;
3422         for (i = 1; i < 31; ++i) {
3423                 struct xhci_virt_ep *ep = &virt_dev->eps[i];
3424
3425                 if (ep->ep_state & EP_HAS_STREAMS) {
3426                         xhci_free_stream_info(xhci, ep->stream_info);
3427                         ep->stream_info = NULL;
3428                         ep->ep_state &= ~EP_HAS_STREAMS;
3429                 }
3430
3431                 if (ep->ring) {
3432                         xhci_free_or_cache_endpoint_ring(xhci, virt_dev, i);
3433                         last_freed_endpoint = i;
3434                 }
3435                 if (!list_empty(&virt_dev->eps[i].bw_endpoint_list))
3436                         xhci_drop_ep_from_interval_table(xhci,
3437                                         &virt_dev->eps[i].bw_info,
3438                                         virt_dev->bw_table,
3439                                         udev,
3440                                         &virt_dev->eps[i],
3441                                         virt_dev->tt_info);
3442                 xhci_clear_endpoint_bw_info(&virt_dev->eps[i].bw_info);
3443         }
3444         /* If necessary, update the number of active TTs on this root port */
3445         xhci_update_tt_active_eps(xhci, virt_dev, old_active_eps);
3446
3447         xhci_dbg(xhci, "Output context after successful reset device cmd:\n");
3448         xhci_dbg_ctx(xhci, virt_dev->out_ctx, last_freed_endpoint);
3449         ret = 0;
3450
3451 command_cleanup:
3452         xhci_free_command(xhci, reset_device_cmd);
3453         return ret;
3454 }
3455
3456 /*
3457  * At this point, the struct usb_device is about to go away, the device has
3458  * disconnected, and all traffic has been stopped and the endpoints have been
3459  * disabled.  Free any HC data structures associated with that device.
3460  */
3461 void xhci_free_dev(struct usb_hcd *hcd, struct usb_device *udev)
3462 {
3463         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3464         struct xhci_virt_device *virt_dev;
3465         unsigned long flags;
3466         u32 state;
3467         int i, ret;
3468
3469         ret = xhci_check_args(hcd, udev, NULL, 0, true, __func__);
3470         /* If the host is halted due to driver unload, we still need to free the
3471          * device.
3472          */
3473         if (ret <= 0 && ret != -ENODEV)
3474                 return;
3475
3476         virt_dev = xhci->devs[udev->slot_id];
3477
3478         /* Stop any wayward timer functions (which may grab the lock) */
3479         for (i = 0; i < 31; ++i) {
3480                 virt_dev->eps[i].ep_state &= ~EP_HALT_PENDING;
3481                 del_timer_sync(&virt_dev->eps[i].stop_cmd_timer);
3482         }
3483
3484         if (udev->usb2_hw_lpm_enabled) {
3485                 xhci_set_usb2_hardware_lpm(hcd, udev, 0);
3486                 udev->usb2_hw_lpm_enabled = 0;
3487         }
3488
3489         spin_lock_irqsave(&xhci->lock, flags);
3490         /* Don't disable the slot if the host controller is dead. */
3491         state = xhci_readl(xhci, &xhci->op_regs->status);
3492         if (state == 0xffffffff || (xhci->xhc_state & XHCI_STATE_DYING) ||
3493                         (xhci->xhc_state & XHCI_STATE_HALTED)) {
3494                 xhci_free_virt_device(xhci, udev->slot_id);
3495                 spin_unlock_irqrestore(&xhci->lock, flags);
3496                 return;
3497         }
3498
3499         if (xhci_queue_slot_control(xhci, TRB_DISABLE_SLOT, udev->slot_id)) {
3500                 spin_unlock_irqrestore(&xhci->lock, flags);
3501                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3502                 return;
3503         }
3504         xhci_ring_cmd_db(xhci);
3505         spin_unlock_irqrestore(&xhci->lock, flags);
3506         /*
3507          * Event command completion handler will free any data structures
3508          * associated with the slot.  XXX Can free sleep?
3509          */
3510 }
3511
3512 /*
3513  * Checks if we have enough host controller resources for the default control
3514  * endpoint.
3515  *
3516  * Must be called with xhci->lock held.
3517  */
3518 static int xhci_reserve_host_control_ep_resources(struct xhci_hcd *xhci)
3519 {
3520         if (xhci->num_active_eps + 1 > xhci->limit_active_eps) {
3521                 xhci_dbg(xhci, "Not enough ep ctxs: "
3522                                 "%u active, need to add 1, limit is %u.\n",
3523                                 xhci->num_active_eps, xhci->limit_active_eps);
3524                 return -ENOMEM;
3525         }
3526         xhci->num_active_eps += 1;
3527         xhci_dbg(xhci, "Adding 1 ep ctx, %u now active.\n",
3528                         xhci->num_active_eps);
3529         return 0;
3530 }
3531
3532
3533 /*
3534  * Returns 0 if the xHC ran out of device slots, the Enable Slot command
3535  * timed out, or allocating memory failed.  Returns 1 on success.
3536  */
3537 int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev)
3538 {
3539         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3540         unsigned long flags;
3541         int timeleft;
3542         int ret;
3543         union xhci_trb *cmd_trb;
3544
3545         spin_lock_irqsave(&xhci->lock, flags);
3546         cmd_trb = xhci->cmd_ring->dequeue;
3547         ret = xhci_queue_slot_control(xhci, TRB_ENABLE_SLOT, 0);
3548         if (ret) {
3549                 spin_unlock_irqrestore(&xhci->lock, flags);
3550                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3551                 return 0;
3552         }
3553         xhci_ring_cmd_db(xhci);
3554         spin_unlock_irqrestore(&xhci->lock, flags);
3555
3556         /* XXX: how much time for xHC slot assignment? */
3557         timeleft = wait_for_completion_interruptible_timeout(&xhci->addr_dev,
3558                         XHCI_CMD_DEFAULT_TIMEOUT);
3559         if (timeleft <= 0) {
3560                 xhci_warn(xhci, "%s while waiting for a slot\n",
3561                                 timeleft == 0 ? "Timeout" : "Signal");
3562                 /* cancel the enable slot request */
3563                 return xhci_cancel_cmd(xhci, NULL, cmd_trb);
3564         }
3565
3566         if (!xhci->slot_id) {
3567                 xhci_err(xhci, "Error while assigning device slot ID\n");
3568                 return 0;
3569         }
3570
3571         if ((xhci->quirks & XHCI_EP_LIMIT_QUIRK)) {
3572                 spin_lock_irqsave(&xhci->lock, flags);
3573                 ret = xhci_reserve_host_control_ep_resources(xhci);
3574                 if (ret) {
3575                         spin_unlock_irqrestore(&xhci->lock, flags);
3576                         xhci_warn(xhci, "Not enough host resources, "
3577                                         "active endpoint contexts = %u\n",
3578                                         xhci->num_active_eps);
3579                         goto disable_slot;
3580                 }
3581                 spin_unlock_irqrestore(&xhci->lock, flags);
3582         }
3583         /* Use GFP_NOIO, since this function can be called from
3584          * xhci_discover_or_reset_device(), which may be called as part of
3585          * mass storage driver error handling.
3586          */
3587         if (!xhci_alloc_virt_device(xhci, xhci->slot_id, udev, GFP_NOIO)) {
3588                 xhci_warn(xhci, "Could not allocate xHCI USB device data structures\n");
3589                 goto disable_slot;
3590         }
3591         udev->slot_id = xhci->slot_id;
3592         /* Is this a LS or FS device under a HS hub? */
3593         /* Hub or peripherial? */
3594         return 1;
3595
3596 disable_slot:
3597         /* Disable slot, if we can do it without mem alloc */
3598         spin_lock_irqsave(&xhci->lock, flags);
3599         if (!xhci_queue_slot_control(xhci, TRB_DISABLE_SLOT, udev->slot_id))
3600                 xhci_ring_cmd_db(xhci);
3601         spin_unlock_irqrestore(&xhci->lock, flags);
3602         return 0;
3603 }
3604
3605 /*
3606  * Issue an Address Device command (which will issue a SetAddress request to
3607  * the device).
3608  * We should be protected by the usb_address0_mutex in khubd's hub_port_init, so
3609  * we should only issue and wait on one address command at the same time.
3610  *
3611  * We add one to the device address issued by the hardware because the USB core
3612  * uses address 1 for the root hubs (even though they're not really devices).
3613  */
3614 int xhci_address_device(struct usb_hcd *hcd, struct usb_device *udev)
3615 {
3616         unsigned long flags;
3617         int timeleft;
3618         struct xhci_virt_device *virt_dev;
3619         int ret = 0;
3620         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3621         struct xhci_slot_ctx *slot_ctx;
3622         struct xhci_input_control_ctx *ctrl_ctx;
3623         u64 temp_64;
3624         union xhci_trb *cmd_trb;
3625
3626         if (!udev->slot_id) {
3627                 xhci_dbg(xhci, "Bad Slot ID %d\n", udev->slot_id);
3628                 return -EINVAL;
3629         }
3630
3631         virt_dev = xhci->devs[udev->slot_id];
3632
3633         if (WARN_ON(!virt_dev)) {
3634                 /*
3635                  * In plug/unplug torture test with an NEC controller,
3636                  * a zero-dereference was observed once due to virt_dev = 0.
3637                  * Print useful debug rather than crash if it is observed again!
3638                  */
3639                 xhci_warn(xhci, "Virt dev invalid for slot_id 0x%x!\n",
3640                         udev->slot_id);
3641                 return -EINVAL;
3642         }
3643
3644         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->in_ctx);
3645         /*
3646          * If this is the first Set Address since device plug-in or
3647          * virt_device realloaction after a resume with an xHCI power loss,
3648          * then set up the slot context.
3649          */
3650         if (!slot_ctx->dev_info)
3651                 xhci_setup_addressable_virt_dev(xhci, udev);
3652         /* Otherwise, update the control endpoint ring enqueue pointer. */
3653         else
3654                 xhci_copy_ep0_dequeue_into_input_ctx(xhci, udev);
3655         ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx);
3656         ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
3657         ctrl_ctx->drop_flags = 0;
3658
3659         xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
3660         xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
3661
3662         spin_lock_irqsave(&xhci->lock, flags);
3663         cmd_trb = xhci->cmd_ring->dequeue;
3664         ret = xhci_queue_address_device(xhci, virt_dev->in_ctx->dma,
3665                                         udev->slot_id);
3666         if (ret) {
3667                 spin_unlock_irqrestore(&xhci->lock, flags);
3668                 xhci_dbg(xhci, "FIXME: allocate a command ring segment\n");
3669                 return ret;
3670         }
3671         xhci_ring_cmd_db(xhci);
3672         spin_unlock_irqrestore(&xhci->lock, flags);
3673
3674         /* ctrl tx can take up to 5 sec; XXX: need more time for xHC? */
3675         timeleft = wait_for_completion_interruptible_timeout(&xhci->addr_dev,
3676                         XHCI_CMD_DEFAULT_TIMEOUT);
3677         /* FIXME: From section 4.3.4: "Software shall be responsible for timing
3678          * the SetAddress() "recovery interval" required by USB and aborting the
3679          * command on a timeout.
3680          */
3681         if (timeleft <= 0) {
3682                 xhci_warn(xhci, "%s while waiting for address device command\n",
3683                                 timeleft == 0 ? "Timeout" : "Signal");
3684                 /* cancel the address device command */
3685                 ret = xhci_cancel_cmd(xhci, NULL, cmd_trb);
3686                 if (ret < 0)
3687                         return ret;
3688                 return -ETIME;
3689         }
3690
3691         switch (virt_dev->cmd_status) {
3692         case COMP_CTX_STATE:
3693         case COMP_EBADSLT:
3694                 xhci_err(xhci, "Setup ERROR: address device command for slot %d.\n",
3695                                 udev->slot_id);
3696                 ret = -EINVAL;
3697                 break;
3698         case COMP_TX_ERR:
3699                 dev_warn(&udev->dev, "Device not responding to set address.\n");
3700                 ret = -EPROTO;
3701                 break;
3702         case COMP_DEV_ERR:
3703                 dev_warn(&udev->dev, "ERROR: Incompatible device for address "
3704                                 "device command.\n");
3705                 ret = -ENODEV;
3706                 break;
3707         case COMP_SUCCESS:
3708                 xhci_dbg(xhci, "Successful Address Device command\n");
3709                 break;
3710         default:
3711                 xhci_err(xhci, "ERROR: unexpected command completion "
3712                                 "code 0x%x.\n", virt_dev->cmd_status);
3713                 xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
3714                 xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
3715                 ret = -EINVAL;
3716                 break;
3717         }
3718         if (ret) {
3719                 return ret;
3720         }
3721         temp_64 = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
3722         xhci_dbg(xhci, "Op regs DCBAA ptr = %#016llx\n", temp_64);
3723         xhci_dbg(xhci, "Slot ID %d dcbaa entry @%p = %#016llx\n",
3724                  udev->slot_id,
3725                  &xhci->dcbaa->dev_context_ptrs[udev->slot_id],
3726                  (unsigned long long)
3727                  le64_to_cpu(xhci->dcbaa->dev_context_ptrs[udev->slot_id]));
3728         xhci_dbg(xhci, "Output Context DMA address = %#08llx\n",
3729                         (unsigned long long)virt_dev->out_ctx->dma);
3730         xhci_dbg(xhci, "Slot ID %d Input Context:\n", udev->slot_id);
3731         xhci_dbg_ctx(xhci, virt_dev->in_ctx, 2);
3732         xhci_dbg(xhci, "Slot ID %d Output Context:\n", udev->slot_id);
3733         xhci_dbg_ctx(xhci, virt_dev->out_ctx, 2);
3734         /*
3735          * USB core uses address 1 for the roothubs, so we add one to the
3736          * address given back to us by the HC.
3737          */
3738         slot_ctx = xhci_get_slot_ctx(xhci, virt_dev->out_ctx);
3739         /* Use kernel assigned address for devices; store xHC assigned
3740          * address locally. */
3741         virt_dev->address = (le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK)
3742                 + 1;
3743         /* Zero the input context control for later use */
3744         ctrl_ctx->add_flags = 0;
3745         ctrl_ctx->drop_flags = 0;
3746
3747         xhci_dbg(xhci, "Internal device address = %d\n", virt_dev->address);
3748
3749         return 0;
3750 }
3751
3752 #ifdef CONFIG_USB_SUSPEND
3753
3754 /* BESL to HIRD Encoding array for USB2 LPM */
3755 static int xhci_besl_encoding[16] = {125, 150, 200, 300, 400, 500, 1000, 2000,
3756         3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000};
3757
3758 /* Calculate HIRD/BESL for USB2 PORTPMSC*/
3759 static int xhci_calculate_hird_besl(int u2del, bool use_besl)
3760 {
3761         int hird;
3762
3763         if (use_besl) {
3764                 for (hird = 0; hird < 16; hird++) {
3765                         if (xhci_besl_encoding[hird] >= u2del)
3766                                 break;
3767                 }
3768         } else {
3769                 if (u2del <= 50)
3770                         hird = 0;
3771                 else
3772                         hird = (u2del - 51) / 75 + 1;
3773
3774                 if (hird > 15)
3775                         hird = 15;
3776         }
3777
3778         return hird;
3779 }
3780
3781 static int xhci_usb2_software_lpm_test(struct usb_hcd *hcd,
3782                                         struct usb_device *udev)
3783 {
3784         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3785         struct dev_info *dev_info;
3786         __le32 __iomem  **port_array;
3787         __le32 __iomem  *addr, *pm_addr;
3788         u32             temp, dev_id;
3789         unsigned int    port_num;
3790         unsigned long   flags;
3791         int             u2del, hird;
3792         int             ret;
3793
3794         if (hcd->speed == HCD_USB3 || !xhci->sw_lpm_support ||
3795                         !udev->lpm_capable)
3796                 return -EINVAL;
3797
3798         /* we only support lpm for non-hub device connected to root hub yet */
3799         if (!udev->parent || udev->parent->parent ||
3800                         udev->descriptor.bDeviceClass == USB_CLASS_HUB)
3801                 return -EINVAL;
3802
3803         spin_lock_irqsave(&xhci->lock, flags);
3804
3805         /* Look for devices in lpm_failed_devs list */
3806         dev_id = le16_to_cpu(udev->descriptor.idVendor) << 16 |
3807                         le16_to_cpu(udev->descriptor.idProduct);
3808         list_for_each_entry(dev_info, &xhci->lpm_failed_devs, list) {
3809                 if (dev_info->dev_id == dev_id) {
3810                         ret = -EINVAL;
3811                         goto finish;
3812                 }
3813         }
3814
3815         port_array = xhci->usb2_ports;
3816         port_num = udev->portnum - 1;
3817
3818         if (port_num > HCS_MAX_PORTS(xhci->hcs_params1)) {
3819                 xhci_dbg(xhci, "invalid port number %d\n", udev->portnum);
3820                 ret = -EINVAL;
3821                 goto finish;
3822         }
3823
3824         /*
3825          * Test USB 2.0 software LPM.
3826          * FIXME: some xHCI 1.0 hosts may implement a new register to set up
3827          * hardware-controlled USB 2.0 LPM. See section 5.4.11 and 4.23.5.1.1.1
3828          * in the June 2011 errata release.
3829          */
3830         xhci_dbg(xhci, "test port %d software LPM\n", port_num);
3831         /*
3832          * Set L1 Device Slot and HIRD/BESL.
3833          * Check device's USB 2.0 extension descriptor to determine whether
3834          * HIRD or BESL shoule be used. See USB2.0 LPM errata.
3835          */
3836         pm_addr = port_array[port_num] + 1;
3837         u2del = HCS_U2_LATENCY(xhci->hcs_params3);
3838         if (le32_to_cpu(udev->bos->ext_cap->bmAttributes) & (1 << 2))
3839                 hird = xhci_calculate_hird_besl(u2del, 1);
3840         else
3841                 hird = xhci_calculate_hird_besl(u2del, 0);
3842
3843         temp = PORT_L1DS(udev->slot_id) | PORT_HIRD(hird);
3844         xhci_writel(xhci, temp, pm_addr);
3845
3846         /* Set port link state to U2(L1) */
3847         addr = port_array[port_num];
3848         xhci_set_link_state(xhci, port_array, port_num, XDEV_U2);
3849
3850         /* wait for ACK */
3851         spin_unlock_irqrestore(&xhci->lock, flags);
3852         msleep(10);
3853         spin_lock_irqsave(&xhci->lock, flags);
3854
3855         /* Check L1 Status */
3856         ret = handshake(xhci, pm_addr, PORT_L1S_MASK, PORT_L1S_SUCCESS, 125);
3857         if (ret != -ETIMEDOUT) {
3858                 /* enter L1 successfully */
3859                 temp = xhci_readl(xhci, addr);
3860                 xhci_dbg(xhci, "port %d entered L1 state, port status 0x%x\n",
3861                                 port_num, temp);
3862                 ret = 0;
3863         } else {
3864                 temp = xhci_readl(xhci, pm_addr);
3865                 xhci_dbg(xhci, "port %d software lpm failed, L1 status %d\n",
3866                                 port_num, temp & PORT_L1S_MASK);
3867                 ret = -EINVAL;
3868         }
3869
3870         /* Resume the port */
3871         xhci_set_link_state(xhci, port_array, port_num, XDEV_U0);
3872
3873         spin_unlock_irqrestore(&xhci->lock, flags);
3874         msleep(10);
3875         spin_lock_irqsave(&xhci->lock, flags);
3876
3877         /* Clear PLC */
3878         xhci_test_and_clear_bit(xhci, port_array, port_num, PORT_PLC);
3879
3880         /* Check PORTSC to make sure the device is in the right state */
3881         if (!ret) {
3882                 temp = xhci_readl(xhci, addr);
3883                 xhci_dbg(xhci, "resumed port %d status 0x%x\n", port_num, temp);
3884                 if (!(temp & PORT_CONNECT) || !(temp & PORT_PE) ||
3885                                 (temp & PORT_PLS_MASK) != XDEV_U0) {
3886                         xhci_dbg(xhci, "port L1 resume fail\n");
3887                         ret = -EINVAL;
3888                 }
3889         }
3890
3891         if (ret) {
3892                 /* Insert dev to lpm_failed_devs list */
3893                 xhci_warn(xhci, "device LPM test failed, may disconnect and "
3894                                 "re-enumerate\n");
3895                 dev_info = kzalloc(sizeof(struct dev_info), GFP_ATOMIC);
3896                 if (!dev_info) {
3897                         ret = -ENOMEM;
3898                         goto finish;
3899                 }
3900                 dev_info->dev_id = dev_id;
3901                 INIT_LIST_HEAD(&dev_info->list);
3902                 list_add(&dev_info->list, &xhci->lpm_failed_devs);
3903         } else {
3904                 xhci_ring_device(xhci, udev->slot_id);
3905         }
3906
3907 finish:
3908         spin_unlock_irqrestore(&xhci->lock, flags);
3909         return ret;
3910 }
3911
3912 int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
3913                         struct usb_device *udev, int enable)
3914 {
3915         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3916         __le32 __iomem  **port_array;
3917         __le32 __iomem  *pm_addr;
3918         u32             temp;
3919         unsigned int    port_num;
3920         unsigned long   flags;
3921         int             u2del, hird;
3922
3923         if (hcd->speed == HCD_USB3 || !xhci->hw_lpm_support ||
3924                         !udev->lpm_capable)
3925                 return -EPERM;
3926
3927         if (!udev->parent || udev->parent->parent ||
3928                         udev->descriptor.bDeviceClass == USB_CLASS_HUB)
3929                 return -EPERM;
3930
3931         if (udev->usb2_hw_lpm_capable != 1)
3932                 return -EPERM;
3933
3934         spin_lock_irqsave(&xhci->lock, flags);
3935
3936         port_array = xhci->usb2_ports;
3937         port_num = udev->portnum - 1;
3938         pm_addr = port_array[port_num] + 1;
3939         temp = xhci_readl(xhci, pm_addr);
3940
3941         xhci_dbg(xhci, "%s port %d USB2 hardware LPM\n",
3942                         enable ? "enable" : "disable", port_num);
3943
3944         u2del = HCS_U2_LATENCY(xhci->hcs_params3);
3945         if (le32_to_cpu(udev->bos->ext_cap->bmAttributes) & (1 << 2))
3946                 hird = xhci_calculate_hird_besl(u2del, 1);
3947         else
3948                 hird = xhci_calculate_hird_besl(u2del, 0);
3949
3950         if (enable) {
3951                 temp &= ~PORT_HIRD_MASK;
3952                 temp |= PORT_HIRD(hird) | PORT_RWE;
3953                 xhci_writel(xhci, temp, pm_addr);
3954                 temp = xhci_readl(xhci, pm_addr);
3955                 temp |= PORT_HLE;
3956                 xhci_writel(xhci, temp, pm_addr);
3957         } else {
3958                 temp &= ~(PORT_HLE | PORT_RWE | PORT_HIRD_MASK);
3959                 xhci_writel(xhci, temp, pm_addr);
3960         }
3961
3962         spin_unlock_irqrestore(&xhci->lock, flags);
3963         return 0;
3964 }
3965
3966 int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
3967 {
3968         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
3969         int             ret;
3970
3971         ret = xhci_usb2_software_lpm_test(hcd, udev);
3972         if (!ret) {
3973                 xhci_dbg(xhci, "software LPM test succeed\n");
3974                 if (xhci->hw_lpm_support == 1) {
3975                         udev->usb2_hw_lpm_capable = 1;
3976                         ret = xhci_set_usb2_hardware_lpm(hcd, udev, 1);
3977                         if (!ret)
3978                                 udev->usb2_hw_lpm_enabled = 1;
3979                 }
3980         }
3981
3982         return 0;
3983 }
3984
3985 #else
3986
3987 int xhci_set_usb2_hardware_lpm(struct usb_hcd *hcd,
3988                                 struct usb_device *udev, int enable)
3989 {
3990         return 0;
3991 }
3992
3993 int xhci_update_device(struct usb_hcd *hcd, struct usb_device *udev)
3994 {
3995         return 0;
3996 }
3997
3998 #endif /* CONFIG_USB_SUSPEND */
3999
4000 /* Once a hub descriptor is fetched for a device, we need to update the xHC's
4001  * internal data structures for the device.
4002  */
4003 int xhci_update_hub_device(struct usb_hcd *hcd, struct usb_device *hdev,
4004                         struct usb_tt *tt, gfp_t mem_flags)
4005 {
4006         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4007         struct xhci_virt_device *vdev;
4008         struct xhci_command *config_cmd;
4009         struct xhci_input_control_ctx *ctrl_ctx;
4010         struct xhci_slot_ctx *slot_ctx;
4011         unsigned long flags;
4012         unsigned think_time;
4013         int ret;
4014
4015         /* Ignore root hubs */
4016         if (!hdev->parent)
4017                 return 0;
4018
4019         vdev = xhci->devs[hdev->slot_id];
4020         if (!vdev) {
4021                 xhci_warn(xhci, "Cannot update hub desc for unknown device.\n");
4022                 return -EINVAL;
4023         }
4024         config_cmd = xhci_alloc_command(xhci, true, true, mem_flags);
4025         if (!config_cmd) {
4026                 xhci_dbg(xhci, "Could not allocate xHCI command structure.\n");
4027                 return -ENOMEM;
4028         }
4029
4030         spin_lock_irqsave(&xhci->lock, flags);
4031         if (hdev->speed == USB_SPEED_HIGH &&
4032                         xhci_alloc_tt_info(xhci, vdev, hdev, tt, GFP_ATOMIC)) {
4033                 xhci_dbg(xhci, "Could not allocate xHCI TT structure.\n");
4034                 xhci_free_command(xhci, config_cmd);
4035                 spin_unlock_irqrestore(&xhci->lock, flags);
4036                 return -ENOMEM;
4037         }
4038
4039         xhci_slot_copy(xhci, config_cmd->in_ctx, vdev->out_ctx);
4040         ctrl_ctx = xhci_get_input_control_ctx(xhci, config_cmd->in_ctx);
4041         ctrl_ctx->add_flags |= cpu_to_le32(SLOT_FLAG);
4042         slot_ctx = xhci_get_slot_ctx(xhci, config_cmd->in_ctx);
4043         slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
4044         if (tt->multi)
4045                 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
4046         if (xhci->hci_version > 0x95) {
4047                 xhci_dbg(xhci, "xHCI version %x needs hub "
4048                                 "TT think time and number of ports\n",
4049                                 (unsigned int) xhci->hci_version);
4050                 slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(hdev->maxchild));
4051                 /* Set TT think time - convert from ns to FS bit times.
4052                  * 0 = 8 FS bit times, 1 = 16 FS bit times,
4053                  * 2 = 24 FS bit times, 3 = 32 FS bit times.
4054                  *
4055                  * xHCI 1.0: this field shall be 0 if the device is not a
4056                  * High-spped hub.
4057                  */
4058                 think_time = tt->think_time;
4059                 if (think_time != 0)
4060                         think_time = (think_time / 666) - 1;
4061                 if (xhci->hci_version < 0x100 || hdev->speed == USB_SPEED_HIGH)
4062                         slot_ctx->tt_info |=
4063                                 cpu_to_le32(TT_THINK_TIME(think_time));
4064         } else {
4065                 xhci_dbg(xhci, "xHCI version %x doesn't need hub "
4066                                 "TT think time or number of ports\n",
4067                                 (unsigned int) xhci->hci_version);
4068         }
4069         slot_ctx->dev_state = 0;
4070         spin_unlock_irqrestore(&xhci->lock, flags);
4071
4072         xhci_dbg(xhci, "Set up %s for hub device.\n",
4073                         (xhci->hci_version > 0x95) ?
4074                         "configure endpoint" : "evaluate context");
4075         xhci_dbg(xhci, "Slot %u Input Context:\n", hdev->slot_id);
4076         xhci_dbg_ctx(xhci, config_cmd->in_ctx, 0);
4077
4078         /* Issue and wait for the configure endpoint or
4079          * evaluate context command.
4080          */
4081         if (xhci->hci_version > 0x95)
4082                 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
4083                                 false, false);
4084         else
4085                 ret = xhci_configure_endpoint(xhci, hdev, config_cmd,
4086                                 true, false);
4087
4088         xhci_dbg(xhci, "Slot %u Output Context:\n", hdev->slot_id);
4089         xhci_dbg_ctx(xhci, vdev->out_ctx, 0);
4090
4091         xhci_free_command(xhci, config_cmd);
4092         return ret;
4093 }
4094
4095 int xhci_get_frame(struct usb_hcd *hcd)
4096 {
4097         struct xhci_hcd *xhci = hcd_to_xhci(hcd);
4098         /* EHCI mods by the periodic size.  Why? */
4099         return xhci_readl(xhci, &xhci->run_regs->microframe_index) >> 3;
4100 }
4101
4102 int xhci_gen_setup(struct usb_hcd *hcd, xhci_get_quirks_t get_quirks)
4103 {
4104         struct xhci_hcd         *xhci;
4105         struct device           *dev = hcd->self.controller;
4106         int                     retval;
4107         u32                     temp;
4108
4109         hcd->self.sg_tablesize = TRBS_PER_SEGMENT - 2;
4110
4111         if (usb_hcd_is_primary_hcd(hcd)) {
4112                 xhci = kzalloc(sizeof(struct xhci_hcd), GFP_KERNEL);
4113                 if (!xhci)
4114                         return -ENOMEM;
4115                 *((struct xhci_hcd **) hcd->hcd_priv) = xhci;
4116                 xhci->main_hcd = hcd;
4117                 /* Mark the first roothub as being USB 2.0.
4118                  * The xHCI driver will register the USB 3.0 roothub.
4119                  */
4120                 hcd->speed = HCD_USB2;
4121                 hcd->self.root_hub->speed = USB_SPEED_HIGH;
4122                 /*
4123                  * USB 2.0 roothub under xHCI has an integrated TT,
4124                  * (rate matching hub) as opposed to having an OHCI/UHCI
4125                  * companion controller.
4126                  */
4127                 hcd->has_tt = 1;
4128         } else {
4129                 /* xHCI private pointer was set in xhci_pci_probe for the second
4130                  * registered roothub.
4131                  */
4132                 xhci = hcd_to_xhci(hcd);
4133                 temp = xhci_readl(xhci, &xhci->cap_regs->hcc_params);
4134                 if (HCC_64BIT_ADDR(temp)) {
4135                         xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
4136                         dma_set_mask(hcd->self.controller, DMA_BIT_MASK(64));
4137                 } else {
4138                         dma_set_mask(hcd->self.controller, DMA_BIT_MASK(32));
4139                 }
4140                 return 0;
4141         }
4142
4143         xhci->cap_regs = hcd->regs;
4144         xhci->op_regs = hcd->regs +
4145                 HC_LENGTH(xhci_readl(xhci, &xhci->cap_regs->hc_capbase));
4146         xhci->run_regs = hcd->regs +
4147                 (xhci_readl(xhci, &xhci->cap_regs->run_regs_off) & RTSOFF_MASK);
4148         /* Cache read-only capability registers */
4149         xhci->hcs_params1 = xhci_readl(xhci, &xhci->cap_regs->hcs_params1);
4150         xhci->hcs_params2 = xhci_readl(xhci, &xhci->cap_regs->hcs_params2);
4151         xhci->hcs_params3 = xhci_readl(xhci, &xhci->cap_regs->hcs_params3);
4152         xhci->hcc_params = xhci_readl(xhci, &xhci->cap_regs->hc_capbase);
4153         xhci->hci_version = HC_VERSION(xhci->hcc_params);
4154         xhci->hcc_params = xhci_readl(xhci, &xhci->cap_regs->hcc_params);
4155         xhci_print_registers(xhci);
4156
4157         get_quirks(dev, xhci);
4158
4159         /* Make sure the HC is halted. */
4160         retval = xhci_halt(xhci);
4161         if (retval)
4162                 goto error;
4163
4164         xhci_dbg(xhci, "Resetting HCD\n");
4165         /* Reset the internal HC memory state and registers. */
4166         retval = xhci_reset(xhci);
4167         if (retval)
4168                 goto error;
4169         xhci_dbg(xhci, "Reset complete\n");
4170
4171         temp = xhci_readl(xhci, &xhci->cap_regs->hcc_params);
4172         if (HCC_64BIT_ADDR(temp)) {
4173                 xhci_dbg(xhci, "Enabling 64-bit DMA addresses.\n");
4174                 dma_set_mask(hcd->self.controller, DMA_BIT_MASK(64));
4175         } else {
4176                 dma_set_mask(hcd->self.controller, DMA_BIT_MASK(32));
4177         }
4178
4179         xhci_dbg(xhci, "Calling HCD init\n");
4180         /* Initialize HCD and host controller data structures. */
4181         retval = xhci_init(hcd);
4182         if (retval)
4183                 goto error;
4184         xhci_dbg(xhci, "Called HCD init\n");
4185         return 0;
4186 error:
4187         kfree(xhci);
4188         return retval;
4189 }
4190
4191 MODULE_DESCRIPTION(DRIVER_DESC);
4192 MODULE_AUTHOR(DRIVER_AUTHOR);
4193 MODULE_LICENSE("GPL");
4194
4195 static int __init xhci_hcd_init(void)
4196 {
4197         int retval;
4198
4199         retval = xhci_register_pci();
4200         if (retval < 0) {
4201                 printk(KERN_DEBUG "Problem registering PCI driver.");
4202                 return retval;
4203         }
4204         /*
4205          * Check the compiler generated sizes of structures that must be laid
4206          * out in specific ways for hardware access.
4207          */
4208         BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
4209         BUILD_BUG_ON(sizeof(struct xhci_slot_ctx) != 8*32/8);
4210         BUILD_BUG_ON(sizeof(struct xhci_ep_ctx) != 8*32/8);
4211         /* xhci_device_control has eight fields, and also
4212          * embeds one xhci_slot_ctx and 31 xhci_ep_ctx
4213          */
4214         BUILD_BUG_ON(sizeof(struct xhci_stream_ctx) != 4*32/8);
4215         BUILD_BUG_ON(sizeof(union xhci_trb) != 4*32/8);
4216         BUILD_BUG_ON(sizeof(struct xhci_erst_entry) != 4*32/8);
4217         BUILD_BUG_ON(sizeof(struct xhci_cap_regs) != 7*32/8);
4218         BUILD_BUG_ON(sizeof(struct xhci_intr_reg) != 8*32/8);
4219         /* xhci_run_regs has eight fields and embeds 128 xhci_intr_regs */
4220         BUILD_BUG_ON(sizeof(struct xhci_run_regs) != (8+8*128)*32/8);
4221         BUILD_BUG_ON(sizeof(struct xhci_doorbell_array) != 256*32/8);
4222         return 0;
4223 }
4224 module_init(xhci_hcd_init);
4225
4226 static void __exit xhci_hcd_cleanup(void)
4227 {
4228         xhci_unregister_pci();
4229 }
4230 module_exit(xhci_hcd_cleanup);