patch-2_6_7-vs1_9_1_12
[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 model tree, and then calls usb_new_device() to register the
768  * usb device.  It also assigns the root hub's USB address (always 1).
769  */
770 int usb_register_root_hub (struct usb_device *usb_dev, struct device *parent_dev)
771 {
772         const int devnum = 1;
773         int retval;
774
775         usb_dev->devnum = devnum;
776         usb_dev->bus->devnum_next = devnum + 1;
777         memset (&usb_dev->bus->devmap.devicemap, 0,
778                         sizeof usb_dev->bus->devmap.devicemap);
779         set_bit (devnum, usb_dev->bus->devmap.devicemap);
780         usb_dev->state = USB_STATE_ADDRESS;
781
782         usb_dev->epmaxpacketin[0] = usb_dev->epmaxpacketout[0] = 64;
783         retval = usb_get_device_descriptor(usb_dev, USB_DT_DEVICE_SIZE);
784         if (retval != sizeof usb_dev->descriptor) {
785                 dev_dbg (parent_dev, "can't read %s device descriptor %d\n",
786                                 usb_dev->dev.bus_id, retval);
787                 return (retval < 0) ? retval : -EMSGSIZE;
788         }
789
790         (void) usb_get_dev (usb_dev);
791         down (&usb_dev->serialize);
792         retval = usb_new_device (usb_dev);
793         if (retval)
794                 dev_err (parent_dev, "can't register root hub for %s, %d\n",
795                                 usb_dev->dev.bus_id, retval);
796         up (&usb_dev->serialize);
797         usb_put_dev (usb_dev);
798         return retval;
799 }
800 EXPORT_SYMBOL (usb_register_root_hub);
801
802
803 /*-------------------------------------------------------------------------*/
804
805 /**
806  * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
807  * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
808  * @is_input: true iff the transaction sends data to the host
809  * @isoc: true for isochronous transactions, false for interrupt ones
810  * @bytecount: how many bytes in the transaction.
811  *
812  * Returns approximate bus time in nanoseconds for a periodic transaction.
813  * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
814  * scheduled in software, this function is only used for such scheduling.
815  */
816 long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
817 {
818         unsigned long   tmp;
819
820         switch (speed) {
821         case USB_SPEED_LOW:     /* INTR only */
822                 if (is_input) {
823                         tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
824                         return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
825                 } else {
826                         tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
827                         return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
828                 }
829         case USB_SPEED_FULL:    /* ISOC or INTR */
830                 if (isoc) {
831                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
832                         return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
833                 } else {
834                         tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
835                         return (9107L + BW_HOST_DELAY + tmp);
836                 }
837         case USB_SPEED_HIGH:    /* ISOC or INTR */
838                 // FIXME adjust for input vs output
839                 if (isoc)
840                         tmp = HS_USECS (bytecount);
841                 else
842                         tmp = HS_USECS_ISO (bytecount);
843                 return tmp;
844         default:
845                 pr_debug ("%s: bogus device speed!\n", usbcore_name);
846                 return -1;
847         }
848 }
849 EXPORT_SYMBOL (usb_calc_bus_time);
850
851 /*
852  * usb_check_bandwidth():
853  *
854  * old_alloc is from host_controller->bandwidth_allocated in microseconds;
855  * bustime is from calc_bus_time(), but converted to microseconds.
856  *
857  * returns <bustime in us> if successful,
858  * or -ENOSPC if bandwidth request fails.
859  *
860  * FIXME:
861  * This initial implementation does not use Endpoint.bInterval
862  * in managing bandwidth allocation.
863  * It probably needs to be expanded to use Endpoint.bInterval.
864  * This can be done as a later enhancement (correction).
865  *
866  * This will also probably require some kind of
867  * frame allocation tracking...meaning, for example,
868  * that if multiple drivers request interrupts every 10 USB frames,
869  * they don't all have to be allocated at
870  * frame numbers N, N+10, N+20, etc.  Some of them could be at
871  * N+11, N+21, N+31, etc., and others at
872  * N+12, N+22, N+32, etc.
873  *
874  * Similarly for isochronous transfers...
875  *
876  * Individual HCDs can schedule more directly ... this logic
877  * is not correct for high speed transfers.
878  */
879 int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
880 {
881         unsigned int    pipe = urb->pipe;
882         long            bustime;
883         int             is_in = usb_pipein (pipe);
884         int             is_iso = usb_pipeisoc (pipe);
885         int             old_alloc = dev->bus->bandwidth_allocated;
886         int             new_alloc;
887
888
889         bustime = NS_TO_US (usb_calc_bus_time (dev->speed, is_in, is_iso,
890                         usb_maxpacket (dev, pipe, !is_in)));
891         if (is_iso)
892                 bustime /= urb->number_of_packets;
893
894         new_alloc = old_alloc + (int) bustime;
895         if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC) {
896 #ifdef  DEBUG
897                 char    *mode = 
898 #ifdef CONFIG_USB_BANDWIDTH
899                         "";
900 #else
901                         "would have ";
902 #endif
903                 dev_dbg (&dev->dev, "usb_check_bandwidth %sFAILED: %d + %ld = %d usec\n",
904                         mode, old_alloc, bustime, new_alloc);
905 #endif
906 #ifdef CONFIG_USB_BANDWIDTH
907                 bustime = -ENOSPC;      /* report error */
908 #endif
909         }
910
911         return bustime;
912 }
913 EXPORT_SYMBOL (usb_check_bandwidth);
914
915
916 /**
917  * usb_claim_bandwidth - records bandwidth for a periodic transfer
918  * @dev: source/target of request
919  * @urb: request (urb->dev == dev)
920  * @bustime: bandwidth consumed, in (average) microseconds per frame
921  * @isoc: true iff the request is isochronous
922  *
923  * Bus bandwidth reservations are recorded purely for diagnostic purposes.
924  * HCDs are expected not to overcommit periodic bandwidth, and to record such
925  * reservations whenever endpoints are added to the periodic schedule.
926  *
927  * FIXME averaging per-frame is suboptimal.  Better to sum over the HCD's
928  * entire periodic schedule ... 32 frames for OHCI, 1024 for UHCI, settable
929  * for EHCI (256/512/1024 frames, default 1024) and have the bus expose how
930  * large its periodic schedule is.
931  */
932 void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
933 {
934         dev->bus->bandwidth_allocated += bustime;
935         if (isoc)
936                 dev->bus->bandwidth_isoc_reqs++;
937         else
938                 dev->bus->bandwidth_int_reqs++;
939         urb->bandwidth = bustime;
940
941 #ifdef USB_BANDWIDTH_MESSAGES
942         dev_dbg (&dev->dev, "bandwidth alloc increased by %d (%s) to %d for %d requesters\n",
943                 bustime,
944                 isoc ? "ISOC" : "INTR",
945                 dev->bus->bandwidth_allocated,
946                 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
947 #endif
948 }
949 EXPORT_SYMBOL (usb_claim_bandwidth);
950
951
952 /**
953  * usb_release_bandwidth - reverses effect of usb_claim_bandwidth()
954  * @dev: source/target of request
955  * @urb: request (urb->dev == dev)
956  * @isoc: true iff the request is isochronous
957  *
958  * This records that previously allocated bandwidth has been released.
959  * Bandwidth is released when endpoints are removed from the host controller's
960  * periodic schedule.
961  */
962 void usb_release_bandwidth (struct usb_device *dev, struct urb *urb, int isoc)
963 {
964         dev->bus->bandwidth_allocated -= urb->bandwidth;
965         if (isoc)
966                 dev->bus->bandwidth_isoc_reqs--;
967         else
968                 dev->bus->bandwidth_int_reqs--;
969
970 #ifdef USB_BANDWIDTH_MESSAGES
971         dev_dbg (&dev->dev, "bandwidth alloc reduced by %d (%s) to %d for %d requesters\n",
972                 urb->bandwidth,
973                 isoc ? "ISOC" : "INTR",
974                 dev->bus->bandwidth_allocated,
975                 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
976 #endif
977         urb->bandwidth = 0;
978 }
979 EXPORT_SYMBOL (usb_release_bandwidth);
980
981
982 /*-------------------------------------------------------------------------*/
983
984 /*
985  * Generic HC operations.
986  */
987
988 /*-------------------------------------------------------------------------*/
989
990 /* called from khubd, or root hub init threads for hcd-private init */
991 static int hcd_alloc_dev (struct usb_device *udev)
992 {
993         struct hcd_dev          *dev;
994         struct usb_hcd          *hcd;
995         unsigned long           flags;
996
997         if (!udev || udev->hcpriv)
998                 return -EINVAL;
999         if (!udev->bus || !udev->bus->hcpriv)
1000                 return -ENODEV;
1001         hcd = udev->bus->hcpriv;
1002         if (hcd->state == USB_STATE_QUIESCING)
1003                 return -ENOLINK;
1004
1005         dev = (struct hcd_dev *) kmalloc (sizeof *dev, GFP_KERNEL);
1006         if (dev == NULL)
1007                 return -ENOMEM;
1008         memset (dev, 0, sizeof *dev);
1009
1010         INIT_LIST_HEAD (&dev->dev_list);
1011         INIT_LIST_HEAD (&dev->urb_list);
1012
1013         spin_lock_irqsave (&hcd_data_lock, flags);
1014         list_add (&dev->dev_list, &hcd->dev_list);
1015         // refcount is implicit
1016         udev->hcpriv = dev;
1017         spin_unlock_irqrestore (&hcd_data_lock, flags);
1018
1019         return 0;
1020 }
1021
1022 /*-------------------------------------------------------------------------*/
1023
1024 static void urb_unlink (struct urb *urb)
1025 {
1026         unsigned long           flags;
1027         struct usb_device       *dev;
1028
1029         /* Release any periodic transfer bandwidth */
1030         if (urb->bandwidth)
1031                 usb_release_bandwidth (urb->dev, urb,
1032                         usb_pipeisoc (urb->pipe));
1033
1034         /* clear all state linking urb to this dev (and hcd) */
1035
1036         spin_lock_irqsave (&hcd_data_lock, flags);
1037         list_del_init (&urb->urb_list);
1038         dev = urb->dev;
1039         spin_unlock_irqrestore (&hcd_data_lock, flags);
1040         usb_put_dev (dev);
1041 }
1042
1043
1044 /* may be called in any context with a valid urb->dev usecount
1045  * caller surrenders "ownership" of urb
1046  * expects usb_submit_urb() to have sanity checked and conditioned all
1047  * inputs in the urb
1048  */
1049 static int hcd_submit_urb (struct urb *urb, int mem_flags)
1050 {
1051         int                     status;
1052         struct usb_hcd          *hcd = urb->dev->bus->hcpriv;
1053         struct hcd_dev          *dev = urb->dev->hcpriv;
1054         unsigned long           flags;
1055
1056         if (!hcd || !dev)
1057                 return -ENODEV;
1058
1059         /*
1060          * FIXME:  make urb timeouts be generic, keeping the HCD cores
1061          * as simple as possible.
1062          */
1063
1064         // NOTE:  a generic device/urb monitoring hook would go here.
1065         // hcd_monitor_hook(MONITOR_URB_SUBMIT, urb)
1066         // It would catch submission paths for all urbs.
1067
1068         /*
1069          * Atomically queue the urb,  first to our records, then to the HCD.
1070          * Access to urb->status is controlled by urb->lock ... changes on
1071          * i/o completion (normal or fault) or unlinking.
1072          */
1073
1074         // FIXME:  verify that quiescing hc works right (RH cleans up)
1075
1076         spin_lock_irqsave (&hcd_data_lock, flags);
1077         if (HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_QUIESCING) {
1078                 usb_get_dev (urb->dev);
1079                 list_add_tail (&urb->urb_list, &dev->urb_list);
1080                 status = 0;
1081         } else {
1082                 INIT_LIST_HEAD (&urb->urb_list);
1083                 status = -ESHUTDOWN;
1084         }
1085         spin_unlock_irqrestore (&hcd_data_lock, flags);
1086         if (status)
1087                 return status;
1088
1089         /* increment urb's reference count as part of giving it to the HCD
1090          * (which now controls it).  HCD guarantees that it either returns
1091          * an error or calls giveback(), but not both.
1092          */
1093         urb = usb_get_urb (urb);
1094         if (urb->dev == hcd->self.root_hub) {
1095                 /* NOTE:  requirement on hub callers (usbfs and the hub
1096                  * driver, for now) that URBs' urb->transfer_buffer be
1097                  * valid and usb_buffer_{sync,unmap}() not be needed, since
1098                  * they could clobber root hub response data.
1099                  */
1100                 urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
1101                                         | URB_NO_SETUP_DMA_MAP);
1102                 status = rh_urb_enqueue (hcd, urb);
1103                 goto done;
1104         }
1105
1106         /* lower level hcd code should use *_dma exclusively,
1107          * unless it uses pio or talks to another transport.
1108          */
1109         if (hcd->self.controller->dma_mask) {
1110                 if (usb_pipecontrol (urb->pipe)
1111                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1112                         urb->setup_dma = dma_map_single (
1113                                         hcd->self.controller,
1114                                         urb->setup_packet,
1115                                         sizeof (struct usb_ctrlrequest),
1116                                         DMA_TO_DEVICE);
1117                 if (urb->transfer_buffer_length != 0
1118                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1119                         urb->transfer_dma = dma_map_single (
1120                                         hcd->self.controller,
1121                                         urb->transfer_buffer,
1122                                         urb->transfer_buffer_length,
1123                                         usb_pipein (urb->pipe)
1124                                             ? DMA_FROM_DEVICE
1125                                             : DMA_TO_DEVICE);
1126         }
1127
1128         status = hcd->driver->urb_enqueue (hcd, urb, mem_flags);
1129 done:
1130         if (status) {
1131                 usb_put_urb (urb);
1132                 urb_unlink (urb);
1133         }
1134         return status;
1135 }
1136
1137 /*-------------------------------------------------------------------------*/
1138
1139 /* called in any context */
1140 static int hcd_get_frame_number (struct usb_device *udev)
1141 {
1142         struct usb_hcd  *hcd = (struct usb_hcd *)udev->bus->hcpriv;
1143         if (!HCD_IS_RUNNING (hcd->state))
1144                 return -ESHUTDOWN;
1145         return hcd->driver->get_frame_number (hcd);
1146 }
1147
1148 /*-------------------------------------------------------------------------*/
1149
1150 /* this makes the hcd giveback() the urb more quickly, by kicking it
1151  * off hardware queues (which may take a while) and returning it as
1152  * soon as practical.  we've already set up the urb's return status,
1153  * but we can't know if the callback completed already.
1154  */
1155 static void
1156 unlink1 (struct usb_hcd *hcd, struct urb *urb)
1157 {
1158         if (urb == (struct urb *) hcd->rh_timer.data)
1159                 usb_rh_status_dequeue (hcd, urb);
1160         else {
1161                 int             value;
1162
1163                 /* failures "should" be harmless */
1164                 value = hcd->driver->urb_dequeue (hcd, urb);
1165                 if (value != 0)
1166                         dev_dbg (hcd->self.controller,
1167                                 "dequeue %p --> %d\n",
1168                                 urb, value);
1169         }
1170 }
1171
1172 struct completion_splice {              // modified urb context:
1173         /* did we complete? */
1174         struct completion       done;
1175
1176         /* original urb data */
1177         usb_complete_t          complete;
1178         void                    *context;
1179 };
1180
1181 static void unlink_complete (struct urb *urb, struct pt_regs *regs)
1182 {
1183         struct completion_splice        *splice;
1184
1185         splice = (struct completion_splice *) urb->context;
1186
1187         /* issue original completion call */
1188         urb->complete = splice->complete;
1189         urb->context = splice->context;
1190         urb->complete (urb, regs);
1191
1192         /* then let the synchronous unlink call complete */
1193         complete (&splice->done);
1194 }
1195
1196 /*
1197  * called in any context; note ASYNC_UNLINK restrictions
1198  *
1199  * caller guarantees urb won't be recycled till both unlink()
1200  * and the urb's completion function return
1201  */
1202 static int hcd_unlink_urb (struct urb *urb)
1203 {
1204         struct hcd_dev                  *dev;
1205         struct usb_hcd                  *hcd = 0;
1206         struct device                   *sys = 0;
1207         unsigned long                   flags;
1208         struct completion_splice        splice;
1209         struct list_head                *tmp;
1210         int                             retval;
1211
1212         if (!urb)
1213                 return -EINVAL;
1214
1215         /*
1216          * we contend for urb->status with the hcd core,
1217          * which changes it while returning the urb.
1218          *
1219          * Caller guaranteed that the urb pointer hasn't been freed, and
1220          * that it was submitted.  But as a rule it can't know whether or
1221          * not it's already been unlinked ... so we respect the reversed
1222          * lock sequence needed for the usb_hcd_giveback_urb() code paths
1223          * (urb lock, then hcd_data_lock) in case some other CPU is now
1224          * unlinking it.
1225          */
1226         spin_lock_irqsave (&urb->lock, flags);
1227         spin_lock (&hcd_data_lock);
1228
1229         if (!urb->dev || !urb->dev->bus) {
1230                 retval = -ENODEV;
1231                 goto done;
1232         }
1233
1234         dev = urb->dev->hcpriv;
1235         sys = &urb->dev->dev;
1236         hcd = urb->dev->bus->hcpriv;
1237         if (!dev || !hcd) {
1238                 retval = -ENODEV;
1239                 goto done;
1240         }
1241
1242         /* running ~= hc unlink handshake works (irq, timer, etc)
1243          * halted ~= no unlink handshake is needed
1244          * suspended, resuming == should never happen
1245          */
1246         WARN_ON (!HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_HALT);
1247
1248         /* insist the urb is still queued */
1249         list_for_each(tmp, &dev->urb_list) {
1250                 if (tmp == &urb->urb_list)
1251                         break;
1252         }
1253         if (tmp != &urb->urb_list) {
1254                 retval = -EIDRM;
1255                 goto done;
1256         }
1257
1258         /* Any status except -EINPROGRESS means something already started to
1259          * unlink this URB from the hardware.  So there's no more work to do.
1260          *
1261          * FIXME use better explicit urb state
1262          */
1263         if (urb->status != -EINPROGRESS) {
1264                 retval = -EBUSY;
1265                 goto done;
1266         }
1267
1268         /* PCI IRQ setup can easily be broken so that USB controllers
1269          * never get completion IRQs ... maybe even the ones we need to
1270          * finish unlinking the initial failed usb_set_address().
1271          */
1272         if (!hcd->saw_irq) {
1273                 dev_warn (hcd->self.controller, "Unlink after no-IRQ?  "
1274                         "Different ACPI or APIC settings may help."
1275                         "\n");
1276                 hcd->saw_irq = 1;
1277         }
1278
1279         /* maybe set up to block until the urb's completion fires.  the
1280          * lower level hcd code is always async, locking on urb->status
1281          * updates; an intercepted completion unblocks us.
1282          */
1283         if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1284                 if (in_interrupt ()) {
1285                         dev_dbg (hcd->self.controller, 
1286                                 "non-async unlink in_interrupt");
1287                         retval = -EWOULDBLOCK;
1288                         goto done;
1289                 }
1290                 /* synchronous unlink: block till we see the completion */
1291                 init_completion (&splice.done);
1292                 splice.complete = urb->complete;
1293                 splice.context = urb->context;
1294                 urb->complete = unlink_complete;
1295                 urb->context = &splice;
1296                 urb->status = -ENOENT;
1297         } else {
1298                 /* asynchronous unlink */
1299                 urb->status = -ECONNRESET;
1300         }
1301         spin_unlock (&hcd_data_lock);
1302         spin_unlock_irqrestore (&urb->lock, flags);
1303
1304         // FIXME remove splicing, so this becomes unlink1 (hcd, urb);
1305         if (urb == (struct urb *) hcd->rh_timer.data) {
1306                 usb_rh_status_dequeue (hcd, urb);
1307                 retval = 0;
1308         } else {
1309                 retval = hcd->driver->urb_dequeue (hcd, urb);
1310
1311                 /* hcds shouldn't really fail these calls, but... */
1312                 if (retval) {
1313                         dev_dbg (sys, "dequeue %p --> %d\n", urb, retval);
1314                         if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1315                                 spin_lock_irqsave (&urb->lock, flags);
1316                                 urb->complete = splice.complete;
1317                                 urb->context = splice.context;
1318                                 spin_unlock_irqrestore (&urb->lock, flags);
1319                         }
1320                         goto bye;
1321                 }
1322         }
1323
1324         /* block till giveback, if needed */
1325         if (urb->transfer_flags & URB_ASYNC_UNLINK)
1326                 return -EINPROGRESS;
1327
1328         wait_for_completion (&splice.done);
1329         return 0;
1330
1331 done:
1332         spin_unlock (&hcd_data_lock);
1333         spin_unlock_irqrestore (&urb->lock, flags);
1334 bye:
1335         if (retval != -EIDRM && sys && sys->driver)
1336                 dev_dbg (sys, "hcd_unlink_urb %p fail %d\n", urb, retval);
1337         return retval;
1338 }
1339
1340 /*-------------------------------------------------------------------------*/
1341
1342 /* disables the endpoint: cancels any pending urbs, then synchronizes with
1343  * the hcd to make sure all endpoint state is gone from hardware. use for
1344  * set_configuration, set_interface, driver removal, physical disconnect.
1345  *
1346  * example:  a qh stored in hcd_dev.ep[], holding state related to endpoint
1347  * type, maxpacket size, toggle, halt status, and scheduling.
1348  */
1349 static void hcd_endpoint_disable (struct usb_device *udev, int endpoint)
1350 {
1351         struct hcd_dev  *dev;
1352         struct usb_hcd  *hcd;
1353         struct urb      *urb;
1354         unsigned        epnum = endpoint & USB_ENDPOINT_NUMBER_MASK;
1355
1356         dev = udev->hcpriv;
1357         hcd = udev->bus->hcpriv;
1358
1359         WARN_ON (!HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_HALT);
1360
1361         local_irq_disable ();
1362
1363 rescan:
1364         /* (re)block new requests, as best we can */
1365         if (endpoint & USB_DIR_IN) {
1366                 usb_endpoint_halt (udev, epnum, 0);
1367                 udev->epmaxpacketin [epnum] = 0;
1368         } else {
1369                 usb_endpoint_halt (udev, epnum, 1);
1370                 udev->epmaxpacketout [epnum] = 0;
1371         }
1372
1373         /* then kill any current requests */
1374         spin_lock (&hcd_data_lock);
1375         list_for_each_entry (urb, &dev->urb_list, urb_list) {
1376                 int     tmp = urb->pipe;
1377
1378                 /* ignore urbs for other endpoints */
1379                 if (usb_pipeendpoint (tmp) != epnum)
1380                         continue;
1381                 /* NOTE assumption that only ep0 is a control endpoint */
1382                 if (epnum != 0 && ((tmp ^ endpoint) & USB_DIR_IN))
1383                         continue;
1384
1385                 /* another cpu may be in hcd, spinning on hcd_data_lock
1386                  * to giveback() this urb.  the races here should be
1387                  * small, but a full fix needs a new "can't submit"
1388                  * urb state.
1389                  */
1390                 if (urb->status != -EINPROGRESS)
1391                         continue;
1392                 usb_get_urb (urb);
1393                 spin_unlock (&hcd_data_lock);
1394
1395                 spin_lock (&urb->lock);
1396                 tmp = urb->status;
1397                 if (tmp == -EINPROGRESS)
1398                         urb->status = -ESHUTDOWN;
1399                 spin_unlock (&urb->lock);
1400
1401                 /* kick hcd unless it's already returning this */
1402                 if (tmp == -EINPROGRESS) {
1403                         tmp = urb->pipe;
1404                         unlink1 (hcd, urb);
1405                         dev_dbg (hcd->self.controller,
1406                                 "shutdown urb %p pipe %08x ep%d%s%s\n",
1407                                 urb, tmp, usb_pipeendpoint (tmp),
1408                                 (tmp & USB_DIR_IN) ? "in" : "out",
1409                                 ({ char *s; \
1410                                  switch (usb_pipetype (tmp)) { \
1411                                  case PIPE_CONTROL:     s = ""; break; \
1412                                  case PIPE_BULK:        s = "-bulk"; break; \
1413                                  case PIPE_INTERRUPT:   s = "-intr"; break; \
1414                                  default:               s = "-iso"; break; \
1415                                 }; s;}));
1416                 }
1417                 usb_put_urb (urb);
1418
1419                 /* list contents may have changed */
1420                 goto rescan;
1421         }
1422         spin_unlock (&hcd_data_lock);
1423         local_irq_enable ();
1424
1425         /* synchronize with the hardware, so old configuration state
1426          * clears out immediately (and will be freed).
1427          */
1428         might_sleep ();
1429         if (hcd->driver->endpoint_disable)
1430                 hcd->driver->endpoint_disable (hcd, dev, endpoint);
1431 }
1432
1433 /*-------------------------------------------------------------------------*/
1434
1435 /* called by khubd, rmmod, apmd, or other thread for hcd-private cleanup.
1436  * we're guaranteed that the device is fully quiesced.  also, that each
1437  * endpoint has been hcd_endpoint_disabled.
1438  */
1439
1440 static int hcd_free_dev (struct usb_device *udev)
1441 {
1442         struct hcd_dev          *dev;
1443         struct usb_hcd          *hcd;
1444         unsigned long           flags;
1445
1446         if (!udev || !udev->hcpriv)
1447                 return -EINVAL;
1448
1449         if (!udev->bus || !udev->bus->hcpriv)
1450                 return -ENODEV;
1451
1452         // should udev->devnum == -1 ??
1453
1454         dev = udev->hcpriv;
1455         hcd = udev->bus->hcpriv;
1456
1457         /* device driver problem with refcounts? */
1458         if (!list_empty (&dev->urb_list)) {
1459                 dev_dbg (hcd->self.controller, "free busy dev, %s devnum %d (bug!)\n",
1460                         hcd->self.bus_name, udev->devnum);
1461                 return -EINVAL;
1462         }
1463
1464         spin_lock_irqsave (&hcd_data_lock, flags);
1465         list_del (&dev->dev_list);
1466         udev->hcpriv = NULL;
1467         spin_unlock_irqrestore (&hcd_data_lock, flags);
1468
1469         kfree (dev);
1470         return 0;
1471 }
1472
1473 /*
1474  * usb_hcd_operations - adapts usb_bus framework to HCD framework (bus glue)
1475  *
1476  * When registering a USB bus through the HCD framework code, use this
1477  * usb_operations vector.  The PCI glue layer does so automatically; only
1478  * bus glue for non-PCI system busses will need to use this.
1479  */
1480 struct usb_operations usb_hcd_operations = {
1481         .allocate =             hcd_alloc_dev,
1482         .get_frame_number =     hcd_get_frame_number,
1483         .submit_urb =           hcd_submit_urb,
1484         .unlink_urb =           hcd_unlink_urb,
1485         .deallocate =           hcd_free_dev,
1486         .buffer_alloc =         hcd_buffer_alloc,
1487         .buffer_free =          hcd_buffer_free,
1488         .disable =              hcd_endpoint_disable,
1489 };
1490 EXPORT_SYMBOL (usb_hcd_operations);
1491
1492 /*-------------------------------------------------------------------------*/
1493
1494 /**
1495  * usb_hcd_giveback_urb - return URB from HCD to device driver
1496  * @hcd: host controller returning the URB
1497  * @urb: urb being returned to the USB device driver.
1498  * @regs: pt_regs, passed down to the URB completion handler
1499  * Context: in_interrupt()
1500  *
1501  * This hands the URB from HCD to its USB device driver, using its
1502  * completion function.  The HCD has freed all per-urb resources
1503  * (and is done using urb->hcpriv).  It also released all HCD locks;
1504  * the device driver won't cause problems if it frees, modifies,
1505  * or resubmits this URB.
1506  */
1507 void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb, struct pt_regs *regs)
1508 {
1509         urb_unlink (urb);
1510
1511         // NOTE:  a generic device/urb monitoring hook would go here.
1512         // hcd_monitor_hook(MONITOR_URB_FINISH, urb, dev)
1513         // It would catch exit/unlink paths for all urbs.
1514
1515         /* lower level hcd code should use *_dma exclusively */
1516         if (hcd->self.controller->dma_mask) {
1517                 if (usb_pipecontrol (urb->pipe)
1518                         && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1519                         dma_unmap_single (hcd->self.controller, urb->setup_dma,
1520                                         sizeof (struct usb_ctrlrequest),
1521                                         DMA_TO_DEVICE);
1522                 if (urb->transfer_buffer_length != 0
1523                         && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1524                         dma_unmap_single (hcd->self.controller, 
1525                                         urb->transfer_dma,
1526                                         urb->transfer_buffer_length,
1527                                         usb_pipein (urb->pipe)
1528                                             ? DMA_FROM_DEVICE
1529                                             : DMA_TO_DEVICE);
1530         }
1531
1532         /* pass ownership to the completion handler */
1533         urb->complete (urb, regs);
1534         usb_put_urb (urb);
1535 }
1536 EXPORT_SYMBOL (usb_hcd_giveback_urb);
1537
1538 /*-------------------------------------------------------------------------*/
1539
1540 /**
1541  * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
1542  * @irq: the IRQ being raised
1543  * @__hcd: pointer to the HCD whose IRQ is beinng signaled
1544  * @r: saved hardware registers
1545  *
1546  * When registering a USB bus through the HCD framework code, use this
1547  * to handle interrupts.  The PCI glue layer does so automatically; only
1548  * bus glue for non-PCI system busses will need to use this.
1549  */
1550 irqreturn_t usb_hcd_irq (int irq, void *__hcd, struct pt_regs * r)
1551 {
1552         struct usb_hcd          *hcd = __hcd;
1553         int                     start = hcd->state;
1554
1555         if (unlikely (hcd->state == USB_STATE_HALT))    /* irq sharing? */
1556                 return IRQ_NONE;
1557
1558         hcd->saw_irq = 1;
1559         if (hcd->driver->irq (hcd, r) == IRQ_NONE)
1560                 return IRQ_NONE;
1561
1562         if (hcd->state != start && hcd->state == USB_STATE_HALT)
1563                 usb_hc_died (hcd);
1564         return IRQ_HANDLED;
1565 }
1566 EXPORT_SYMBOL (usb_hcd_irq);
1567
1568 /*-------------------------------------------------------------------------*/
1569
1570 static void hcd_panic (void *_hcd)
1571 {
1572         struct usb_hcd          *hcd = _hcd;
1573         struct usb_device       *hub = hcd->self.root_hub;
1574         unsigned                i;
1575
1576         /* hc's root hub is removed later removed in hcd->stop() */
1577         hub->state = USB_STATE_NOTATTACHED;
1578         for (i = 0; i < hub->maxchild; i++) {
1579                 if (hub->children [i])
1580                         usb_disconnect (&hub->children [i]);
1581         }
1582 }
1583
1584 /**
1585  * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
1586  * @hcd: pointer to the HCD representing the controller
1587  *
1588  * This is called by bus glue to report a USB host controller that died
1589  * while operations may still have been pending.  It's called automatically
1590  * by the PCI glue, so only glue for non-PCI busses should need to call it. 
1591  */
1592 void usb_hc_died (struct usb_hcd *hcd)
1593 {
1594         dev_err (hcd->self.controller, "HC died; cleaning up\n");
1595
1596         /* clean up old urbs and devices; needs a task context */
1597         INIT_WORK (&hcd->work, hcd_panic, hcd);
1598         (void) schedule_work (&hcd->work);
1599 }
1600 EXPORT_SYMBOL (usb_hc_died);
1601