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
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
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
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 */
39 #include <asm/scatterlist.h>
40 #include <linux/device.h>
41 #include <linux/dma-mapping.h>
42 #include <asm/byteorder.h>
44 #include <linux/usb.h>
50 // #define USB_BANDWIDTH_MESSAGES
52 /*-------------------------------------------------------------------------*/
55 * USB Host Controller Driver framework
57 * Plugs into usbcore (usb_bus) and lets HCDs share code, minimizing
58 * HCD-specific behaviors/bugs.
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.
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.
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.
76 * Contributors of ideas or unattributed patches include: David Brownell,
77 * Roman Weissgaerber, Rory Bolt, Greg Kroah-Hartman, ...
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.
85 /*-------------------------------------------------------------------------*/
87 /* host controllers we manage */
88 LIST_HEAD (usb_bus_list);
89 EXPORT_SYMBOL_GPL (usb_bus_list);
91 /* used when allocating bus numbers */
94 unsigned long busmap [USB_MAXBUS / (8*sizeof (unsigned long))];
96 static struct usb_busmap busmap;
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);
102 /* used when updating hcd data */
103 static spinlock_t hcd_data_lock = SPIN_LOCK_UNLOCKED;
105 /*-------------------------------------------------------------------------*/
108 * Sharable chunks of root hub code.
111 /*-------------------------------------------------------------------------*/
113 #define KERNEL_REL ((LINUX_VERSION_CODE >> 16) & 0x0ff)
114 #define KERNEL_VER ((LINUX_VERSION_CODE >> 8) & 0x0ff)
116 /* usb 2.0 root hub device descriptor */
117 static const u8 usb2_rh_dev_descriptor [18] = {
118 0x12, /* __u8 bLength; */
119 0x01, /* __u8 bDescriptorType; Device */
120 0x00, 0x02, /* __u16 bcdUSB; v2.0 */
122 0x09, /* __u8 bDeviceClass; HUB_CLASSCODE */
123 0x00, /* __u8 bDeviceSubClass; */
124 0x01, /* __u8 bDeviceProtocol; [ usb 2.0 single TT ]*/
125 0x08, /* __u8 bMaxPacketSize0; 8 Bytes */
127 0x00, 0x00, /* __u16 idVendor; */
128 0x00, 0x00, /* __u16 idProduct; */
129 KERNEL_VER, KERNEL_REL, /* __u16 bcdDevice */
131 0x03, /* __u8 iManufacturer; */
132 0x02, /* __u8 iProduct; */
133 0x01, /* __u8 iSerialNumber; */
134 0x01 /* __u8 bNumConfigurations; */
137 /* no usb 2.0 root hub "device qualifier" descriptor: one speed only */
139 /* usb 1.1 root hub device descriptor */
140 static const u8 usb11_rh_dev_descriptor [18] = {
141 0x12, /* __u8 bLength; */
142 0x01, /* __u8 bDescriptorType; Device */
143 0x10, 0x01, /* __u16 bcdUSB; v1.1 */
145 0x09, /* __u8 bDeviceClass; HUB_CLASSCODE */
146 0x00, /* __u8 bDeviceSubClass; */
147 0x00, /* __u8 bDeviceProtocol; [ low/full speeds only ] */
148 0x08, /* __u8 bMaxPacketSize0; 8 Bytes */
150 0x00, 0x00, /* __u16 idVendor; */
151 0x00, 0x00, /* __u16 idProduct; */
152 KERNEL_VER, KERNEL_REL, /* __u16 bcdDevice */
154 0x03, /* __u8 iManufacturer; */
155 0x02, /* __u8 iProduct; */
156 0x01, /* __u8 iSerialNumber; */
157 0x01 /* __u8 bNumConfigurations; */
161 /*-------------------------------------------------------------------------*/
163 /* Configuration descriptors for our root hubs */
165 static const u8 fs_rh_config_descriptor [] = {
167 /* one configuration */
168 0x09, /* __u8 bLength; */
169 0x02, /* __u8 bDescriptorType; Configuration */
170 0x19, 0x00, /* __u16 wTotalLength; */
171 0x01, /* __u8 bNumInterfaces; (1) */
172 0x01, /* __u8 bConfigurationValue; */
173 0x00, /* __u8 iConfiguration; */
174 0x40, /* __u8 bmAttributes;
179 0x00, /* __u8 MaxPower; */
182 * USB 2.0, single TT organization (mandatory):
183 * one interface, protocol 0
185 * USB 2.0, multiple TT organization (optional):
186 * two interfaces, protocols 1 (like single TT)
187 * and 2 (multiple TT mode) ... config is
193 0x09, /* __u8 if_bLength; */
194 0x04, /* __u8 if_bDescriptorType; Interface */
195 0x00, /* __u8 if_bInterfaceNumber; */
196 0x00, /* __u8 if_bAlternateSetting; */
197 0x01, /* __u8 if_bNumEndpoints; */
198 0x09, /* __u8 if_bInterfaceClass; HUB_CLASSCODE */
199 0x00, /* __u8 if_bInterfaceSubClass; */
200 0x00, /* __u8 if_bInterfaceProtocol; [usb1.1 or single tt] */
201 0x00, /* __u8 if_iInterface; */
203 /* one endpoint (status change endpoint) */
204 0x07, /* __u8 ep_bLength; */
205 0x05, /* __u8 ep_bDescriptorType; Endpoint */
206 0x81, /* __u8 ep_bEndpointAddress; IN Endpoint 1 */
207 0x03, /* __u8 ep_bmAttributes; Interrupt */
208 0x02, 0x00, /* __u16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
209 0xff /* __u8 ep_bInterval; (255ms -- usb 2.0 spec) */
212 static const u8 hs_rh_config_descriptor [] = {
214 /* one configuration */
215 0x09, /* __u8 bLength; */
216 0x02, /* __u8 bDescriptorType; Configuration */
217 0x19, 0x00, /* __u16 wTotalLength; */
218 0x01, /* __u8 bNumInterfaces; (1) */
219 0x01, /* __u8 bConfigurationValue; */
220 0x00, /* __u8 iConfiguration; */
221 0x40, /* __u8 bmAttributes;
226 0x00, /* __u8 MaxPower; */
229 * USB 2.0, single TT organization (mandatory):
230 * one interface, protocol 0
232 * USB 2.0, multiple TT organization (optional):
233 * two interfaces, protocols 1 (like single TT)
234 * and 2 (multiple TT mode) ... config is
240 0x09, /* __u8 if_bLength; */
241 0x04, /* __u8 if_bDescriptorType; Interface */
242 0x00, /* __u8 if_bInterfaceNumber; */
243 0x00, /* __u8 if_bAlternateSetting; */
244 0x01, /* __u8 if_bNumEndpoints; */
245 0x09, /* __u8 if_bInterfaceClass; HUB_CLASSCODE */
246 0x00, /* __u8 if_bInterfaceSubClass; */
247 0x00, /* __u8 if_bInterfaceProtocol; [usb1.1 or single tt] */
248 0x00, /* __u8 if_iInterface; */
250 /* one endpoint (status change endpoint) */
251 0x07, /* __u8 ep_bLength; */
252 0x05, /* __u8 ep_bDescriptorType; Endpoint */
253 0x81, /* __u8 ep_bEndpointAddress; IN Endpoint 1 */
254 0x03, /* __u8 ep_bmAttributes; Interrupt */
255 0x02, 0x00, /* __u16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
256 0x0c /* __u8 ep_bInterval; (256ms -- usb 2.0 spec) */
259 /*-------------------------------------------------------------------------*/
262 * helper routine for returning string descriptors in UTF-16LE
263 * input can actually be ISO-8859-1; ASCII is its 7-bit subset
265 static int ascii2utf (char *s, u8 *utf, int utfmax)
269 for (retval = 0; *s && utfmax > 1; utfmax -= 2, retval += 2) {
277 * rh_string - provides manufacturer, product and serial strings for root hub
278 * @id: the string ID number (1: serial number, 2: product, 3: vendor)
279 * @hcd: the host controller for this root hub
280 * @type: string describing our driver
281 * @data: return packet in UTF-16 LE
282 * @len: length of the return packet
284 * Produces either a manufacturer, product or serial number string for the
285 * virtual root hub device.
287 static int rh_string (
297 *data++ = 4; *data++ = 3; /* 4 bytes string data */
298 *data++ = 0x09; *data++ = 0x04; /* MSFT-speak for "en-us" */
302 } else if (id == 1) {
303 strcpy (buf, hcd->self.bus_name);
305 // product description
306 } else if (id == 2) {
307 strcpy (buf, hcd->product_desc);
309 // id 3 == vendor description
310 } else if (id == 3) {
311 sprintf (buf, "%s %s %s", UTS_SYSNAME, UTS_RELEASE,
314 // unsupported IDs --> "protocol stall"
318 data [0] = 2 * (strlen (buf) + 1);
319 data [1] = 3; /* type == string */
320 return 2 + ascii2utf (buf, data + 2, len - 2);
324 /* Root hub control transfers execute synchronously */
325 static int rh_call_control (struct usb_hcd *hcd, struct urb *urb)
327 struct usb_ctrlrequest *cmd = (struct usb_ctrlrequest *) urb->setup_packet;
328 u16 typeReq, wValue, wIndex, wLength;
330 u8 *ubuf = urb->transfer_buffer;
334 typeReq = (cmd->bRequestType << 8) | cmd->bRequest;
335 wValue = le16_to_cpu (cmd->wValue);
336 wIndex = le16_to_cpu (cmd->wIndex);
337 wLength = le16_to_cpu (cmd->wLength);
339 if (wLength > urb->transfer_buffer_length)
342 /* set up for success */
344 urb->actual_length = wLength;
347 /* DEVICE REQUESTS */
349 case DeviceRequest | USB_REQ_GET_STATUS:
350 // DEVICE_REMOTE_WAKEUP
351 ubuf [0] = 1; // selfpowered
354 case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
355 case DeviceOutRequest | USB_REQ_SET_FEATURE:
356 dev_dbg (hcd->self.controller, "no device features yet yet\n");
358 case DeviceRequest | USB_REQ_GET_CONFIGURATION:
361 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
363 case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
364 switch (wValue & 0xff00) {
365 case USB_DT_DEVICE << 8:
366 if (hcd->driver->flags & HCD_USB2)
367 bufp = usb2_rh_dev_descriptor;
368 else if (hcd->driver->flags & HCD_USB11)
369 bufp = usb11_rh_dev_descriptor;
374 case USB_DT_CONFIG << 8:
375 if (hcd->driver->flags & HCD_USB2) {
376 bufp = hs_rh_config_descriptor;
377 len = sizeof hs_rh_config_descriptor;
379 bufp = fs_rh_config_descriptor;
380 len = sizeof fs_rh_config_descriptor;
383 case USB_DT_STRING << 8:
384 urb->actual_length = rh_string (
392 case DeviceRequest | USB_REQ_GET_INTERFACE:
395 case DeviceOutRequest | USB_REQ_SET_INTERFACE:
397 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
398 // wValue == urb->dev->devaddr
399 dev_dbg (hcd->self.controller, "root hub device address %d\n",
403 /* INTERFACE REQUESTS (no defined feature/status flags) */
405 /* ENDPOINT REQUESTS */
407 case EndpointRequest | USB_REQ_GET_STATUS:
408 // ENDPOINT_HALT flag
412 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
413 case EndpointOutRequest | USB_REQ_SET_FEATURE:
414 dev_dbg (hcd->self.controller, "no endpoint features yet\n");
417 /* CLASS REQUESTS (and errors) */
420 /* non-generic request */
421 if (HCD_IS_SUSPENDED (hcd->state))
422 urb->status = -EAGAIN;
423 else if (!HCD_IS_RUNNING (hcd->state))
424 urb->status = -ENODEV;
426 urb->status = hcd->driver->hub_control (hcd,
427 typeReq, wValue, wIndex,
431 /* "protocol stall" on error */
432 urb->status = -EPIPE;
433 dev_dbg (hcd->self.controller, "unsupported hub control message (maxchild %d)\n",
437 urb->actual_length = 0;
438 dev_dbg (hcd->self.controller, "CTRL: TypeReq=0x%x val=0x%x idx=0x%x len=%d ==> %d\n",
439 typeReq, wValue, wIndex, wLength, urb->status);
442 if (urb->transfer_buffer_length < len)
443 len = urb->transfer_buffer_length;
444 urb->actual_length = len;
445 // always USB_DIR_IN, toward host
446 memcpy (ubuf, bufp, len);
449 /* any errors get returned through the urb completion */
450 local_irq_save (flags);
451 usb_hcd_giveback_urb (hcd, urb, NULL);
452 local_irq_restore (flags);
456 /*-------------------------------------------------------------------------*/
459 * Root Hub interrupt transfers are synthesized with a timer.
460 * Completions are called in_interrupt() but not in_irq().
463 static void rh_report_status (unsigned long ptr);
465 static int rh_status_urb (struct usb_hcd *hcd, struct urb *urb)
467 int len = 1 + (urb->dev->maxchild / 8);
469 /* rh_timer protected by hcd_data_lock */
470 if (hcd->rh_timer.data
471 || urb->status != -EINPROGRESS
472 || urb->transfer_buffer_length < len
473 || !HCD_IS_RUNNING (hcd->state)) {
474 dev_dbg (hcd->self.controller,
475 "not queuing rh status urb, stat %d\n",
480 init_timer (&hcd->rh_timer);
481 hcd->rh_timer.function = rh_report_status;
482 hcd->rh_timer.data = (unsigned long) urb;
483 /* USB 2.0 spec says 256msec; this is close enough */
484 hcd->rh_timer.expires = jiffies + HZ/4;
485 add_timer (&hcd->rh_timer);
486 urb->hcpriv = hcd; /* nonzero to indicate it's queued */
492 static void rh_report_status (unsigned long ptr)
499 urb = (struct urb *) ptr;
500 local_irq_save (flags);
501 spin_lock (&urb->lock);
503 /* do nothing if the urb's been unlinked */
505 || urb->status != -EINPROGRESS
506 || (hcd = urb->dev->bus->hcpriv) == 0) {
507 spin_unlock (&urb->lock);
508 local_irq_restore (flags);
512 if (!HCD_IS_SUSPENDED (hcd->state))
513 length = hcd->driver->hub_status_data (
514 hcd, urb->transfer_buffer);
516 /* complete the status urb, or retrigger the timer */
517 spin_lock (&hcd_data_lock);
519 hcd->rh_timer.data = 0;
520 urb->actual_length = length;
524 mod_timer (&hcd->rh_timer, jiffies + HZ/4);
525 spin_unlock (&hcd_data_lock);
526 spin_unlock (&urb->lock);
528 /* local irqs are always blocked in completions */
530 usb_hcd_giveback_urb (hcd, urb, NULL);
531 local_irq_restore (flags);
534 /*-------------------------------------------------------------------------*/
536 static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
538 if (usb_pipeint (urb->pipe)) {
542 spin_lock_irqsave (&hcd_data_lock, flags);
543 retval = rh_status_urb (hcd, urb);
544 spin_unlock_irqrestore (&hcd_data_lock, flags);
547 if (usb_pipecontrol (urb->pipe))
548 return rh_call_control (hcd, urb);
553 /*-------------------------------------------------------------------------*/
555 void usb_rh_status_dequeue (struct usb_hcd *hcd, struct urb *urb)
559 /* note: always a synchronous unlink */
560 del_timer_sync (&hcd->rh_timer);
561 hcd->rh_timer.data = 0;
563 local_irq_save (flags);
565 usb_hcd_giveback_urb (hcd, urb, NULL);
566 local_irq_restore (flags);
569 /*-------------------------------------------------------------------------*/
571 /* exported only within usbcore */
572 struct usb_bus *usb_bus_get (struct usb_bus *bus)
574 struct class_device *tmp;
579 tmp = class_device_get(&bus->class_dev);
581 return to_usb_bus(tmp);
586 /* exported only within usbcore */
587 void usb_bus_put (struct usb_bus *bus)
590 class_device_put(&bus->class_dev);
593 /*-------------------------------------------------------------------------*/
595 static void usb_host_release(struct class_device *class_dev)
597 struct usb_bus *bus = to_usb_bus(class_dev);
603 static struct class usb_host_class = {
605 .release = &usb_host_release,
608 void usb_host_init(void)
610 class_register(&usb_host_class);
613 void usb_host_cleanup(void)
615 class_unregister(&usb_host_class);
619 * usb_bus_init - shared initialization code
620 * @bus: the bus structure being initialized
622 * This code is used to initialize a usb_bus structure, memory for which is
623 * separately managed.
625 void usb_bus_init (struct usb_bus *bus)
627 memset (&bus->devmap, 0, sizeof(struct usb_devmap));
629 bus->devnum_next = 1;
631 bus->root_hub = NULL;
634 bus->bandwidth_allocated = 0;
635 bus->bandwidth_int_reqs = 0;
636 bus->bandwidth_isoc_reqs = 0;
638 INIT_LIST_HEAD (&bus->bus_list);
640 EXPORT_SYMBOL (usb_bus_init);
643 * usb_alloc_bus - creates a new USB host controller structure
644 * @op: pointer to a struct usb_operations that this bus structure should use
645 * Context: !in_interrupt()
647 * Creates a USB host controller bus structure with the specified
648 * usb_operations and initializes all the necessary internal objects.
650 * If no memory is available, NULL is returned.
652 * The caller should call usb_put_bus() when it is finished with the structure.
654 struct usb_bus *usb_alloc_bus (struct usb_operations *op)
658 bus = kmalloc (sizeof *bus, GFP_KERNEL);
661 memset(bus, 0, sizeof(struct usb_bus));
666 EXPORT_SYMBOL (usb_alloc_bus);
668 /*-------------------------------------------------------------------------*/
671 * usb_register_bus - registers the USB host controller with the usb core
672 * @bus: pointer to the bus to register
673 * Context: !in_interrupt()
675 * Assigns a bus number, and links the controller into usbcore data
676 * structures so that it can be seen by scanning the bus list.
678 int usb_register_bus(struct usb_bus *bus)
683 down (&usb_bus_list_lock);
684 busnum = find_next_zero_bit (busmap.busmap, USB_MAXBUS, 1);
685 if (busnum < USB_MAXBUS) {
686 set_bit (busnum, busmap.busmap);
687 bus->busnum = busnum;
689 printk (KERN_ERR "%s: too many buses\n", usbcore_name);
693 snprintf(bus->class_dev.class_id, BUS_ID_SIZE, "usb%d", busnum);
694 bus->class_dev.class = &usb_host_class;
695 bus->class_dev.dev = bus->controller;
696 retval = class_device_register(&bus->class_dev);
698 clear_bit(busnum, busmap.busmap);
699 up(&usb_bus_list_lock);
703 /* Add it to the local list of buses */
704 list_add (&bus->bus_list, &usb_bus_list);
705 up (&usb_bus_list_lock);
709 dev_info (bus->controller, "new USB bus registered, assigned bus number %d\n", bus->busnum);
712 EXPORT_SYMBOL (usb_register_bus);
715 * usb_deregister_bus - deregisters the USB host controller
716 * @bus: pointer to the bus to deregister
717 * Context: !in_interrupt()
719 * Recycles the bus number, and unlinks the controller from usbcore data
720 * structures so that it won't be seen by scanning the bus list.
722 void usb_deregister_bus (struct usb_bus *bus)
724 dev_info (bus->controller, "USB bus %d deregistered\n", bus->busnum);
727 * NOTE: make sure that all the devices are removed by the
728 * controller code, as well as having it call this when cleaning
731 down (&usb_bus_list_lock);
732 list_del (&bus->bus_list);
733 up (&usb_bus_list_lock);
735 usbfs_remove_bus (bus);
737 clear_bit (bus->busnum, busmap.busmap);
739 class_device_unregister(&bus->class_dev);
741 EXPORT_SYMBOL (usb_deregister_bus);
744 * usb_register_root_hub - called by HCD to register its root hub
745 * @usb_dev: the usb root hub device to be registered.
746 * @parent_dev: the parent device of this root hub.
748 * The USB host controller calls this function to register the root hub
749 * properly with the USB subsystem. It sets up the device properly in
750 * the device model tree, and then calls usb_new_device() to register the
751 * usb device. It also assigns the root hub's USB address (always 1).
753 int usb_register_root_hub (struct usb_device *usb_dev, struct device *parent_dev)
755 const int devnum = 1;
758 usb_dev->devnum = devnum;
759 usb_dev->bus->devnum_next = devnum + 1;
760 memset (&usb_dev->bus->devmap.devicemap, 0,
761 sizeof usb_dev->bus->devmap.devicemap);
762 set_bit (devnum, usb_dev->bus->devmap.devicemap);
763 usb_dev->state = USB_STATE_ADDRESS;
765 retval = usb_new_device (usb_dev);
767 dev_err (parent_dev, "can't register root hub for %s, %d\n",
768 usb_dev->dev.bus_id, retval);
771 EXPORT_SYMBOL (usb_register_root_hub);
774 /*-------------------------------------------------------------------------*/
777 * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
778 * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
779 * @is_input: true iff the transaction sends data to the host
780 * @isoc: true for isochronous transactions, false for interrupt ones
781 * @bytecount: how many bytes in the transaction.
783 * Returns approximate bus time in nanoseconds for a periodic transaction.
784 * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
785 * scheduled in software, this function is only used for such scheduling.
787 long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
792 case USB_SPEED_LOW: /* INTR only */
794 tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
795 return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
797 tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
798 return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
800 case USB_SPEED_FULL: /* ISOC or INTR */
802 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
803 return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
805 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
806 return (9107L + BW_HOST_DELAY + tmp);
808 case USB_SPEED_HIGH: /* ISOC or INTR */
809 // FIXME adjust for input vs output
811 tmp = HS_USECS (bytecount);
813 tmp = HS_USECS_ISO (bytecount);
816 pr_debug ("%s: bogus device speed!\n", usbcore_name);
820 EXPORT_SYMBOL (usb_calc_bus_time);
823 * usb_check_bandwidth():
825 * old_alloc is from host_controller->bandwidth_allocated in microseconds;
826 * bustime is from calc_bus_time(), but converted to microseconds.
828 * returns <bustime in us> if successful,
829 * or -ENOSPC if bandwidth request fails.
832 * This initial implementation does not use Endpoint.bInterval
833 * in managing bandwidth allocation.
834 * It probably needs to be expanded to use Endpoint.bInterval.
835 * This can be done as a later enhancement (correction).
837 * This will also probably require some kind of
838 * frame allocation tracking...meaning, for example,
839 * that if multiple drivers request interrupts every 10 USB frames,
840 * they don't all have to be allocated at
841 * frame numbers N, N+10, N+20, etc. Some of them could be at
842 * N+11, N+21, N+31, etc., and others at
843 * N+12, N+22, N+32, etc.
845 * Similarly for isochronous transfers...
847 * Individual HCDs can schedule more directly ... this logic
848 * is not correct for high speed transfers.
850 int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
852 unsigned int pipe = urb->pipe;
854 int is_in = usb_pipein (pipe);
855 int is_iso = usb_pipeisoc (pipe);
856 int old_alloc = dev->bus->bandwidth_allocated;
860 bustime = NS_TO_US (usb_calc_bus_time (dev->speed, is_in, is_iso,
861 usb_maxpacket (dev, pipe, !is_in)));
863 bustime /= urb->number_of_packets;
865 new_alloc = old_alloc + (int) bustime;
866 if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC) {
869 #ifdef CONFIG_USB_BANDWIDTH
874 dev_dbg (&dev->dev, "usb_check_bandwidth %sFAILED: %d + %ld = %d usec\n",
875 mode, old_alloc, bustime, new_alloc);
877 #ifdef CONFIG_USB_BANDWIDTH
878 bustime = -ENOSPC; /* report error */
884 EXPORT_SYMBOL (usb_check_bandwidth);
888 * usb_claim_bandwidth - records bandwidth for a periodic transfer
889 * @dev: source/target of request
890 * @urb: request (urb->dev == dev)
891 * @bustime: bandwidth consumed, in (average) microseconds per frame
892 * @isoc: true iff the request is isochronous
894 * Bus bandwidth reservations are recorded purely for diagnostic purposes.
895 * HCDs are expected not to overcommit periodic bandwidth, and to record such
896 * reservations whenever endpoints are added to the periodic schedule.
898 * FIXME averaging per-frame is suboptimal. Better to sum over the HCD's
899 * entire periodic schedule ... 32 frames for OHCI, 1024 for UHCI, settable
900 * for EHCI (256/512/1024 frames, default 1024) and have the bus expose how
901 * large its periodic schedule is.
903 void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
905 dev->bus->bandwidth_allocated += bustime;
907 dev->bus->bandwidth_isoc_reqs++;
909 dev->bus->bandwidth_int_reqs++;
910 urb->bandwidth = bustime;
912 #ifdef USB_BANDWIDTH_MESSAGES
913 dev_dbg (&dev->dev, "bandwidth alloc increased by %d (%s) to %d for %d requesters\n",
915 isoc ? "ISOC" : "INTR",
916 dev->bus->bandwidth_allocated,
917 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
920 EXPORT_SYMBOL (usb_claim_bandwidth);
924 * usb_release_bandwidth - reverses effect of usb_claim_bandwidth()
925 * @dev: source/target of request
926 * @urb: request (urb->dev == dev)
927 * @isoc: true iff the request is isochronous
929 * This records that previously allocated bandwidth has been released.
930 * Bandwidth is released when endpoints are removed from the host controller's
933 void usb_release_bandwidth (struct usb_device *dev, struct urb *urb, int isoc)
935 dev->bus->bandwidth_allocated -= urb->bandwidth;
937 dev->bus->bandwidth_isoc_reqs--;
939 dev->bus->bandwidth_int_reqs--;
941 #ifdef USB_BANDWIDTH_MESSAGES
942 dev_dbg (&dev->dev, "bandwidth alloc reduced by %d (%s) to %d for %d requesters\n",
944 isoc ? "ISOC" : "INTR",
945 dev->bus->bandwidth_allocated,
946 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
950 EXPORT_SYMBOL (usb_release_bandwidth);
953 /*-------------------------------------------------------------------------*/
956 * Generic HC operations.
959 /*-------------------------------------------------------------------------*/
961 /* called from khubd, or root hub init threads for hcd-private init */
962 static int hcd_alloc_dev (struct usb_device *udev)
968 if (!udev || udev->hcpriv)
970 if (!udev->bus || !udev->bus->hcpriv)
972 hcd = udev->bus->hcpriv;
973 if (hcd->state == USB_STATE_QUIESCING)
976 dev = (struct hcd_dev *) kmalloc (sizeof *dev, GFP_KERNEL);
979 memset (dev, 0, sizeof *dev);
981 INIT_LIST_HEAD (&dev->dev_list);
982 INIT_LIST_HEAD (&dev->urb_list);
984 spin_lock_irqsave (&hcd_data_lock, flags);
985 list_add (&dev->dev_list, &hcd->dev_list);
986 // refcount is implicit
988 spin_unlock_irqrestore (&hcd_data_lock, flags);
993 /*-------------------------------------------------------------------------*/
995 static void urb_unlink (struct urb *urb)
998 struct usb_device *dev;
1000 /* Release any periodic transfer bandwidth */
1002 usb_release_bandwidth (urb->dev, urb,
1003 usb_pipeisoc (urb->pipe));
1005 /* clear all state linking urb to this dev (and hcd) */
1007 spin_lock_irqsave (&hcd_data_lock, flags);
1008 list_del_init (&urb->urb_list);
1010 spin_unlock_irqrestore (&hcd_data_lock, flags);
1015 /* may be called in any context with a valid urb->dev usecount
1016 * caller surrenders "ownership" of urb
1017 * expects usb_submit_urb() to have sanity checked and conditioned all
1020 static int hcd_submit_urb (struct urb *urb, int mem_flags)
1023 struct usb_hcd *hcd = urb->dev->bus->hcpriv;
1024 struct hcd_dev *dev = urb->dev->hcpriv;
1025 unsigned long flags;
1031 * FIXME: make urb timeouts be generic, keeping the HCD cores
1032 * as simple as possible.
1035 // NOTE: a generic device/urb monitoring hook would go here.
1036 // hcd_monitor_hook(MONITOR_URB_SUBMIT, urb)
1037 // It would catch submission paths for all urbs.
1040 * Atomically queue the urb, first to our records, then to the HCD.
1041 * Access to urb->status is controlled by urb->lock ... changes on
1042 * i/o completion (normal or fault) or unlinking.
1045 // FIXME: verify that quiescing hc works right (RH cleans up)
1047 spin_lock_irqsave (&hcd_data_lock, flags);
1048 if (HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_QUIESCING) {
1049 usb_get_dev (urb->dev);
1050 list_add_tail (&urb->urb_list, &dev->urb_list);
1053 INIT_LIST_HEAD (&urb->urb_list);
1054 status = -ESHUTDOWN;
1056 spin_unlock_irqrestore (&hcd_data_lock, flags);
1060 /* increment urb's reference count as part of giving it to the HCD
1061 * (which now controls it). HCD guarantees that it either returns
1062 * an error or calls giveback(), but not both.
1064 urb = usb_get_urb (urb);
1065 if (urb->dev == hcd->self.root_hub) {
1066 /* NOTE: requirement on hub callers (usbfs and the hub
1067 * driver, for now) that URBs' urb->transfer_buffer be
1068 * valid and usb_buffer_{sync,unmap}() not be needed, since
1069 * they could clobber root hub response data.
1071 urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
1072 | URB_NO_SETUP_DMA_MAP);
1073 status = rh_urb_enqueue (hcd, urb);
1077 /* lower level hcd code should use *_dma exclusively,
1078 * unless it uses pio or talks to another transport.
1080 if (hcd->self.controller->dma_mask) {
1081 if (usb_pipecontrol (urb->pipe)
1082 && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1083 urb->setup_dma = dma_map_single (
1084 hcd->self.controller,
1086 sizeof (struct usb_ctrlrequest),
1088 if (urb->transfer_buffer_length != 0
1089 && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1090 urb->transfer_dma = dma_map_single (
1091 hcd->self.controller,
1092 urb->transfer_buffer,
1093 urb->transfer_buffer_length,
1094 usb_pipein (urb->pipe)
1099 status = hcd->driver->urb_enqueue (hcd, urb, mem_flags);
1108 /*-------------------------------------------------------------------------*/
1110 /* called in any context */
1111 static int hcd_get_frame_number (struct usb_device *udev)
1113 struct usb_hcd *hcd = (struct usb_hcd *)udev->bus->hcpriv;
1114 if (!HCD_IS_RUNNING (hcd->state))
1116 return hcd->driver->get_frame_number (hcd);
1119 /*-------------------------------------------------------------------------*/
1121 /* this makes the hcd giveback() the urb more quickly, by kicking it
1122 * off hardware queues (which may take a while) and returning it as
1123 * soon as practical. we've already set up the urb's return status,
1124 * but we can't know if the callback completed already.
1127 unlink1 (struct usb_hcd *hcd, struct urb *urb)
1129 if (urb == (struct urb *) hcd->rh_timer.data)
1130 usb_rh_status_dequeue (hcd, urb);
1134 /* failures "should" be harmless */
1135 value = hcd->driver->urb_dequeue (hcd, urb);
1137 dev_dbg (hcd->self.controller,
1138 "dequeue %p --> %d\n",
1143 struct completion_splice { // modified urb context:
1144 /* did we complete? */
1145 struct completion done;
1147 /* original urb data */
1148 usb_complete_t complete;
1152 static void unlink_complete (struct urb *urb, struct pt_regs *regs)
1154 struct completion_splice *splice;
1156 splice = (struct completion_splice *) urb->context;
1158 /* issue original completion call */
1159 urb->complete = splice->complete;
1160 urb->context = splice->context;
1161 urb->complete (urb, regs);
1163 /* then let the synchronous unlink call complete */
1164 complete (&splice->done);
1168 * called in any context; note ASYNC_UNLINK restrictions
1170 * caller guarantees urb won't be recycled till both unlink()
1171 * and the urb's completion function return
1173 static int hcd_unlink_urb (struct urb *urb)
1175 struct hcd_dev *dev;
1176 struct usb_hcd *hcd = 0;
1177 struct device *sys = 0;
1178 unsigned long flags;
1179 struct completion_splice splice;
1180 struct list_head *tmp;
1187 * we contend for urb->status with the hcd core,
1188 * which changes it while returning the urb.
1190 * Caller guaranteed that the urb pointer hasn't been freed, and
1191 * that it was submitted. But as a rule it can't know whether or
1192 * not it's already been unlinked ... so we respect the reversed
1193 * lock sequence needed for the usb_hcd_giveback_urb() code paths
1194 * (urb lock, then hcd_data_lock) in case some other CPU is now
1197 spin_lock_irqsave (&urb->lock, flags);
1198 spin_lock (&hcd_data_lock);
1200 if (!urb->dev || !urb->dev->bus) {
1205 dev = urb->dev->hcpriv;
1206 sys = &urb->dev->dev;
1207 hcd = urb->dev->bus->hcpriv;
1213 /* running ~= hc unlink handshake works (irq, timer, etc)
1214 * halted ~= no unlink handshake is needed
1215 * suspended, resuming == should never happen
1217 WARN_ON (!HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_HALT);
1219 /* insist the urb is still queued */
1220 list_for_each(tmp, &dev->urb_list) {
1221 if (tmp == &urb->urb_list)
1224 if (tmp != &urb->urb_list) {
1229 /* Any status except -EINPROGRESS means something already started to
1230 * unlink this URB from the hardware. So there's no more work to do.
1232 * FIXME use better explicit urb state
1234 if (urb->status != -EINPROGRESS) {
1239 /* PCI IRQ setup can easily be broken so that USB controllers
1240 * never get completion IRQs ... maybe even the ones we need to
1241 * finish unlinking the initial failed usb_set_address().
1243 if (!hcd->saw_irq) {
1244 dev_warn (hcd->self.controller, "Unlink after no-IRQ? "
1245 "Different ACPI or APIC settings may help."
1250 /* maybe set up to block until the urb's completion fires. the
1251 * lower level hcd code is always async, locking on urb->status
1252 * updates; an intercepted completion unblocks us.
1254 if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1255 if (in_interrupt ()) {
1256 dev_dbg (hcd->self.controller,
1257 "non-async unlink in_interrupt");
1258 retval = -EWOULDBLOCK;
1261 /* synchronous unlink: block till we see the completion */
1262 init_completion (&splice.done);
1263 splice.complete = urb->complete;
1264 splice.context = urb->context;
1265 urb->complete = unlink_complete;
1266 urb->context = &splice;
1267 urb->status = -ENOENT;
1269 /* asynchronous unlink */
1270 urb->status = -ECONNRESET;
1272 spin_unlock (&hcd_data_lock);
1273 spin_unlock_irqrestore (&urb->lock, flags);
1275 // FIXME remove splicing, so this becomes unlink1 (hcd, urb);
1276 if (urb == (struct urb *) hcd->rh_timer.data) {
1277 usb_rh_status_dequeue (hcd, urb);
1280 retval = hcd->driver->urb_dequeue (hcd, urb);
1282 /* hcds shouldn't really fail these calls, but... */
1284 dev_dbg (sys, "dequeue %p --> %d\n", urb, retval);
1285 if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
1286 spin_lock_irqsave (&urb->lock, flags);
1287 urb->complete = splice.complete;
1288 urb->context = splice.context;
1289 spin_unlock_irqrestore (&urb->lock, flags);
1295 /* block till giveback, if needed */
1296 if (urb->transfer_flags & URB_ASYNC_UNLINK)
1297 return -EINPROGRESS;
1299 wait_for_completion (&splice.done);
1303 spin_unlock (&hcd_data_lock);
1304 spin_unlock_irqrestore (&urb->lock, flags);
1306 if (retval != -EIDRM && sys && sys->driver)
1307 dev_dbg (sys, "hcd_unlink_urb %p fail %d\n", urb, retval);
1311 /*-------------------------------------------------------------------------*/
1313 /* disables the endpoint: cancels any pending urbs, then synchronizes with
1314 * the hcd to make sure all endpoint state is gone from hardware. use for
1315 * set_configuration, set_interface, driver removal, physical disconnect.
1317 * example: a qh stored in hcd_dev.ep[], holding state related to endpoint
1318 * type, maxpacket size, toggle, halt status, and scheduling.
1320 static void hcd_endpoint_disable (struct usb_device *udev, int endpoint)
1322 struct hcd_dev *dev;
1323 struct usb_hcd *hcd;
1325 unsigned epnum = endpoint & USB_ENDPOINT_NUMBER_MASK;
1328 hcd = udev->bus->hcpriv;
1330 WARN_ON (!HCD_IS_RUNNING (hcd->state) && hcd->state != USB_STATE_HALT);
1332 local_irq_disable ();
1335 /* (re)block new requests, as best we can */
1336 if (endpoint & USB_DIR_IN) {
1337 usb_endpoint_halt (udev, epnum, 0);
1338 udev->epmaxpacketin [epnum] = 0;
1340 usb_endpoint_halt (udev, epnum, 1);
1341 udev->epmaxpacketout [epnum] = 0;
1344 /* then kill any current requests */
1345 spin_lock (&hcd_data_lock);
1346 list_for_each_entry (urb, &dev->urb_list, urb_list) {
1347 int tmp = urb->pipe;
1349 /* ignore urbs for other endpoints */
1350 if (usb_pipeendpoint (tmp) != epnum)
1352 /* NOTE assumption that only ep0 is a control endpoint */
1353 if (epnum != 0 && ((tmp ^ endpoint) & USB_DIR_IN))
1356 /* another cpu may be in hcd, spinning on hcd_data_lock
1357 * to giveback() this urb. the races here should be
1358 * small, but a full fix needs a new "can't submit"
1361 if (urb->status != -EINPROGRESS)
1364 spin_unlock (&hcd_data_lock);
1366 spin_lock (&urb->lock);
1368 if (tmp == -EINPROGRESS)
1369 urb->status = -ESHUTDOWN;
1370 spin_unlock (&urb->lock);
1372 /* kick hcd unless it's already returning this */
1373 if (tmp == -EINPROGRESS) {
1376 dev_dbg (hcd->self.controller,
1377 "shutdown urb %p pipe %08x ep%d%s%s\n",
1378 urb, tmp, usb_pipeendpoint (tmp),
1379 (tmp & USB_DIR_IN) ? "in" : "out",
1381 switch (usb_pipetype (tmp)) { \
1382 case PIPE_CONTROL: s = ""; break; \
1383 case PIPE_BULK: s = "-bulk"; break; \
1384 case PIPE_INTERRUPT: s = "-intr"; break; \
1385 default: s = "-iso"; break; \
1390 /* list contents may have changed */
1393 spin_unlock (&hcd_data_lock);
1394 local_irq_enable ();
1396 /* synchronize with the hardware, so old configuration state
1397 * clears out immediately (and will be freed).
1400 if (hcd->driver->endpoint_disable)
1401 hcd->driver->endpoint_disable (hcd, dev, endpoint);
1404 /*-------------------------------------------------------------------------*/
1406 /* called by khubd, rmmod, apmd, or other thread for hcd-private cleanup.
1407 * we're guaranteed that the device is fully quiesced. also, that each
1408 * endpoint has been hcd_endpoint_disabled.
1411 static int hcd_free_dev (struct usb_device *udev)
1413 struct hcd_dev *dev;
1414 struct usb_hcd *hcd;
1415 unsigned long flags;
1417 if (!udev || !udev->hcpriv)
1420 if (!udev->bus || !udev->bus->hcpriv)
1423 // should udev->devnum == -1 ??
1426 hcd = udev->bus->hcpriv;
1428 /* device driver problem with refcounts? */
1429 if (!list_empty (&dev->urb_list)) {
1430 dev_dbg (hcd->self.controller, "free busy dev, %s devnum %d (bug!)\n",
1431 hcd->self.bus_name, udev->devnum);
1435 spin_lock_irqsave (&hcd_data_lock, flags);
1436 list_del (&dev->dev_list);
1437 udev->hcpriv = NULL;
1438 spin_unlock_irqrestore (&hcd_data_lock, flags);
1445 * usb_hcd_operations - adapts usb_bus framework to HCD framework (bus glue)
1447 * When registering a USB bus through the HCD framework code, use this
1448 * usb_operations vector. The PCI glue layer does so automatically; only
1449 * bus glue for non-PCI system busses will need to use this.
1451 struct usb_operations usb_hcd_operations = {
1452 .allocate = hcd_alloc_dev,
1453 .get_frame_number = hcd_get_frame_number,
1454 .submit_urb = hcd_submit_urb,
1455 .unlink_urb = hcd_unlink_urb,
1456 .deallocate = hcd_free_dev,
1457 .buffer_alloc = hcd_buffer_alloc,
1458 .buffer_free = hcd_buffer_free,
1459 .disable = hcd_endpoint_disable,
1461 EXPORT_SYMBOL (usb_hcd_operations);
1463 /*-------------------------------------------------------------------------*/
1466 * usb_hcd_giveback_urb - return URB from HCD to device driver
1467 * @hcd: host controller returning the URB
1468 * @urb: urb being returned to the USB device driver.
1469 * @regs: pt_regs, passed down to the URB completion handler
1470 * Context: in_interrupt()
1472 * This hands the URB from HCD to its USB device driver, using its
1473 * completion function. The HCD has freed all per-urb resources
1474 * (and is done using urb->hcpriv). It also released all HCD locks;
1475 * the device driver won't cause problems if it frees, modifies,
1476 * or resubmits this URB.
1478 void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb, struct pt_regs *regs)
1482 // NOTE: a generic device/urb monitoring hook would go here.
1483 // hcd_monitor_hook(MONITOR_URB_FINISH, urb, dev)
1484 // It would catch exit/unlink paths for all urbs.
1486 /* lower level hcd code should use *_dma exclusively */
1487 if (hcd->self.controller->dma_mask) {
1488 if (usb_pipecontrol (urb->pipe)
1489 && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1490 dma_unmap_single (hcd->self.controller, urb->setup_dma,
1491 sizeof (struct usb_ctrlrequest),
1493 if (urb->transfer_buffer_length != 0
1494 && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1495 dma_unmap_single (hcd->self.controller,
1497 urb->transfer_buffer_length,
1498 usb_pipein (urb->pipe)
1503 /* pass ownership to the completion handler */
1504 urb->complete (urb, regs);
1507 EXPORT_SYMBOL (usb_hcd_giveback_urb);
1509 /*-------------------------------------------------------------------------*/
1512 * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
1513 * @irq: the IRQ being raised
1514 * @__hcd: pointer to the HCD whose IRQ is beinng signaled
1515 * @r: saved hardware registers
1517 * When registering a USB bus through the HCD framework code, use this
1518 * to handle interrupts. The PCI glue layer does so automatically; only
1519 * bus glue for non-PCI system busses will need to use this.
1521 irqreturn_t usb_hcd_irq (int irq, void *__hcd, struct pt_regs * r)
1523 struct usb_hcd *hcd = __hcd;
1524 int start = hcd->state;
1526 if (unlikely (hcd->state == USB_STATE_HALT)) /* irq sharing? */
1530 if (hcd->driver->irq (hcd, r) == IRQ_NONE)
1533 if (hcd->state != start && hcd->state == USB_STATE_HALT)
1537 EXPORT_SYMBOL (usb_hcd_irq);
1539 /*-------------------------------------------------------------------------*/
1541 static void hcd_panic (void *_hcd)
1543 struct usb_hcd *hcd = _hcd;
1544 struct usb_device *hub = hcd->self.root_hub;
1547 /* hc's root hub is removed later removed in hcd->stop() */
1548 hub->state = USB_STATE_NOTATTACHED;
1549 for (i = 0; i < hub->maxchild; i++) {
1550 if (hub->children [i])
1551 usb_disconnect (&hub->children [i]);
1556 * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
1557 * @hcd: pointer to the HCD representing the controller
1559 * This is called by bus glue to report a USB host controller that died
1560 * while operations may still have been pending. It's called automatically
1561 * by the PCI glue, so only glue for non-PCI busses should need to call it.
1563 void usb_hc_died (struct usb_hcd *hcd)
1565 dev_err (hcd->self.controller, "HC died; cleaning up\n");
1567 /* clean up old urbs and devices; needs a task context */
1568 INIT_WORK (&hcd->work, hcd_panic, hcd);
1569 (void) schedule_work (&hcd->work);
1571 EXPORT_SYMBOL (usb_hc_died);