more changes on original files
[linux-2.4.git] / drivers / usb / hcd.c
1 /*
2  * Copyright (c) 2001-2002 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 #include <linux/module.h>
21 #include <linux/pci.h>
22 #include <linux/kernel.h>
23 #include <linux/delay.h>
24 #include <linux/ioport.h>
25 #include <linux/sched.h>
26 #include <linux/slab.h>
27 #include <linux/smp_lock.h>
28 #include <linux/errno.h>
29 #include <linux/kmod.h>
30 #include <linux/init.h>
31 #include <linux/timer.h>
32 #include <linux/list.h>
33 #include <linux/interrupt.h>
34 #include <linux/completion.h>
35 #include <linux/uts.h>                  /* for UTS_SYSNAME */
36
37
38 #ifdef CONFIG_USB_DEBUG
39         #define DEBUG
40 #else
41         #undef DEBUG
42 #endif
43
44 #include <linux/usb.h>
45 #include "hcd.h"
46
47 #include <asm/io.h>
48 #include <asm/irq.h>
49 #include <asm/system.h>
50 #include <asm/unaligned.h>
51
52
53 /*-------------------------------------------------------------------------*/
54
55 /*
56  * USB Host Controller Driver framework
57  *
58  * Plugs into usbcore (usb_bus) and lets HCDs share code, minimizing
59  * HCD-specific behaviors/bugs.  Think of it as the "upper level" of
60  * some drivers, where the "lower level" is hardware-specific.
61  *
62  * This does error checks, tracks devices and urbs, and delegates to a
63  * "hc_driver" only for code (and data) that really needs to know about
64  * hardware differences.  That includes root hub registers, i/o queues,
65  * and so on ... but as little else as possible.
66  *
67  * Shared code includes most of the "root hub" code (these are emulated,
68  * though each HC's hardware works differently) and PCI glue, plus request
69  * tracking overhead.  The HCD code should only block on spinlocks or on
70  * hardware handshaking; blocking on software events (such as other kernel
71  * threads releasing resources, or completing actions) is all generic.
72  *
73  * Happens the USB 2.0 spec says this would be invisible inside the "USBD",
74  * and includes mostly a "HCDI" (HCD Interface) along with some APIs used
75  * only by the hub driver ... and that neither should be seen or used by
76  * usb client device drivers.
77  *
78  * Contributors of ideas or unattributed patches include: David Brownell,
79  * Roman Weissgaerber, Rory Bolt, ...
80  *
81  * HISTORY:
82  * 2002-sept    Merge some 2.5 updates so we can share hardware level HCD
83  *      code between the 2.4.20+ and 2.5 trees.
84  * 2002-feb     merge to 2.4.19
85  * 2001-12-12   Initial patch version for Linux 2.5.1 kernel.
86  */
87
88 /*-------------------------------------------------------------------------*/
89
90 /* host controllers we manage */
91 static LIST_HEAD (hcd_list);
92
93 /* used when updating list of hcds */
94 static DECLARE_MUTEX (hcd_list_lock);
95
96 /* used when updating hcd data */
97 static spinlock_t hcd_data_lock = SPIN_LOCK_UNLOCKED;
98
99 static struct usb_operations hcd_operations;
100
101 /*-------------------------------------------------------------------------*/
102
103 /*
104  * Sharable chunks of root hub code.
105  */
106
107 /*-------------------------------------------------------------------------*/
108
109 #define KERNEL_REL      ((LINUX_VERSION_CODE >> 16) & 0x0ff)
110 #define KERNEL_VER      ((LINUX_VERSION_CODE >> 8) & 0x0ff)
111
112 /* usb 2.0 root hub device descriptor */
113 static const u8 usb2_rh_dev_descriptor [18] = {
114         0x12,       /*  __u8  bLength; */
115         0x01,       /*  __u8  bDescriptorType; Device */
116         0x00, 0x02, /*  __u16 bcdUSB; v2.0 */
117
118         0x09,       /*  __u8  bDeviceClass; HUB_CLASSCODE */
119         0x00,       /*  __u8  bDeviceSubClass; */
120         0x01,       /*  __u8  bDeviceProtocol; [ usb 2.0 single TT ]*/
121         0x08,       /*  __u8  bMaxPacketSize0; 8 Bytes */
122
123         0x00, 0x00, /*  __u16 idVendor; */
124         0x00, 0x00, /*  __u16 idProduct; */
125         KERNEL_VER, KERNEL_REL, /*  __u16 bcdDevice */
126
127         0x03,       /*  __u8  iManufacturer; */
128         0x02,       /*  __u8  iProduct; */
129         0x01,       /*  __u8  iSerialNumber; */
130         0x01        /*  __u8  bNumConfigurations; */
131 };
132
133 /* no usb 2.0 root hub "device qualifier" descriptor: one speed only */
134
135 /* usb 1.1 root hub device descriptor */
136 static const u8 usb11_rh_dev_descriptor [18] = {
137         0x12,       /*  __u8  bLength; */
138         0x01,       /*  __u8  bDescriptorType; Device */
139         0x10, 0x01, /*  __u16 bcdUSB; v1.1 */
140
141         0x09,       /*  __u8  bDeviceClass; HUB_CLASSCODE */
142         0x00,       /*  __u8  bDeviceSubClass; */
143         0x00,       /*  __u8  bDeviceProtocol; [ low/full speeds only ] */
144         0x08,       /*  __u8  bMaxPacketSize0; 8 Bytes */
145
146         0x00, 0x00, /*  __u16 idVendor; */
147         0x00, 0x00, /*  __u16 idProduct; */
148         KERNEL_VER, KERNEL_REL, /*  __u16 bcdDevice */
149
150         0x03,       /*  __u8  iManufacturer; */
151         0x02,       /*  __u8  iProduct; */
152         0x01,       /*  __u8  iSerialNumber; */
153         0x01        /*  __u8  bNumConfigurations; */
154 };
155
156
157 /*-------------------------------------------------------------------------*/
158
159 /* Configuration descriptors for our root hubs */
160
161 static const u8 fs_rh_config_descriptor [] = {
162
163         /* one configuration */
164         0x09,       /*  __u8  bLength; */
165         0x02,       /*  __u8  bDescriptorType; Configuration */
166         0x19, 0x00, /*  __u16 wTotalLength; */
167         0x01,       /*  __u8  bNumInterfaces; (1) */
168         0x01,       /*  __u8  bConfigurationValue; */
169         0x00,       /*  __u8  iConfiguration; */
170         0x40,       /*  __u8  bmAttributes; 
171                                  Bit 7: Bus-powered,
172                                      6: Self-powered,
173                                      5 Remote-wakwup,
174                                      4..0: resvd */
175         0x00,       /*  __u8  MaxPower; */
176       
177         /* USB 1.1:
178          * USB 2.0, single TT organization (mandatory):
179          *      one interface, protocol 0
180          *
181          * USB 2.0, multiple TT organization (optional):
182          *      two interfaces, protocols 1 (like single TT)
183          *      and 2 (multiple TT mode) ... config is
184          *      sometimes settable
185          *      NOT IMPLEMENTED
186          */
187
188         /* one interface */
189         0x09,       /*  __u8  if_bLength; */
190         0x04,       /*  __u8  if_bDescriptorType; Interface */
191         0x00,       /*  __u8  if_bInterfaceNumber; */
192         0x00,       /*  __u8  if_bAlternateSetting; */
193         0x01,       /*  __u8  if_bNumEndpoints; */
194         0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
195         0x00,       /*  __u8  if_bInterfaceSubClass; */
196         0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
197         0x00,       /*  __u8  if_iInterface; */
198      
199         /* one endpoint (status change endpoint) */
200         0x07,       /*  __u8  ep_bLength; */
201         0x05,       /*  __u8  ep_bDescriptorType; Endpoint */
202         0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
203         0x03,       /*  __u8  ep_bmAttributes; Interrupt */
204         0x02, 0x00, /*  __u16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
205         0xff        /*  __u8  ep_bInterval; (255ms -- usb 2.0 spec) */
206 };
207
208 static const u8 hs_rh_config_descriptor [] = {
209
210         /* one configuration */
211         0x09,       /*  __u8  bLength; */
212         0x02,       /*  __u8  bDescriptorType; Configuration */
213         0x19, 0x00, /*  __u16 wTotalLength; */
214         0x01,       /*  __u8  bNumInterfaces; (1) */
215         0x01,       /*  __u8  bConfigurationValue; */
216         0x00,       /*  __u8  iConfiguration; */
217         0x40,       /*  __u8  bmAttributes; 
218                                  Bit 7: Bus-powered,
219                                      6: Self-powered,
220                                      5 Remote-wakwup,
221                                      4..0: resvd */
222         0x00,       /*  __u8  MaxPower; */
223       
224         /* USB 1.1:
225          * USB 2.0, single TT organization (mandatory):
226          *      one interface, protocol 0
227          *
228          * USB 2.0, multiple TT organization (optional):
229          *      two interfaces, protocols 1 (like single TT)
230          *      and 2 (multiple TT mode) ... config is
231          *      sometimes settable
232          *      NOT IMPLEMENTED
233          */
234
235         /* one interface */
236         0x09,       /*  __u8  if_bLength; */
237         0x04,       /*  __u8  if_bDescriptorType; Interface */
238         0x00,       /*  __u8  if_bInterfaceNumber; */
239         0x00,       /*  __u8  if_bAlternateSetting; */
240         0x01,       /*  __u8  if_bNumEndpoints; */
241         0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
242         0x00,       /*  __u8  if_bInterfaceSubClass; */
243         0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
244         0x00,       /*  __u8  if_iInterface; */
245      
246         /* one endpoint (status change endpoint) */
247         0x07,       /*  __u8  ep_bLength; */
248         0x05,       /*  __u8  ep_bDescriptorType; Endpoint */
249         0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
250         0x03,       /*  __u8  ep_bmAttributes; Interrupt */
251         0x02, 0x00, /*  __u16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
252         0x0c        /*  __u8  ep_bInterval; (256ms -- usb 2.0 spec) */
253 };
254
255 /*-------------------------------------------------------------------------*/
256
257 /*
258  * helper routine for returning string descriptors in UTF-16LE
259  * input can actually be ISO-8859-1; ASCII is its 7-bit subset
260  */
261 static int ascii2utf (char *s, u8 *utf, int utfmax)
262 {
263         int retval;
264
265         for (retval = 0; *s && utfmax > 1; utfmax -= 2, retval += 2) {
266                 *utf++ = *s++;
267                 *utf++ = 0;
268         }
269         return retval;
270 }
271
272 /*
273  * rh_string - provides manufacturer, product and serial strings for root hub
274  * @id: the string ID number (1: serial number, 2: product, 3: vendor)
275  * @pci_desc: PCI device descriptor for the relevant HC
276  * @type: string describing our driver 
277  * @data: return packet in UTF-16 LE
278  * @len: length of the return packet
279  *
280  * Produces either a manufacturer, product or serial number string for the
281  * virtual root hub device.
282  */
283 static int rh_string (
284         int             id,
285         struct usb_hcd  *hcd,
286         u8              *data,
287         int             len
288 ) {
289         char buf [100];
290
291         // language ids
292         if (id == 0) {
293                 *data++ = 4; *data++ = 3;       /* 4 bytes string data */
294                 *data++ = 0; *data++ = 0;       /* some language id */
295                 return 4;
296
297         // serial number
298         } else if (id == 1) {
299                 strcpy (buf, hcd->bus->bus_name);
300
301         // product description
302         } else if (id == 2) {
303                 strcpy (buf, hcd->product_desc);
304
305         // id 3 == vendor description
306         } else if (id == 3) {
307                 sprintf (buf, "%s %s %s", UTS_SYSNAME, UTS_RELEASE,
308                         hcd->description);
309
310         // unsupported IDs --> "protocol stall"
311         } else
312             return 0;
313
314         data [0] = 2 * (strlen (buf) + 1);
315         data [1] = 3;   /* type == string */
316         return 2 + ascii2utf (buf, data + 2, len - 2);
317 }
318
319
320 /* Root hub control transfers execute synchronously */
321 static int rh_call_control (struct usb_hcd *hcd, struct urb *urb)
322 {
323         struct usb_ctrlrequest *cmd = (struct usb_ctrlrequest *) urb->setup_packet;
324         u16             typeReq, wValue, wIndex, wLength;
325         const u8        *bufp = 0;
326         u8              *ubuf = urb->transfer_buffer;
327         int             len = 0;
328
329         typeReq  = (cmd->bRequestType << 8) | cmd->bRequest;
330         wValue   = le16_to_cpu (cmd->wValue);
331         wIndex   = le16_to_cpu (cmd->wIndex);
332         wLength  = le16_to_cpu (cmd->wLength);
333
334         if (wLength > urb->transfer_buffer_length)
335                 goto error;
336
337         /* set up for success */
338         urb->status = 0;
339         urb->actual_length = wLength;
340         switch (typeReq) {
341
342         /* DEVICE REQUESTS */
343
344         case DeviceRequest | USB_REQ_GET_STATUS:
345                 // DEVICE_REMOTE_WAKEUP
346                 ubuf [0] = 1; // selfpowered
347                 ubuf [1] = 0;
348                         /* FALLTHROUGH */
349         case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
350         case DeviceOutRequest | USB_REQ_SET_FEATURE:
351                 dbg ("no device features yet yet");
352                 break;
353         case DeviceRequest | USB_REQ_GET_CONFIGURATION:
354                 ubuf [0] = 1;
355                         /* FALLTHROUGH */
356         case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
357                 break;
358         case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
359                 switch (wValue & 0xff00) {
360                 case USB_DT_DEVICE << 8:
361                         if (hcd->driver->flags & HCD_USB2)
362                                 bufp = usb2_rh_dev_descriptor;
363                         else if (hcd->driver->flags & HCD_USB11)
364                                 bufp = usb11_rh_dev_descriptor;
365                         else
366                                 goto error;
367                         len = 18;
368                         break;
369                 case USB_DT_CONFIG << 8:
370                         if (hcd->driver->flags & HCD_USB2) {
371                                 bufp = hs_rh_config_descriptor;
372                                 len = sizeof hs_rh_config_descriptor;
373                         } else {
374                                 bufp = fs_rh_config_descriptor;
375                                 len = sizeof fs_rh_config_descriptor;
376                         }
377                         break;
378                 case USB_DT_STRING << 8:
379                         urb->actual_length = rh_string (
380                                 wValue & 0xff, hcd,
381                                 ubuf, wLength);
382                         break;
383                 default:
384                         goto error;
385                 }
386                 break;
387         case DeviceRequest | USB_REQ_GET_INTERFACE:
388                 ubuf [0] = 0;
389                         /* FALLTHROUGH */
390         case DeviceOutRequest | USB_REQ_SET_INTERFACE:
391                 break;
392         case DeviceOutRequest | USB_REQ_SET_ADDRESS:
393                 // wValue == urb->dev->devaddr
394                 dbg ("%s root hub device address %d",
395                         hcd->bus->bus_name, wValue);
396                 break;
397
398         /* INTERFACE REQUESTS (no defined feature/status flags) */
399
400         /* ENDPOINT REQUESTS */
401
402         case EndpointRequest | USB_REQ_GET_STATUS:
403                 // ENDPOINT_HALT flag
404                 ubuf [0] = 0;
405                 ubuf [1] = 0;
406                         /* FALLTHROUGH */
407         case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
408         case EndpointOutRequest | USB_REQ_SET_FEATURE:
409                 dbg ("no endpoint features yet");
410                 break;
411
412         /* CLASS REQUESTS (and errors) */
413
414         default:
415                 /* non-generic request */
416                 urb->status = hcd->driver->hub_control (hcd,
417                         typeReq, wValue, wIndex,
418                         ubuf, wLength);
419                 break;
420 error:
421                 /* "protocol stall" on error */
422                 urb->status = -EPIPE;
423                 dbg ("unsupported hub control message (maxchild %d)",
424                                 urb->dev->maxchild);
425         }
426         if (urb->status) {
427                 urb->actual_length = 0;
428                 dbg ("CTRL: TypeReq=0x%x val=0x%x idx=0x%x len=%d ==> %d",
429                         typeReq, wValue, wIndex, wLength, urb->status);
430         }
431         if (bufp) {
432                 if (urb->transfer_buffer_length < len)
433                         len = urb->transfer_buffer_length;
434                 urb->actual_length = len;
435                 // always USB_DIR_IN, toward host
436                 memcpy (ubuf, bufp, len);
437         }
438
439         /* any errors get returned through the urb completion */
440         usb_hcd_giveback_urb (hcd, urb, 0);
441         return 0;
442 }
443
444 /*-------------------------------------------------------------------------*/
445
446 /*
447  * Root Hub interrupt transfers are synthesized with a timer.
448  * Completions are called in_interrupt() but not in_irq().
449  */
450
451 static void rh_report_status (unsigned long ptr);
452
453 static int rh_status_urb (struct usb_hcd *hcd, struct urb *urb) 
454 {
455         int     len = 1 + (urb->dev->maxchild / 8);
456
457         /* rh_timer protected by hcd_data_lock */
458         if (timer_pending (&hcd->rh_timer)
459                         || urb->status != -EINPROGRESS
460                         || !HCD_IS_RUNNING (hcd->state)
461                         || urb->transfer_buffer_length < len) {
462                 dbg ("not queuing status urb, stat %d", urb->status);
463                 return -EINVAL;
464         }
465
466         urb->hcpriv = hcd;      /* nonzero to indicate it's queued */
467         init_timer (&hcd->rh_timer);
468         hcd->rh_timer.function = rh_report_status;
469         hcd->rh_timer.data = (unsigned long) urb;
470         /* USB 2.0 spec says 256msec; this is close enough */
471         hcd->rh_timer.expires = jiffies + HZ/4;
472         add_timer (&hcd->rh_timer);
473         return 0;
474 }
475
476 /* timer callback */
477
478 static void rh_report_status (unsigned long ptr)
479 {
480         struct urb      *urb;
481         struct usb_hcd  *hcd;
482         int             length;
483         unsigned long   flags;
484
485         urb = (struct urb *) ptr;
486         spin_lock_irqsave (&urb->lock, flags);
487         if (!urb->dev) {
488                 spin_unlock_irqrestore (&urb->lock, flags);
489                 return;
490         }
491
492         hcd = urb->dev->bus->hcpriv;
493         if (urb->status == -EINPROGRESS) {
494                 if (HCD_IS_RUNNING (hcd->state)) {
495                         length = hcd->driver->hub_status_data (hcd,
496                                         urb->transfer_buffer);
497                         spin_unlock_irqrestore (&urb->lock, flags);
498                         if (length > 0) {
499                                 urb->actual_length = length;
500                                 urb->status = 0;
501                                 urb->complete (urb);
502                         }
503                         spin_lock_irqsave (&hcd_data_lock, flags);
504                         urb->status = -EINPROGRESS;
505                         if (HCD_IS_RUNNING (hcd->state)
506                                         && rh_status_urb (hcd, urb) != 0) {
507                                 /* another driver snuck in? */
508                                 dbg ("%s, can't resubmit roothub status urb?",
509                                         hcd->bus->bus_name);
510                                 spin_unlock_irqrestore (&hcd_data_lock, flags);
511                                 BUG ();
512                         }
513                         spin_unlock_irqrestore (&hcd_data_lock, flags);
514                 } else
515                         spin_unlock_irqrestore (&urb->lock, flags);
516         } else {
517                 /* this urb's been unlinked */
518                 urb->hcpriv = 0;
519                 spin_unlock_irqrestore (&urb->lock, flags);
520
521                 usb_hcd_giveback_urb (hcd, urb, 0);
522         }
523 }
524
525 /*-------------------------------------------------------------------------*/
526
527 static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
528 {
529         if (usb_pipeint (urb->pipe)) {
530                 int             retval;
531                 unsigned long   flags;
532
533                 spin_lock_irqsave (&hcd_data_lock, flags);
534                 retval = rh_status_urb (hcd, urb);
535                 spin_unlock_irqrestore (&hcd_data_lock, flags);
536                 return retval;
537         }
538         if (usb_pipecontrol (urb->pipe))
539                 return rh_call_control (hcd, urb);
540         else
541                 return -EINVAL;
542 }
543
544 /*-------------------------------------------------------------------------*/
545
546 static void rh_status_dequeue (struct usb_hcd *hcd, struct urb *urb)
547 {
548         unsigned long   flags;
549
550         spin_lock_irqsave (&hcd_data_lock, flags);
551         del_timer_sync (&hcd->rh_timer);
552         hcd->rh_timer.data = 0;
553         spin_unlock_irqrestore (&hcd_data_lock, flags);
554
555         /* we rely on RH callback code not unlinking its URB! */
556         usb_hcd_giveback_urb (hcd, urb, 0);
557 }
558
559 /*-------------------------------------------------------------------------*/
560
561 #ifdef CONFIG_PCI
562
563 /* PCI-based HCs are normal, but custom bus glue should be ok */
564
565 static void hcd_irq (int irq, void *__hcd, struct pt_regs *r);
566 static void hc_died (struct usb_hcd *hcd);
567
568 /*-------------------------------------------------------------------------*/
569
570 /* configure so an HC device and id are always provided */
571 /* always called with process context; sleeping is OK */
572
573 /**
574  * usb_hcd_pci_probe - initialize PCI-based HCDs
575  * @dev: USB Host Controller being probed
576  * @id: pci hotplug id connecting controller to HCD framework
577  * Context: !in_interrupt()
578  *
579  * Allocates basic PCI resources for this USB host controller, and
580  * then invokes the start() method for the HCD associated with it
581  * through the hotplug entry's driver_data.
582  *
583  * Store this function in the HCD's struct pci_driver as probe().
584  */
585 int usb_hcd_pci_probe (struct pci_dev *dev, const struct pci_device_id *id)
586 {
587         struct hc_driver        *driver;
588         unsigned long           resource, len;
589         void                    *base;
590         struct usb_bus          *bus;
591         struct usb_hcd          *hcd;
592         int                     retval, region;
593         char                    buf [8], *bufp = buf;
594
595         if (!id || !(driver = (struct hc_driver *) id->driver_data))
596                 return -EINVAL;
597
598         if (pci_enable_device (dev) < 0)
599                 return -ENODEV;
600         
601         if (!dev->irq) {
602                 err ("Found HC with no IRQ.  Check BIOS/PCI %s setup!",
603                         dev->slot_name);
604                 return -ENODEV;
605         }
606         
607         if (driver->flags & HCD_MEMORY) {       // EHCI, OHCI
608                 region = 0;
609                 resource = pci_resource_start (dev, 0);
610                 len = pci_resource_len (dev, 0);
611                 if (!request_mem_region (resource, len, driver->description)) {
612                         dbg ("controller already in use");
613                         return -EBUSY;
614                 }
615                 base = ioremap_nocache (resource, len);
616                 if (base == NULL) {
617                         dbg ("error mapping memory");
618                         retval = -EFAULT;
619 clean_1:
620                         release_mem_region (resource, len);
621                         err ("init %s fail, %d", dev->slot_name, retval);
622                         return retval;
623                 }
624
625         } else {                                // UHCI
626                 resource = len = 0;
627                 for (region = 0; region < PCI_ROM_RESOURCE; region++) {
628                         if (!(pci_resource_flags (dev, region) & IORESOURCE_IO))
629                                 continue;
630
631                         resource = pci_resource_start (dev, region);
632                         len = pci_resource_len (dev, region);
633                         if (request_region (resource, len,
634                                         driver->description))
635                                 break;
636                 }
637                 if (region == PCI_ROM_RESOURCE) {
638                         dbg ("no i/o regions available");
639                         return -EBUSY;
640                 }
641                 base = (void *) resource;
642         }
643
644         // driver->start(), later on, will transfer device from
645         // control by SMM/BIOS to control by Linux (if needed)
646
647         pci_set_master (dev);
648         hcd = driver->hcd_alloc ();
649         if (hcd == NULL){
650                 dbg ("hcd alloc fail");
651                 retval = -ENOMEM;
652 clean_2:
653                 if (driver->flags & HCD_MEMORY) {
654                         iounmap (base);
655                         goto clean_1;
656                 } else {
657                         release_region (resource, len);
658                         err ("init %s fail, %d", dev->slot_name, retval);
659                         return retval;
660                 }
661         }
662         pci_set_drvdata(dev, hcd);
663         hcd->driver = driver;
664         hcd->description = driver->description;
665         hcd->pdev = dev;
666         printk (KERN_INFO "%s %s: %s\n",
667                         hcd->description,  dev->slot_name, dev->name);
668
669 #ifndef __sparc__
670         sprintf (buf, "%d", dev->irq);
671 #else
672         bufp = __irq_itoa(dev->irq);
673 #endif
674         //+Wilson 10/14/2003
675         //if (request_irq (dev->irq, hcd_irq, SA_SHIRQ, hcd->description, hcd)
676         if (request_irq (dev->irq, hcd_irq, SA_INTERRUPT, hcd->description, hcd)
677                         != 0) {
678                 err ("request interrupt %s failed", bufp);
679                 retval = -EBUSY;
680 clean_3:
681                 driver->hcd_free (hcd);
682                 goto clean_2;
683         }
684         hcd->irq = dev->irq;
685
686         hcd->regs = base;
687         hcd->region = region;
688         printk (KERN_INFO "%s %s: irq %s, %s %p\n",
689                 hcd->description,  dev->slot_name, bufp,
690                 (driver->flags & HCD_MEMORY) ? "pci mem" : "io base",
691                 base);
692
693 // FIXME simpler: make "bus" be that data, not pointer to it.
694 // (fixed in 2.5)
695         bus = usb_alloc_bus (&hcd_operations);
696         if (bus == NULL) {
697                 dbg ("usb_alloc_bus fail");
698                 retval = -ENOMEM;
699                 free_irq (dev->irq, hcd);
700                 goto clean_3;
701         }
702         hcd->bus = bus;
703         bus->bus_name = dev->slot_name;
704         hcd->product_desc = dev->name;
705         bus->hcpriv = (void *) hcd;
706
707         INIT_LIST_HEAD (&hcd->dev_list);
708         INIT_LIST_HEAD (&hcd->hcd_list);
709
710         down (&hcd_list_lock);
711         list_add (&hcd->hcd_list, &hcd_list);
712         up (&hcd_list_lock);
713
714         usb_register_bus (bus);
715
716         if ((retval = driver->start (hcd)) < 0)
717                 usb_hcd_pci_remove (dev);
718
719         return retval;
720
721 EXPORT_SYMBOL (usb_hcd_pci_probe);
722
723
724 /* may be called without controller electrically present */
725 /* may be called with controller, bus, and devices active */
726
727 /**
728  * usb_hcd_pci_remove - shutdown processing for PCI-based HCDs
729  * @dev: USB Host Controller being removed
730  * Context: !in_interrupt()
731  *
732  * Reverses the effect of usb_hcd_pci_probe(), first invoking
733  * the HCD's stop() method.  It is always called from a thread
734  * context, normally "rmmod", "apmd", or something similar.
735  *
736  * Store this function in the HCD's struct pci_driver as remove().
737  */
738 void usb_hcd_pci_remove (struct pci_dev *dev)
739 {
740         struct usb_hcd          *hcd;
741         struct usb_device       *hub;
742
743         hcd = pci_get_drvdata(dev);
744         if (!hcd)
745                 return;
746         printk (KERN_INFO "%s %s: remove state %x\n",
747                 hcd->description,  dev->slot_name, hcd->state);
748
749         if (in_interrupt ()) BUG ();
750
751         hub = hcd->bus->root_hub;
752         hcd->state = USB_STATE_QUIESCING;
753
754         dbg ("%s: roothub graceful disconnect", hcd->bus->bus_name);
755         usb_disconnect (&hub);
756         // usb_disconnect (&hcd->bus->root_hub);
757
758         hcd->driver->stop (hcd);
759         hcd->state = USB_STATE_HALT;
760
761         free_irq (hcd->irq, hcd);
762         if (hcd->driver->flags & HCD_MEMORY) {
763                 iounmap (hcd->regs);
764                 release_mem_region (pci_resource_start (dev, 0),
765                         pci_resource_len (dev, 0));
766         } else {
767                 release_region (pci_resource_start (dev, hcd->region),
768                         pci_resource_len (dev, hcd->region));
769         }
770
771         down (&hcd_list_lock);
772         list_del (&hcd->hcd_list);
773         up (&hcd_list_lock);
774
775         usb_deregister_bus (hcd->bus);
776         usb_free_bus (hcd->bus);
777         hcd->bus = NULL;
778
779         hcd->driver->hcd_free (hcd);
780 }
781 EXPORT_SYMBOL (usb_hcd_pci_remove);
782
783
784 #ifdef  CONFIG_PM
785
786 /*
787  * Some "sleep" power levels imply updating struct usb_driver
788  * to include a callback asking hcds to do their bit by checking
789  * if all the drivers can suspend.  Gets involved with remote wakeup.
790  *
791  * If there are pending urbs, then HCs will need to access memory,
792  * causing extra power drain.  New sleep()/wakeup() PM calls might
793  * be needed, beyond PCI suspend()/resume().  The root hub timer
794  * still be accessing memory though ...
795  *
796  * FIXME:  USB should have some power budgeting support working with
797  * all kinds of hubs.
798  *
799  * FIXME:  This assumes only D0->D3 suspend and D3->D0 resume.
800  * D1 and D2 states should do something, yes?
801  *
802  * FIXME:  Should provide generic enable_wake(), calling pci_enable_wake()
803  * for all supported states, so that USB remote wakeup can work for any
804  * devices that support it (and are connected via powered hubs).
805  *
806  * FIXME:  resume doesn't seem to work right any more...
807  */
808
809
810 // 2.4 kernels have issued concurrent resumes (w/APM)
811 // we defend against that error; PCI doesn't yet.
812
813 /**
814  * usb_hcd_pci_suspend - power management suspend of a PCI-based HCD
815  * @dev: USB Host Controller being suspended
816  *
817  * Store this function in the HCD's struct pci_driver as suspend().
818  */
819 int usb_hcd_pci_suspend (struct pci_dev *dev, u32 state)
820 {
821         struct usb_hcd          *hcd;
822         int                     retval;
823
824         hcd = pci_get_drvdata(dev);
825         printk (KERN_INFO "%s %s: suspend to state %d\n",
826                 hcd->description,  dev->slot_name, state);
827
828         pci_save_state (dev, hcd->pci_state);
829
830         // FIXME for all connected devices, leaf-to-root:
831         // driver->suspend()
832         // proposed "new 2.5 driver model" will automate that
833
834         /* driver may want to disable DMA etc */
835         retval = hcd->driver->suspend (hcd, state);
836         hcd->state = USB_STATE_SUSPENDED;
837
838         pci_set_power_state (dev, state);
839         return retval;
840 }
841 EXPORT_SYMBOL (usb_hcd_pci_suspend);
842
843 /**
844  * usb_hcd_pci_resume - power management resume of a PCI-based HCD
845  * @dev: USB Host Controller being resumed
846  *
847  * Store this function in the HCD's struct pci_driver as resume().
848  */
849 int usb_hcd_pci_resume (struct pci_dev *dev)
850 {
851         struct usb_hcd          *hcd;
852         int                     retval;
853
854         hcd = pci_get_drvdata(dev);
855         printk (KERN_INFO "%s %s: resume\n",
856                 hcd->description,  dev->slot_name);
857
858         /* guard against multiple resumes (APM bug?) */
859         atomic_inc (&hcd->resume_count);
860         if (atomic_read (&hcd->resume_count) != 1) {
861                 err ("concurrent PCI resumes for %s", hcd->bus->bus_name);
862                 retval = 0;
863                 goto done;
864         }
865
866         retval = -EBUSY;
867         if (hcd->state != USB_STATE_SUSPENDED) {
868                 dbg ("can't resume, not suspended!");
869                 goto done;
870         }
871         hcd->state = USB_STATE_RESUMING;
872
873         pci_set_power_state (dev, 0);
874         pci_restore_state (dev, hcd->pci_state);
875
876         retval = hcd->driver->resume (hcd);
877         if (!HCD_IS_RUNNING (hcd->state)) {
878                 dbg ("resume %s failure, retval %d",
879                         hcd->bus->bus_name, retval);
880                 hc_died (hcd);
881 // FIXME:  recover, reset etc.
882         } else {
883                 // FIXME for all connected devices, root-to-leaf:
884                 // driver->resume ();
885                 // proposed "new 2.5 driver model" will automate that
886         }
887
888 done:
889         atomic_dec (&hcd->resume_count);
890         return retval;
891 }
892 EXPORT_SYMBOL (usb_hcd_pci_resume);
893
894 #endif  /* CONFIG_PM */
895
896 #endif
897
898 /*-------------------------------------------------------------------------*/
899
900 /*
901  * Generic HC operations.
902  */
903
904 /*-------------------------------------------------------------------------*/
905
906 /* called from khubd, or root hub init threads for hcd-private init */
907 static int hcd_alloc_dev (struct usb_device *udev)
908 {
909         struct hcd_dev          *dev;
910         struct usb_hcd          *hcd;
911         unsigned long           flags;
912
913         if (!udev || udev->hcpriv)
914                 return -EINVAL;
915         if (!udev->bus || !udev->bus->hcpriv)
916                 return -ENODEV;
917         hcd = udev->bus->hcpriv;
918         if (hcd->state == USB_STATE_QUIESCING)
919                 return -ENOLINK;
920
921         dev = (struct hcd_dev *) kmalloc (sizeof *dev, GFP_KERNEL);
922         if (dev == NULL)
923                 return -ENOMEM;
924         memset (dev, 0, sizeof *dev);
925
926         INIT_LIST_HEAD (&dev->dev_list);
927         INIT_LIST_HEAD (&dev->urb_list);
928
929         spin_lock_irqsave (&hcd_data_lock, flags);
930         list_add (&dev->dev_list, &hcd->dev_list);
931         // refcount is implicit
932         udev->hcpriv = dev;
933         spin_unlock_irqrestore (&hcd_data_lock, flags);
934
935         return 0;
936 }
937
938 /*-------------------------------------------------------------------------*/
939
940 static void hcd_panic (void *_hcd)
941 {
942         struct usb_hcd *hcd = _hcd;
943         hcd->driver->stop (hcd);
944 }
945
946 static void hc_died (struct usb_hcd *hcd)
947 {
948         struct list_head        *devlist, *urblist;
949         struct hcd_dev          *dev;
950         struct urb              *urb;
951         unsigned long           flags;
952         
953         /* flag every pending urb as done */
954         spin_lock_irqsave (&hcd_data_lock, flags);
955         list_for_each (devlist, &hcd->dev_list) {
956                 dev = list_entry (devlist, struct hcd_dev, dev_list);
957                 list_for_each (urblist, &dev->urb_list) {
958                         urb = list_entry (urblist, struct urb, urb_list);
959                         dbg ("shutdown %s urb %p pipe %x, current status %d",
960                                 hcd->bus->bus_name,
961                                 urb, urb->pipe, urb->status);
962                         if (urb->status == -EINPROGRESS)
963                                 urb->status = -ESHUTDOWN;
964                 }
965         }
966         urb = (struct urb *) hcd->rh_timer.data;
967         if (urb)
968                 urb->status = -ESHUTDOWN;
969         spin_unlock_irqrestore (&hcd_data_lock, flags);
970
971         if (urb)
972                 rh_status_dequeue (hcd, urb);
973
974         /* hcd->stop() needs a task context */
975         INIT_TQUEUE (&hcd->work, hcd_panic, hcd);
976         (void) schedule_task (&hcd->work);
977 }
978
979 /*-------------------------------------------------------------------------*/
980
981 static void urb_unlink (struct urb *urb)
982 {
983         unsigned long           flags;
984         struct usb_device       *dev;
985
986         /* Release any periodic transfer bandwidth */
987         if (urb->bandwidth)
988                 usb_release_bandwidth (urb->dev, urb,
989                         usb_pipeisoc (urb->pipe));
990
991         /* clear all state linking urb to this dev (and hcd) */
992
993         spin_lock_irqsave (&hcd_data_lock, flags);
994         list_del_init (&urb->urb_list);
995         dev = urb->dev;
996         urb->dev = NULL;
997         usb_dec_dev_use (dev);
998         spin_unlock_irqrestore (&hcd_data_lock, flags);
999 }
1000
1001
1002 /* may be called in any context with a valid urb->dev usecount */
1003 /* caller surrenders "ownership" of urb */
1004
1005 static int hcd_submit_urb (struct urb *urb)
1006 {
1007         int                     status;
1008         struct usb_hcd          *hcd;
1009         struct hcd_dev          *dev;
1010         unsigned long           flags;
1011         int                     pipe, temp, max;
1012         int                     mem_flags;
1013
1014         if (!urb || urb->hcpriv || !urb->complete)
1015                 return -EINVAL;
1016
1017         urb->status = -EINPROGRESS;
1018         urb->actual_length = 0;
1019         urb->bandwidth = 0;
1020         INIT_LIST_HEAD (&urb->urb_list);
1021
1022         if (!urb->dev || !urb->dev->bus || urb->dev->devnum <= 0)
1023                 return -ENODEV;
1024         hcd = urb->dev->bus->hcpriv;
1025         dev = urb->dev->hcpriv;
1026         if (!hcd || !dev)
1027                 return -ENODEV;
1028
1029         /* can't submit new urbs when quiescing, halted, ... */
1030         if (hcd->state == USB_STATE_QUIESCING || !HCD_IS_RUNNING (hcd->state))
1031                 return -ESHUTDOWN;
1032         pipe = urb->pipe;
1033         temp = usb_pipetype (urb->pipe);
1034         if (usb_endpoint_halted (urb->dev, usb_pipeendpoint (pipe),
1035                         usb_pipeout (pipe)))
1036                 return -EPIPE;
1037
1038         /* NOTE: 2.5 passes this value explicitly in submit() */
1039         mem_flags = GFP_ATOMIC;
1040
1041         /* FIXME there should be a sharable lock protecting us against
1042          * config/altsetting changes and disconnects, kicking in here.
1043          */
1044
1045         /* Sanity check, so HCDs can rely on clean data */
1046         max = usb_maxpacket (urb->dev, pipe, usb_pipeout (pipe));
1047         if (max <= 0) {
1048                 err ("bogus endpoint (bad maxpacket)");
1049                 return -EINVAL;
1050         }
1051
1052         /* "high bandwidth" mode, 1-3 packets/uframe? */
1053         if (urb->dev->speed == USB_SPEED_HIGH) {
1054                 int     mult;
1055                 switch (temp) {
1056                 case PIPE_ISOCHRONOUS:
1057                 case PIPE_INTERRUPT:
1058                         mult = 1 + ((max >> 11) & 0x03);
1059                         max &= 0x03ff;
1060                         max *= mult;
1061                 }
1062         }
1063
1064         /* periodic transfers limit size per frame/uframe */
1065         switch (temp) {
1066         case PIPE_ISOCHRONOUS: {
1067                 int     n, len;
1068
1069                 if (urb->number_of_packets <= 0)                    
1070                         return -EINVAL;
1071                 for (n = 0; n < urb->number_of_packets; n++) {
1072                         len = urb->iso_frame_desc [n].length;
1073                         if (len < 0 || len > max) 
1074                                 return -EINVAL;
1075                 }
1076
1077                 }
1078                 break;
1079         case PIPE_INTERRUPT:
1080                 if (urb->transfer_buffer_length > max)
1081                         return -EINVAL;
1082         }
1083
1084         /* the I/O buffer must usually be mapped/unmapped */
1085         if (urb->transfer_buffer_length < 0)
1086                 return -EINVAL;
1087
1088         if (urb->next) {
1089                 warn ("use explicit queuing not urb->next");
1090                 return -EINVAL;
1091         }
1092
1093 #ifdef DEBUG
1094         /* stuff that drivers shouldn't do, but which shouldn't
1095          * cause problems in HCDs if they get it wrong.
1096          */
1097         {
1098         unsigned int    orig_flags = urb->transfer_flags;
1099         unsigned int    allowed;
1100
1101         /* enforce simple/standard policy */
1102         allowed = USB_ASYNC_UNLINK;     // affects later unlinks
1103         allowed |= USB_NO_FSBR;         // only affects UHCI
1104         switch (temp) {
1105         case PIPE_CONTROL:
1106                 allowed |= USB_DISABLE_SPD;
1107                 break;
1108         case PIPE_BULK:
1109                 allowed |= USB_DISABLE_SPD | USB_QUEUE_BULK
1110                                 | USB_ZERO_PACKET | URB_NO_INTERRUPT;
1111                 break;
1112         case PIPE_INTERRUPT:
1113                 allowed |= USB_DISABLE_SPD;
1114                 break;
1115         case PIPE_ISOCHRONOUS:
1116                 allowed |= USB_ISO_ASAP;
1117                 break;
1118         }
1119         urb->transfer_flags &= allowed;
1120
1121         /* fail if submitter gave bogus flags */
1122         if (urb->transfer_flags != orig_flags) {
1123                 err ("BOGUS urb flags, %x --> %x",
1124                         orig_flags, urb->transfer_flags);
1125                 return -EINVAL;
1126         }
1127         }
1128 #endif
1129         /*
1130          * Force periodic transfer intervals to be legal values that are
1131          * a power of two (so HCDs don't need to).
1132          *
1133          * FIXME want bus->{intr,iso}_sched_horizon values here.  Each HC
1134          * supports different values... this uses EHCI/UHCI defaults (and
1135          * EHCI can use smaller non-default values).
1136          */
1137         switch (temp) {
1138         case PIPE_ISOCHRONOUS:
1139         case PIPE_INTERRUPT:
1140                 /* too small? */
1141                 if (urb->interval <= 0)
1142                         return -EINVAL;
1143                 /* too big? */
1144                 switch (urb->dev->speed) {
1145                 case USB_SPEED_HIGH:    /* units are microframes */
1146                         // NOTE usb handles 2^15
1147                         if (urb->interval > (1024 * 8))
1148                                 urb->interval = 1024 * 8;
1149                         temp = 1024 * 8;
1150                         break;
1151                 case USB_SPEED_FULL:    /* units are frames/msec */
1152                 case USB_SPEED_LOW:
1153                         if (temp == PIPE_INTERRUPT) {
1154                                 if (urb->interval > 255)
1155                                         return -EINVAL;
1156                                 // NOTE ohci only handles up to 32
1157                                 temp = 128;
1158                         } else {
1159                                 if (urb->interval > 1024)
1160                                         urb->interval = 1024;
1161                                 // NOTE usb and ohci handle up to 2^15
1162                                 temp = 1024;
1163                         }
1164                         break;
1165                 default:
1166                         return -EINVAL;
1167                 }
1168                 /* power of two? */
1169                 while (temp > urb->interval)
1170                         temp >>= 1;
1171                 urb->interval = temp;
1172         }
1173
1174
1175         /*
1176          * FIXME:  make urb timeouts be generic, keeping the HCD cores
1177          * as simple as possible.
1178          */
1179
1180         // NOTE:  a generic device/urb monitoring hook would go here.
1181         // hcd_monitor_hook(MONITOR_URB_SUBMIT, urb)
1182         // It would catch submission paths for all urbs.
1183
1184         /*
1185          * Atomically queue the urb,  first to our records, then to the HCD.
1186          * Access to urb->status is controlled by urb->lock ... changes on
1187          * i/o completion (normal or fault) or unlinking.
1188          */
1189
1190         // FIXME:  verify that quiescing hc works right (RH cleans up)
1191
1192         spin_lock_irqsave (&hcd_data_lock, flags);
1193         if (HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_QUIESCING) {
1194                 usb_inc_dev_use (urb->dev);
1195                 list_add (&urb->urb_list, &dev->urb_list);
1196                 status = 0;
1197         } else {
1198                 INIT_LIST_HEAD (&urb->urb_list);
1199                 status = -ESHUTDOWN;
1200         }
1201         spin_unlock_irqrestore (&hcd_data_lock, flags);
1202         if (status)
1203                 return status;
1204
1205         // NOTE:  2.5 does this if !URB_NO_DMA_MAP transfer flag
1206         
1207         /* For 2.4, don't map bounce buffer if it's a root hub operation. */
1208         if (urb->dev == hcd->bus->root_hub) {
1209                 status = rh_urb_enqueue (hcd, urb);
1210         } else {
1211                 if (usb_pipecontrol (urb->pipe))
1212                         urb->setup_dma = pci_map_single (
1213                                         hcd->pdev,
1214                                         urb->setup_packet,
1215                                         sizeof (struct usb_ctrlrequest),
1216                                         PCI_DMA_TODEVICE);
1217                 if (urb->transfer_buffer_length != 0)
1218                         urb->transfer_dma = pci_map_single (
1219                                         hcd->pdev,
1220                                         urb->transfer_buffer,
1221                                         urb->transfer_buffer_length,
1222                                         usb_pipein (urb->pipe)
1223                                             ? PCI_DMA_FROMDEVICE
1224                                             : PCI_DMA_TODEVICE);
1225                 status = hcd->driver->urb_enqueue (hcd, urb, mem_flags);
1226         }
1227         return status;
1228 }
1229
1230 /*-------------------------------------------------------------------------*/
1231
1232 /* called in any context */
1233 static int hcd_get_frame_number (struct usb_device *udev)
1234 {
1235         struct usb_hcd  *hcd = (struct usb_hcd *)udev->bus->hcpriv;
1236         return hcd->driver->get_frame_number (hcd);
1237 }
1238
1239 /*-------------------------------------------------------------------------*/
1240
1241 struct completion_splice {              // modified urb context:
1242         /* did we complete? */
1243         struct completion       done;
1244
1245         /* original urb data */
1246         void                    (*complete)(struct urb *);
1247         void                    *context;
1248 };
1249
1250 static void unlink_complete (struct urb *urb)
1251 {
1252         struct completion_splice        *splice;
1253
1254         splice = (struct completion_splice *) urb->context;
1255
1256         /* issue original completion call */
1257         urb->complete = splice->complete;
1258         urb->context = splice->context;
1259         urb->complete (urb);
1260
1261         /* then let the synchronous unlink call complete */
1262         complete (&splice->done);
1263 }
1264
1265 /*
1266  * called in any context; note ASYNC_UNLINK restrictions
1267  *
1268  * caller guarantees urb won't be recycled till both unlink()
1269  * and the urb's completion function return
1270  */
1271 static int hcd_unlink_urb (struct urb *urb)
1272 {
1273         struct hcd_dev                  *dev;
1274         struct usb_hcd                  *hcd = 0;
1275         unsigned long                   flags;
1276         struct completion_splice        splice;
1277         int                             retval;
1278
1279         if (!urb)
1280                 return -EINVAL;
1281
1282         /*
1283          * we contend for urb->status with the hcd core,
1284          * which changes it while returning the urb.
1285          *
1286          * Caller guaranteed that the urb pointer hasn't been freed, and
1287          * that it was submitted.  But as a rule it can't know whether or
1288          * not it's already been unlinked ... so we respect the reversed
1289          * lock sequence needed for the usb_hcd_giveback_urb() code paths
1290          * (urb lock, then hcd_data_lock) in case some other CPU is now
1291          * unlinking it.
1292          */
1293         spin_lock_irqsave (&urb->lock, flags);
1294         spin_lock (&hcd_data_lock);
1295         if (!urb->hcpriv || urb->transfer_flags & USB_TIMEOUT_KILLED) {
1296                 retval = -EINVAL;
1297                 goto done;
1298         }
1299
1300         if (!urb->dev || !urb->dev->bus) {
1301                 retval = -ENODEV;
1302                 goto done;
1303         }
1304
1305         /* giveback clears dev; non-null means it's linked at this level */
1306         dev = urb->dev->hcpriv;
1307         hcd = urb->dev->bus->hcpriv;
1308         if (!dev || !hcd) {
1309                 retval = -ENODEV;
1310                 goto done;
1311         }
1312
1313         /* Any status except -EINPROGRESS means the HCD has already started
1314          * to return this URB to the driver.  In that case, there's no
1315          * more work for us to do.
1316          *
1317          * There's much magic because of "automagic resubmit" of interrupt
1318          * transfers, stopped only by explicit unlinking.  We won't issue
1319          * an "it's unlinked" callback more than once, but device drivers
1320          * can need to retry (SMP, -EAGAIN) an unlink request as well as
1321          * fake out the "not yet completed" state (set -EINPROGRESS) if
1322          * unlinking from complete().  Automagic eventually vanishes.
1323          *
1324          * FIXME use an URB_UNLINKED flag to match URB_TIMEOUT_KILLED
1325          */
1326         if (urb->status != -EINPROGRESS) {
1327                 if (usb_pipetype (urb->pipe) == PIPE_INTERRUPT)
1328                         retval = -EAGAIN;
1329                 else
1330                         retval = -EBUSY;
1331                 goto done;
1332         }
1333
1334         /* maybe set up to block on completion notification */
1335         if ((urb->transfer_flags & USB_TIMEOUT_KILLED))
1336                 urb->status = -ETIMEDOUT;
1337         else if (!(urb->transfer_flags & USB_ASYNC_UNLINK)) {
1338                 if (in_interrupt ()) {
1339                         dbg ("non-async unlink in_interrupt");
1340                         retval = -EWOULDBLOCK;
1341                         goto done;
1342                 }
1343                 /* synchronous unlink: block till we see the completion */
1344                 init_completion (&splice.done);
1345                 splice.complete = urb->complete;
1346                 splice.context = urb->context;
1347                 urb->complete = unlink_complete;
1348                 urb->context = &splice;
1349                 urb->status = -ENOENT;
1350         } else {
1351                 /* asynchronous unlink */
1352                 urb->status = -ECONNRESET;
1353         }
1354         spin_unlock (&hcd_data_lock);
1355         spin_unlock_irqrestore (&urb->lock, flags);
1356
1357         if (urb == (struct urb *) hcd->rh_timer.data) {
1358                 rh_status_dequeue (hcd, urb);
1359                 retval = 0;
1360         } else {
1361                 retval = hcd->driver->urb_dequeue (hcd, urb);
1362 // FIXME:  if retval and we tried to splice, whoa!!
1363 if (retval && urb->status == -ENOENT) err ("whoa! retval %d", retval);
1364         }
1365
1366         /* block till giveback, if needed */
1367         if (!(urb->transfer_flags & (USB_ASYNC_UNLINK|USB_TIMEOUT_KILLED))
1368                         && HCD_IS_RUNNING (hcd->state)
1369                         && !retval) {
1370                 wait_for_completion (&splice.done);
1371         } else if ((urb->transfer_flags & USB_ASYNC_UNLINK) && retval == 0) {
1372                 return -EINPROGRESS;
1373         }
1374         goto bye;
1375 done:
1376         spin_unlock (&hcd_data_lock);
1377         spin_unlock_irqrestore (&urb->lock, flags);
1378 bye:
1379         if (retval)
1380                 dbg ("%s: hcd_unlink_urb fail %d",
1381                     hcd ? hcd->bus->bus_name : "(no bus?)",
1382                     retval);
1383         return retval;
1384 }
1385
1386 /*-------------------------------------------------------------------------*/
1387
1388 /* called by khubd, rmmod, apmd, or other thread for hcd-private cleanup */
1389
1390 // FIXME:  likely best to have explicit per-setting (config+alt)
1391 // setup primitives in the usbcore-to-hcd driver API, so nothing
1392 // is implicit.  kernel 2.5 needs a bunch of config cleanup...
1393
1394 static int hcd_free_dev (struct usb_device *udev)
1395 {
1396         struct hcd_dev          *dev;
1397         struct usb_hcd          *hcd;
1398         unsigned long           flags;
1399
1400         if (!udev || !udev->hcpriv)
1401                 return -EINVAL;
1402
1403         if (!udev->bus || !udev->bus->hcpriv)
1404                 return -ENODEV;
1405
1406         // should udev->devnum == -1 ??
1407
1408         dev = udev->hcpriv;
1409         hcd = udev->bus->hcpriv;
1410
1411         /* device driver problem with refcounts? */
1412         if (!list_empty (&dev->urb_list)) {
1413                 dbg ("free busy dev, %s devnum %d (bug!)",
1414                         hcd->bus->bus_name, udev->devnum);
1415                 return -EINVAL;
1416         }
1417
1418         hcd->driver->free_config (hcd, udev);
1419
1420         spin_lock_irqsave (&hcd_data_lock, flags);
1421         list_del (&dev->dev_list);
1422         udev->hcpriv = NULL;
1423         spin_unlock_irqrestore (&hcd_data_lock, flags);
1424
1425         kfree (dev);
1426         return 0;
1427 }
1428
1429 static struct usb_operations hcd_operations = {
1430         allocate:               hcd_alloc_dev,
1431         get_frame_number:       hcd_get_frame_number,
1432         submit_urb:             hcd_submit_urb,
1433         unlink_urb:             hcd_unlink_urb,
1434         deallocate:             hcd_free_dev,
1435 };
1436
1437 /*-------------------------------------------------------------------------*/
1438
1439 static void hcd_irq (int irq, void *__hcd, struct pt_regs * r)
1440 {
1441         struct usb_hcd          *hcd = __hcd;
1442         int                     start = hcd->state;
1443
1444         if (unlikely (hcd->state == USB_STATE_HALT))    /* irq sharing? */
1445                 return;
1446
1447         hcd->driver->irq (hcd, r);
1448         if (hcd->state != start && hcd->state == USB_STATE_HALT)
1449                 hc_died (hcd);
1450 }
1451
1452 /*-------------------------------------------------------------------------*/
1453
1454 /**
1455  * usb_hcd_giveback_urb - return URB from HCD to device driver
1456  * @hcd: host controller returning the URB
1457  * @urb: urb being returned to the USB device driver.
1458  * @regs: saved hardware registers (ignored on 2.4 kernels)
1459  * Context: in_interrupt()
1460  *
1461  * This hands the URB from HCD to its USB device driver, using its
1462  * completion function.  The HCD has freed all per-urb resources
1463  * (and is done using urb->hcpriv).  It also released all HCD locks;
1464  * the device driver won't cause deadlocks if it resubmits this URB,
1465  * and won't confuse things by modifying and resubmitting this one.
1466  * Bandwidth and other resources will be deallocated.
1467  *
1468  * HCDs must not use this for periodic URBs that are still scheduled
1469  * and will be reissued.  They should just call their completion handlers
1470  * until the urb is returned to the device driver by unlinking.
1471  *
1472  * NOTE that no urb->next processing is done, even for isochronous URBs.
1473  * ISO streaming functionality can be achieved by having completion handlers
1474  * re-queue URBs.  Such explicit queuing doesn't discard error reports.
1475  */
1476 void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb, struct pt_regs *regs)
1477 {
1478         int is_root_hub_operation;
1479
1480         /* Work this out here as urb_unlink clears urb->dev */
1481         is_root_hub_operation = (urb->dev == hcd->bus->root_hub);
1482
1483         urb_unlink (urb);
1484
1485         // NOTE:  a generic device/urb monitoring hook would go here.
1486         // hcd_monitor_hook(MONITOR_URB_FINISH, urb, dev)
1487         // It would catch exit/unlink paths for all urbs, but non-exit
1488         // completions for periodic urbs need hooks inside the HCD.
1489         // hcd_monitor_hook(MONITOR_URB_UPDATE, urb, dev)
1490
1491         // NOTE:  2.5 does this if !URB_NO_DMA_MAP transfer flag
1492         
1493         /* For 2.4, don't unmap bounce buffer if it's a root hub operation. */
1494         if (usb_pipecontrol (urb->pipe) && !is_root_hub_operation)
1495                 pci_unmap_single (hcd->pdev, urb->setup_dma,
1496                                 sizeof (struct usb_ctrlrequest),
1497                                 PCI_DMA_TODEVICE);
1498
1499         if ((urb->transfer_buffer_length != 0) && !is_root_hub_operation)
1500                 pci_unmap_single (hcd->pdev, urb->transfer_dma,
1501                                 urb->transfer_buffer_length,
1502                                 usb_pipein (urb->pipe)
1503                                     ? PCI_DMA_FROMDEVICE
1504                                     : PCI_DMA_TODEVICE);
1505
1506         /* pass ownership to the completion handler */
1507         urb->complete (urb);
1508 }
1509 EXPORT_SYMBOL (usb_hcd_giveback_urb);