ecac9fac2727a77fd030bad861e16b18b57f78ec
[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         0xc0,       /*  __u8  bmAttributes; 
175                                  Bit 7: must be set,
176                                      6: Self-powered,
177                                      5: Remote wakeup,
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         0xc0,       /*  __u8  bmAttributes; 
222                                  Bit 7: must be set,
223                                      6: Self-powered,
224                                      5: Remote wakeup,
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;
328         u16             typeReq, wValue, wIndex, wLength;
329         const u8        *bufp = 0;
330         u8              *ubuf = urb->transfer_buffer;
331         int             len = 0;
332         int             patch_wakeup = 0;
333         unsigned long   flags;
334
335         cmd = (struct usb_ctrlrequest *) urb->setup_packet;
336         typeReq  = (cmd->bRequestType << 8) | cmd->bRequest;
337         wValue   = le16_to_cpu (cmd->wValue);
338         wIndex   = le16_to_cpu (cmd->wIndex);
339         wLength  = le16_to_cpu (cmd->wLength);
340
341         if (wLength > urb->transfer_buffer_length)
342                 goto error;
343
344         /* set up for success */
345         urb->status = 0;
346         urb->actual_length = wLength;
347         switch (typeReq) {
348
349         /* DEVICE REQUESTS */
350
351         case DeviceRequest | USB_REQ_GET_STATUS:
352                 ubuf [0] = (hcd->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP)
353                                 | (1 << USB_DEVICE_SELF_POWERED);
354                 ubuf [1] = 0;
355                 break;
356         case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
357                 if (wValue == USB_DEVICE_REMOTE_WAKEUP)
358                         hcd->remote_wakeup = 0;
359                 else
360                         goto error;
361                 break;
362         case DeviceOutRequest | USB_REQ_SET_FEATURE:
363                 if (hcd->can_wakeup && wValue == USB_DEVICE_REMOTE_WAKEUP)
364                         hcd->remote_wakeup = 1;
365                 else
366                         goto error;
367                 break;
368         case DeviceRequest | USB_REQ_GET_CONFIGURATION:
369                 ubuf [0] = 1;
370                         /* FALLTHROUGH */
371         case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
372                 break;
373         case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
374                 switch (wValue & 0xff00) {
375                 case USB_DT_DEVICE << 8:
376                         if (hcd->driver->flags & HCD_USB2)
377                                 bufp = usb2_rh_dev_descriptor;
378                         else if (hcd->driver->flags & HCD_USB11)
379                                 bufp = usb11_rh_dev_descriptor;
380                         else
381                                 goto error;
382                         len = 18;
383                         break;
384                 case USB_DT_CONFIG << 8:
385                         if (hcd->driver->flags & HCD_USB2) {
386                                 bufp = hs_rh_config_descriptor;
387                                 len = sizeof hs_rh_config_descriptor;
388                         } else {
389                                 bufp = fs_rh_config_descriptor;
390                                 len = sizeof fs_rh_config_descriptor;
391                         }
392                         if (hcd->can_wakeup)
393                                 patch_wakeup = 1;
394                         break;
395                 case USB_DT_STRING << 8:
396                         urb->actual_length = rh_string (
397                                 wValue & 0xff, hcd,
398                                 ubuf, wLength);
399                         break;
400                 default:
401                         goto error;
402                 }
403                 break;
404         case DeviceRequest | USB_REQ_GET_INTERFACE:
405                 ubuf [0] = 0;
406                         /* FALLTHROUGH */
407         case DeviceOutRequest | USB_REQ_SET_INTERFACE:
408                 break;
409         case DeviceOutRequest | USB_REQ_SET_ADDRESS:
410                 // wValue == urb->dev->devaddr
411                 dev_dbg (hcd->self.controller, "root hub device address %d\n",
412                         wValue);
413                 break;
414
415         /* INTERFACE REQUESTS (no defined feature/status flags) */
416
417         /* ENDPOINT REQUESTS */
418
419         case EndpointRequest | USB_REQ_GET_STATUS:
420                 // ENDPOINT_HALT flag
421                 ubuf [0] = 0;
422                 ubuf [1] = 0;
423                         /* FALLTHROUGH */
424         case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
425         case EndpointOutRequest | USB_REQ_SET_FEATURE:
426                 dev_dbg (hcd->self.controller, "no endpoint features yet\n");
427                 break;
428
429         /* CLASS REQUESTS (and errors) */
430
431         default:
432                 /* non-generic request */
433                 if (HCD_IS_SUSPENDED (hcd->state))
434                         urb->status = -EAGAIN;
435                 else if (!HCD_IS_RUNNING (hcd->state))
436                         urb->status = -ENODEV;
437                 else
438                         urb->status = hcd->driver->hub_control (hcd,
439                                 typeReq, wValue, wIndex,
440                                 ubuf, wLength);
441                 break;
442 error:
443                 /* "protocol stall" on error */
444                 urb->status = -EPIPE;
445                 dev_dbg (hcd->self.controller, "unsupported hub control message (maxchild %d)\n",
446                                 urb->dev->maxchild);
447         }
448         if (urb->status) {
449                 urb->actual_length = 0;
450                 dev_dbg (hcd->self.controller, "CTRL: TypeReq=0x%x val=0x%x idx=0x%x len=%d ==> %d\n",
451                         typeReq, wValue, wIndex, wLength, urb->status);
452         }
453         if (bufp) {
454                 if (urb->transfer_buffer_length < len)
455                         len = urb->transfer_buffer_length;
456                 urb->actual_length = len;
457                 // always USB_DIR_IN, toward host
458                 memcpy (ubuf, bufp, len);
459
460                 /* report whether RH hardware supports remote wakeup */
461                 if (patch_wakeup)
462                         ((struct usb_config_descriptor *)ubuf)->bmAttributes
463                                 |= USB_CONFIG_ATT_WAKEUP;
464         }
465
466         /* any errors get returned through the urb completion */
467         local_irq_save (flags);
468         usb_hcd_giveback_urb (hcd, urb, NULL);
469         local_irq_restore (flags);
470         return 0;
471 }
472
473 /*-------------------------------------------------------------------------*/
474
475 /*
476  * Root Hub interrupt transfers are synthesized with a timer.
477  * Completions are called in_interrupt() but not in_irq().
478  */
479
480 static void rh_report_status (unsigned long ptr);
481
482 static int rh_status_urb (struct usb_hcd *hcd, struct urb *urb) 
483 {
484         int     len = 1 + (urb->dev->maxchild / 8);
485
486         /* rh_timer protected by hcd_data_lock */
487         if (hcd->rh_timer.data
488                         || urb->status != -EINPROGRESS
489                         || urb->transfer_buffer_length < len
490                         || !HCD_IS_RUNNING (hcd->state)) {
491                 dev_dbg (hcd->self.controller,
492                                 "not queuing rh status urb, stat %d\n",
493                                 urb->status);
494                 return -EINVAL;
495         }
496
497         init_timer (&hcd->rh_timer);
498         hcd->rh_timer.function = rh_report_status;
499         hcd->rh_timer.data = (unsigned long) urb;
500         /* USB 2.0 spec says 256msec; this is close enough */
501         hcd->rh_timer.expires = jiffies + HZ/4;
502         add_timer (&hcd->rh_timer);
503         urb->hcpriv = hcd;      /* nonzero to indicate it's queued */
504         return 0;
505 }
506
507 /* timer callback */
508
509 static void rh_report_status (unsigned long ptr)
510 {
511         struct urb      *urb;
512         struct usb_hcd  *hcd;
513         int             length = 0;
514         unsigned long   flags;
515
516         urb = (struct urb *) ptr;
517         local_irq_save (flags);
518         spin_lock (&urb->lock);
519
520         /* do nothing if the urb's been unlinked */
521         if (!urb->dev
522                         || urb->status != -EINPROGRESS
523                         || (hcd = urb->dev->bus->hcpriv) == 0) {
524                 spin_unlock (&urb->lock);
525                 local_irq_restore (flags);
526                 return;
527         }
528
529         if (!HCD_IS_SUSPENDED (hcd->state))
530                 length = hcd->driver->hub_status_data (
531                                         hcd, urb->transfer_buffer);
532
533         /* complete the status urb, or retrigger the timer */
534         spin_lock (&hcd_data_lock);
535         if (length > 0) {
536                 hcd->rh_timer.data = 0;
537                 urb->actual_length = length;
538                 urb->status = 0;
539                 urb->hcpriv = 0;
540         } else
541                 mod_timer (&hcd->rh_timer, jiffies + HZ/4);
542         spin_unlock (&hcd_data_lock);
543         spin_unlock (&urb->lock);
544
545         /* local irqs are always blocked in completions */
546         if (length > 0)
547                 usb_hcd_giveback_urb (hcd, urb, NULL);
548         local_irq_restore (flags);
549 }
550
551 /*-------------------------------------------------------------------------*/
552
553 static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
554 {
555         if (usb_pipeint (urb->pipe)) {
556                 int             retval;
557                 unsigned long   flags;
558
559                 spin_lock_irqsave (&hcd_data_lock, flags);
560                 retval = rh_status_urb (hcd, urb);
561                 spin_unlock_irqrestore (&hcd_data_lock, flags);
562                 return retval;
563         }
564         if (usb_pipecontrol (urb->pipe))
565                 return rh_call_control (hcd, urb);
566         else
567                 return -EINVAL;
568 }
569
570 /*-------------------------------------------------------------------------*/
571
572 void usb_rh_status_dequeue (struct usb_hcd *hcd, struct urb *urb)
573 {
574         unsigned long   flags;
575
576         /* note:  always a synchronous unlink */
577         del_timer_sync (&hcd->rh_timer);
578         hcd->rh_timer.data = 0;
579
580         local_irq_save (flags);
581         urb->hcpriv = 0;
582         usb_hcd_giveback_urb (hcd, urb, NULL);
583         local_irq_restore (flags);
584 }
585
586 /*-------------------------------------------------------------------------*/
587
588 /* exported only within usbcore */
589 struct usb_bus *usb_bus_get (struct usb_bus *bus)
590 {
591         struct class_device *tmp;
592
593         if (!bus)
594                 return NULL;
595
596         tmp = class_device_get(&bus->class_dev);
597         if (tmp)        
598                 return to_usb_bus(tmp);
599         else
600                 return NULL;
601 }
602
603 /* exported only within usbcore */
604 void usb_bus_put (struct usb_bus *bus)
605 {
606         if (bus)
607                 class_device_put(&bus->class_dev);
608 }
609
610 /*-------------------------------------------------------------------------*/
611
612 static void usb_host_release(struct class_device *class_dev)
613 {
614         struct usb_bus *bus = to_usb_bus(class_dev);
615
616         if (bus->release)
617                 bus->release(bus);
618 }
619
620 static struct class usb_host_class = {
621         .name           = "usb_host",
622         .release        = &usb_host_release,
623 };
624
625 void usb_host_init(void)
626 {
627         class_register(&usb_host_class);
628 }
629
630 void usb_host_cleanup(void)
631 {
632         class_unregister(&usb_host_class);
633 }
634
635 /**
636  * usb_bus_init - shared initialization code
637  * @bus: the bus structure being initialized
638  *
639  * This code is used to initialize a usb_bus structure, memory for which is
640  * separately managed.
641  */
642 void usb_bus_init (struct usb_bus *bus)
643 {
644         memset (&bus->devmap, 0, sizeof(struct usb_devmap));
645
646         bus->devnum_next = 1;
647
648         bus->root_hub = NULL;
649         bus->hcpriv = NULL;
650         bus->busnum = -1;
651         bus->bandwidth_allocated = 0;
652         bus->bandwidth_int_reqs  = 0;
653         bus->bandwidth_isoc_reqs = 0;
654
655         INIT_LIST_HEAD (&bus->bus_list);
656 }
657 EXPORT_SYMBOL (usb_bus_init);
658
659 /**
660  * usb_alloc_bus - creates a new USB host controller structure
661  * @op: pointer to a struct usb_operations that this bus structure should use
662  * Context: !in_interrupt()
663  *
664  * Creates a USB host controller bus structure with the specified 
665  * usb_operations and initializes all the necessary internal objects.
666  *
667  * If no memory is available, NULL is returned.
668  *
669  * The caller should call usb_put_bus() when it is finished with the structure.
670  */
671 struct usb_bus *usb_alloc_bus (struct usb_operations *op)
672 {
673         struct usb_bus *bus;
674
675         bus = kmalloc (sizeof *bus, GFP_KERNEL);
676         if (!bus)
677                 return NULL;
678         memset(bus, 0, sizeof(struct usb_bus));
679         usb_bus_init (bus);
680         bus->op = op;
681         return bus;
682 }
683 EXPORT_SYMBOL (usb_alloc_bus);
684
685 /*-------------------------------------------------------------------------*/
686
687 /**
688  * usb_register_bus - registers the USB host controller with the usb core
689  * @bus: pointer to the bus to register
690  * Context: !in_interrupt()
691  *
692  * Assigns a bus number, and links the controller into usbcore data
693  * structures so that it can be seen by scanning the bus list.
694  */
695 int usb_register_bus(struct usb_bus *bus)
696 {
697         int busnum;
698         int retval;
699
700         down (&usb_bus_list_lock);
701         busnum = find_next_zero_bit (busmap.busmap, USB_MAXBUS, 1);
702         if (busnum < USB_MAXBUS) {
703                 set_bit (busnum, busmap.busmap);
704                 bus->busnum = busnum;
705         } else {
706                 printk (KERN_ERR "%s: too many buses\n", usbcore_name);
707                 return -E2BIG;
708         }
709
710         snprintf(bus->class_dev.class_id, BUS_ID_SIZE, "usb%d", busnum);
711         bus->class_dev.class = &usb_host_class;
712         bus->class_dev.dev = bus->controller;
713         retval = class_device_register(&bus->class_dev);
714         if (retval) {
715                 clear_bit(busnum, busmap.busmap);
716                 up(&usb_bus_list_lock);
717                 return retval;
718         }
719
720         /* Add it to the local list of buses */
721         list_add (&bus->bus_list, &usb_bus_list);
722         up (&usb_bus_list_lock);
723
724         usbfs_add_bus (bus);
725
726         dev_info (bus->controller, "new USB bus registered, assigned bus number %d\n", bus->busnum);
727         return 0;
728 }
729 EXPORT_SYMBOL (usb_register_bus);
730
731 /**
732  * usb_deregister_bus - deregisters the USB host controller
733  * @bus: pointer to the bus to deregister
734  * Context: !in_interrupt()
735  *
736  * Recycles the bus number, and unlinks the controller from usbcore data
737  * structures so that it won't be seen by scanning the bus list.
738  */
739 void usb_deregister_bus (struct usb_bus *bus)
740 {
741         dev_info (bus->controller, "USB bus %d deregistered\n", bus->busnum);
742
743         /*
744          * NOTE: make sure that all the devices are removed by the
745          * controller code, as well as having it call this when cleaning
746          * itself up
747          */
748         down (&usb_bus_list_lock);
749         list_del (&bus->bus_list);
750         up (&usb_bus_list_lock);
751
752         usbfs_remove_bus (bus);
753
754         clear_bit (bus->busnum, busmap.busmap);
755
756         class_device_unregister(&bus->class_dev);
757 }
758 EXPORT_SYMBOL (usb_deregister_bus);
759
760 /**
761  * usb_register_root_hub - called by HCD to register its root hub 
762  * @usb_dev: the usb root hub device to be registered.
763  * @parent_dev: the parent device of this root hub.
764  *
765  * The USB host controller calls this function to register the root hub
766  * properly with the USB subsystem.  It sets up the device properly in
767  * the device tree and stores the root_hub pointer in the bus structure,
768  * then calls usb_new_device() to register the usb device.  It also
769  * assigns the root hub's USB address (always 1).
770  */
771 int usb_register_root_hub (struct usb_device *usb_dev, struct device *parent_dev)
772 {
773         const int devnum = 1;
774         int retval;
775
776         usb_dev->devnum = devnum;
777         usb_dev->bus->devnum_next = devnum + 1;
778         memset (&usb_dev->bus->devmap.devicemap, 0,
779                         sizeof usb_dev->bus->devmap.devicemap);
780         set_bit (devnum, usb_dev->bus->devmap.devicemap);
781         usb_set_device_state(usb_dev, USB_STATE_ADDRESS);
782
783         down (&usb_bus_list_lock);
784         usb_dev->bus->root_hub = usb_dev;
785
786         usb_dev->epmaxpacketin[0] = usb_dev->epmaxpacketout[0] = 64;
787         retval = usb_get_device_descriptor(usb_dev, USB_DT_DEVICE_SIZE);
788         if (retval != sizeof usb_dev->descriptor) {
789                 dev_dbg (parent_dev, "can't read %s device descriptor %d\n",
790                                 usb_dev->dev.bus_id, retval);
791                 return (retval < 0) ? retval : -EMSGSIZE;
792         }
793
794         down (&usb_dev->serialize);
795         retval = usb_new_device (usb_dev);
796         up (&usb_dev->serialize);
797         if (retval) {
798                 usb_dev->bus->root_hub = NULL;
799                 dev_err (parent_dev, "can't register root hub for %s, %d\n",
800                                 usb_dev->dev.bus_id, retval);
801         }
802         up (&usb_bus_list_lock);
803         return retval;
804 }
805 EXPORT_SYMBOL (usb_register_root_hub);
806
807
808 /*-------------------------------------------------------------------------*/
809
810 /**
811  * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
812  * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
813  * @is_input: true iff the transaction sends data to the host
814  * @isoc: true for isochronous transactions, false for interrupt ones
815  * @bytecount: how many bytes in the transaction.
816  *
817  * Returns approximate bus time in nanoseconds for a periodic transaction.
818  * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
819  * scheduled in software, this function is only used for such scheduling.
820  */
821 long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
822 {
823         unsigned long   tmp;
824
825         switch (speed) {
826         case USB_SPEED_LOW:     /* INTR only */
827                 if (is_input) {
828                         tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
829                         return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
830                 } else {
831                         tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
832                         return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
833                 }
834         case USB_SPEED_FULL:    /* ISOC or INTR */
835                 if (isoc) {
836                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
837                         return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
838                 } else {
839                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
840                         return (9107L + BW_HOST_DELAY + tmp);
841                 }
842         case USB_SPEED_HIGH:    /* ISOC or INTR */
843                 // FIXME adjust for input vs output
844                 if (isoc)
845                         tmp = HS_USECS (bytecount);
846                 else
847                         tmp = HS_USECS_ISO (bytecount);
848                 return tmp;
849         default:
850                 pr_debug ("%s: bogus device speed!\n", usbcore_name);
851                 return -1;
852         }
853 }
854 EXPORT_SYMBOL (usb_calc_bus_time);
855
856 /*
857  * usb_check_bandwidth():
858  *
859  * old_alloc is from host_controller->bandwidth_allocated in microseconds;
860  * bustime is from calc_bus_time(), but converted to microseconds.
861  *
862  * returns <bustime in us> if successful,
863  * or -ENOSPC if bandwidth request fails.
864  *
865  * FIXME:
866  * This initial implementation does not use Endpoint.bInterval
867  * in managing bandwidth allocation.
868  * It probably needs to be expanded to use Endpoint.bInterval.
869  * This can be done as a later enhancement (correction).
870  *
871  * This will also probably require some kind of
872  * frame allocation tracking...meaning, for example,
873  * that if multiple drivers request interrupts every 10 USB frames,
874  * they don't all have to be allocated at
875  * frame numbers N, N+10, N+20, etc.  Some of them could be at
876  * N+11, N+21, N+31, etc., and others at
877  * N+12, N+22, N+32, etc.
878  *
879  * Similarly for isochronous transfers...
880  *
881  * Individual HCDs can schedule more directly ... this logic
882  * is not correct for high speed transfers.
883  */
884 int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
885 {
886         unsigned int    pipe = urb->pipe;
887         long            bustime;
888         int             is_in = usb_pipein (pipe);
889         int             is_iso = usb_pipeisoc (pipe);
890         int             old_alloc = dev->bus->bandwidth_allocated;
891         int             new_alloc;
892
893
894         bustime = NS_TO_US (usb_calc_bus_time (dev->speed, is_in, is_iso,
895                         usb_maxpacket (dev, pipe, !is_in)));
896         if (is_iso)
897                 bustime /= urb->number_of_packets;
898
899         new_alloc = old_alloc + (int) bustime;
900         if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC) {
901 #ifdef  DEBUG
902                 char    *mode = 
903 #ifdef CONFIG_USB_BANDWIDTH
904                         "";
905 #else
906                         "would have ";
907 #endif
908                 dev_dbg (&dev->dev, "usb_check_bandwidth %sFAILED: %d + %ld = %d usec\n",
909                         mode, old_alloc, bustime, new_alloc);
910 #endif
911 #ifdef CONFIG_USB_BANDWIDTH
912                 bustime = -ENOSPC;      /* report error */
913 #endif
914         }
915
916         return bustime;
917 }
918 EXPORT_SYMBOL (usb_check_bandwidth);
919
920
921 /**
922  * usb_claim_bandwidth - records bandwidth for a periodic transfer
923  * @dev: source/target of request
924  * @urb: request (urb->dev == dev)
925  * @bustime: bandwidth consumed, in (average) microseconds per frame
926  * @isoc: true iff the request is isochronous
927  *
928  * Bus bandwidth reservations are recorded purely for diagnostic purposes.
929  * HCDs are expected not to overcommit periodic bandwidth, and to record such
930  * reservations whenever endpoints are added to the periodic schedule.
931  *
932  * FIXME averaging per-frame is suboptimal.  Better to sum over the HCD's
933  * entire periodic schedule ... 32 frames for OHCI, 1024 for UHCI, settable
934  * for EHCI (256/512/1024 frames, default 1024) and have the bus expose how
935  * large its periodic schedule is.
936  */
937 void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
938 {
939         dev->bus->bandwidth_allocated += bustime;
940         if (isoc)
941                 dev->bus->bandwidth_isoc_reqs++;
942         else
943                 dev->bus->bandwidth_int_reqs++;
944         urb->bandwidth = bustime;
945
946 #ifdef USB_BANDWIDTH_MESSAGES
947         dev_dbg (&dev->dev, "bandwidth alloc increased by %d (%s) to %d for %d requesters\n",
948                 bustime,
949                 isoc ? "ISOC" : "INTR",
950                 dev->bus->bandwidth_allocated,
951                 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
952 #endif
953 }
954 EXPORT_SYMBOL (usb_claim_bandwidth);
955
956
957 /**
958  * usb_release_bandwidth - reverses effect of usb_claim_bandwidth()
959  * @dev: source/target of request
960  * @urb: request (urb->dev == dev)
961  * @isoc: true iff the request is isochronous
962  *
963  * This records that previously allocated bandwidth has been released.
964  * Bandwidth is released when endpoints are removed from the host controller's
965  * periodic schedule.
966  */
967 void usb_release_bandwidth (struct usb_device *dev, struct urb *urb, int isoc)
968 {
969         dev->bus->bandwidth_allocated -= urb->bandwidth;
970         if (isoc)
971                 dev->bus->bandwidth_isoc_reqs--;
972         else
973                 dev->bus->bandwidth_int_reqs--;
974
975 #ifdef USB_BANDWIDTH_MESSAGES
976         dev_dbg (&dev->dev, "bandwidth alloc reduced by %d (%s) to %d for %d requesters\n",
977                 urb->bandwidth,
978                 isoc ? "ISOC" : "INTR",
979                 dev->bus->bandwidth_allocated,
980                 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
981 #endif
982         urb->bandwidth = 0;
983 }
984 EXPORT_SYMBOL (usb_release_bandwidth);
985
986
987 /*-------------------------------------------------------------------------*/
988
989 /*
990  * Generic HC operations.
991  */
992
993 /*-------------------------------------------------------------------------*/
994
995 /* called from khubd, or root hub init threads for hcd-private init */
996 static int hcd_alloc_dev (struct usb_device *udev)
997 {
998         struct hcd_dev          *dev;
999         struct usb_hcd          *hcd;
1000         unsigned long           flags;
1001
1002         if (!udev || udev->hcpriv)
1003                 return -EINVAL;
1004         if (!udev->bus || !udev->bus->hcpriv)
1005                 return -ENODEV;
1006         hcd = udev->bus->hcpriv;
1007         if (hcd->state == USB_STATE_QUIESCING)
1008                 return -ENOLINK;
1009
1010         dev = (struct hcd_dev *) kmalloc (sizeof *dev, GFP_KERNEL);
1011         if (dev == NULL)
1012                 return -ENOMEM;
1013         memset (dev, 0, sizeof *dev);
1014
1015         INIT_LIST_HEAD (&dev->dev_list);
1016         INIT_LIST_HEAD (&dev->urb_list);
1017
1018         spin_lock_irqsave (&hcd_data_lock, flags);
1019         list_add (&dev->dev_list, &hcd->dev_list);
1020         // refcount is implicit
1021         udev->hcpriv = dev;
1022         spin_unlock_irqrestore (&hcd_data_lock, flags);
1023
1024         return 0;
1025 }
1026
1027 /*-------------------------------------------------------------------------*/
1028
1029 static void urb_unlink (struct urb *urb)
1030 {
1031         unsigned long           flags;
1032         struct usb_device       *dev;
1033
1034         /* Release any periodic transfer bandwidth */
1035         if (urb->bandwidth)
1036                 usb_release_bandwidth (urb->dev, urb,
1037                         usb_pipeisoc (urb->pipe));
1038
1039         /* clear all state linking urb to this dev (and hcd) */
1040
1041         spin_lock_irqsave (&hcd_data_lock, flags);
1042         list_del_init (&urb->urb_list);
1043         dev = urb->dev;
1044         spin_unlock_irqrestore (&hcd_data_lock, flags);
1045         usb_put_dev (dev);
1046 }
1047
1048
1049 /* may be called in any context with a valid urb->dev usecount
1050  * caller surrenders "ownership" of urb
1051  * expects usb_submit_urb() to have sanity checked and conditioned all
1052  * inputs in the urb
1053  */
1054 static int hcd_submit_urb (struct urb *urb, int mem_flags)
1055 {
1056         int                     status;
1057         struct usb_hcd          *hcd = urb->dev->bus->hcpriv;
1058         struct hcd_dev          *dev = urb->dev->hcpriv;
1059         unsigned long           flags;
1060
1061         if (!hcd || !dev)
1062                 return -ENODEV;
1063
1064         /*
1065          * FIXME:  make urb timeouts be generic, keeping the HCD cores
1066          * as simple as possible.
1067          */
1068
1069         // NOTE:  a generic device/urb monitoring hook would go here.
1070         // hcd_monitor_hook(MONITOR_URB_SUBMIT, urb)
1071         // It would catch submission paths for all urbs.
1072
1073         /*
1074          * Atomically queue the urb,  first to our records, then to the HCD.
1075          * Access to urb->status is controlled by urb->lock ... changes on
1076          * i/o completion (normal or fault) or unlinking.
1077          */
1078
1079         // FIXME:  verify that quiescing hc works right (RH cleans up)
1080
1081         spin_lock_irqsave (&hcd_data_lock, flags);
1082         if (HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_QUIESCING) {
1083                 usb_get_dev (urb->dev);
1084                 list_add_tail (&urb->urb_list, &dev->urb_list);
1085                 status = 0;
1086         } else {
1087                 INIT_LIST_HEAD (&urb->urb_list);
1088                 status = -ESHUTDOWN;
1089         }
1090         spin_unlock_irqrestore (&hcd_data_lock, flags);
1091         if (status)
1092                 return status;
1093
1094         /* increment urb's reference count as part of giving it to the HCD
1095          * (which now controls it).  HCD guarantees that it either returns
1096          * an error or calls giveback(), but not both.
1097          */
1098         urb = usb_get_urb (urb);
1099         if (urb->dev == hcd->self.root_hub) {
1100                 /* NOTE:  requirement on hub callers (usbfs and the hub
1101                  * driver, for now) that URBs' urb->transfer_buffer be
1102                  * valid and usb_buffer_{sync,unmap}() not be needed, since
1103                  * they could clobber root hub response data.
1104                  */
1105                 urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
1106                                         | URB_NO_SETUP_DMA_MAP);
1107                 status = rh_urb_enqueue (hcd, urb);
1108                 goto done;
1109         }
1110
1111         /* lower level hcd code should use *_dma exclusively,
1112          * unless it uses pio or talks to another transport.
1113          */
1114         if (hcd->self.controller->dma_mask) {
1115                 if (usb_pipecontrol (urb->pipe)
1116                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1117                         urb->setup_dma = dma_map_single (
1118                                         hcd->self.controller,
1119                                         urb->setup_packet,
1120                                         sizeof (struct usb_ctrlrequest),
1121                                         DMA_TO_DEVICE);
1122                 if (urb->transfer_buffer_length != 0
1123                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1124                         urb->transfer_dma = dma_map_single (
1125                                         hcd->self.controller,
1126                                         urb->transfer_buffer,
1127                                         urb->transfer_buffer_length,
1128                                         usb_pipein (urb->pipe)
1129                                             ? DMA_FROM_DEVICE
1130                                             : DMA_TO_DEVICE);
1131         }
1132
1133         status = hcd->driver->urb_enqueue (hcd, urb, mem_flags);
1134 done:
1135         if (status) {
1136                 usb_put_urb (urb);
1137                 urb_unlink (urb);
1138         }
1139         return status;
1140 }
1141
1142 /*-------------------------------------------------------------------------*/
1143
1144 /* called in any context */
1145 static int hcd_get_frame_number (struct usb_device *udev)
1146 {
1147         struct usb_hcd  *hcd = (struct usb_hcd *)udev->bus->hcpriv;
1148         if (!HCD_IS_RUNNING (hcd->state))
1149                 return -ESHUTDOWN;
1150         return hcd->driver->get_frame_number (hcd);
1151 }
1152
1153 /*-------------------------------------------------------------------------*/
1154
1155 /* this makes the hcd giveback() the urb more quickly, by kicking it
1156  * off hardware queues (which may take a while) and returning it as
1157  * soon as practical.  we've already set up the urb's return status,
1158  * but we can't know if the callback completed already.
1159  */
1160 static void
1161 unlink1 (struct usb_hcd *hcd, struct urb *urb)
1162 {
1163         if (urb == (struct urb *) hcd->rh_timer.data)
1164                 usb_rh_status_dequeue (hcd, urb);
1165         else {
1166                 int             value;
1167
1168                 /* failures "should" be harmless */
1169                 value = hcd->driver->urb_dequeue (hcd, urb);
1170                 if (value != 0)
1171                         dev_dbg (hcd->self.controller,
1172                                 "dequeue %p --> %d\n",
1173                                 urb, value);
1174         }
1175 }
1176
1177 struct completion_splice {              // modified urb context:
1178         /* did we complete? */
1179         struct completion       done;
1180
1181         /* original urb data */
1182         usb_complete_t          complete;
1183         void                    *context;
1184 };
1185
1186 static void unlink_complete (struct urb *urb, struct pt_regs *regs)
1187 {
1188         struct completion_splice        *splice;
1189
1190         splice = (struct completion_splice *) urb->context;
1191
1192         /* issue original completion call */
1193         urb->complete = splice->complete;
1194         urb->context = splice->context;
1195         urb->complete (urb, regs);
1196
1197         /* then let the synchronous unlink call complete */
1198         complete (&splice->done);
1199 }
1200
1201 /*
1202  * called in any context; note ASYNC_UNLINK restrictions
1203  *
1204  * caller guarantees urb won't be recycled till both unlink()
1205  * and the urb's completion function return
1206  */
1207 static int hcd_unlink_urb (struct urb *urb)
1208 {
1209         struct hcd_dev                  *dev;
1210         struct usb_hcd                  *hcd = 0;
1211         struct device                   *sys = 0;
1212         unsigned long                   flags;
1213         struct completion_splice        splice;
1214         struct list_head                *tmp;
1215         int                             retval;
1216
1217         if (!urb)
1218                 return -EINVAL;
1219
1220         /*
1221          * we contend for urb->status with the hcd core,
1222          * which changes it while returning the urb.
1223          *
1224          * Caller guaranteed that the urb pointer hasn't been freed, and
1225          * that it was submitted.  But as a rule it can't know whether or
1226          * not it's already been unlinked ... so we respect the reversed
1227          * lock sequence needed for the usb_hcd_giveback_urb() code paths
1228          * (urb lock, then hcd_data_lock) in case some other CPU is now
1229          * unlinking it.
1230          */
1231         spin_lock_irqsave (&urb->lock, flags);
1232         spin_lock (&hcd_data_lock);
1233
1234         if (!urb->dev || !urb->dev->bus) {
1235                 retval = -ENODEV;
1236                 goto done;
1237         }
1238
1239         dev = urb->dev->hcpriv;
1240         sys = &urb->dev->dev;
1241         hcd = urb->dev->bus->hcpriv;
1242         if (!dev || !hcd) {
1243                 retval = -ENODEV;
1244                 goto done;
1245         }
1246
1247         /* running ~= hc unlink handshake works (irq, timer, etc)
1248          * halted ~= no unlink handshake is needed
1249          * suspended, resuming == should never happen
1250          */
1251         WARN_ON (!HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_HALT);
1252
1253         /* insist the urb is still queued */
1254         list_for_each(tmp, &dev->urb_list) {
1255                 if (tmp == &urb->urb_list)
1256                         break;
1257         }
1258         if (tmp != &urb->urb_list) {
1259                 retval = -EIDRM;
1260                 goto done;
1261         }
1262
1263         /* Any status except -EINPROGRESS means something already started to
1264          * unlink this URB from the hardware.  So there's no more work to do.
1265          *
1266          * FIXME use better explicit urb state
1267          */
1268         if (urb->status != -EINPROGRESS) {
1269                 retval = -EBUSY;
1270                 goto done;
1271         }
1272
1273         /* PCI IRQ setup can easily be broken so that USB controllers
1274          * never get completion IRQs ... maybe even the ones we need to
1275          * finish unlinking the initial failed usb_set_address().
1276          */
1277         if (!hcd->saw_irq) {
1278                 dev_warn (hcd->self.controller, "Unlink after no-IRQ?  "
1279                         "Different ACPI or APIC settings may help."
1280                         "\n");
1281                 hcd->saw_irq = 1;
1282         }
1283
1284         /* maybe set up to block until the urb's completion fires.  the
1285          * lower level hcd code is always async, locking on urb->status
1286          * updates; an intercepted completion unblocks us.
1287          */
1288         if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1289                 if (in_interrupt ()) {
1290                         dev_dbg (hcd->self.controller, 
1291                                 "non-async unlink in_interrupt");
1292                         retval = -EWOULDBLOCK;
1293                         goto done;
1294                 }
1295                 /* synchronous unlink: block till we see the completion */
1296                 init_completion (&splice.done);
1297                 splice.complete = urb->complete;
1298                 splice.context = urb->context;
1299                 urb->complete = unlink_complete;
1300                 urb->context = &splice;
1301                 urb->status = -ENOENT;
1302         } else {
1303                 /* asynchronous unlink */
1304                 urb->status = -ECONNRESET;
1305         }
1306         spin_unlock (&hcd_data_lock);
1307         spin_unlock_irqrestore (&urb->lock, flags);
1308
1309         // FIXME remove splicing, so this becomes unlink1 (hcd, urb);
1310         if (urb == (struct urb *) hcd->rh_timer.data) {
1311                 usb_rh_status_dequeue (hcd, urb);
1312                 retval = 0;
1313         } else {
1314                 retval = hcd->driver->urb_dequeue (hcd, urb);
1315
1316                 /* hcds shouldn't really fail these calls, but... */
1317                 if (retval) {
1318                         dev_dbg (sys, "dequeue %p --> %d\n", urb, retval);
1319                         if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1320                                 spin_lock_irqsave (&urb->lock, flags);
1321                                 urb->complete = splice.complete;
1322                                 urb->context = splice.context;
1323                                 spin_unlock_irqrestore (&urb->lock, flags);
1324                         }
1325                         goto bye;
1326                 }
1327         }
1328
1329         /* block till giveback, if needed */
1330         if (urb->transfer_flags & URB_ASYNC_UNLINK)
1331                 return -EINPROGRESS;
1332
1333         wait_for_completion (&splice.done);
1334         return 0;
1335
1336 done:
1337         spin_unlock (&hcd_data_lock);
1338         spin_unlock_irqrestore (&urb->lock, flags);
1339 bye:
1340         if (retval != -EIDRM && sys && sys->driver)
1341                 dev_dbg (sys, "hcd_unlink_urb %p fail %d\n", urb, retval);
1342         return retval;
1343 }
1344
1345 /*-------------------------------------------------------------------------*/
1346
1347 /* disables the endpoint: cancels any pending urbs, then synchronizes with
1348  * the hcd to make sure all endpoint state is gone from hardware. use for
1349  * set_configuration, set_interface, driver removal, physical disconnect.
1350  *
1351  * example:  a qh stored in hcd_dev.ep[], holding state related to endpoint
1352  * type, maxpacket size, toggle, halt status, and scheduling.
1353  */
1354 static void hcd_endpoint_disable (struct usb_device *udev, int endpoint)
1355 {
1356         struct hcd_dev  *dev;
1357         struct usb_hcd  *hcd;
1358         struct urb      *urb;
1359         unsigned        epnum = endpoint & USB_ENDPOINT_NUMBER_MASK;
1360
1361         dev = udev->hcpriv;
1362         hcd = udev->bus->hcpriv;
1363
1364         WARN_ON (!HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_HALT);
1365
1366         local_irq_disable ();
1367
1368 rescan:
1369         /* (re)block new requests, as best we can */
1370         if (endpoint & USB_DIR_IN) {
1371                 usb_endpoint_halt (udev, epnum, 0);
1372                 udev->epmaxpacketin [epnum] = 0;
1373         } else {
1374                 usb_endpoint_halt (udev, epnum, 1);
1375                 udev->epmaxpacketout [epnum] = 0;
1376         }
1377
1378         /* then kill any current requests */
1379         spin_lock (&hcd_data_lock);
1380         list_for_each_entry (urb, &dev->urb_list, urb_list) {
1381                 int     tmp = urb->pipe;
1382
1383                 /* ignore urbs for other endpoints */
1384                 if (usb_pipeendpoint (tmp) != epnum)
1385                         continue;
1386                 /* NOTE assumption that only ep0 is a control endpoint */
1387                 if (epnum != 0 && ((tmp ^ endpoint) & USB_DIR_IN))
1388                         continue;
1389
1390                 /* another cpu may be in hcd, spinning on hcd_data_lock
1391                  * to giveback() this urb.  the races here should be
1392                  * small, but a full fix needs a new "can't submit"
1393                  * urb state.
1394                  */
1395                 if (urb->status != -EINPROGRESS)
1396                         continue;
1397                 usb_get_urb (urb);
1398                 spin_unlock (&hcd_data_lock);
1399
1400                 spin_lock (&urb->lock);
1401                 tmp = urb->status;
1402                 if (tmp == -EINPROGRESS)
1403                         urb->status = -ESHUTDOWN;
1404                 spin_unlock (&urb->lock);
1405
1406                 /* kick hcd unless it's already returning this */
1407                 if (tmp == -EINPROGRESS) {
1408                         tmp = urb->pipe;
1409                         unlink1 (hcd, urb);
1410                         dev_dbg (hcd->self.controller,
1411                                 "shutdown urb %p pipe %08x ep%d%s%s\n",
1412                                 urb, tmp, usb_pipeendpoint (tmp),
1413                                 (tmp & USB_DIR_IN) ? "in" : "out",
1414                                 ({ char *s; \
1415                                  switch (usb_pipetype (tmp)) { \
1416                                  case PIPE_CONTROL:     s = ""; break; \
1417                                  case PIPE_BULK:        s = "-bulk"; break; \
1418                                  case PIPE_INTERRUPT:   s = "-intr"; break; \
1419                                  default:               s = "-iso"; break; \
1420                                 }; s;}));
1421                 }
1422                 usb_put_urb (urb);
1423
1424                 /* list contents may have changed */
1425                 goto rescan;
1426         }
1427         spin_unlock (&hcd_data_lock);
1428         local_irq_enable ();
1429
1430         /* synchronize with the hardware, so old configuration state
1431          * clears out immediately (and will be freed).
1432          */
1433         might_sleep ();
1434         if (hcd->driver->endpoint_disable)
1435                 hcd->driver->endpoint_disable (hcd, dev, endpoint);
1436 }
1437
1438 /*-------------------------------------------------------------------------*/
1439
1440 /* called by khubd, rmmod, apmd, or other thread for hcd-private cleanup.
1441  * we're guaranteed that the device is fully quiesced.  also, that each
1442  * endpoint has been hcd_endpoint_disabled.
1443  */
1444
1445 static int hcd_free_dev (struct usb_device *udev)
1446 {
1447         struct hcd_dev          *dev;
1448         struct usb_hcd          *hcd;
1449         unsigned long           flags;
1450
1451         if (!udev || !udev->hcpriv)
1452                 return -EINVAL;
1453
1454         if (!udev->bus || !udev->bus->hcpriv)
1455                 return -ENODEV;
1456
1457         // should udev->devnum == -1 ??
1458
1459         dev = udev->hcpriv;
1460         hcd = udev->bus->hcpriv;
1461
1462         /* device driver problem with refcounts? */
1463         if (!list_empty (&dev->urb_list)) {
1464                 dev_dbg (hcd->self.controller, "free busy dev, %s devnum %d (bug!)\n",
1465                         hcd->self.bus_name, udev->devnum);
1466                 return -EINVAL;
1467         }
1468
1469         spin_lock_irqsave (&hcd_data_lock, flags);
1470         list_del (&dev->dev_list);
1471         udev->hcpriv = NULL;
1472         spin_unlock_irqrestore (&hcd_data_lock, flags);
1473
1474         kfree (dev);
1475         return 0;
1476 }
1477
1478 /*
1479  * usb_hcd_operations - adapts usb_bus framework to HCD framework (bus glue)
1480  *
1481  * When registering a USB bus through the HCD framework code, use this
1482  * usb_operations vector.  The PCI glue layer does so automatically; only
1483  * bus glue for non-PCI system busses will need to use this.
1484  */
1485 struct usb_operations usb_hcd_operations = {
1486         .allocate =             hcd_alloc_dev,
1487         .get_frame_number =     hcd_get_frame_number,
1488         .submit_urb =           hcd_submit_urb,
1489         .unlink_urb =           hcd_unlink_urb,
1490         .deallocate =           hcd_free_dev,
1491         .buffer_alloc =         hcd_buffer_alloc,
1492         .buffer_free =          hcd_buffer_free,
1493         .disable =              hcd_endpoint_disable,
1494 };
1495 EXPORT_SYMBOL (usb_hcd_operations);
1496
1497 /*-------------------------------------------------------------------------*/
1498
1499 /**
1500  * usb_hcd_giveback_urb - return URB from HCD to device driver
1501  * @hcd: host controller returning the URB
1502  * @urb: urb being returned to the USB device driver.
1503  * @regs: pt_regs, passed down to the URB completion handler
1504  * Context: in_interrupt()
1505  *
1506  * This hands the URB from HCD to its USB device driver, using its
1507  * completion function.  The HCD has freed all per-urb resources
1508  * (and is done using urb->hcpriv).  It also released all HCD locks;
1509  * the device driver won't cause problems if it frees, modifies,
1510  * or resubmits this URB.
1511  */
1512 void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb, struct pt_regs *regs)
1513 {
1514         urb_unlink (urb);
1515
1516         // NOTE:  a generic device/urb monitoring hook would go here.
1517         // hcd_monitor_hook(MONITOR_URB_FINISH, urb, dev)
1518         // It would catch exit/unlink paths for all urbs.
1519
1520         /* lower level hcd code should use *_dma exclusively */
1521         if (hcd->self.controller->dma_mask) {
1522                 if (usb_pipecontrol (urb->pipe)
1523                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1524                         dma_unmap_single (hcd->self.controller, urb->setup_dma,
1525                                         sizeof (struct usb_ctrlrequest),
1526                                         DMA_TO_DEVICE);
1527                 if (urb->transfer_buffer_length != 0
1528                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1529                         dma_unmap_single (hcd->self.controller, 
1530                                         urb->transfer_dma,
1531                                         urb->transfer_buffer_length,
1532                                         usb_pipein (urb->pipe)
1533                                             ? DMA_FROM_DEVICE
1534                                             : DMA_TO_DEVICE);
1535         }
1536
1537         /* pass ownership to the completion handler */
1538         urb->complete (urb, regs);
1539         usb_put_urb (urb);
1540 }
1541 EXPORT_SYMBOL (usb_hcd_giveback_urb);
1542
1543 /*-------------------------------------------------------------------------*/
1544
1545 /**
1546  * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
1547  * @irq: the IRQ being raised
1548  * @__hcd: pointer to the HCD whose IRQ is beinng signaled
1549  * @r: saved hardware registers
1550  *
1551  * When registering a USB bus through the HCD framework code, use this
1552  * to handle interrupts.  The PCI glue layer does so automatically; only
1553  * bus glue for non-PCI system busses will need to use this.
1554  */
1555 irqreturn_t usb_hcd_irq (int irq, void *__hcd, struct pt_regs * r)
1556 {
1557         struct usb_hcd          *hcd = __hcd;
1558         int                     start = hcd->state;
1559
1560         if (unlikely (hcd->state == USB_STATE_HALT))    /* irq sharing? */
1561                 return IRQ_NONE;
1562
1563         hcd->saw_irq = 1;
1564         if (hcd->driver->irq (hcd, r) == IRQ_NONE)
1565                 return IRQ_NONE;
1566
1567         if (hcd->state != start && hcd->state == USB_STATE_HALT)
1568                 usb_hc_died (hcd);
1569         return IRQ_HANDLED;
1570 }
1571 EXPORT_SYMBOL (usb_hcd_irq);
1572
1573 /*-------------------------------------------------------------------------*/
1574
1575 static void hcd_panic (void *_hcd)
1576 {
1577         struct usb_hcd          *hcd = _hcd;
1578         struct usb_device       *hub = hcd->self.root_hub;
1579         unsigned                i;
1580
1581         /* hc's root hub is removed later removed in hcd->stop() */
1582         down (&hub->serialize);
1583         usb_set_device_state(hub, USB_STATE_NOTATTACHED);
1584         for (i = 0; i < hub->maxchild; i++) {
1585                 if (hub->children [i])
1586                         usb_disconnect (&hub->children [i]);
1587         }
1588         up (&hub->serialize);
1589 }
1590
1591 /**
1592  * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
1593  * @hcd: pointer to the HCD representing the controller
1594  *
1595  * This is called by bus glue to report a USB host controller that died
1596  * while operations may still have been pending.  It's called automatically
1597  * by the PCI glue, so only glue for non-PCI busses should need to call it. 
1598  */
1599 void usb_hc_died (struct usb_hcd *hcd)
1600 {
1601         dev_err (hcd->self.controller, "HC died; cleaning up\n");
1602
1603         /* clean up old urbs and devices; needs a task context */
1604         INIT_WORK (&hcd->work, hcd_panic, hcd);
1605         (void) schedule_work (&hcd->work);
1606 }
1607 EXPORT_SYMBOL (usb_hc_died);
1608