Merge with Linux 2.5.48.
[linux-2.6/linux-mips.git] / drivers / usb / core / hcd.c
blobf8153e7ee70406358f643882f6bbc05577307bbd
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.
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.
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.
25 #include <linux/config.h>
27 #ifdef CONFIG_USB_DEBUG
28 #define DEBUG
29 #endif
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/pci.h> /* for hcd->pdev and dma addressing */
38 #include <asm/byteorder.h>
40 #include <linux/usb.h>
41 #include "hcd.h"
44 // #define USB_BANDWIDTH_MESSAGES
46 /*-------------------------------------------------------------------------*/
49 * USB Host Controller Driver framework
51 * Plugs into usbcore (usb_bus) and lets HCDs share code, minimizing
52 * HCD-specific behaviors/bugs.
54 * This does error checks, tracks devices and urbs, and delegates to a
55 * "hc_driver" only for code (and data) that really needs to know about
56 * hardware differences. That includes root hub registers, i/o queues,
57 * and so on ... but as little else as possible.
59 * Shared code includes most of the "root hub" code (these are emulated,
60 * though each HC's hardware works differently) and PCI glue, plus request
61 * tracking overhead. The HCD code should only block on spinlocks or on
62 * hardware handshaking; blocking on software events (such as other kernel
63 * threads releasing resources, or completing actions) is all generic.
65 * Happens the USB 2.0 spec says this would be invisible inside the "USBD",
66 * and includes mostly a "HCDI" (HCD Interface) along with some APIs used
67 * only by the hub driver ... and that neither should be seen or used by
68 * usb client device drivers.
70 * Contributors of ideas or unattributed patches include: David Brownell,
71 * Roman Weissgaerber, Rory Bolt, Greg Kroah-Hartman, ...
73 * HISTORY:
74 * 2002-02-21 Pull in most of the usb_bus support from usb.c; some
75 * associated cleanup. "usb_hcd" still != "usb_bus".
76 * 2001-12-12 Initial patch version for Linux 2.5.1 kernel.
79 /*-------------------------------------------------------------------------*/
81 /* host controllers we manage */
82 LIST_HEAD (usb_bus_list);
84 /* used when allocating bus numbers */
85 #define USB_MAXBUS 64
86 struct usb_busmap {
87 unsigned long busmap [USB_MAXBUS / (8*sizeof (unsigned long))];
89 static struct usb_busmap busmap;
91 /* used when updating list of hcds */
92 DECLARE_MUTEX (usb_bus_list_lock); /* exported only for usbfs */
94 /* used when updating hcd data */
95 static spinlock_t hcd_data_lock = SPIN_LOCK_UNLOCKED;
97 /*-------------------------------------------------------------------------*/
100 * Sharable chunks of root hub code.
103 /*-------------------------------------------------------------------------*/
105 #define KERNEL_REL ((LINUX_VERSION_CODE >> 16) & 0x0ff)
106 #define KERNEL_VER ((LINUX_VERSION_CODE >> 8) & 0x0ff)
108 /* usb 2.0 root hub device descriptor */
109 static const u8 usb2_rh_dev_descriptor [18] = {
110 0x12, /* __u8 bLength; */
111 0x01, /* __u8 bDescriptorType; Device */
112 0x00, 0x02, /* __u16 bcdUSB; v2.0 */
114 0x09, /* __u8 bDeviceClass; HUB_CLASSCODE */
115 0x00, /* __u8 bDeviceSubClass; */
116 0x01, /* __u8 bDeviceProtocol; [ usb 2.0 single TT ]*/
117 0x08, /* __u8 bMaxPacketSize0; 8 Bytes */
119 0x00, 0x00, /* __u16 idVendor; */
120 0x00, 0x00, /* __u16 idProduct; */
121 KERNEL_VER, KERNEL_REL, /* __u16 bcdDevice */
123 0x03, /* __u8 iManufacturer; */
124 0x02, /* __u8 iProduct; */
125 0x01, /* __u8 iSerialNumber; */
126 0x01 /* __u8 bNumConfigurations; */
129 /* no usb 2.0 root hub "device qualifier" descriptor: one speed only */
131 /* usb 1.1 root hub device descriptor */
132 static const u8 usb11_rh_dev_descriptor [18] = {
133 0x12, /* __u8 bLength; */
134 0x01, /* __u8 bDescriptorType; Device */
135 0x10, 0x01, /* __u16 bcdUSB; v1.1 */
137 0x09, /* __u8 bDeviceClass; HUB_CLASSCODE */
138 0x00, /* __u8 bDeviceSubClass; */
139 0x00, /* __u8 bDeviceProtocol; [ low/full speeds only ] */
140 0x08, /* __u8 bMaxPacketSize0; 8 Bytes */
142 0x00, 0x00, /* __u16 idVendor; */
143 0x00, 0x00, /* __u16 idProduct; */
144 KERNEL_VER, KERNEL_REL, /* __u16 bcdDevice */
146 0x03, /* __u8 iManufacturer; */
147 0x02, /* __u8 iProduct; */
148 0x01, /* __u8 iSerialNumber; */
149 0x01 /* __u8 bNumConfigurations; */
153 /*-------------------------------------------------------------------------*/
155 /* Configuration descriptors for our root hubs */
157 static const u8 fs_rh_config_descriptor [] = {
159 /* one configuration */
160 0x09, /* __u8 bLength; */
161 0x02, /* __u8 bDescriptorType; Configuration */
162 0x19, 0x00, /* __u16 wTotalLength; */
163 0x01, /* __u8 bNumInterfaces; (1) */
164 0x01, /* __u8 bConfigurationValue; */
165 0x00, /* __u8 iConfiguration; */
166 0x40, /* __u8 bmAttributes;
167 Bit 7: Bus-powered,
168 6: Self-powered,
169 5 Remote-wakwup,
170 4..0: resvd */
171 0x00, /* __u8 MaxPower; */
173 /* USB 1.1:
174 * USB 2.0, single TT organization (mandatory):
175 * one interface, protocol 0
177 * USB 2.0, multiple TT organization (optional):
178 * two interfaces, protocols 1 (like single TT)
179 * and 2 (multiple TT mode) ... config is
180 * sometimes settable
181 * NOT IMPLEMENTED
184 /* one interface */
185 0x09, /* __u8 if_bLength; */
186 0x04, /* __u8 if_bDescriptorType; Interface */
187 0x00, /* __u8 if_bInterfaceNumber; */
188 0x00, /* __u8 if_bAlternateSetting; */
189 0x01, /* __u8 if_bNumEndpoints; */
190 0x09, /* __u8 if_bInterfaceClass; HUB_CLASSCODE */
191 0x00, /* __u8 if_bInterfaceSubClass; */
192 0x00, /* __u8 if_bInterfaceProtocol; [usb1.1 or single tt] */
193 0x00, /* __u8 if_iInterface; */
195 /* one endpoint (status change endpoint) */
196 0x07, /* __u8 ep_bLength; */
197 0x05, /* __u8 ep_bDescriptorType; Endpoint */
198 0x81, /* __u8 ep_bEndpointAddress; IN Endpoint 1 */
199 0x03, /* __u8 ep_bmAttributes; Interrupt */
200 0x02, 0x00, /* __u16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
201 0xff /* __u8 ep_bInterval; (255ms -- usb 2.0 spec) */
204 static const u8 hs_rh_config_descriptor [] = {
206 /* one configuration */
207 0x09, /* __u8 bLength; */
208 0x02, /* __u8 bDescriptorType; Configuration */
209 0x19, 0x00, /* __u16 wTotalLength; */
210 0x01, /* __u8 bNumInterfaces; (1) */
211 0x01, /* __u8 bConfigurationValue; */
212 0x00, /* __u8 iConfiguration; */
213 0x40, /* __u8 bmAttributes;
214 Bit 7: Bus-powered,
215 6: Self-powered,
216 5 Remote-wakwup,
217 4..0: resvd */
218 0x00, /* __u8 MaxPower; */
220 /* USB 1.1:
221 * USB 2.0, single TT organization (mandatory):
222 * one interface, protocol 0
224 * USB 2.0, multiple TT organization (optional):
225 * two interfaces, protocols 1 (like single TT)
226 * and 2 (multiple TT mode) ... config is
227 * sometimes settable
228 * NOT IMPLEMENTED
231 /* one interface */
232 0x09, /* __u8 if_bLength; */
233 0x04, /* __u8 if_bDescriptorType; Interface */
234 0x00, /* __u8 if_bInterfaceNumber; */
235 0x00, /* __u8 if_bAlternateSetting; */
236 0x01, /* __u8 if_bNumEndpoints; */
237 0x09, /* __u8 if_bInterfaceClass; HUB_CLASSCODE */
238 0x00, /* __u8 if_bInterfaceSubClass; */
239 0x00, /* __u8 if_bInterfaceProtocol; [usb1.1 or single tt] */
240 0x00, /* __u8 if_iInterface; */
242 /* one endpoint (status change endpoint) */
243 0x07, /* __u8 ep_bLength; */
244 0x05, /* __u8 ep_bDescriptorType; Endpoint */
245 0x81, /* __u8 ep_bEndpointAddress; IN Endpoint 1 */
246 0x03, /* __u8 ep_bmAttributes; Interrupt */
247 0x02, 0x00, /* __u16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
248 0x0c /* __u8 ep_bInterval; (256ms -- usb 2.0 spec) */
251 /*-------------------------------------------------------------------------*/
254 * helper routine for returning string descriptors in UTF-16LE
255 * input can actually be ISO-8859-1; ASCII is its 7-bit subset
257 static int ascii2utf (char *s, u8 *utf, int utfmax)
259 int retval;
261 for (retval = 0; *s && utfmax > 1; utfmax -= 2, retval += 2) {
262 *utf++ = *s++;
263 *utf++ = 0;
265 return retval;
269 * rh_string - provides manufacturer, product and serial strings for root hub
270 * @id: the string ID number (1: serial number, 2: product, 3: vendor)
271 * @hcd: the host controller for this root hub
272 * @type: string describing our driver
273 * @data: return packet in UTF-16 LE
274 * @len: length of the return packet
276 * Produces either a manufacturer, product or serial number string for the
277 * virtual root hub device.
279 static int rh_string (
280 int id,
281 struct usb_hcd *hcd,
282 u8 *data,
283 int len
285 char buf [100];
287 // language ids
288 if (id == 0) {
289 *data++ = 4; *data++ = 3; /* 4 bytes string data */
290 *data++ = 0x09; *data++ = 0x04; /* MSFT-speak for "en-us" */
291 return 4;
293 // serial number
294 } else if (id == 1) {
295 strcpy (buf, hcd->self.bus_name);
297 // product description
298 } else if (id == 2) {
299 strcpy (buf, hcd->product_desc);
301 // id 3 == vendor description
302 } else if (id == 3) {
303 sprintf (buf, "%s %s %s", UTS_SYSNAME, UTS_RELEASE,
304 hcd->description);
306 // unsupported IDs --> "protocol stall"
307 } else
308 return 0;
310 data [0] = 2 + ascii2utf (buf, data + 2, len - 2);
311 data [1] = 3; /* type == string */
312 return data [0];
316 /* Root hub control transfers execute synchronously */
317 static int rh_call_control (struct usb_hcd *hcd, struct urb *urb)
319 struct usb_ctrlrequest *cmd = (struct usb_ctrlrequest *) urb->setup_packet;
320 u16 typeReq, wValue, wIndex, wLength;
321 const u8 *bufp = 0;
322 u8 *ubuf = urb->transfer_buffer;
323 int len = 0;
325 typeReq = (cmd->bRequestType << 8) | cmd->bRequest;
326 wValue = le16_to_cpu (cmd->wValue);
327 wIndex = le16_to_cpu (cmd->wIndex);
328 wLength = le16_to_cpu (cmd->wLength);
330 if (wLength > urb->transfer_buffer_length)
331 goto error;
333 /* set up for success */
334 urb->status = 0;
335 urb->actual_length = wLength;
336 switch (typeReq) {
338 /* DEVICE REQUESTS */
340 case DeviceRequest | USB_REQ_GET_STATUS:
341 // DEVICE_REMOTE_WAKEUP
342 ubuf [0] = 1; // selfpowered
343 ubuf [1] = 0;
344 /* FALLTHROUGH */
345 case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
346 case DeviceOutRequest | USB_REQ_SET_FEATURE:
347 dbg ("no device features yet yet");
348 break;
349 case DeviceRequest | USB_REQ_GET_CONFIGURATION:
350 ubuf [0] = 1;
351 /* FALLTHROUGH */
352 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
353 break;
354 case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
355 switch (wValue & 0xff00) {
356 case USB_DT_DEVICE << 8:
357 if (hcd->driver->flags & HCD_USB2)
358 bufp = usb2_rh_dev_descriptor;
359 else if (hcd->driver->flags & HCD_USB11)
360 bufp = usb11_rh_dev_descriptor;
361 else
362 goto error;
363 len = 18;
364 break;
365 case USB_DT_CONFIG << 8:
366 if (hcd->driver->flags & HCD_USB2) {
367 bufp = hs_rh_config_descriptor;
368 len = sizeof hs_rh_config_descriptor;
369 } else {
370 bufp = fs_rh_config_descriptor;
371 len = sizeof fs_rh_config_descriptor;
373 break;
374 case USB_DT_STRING << 8:
375 urb->actual_length = rh_string (
376 wValue & 0xff, hcd,
377 ubuf, wLength);
378 break;
379 default:
380 goto error;
382 break;
383 case DeviceRequest | USB_REQ_GET_INTERFACE:
384 ubuf [0] = 0;
385 /* FALLTHROUGH */
386 case DeviceOutRequest | USB_REQ_SET_INTERFACE:
387 break;
388 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
389 // wValue == urb->dev->devaddr
390 dbg ("%s root hub device address %d",
391 hcd->self.bus_name, wValue);
392 break;
394 /* INTERFACE REQUESTS (no defined feature/status flags) */
396 /* ENDPOINT REQUESTS */
398 case EndpointRequest | USB_REQ_GET_STATUS:
399 // ENDPOINT_HALT flag
400 ubuf [0] = 0;
401 ubuf [1] = 0;
402 /* FALLTHROUGH */
403 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
404 case EndpointOutRequest | USB_REQ_SET_FEATURE:
405 dbg ("no endpoint features yet");
406 break;
408 /* CLASS REQUESTS (and errors) */
410 default:
411 /* non-generic request */
412 urb->status = hcd->driver->hub_control (hcd,
413 typeReq, wValue, wIndex,
414 ubuf, wLength);
415 break;
416 error:
417 /* "protocol stall" on error */
418 urb->status = -EPIPE;
419 dbg ("unsupported hub control message (maxchild %d)",
420 urb->dev->maxchild);
422 if (urb->status) {
423 urb->actual_length = 0;
424 dbg ("CTRL: TypeReq=0x%x val=0x%x idx=0x%x len=%d ==> %d",
425 typeReq, wValue, wIndex, wLength, urb->status);
427 if (bufp) {
428 if (urb->transfer_buffer_length < len)
429 len = urb->transfer_buffer_length;
430 urb->actual_length = len;
431 // always USB_DIR_IN, toward host
432 memcpy (ubuf, bufp, len);
435 /* any errors get returned through the urb completion */
436 usb_hcd_giveback_urb (hcd, urb);
437 return 0;
440 /*-------------------------------------------------------------------------*/
443 * Root Hub interrupt transfers are synthesized with a timer.
444 * Completions are called in_interrupt() but not in_irq().
447 static void rh_report_status (unsigned long ptr);
449 static int rh_status_urb (struct usb_hcd *hcd, struct urb *urb)
451 int len = 1 + (urb->dev->maxchild / 8);
453 /* rh_timer protected by hcd_data_lock */
454 if (timer_pending (&hcd->rh_timer)
455 || urb->status != -EINPROGRESS
456 || urb->transfer_buffer_length < len) {
457 dbg ("not queuing status urb, stat %d", urb->status);
458 return -EINVAL;
461 urb->hcpriv = hcd; /* nonzero to indicate it's queued */
462 init_timer (&hcd->rh_timer);
463 hcd->rh_timer.function = rh_report_status;
464 hcd->rh_timer.data = (unsigned long) urb;
465 /* USB 2.0 spec says 256msec; this is close enough */
466 hcd->rh_timer.expires = jiffies + HZ/4;
467 add_timer (&hcd->rh_timer);
468 return 0;
471 /* timer callback */
473 static void rh_report_status (unsigned long ptr)
475 struct urb *urb;
476 struct usb_hcd *hcd;
477 int length;
478 unsigned long flags;
480 urb = (struct urb *) ptr;
481 spin_lock_irqsave (&urb->lock, flags);
482 if (!urb->dev) {
483 spin_unlock_irqrestore (&urb->lock, flags);
484 return;
487 hcd = urb->dev->bus->hcpriv;
488 if (urb->status == -EINPROGRESS) {
489 if (HCD_IS_RUNNING (hcd->state)) {
490 length = hcd->driver->hub_status_data (hcd,
491 urb->transfer_buffer);
492 spin_unlock_irqrestore (&urb->lock, flags);
493 if (length > 0) {
494 urb->actual_length = length;
495 urb->status = 0;
496 urb->hcpriv = 0;
497 urb->complete (urb);
498 return;
500 } else
501 spin_unlock_irqrestore (&urb->lock, flags);
503 /* retrigger timer until completion: success or unlink */
504 spin_lock_irqsave (&hcd_data_lock, flags);
505 rh_status_urb (hcd, urb);
506 spin_unlock_irqrestore (&hcd_data_lock, flags);
507 } else {
508 /* this urb's been unlinked */
509 urb->hcpriv = 0;
510 spin_unlock_irqrestore (&urb->lock, flags);
512 usb_hcd_giveback_urb (hcd, urb);
516 /*-------------------------------------------------------------------------*/
518 static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
520 if (usb_pipeint (urb->pipe)) {
521 int retval;
522 unsigned long flags;
524 spin_lock_irqsave (&hcd_data_lock, flags);
525 retval = rh_status_urb (hcd, urb);
526 spin_unlock_irqrestore (&hcd_data_lock, flags);
527 return retval;
529 if (usb_pipecontrol (urb->pipe))
530 return rh_call_control (hcd, urb);
531 else
532 return -EINVAL;
535 /*-------------------------------------------------------------------------*/
537 void usb_rh_status_dequeue (struct usb_hcd *hcd, struct urb *urb)
539 unsigned long flags;
541 spin_lock_irqsave (&hcd_data_lock, flags);
542 del_timer_sync (&hcd->rh_timer);
543 hcd->rh_timer.data = 0;
544 spin_unlock_irqrestore (&hcd_data_lock, flags);
546 /* we rely on RH callback code not unlinking its URB! */
547 usb_hcd_giveback_urb (hcd, urb);
550 /*-------------------------------------------------------------------------*/
552 /* exported only within usbcore */
553 void usb_bus_get (struct usb_bus *bus)
555 atomic_inc (&bus->refcnt);
558 /* exported only within usbcore */
559 void usb_bus_put (struct usb_bus *bus)
561 if (atomic_dec_and_test (&bus->refcnt))
562 kfree (bus);
565 /*-------------------------------------------------------------------------*/
568 * usb_bus_init - shared initialization code
569 * @bus: the bus structure being initialized
571 * This code is used to initialize a usb_bus structure, memory for which is
572 * separately managed.
574 void usb_bus_init (struct usb_bus *bus)
576 memset (&bus->devmap, 0, sizeof(struct usb_devmap));
578 bus->devnum_next = 1;
580 bus->root_hub = NULL;
581 bus->hcpriv = NULL;
582 bus->busnum = -1;
583 bus->bandwidth_allocated = 0;
584 bus->bandwidth_int_reqs = 0;
585 bus->bandwidth_isoc_reqs = 0;
587 INIT_LIST_HEAD (&bus->bus_list);
589 atomic_set (&bus->refcnt, 1);
591 EXPORT_SYMBOL (usb_bus_init);
594 * usb_alloc_bus - creates a new USB host controller structure
595 * @op: pointer to a struct usb_operations that this bus structure should use
596 * Context: !in_interrupt()
598 * Creates a USB host controller bus structure with the specified
599 * usb_operations and initializes all the necessary internal objects.
601 * If no memory is available, NULL is returned.
603 * The caller should call usb_free_bus() when it is finished with the structure.
605 struct usb_bus *usb_alloc_bus (struct usb_operations *op)
607 struct usb_bus *bus;
609 bus = kmalloc (sizeof *bus, GFP_KERNEL);
610 if (!bus)
611 return NULL;
612 usb_bus_init (bus);
613 bus->op = op;
614 return bus;
616 EXPORT_SYMBOL (usb_alloc_bus);
619 * usb_free_bus - frees the memory used by a bus structure
620 * @bus: pointer to the bus to free
622 * To be invoked by a HCD, only as the last step of decoupling from
623 * hardware. It is an error to call this if the reference count is
624 * anything but one. That would indicate that some system component
625 * did not correctly shut down, and thought the hardware was still
626 * accessible.
628 void usb_free_bus (struct usb_bus *bus)
630 if (!bus)
631 return;
632 if (atomic_read (&bus->refcnt) != 1)
633 err ("usb_free_bus #%d, count != 1", bus->busnum);
634 usb_bus_put (bus);
636 EXPORT_SYMBOL (usb_free_bus);
638 /*-------------------------------------------------------------------------*/
641 * usb_register_bus - registers the USB host controller with the usb core
642 * @bus: pointer to the bus to register
643 * Context: !in_interrupt()
645 * Assigns a bus number, and links the controller into usbcore data
646 * structures so that it can be seen by scanning the bus list.
648 void usb_register_bus(struct usb_bus *bus)
650 int busnum;
652 down (&usb_bus_list_lock);
653 busnum = find_next_zero_bit (busmap.busmap, USB_MAXBUS, 1);
654 if (busnum < USB_MAXBUS) {
655 set_bit (busnum, busmap.busmap);
656 bus->busnum = busnum;
657 } else
658 warn ("too many buses");
660 usb_bus_get (bus);
662 /* Add it to the list of buses */
663 list_add (&bus->bus_list, &usb_bus_list);
664 up (&usb_bus_list_lock);
666 usbfs_add_bus (bus);
668 info ("new USB bus registered, assigned bus number %d", bus->busnum);
670 EXPORT_SYMBOL (usb_register_bus);
673 * usb_deregister_bus - deregisters the USB host controller
674 * @bus: pointer to the bus to deregister
675 * Context: !in_interrupt()
677 * Recycles the bus number, and unlinks the controller from usbcore data
678 * structures so that it won't be seen by scanning the bus list.
680 void usb_deregister_bus (struct usb_bus *bus)
682 info ("USB bus %d deregistered", bus->busnum);
685 * NOTE: make sure that all the devices are removed by the
686 * controller code, as well as having it call this when cleaning
687 * itself up
689 down (&usb_bus_list_lock);
690 list_del (&bus->bus_list);
691 up (&usb_bus_list_lock);
693 usbfs_remove_bus (bus);
695 clear_bit (bus->busnum, busmap.busmap);
697 usb_bus_put (bus);
699 EXPORT_SYMBOL (usb_deregister_bus);
702 * usb_register_root_hub - called by HCD to register its root hub
703 * @usb_dev: the usb root hub device to be registered.
704 * @parent_dev: the parent device of this root hub.
706 * The USB host controller calls this function to register the root hub
707 * properly with the USB subsystem. It sets up the device properly in
708 * the driverfs tree, and then calls usb_new_device() to register the
709 * usb device.
711 int usb_register_root_hub (struct usb_device *usb_dev, struct device *parent_dev)
713 int retval;
715 sprintf (&usb_dev->dev.bus_id[0], "usb%d", usb_dev->bus->busnum);
716 retval = usb_new_device (usb_dev, parent_dev);
717 if (retval)
718 err("%s - usb_new_device failed with value %d", __FUNCTION__, retval);
719 return retval;
721 EXPORT_SYMBOL (usb_register_root_hub);
724 /*-------------------------------------------------------------------------*/
727 * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
728 * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
729 * @is_input: true iff the transaction sends data to the host
730 * @isoc: true for isochronous transactions, false for interrupt ones
731 * @bytecount: how many bytes in the transaction.
733 * Returns approximate bus time in nanoseconds for a periodic transaction.
734 * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
735 * scheduled in software, this function is only used for such scheduling.
737 long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
739 unsigned long tmp;
741 switch (speed) {
742 case USB_SPEED_LOW: /* INTR only */
743 if (is_input) {
744 tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
745 return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
746 } else {
747 tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
748 return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
750 case USB_SPEED_FULL: /* ISOC or INTR */
751 if (isoc) {
752 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
753 return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
754 } else {
755 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
756 return (9107L + BW_HOST_DELAY + tmp);
758 case USB_SPEED_HIGH: /* ISOC or INTR */
759 // FIXME adjust for input vs output
760 if (isoc)
761 tmp = HS_USECS (bytecount);
762 else
763 tmp = HS_USECS_ISO (bytecount);
764 return tmp;
765 default:
766 dbg ("bogus device speed!");
767 return -1;
770 EXPORT_SYMBOL (usb_calc_bus_time);
773 * usb_check_bandwidth():
775 * old_alloc is from host_controller->bandwidth_allocated in microseconds;
776 * bustime is from calc_bus_time(), but converted to microseconds.
778 * returns <bustime in us> if successful,
779 * or -ENOSPC if bandwidth request fails.
781 * FIXME:
782 * This initial implementation does not use Endpoint.bInterval
783 * in managing bandwidth allocation.
784 * It probably needs to be expanded to use Endpoint.bInterval.
785 * This can be done as a later enhancement (correction).
787 * This will also probably require some kind of
788 * frame allocation tracking...meaning, for example,
789 * that if multiple drivers request interrupts every 10 USB frames,
790 * they don't all have to be allocated at
791 * frame numbers N, N+10, N+20, etc. Some of them could be at
792 * N+11, N+21, N+31, etc., and others at
793 * N+12, N+22, N+32, etc.
795 * Similarly for isochronous transfers...
797 * Individual HCDs can schedule more directly ... this logic
798 * is not correct for high speed transfers.
800 int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
802 unsigned int pipe = urb->pipe;
803 long bustime;
804 int is_in = usb_pipein (pipe);
805 int is_iso = usb_pipeisoc (pipe);
806 int old_alloc = dev->bus->bandwidth_allocated;
807 int new_alloc;
810 bustime = NS_TO_US (usb_calc_bus_time (dev->speed, is_in, is_iso,
811 usb_maxpacket (dev, pipe, !is_in)));
812 if (is_iso)
813 bustime /= urb->number_of_packets;
815 new_alloc = old_alloc + (int) bustime;
816 if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC) {
817 #ifdef DEBUG
818 char *mode =
819 #ifdef CONFIG_USB_BANDWIDTH
821 #else
822 "would have ";
823 #endif
824 dbg ("usb_check_bandwidth %sFAILED: %d + %ld = %d usec",
825 mode, old_alloc, bustime, new_alloc);
826 #endif
827 #ifdef CONFIG_USB_BANDWIDTH
828 bustime = -ENOSPC; /* report error */
829 #endif
832 return bustime;
834 EXPORT_SYMBOL (usb_check_bandwidth);
838 * usb_claim_bandwidth - records bandwidth for a periodic transfer
839 * @dev: source/target of request
840 * @urb: request (urb->dev == dev)
841 * @bustime: bandwidth consumed, in (average) microseconds per frame
842 * @isoc: true iff the request is isochronous
844 * Bus bandwidth reservations are recorded purely for diagnostic purposes.
845 * HCDs are expected not to overcommit periodic bandwidth, and to record such
846 * reservations whenever endpoints are added to the periodic schedule.
848 * FIXME averaging per-frame is suboptimal. Better to sum over the HCD's
849 * entire periodic schedule ... 32 frames for OHCI, 1024 for UHCI, settable
850 * for EHCI (256/512/1024 frames, default 1024) and have the bus expose how
851 * large its periodic schedule is.
853 void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
855 dev->bus->bandwidth_allocated += bustime;
856 if (isoc)
857 dev->bus->bandwidth_isoc_reqs++;
858 else
859 dev->bus->bandwidth_int_reqs++;
860 urb->bandwidth = bustime;
862 #ifdef USB_BANDWIDTH_MESSAGES
863 dbg ("bandwidth alloc increased by %d (%s) to %d for %d requesters",
864 bustime,
865 isoc ? "ISOC" : "INTR",
866 dev->bus->bandwidth_allocated,
867 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
868 #endif
870 EXPORT_SYMBOL (usb_claim_bandwidth);
874 * usb_release_bandwidth - reverses effect of usb_claim_bandwidth()
875 * @dev: source/target of request
876 * @urb: request (urb->dev == dev)
877 * @isoc: true iff the request is isochronous
879 * This records that previously allocated bandwidth has been released.
880 * Bandwidth is released when endpoints are removed from the host controller's
881 * periodic schedule.
883 void usb_release_bandwidth (struct usb_device *dev, struct urb *urb, int isoc)
885 dev->bus->bandwidth_allocated -= urb->bandwidth;
886 if (isoc)
887 dev->bus->bandwidth_isoc_reqs--;
888 else
889 dev->bus->bandwidth_int_reqs--;
891 #ifdef USB_BANDWIDTH_MESSAGES
892 dbg ("bandwidth alloc reduced by %d (%s) to %d for %d requesters",
893 urb->bandwidth,
894 isoc ? "ISOC" : "INTR",
895 dev->bus->bandwidth_allocated,
896 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
897 #endif
898 urb->bandwidth = 0;
900 EXPORT_SYMBOL (usb_release_bandwidth);
903 /*-------------------------------------------------------------------------*/
906 * Generic HC operations.
909 /*-------------------------------------------------------------------------*/
911 /* called from khubd, or root hub init threads for hcd-private init */
912 static int hcd_alloc_dev (struct usb_device *udev)
914 struct hcd_dev *dev;
915 struct usb_hcd *hcd;
916 unsigned long flags;
918 if (!udev || udev->hcpriv)
919 return -EINVAL;
920 if (!udev->bus || !udev->bus->hcpriv)
921 return -ENODEV;
922 hcd = udev->bus->hcpriv;
923 if (hcd->state == USB_STATE_QUIESCING)
924 return -ENOLINK;
926 dev = (struct hcd_dev *) kmalloc (sizeof *dev, GFP_KERNEL);
927 if (dev == NULL)
928 return -ENOMEM;
929 memset (dev, 0, sizeof *dev);
931 INIT_LIST_HEAD (&dev->dev_list);
932 INIT_LIST_HEAD (&dev->urb_list);
934 spin_lock_irqsave (&hcd_data_lock, flags);
935 list_add (&dev->dev_list, &hcd->dev_list);
936 // refcount is implicit
937 udev->hcpriv = dev;
938 spin_unlock_irqrestore (&hcd_data_lock, flags);
940 return 0;
943 /*-------------------------------------------------------------------------*/
945 static void urb_unlink (struct urb *urb)
947 unsigned long flags;
948 struct usb_device *dev;
950 /* Release any periodic transfer bandwidth */
951 if (urb->bandwidth)
952 usb_release_bandwidth (urb->dev, urb,
953 usb_pipeisoc (urb->pipe));
955 /* clear all state linking urb to this dev (and hcd) */
957 spin_lock_irqsave (&hcd_data_lock, flags);
958 list_del_init (&urb->urb_list);
959 dev = urb->dev;
960 usb_put_dev (dev);
961 spin_unlock_irqrestore (&hcd_data_lock, flags);
965 /* may be called in any context with a valid urb->dev usecount
966 * caller surrenders "ownership" of urb
967 * expects usb_submit_urb() to have sanity checked and conditioned all
968 * inputs in the urb
970 static int hcd_submit_urb (struct urb *urb, int mem_flags)
972 int status;
973 struct usb_hcd *hcd = urb->dev->bus->hcpriv;
974 struct hcd_dev *dev = urb->dev->hcpriv;
975 unsigned long flags;
977 if (!hcd || !dev)
978 return -ENODEV;
981 * FIXME: make urb timeouts be generic, keeping the HCD cores
982 * as simple as possible.
985 // NOTE: a generic device/urb monitoring hook would go here.
986 // hcd_monitor_hook(MONITOR_URB_SUBMIT, urb)
987 // It would catch submission paths for all urbs.
990 * Atomically queue the urb, first to our records, then to the HCD.
991 * Access to urb->status is controlled by urb->lock ... changes on
992 * i/o completion (normal or fault) or unlinking.
995 // FIXME: verify that quiescing hc works right (RH cleans up)
997 spin_lock_irqsave (&hcd_data_lock, flags);
998 if (HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_QUIESCING) {
999 usb_get_dev (urb->dev);
1000 list_add (&urb->urb_list, &dev->urb_list);
1001 status = 0;
1002 } else {
1003 INIT_LIST_HEAD (&urb->urb_list);
1004 status = -ESHUTDOWN;
1006 spin_unlock_irqrestore (&hcd_data_lock, flags);
1007 if (status)
1008 return status;
1010 /* increment urb's reference count as part of giving it to the HCD
1011 * (which now controls it). HCD guarantees that it either returns
1012 * an error or calls giveback(), but not both.
1014 urb = usb_get_urb (urb);
1015 if (urb->dev == hcd->self.root_hub) {
1016 /* NOTE: requirement on hub callers (usbfs and the hub
1017 * driver, for now) that URBs' urb->transfer_buffer be
1018 * valid and usb_buffer_{sync,unmap}() not be needed, since
1019 * they could clobber root hub response data.
1021 urb->transfer_flags |= URB_NO_DMA_MAP;
1022 return rh_urb_enqueue (hcd, urb);
1025 /* lower level hcd code should use *_dma exclusively */
1026 if (!(urb->transfer_flags & URB_NO_DMA_MAP)) {
1027 if (usb_pipecontrol (urb->pipe))
1028 urb->setup_dma = pci_map_single (
1029 hcd->pdev,
1030 urb->setup_packet,
1031 sizeof (struct usb_ctrlrequest),
1032 PCI_DMA_TODEVICE);
1033 if (urb->transfer_buffer_length != 0)
1034 urb->transfer_dma = pci_map_single (
1035 hcd->pdev,
1036 urb->transfer_buffer,
1037 urb->transfer_buffer_length,
1038 usb_pipein (urb->pipe)
1039 ? PCI_DMA_FROMDEVICE
1040 : PCI_DMA_TODEVICE);
1043 return hcd->driver->urb_enqueue (hcd, urb, mem_flags);
1046 /*-------------------------------------------------------------------------*/
1048 /* called in any context */
1049 static int hcd_get_frame_number (struct usb_device *udev)
1051 struct usb_hcd *hcd = (struct usb_hcd *)udev->bus->hcpriv;
1052 return hcd->driver->get_frame_number (hcd);
1055 /*-------------------------------------------------------------------------*/
1057 struct completion_splice { // modified urb context:
1058 /* did we complete? */
1059 struct completion done;
1061 /* original urb data */
1062 void (*complete)(struct urb *);
1063 void *context;
1066 static void unlink_complete (struct urb *urb)
1068 struct completion_splice *splice;
1070 splice = (struct completion_splice *) urb->context;
1072 /* issue original completion call */
1073 urb->complete = splice->complete;
1074 urb->context = splice->context;
1075 urb->complete (urb);
1077 /* then let the synchronous unlink call complete */
1078 complete (&splice->done);
1082 * called in any context; note ASYNC_UNLINK restrictions
1084 * caller guarantees urb won't be recycled till both unlink()
1085 * and the urb's completion function return
1087 static int hcd_unlink_urb (struct urb *urb)
1089 struct hcd_dev *dev;
1090 struct usb_hcd *hcd = 0;
1091 struct device *sys = 0;
1092 unsigned long flags;
1093 struct completion_splice splice;
1094 int retval;
1096 if (!urb)
1097 return -EINVAL;
1100 * we contend for urb->status with the hcd core,
1101 * which changes it while returning the urb.
1103 * Caller guaranteed that the urb pointer hasn't been freed, and
1104 * that it was submitted. But as a rule it can't know whether or
1105 * not it's already been unlinked ... so we respect the reversed
1106 * lock sequence needed for the usb_hcd_giveback_urb() code paths
1107 * (urb lock, then hcd_data_lock) in case some other CPU is now
1108 * unlinking it.
1110 spin_lock_irqsave (&urb->lock, flags);
1111 spin_lock (&hcd_data_lock);
1113 if (!urb->dev || !urb->dev->bus) {
1114 retval = -ENODEV;
1115 goto done;
1118 dev = urb->dev->hcpriv;
1119 sys = &urb->dev->dev;
1120 hcd = urb->dev->bus->hcpriv;
1121 if (!dev || !hcd) {
1122 retval = -ENODEV;
1123 goto done;
1126 if (!urb->hcpriv) {
1127 retval = -EINVAL;
1128 goto done;
1131 /* Any status except -EINPROGRESS means something already started to
1132 * unlink this URB from the hardware. So there's no more work to do.
1134 * FIXME use better explicit urb state
1136 if (urb->status != -EINPROGRESS) {
1137 retval = -EINVAL;
1138 goto done;
1141 /* maybe set up to block until the urb's completion fires. the
1142 * lower level hcd code is always async, locking on urb->status
1143 * updates; an intercepted completion unblocks us.
1145 if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1146 if (in_interrupt ()) {
1147 dbg ("non-async unlink in_interrupt");
1148 retval = -EWOULDBLOCK;
1149 goto done;
1151 /* synchronous unlink: block till we see the completion */
1152 init_completion (&splice.done);
1153 splice.complete = urb->complete;
1154 splice.context = urb->context;
1155 urb->complete = unlink_complete;
1156 urb->context = &splice;
1157 urb->status = -ENOENT;
1158 } else {
1159 /* asynchronous unlink */
1160 urb->status = -ECONNRESET;
1162 spin_unlock (&hcd_data_lock);
1163 spin_unlock_irqrestore (&urb->lock, flags);
1165 if (urb == (struct urb *) hcd->rh_timer.data) {
1166 usb_rh_status_dequeue (hcd, urb);
1167 retval = 0;
1168 } else {
1169 retval = hcd->driver->urb_dequeue (hcd, urb);
1171 /* hcds shouldn't really fail these calls, but... */
1172 if (retval) {
1173 dev_dbg (*sys, "dequeue %p --> %d\n", urb, retval);
1174 if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1175 spin_lock_irqsave (&urb->lock, flags);
1176 urb->complete = splice.complete;
1177 urb->context = splice.context;
1178 spin_unlock_irqrestore (&urb->lock, flags);
1180 goto bye;
1184 /* block till giveback, if needed */
1185 if (urb->transfer_flags & URB_ASYNC_UNLINK)
1186 return -EINPROGRESS;
1188 dev_dbg (*sys, "wait for giveback urb %p\n", urb);
1189 wait_for_completion (&splice.done);
1190 return 0;
1192 done:
1193 spin_unlock (&hcd_data_lock);
1194 spin_unlock_irqrestore (&urb->lock, flags);
1195 bye:
1196 if (retval && sys)
1197 dev_dbg (*sys, "hcd_unlink_urb %p fail %d\n", urb, retval);
1198 return retval;
1201 /*-------------------------------------------------------------------------*/
1203 /* called by khubd, rmmod, apmd, or other thread for hcd-private cleanup */
1205 // FIXME: likely best to have explicit per-setting (config+alt)
1206 // setup primitives in the usbcore-to-hcd driver API, so nothing
1207 // is implicit. kernel 2.5 needs a bunch of config cleanup...
1209 static int hcd_free_dev (struct usb_device *udev)
1211 struct hcd_dev *dev;
1212 struct usb_hcd *hcd;
1213 unsigned long flags;
1215 if (!udev || !udev->hcpriv)
1216 return -EINVAL;
1218 if (!udev->bus || !udev->bus->hcpriv)
1219 return -ENODEV;
1221 // should udev->devnum == -1 ??
1223 dev = udev->hcpriv;
1224 hcd = udev->bus->hcpriv;
1226 /* device driver problem with refcounts? */
1227 if (!list_empty (&dev->urb_list)) {
1228 dbg ("free busy dev, %s devnum %d (bug!)",
1229 hcd->self.bus_name, udev->devnum);
1230 return -EINVAL;
1233 if (hcd->driver->free_config)
1234 hcd->driver->free_config (hcd, udev);
1236 spin_lock_irqsave (&hcd_data_lock, flags);
1237 list_del (&dev->dev_list);
1238 udev->hcpriv = NULL;
1239 spin_unlock_irqrestore (&hcd_data_lock, flags);
1241 kfree (dev);
1242 return 0;
1246 * usb_hcd_operations - adapts usb_bus framework to HCD framework (bus glue)
1248 * When registering a USB bus through the HCD framework code, use this
1249 * usb_operations vector. The PCI glue layer does so automatically; only
1250 * bus glue for non-PCI system busses will need to use this.
1252 struct usb_operations usb_hcd_operations = {
1253 .allocate = hcd_alloc_dev,
1254 .get_frame_number = hcd_get_frame_number,
1255 .submit_urb = hcd_submit_urb,
1256 .unlink_urb = hcd_unlink_urb,
1257 .deallocate = hcd_free_dev,
1258 .buffer_alloc = hcd_buffer_alloc,
1259 .buffer_free = hcd_buffer_free,
1260 .buffer_map = hcd_buffer_map,
1261 .buffer_dmasync = hcd_buffer_dmasync,
1262 .buffer_unmap = hcd_buffer_unmap,
1263 .buffer_map_sg = hcd_buffer_map_sg,
1264 .buffer_dmasync_sg = hcd_buffer_sync_sg,
1265 .buffer_unmap_sg = hcd_buffer_unmap_sg,
1267 EXPORT_SYMBOL (usb_hcd_operations);
1269 /*-------------------------------------------------------------------------*/
1272 * usb_hcd_giveback_urb - return URB from HCD to device driver
1273 * @hcd: host controller returning the URB
1274 * @urb: urb being returned to the USB device driver.
1275 * Context: in_interrupt()
1277 * This hands the URB from HCD to its USB device driver, using its
1278 * completion function. The HCD has freed all per-urb resources
1279 * (and is done using urb->hcpriv). It also released all HCD locks;
1280 * the device driver won't cause problems if it frees, modifies,
1281 * or resubmits this URB.
1283 void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb)
1285 urb_unlink (urb);
1287 // NOTE: a generic device/urb monitoring hook would go here.
1288 // hcd_monitor_hook(MONITOR_URB_FINISH, urb, dev)
1289 // It would catch exit/unlink paths for all urbs, but non-exit
1290 // completions for periodic urbs need hooks inside the HCD.
1291 // hcd_monitor_hook(MONITOR_URB_UPDATE, urb, dev)
1293 if (urb->status)
1294 dbg ("giveback urb %p status %d len %d",
1295 urb, urb->status, urb->actual_length);
1297 /* lower level hcd code should use *_dma exclusively */
1298 if (!(urb->transfer_flags & URB_NO_DMA_MAP)) {
1299 if (usb_pipecontrol (urb->pipe))
1300 pci_unmap_single (hcd->pdev, urb->setup_dma,
1301 sizeof (struct usb_ctrlrequest),
1302 PCI_DMA_TODEVICE);
1303 if (urb->transfer_buffer_length != 0)
1304 pci_unmap_single (hcd->pdev, urb->transfer_dma,
1305 urb->transfer_buffer_length,
1306 usb_pipein (urb->pipe)
1307 ? PCI_DMA_FROMDEVICE
1308 : PCI_DMA_TODEVICE);
1311 /* pass ownership to the completion handler */
1312 urb->complete (urb);
1313 usb_put_urb (urb);
1315 EXPORT_SYMBOL (usb_hcd_giveback_urb);
1317 /*-------------------------------------------------------------------------*/
1320 * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
1321 * @irq: the IRQ being raised
1322 * @__hcd: pointer to the HCD whose IRQ is beinng signaled
1323 * @r: saved hardware registers (not passed to HCD)
1325 * When registering a USB bus through the HCD framework code, use this
1326 * to handle interrupts. The PCI glue layer does so automatically; only
1327 * bus glue for non-PCI system busses will need to use this.
1329 void usb_hcd_irq (int irq, void *__hcd, struct pt_regs * r)
1331 struct usb_hcd *hcd = __hcd;
1332 int start = hcd->state;
1334 if (unlikely (hcd->state == USB_STATE_HALT)) /* irq sharing? */
1335 return;
1337 hcd->driver->irq (hcd);
1338 if (hcd->state != start && hcd->state == USB_STATE_HALT)
1339 usb_hc_died (hcd);
1341 EXPORT_SYMBOL (usb_hcd_irq);
1343 /*-------------------------------------------------------------------------*/
1346 * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
1347 * @hcd: pointer to the HCD representing the controller
1349 * This is called by bus glue to report a USB host controller that died
1350 * while operations may still have been pending. It's called automatically
1351 * by the PCI glue, so only glue for non-PCI busses should need to call it.
1353 void usb_hc_died (struct usb_hcd *hcd)
1355 struct list_head *devlist, *urblist;
1356 struct hcd_dev *dev;
1357 struct urb *urb;
1358 unsigned long flags;
1360 /* flag every pending urb as done */
1361 spin_lock_irqsave (&hcd_data_lock, flags);
1362 list_for_each (devlist, &hcd->dev_list) {
1363 dev = list_entry (devlist, struct hcd_dev, dev_list);
1364 list_for_each (urblist, &dev->urb_list) {
1365 urb = list_entry (urblist, struct urb, urb_list);
1366 dbg ("shutdown %s urb %p pipe %x, current status %d",
1367 hcd->self.bus_name, urb, urb->pipe, urb->status);
1368 if (urb->status == -EINPROGRESS)
1369 urb->status = -ESHUTDOWN;
1372 urb = (struct urb *) hcd->rh_timer.data;
1373 if (urb)
1374 urb->status = -ESHUTDOWN;
1375 spin_unlock_irqrestore (&hcd_data_lock, flags);
1377 if (urb)
1378 usb_rh_status_dequeue (hcd, urb);
1379 hcd->driver->stop (hcd);
1381 EXPORT_SYMBOL (usb_hc_died);