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