Merge to Fedora kernel-2.6.7-1.441
[linux-2.6.git] / drivers / usb / host / ehci-hcd.c
1 /*
2  * Copyright (c) 2000-2004 by David Brownell
3  * 
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the
6  * Free Software Foundation; either version 2 of the License, or (at your
7  * option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <linux/config.h>
20
21 #ifdef CONFIG_USB_DEBUG
22         #define DEBUG
23 #else
24         #undef DEBUG
25 #endif
26
27 #include <linux/module.h>
28 #include <linux/pci.h>
29 #include <linux/dmapool.h>
30 #include <linux/kernel.h>
31 #include <linux/delay.h>
32 #include <linux/ioport.h>
33 #include <linux/sched.h>
34 #include <linux/slab.h>
35 #include <linux/smp_lock.h>
36 #include <linux/errno.h>
37 #include <linux/init.h>
38 #include <linux/timer.h>
39 #include <linux/list.h>
40 #include <linux/interrupt.h>
41 #include <linux/reboot.h>
42 #include <linux/usb.h>
43 #include <linux/moduleparam.h>
44 #include <linux/dma-mapping.h>
45
46 #include "../core/hcd.h"
47
48 #include <asm/byteorder.h>
49 #include <asm/io.h>
50 #include <asm/irq.h>
51 #include <asm/system.h>
52 #include <asm/unaligned.h>
53
54
55 /*-------------------------------------------------------------------------*/
56
57 /*
58  * EHCI hc_driver implementation ... experimental, incomplete.
59  * Based on the final 1.0 register interface specification.
60  *
61  * USB 2.0 shows up in upcoming www.pcmcia.org technology.
62  * First was PCMCIA, like ISA; then CardBus, which is PCI.
63  * Next comes "CardBay", using USB 2.0 signals.
64  *
65  * Contains additional contributions by Brad Hards, Rory Bolt, and others.
66  * Special thanks to Intel and VIA for providing host controllers to
67  * test this driver on, and Cypress (including In-System Design) for
68  * providing early devices for those host controllers to talk to!
69  *
70  * HISTORY:
71  *
72  * 2004-05-10 Root hub and PCI suspend/resume support; remote wakeup. (db)
73  * 2004-02-24 Replace pci_* with generic dma_* API calls (dsaxena@plexity.net)
74  * 2003-12-29 Rewritten high speed iso transfer support (by Michal Sojka,
75  *      <sojkam@centrum.cz>, updates by DB).
76  *
77  * 2002-11-29   Correct handling for hw async_next register.
78  * 2002-08-06   Handling for bulk and interrupt transfers is mostly shared;
79  *      only scheduling is different, no arbitrary limitations.
80  * 2002-07-25   Sanity check PCI reads, mostly for better cardbus support,
81  *      clean up HC run state handshaking.
82  * 2002-05-24   Preliminary FS/LS interrupts, using scheduling shortcuts
83  * 2002-05-11   Clear TT errors for FS/LS ctrl/bulk.  Fill in some other
84  *      missing pieces:  enabling 64bit dma, handoff from BIOS/SMM.
85  * 2002-05-07   Some error path cleanups to report better errors; wmb();
86  *      use non-CVS version id; better iso bandwidth claim.
87  * 2002-04-19   Control/bulk/interrupt submit no longer uses giveback() on
88  *      errors in submit path.  Bugfixes to interrupt scheduling/processing.
89  * 2002-03-05   Initial high-speed ISO support; reduce ITD memory; shift
90  *      more checking to generic hcd framework (db).  Make it work with
91  *      Philips EHCI; reduce PCI traffic; shorten IRQ path (Rory Bolt).
92  * 2002-01-14   Minor cleanup; version synch.
93  * 2002-01-08   Fix roothub handoff of FS/LS to companion controllers.
94  * 2002-01-04   Control/Bulk queuing behaves.
95  *
96  * 2001-12-12   Initial patch version for Linux 2.5.1 kernel.
97  * 2001-June    Works with usb-storage and NEC EHCI on 2.4
98  */
99
100 #define DRIVER_VERSION "2004-May-10"
101 #define DRIVER_AUTHOR "David Brownell"
102 #define DRIVER_DESC "USB 2.0 'Enhanced' Host Controller (EHCI) Driver"
103
104 static const char       hcd_name [] = "ehci_hcd";
105
106
107 #undef EHCI_VERBOSE_DEBUG
108 #undef EHCI_URB_TRACE
109
110 #ifdef DEBUG
111 #define EHCI_STATS
112 #endif
113
114 /* magic numbers that can affect system performance */
115 #define EHCI_TUNE_CERR          3       /* 0-3 qtd retries; 0 == don't stop */
116 #define EHCI_TUNE_RL_HS         4       /* nak throttle; see 4.9 */
117 #define EHCI_TUNE_RL_TT         0
118 #define EHCI_TUNE_MULT_HS       1       /* 1-3 transactions/uframe; 4.10.3 */
119 #define EHCI_TUNE_MULT_TT       1
120 #define EHCI_TUNE_FLS           2       /* (small) 256 frame schedule */
121
122 #define EHCI_IAA_JIFFIES        (HZ/100)        /* arbitrary; ~10 msec */
123 #define EHCI_IO_JIFFIES         (HZ/10)         /* io watchdog > irq_thresh */
124 #define EHCI_ASYNC_JIFFIES      (HZ/20)         /* async idle timeout */
125 #define EHCI_SHRINK_JIFFIES     (HZ/200)        /* async qh unlink delay */
126
127 /* Initial IRQ latency:  lower than default */
128 static int log2_irq_thresh = 0;         // 0 to 6
129 module_param (log2_irq_thresh, int, S_IRUGO);
130 MODULE_PARM_DESC (log2_irq_thresh, "log2 IRQ latency, 1-64 microframes");
131
132 #define INTR_MASK (STS_IAA | STS_FATAL | STS_PCD | STS_ERR | STS_INT)
133
134 /*-------------------------------------------------------------------------*/
135
136 #include "ehci.h"
137 #include "ehci-dbg.c"
138
139 /*-------------------------------------------------------------------------*/
140
141 /*
142  * handshake - spin reading hc until handshake completes or fails
143  * @ptr: address of hc register to be read
144  * @mask: bits to look at in result of read
145  * @done: value of those bits when handshake succeeds
146  * @usec: timeout in microseconds
147  *
148  * Returns negative errno, or zero on success
149  *
150  * Success happens when the "mask" bits have the specified value (hardware
151  * handshake done).  There are two failure modes:  "usec" have passed (major
152  * hardware flakeout), or the register reads as all-ones (hardware removed).
153  *
154  * That last failure should_only happen in cases like physical cardbus eject
155  * before driver shutdown. But it also seems to be caused by bugs in cardbus
156  * bridge shutdown:  shutting down the bridge before the devices using it.
157  */
158 static int handshake (u32 *ptr, u32 mask, u32 done, int usec)
159 {
160         u32     result;
161
162         do {
163                 result = readl (ptr);
164                 if (result == ~(u32)0)          /* card removed */
165                         return -ENODEV;
166                 result &= mask;
167                 if (result == done)
168                         return 0;
169                 udelay (1);
170                 usec--;
171         } while (usec > 0);
172         return -ETIMEDOUT;
173 }
174
175 /*
176  * hc states include: unknown, halted, ready, running
177  * transitional states are messy just now
178  * trying to avoid "running" unless urbs are active
179  * a "ready" hc can be finishing prefetched work
180  */
181
182 /* force HC to halt state from unknown (EHCI spec section 2.3) */
183 static int ehci_halt (struct ehci_hcd *ehci)
184 {
185         u32     temp = readl (&ehci->regs->status);
186
187         if ((temp & STS_HALT) != 0)
188                 return 0;
189
190         temp = readl (&ehci->regs->command);
191         temp &= ~CMD_RUN;
192         writel (temp, &ehci->regs->command);
193         return handshake (&ehci->regs->status, STS_HALT, STS_HALT, 16 * 125);
194 }
195
196 /* reset a non-running (STS_HALT == 1) controller */
197 static int ehci_reset (struct ehci_hcd *ehci)
198 {
199         u32     command = readl (&ehci->regs->command);
200
201         command |= CMD_RESET;
202         dbg_cmd (ehci, "reset", command);
203         writel (command, &ehci->regs->command);
204         ehci->hcd.state = USB_STATE_HALT;
205         ehci->next_statechange = jiffies;
206         return handshake (&ehci->regs->command, CMD_RESET, 0, 250 * 1000);
207 }
208
209 /* idle the controller (from running) */
210 static void ehci_ready (struct ehci_hcd *ehci)
211 {
212         u32     temp;
213
214 #ifdef DEBUG
215         if (!HCD_IS_RUNNING (ehci->hcd.state))
216                 BUG ();
217 #endif
218
219         /* wait for any schedule enables/disables to take effect */
220         temp = 0;
221         if (ehci->async->qh_next.qh)
222                 temp = STS_ASS;
223         if (ehci->next_uframe != -1)
224                 temp |= STS_PSS;
225         if (handshake (&ehci->regs->status, STS_ASS | STS_PSS,
226                                 temp, 16 * 125) != 0) {
227                 ehci->hcd.state = USB_STATE_HALT;
228                 return;
229         }
230
231         /* then disable anything that's still active */
232         temp = readl (&ehci->regs->command);
233         temp &= ~(CMD_ASE | CMD_IAAD | CMD_PSE);
234         writel (temp, &ehci->regs->command);
235
236         /* hardware can take 16 microframes to turn off ... */
237         if (handshake (&ehci->regs->status, STS_ASS | STS_PSS,
238                                 0, 16 * 125) != 0) {
239                 ehci->hcd.state = USB_STATE_HALT;
240                 return;
241         }
242 }
243
244 /*-------------------------------------------------------------------------*/
245
246 static void ehci_work(struct ehci_hcd *ehci, struct pt_regs *regs);
247
248 #include "ehci-hub.c"
249 #include "ehci-mem.c"
250 #include "ehci-q.c"
251 #include "ehci-sched.c"
252
253 /*-------------------------------------------------------------------------*/
254
255 static void ehci_watchdog (unsigned long param)
256 {
257         struct ehci_hcd         *ehci = (struct ehci_hcd *) param;
258         unsigned long           flags;
259
260         spin_lock_irqsave (&ehci->lock, flags);
261
262         /* lost IAA irqs wedge things badly; seen with a vt8235 */
263         if (ehci->reclaim) {
264                 u32             status = readl (&ehci->regs->status);
265
266                 if (status & STS_IAA) {
267                         ehci_vdbg (ehci, "lost IAA\n");
268                         COUNT (ehci->stats.lost_iaa);
269                         writel (STS_IAA, &ehci->regs->status);
270                         ehci->reclaim_ready = 1;
271                 }
272         }
273
274         /* stop async processing after it's idled a bit */
275         if (test_bit (TIMER_ASYNC_OFF, &ehci->actions))
276                 start_unlink_async (ehci, ehci->async);
277
278         /* ehci could run by timer, without IRQs ... */
279         ehci_work (ehci, NULL);
280
281         spin_unlock_irqrestore (&ehci->lock, flags);
282 }
283
284 #ifdef  CONFIG_PCI
285
286 /* EHCI 0.96 (and later) section 5.1 says how to kick BIOS/SMM/...
287  * off the controller (maybe it can boot from highspeed USB disks).
288  */
289 static int bios_handoff (struct ehci_hcd *ehci, int where, u32 cap)
290 {
291         if (cap & (1 << 16)) {
292                 int msec = 500;
293                 struct pci_dev *pdev = to_pci_dev(ehci->hcd.self.controller);
294
295                 /* request handoff to OS */
296                 cap |= 1 << 24;
297                 pci_write_config_dword(pdev, where, cap);
298
299                 /* and wait a while for it to happen */
300                 do {
301                         msleep(10);
302                         msec -= 10;
303                         pci_read_config_dword(pdev, where, &cap);
304                 } while ((cap & (1 << 16)) && msec);
305                 if (cap & (1 << 16)) {
306                         ehci_err (ehci, "BIOS handoff failed (%d, %04x)\n",
307                                 where, cap);
308                         return 1;
309                 } 
310                 ehci_dbg (ehci, "BIOS handoff succeeded\n");
311         }
312         return 0;
313 }
314
315 #endif
316
317 static int
318 ehci_reboot (struct notifier_block *self, unsigned long code, void *null)
319 {
320         struct ehci_hcd         *ehci;
321
322         ehci = container_of (self, struct ehci_hcd, reboot_notifier);
323
324         /* make BIOS/etc use companion controller during reboot */
325         writel (0, &ehci->regs->configured_flag);
326         return 0;
327 }
328
329
330 /* called by khubd or root hub init threads */
331
332 static int ehci_hc_reset (struct usb_hcd *hcd)
333 {
334         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
335         u32                     temp;
336         unsigned                count = 256/4;
337
338         spin_lock_init (&ehci->lock);
339
340         ehci->caps = (struct ehci_caps *) hcd->regs;
341         ehci->regs = (struct ehci_regs *) (hcd->regs + 
342                                 HC_LENGTH (readl (&ehci->caps->hc_capbase)));
343         dbg_hcs_params (ehci, "reset");
344         dbg_hcc_params (ehci, "reset");
345
346 #ifdef  CONFIG_PCI
347         writel(0, &ehci->regs->intr_enable);
348         /* EHCI 0.96 and later may have "extended capabilities" */
349         if (hcd->self.controller->bus == &pci_bus_type)
350                 temp = HCC_EXT_CAPS (readl (&ehci->caps->hcc_params));
351         else
352                 temp = 0;
353         while (temp && count--) {
354                 u32             cap;
355
356                 pci_read_config_dword (to_pci_dev(ehci->hcd.self.controller),
357                                 temp, &cap);
358                 ehci_dbg (ehci, "capability %04x at %02x\n", cap, temp);
359                 switch (cap & 0xff) {
360                 case 1:                 /* BIOS/SMM/... handoff */
361                         if (bios_handoff (ehci, temp, cap) != 0)
362                                 return -EOPNOTSUPP;
363                         break;
364                 case 0x0a:              /* appendix C */
365                         ehci_dbg (ehci, "debug registers, BAR %d offset %d\n",
366                                 (cap >> 29) & 0x07, (cap >> 16) & 0x0fff);
367                         break;
368                 case 0:                 /* illegal reserved capability */
369                         ehci_warn (ehci, "illegal capability!\n");
370                         cap = 0;
371                         /* FALLTHROUGH */
372                 default:                /* unknown */
373                         break;
374                 }
375                 temp = (cap >> 8) & 0xff;
376         }
377         if (!count) {
378                 ehci_err (ehci, "bogus capabilities ... PCI problems!\n");
379                 return -EIO;
380         }
381 #endif
382
383         /* cache this readonly data; minimize PCI reads */
384         ehci->hcs_params = readl (&ehci->caps->hcs_params);
385
386         /* force HC to halt state */
387         return ehci_halt (ehci);
388 }
389
390 static int ehci_start (struct usb_hcd *hcd)
391 {
392         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
393         u32                     temp;
394         struct usb_device       *udev;
395         struct usb_bus          *bus;
396         int                     retval;
397         u32                     hcc_params;
398         u8                      sbrn = 0;
399
400         init_timer (&ehci->watchdog);
401         ehci->watchdog.function = ehci_watchdog;
402         ehci->watchdog.data = (unsigned long) ehci;
403
404         /*
405          * hw default: 1K periodic list heads, one per frame.
406          * periodic_size can shrink by USBCMD update if hcc_params allows.
407          */
408         ehci->periodic_size = DEFAULT_I_TDPS;
409         if ((retval = ehci_mem_init (ehci, GFP_KERNEL)) < 0)
410                 return retval;
411
412         /* controllers may cache some of the periodic schedule ... */
413         hcc_params = readl (&ehci->caps->hcc_params);
414         if (HCC_ISOC_CACHE (hcc_params))        // full frame cache
415                 ehci->i_thresh = 8;
416         else                                    // N microframes cached
417                 ehci->i_thresh = 2 + HCC_ISOC_THRES (hcc_params);
418
419         ehci->reclaim = 0;
420         ehci->next_uframe = -1;
421
422         /* controller state:  unknown --> reset */
423
424         /* EHCI spec section 4.1 */
425         if ((retval = ehci_reset (ehci)) != 0) {
426                 ehci_mem_cleanup (ehci);
427                 return retval;
428         }
429         writel (INTR_MASK, &ehci->regs->intr_enable);
430         writel (ehci->periodic_dma, &ehci->regs->frame_list);
431
432 #ifdef  CONFIG_PCI
433         if (hcd->self.controller->bus == &pci_bus_type) {
434                 struct pci_dev          *pdev;
435                 u16                     port_wake;
436
437                 pdev = to_pci_dev(hcd->self.controller);
438
439                 /* Serial Bus Release Number is at PCI 0x60 offset */
440                 pci_read_config_byte(pdev, 0x60, &sbrn);
441
442                 /* port wake capability, reported by boot firmware */
443                 pci_read_config_word(pdev, 0x62, &port_wake);
444                 hcd->can_wakeup = (port_wake & 1) != 0;
445
446                 /* help hc dma work well with cachelines */
447                 pci_set_mwi (pdev);
448
449                 /* chip-specific init */
450                 switch (pdev->vendor) {
451                 case PCI_VENDOR_ID_ARC:
452                         if (pdev->device == PCI_DEVICE_ID_ARC_EHCI)
453                                 ehci->is_arc_rh_tt = 1;
454                         break;
455                 }
456
457         }
458 #endif
459
460         /*
461          * dedicate a qh for the async ring head, since we couldn't unlink
462          * a 'real' qh without stopping the async schedule [4.8].  use it
463          * as the 'reclamation list head' too.
464          * its dummy is used in hw_alt_next of many tds, to prevent the qh
465          * from automatically advancing to the next td after short reads.
466          */
467         ehci->async->qh_next.qh = 0;
468         ehci->async->hw_next = QH_NEXT (ehci->async->qh_dma);
469         ehci->async->hw_info1 = cpu_to_le32 (QH_HEAD);
470         ehci->async->hw_token = cpu_to_le32 (QTD_STS_HALT);
471         ehci->async->hw_qtd_next = EHCI_LIST_END;
472         ehci->async->qh_state = QH_STATE_LINKED;
473         ehci->async->hw_alt_next = QTD_NEXT (ehci->async->dummy->qtd_dma);
474         writel ((u32)ehci->async->qh_dma, &ehci->regs->async_next);
475
476         /*
477          * hcc_params controls whether ehci->regs->segment must (!!!)
478          * be used; it constrains QH/ITD/SITD and QTD locations.
479          * pci_pool consistent memory always uses segment zero.
480          * streaming mappings for I/O buffers, like pci_map_single(),
481          * can return segments above 4GB, if the device allows.
482          *
483          * NOTE:  the dma mask is visible through dma_supported(), so
484          * drivers can pass this info along ... like NETIF_F_HIGHDMA,
485          * Scsi_Host.highmem_io, and so forth.  It's readonly to all
486          * host side drivers though.
487          */
488         if (HCC_64BIT_ADDR (hcc_params)) {
489                 writel (0, &ehci->regs->segment);
490 #if 0
491 // this is deeply broken on almost all architectures
492                 if (!pci_set_dma_mask (to_pci_dev(ehci->hcd.self.controller), 0xffffffffffffffffULL))
493                         ehci_info (ehci, "enabled 64bit PCI DMA\n");
494 #endif
495         }
496
497         /* clear interrupt enables, set irq latency */
498         temp = readl (&ehci->regs->command) & 0x0fff;
499         if (log2_irq_thresh < 0 || log2_irq_thresh > 6)
500                 log2_irq_thresh = 0;
501         temp |= 1 << (16 + log2_irq_thresh);
502         // if hc can park (ehci >= 0.96), default is 3 packets per async QH 
503         if (HCC_PGM_FRAMELISTLEN (hcc_params)) {
504                 /* periodic schedule size can be smaller than default */
505                 temp &= ~(3 << 2);
506                 temp |= (EHCI_TUNE_FLS << 2);
507                 switch (EHCI_TUNE_FLS) {
508                 case 0: ehci->periodic_size = 1024; break;
509                 case 1: ehci->periodic_size = 512; break;
510                 case 2: ehci->periodic_size = 256; break;
511                 default:        BUG ();
512                 }
513         }
514         temp &= ~(CMD_IAAD | CMD_ASE | CMD_PSE),
515         // Philips, Intel, and maybe others need CMD_RUN before the
516         // root hub will detect new devices (why?); NEC doesn't
517         temp |= CMD_RUN;
518         writel (temp, &ehci->regs->command);
519         dbg_cmd (ehci, "init", temp);
520
521         /* set async sleep time = 10 us ... ? */
522
523         /* wire up the root hub */
524         bus = hcd_to_bus (hcd);
525         udev = usb_alloc_dev (NULL, bus, 0);
526         if (!udev) {
527 done2:
528                 ehci_mem_cleanup (ehci);
529                 return -ENOMEM;
530         }
531
532         /*
533          * Start, enabling full USB 2.0 functionality ... usb 1.1 devices
534          * are explicitly handed to companion controller(s), so no TT is
535          * involved with the root hub.
536          */
537         ehci->reboot_notifier.notifier_call = ehci_reboot;
538         register_reboot_notifier (&ehci->reboot_notifier);
539
540         ehci->hcd.state = USB_STATE_RUNNING;
541         writel (FLAG_CF, &ehci->regs->configured_flag);
542         readl (&ehci->regs->command);   /* unblock posted write */
543
544         temp = HC_VERSION(readl (&ehci->caps->hc_capbase));
545         ehci_info (ehci,
546                 "USB %x.%x enabled, EHCI %x.%02x, driver %s\n",
547                 ((sbrn & 0xf0)>>4), (sbrn & 0x0f),
548                 temp >> 8, temp & 0xff, DRIVER_VERSION);
549
550         /*
551          * From here on, khubd concurrently accesses the root
552          * hub; drivers will be talking to enumerated devices.
553          *
554          * Before this point the HC was idle/ready.  After, khubd
555          * and device drivers may start it running.
556          */
557         udev->speed = USB_SPEED_HIGH;
558         if (hcd_register_root (udev, hcd) != 0) {
559                 if (hcd->state == USB_STATE_RUNNING)
560                         ehci_ready (ehci);
561                 ehci_reset (ehci);
562                 usb_put_dev (udev); 
563                 retval = -ENODEV;
564                 goto done2;
565         }
566
567         create_debug_files (ehci);
568
569         return 0;
570 }
571
572 /* always called by thread; normally rmmod */
573
574 static void ehci_stop (struct usb_hcd *hcd)
575 {
576         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
577
578         ehci_dbg (ehci, "stop\n");
579
580         /* no more interrupts ... */
581         if (hcd->state == USB_STATE_RUNNING)
582                 ehci_ready (ehci);
583         if (in_interrupt ()) {          /* must not happen!! */
584                 ehci_err (ehci, "stopped in_interrupt!\n");
585                 return;
586         }
587         del_timer_sync (&ehci->watchdog);
588         ehci_reset (ehci);
589
590         /* let companion controllers work when we aren't */
591         writel (0, &ehci->regs->configured_flag);
592         unregister_reboot_notifier (&ehci->reboot_notifier);
593
594         remove_debug_files (ehci);
595
596         /* root hub is shut down separately (first, when possible) */
597         spin_lock_irq (&ehci->lock);
598         if (ehci->async)
599                 ehci_work (ehci, NULL);
600         spin_unlock_irq (&ehci->lock);
601         ehci_mem_cleanup (ehci);
602
603 #ifdef  EHCI_STATS
604         ehci_dbg (ehci, "irq normal %ld err %ld reclaim %ld (lost %ld)\n",
605                 ehci->stats.normal, ehci->stats.error, ehci->stats.reclaim,
606                 ehci->stats.lost_iaa);
607         ehci_dbg (ehci, "complete %ld unlink %ld\n",
608                 ehci->stats.complete, ehci->stats.unlink);
609 #endif
610
611         dbg_status (ehci, "ehci_stop completed", readl (&ehci->regs->status));
612 }
613
614 static int ehci_get_frame (struct usb_hcd *hcd)
615 {
616         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
617         return (readl (&ehci->regs->frame_index) >> 3) % ehci->periodic_size;
618 }
619
620 /*-------------------------------------------------------------------------*/
621
622 #ifdef  CONFIG_PM
623
624 /* suspend/resume, section 4.3 */
625
626 /* These routines rely on PCI to handle powerdown and wakeup, and
627  * transceivers that don't need any software attention to set up
628  * the right sort of wakeup.  
629  */
630
631 static int ehci_suspend (struct usb_hcd *hcd, u32 state)
632 {
633         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
634
635         while (time_before (jiffies, ehci->next_statechange))
636                 msleep (100);
637
638 #ifdef  CONFIG_USB_SUSPEND
639         (void) usb_suspend_device (hcd->self.root_hub);
640 #else
641         /* FIXME lock root hub */
642         (void) ehci_hub_suspend (hcd);
643 #endif
644
645         // save (PCI) FLADJ in case of Vaux power loss
646
647         return 0;
648 }
649
650 static int ehci_resume (struct usb_hcd *hcd)
651 {
652         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
653         int                     retval;
654
655         // maybe restore (PCI) FLADJ
656
657         while (time_before (jiffies, ehci->next_statechange))
658                 msleep (100);
659
660 #ifdef  CONFIG_USB_SUSPEND
661         retval = usb_resume_device (hcd->self.root_hub);
662 #else
663         /* FIXME lock root hub */
664         retval = ehci_hub_resume (hcd);
665 #endif
666         if (retval == 0)
667                 hcd->self.controller->power.power_state = 0;
668         return retval;
669 }
670
671 #endif
672
673 /*-------------------------------------------------------------------------*/
674
675 /*
676  * ehci_work is called from some interrupts, timers, and so on.
677  * it calls driver completion functions, after dropping ehci->lock.
678  */
679 static void ehci_work (struct ehci_hcd *ehci, struct pt_regs *regs)
680 {
681         timer_action_done (ehci, TIMER_IO_WATCHDOG);
682         if (ehci->reclaim_ready)
683                 end_unlink_async (ehci, regs);
684         scan_async (ehci, regs);
685         if (ehci->next_uframe != -1)
686                 scan_periodic (ehci, regs);
687
688         /* the IO watchdog guards against hardware or driver bugs that
689          * misplace IRQs, and should let us run completely without IRQs.
690          * such lossage has been observed on both VT6202 and VT8235. 
691          */
692         if ((ehci->async->qh_next.ptr != 0) || (ehci->periodic_sched != 0))
693                 timer_action (ehci, TIMER_IO_WATCHDOG);
694 }
695
696 /*-------------------------------------------------------------------------*/
697
698 static irqreturn_t ehci_irq (struct usb_hcd *hcd, struct pt_regs *regs)
699 {
700         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
701         u32                     status;
702         int                     bh;
703
704         spin_lock (&ehci->lock);
705
706         status = readl (&ehci->regs->status);
707
708         /* shared irq */
709         if (status == 0) {
710                 spin_unlock (&ehci->lock);
711                 return IRQ_NONE;
712         }
713
714         /* e.g. cardbus physical eject */
715         if (status == ~(u32) 0) {
716                 ehci_dbg (ehci, "device removed\n");
717                 goto dead;
718         }
719
720         status &= INTR_MASK;
721         if (!status)                    /* irq sharing? */
722                 goto done;
723
724         /* clear (just) interrupts */
725         writel (status, &ehci->regs->status);
726         readl (&ehci->regs->command);   /* unblock posted write */
727         bh = 0;
728
729 #ifdef  EHCI_VERBOSE_DEBUG
730         /* unrequested/ignored: Frame List Rollover */
731         dbg_status (ehci, "irq", status);
732 #endif
733
734         /* INT, ERR, and IAA interrupt rates can be throttled */
735
736         /* normal [4.15.1.2] or error [4.15.1.1] completion */
737         if (likely ((status & (STS_INT|STS_ERR)) != 0)) {
738                 if (likely ((status & STS_ERR) == 0))
739                         COUNT (ehci->stats.normal);
740                 else
741                         COUNT (ehci->stats.error);
742                 bh = 1;
743         }
744
745         /* complete the unlinking of some qh [4.15.2.3] */
746         if (status & STS_IAA) {
747                 COUNT (ehci->stats.reclaim);
748                 ehci->reclaim_ready = 1;
749                 bh = 1;
750         }
751
752         /* remote wakeup [4.3.1] */
753         if ((status & STS_PCD) && ehci->hcd.remote_wakeup) {
754                 unsigned        i = HCS_N_PORTS (ehci->hcs_params);
755
756                 /* resume root hub? */
757                 status = readl (&ehci->regs->command);
758                 if (!(status & CMD_RUN))
759                         writel (status | CMD_RUN, &ehci->regs->command);
760
761                 while (i--) {
762                         status = readl (&ehci->regs->port_status [i]);
763                         if (status & PORT_OWNER)
764                                 continue;
765                         if (!(status & PORT_RESUME)
766                                         || ehci->reset_done [i] != 0)
767                                 continue;
768
769                         /* start 20 msec resume signaling from this port,
770                          * and make khubd collect PORT_STAT_C_SUSPEND to
771                          * stop that signaling.
772                          */
773                         ehci->reset_done [i] = jiffies + msecs_to_jiffies (20);
774                         mod_timer (&ehci->hcd.rh_timer,
775                                         ehci->reset_done [i] + 1);
776                         ehci_dbg (ehci, "port %d remote wakeup\n", i + 1);
777                 }
778         }
779
780         /* PCI errors [4.15.2.4] */
781         if (unlikely ((status & STS_FATAL) != 0)) {
782                 ehci_err (ehci, "fatal error\n");
783 dead:
784                 ehci_reset (ehci);
785                 /* generic layer kills/unlinks all urbs, then
786                  * uses ehci_stop to clean up the rest
787                  */
788                 bh = 1;
789         }
790
791         if (bh)
792                 ehci_work (ehci, regs);
793 done:
794         spin_unlock (&ehci->lock);
795         return IRQ_HANDLED;
796 }
797
798 /*-------------------------------------------------------------------------*/
799
800 /*
801  * non-error returns are a promise to giveback() the urb later
802  * we drop ownership so next owner (or urb unlink) can get it
803  *
804  * urb + dev is in hcd.self.controller.urb_list
805  * we're queueing TDs onto software and hardware lists
806  *
807  * hcd-specific init for hcpriv hasn't been done yet
808  *
809  * NOTE:  control, bulk, and interrupt share the same code to append TDs
810  * to a (possibly active) QH, and the same QH scanning code.
811  */
812 static int ehci_urb_enqueue (
813         struct usb_hcd  *hcd,
814         struct urb      *urb,
815         int             mem_flags
816 ) {
817         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
818         struct list_head        qtd_list;
819
820         INIT_LIST_HEAD (&qtd_list);
821
822         switch (usb_pipetype (urb->pipe)) {
823         // case PIPE_CONTROL:
824         // case PIPE_BULK:
825         default:
826                 if (!qh_urb_transaction (ehci, urb, &qtd_list, mem_flags))
827                         return -ENOMEM;
828                 return submit_async (ehci, urb, &qtd_list, mem_flags);
829
830         case PIPE_INTERRUPT:
831                 if (!qh_urb_transaction (ehci, urb, &qtd_list, mem_flags))
832                         return -ENOMEM;
833                 return intr_submit (ehci, urb, &qtd_list, mem_flags);
834
835         case PIPE_ISOCHRONOUS:
836                 if (urb->dev->speed == USB_SPEED_HIGH)
837                         return itd_submit (ehci, urb, mem_flags);
838                 else
839                         return sitd_submit (ehci, urb, mem_flags);
840         }
841 }
842
843 /* remove from hardware lists
844  * completions normally happen asynchronously
845  */
846
847 static int ehci_urb_dequeue (struct usb_hcd *hcd, struct urb *urb)
848 {
849         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
850         struct ehci_qh          *qh;
851         unsigned long           flags;
852
853         spin_lock_irqsave (&ehci->lock, flags);
854         switch (usb_pipetype (urb->pipe)) {
855         // case PIPE_CONTROL:
856         // case PIPE_BULK:
857         default:
858                 qh = (struct ehci_qh *) urb->hcpriv;
859                 if (!qh)
860                         break;
861
862                 /* if we need to use IAA and it's busy, defer */
863                 if (qh->qh_state == QH_STATE_LINKED
864                                 && ehci->reclaim
865                                 && HCD_IS_RUNNING (ehci->hcd.state)
866                                 ) {
867                         struct ehci_qh          *last;
868
869                         for (last = ehci->reclaim;
870                                         last->reclaim;
871                                         last = last->reclaim)
872                                 continue;
873                         qh->qh_state = QH_STATE_UNLINK_WAIT;
874                         last->reclaim = qh;
875
876                 /* bypass IAA if the hc can't care */
877                 } else if (!HCD_IS_RUNNING (ehci->hcd.state) && ehci->reclaim)
878                         end_unlink_async (ehci, NULL);
879
880                 /* something else might have unlinked the qh by now */
881                 if (qh->qh_state == QH_STATE_LINKED)
882                         start_unlink_async (ehci, qh);
883                 break;
884
885         case PIPE_INTERRUPT:
886                 qh = (struct ehci_qh *) urb->hcpriv;
887                 if (!qh)
888                         break;
889                 if (qh->qh_state == QH_STATE_LINKED) {
890                         /* messy, can spin or block a microframe ... */
891                         intr_deschedule (ehci, qh, 1);
892                         /* qh_state == IDLE */
893                 }
894                 qh_completions (ehci, qh, NULL);
895
896                 /* reschedule QH iff another request is queued */
897                 if (!list_empty (&qh->qtd_list)
898                                 && HCD_IS_RUNNING (ehci->hcd.state)) {
899                         int status;
900
901                         status = qh_schedule (ehci, qh);
902                         spin_unlock_irqrestore (&ehci->lock, flags);
903
904                         if (status != 0) {
905                                 // shouldn't happen often, but ...
906                                 // FIXME kill those tds' urbs
907                                 err ("can't reschedule qh %p, err %d",
908                                         qh, status);
909                         }
910                         return status;
911                 }
912                 break;
913
914         case PIPE_ISOCHRONOUS:
915                 // itd or sitd ...
916
917                 // wait till next completion, do it then.
918                 // completion irqs can wait up to 1024 msec,
919                 break;
920         }
921         spin_unlock_irqrestore (&ehci->lock, flags);
922         return 0;
923 }
924
925 /*-------------------------------------------------------------------------*/
926
927 // bulk qh holds the data toggle
928
929 static void
930 ehci_endpoint_disable (struct usb_hcd *hcd, struct hcd_dev *dev, int ep)
931 {
932         struct ehci_hcd         *ehci = hcd_to_ehci (hcd);
933         int                     epnum;
934         unsigned long           flags;
935         struct ehci_qh          *qh;
936
937         /* ASSERT:  any requests/urbs are being unlinked */
938         /* ASSERT:  nobody can be submitting urbs for this any more */
939
940         epnum = ep & USB_ENDPOINT_NUMBER_MASK;
941         if (epnum != 0 && (ep & USB_DIR_IN))
942                 epnum |= 0x10;
943
944 rescan:
945         spin_lock_irqsave (&ehci->lock, flags);
946         qh = (struct ehci_qh *) dev->ep [epnum];
947         if (!qh)
948                 goto done;
949
950         /* endpoints can be iso streams.  for now, we don't
951          * accelerate iso completions ... so spin a while.
952          */
953         if (qh->hw_info1 == 0) {
954                 ehci_vdbg (ehci, "iso delay\n");
955                 goto idle_timeout;
956         }
957
958         if (!HCD_IS_RUNNING (ehci->hcd.state))
959                 qh->qh_state = QH_STATE_IDLE;
960         switch (qh->qh_state) {
961         case QH_STATE_UNLINK:           /* wait for hw to finish? */
962 idle_timeout:
963                 spin_unlock_irqrestore (&ehci->lock, flags);
964                 set_current_state (TASK_UNINTERRUPTIBLE);
965                 schedule_timeout (1);
966                 goto rescan;
967         case QH_STATE_IDLE:             /* fully unlinked */
968                 if (list_empty (&qh->qtd_list)) {
969                         qh_put (qh);
970                         break;
971                 }
972                 /* else FALL THROUGH */
973         default:
974                 /* caller was supposed to have unlinked any requests;
975                  * that's not our job.  just leak this memory.
976                  */
977                 ehci_err (ehci, "qh %p (#%d) state %d%s\n",
978                         qh, epnum, qh->qh_state,
979                         list_empty (&qh->qtd_list) ? "" : "(has tds)");
980                 break;
981         }
982         dev->ep [epnum] = 0;
983 done:
984         spin_unlock_irqrestore (&ehci->lock, flags);
985         return;
986 }
987
988 /*-------------------------------------------------------------------------*/
989
990 static const struct hc_driver ehci_driver = {
991         .description =          hcd_name,
992
993         /*
994          * generic hardware linkage
995          */
996         .irq =                  ehci_irq,
997         .flags =                HCD_MEMORY | HCD_USB2,
998
999         /*
1000          * basic lifecycle operations
1001          */
1002         .reset =                ehci_hc_reset,
1003         .start =                ehci_start,
1004 #ifdef  CONFIG_PM
1005         .suspend =              ehci_suspend,
1006         .resume =               ehci_resume,
1007 #endif
1008         .stop =                 ehci_stop,
1009
1010         /*
1011          * memory lifecycle (except per-request)
1012          */
1013         .hcd_alloc =            ehci_hcd_alloc,
1014         .hcd_free =             ehci_hcd_free,
1015
1016         /*
1017          * managing i/o requests and associated device resources
1018          */
1019         .urb_enqueue =          ehci_urb_enqueue,
1020         .urb_dequeue =          ehci_urb_dequeue,
1021         .endpoint_disable =     ehci_endpoint_disable,
1022
1023         /*
1024          * scheduling support
1025          */
1026         .get_frame_number =     ehci_get_frame,
1027
1028         /*
1029          * root hub support
1030          */
1031         .hub_status_data =      ehci_hub_status_data,
1032         .hub_control =          ehci_hub_control,
1033 };
1034
1035 /*-------------------------------------------------------------------------*/
1036
1037 /* EHCI 1.0 doesn't require PCI */
1038
1039 #ifdef  CONFIG_PCI
1040
1041 /* PCI driver selection metadata; PCI hotplugging uses this */
1042 static const struct pci_device_id pci_ids [] = { {
1043         /* handle any USB 2.0 EHCI controller */
1044         PCI_DEVICE_CLASS(((PCI_CLASS_SERIAL_USB << 8) | 0x20), ~0),
1045         .driver_data =  (unsigned long) &ehci_driver,
1046         },
1047         { /* end: all zeroes */ }
1048 };
1049 MODULE_DEVICE_TABLE (pci, pci_ids);
1050
1051 /* pci driver glue; this is a "new style" PCI driver module */
1052 static struct pci_driver ehci_pci_driver = {
1053         .name =         (char *) hcd_name,
1054         .id_table =     pci_ids,
1055
1056         .probe =        usb_hcd_pci_probe,
1057         .remove =       usb_hcd_pci_remove,
1058
1059 #ifdef  CONFIG_PM
1060         .suspend =      usb_hcd_pci_suspend,
1061         .resume =       usb_hcd_pci_resume,
1062 #endif
1063 };
1064
1065 #endif  /* PCI */
1066
1067
1068 #define DRIVER_INFO DRIVER_VERSION " " DRIVER_DESC
1069
1070 MODULE_DESCRIPTION (DRIVER_INFO);
1071 MODULE_AUTHOR (DRIVER_AUTHOR);
1072 MODULE_LICENSE ("GPL");
1073
1074 static int __init init (void) 
1075 {
1076         if (usb_disabled())
1077                 return -ENODEV;
1078
1079         pr_debug ("%s: block sizes: qh %Zd qtd %Zd itd %Zd sitd %Zd\n",
1080                 hcd_name,
1081                 sizeof (struct ehci_qh), sizeof (struct ehci_qtd),
1082                 sizeof (struct ehci_itd), sizeof (struct ehci_sitd));
1083
1084         return pci_module_init (&ehci_pci_driver);
1085 }
1086 module_init (init);
1087
1088 static void __exit cleanup (void) 
1089 {       
1090         pci_unregister_driver (&ehci_pci_driver);
1091 }
1092 module_exit (cleanup);