ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / usb / core / hcd.c
1 /*
2  * (C) Copyright Linus Torvalds 1999
3  * (C) Copyright Johannes Erdfelt 1999-2001
4  * (C) Copyright Andreas Gal 1999
5  * (C) Copyright Gregory P. Smith 1999
6  * (C) Copyright Deti Fliegl 1999
7  * (C) Copyright Randy Dunlap 2000
8  * (C) Copyright David Brownell 2000-2002
9  * 
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published by the
12  * Free Software Foundation; either version 2 of the License, or (at your
13  * option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18  * for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 #include <linux/config.h>
26
27 #ifdef CONFIG_USB_DEBUG
28 #define DEBUG
29 #endif
30
31 #include <linux/module.h>
32 #include <linux/version.h>
33 #include <linux/kernel.h>
34 #include <linux/slab.h>
35 #include <linux/completion.h>
36 #include <linux/uts.h>                  /* for UTS_SYSNAME */
37 #include <linux/mm.h>
38 #include <asm/io.h>
39 #include <asm/scatterlist.h>
40 #include <linux/device.h>
41 #include <linux/dma-mapping.h>
42 #include <asm/byteorder.h>
43
44 #include <linux/usb.h>
45
46 #include "usb.h"
47 #include "hcd.h"
48
49
50 // #define USB_BANDWIDTH_MESSAGES
51
52 /*-------------------------------------------------------------------------*/
53
54 /*
55  * USB Host Controller Driver framework
56  *
57  * Plugs into usbcore (usb_bus) and lets HCDs share code, minimizing
58  * HCD-specific behaviors/bugs.
59  *
60  * This does error checks, tracks devices and urbs, and delegates to a
61  * "hc_driver" only for code (and data) that really needs to know about
62  * hardware differences.  That includes root hub registers, i/o queues,
63  * and so on ... but as little else as possible.
64  *
65  * Shared code includes most of the "root hub" code (these are emulated,
66  * though each HC's hardware works differently) and PCI glue, plus request
67  * tracking overhead.  The HCD code should only block on spinlocks or on
68  * hardware handshaking; blocking on software events (such as other kernel
69  * threads releasing resources, or completing actions) is all generic.
70  *
71  * Happens the USB 2.0 spec says this would be invisible inside the "USBD",
72  * and includes mostly a "HCDI" (HCD Interface) along with some APIs used
73  * only by the hub driver ... and that neither should be seen or used by
74  * usb client device drivers.
75  *
76  * Contributors of ideas or unattributed patches include: David Brownell,
77  * Roman Weissgaerber, Rory Bolt, Greg Kroah-Hartman, ...
78  *
79  * HISTORY:
80  * 2002-02-21   Pull in most of the usb_bus support from usb.c; some
81  *              associated cleanup.  "usb_hcd" still != "usb_bus".
82  * 2001-12-12   Initial patch version for Linux 2.5.1 kernel.
83  */
84
85 /*-------------------------------------------------------------------------*/
86
87 /* host controllers we manage */
88 LIST_HEAD (usb_bus_list);
89 EXPORT_SYMBOL_GPL (usb_bus_list);
90
91 /* used when allocating bus numbers */
92 #define USB_MAXBUS              64
93 struct usb_busmap {
94         unsigned long busmap [USB_MAXBUS / (8*sizeof (unsigned long))];
95 };
96 static struct usb_busmap busmap;
97
98 /* used when updating list of hcds */
99 DECLARE_MUTEX (usb_bus_list_lock);      /* exported only for usbfs */
100 EXPORT_SYMBOL_GPL (usb_bus_list_lock);
101
102 /* used when updating hcd data */
103 static spinlock_t hcd_data_lock = SPIN_LOCK_UNLOCKED;
104
105 /*-------------------------------------------------------------------------*/
106
107 /*
108  * Sharable chunks of root hub code.
109  */
110
111 /*-------------------------------------------------------------------------*/
112
113 #define KERNEL_REL      ((LINUX_VERSION_CODE >> 16) & 0x0ff)
114 #define KERNEL_VER      ((LINUX_VERSION_CODE >> 8) & 0x0ff)
115
116 /* usb 2.0 root hub device descriptor */
117 static const u8 usb2_rh_dev_descriptor [18] = {
118         0x12,       /*  __u8  bLength; */
119         0x01,       /*  __u8  bDescriptorType; Device */
120         0x00, 0x02, /*  __u16 bcdUSB; v2.0 */
121
122         0x09,       /*  __u8  bDeviceClass; HUB_CLASSCODE */
123         0x00,       /*  __u8  bDeviceSubClass; */
124         0x01,       /*  __u8  bDeviceProtocol; [ usb 2.0 single TT ]*/
125         0x08,       /*  __u8  bMaxPacketSize0; 8 Bytes */
126
127         0x00, 0x00, /*  __u16 idVendor; */
128         0x00, 0x00, /*  __u16 idProduct; */
129         KERNEL_VER, KERNEL_REL, /*  __u16 bcdDevice */
130
131         0x03,       /*  __u8  iManufacturer; */
132         0x02,       /*  __u8  iProduct; */
133         0x01,       /*  __u8  iSerialNumber; */
134         0x01        /*  __u8  bNumConfigurations; */
135 };
136
137 /* no usb 2.0 root hub "device qualifier" descriptor: one speed only */
138
139 /* usb 1.1 root hub device descriptor */
140 static const u8 usb11_rh_dev_descriptor [18] = {
141         0x12,       /*  __u8  bLength; */
142         0x01,       /*  __u8  bDescriptorType; Device */
143         0x10, 0x01, /*  __u16 bcdUSB; v1.1 */
144
145         0x09,       /*  __u8  bDeviceClass; HUB_CLASSCODE */
146         0x00,       /*  __u8  bDeviceSubClass; */
147         0x00,       /*  __u8  bDeviceProtocol; [ low/full speeds only ] */
148         0x08,       /*  __u8  bMaxPacketSize0; 8 Bytes */
149
150         0x00, 0x00, /*  __u16 idVendor; */
151         0x00, 0x00, /*  __u16 idProduct; */
152         KERNEL_VER, KERNEL_REL, /*  __u16 bcdDevice */
153
154         0x03,       /*  __u8  iManufacturer; */
155         0x02,       /*  __u8  iProduct; */
156         0x01,       /*  __u8  iSerialNumber; */
157         0x01        /*  __u8  bNumConfigurations; */
158 };
159
160
161 /*-------------------------------------------------------------------------*/
162
163 /* Configuration descriptors for our root hubs */
164
165 static const u8 fs_rh_config_descriptor [] = {
166
167         /* one configuration */
168         0x09,       /*  __u8  bLength; */
169         0x02,       /*  __u8  bDescriptorType; Configuration */
170         0x19, 0x00, /*  __u16 wTotalLength; */
171         0x01,       /*  __u8  bNumInterfaces; (1) */
172         0x01,       /*  __u8  bConfigurationValue; */
173         0x00,       /*  __u8  iConfiguration; */
174         0x40,       /*  __u8  bmAttributes; 
175                                  Bit 7: Bus-powered,
176                                      6: Self-powered,
177                                      5 Remote-wakwup,
178                                      4..0: resvd */
179         0x00,       /*  __u8  MaxPower; */
180       
181         /* USB 1.1:
182          * USB 2.0, single TT organization (mandatory):
183          *      one interface, protocol 0
184          *
185          * USB 2.0, multiple TT organization (optional):
186          *      two interfaces, protocols 1 (like single TT)
187          *      and 2 (multiple TT mode) ... config is
188          *      sometimes settable
189          *      NOT IMPLEMENTED
190          */
191
192         /* one interface */
193         0x09,       /*  __u8  if_bLength; */
194         0x04,       /*  __u8  if_bDescriptorType; Interface */
195         0x00,       /*  __u8  if_bInterfaceNumber; */
196         0x00,       /*  __u8  if_bAlternateSetting; */
197         0x01,       /*  __u8  if_bNumEndpoints; */
198         0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
199         0x00,       /*  __u8  if_bInterfaceSubClass; */
200         0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
201         0x00,       /*  __u8  if_iInterface; */
202      
203         /* one endpoint (status change endpoint) */
204         0x07,       /*  __u8  ep_bLength; */
205         0x05,       /*  __u8  ep_bDescriptorType; Endpoint */
206         0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
207         0x03,       /*  __u8  ep_bmAttributes; Interrupt */
208         0x02, 0x00, /*  __u16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
209         0xff        /*  __u8  ep_bInterval; (255ms -- usb 2.0 spec) */
210 };
211
212 static const u8 hs_rh_config_descriptor [] = {
213
214         /* one configuration */
215         0x09,       /*  __u8  bLength; */
216         0x02,       /*  __u8  bDescriptorType; Configuration */
217         0x19, 0x00, /*  __u16 wTotalLength; */
218         0x01,       /*  __u8  bNumInterfaces; (1) */
219         0x01,       /*  __u8  bConfigurationValue; */
220         0x00,       /*  __u8  iConfiguration; */
221         0x40,       /*  __u8  bmAttributes; 
222                                  Bit 7: Bus-powered,
223                                      6: Self-powered,
224                                      5 Remote-wakwup,
225                                      4..0: resvd */
226         0x00,       /*  __u8  MaxPower; */
227       
228         /* USB 1.1:
229          * USB 2.0, single TT organization (mandatory):
230          *      one interface, protocol 0
231          *
232          * USB 2.0, multiple TT organization (optional):
233          *      two interfaces, protocols 1 (like single TT)
234          *      and 2 (multiple TT mode) ... config is
235          *      sometimes settable
236          *      NOT IMPLEMENTED
237          */
238
239         /* one interface */
240         0x09,       /*  __u8  if_bLength; */
241         0x04,       /*  __u8  if_bDescriptorType; Interface */
242         0x00,       /*  __u8  if_bInterfaceNumber; */
243         0x00,       /*  __u8  if_bAlternateSetting; */
244         0x01,       /*  __u8  if_bNumEndpoints; */
245         0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
246         0x00,       /*  __u8  if_bInterfaceSubClass; */
247         0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
248         0x00,       /*  __u8  if_iInterface; */
249      
250         /* one endpoint (status change endpoint) */
251         0x07,       /*  __u8  ep_bLength; */
252         0x05,       /*  __u8  ep_bDescriptorType; Endpoint */
253         0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
254         0x03,       /*  __u8  ep_bmAttributes; Interrupt */
255         0x02, 0x00, /*  __u16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
256         0x0c        /*  __u8  ep_bInterval; (256ms -- usb 2.0 spec) */
257 };
258
259 /*-------------------------------------------------------------------------*/
260
261 /*
262  * helper routine for returning string descriptors in UTF-16LE
263  * input can actually be ISO-8859-1; ASCII is its 7-bit subset
264  */
265 static int ascii2utf (char *s, u8 *utf, int utfmax)
266 {
267         int retval;
268
269         for (retval = 0; *s && utfmax > 1; utfmax -= 2, retval += 2) {
270                 *utf++ = *s++;
271                 *utf++ = 0;
272         }
273         return retval;
274 }
275
276 /*
277  * rh_string - provides manufacturer, product and serial strings for root hub
278  * @id: the string ID number (1: serial number, 2: product, 3: vendor)
279  * @hcd: the host controller for this root hub
280  * @type: string describing our driver 
281  * @data: return packet in UTF-16 LE
282  * @len: length of the return packet
283  *
284  * Produces either a manufacturer, product or serial number string for the
285  * virtual root hub device.
286  */
287 static int rh_string (
288         int             id,
289         struct usb_hcd  *hcd,
290         u8              *data,
291         int             len
292 ) {
293         char buf [100];
294
295         // language ids
296         if (id == 0) {
297                 *data++ = 4; *data++ = 3;       /* 4 bytes string data */
298                 *data++ = 0x09; *data++ = 0x04; /* MSFT-speak for "en-us" */
299                 return 4;
300
301         // serial number
302         } else if (id == 1) {
303                 strcpy (buf, hcd->self.bus_name);
304
305         // product description
306         } else if (id == 2) {
307                 strcpy (buf, hcd->product_desc);
308
309         // id 3 == vendor description
310         } else if (id == 3) {
311                 sprintf (buf, "%s %s %s", UTS_SYSNAME, UTS_RELEASE,
312                         hcd->description);
313
314         // unsupported IDs --> "protocol stall"
315         } else
316             return 0;
317
318         data [0] = 2 * (strlen (buf) + 1);
319         data [1] = 3;   /* type == string */
320         return 2 + ascii2utf (buf, data + 2, len - 2);
321 }
322
323
324 /* Root hub control transfers execute synchronously */
325 static int rh_call_control (struct usb_hcd *hcd, struct urb *urb)
326 {
327         struct usb_ctrlrequest *cmd = (struct usb_ctrlrequest *) urb->setup_packet;
328         u16             typeReq, wValue, wIndex, wLength;
329         const u8        *bufp = 0;
330         u8              *ubuf = urb->transfer_buffer;
331         int             len = 0;
332         unsigned long   flags;
333
334         typeReq  = (cmd->bRequestType << 8) | cmd->bRequest;
335         wValue   = le16_to_cpu (cmd->wValue);
336         wIndex   = le16_to_cpu (cmd->wIndex);
337         wLength  = le16_to_cpu (cmd->wLength);
338
339         if (wLength > urb->transfer_buffer_length)
340                 goto error;
341
342         /* set up for success */
343         urb->status = 0;
344         urb->actual_length = wLength;
345         switch (typeReq) {
346
347         /* DEVICE REQUESTS */
348
349         case DeviceRequest | USB_REQ_GET_STATUS:
350                 // DEVICE_REMOTE_WAKEUP
351                 ubuf [0] = 1; // selfpowered
352                 ubuf [1] = 0;
353                         /* FALLTHROUGH */
354         case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
355         case DeviceOutRequest | USB_REQ_SET_FEATURE:
356                 dev_dbg (hcd->self.controller, "no device features yet yet\n");
357                 break;
358         case DeviceRequest | USB_REQ_GET_CONFIGURATION:
359                 ubuf [0] = 1;
360                         /* FALLTHROUGH */
361         case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
362                 break;
363         case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
364                 switch (wValue & 0xff00) {
365                 case USB_DT_DEVICE << 8:
366                         if (hcd->driver->flags & HCD_USB2)
367                                 bufp = usb2_rh_dev_descriptor;
368                         else if (hcd->driver->flags & HCD_USB11)
369                                 bufp = usb11_rh_dev_descriptor;
370                         else
371                                 goto error;
372                         len = 18;
373                         break;
374                 case USB_DT_CONFIG << 8:
375                         if (hcd->driver->flags & HCD_USB2) {
376                                 bufp = hs_rh_config_descriptor;
377                                 len = sizeof hs_rh_config_descriptor;
378                         } else {
379                                 bufp = fs_rh_config_descriptor;
380                                 len = sizeof fs_rh_config_descriptor;
381                         }
382                         break;
383                 case USB_DT_STRING << 8:
384                         urb->actual_length = rh_string (
385                                 wValue & 0xff, hcd,
386                                 ubuf, wLength);
387                         break;
388                 default:
389                         goto error;
390                 }
391                 break;
392         case DeviceRequest | USB_REQ_GET_INTERFACE:
393                 ubuf [0] = 0;
394                         /* FALLTHROUGH */
395         case DeviceOutRequest | USB_REQ_SET_INTERFACE:
396                 break;
397         case DeviceOutRequest | USB_REQ_SET_ADDRESS:
398                 // wValue == urb->dev->devaddr
399                 dev_dbg (hcd->self.controller, "root hub device address %d\n",
400                         wValue);
401                 break;
402
403         /* INTERFACE REQUESTS (no defined feature/status flags) */
404
405         /* ENDPOINT REQUESTS */
406
407         case EndpointRequest | USB_REQ_GET_STATUS:
408                 // ENDPOINT_HALT flag
409                 ubuf [0] = 0;
410                 ubuf [1] = 0;
411                         /* FALLTHROUGH */
412         case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
413         case EndpointOutRequest | USB_REQ_SET_FEATURE:
414                 dev_dbg (hcd->self.controller, "no endpoint features yet\n");
415                 break;
416
417         /* CLASS REQUESTS (and errors) */
418
419         default:
420                 /* non-generic request */
421                 if (HCD_IS_SUSPENDED (hcd->state))
422                         urb->status = -EAGAIN;
423                 else if (!HCD_IS_RUNNING (hcd->state))
424                         urb->status = -ENODEV;
425                 else
426                         urb->status = hcd->driver->hub_control (hcd,
427                                 typeReq, wValue, wIndex,
428                                 ubuf, wLength);
429                 break;
430 error:
431                 /* "protocol stall" on error */
432                 urb->status = -EPIPE;
433                 dev_dbg (hcd->self.controller, "unsupported hub control message (maxchild %d)\n",
434                                 urb->dev->maxchild);
435         }
436         if (urb->status) {
437                 urb->actual_length = 0;
438                 dev_dbg (hcd->self.controller, "CTRL: TypeReq=0x%x val=0x%x idx=0x%x len=%d ==> %d\n",
439                         typeReq, wValue, wIndex, wLength, urb->status);
440         }
441         if (bufp) {
442                 if (urb->transfer_buffer_length < len)
443                         len = urb->transfer_buffer_length;
444                 urb->actual_length = len;
445                 // always USB_DIR_IN, toward host
446                 memcpy (ubuf, bufp, len);
447         }
448
449         /* any errors get returned through the urb completion */
450         local_irq_save (flags);
451         usb_hcd_giveback_urb (hcd, urb, NULL);
452         local_irq_restore (flags);
453         return 0;
454 }
455
456 /*-------------------------------------------------------------------------*/
457
458 /*
459  * Root Hub interrupt transfers are synthesized with a timer.
460  * Completions are called in_interrupt() but not in_irq().
461  */
462
463 static void rh_report_status (unsigned long ptr);
464
465 static int rh_status_urb (struct usb_hcd *hcd, struct urb *urb) 
466 {
467         int     len = 1 + (urb->dev->maxchild / 8);
468
469         /* rh_timer protected by hcd_data_lock */
470         if (hcd->rh_timer.data
471                         || urb->status != -EINPROGRESS
472                         || urb->transfer_buffer_length < len
473                         || !HCD_IS_RUNNING (hcd->state)) {
474                 dev_dbg (hcd->self.controller,
475                                 "not queuing rh status urb, stat %d\n",
476                                 urb->status);
477                 return -EINVAL;
478         }
479
480         init_timer (&hcd->rh_timer);
481         hcd->rh_timer.function = rh_report_status;
482         hcd->rh_timer.data = (unsigned long) urb;
483         /* USB 2.0 spec says 256msec; this is close enough */
484         hcd->rh_timer.expires = jiffies + HZ/4;
485         add_timer (&hcd->rh_timer);
486         urb->hcpriv = hcd;      /* nonzero to indicate it's queued */
487         return 0;
488 }
489
490 /* timer callback */
491
492 static void rh_report_status (unsigned long ptr)
493 {
494         struct urb      *urb;
495         struct usb_hcd  *hcd;
496         int             length = 0;
497         unsigned long   flags;
498
499         urb = (struct urb *) ptr;
500         local_irq_save (flags);
501         spin_lock (&urb->lock);
502
503         /* do nothing if the urb's been unlinked */
504         if (!urb->dev
505                         || urb->status != -EINPROGRESS
506                         || (hcd = urb->dev->bus->hcpriv) == 0) {
507                 spin_unlock (&urb->lock);
508                 local_irq_restore (flags);
509                 return;
510         }
511
512         if (!HCD_IS_SUSPENDED (hcd->state))
513                 length = hcd->driver->hub_status_data (
514                                         hcd, urb->transfer_buffer);
515
516         /* complete the status urb, or retrigger the timer */
517         spin_lock (&hcd_data_lock);
518         if (length > 0) {
519                 hcd->rh_timer.data = 0;
520                 urb->actual_length = length;
521                 urb->status = 0;
522                 urb->hcpriv = 0;
523         } else
524                 mod_timer (&hcd->rh_timer, jiffies + HZ/4);
525         spin_unlock (&hcd_data_lock);
526         spin_unlock (&urb->lock);
527
528         /* local irqs are always blocked in completions */
529         if (length > 0)
530                 usb_hcd_giveback_urb (hcd, urb, NULL);
531         local_irq_restore (flags);
532 }
533
534 /*-------------------------------------------------------------------------*/
535
536 static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
537 {
538         if (usb_pipeint (urb->pipe)) {
539                 int             retval;
540                 unsigned long   flags;
541
542                 spin_lock_irqsave (&hcd_data_lock, flags);
543                 retval = rh_status_urb (hcd, urb);
544                 spin_unlock_irqrestore (&hcd_data_lock, flags);
545                 return retval;
546         }
547         if (usb_pipecontrol (urb->pipe))
548                 return rh_call_control (hcd, urb);
549         else
550                 return -EINVAL;
551 }
552
553 /*-------------------------------------------------------------------------*/
554
555 void usb_rh_status_dequeue (struct usb_hcd *hcd, struct urb *urb)
556 {
557         unsigned long   flags;
558
559         /* note:  always a synchronous unlink */
560         del_timer_sync (&hcd->rh_timer);
561         hcd->rh_timer.data = 0;
562
563         local_irq_save (flags);
564         urb->hcpriv = 0;
565         usb_hcd_giveback_urb (hcd, urb, NULL);
566         local_irq_restore (flags);
567 }
568
569 /*-------------------------------------------------------------------------*/
570
571 /* exported only within usbcore */
572 struct usb_bus *usb_bus_get (struct usb_bus *bus)
573 {
574         struct class_device *tmp;
575
576         if (!bus)
577                 return NULL;
578
579         tmp = class_device_get(&bus->class_dev);
580         if (tmp)        
581                 return to_usb_bus(tmp);
582         else
583                 return NULL;
584 }
585
586 /* exported only within usbcore */
587 void usb_bus_put (struct usb_bus *bus)
588 {
589         if (bus)
590                 class_device_put(&bus->class_dev);
591 }
592
593 /*-------------------------------------------------------------------------*/
594
595 static void usb_host_release(struct class_device *class_dev)
596 {
597         struct usb_bus *bus = to_usb_bus(class_dev);
598
599         if (bus->release)
600                 bus->release(bus);
601 }
602
603 static struct class usb_host_class = {
604         .name           = "usb_host",
605         .release        = &usb_host_release,
606 };
607
608 void usb_host_init(void)
609 {
610         class_register(&usb_host_class);
611 }
612
613 void usb_host_cleanup(void)
614 {
615         class_unregister(&usb_host_class);
616 }
617
618 /**
619  * usb_bus_init - shared initialization code
620  * @bus: the bus structure being initialized
621  *
622  * This code is used to initialize a usb_bus structure, memory for which is
623  * separately managed.
624  */
625 void usb_bus_init (struct usb_bus *bus)
626 {
627         memset (&bus->devmap, 0, sizeof(struct usb_devmap));
628
629         bus->devnum_next = 1;
630
631         bus->root_hub = NULL;
632         bus->hcpriv = NULL;
633         bus->busnum = -1;
634         bus->bandwidth_allocated = 0;
635         bus->bandwidth_int_reqs  = 0;
636         bus->bandwidth_isoc_reqs = 0;
637
638         INIT_LIST_HEAD (&bus->bus_list);
639 }
640 EXPORT_SYMBOL (usb_bus_init);
641
642 /**
643  * usb_alloc_bus - creates a new USB host controller structure
644  * @op: pointer to a struct usb_operations that this bus structure should use
645  * Context: !in_interrupt()
646  *
647  * Creates a USB host controller bus structure with the specified 
648  * usb_operations and initializes all the necessary internal objects.
649  *
650  * If no memory is available, NULL is returned.
651  *
652  * The caller should call usb_put_bus() when it is finished with the structure.
653  */
654 struct usb_bus *usb_alloc_bus (struct usb_operations *op)
655 {
656         struct usb_bus *bus;
657
658         bus = kmalloc (sizeof *bus, GFP_KERNEL);
659         if (!bus)
660                 return NULL;
661         memset(bus, 0, sizeof(struct usb_bus));
662         usb_bus_init (bus);
663         bus->op = op;
664         return bus;
665 }
666 EXPORT_SYMBOL (usb_alloc_bus);
667
668 /*-------------------------------------------------------------------------*/
669
670 /**
671  * usb_register_bus - registers the USB host controller with the usb core
672  * @bus: pointer to the bus to register
673  * Context: !in_interrupt()
674  *
675  * Assigns a bus number, and links the controller into usbcore data
676  * structures so that it can be seen by scanning the bus list.
677  */
678 int usb_register_bus(struct usb_bus *bus)
679 {
680         int busnum;
681         int retval;
682
683         down (&usb_bus_list_lock);
684         busnum = find_next_zero_bit (busmap.busmap, USB_MAXBUS, 1);
685         if (busnum < USB_MAXBUS) {
686                 set_bit (busnum, busmap.busmap);
687                 bus->busnum = busnum;
688         } else {
689                 printk (KERN_ERR "%s: too many buses\n", usbcore_name);
690                 return -E2BIG;
691         }
692
693         snprintf(bus->class_dev.class_id, BUS_ID_SIZE, "usb%d", busnum);
694         bus->class_dev.class = &usb_host_class;
695         bus->class_dev.dev = bus->controller;
696         retval = class_device_register(&bus->class_dev);
697         if (retval) {
698                 clear_bit(busnum, busmap.busmap);
699                 up(&usb_bus_list_lock);
700                 return retval;
701         }
702
703         /* Add it to the local list of buses */
704         list_add (&bus->bus_list, &usb_bus_list);
705         up (&usb_bus_list_lock);
706
707         usbfs_add_bus (bus);
708
709         dev_info (bus->controller, "new USB bus registered, assigned bus number %d\n", bus->busnum);
710         return 0;
711 }
712 EXPORT_SYMBOL (usb_register_bus);
713
714 /**
715  * usb_deregister_bus - deregisters the USB host controller
716  * @bus: pointer to the bus to deregister
717  * Context: !in_interrupt()
718  *
719  * Recycles the bus number, and unlinks the controller from usbcore data
720  * structures so that it won't be seen by scanning the bus list.
721  */
722 void usb_deregister_bus (struct usb_bus *bus)
723 {
724         dev_info (bus->controller, "USB bus %d deregistered\n", bus->busnum);
725
726         /*
727          * NOTE: make sure that all the devices are removed by the
728          * controller code, as well as having it call this when cleaning
729          * itself up
730          */
731         down (&usb_bus_list_lock);
732         list_del (&bus->bus_list);
733         up (&usb_bus_list_lock);
734
735         usbfs_remove_bus (bus);
736
737         clear_bit (bus->busnum, busmap.busmap);
738
739         class_device_unregister(&bus->class_dev);
740 }
741 EXPORT_SYMBOL (usb_deregister_bus);
742
743 /**
744  * usb_register_root_hub - called by HCD to register its root hub 
745  * @usb_dev: the usb root hub device to be registered.
746  * @parent_dev: the parent device of this root hub.
747  *
748  * The USB host controller calls this function to register the root hub
749  * properly with the USB subsystem.  It sets up the device properly in
750  * the device model tree, and then calls usb_new_device() to register the
751  * usb device.  It also assigns the root hub's USB address (always 1).
752  */
753 int usb_register_root_hub (struct usb_device *usb_dev, struct device *parent_dev)
754 {
755         const int devnum = 1;
756         int retval;
757
758         usb_dev->devnum = devnum;
759         usb_dev->bus->devnum_next = devnum + 1;
760         memset (&usb_dev->bus->devmap.devicemap, 0,
761                         sizeof usb_dev->bus->devmap.devicemap);
762         set_bit (devnum, usb_dev->bus->devmap.devicemap);
763         usb_dev->state = USB_STATE_ADDRESS;
764
765         retval = usb_new_device (usb_dev);
766         if (retval)
767                 dev_err (parent_dev, "can't register root hub for %s, %d\n",
768                                 usb_dev->dev.bus_id, retval);
769         return retval;
770 }
771 EXPORT_SYMBOL (usb_register_root_hub);
772
773
774 /*-------------------------------------------------------------------------*/
775
776 /**
777  * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
778  * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
779  * @is_input: true iff the transaction sends data to the host
780  * @isoc: true for isochronous transactions, false for interrupt ones
781  * @bytecount: how many bytes in the transaction.
782  *
783  * Returns approximate bus time in nanoseconds for a periodic transaction.
784  * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
785  * scheduled in software, this function is only used for such scheduling.
786  */
787 long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
788 {
789         unsigned long   tmp;
790
791         switch (speed) {
792         case USB_SPEED_LOW:     /* INTR only */
793                 if (is_input) {
794                         tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
795                         return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
796                 } else {
797                         tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
798                         return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
799                 }
800         case USB_SPEED_FULL:    /* ISOC or INTR */
801                 if (isoc) {
802                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
803                         return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
804                 } else {
805                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
806                         return (9107L + BW_HOST_DELAY + tmp);
807                 }
808         case USB_SPEED_HIGH:    /* ISOC or INTR */
809                 // FIXME adjust for input vs output
810                 if (isoc)
811                         tmp = HS_USECS (bytecount);
812                 else
813                         tmp = HS_USECS_ISO (bytecount);
814                 return tmp;
815         default:
816                 pr_debug ("%s: bogus device speed!\n", usbcore_name);
817                 return -1;
818         }
819 }
820 EXPORT_SYMBOL (usb_calc_bus_time);
821
822 /*
823  * usb_check_bandwidth():
824  *
825  * old_alloc is from host_controller->bandwidth_allocated in microseconds;
826  * bustime is from calc_bus_time(), but converted to microseconds.
827  *
828  * returns <bustime in us> if successful,
829  * or -ENOSPC if bandwidth request fails.
830  *
831  * FIXME:
832  * This initial implementation does not use Endpoint.bInterval
833  * in managing bandwidth allocation.
834  * It probably needs to be expanded to use Endpoint.bInterval.
835  * This can be done as a later enhancement (correction).
836  *
837  * This will also probably require some kind of
838  * frame allocation tracking...meaning, for example,
839  * that if multiple drivers request interrupts every 10 USB frames,
840  * they don't all have to be allocated at
841  * frame numbers N, N+10, N+20, etc.  Some of them could be at
842  * N+11, N+21, N+31, etc., and others at
843  * N+12, N+22, N+32, etc.
844  *
845  * Similarly for isochronous transfers...
846  *
847  * Individual HCDs can schedule more directly ... this logic
848  * is not correct for high speed transfers.
849  */
850 int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
851 {
852         unsigned int    pipe = urb->pipe;
853         long            bustime;
854         int             is_in = usb_pipein (pipe);
855         int             is_iso = usb_pipeisoc (pipe);
856         int             old_alloc = dev->bus->bandwidth_allocated;
857         int             new_alloc;
858
859
860         bustime = NS_TO_US (usb_calc_bus_time (dev->speed, is_in, is_iso,
861                         usb_maxpacket (dev, pipe, !is_in)));
862         if (is_iso)
863                 bustime /= urb->number_of_packets;
864
865         new_alloc = old_alloc + (int) bustime;
866         if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC) {
867 #ifdef  DEBUG
868                 char    *mode = 
869 #ifdef CONFIG_USB_BANDWIDTH
870                         "";
871 #else
872                         "would have ";
873 #endif
874                 dev_dbg (&dev->dev, "usb_check_bandwidth %sFAILED: %d + %ld = %d usec\n",
875                         mode, old_alloc, bustime, new_alloc);
876 #endif
877 #ifdef CONFIG_USB_BANDWIDTH
878                 bustime = -ENOSPC;      /* report error */
879 #endif
880         }
881
882         return bustime;
883 }
884 EXPORT_SYMBOL (usb_check_bandwidth);
885
886
887 /**
888  * usb_claim_bandwidth - records bandwidth for a periodic transfer
889  * @dev: source/target of request
890  * @urb: request (urb->dev == dev)
891  * @bustime: bandwidth consumed, in (average) microseconds per frame
892  * @isoc: true iff the request is isochronous
893  *
894  * Bus bandwidth reservations are recorded purely for diagnostic purposes.
895  * HCDs are expected not to overcommit periodic bandwidth, and to record such
896  * reservations whenever endpoints are added to the periodic schedule.
897  *
898  * FIXME averaging per-frame is suboptimal.  Better to sum over the HCD's
899  * entire periodic schedule ... 32 frames for OHCI, 1024 for UHCI, settable
900  * for EHCI (256/512/1024 frames, default 1024) and have the bus expose how
901  * large its periodic schedule is.
902  */
903 void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
904 {
905         dev->bus->bandwidth_allocated += bustime;
906         if (isoc)
907                 dev->bus->bandwidth_isoc_reqs++;
908         else
909                 dev->bus->bandwidth_int_reqs++;
910         urb->bandwidth = bustime;
911
912 #ifdef USB_BANDWIDTH_MESSAGES
913         dev_dbg (&dev->dev, "bandwidth alloc increased by %d (%s) to %d for %d requesters\n",
914                 bustime,
915                 isoc ? "ISOC" : "INTR",
916                 dev->bus->bandwidth_allocated,
917                 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
918 #endif
919 }
920 EXPORT_SYMBOL (usb_claim_bandwidth);
921
922
923 /**
924  * usb_release_bandwidth - reverses effect of usb_claim_bandwidth()
925  * @dev: source/target of request
926  * @urb: request (urb->dev == dev)
927  * @isoc: true iff the request is isochronous
928  *
929  * This records that previously allocated bandwidth has been released.
930  * Bandwidth is released when endpoints are removed from the host controller's
931  * periodic schedule.
932  */
933 void usb_release_bandwidth (struct usb_device *dev, struct urb *urb, int isoc)
934 {
935         dev->bus->bandwidth_allocated -= urb->bandwidth;
936         if (isoc)
937                 dev->bus->bandwidth_isoc_reqs--;
938         else
939                 dev->bus->bandwidth_int_reqs--;
940
941 #ifdef USB_BANDWIDTH_MESSAGES
942         dev_dbg (&dev->dev, "bandwidth alloc reduced by %d (%s) to %d for %d requesters\n",
943                 urb->bandwidth,
944                 isoc ? "ISOC" : "INTR",
945                 dev->bus->bandwidth_allocated,
946                 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
947 #endif
948         urb->bandwidth = 0;
949 }
950 EXPORT_SYMBOL (usb_release_bandwidth);
951
952
953 /*-------------------------------------------------------------------------*/
954
955 /*
956  * Generic HC operations.
957  */
958
959 /*-------------------------------------------------------------------------*/
960
961 /* called from khubd, or root hub init threads for hcd-private init */
962 static int hcd_alloc_dev (struct usb_device *udev)
963 {
964         struct hcd_dev          *dev;
965         struct usb_hcd          *hcd;
966         unsigned long           flags;
967
968         if (!udev || udev->hcpriv)
969                 return -EINVAL;
970         if (!udev->bus || !udev->bus->hcpriv)
971                 return -ENODEV;
972         hcd = udev->bus->hcpriv;
973         if (hcd->state == USB_STATE_QUIESCING)
974                 return -ENOLINK;
975
976         dev = (struct hcd_dev *) kmalloc (sizeof *dev, GFP_KERNEL);
977         if (dev == NULL)
978                 return -ENOMEM;
979         memset (dev, 0, sizeof *dev);
980
981         INIT_LIST_HEAD (&dev->dev_list);
982         INIT_LIST_HEAD (&dev->urb_list);
983
984         spin_lock_irqsave (&hcd_data_lock, flags);
985         list_add (&dev->dev_list, &hcd->dev_list);
986         // refcount is implicit
987         udev->hcpriv = dev;
988         spin_unlock_irqrestore (&hcd_data_lock, flags);
989
990         return 0;
991 }
992
993 /*-------------------------------------------------------------------------*/
994
995 static void urb_unlink (struct urb *urb)
996 {
997         unsigned long           flags;
998         struct usb_device       *dev;
999
1000         /* Release any periodic transfer bandwidth */
1001         if (urb->bandwidth)
1002                 usb_release_bandwidth (urb->dev, urb,
1003                         usb_pipeisoc (urb->pipe));
1004
1005         /* clear all state linking urb to this dev (and hcd) */
1006
1007         spin_lock_irqsave (&hcd_data_lock, flags);
1008         list_del_init (&urb->urb_list);
1009         dev = urb->dev;
1010         spin_unlock_irqrestore (&hcd_data_lock, flags);
1011         usb_put_dev (dev);
1012 }
1013
1014
1015 /* may be called in any context with a valid urb->dev usecount
1016  * caller surrenders "ownership" of urb
1017  * expects usb_submit_urb() to have sanity checked and conditioned all
1018  * inputs in the urb
1019  */
1020 static int hcd_submit_urb (struct urb *urb, int mem_flags)
1021 {
1022         int                     status;
1023         struct usb_hcd          *hcd = urb->dev->bus->hcpriv;
1024         struct hcd_dev          *dev = urb->dev->hcpriv;
1025         unsigned long           flags;
1026
1027         if (!hcd || !dev)
1028                 return -ENODEV;
1029
1030         /*
1031          * FIXME:  make urb timeouts be generic, keeping the HCD cores
1032          * as simple as possible.
1033          */
1034
1035         // NOTE:  a generic device/urb monitoring hook would go here.
1036         // hcd_monitor_hook(MONITOR_URB_SUBMIT, urb)
1037         // It would catch submission paths for all urbs.
1038
1039         /*
1040          * Atomically queue the urb,  first to our records, then to the HCD.
1041          * Access to urb->status is controlled by urb->lock ... changes on
1042          * i/o completion (normal or fault) or unlinking.
1043          */
1044
1045         // FIXME:  verify that quiescing hc works right (RH cleans up)
1046
1047         spin_lock_irqsave (&hcd_data_lock, flags);
1048         if (HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_QUIESCING) {
1049                 usb_get_dev (urb->dev);
1050                 list_add_tail (&urb->urb_list, &dev->urb_list);
1051                 status = 0;
1052         } else {
1053                 INIT_LIST_HEAD (&urb->urb_list);
1054                 status = -ESHUTDOWN;
1055         }
1056         spin_unlock_irqrestore (&hcd_data_lock, flags);
1057         if (status)
1058                 return status;
1059
1060         /* increment urb's reference count as part of giving it to the HCD
1061          * (which now controls it).  HCD guarantees that it either returns
1062          * an error or calls giveback(), but not both.
1063          */
1064         urb = usb_get_urb (urb);
1065         if (urb->dev == hcd->self.root_hub) {
1066                 /* NOTE:  requirement on hub callers (usbfs and the hub
1067                  * driver, for now) that URBs' urb->transfer_buffer be
1068                  * valid and usb_buffer_{sync,unmap}() not be needed, since
1069                  * they could clobber root hub response data.
1070                  */
1071                 urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
1072                                         | URB_NO_SETUP_DMA_MAP);
1073                 status = rh_urb_enqueue (hcd, urb);
1074                 goto done;
1075         }
1076
1077         /* lower level hcd code should use *_dma exclusively,
1078          * unless it uses pio or talks to another transport.
1079          */
1080         if (hcd->self.controller->dma_mask) {
1081                 if (usb_pipecontrol (urb->pipe)
1082                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1083                         urb->setup_dma = dma_map_single (
1084                                         hcd->self.controller,
1085                                         urb->setup_packet,
1086                                         sizeof (struct usb_ctrlrequest),
1087                                         DMA_TO_DEVICE);
1088                 if (urb->transfer_buffer_length != 0
1089                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1090                         urb->transfer_dma = dma_map_single (
1091                                         hcd->self.controller,
1092                                         urb->transfer_buffer,
1093                                         urb->transfer_buffer_length,
1094                                         usb_pipein (urb->pipe)
1095                                             ? DMA_FROM_DEVICE
1096                                             : DMA_TO_DEVICE);
1097         }
1098
1099         status = hcd->driver->urb_enqueue (hcd, urb, mem_flags);
1100 done:
1101         if (status) {
1102                 usb_put_urb (urb);
1103                 urb_unlink (urb);
1104         }
1105         return status;
1106 }
1107
1108 /*-------------------------------------------------------------------------*/
1109
1110 /* called in any context */
1111 static int hcd_get_frame_number (struct usb_device *udev)
1112 {
1113         struct usb_hcd  *hcd = (struct usb_hcd *)udev->bus->hcpriv;
1114         if (!HCD_IS_RUNNING (hcd->state))
1115                 return -ESHUTDOWN;
1116         return hcd->driver->get_frame_number (hcd);
1117 }
1118
1119 /*-------------------------------------------------------------------------*/
1120
1121 /* this makes the hcd giveback() the urb more quickly, by kicking it
1122  * off hardware queues (which may take a while) and returning it as
1123  * soon as practical.  we've already set up the urb's return status,
1124  * but we can't know if the callback completed already.
1125  */
1126 static void
1127 unlink1 (struct usb_hcd *hcd, struct urb *urb)
1128 {
1129         if (urb == (struct urb *) hcd->rh_timer.data)
1130                 usb_rh_status_dequeue (hcd, urb);
1131         else {
1132                 int             value;
1133
1134                 /* failures "should" be harmless */
1135                 value = hcd->driver->urb_dequeue (hcd, urb);
1136                 if (value != 0)
1137                         dev_dbg (hcd->self.controller,
1138                                 "dequeue %p --> %d\n",
1139                                 urb, value);
1140         }
1141 }
1142
1143 struct completion_splice {              // modified urb context:
1144         /* did we complete? */
1145         struct completion       done;
1146
1147         /* original urb data */
1148         usb_complete_t          complete;
1149         void                    *context;
1150 };
1151
1152 static void unlink_complete (struct urb *urb, struct pt_regs *regs)
1153 {
1154         struct completion_splice        *splice;
1155
1156         splice = (struct completion_splice *) urb->context;
1157
1158         /* issue original completion call */
1159         urb->complete = splice->complete;
1160         urb->context = splice->context;
1161         urb->complete (urb, regs);
1162
1163         /* then let the synchronous unlink call complete */
1164         complete (&splice->done);
1165 }
1166
1167 /*
1168  * called in any context; note ASYNC_UNLINK restrictions
1169  *
1170  * caller guarantees urb won't be recycled till both unlink()
1171  * and the urb's completion function return
1172  */
1173 static int hcd_unlink_urb (struct urb *urb)
1174 {
1175         struct hcd_dev                  *dev;
1176         struct usb_hcd                  *hcd = 0;
1177         struct device                   *sys = 0;
1178         unsigned long                   flags;
1179         struct completion_splice        splice;
1180         struct list_head                *tmp;
1181         int                             retval;
1182
1183         if (!urb)
1184                 return -EINVAL;
1185
1186         /*
1187          * we contend for urb->status with the hcd core,
1188          * which changes it while returning the urb.
1189          *
1190          * Caller guaranteed that the urb pointer hasn't been freed, and
1191          * that it was submitted.  But as a rule it can't know whether or
1192          * not it's already been unlinked ... so we respect the reversed
1193          * lock sequence needed for the usb_hcd_giveback_urb() code paths
1194          * (urb lock, then hcd_data_lock) in case some other CPU is now
1195          * unlinking it.
1196          */
1197         spin_lock_irqsave (&urb->lock, flags);
1198         spin_lock (&hcd_data_lock);
1199
1200         if (!urb->dev || !urb->dev->bus) {
1201                 retval = -ENODEV;
1202                 goto done;
1203         }
1204
1205         dev = urb->dev->hcpriv;
1206         sys = &urb->dev->dev;
1207         hcd = urb->dev->bus->hcpriv;
1208         if (!dev || !hcd) {
1209                 retval = -ENODEV;
1210                 goto done;
1211         }
1212
1213         /* running ~= hc unlink handshake works (irq, timer, etc)
1214          * halted ~= no unlink handshake is needed
1215          * suspended, resuming == should never happen
1216          */
1217         WARN_ON (!HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_HALT);
1218
1219         /* insist the urb is still queued */
1220         list_for_each(tmp, &dev->urb_list) {
1221                 if (tmp == &urb->urb_list)
1222                         break;
1223         }
1224         if (tmp != &urb->urb_list) {
1225                 retval = -EIDRM;
1226                 goto done;
1227         }
1228
1229         /* Any status except -EINPROGRESS means something already started to
1230          * unlink this URB from the hardware.  So there's no more work to do.
1231          *
1232          * FIXME use better explicit urb state
1233          */
1234         if (urb->status != -EINPROGRESS) {
1235                 retval = -EBUSY;
1236                 goto done;
1237         }
1238
1239         /* PCI IRQ setup can easily be broken so that USB controllers
1240          * never get completion IRQs ... maybe even the ones we need to
1241          * finish unlinking the initial failed usb_set_address().
1242          */
1243         if (!hcd->saw_irq) {
1244                 dev_warn (hcd->self.controller, "Unlink after no-IRQ?  "
1245                         "Different ACPI or APIC settings may help."
1246                         "\n");
1247                 hcd->saw_irq = 1;
1248         }
1249
1250         /* maybe set up to block until the urb's completion fires.  the
1251          * lower level hcd code is always async, locking on urb->status
1252          * updates; an intercepted completion unblocks us.
1253          */
1254         if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1255                 if (in_interrupt ()) {
1256                         dev_dbg (hcd->self.controller, 
1257                                 "non-async unlink in_interrupt");
1258                         retval = -EWOULDBLOCK;
1259                         goto done;
1260                 }
1261                 /* synchronous unlink: block till we see the completion */
1262                 init_completion (&splice.done);
1263                 splice.complete = urb->complete;
1264                 splice.context = urb->context;
1265                 urb->complete = unlink_complete;
1266                 urb->context = &splice;
1267                 urb->status = -ENOENT;
1268         } else {
1269                 /* asynchronous unlink */
1270                 urb->status = -ECONNRESET;
1271         }
1272         spin_unlock (&hcd_data_lock);
1273         spin_unlock_irqrestore (&urb->lock, flags);
1274
1275         // FIXME remove splicing, so this becomes unlink1 (hcd, urb);
1276         if (urb == (struct urb *) hcd->rh_timer.data) {
1277                 usb_rh_status_dequeue (hcd, urb);
1278                 retval = 0;
1279         } else {
1280                 retval = hcd->driver->urb_dequeue (hcd, urb);
1281
1282                 /* hcds shouldn't really fail these calls, but... */
1283                 if (retval) {
1284                         dev_dbg (sys, "dequeue %p --> %d\n", urb, retval);
1285                         if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1286                                 spin_lock_irqsave (&urb->lock, flags);
1287                                 urb->complete = splice.complete;
1288                                 urb->context = splice.context;
1289                                 spin_unlock_irqrestore (&urb->lock, flags);
1290                         }
1291                         goto bye;
1292                 }
1293         }
1294
1295         /* block till giveback, if needed */
1296         if (urb->transfer_flags & URB_ASYNC_UNLINK)
1297                 return -EINPROGRESS;
1298
1299         wait_for_completion (&splice.done);
1300         return 0;
1301
1302 done:
1303         spin_unlock (&hcd_data_lock);
1304         spin_unlock_irqrestore (&urb->lock, flags);
1305 bye:
1306         if (retval != -EIDRM && sys && sys->driver)
1307                 dev_dbg (sys, "hcd_unlink_urb %p fail %d\n", urb, retval);
1308         return retval;
1309 }
1310
1311 /*-------------------------------------------------------------------------*/
1312
1313 /* disables the endpoint: cancels any pending urbs, then synchronizes with
1314  * the hcd to make sure all endpoint state is gone from hardware. use for
1315  * set_configuration, set_interface, driver removal, physical disconnect.
1316  *
1317  * example:  a qh stored in hcd_dev.ep[], holding state related to endpoint
1318  * type, maxpacket size, toggle, halt status, and scheduling.
1319  */
1320 static void hcd_endpoint_disable (struct usb_device *udev, int endpoint)
1321 {
1322         struct hcd_dev  *dev;
1323         struct usb_hcd  *hcd;
1324         struct urb      *urb;
1325         unsigned        epnum = endpoint & USB_ENDPOINT_NUMBER_MASK;
1326
1327         dev = udev->hcpriv;
1328         hcd = udev->bus->hcpriv;
1329
1330         WARN_ON (!HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_HALT);
1331
1332         local_irq_disable ();
1333
1334 rescan:
1335         /* (re)block new requests, as best we can */
1336         if (endpoint & USB_DIR_IN) {
1337                 usb_endpoint_halt (udev, epnum, 0);
1338                 udev->epmaxpacketin [epnum] = 0;
1339         } else {
1340                 usb_endpoint_halt (udev, epnum, 1);
1341                 udev->epmaxpacketout [epnum] = 0;
1342         }
1343
1344         /* then kill any current requests */
1345         spin_lock (&hcd_data_lock);
1346         list_for_each_entry (urb, &dev->urb_list, urb_list) {
1347                 int     tmp = urb->pipe;
1348
1349                 /* ignore urbs for other endpoints */
1350                 if (usb_pipeendpoint (tmp) != epnum)
1351                         continue;
1352                 /* NOTE assumption that only ep0 is a control endpoint */
1353                 if (epnum != 0 && ((tmp ^ endpoint) & USB_DIR_IN))
1354                         continue;
1355
1356                 /* another cpu may be in hcd, spinning on hcd_data_lock
1357                  * to giveback() this urb.  the races here should be
1358                  * small, but a full fix needs a new "can't submit"
1359                  * urb state.
1360                  */
1361                 if (urb->status != -EINPROGRESS)
1362                         continue;
1363                 usb_get_urb (urb);
1364                 spin_unlock (&hcd_data_lock);
1365
1366                 spin_lock (&urb->lock);
1367                 tmp = urb->status;
1368                 if (tmp == -EINPROGRESS)
1369                         urb->status = -ESHUTDOWN;
1370                 spin_unlock (&urb->lock);
1371
1372                 /* kick hcd unless it's already returning this */
1373                 if (tmp == -EINPROGRESS) {
1374                         tmp = urb->pipe;
1375                         unlink1 (hcd, urb);
1376                         dev_dbg (hcd->self.controller,
1377                                 "shutdown urb %p pipe %08x ep%d%s%s\n",
1378                                 urb, tmp, usb_pipeendpoint (tmp),
1379                                 (tmp & USB_DIR_IN) ? "in" : "out",
1380                                 ({ char *s; \
1381                                  switch (usb_pipetype (tmp)) { \
1382                                  case PIPE_CONTROL:     s = ""; break; \
1383                                  case PIPE_BULK:        s = "-bulk"; break; \
1384                                  case PIPE_INTERRUPT:   s = "-intr"; break; \
1385                                  default:               s = "-iso"; break; \
1386                                 }; s;}));
1387                 }
1388                 usb_put_urb (urb);
1389
1390                 /* list contents may have changed */
1391                 goto rescan;
1392         }
1393         spin_unlock (&hcd_data_lock);
1394         local_irq_enable ();
1395
1396         /* synchronize with the hardware, so old configuration state
1397          * clears out immediately (and will be freed).
1398          */
1399         might_sleep ();
1400         if (hcd->driver->endpoint_disable)
1401                 hcd->driver->endpoint_disable (hcd, dev, endpoint);
1402 }
1403
1404 /*-------------------------------------------------------------------------*/
1405
1406 /* called by khubd, rmmod, apmd, or other thread for hcd-private cleanup.
1407  * we're guaranteed that the device is fully quiesced.  also, that each
1408  * endpoint has been hcd_endpoint_disabled.
1409  */
1410
1411 static int hcd_free_dev (struct usb_device *udev)
1412 {
1413         struct hcd_dev          *dev;
1414         struct usb_hcd          *hcd;
1415         unsigned long           flags;
1416
1417         if (!udev || !udev->hcpriv)
1418                 return -EINVAL;
1419
1420         if (!udev->bus || !udev->bus->hcpriv)
1421                 return -ENODEV;
1422
1423         // should udev->devnum == -1 ??
1424
1425         dev = udev->hcpriv;
1426         hcd = udev->bus->hcpriv;
1427
1428         /* device driver problem with refcounts? */
1429         if (!list_empty (&dev->urb_list)) {
1430                 dev_dbg (hcd->self.controller, "free busy dev, %s devnum %d (bug!)\n",
1431                         hcd->self.bus_name, udev->devnum);
1432                 return -EINVAL;
1433         }
1434
1435         spin_lock_irqsave (&hcd_data_lock, flags);
1436         list_del (&dev->dev_list);
1437         udev->hcpriv = NULL;
1438         spin_unlock_irqrestore (&hcd_data_lock, flags);
1439
1440         kfree (dev);
1441         return 0;
1442 }
1443
1444 /*
1445  * usb_hcd_operations - adapts usb_bus framework to HCD framework (bus glue)
1446  *
1447  * When registering a USB bus through the HCD framework code, use this
1448  * usb_operations vector.  The PCI glue layer does so automatically; only
1449  * bus glue for non-PCI system busses will need to use this.
1450  */
1451 struct usb_operations usb_hcd_operations = {
1452         .allocate =             hcd_alloc_dev,
1453         .get_frame_number =     hcd_get_frame_number,
1454         .submit_urb =           hcd_submit_urb,
1455         .unlink_urb =           hcd_unlink_urb,
1456         .deallocate =           hcd_free_dev,
1457         .buffer_alloc =         hcd_buffer_alloc,
1458         .buffer_free =          hcd_buffer_free,
1459         .disable =              hcd_endpoint_disable,
1460 };
1461 EXPORT_SYMBOL (usb_hcd_operations);
1462
1463 /*-------------------------------------------------------------------------*/
1464
1465 /**
1466  * usb_hcd_giveback_urb - return URB from HCD to device driver
1467  * @hcd: host controller returning the URB
1468  * @urb: urb being returned to the USB device driver.
1469  * @regs: pt_regs, passed down to the URB completion handler
1470  * Context: in_interrupt()
1471  *
1472  * This hands the URB from HCD to its USB device driver, using its
1473  * completion function.  The HCD has freed all per-urb resources
1474  * (and is done using urb->hcpriv).  It also released all HCD locks;
1475  * the device driver won't cause problems if it frees, modifies,
1476  * or resubmits this URB.
1477  */
1478 void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb, struct pt_regs *regs)
1479 {
1480         urb_unlink (urb);
1481
1482         // NOTE:  a generic device/urb monitoring hook would go here.
1483         // hcd_monitor_hook(MONITOR_URB_FINISH, urb, dev)
1484         // It would catch exit/unlink paths for all urbs.
1485
1486         /* lower level hcd code should use *_dma exclusively */
1487         if (hcd->self.controller->dma_mask) {
1488                 if (usb_pipecontrol (urb->pipe)
1489                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1490                         dma_unmap_single (hcd->self.controller, urb->setup_dma,
1491                                         sizeof (struct usb_ctrlrequest),
1492                                         DMA_TO_DEVICE);
1493                 if (urb->transfer_buffer_length != 0
1494                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1495                         dma_unmap_single (hcd->self.controller, 
1496                                         urb->transfer_dma,
1497                                         urb->transfer_buffer_length,
1498                                         usb_pipein (urb->pipe)
1499                                             ? DMA_FROM_DEVICE
1500                                             : DMA_TO_DEVICE);
1501         }
1502
1503         /* pass ownership to the completion handler */
1504         urb->complete (urb, regs);
1505         usb_put_urb (urb);
1506 }
1507 EXPORT_SYMBOL (usb_hcd_giveback_urb);
1508
1509 /*-------------------------------------------------------------------------*/
1510
1511 /**
1512  * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
1513  * @irq: the IRQ being raised
1514  * @__hcd: pointer to the HCD whose IRQ is beinng signaled
1515  * @r: saved hardware registers
1516  *
1517  * When registering a USB bus through the HCD framework code, use this
1518  * to handle interrupts.  The PCI glue layer does so automatically; only
1519  * bus glue for non-PCI system busses will need to use this.
1520  */
1521 irqreturn_t usb_hcd_irq (int irq, void *__hcd, struct pt_regs * r)
1522 {
1523         struct usb_hcd          *hcd = __hcd;
1524         int                     start = hcd->state;
1525
1526         if (unlikely (hcd->state == USB_STATE_HALT))    /* irq sharing? */
1527                 return IRQ_NONE;
1528
1529         hcd->saw_irq = 1;
1530         if (hcd->driver->irq (hcd, r) == IRQ_NONE)
1531                 return IRQ_NONE;
1532
1533         if (hcd->state != start && hcd->state == USB_STATE_HALT)
1534                 usb_hc_died (hcd);
1535         return IRQ_HANDLED;
1536 }
1537 EXPORT_SYMBOL (usb_hcd_irq);
1538
1539 /*-------------------------------------------------------------------------*/
1540
1541 static void hcd_panic (void *_hcd)
1542 {
1543         struct usb_hcd          *hcd = _hcd;
1544         struct usb_device       *hub = hcd->self.root_hub;
1545         unsigned                i;
1546
1547         /* hc's root hub is removed later removed in hcd->stop() */
1548         hub->state = USB_STATE_NOTATTACHED;
1549         for (i = 0; i < hub->maxchild; i++) {
1550                 if (hub->children [i])
1551                         usb_disconnect (&hub->children [i]);
1552         }
1553 }
1554
1555 /**
1556  * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
1557  * @hcd: pointer to the HCD representing the controller
1558  *
1559  * This is called by bus glue to report a USB host controller that died
1560  * while operations may still have been pending.  It's called automatically
1561  * by the PCI glue, so only glue for non-PCI busses should need to call it. 
1562  */
1563 void usb_hc_died (struct usb_hcd *hcd)
1564 {
1565         dev_err (hcd->self.controller, "HC died; cleaning up\n");
1566
1567         /* clean up old urbs and devices; needs a task context */
1568         INIT_WORK (&hcd->work, hcd_panic, hcd);
1569         (void) schedule_work (&hcd->work);
1570 }
1571 EXPORT_SYMBOL (usb_hc_died);
1572