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