2 * message.c - synchronous message handling
5 #include <linux/config.h>
6 #include <linux/pci.h> /* for scatterlist macros */
8 #include <linux/module.h>
9 #include <linux/slab.h>
10 #include <linux/init.h>
12 #include <linux/timer.h>
13 #include <linux/ctype.h>
14 #include <linux/device.h>
15 #include <asm/byteorder.h>
17 #include "hcd.h" /* for usbcore internals */
20 static void usb_api_blocking_completion(struct urb *urb, struct pt_regs *regs)
22 complete((struct completion *)urb->context);
26 static void timeout_kill(unsigned long data)
28 struct urb *urb = (struct urb *) data;
33 // Starts urb and waits for completion or timeout
34 // note that this call is NOT interruptible, while
35 // many device driver i/o requests should be interruptible
36 static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
38 struct completion done;
39 struct timer_list timer;
42 init_completion(&done);
44 urb->actual_length = 0;
45 status = usb_submit_urb(urb, GFP_NOIO);
50 timer.expires = jiffies + msecs_to_jiffies(timeout);
51 timer.data = (unsigned long)urb;
52 timer.function = timeout_kill;
53 /* grr. timeout _should_ include submit delays. */
56 wait_for_completion(&done);
58 /* note: HCDs return ETIMEDOUT for other reasons too */
59 if (status == -ECONNRESET) {
60 dev_dbg(&urb->dev->dev,
61 "%s timed out on ep%d%s len=%d/%d\n",
63 usb_pipeendpoint(urb->pipe),
64 usb_pipein(urb->pipe) ? "in" : "out",
66 urb->transfer_buffer_length
68 if (urb->actual_length > 0)
74 del_timer_sync(&timer);
78 *actual_length = urb->actual_length;
83 /*-------------------------------------------------------------------*/
84 // returns status (negative) or length (positive)
85 static int usb_internal_control_msg(struct usb_device *usb_dev,
87 struct usb_ctrlrequest *cmd,
88 void *data, int len, int timeout)
94 urb = usb_alloc_urb(0, GFP_NOIO);
98 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
99 len, usb_api_blocking_completion, NULL);
101 retv = usb_start_wait_urb(urb, timeout, &length);
109 * usb_control_msg - Builds a control urb, sends it off and waits for completion
110 * @dev: pointer to the usb device to send the message to
111 * @pipe: endpoint "pipe" to send the message to
112 * @request: USB message request value
113 * @requesttype: USB message request type value
114 * @value: USB message value
115 * @index: USB message index value
116 * @data: pointer to the data to send
117 * @size: length in bytes of the data to send
118 * @timeout: time in msecs to wait for the message to complete before
119 * timing out (if 0 the wait is forever)
120 * Context: !in_interrupt ()
122 * This function sends a simple control message to a specified endpoint
123 * and waits for the message to complete, or timeout.
125 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
127 * Don't use this function from within an interrupt context, like a
128 * bottom half handler. If you need an asynchronous message, or need to send
129 * a message from within interrupt context, use usb_submit_urb()
130 * If a thread in your driver uses this call, make sure your disconnect()
131 * method can wait for it to complete. Since you don't have a handle on
132 * the URB used, you can't cancel the request.
134 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
135 __u16 value, __u16 index, void *data, __u16 size, int timeout)
137 struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
143 dr->bRequestType= requesttype;
144 dr->bRequest = request;
145 dr->wValue = cpu_to_le16p(&value);
146 dr->wIndex = cpu_to_le16p(&index);
147 dr->wLength = cpu_to_le16p(&size);
149 //dbg("usb_control_msg");
151 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
160 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
161 * @usb_dev: pointer to the usb device to send the message to
162 * @pipe: endpoint "pipe" to send the message to
163 * @data: pointer to the data to send
164 * @len: length in bytes of the data to send
165 * @actual_length: pointer to a location to put the actual length transferred in bytes
166 * @timeout: time in msecs to wait for the message to complete before
167 * timing out (if 0 the wait is forever)
168 * Context: !in_interrupt ()
170 * This function sends a simple bulk message to a specified endpoint
171 * and waits for the message to complete, or timeout.
173 * If successful, it returns 0, otherwise a negative error number.
174 * The number of actual bytes transferred will be stored in the
175 * actual_length paramater.
177 * Don't use this function from within an interrupt context, like a
178 * bottom half handler. If you need an asynchronous message, or need to
179 * send a message from within interrupt context, use usb_submit_urb()
180 * If a thread in your driver uses this call, make sure your disconnect()
181 * method can wait for it to complete. Since you don't have a handle on
182 * the URB used, you can't cancel the request.
184 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT
185 * ioctl, users are forced to abuse this routine by using it to submit
186 * URBs for interrupt endpoints. We will take the liberty of creating
187 * an interrupt URB (with the default interval) if the target is an
188 * interrupt endpoint.
190 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
191 void *data, int len, int *actual_length, int timeout)
194 struct usb_host_endpoint *ep;
196 ep = (usb_pipein(pipe) ? usb_dev->ep_in : usb_dev->ep_out)
197 [usb_pipeendpoint(pipe)];
201 urb = usb_alloc_urb(0, GFP_KERNEL);
205 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
206 USB_ENDPOINT_XFER_INT) {
207 pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
208 usb_fill_int_urb(urb, usb_dev, pipe, data, len,
209 usb_api_blocking_completion, NULL,
212 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
213 usb_api_blocking_completion, NULL);
215 return usb_start_wait_urb(urb, timeout, actual_length);
218 /*-------------------------------------------------------------------*/
220 static void sg_clean (struct usb_sg_request *io)
223 while (io->entries--)
224 usb_free_urb (io->urbs [io->entries]);
228 if (io->dev->dev.dma_mask != NULL)
229 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
233 static void sg_complete (struct urb *urb, struct pt_regs *regs)
235 struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
237 spin_lock (&io->lock);
239 /* In 2.5 we require hcds' endpoint queues not to progress after fault
240 * reports, until the completion callback (this!) returns. That lets
241 * device driver code (like this routine) unlink queued urbs first,
242 * if it needs to, since the HC won't work on them at all. So it's
243 * not possible for page N+1 to overwrite page N, and so on.
245 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
246 * complete before the HCD can get requests away from hardware,
247 * though never during cleanup after a hard fault.
250 && (io->status != -ECONNRESET
251 || urb->status != -ECONNRESET)
252 && urb->actual_length) {
253 dev_err (io->dev->bus->controller,
254 "dev %s ep%d%s scatterlist error %d/%d\n",
256 usb_pipeendpoint (urb->pipe),
257 usb_pipein (urb->pipe) ? "in" : "out",
258 urb->status, io->status);
262 if (io->status == 0 && urb->status && urb->status != -ECONNRESET) {
263 int i, found, status;
265 io->status = urb->status;
267 /* the previous urbs, and this one, completed already.
268 * unlink pending urbs so they won't rx/tx bad data.
269 * careful: unlink can sometimes be synchronous...
271 spin_unlock (&io->lock);
272 for (i = 0, found = 0; i < io->entries; i++) {
273 if (!io->urbs [i] || !io->urbs [i]->dev)
276 status = usb_unlink_urb (io->urbs [i]);
277 if (status != -EINPROGRESS
280 dev_err (&io->dev->dev,
281 "%s, unlink --> %d\n",
282 __FUNCTION__, status);
283 } else if (urb == io->urbs [i])
286 spin_lock (&io->lock);
290 /* on the last completion, signal usb_sg_wait() */
291 io->bytes += urb->actual_length;
294 complete (&io->complete);
296 spin_unlock (&io->lock);
301 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
302 * @io: request block being initialized. until usb_sg_wait() returns,
303 * treat this as a pointer to an opaque block of memory,
304 * @dev: the usb device that will send or receive the data
305 * @pipe: endpoint "pipe" used to transfer the data
306 * @period: polling rate for interrupt endpoints, in frames or
307 * (for high speed endpoints) microframes; ignored for bulk
308 * @sg: scatterlist entries
309 * @nents: how many entries in the scatterlist
310 * @length: how many bytes to send from the scatterlist, or zero to
311 * send every byte identified in the list.
312 * @mem_flags: SLAB_* flags affecting memory allocations in this call
314 * Returns zero for success, else a negative errno value. This initializes a
315 * scatter/gather request, allocating resources such as I/O mappings and urb
316 * memory (except maybe memory used by USB controller drivers).
318 * The request must be issued using usb_sg_wait(), which waits for the I/O to
319 * complete (or to be canceled) and then cleans up all resources allocated by
322 * The request may be canceled with usb_sg_cancel(), either before or after
323 * usb_sg_wait() is called.
326 struct usb_sg_request *io,
327 struct usb_device *dev,
330 struct scatterlist *sg,
340 if (!io || !dev || !sg
341 || usb_pipecontrol (pipe)
342 || usb_pipeisoc (pipe)
346 spin_lock_init (&io->lock);
352 /* not all host controllers use DMA (like the mainstream pci ones);
353 * they can use PIO (sl811) or be software over another transport.
355 dma = (dev->dev.dma_mask != NULL);
357 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
361 /* initialize all the urbs we'll use */
362 if (io->entries <= 0)
365 io->count = io->entries;
366 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
370 urb_flags = URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
371 if (usb_pipein (pipe))
372 urb_flags |= URB_SHORT_NOT_OK;
374 for (i = 0; i < io->entries; i++) {
377 io->urbs [i] = usb_alloc_urb (0, mem_flags);
383 io->urbs [i]->dev = NULL;
384 io->urbs [i]->pipe = pipe;
385 io->urbs [i]->interval = period;
386 io->urbs [i]->transfer_flags = urb_flags;
388 io->urbs [i]->complete = sg_complete;
389 io->urbs [i]->context = io;
390 io->urbs [i]->status = -EINPROGRESS;
391 io->urbs [i]->actual_length = 0;
394 /* hc may use _only_ transfer_dma */
395 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
396 len = sg_dma_len (sg + i);
398 /* hc may use _only_ transfer_buffer */
399 io->urbs [i]->transfer_buffer =
400 page_address (sg [i].page) + sg [i].offset;
405 len = min_t (unsigned, len, length);
410 io->urbs [i]->transfer_buffer_length = len;
412 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
414 /* transaction state */
417 init_completion (&io->complete);
427 * usb_sg_wait - synchronously execute scatter/gather request
428 * @io: request block handle, as initialized with usb_sg_init().
429 * some fields become accessible when this call returns.
430 * Context: !in_interrupt ()
432 * This function blocks until the specified I/O operation completes. It
433 * leverages the grouping of the related I/O requests to get good transfer
434 * rates, by queueing the requests. At higher speeds, such queuing can
435 * significantly improve USB throughput.
437 * There are three kinds of completion for this function.
438 * (1) success, where io->status is zero. The number of io->bytes
439 * transferred is as requested.
440 * (2) error, where io->status is a negative errno value. The number
441 * of io->bytes transferred before the error is usually less
442 * than requested, and can be nonzero.
443 * (3) cancellation, a type of error with status -ECONNRESET that
444 * is initiated by usb_sg_cancel().
446 * When this function returns, all memory allocated through usb_sg_init() or
447 * this call will have been freed. The request block parameter may still be
448 * passed to usb_sg_cancel(), or it may be freed. It could also be
449 * reinitialized and then reused.
451 * Data Transfer Rates:
453 * Bulk transfers are valid for full or high speed endpoints.
454 * The best full speed data rate is 19 packets of 64 bytes each
455 * per frame, or 1216 bytes per millisecond.
456 * The best high speed data rate is 13 packets of 512 bytes each
457 * per microframe, or 52 KBytes per millisecond.
459 * The reason to use interrupt transfers through this API would most likely
460 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
461 * could be transferred. That capability is less useful for low or full
462 * speed interrupt endpoints, which allow at most one packet per millisecond,
463 * of at most 8 or 64 bytes (respectively).
465 void usb_sg_wait (struct usb_sg_request *io)
467 int i, entries = io->entries;
469 /* queue the urbs. */
470 spin_lock_irq (&io->lock);
471 for (i = 0; i < entries && !io->status; i++) {
474 io->urbs [i]->dev = io->dev;
475 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
477 /* after we submit, let completions or cancelations fire;
478 * we handshake using io->status.
480 spin_unlock_irq (&io->lock);
482 /* maybe we retrying will recover */
483 case -ENXIO: // hc didn't queue this one
486 io->urbs[i]->dev = NULL;
492 /* no error? continue immediately.
494 * NOTE: to work better with UHCI (4K I/O buffer may
495 * need 3K of TDs) it may be good to limit how many
496 * URBs are queued at once; N milliseconds?
502 /* fail any uncompleted urbs */
504 io->urbs [i]->dev = NULL;
505 io->urbs [i]->status = retval;
506 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
507 __FUNCTION__, retval);
510 spin_lock_irq (&io->lock);
511 if (retval && (io->status == 0 || io->status == -ECONNRESET))
514 io->count -= entries - i;
516 complete (&io->complete);
517 spin_unlock_irq (&io->lock);
519 /* OK, yes, this could be packaged as non-blocking.
520 * So could the submit loop above ... but it's easier to
521 * solve neither problem than to solve both!
523 wait_for_completion (&io->complete);
529 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
530 * @io: request block, initialized with usb_sg_init()
532 * This stops a request after it has been started by usb_sg_wait().
533 * It can also prevents one initialized by usb_sg_init() from starting,
534 * so that call just frees resources allocated to the request.
536 void usb_sg_cancel (struct usb_sg_request *io)
540 spin_lock_irqsave (&io->lock, flags);
542 /* shut everything down, if it didn't already */
546 io->status = -ECONNRESET;
547 spin_unlock (&io->lock);
548 for (i = 0; i < io->entries; i++) {
551 if (!io->urbs [i]->dev)
553 retval = usb_unlink_urb (io->urbs [i]);
554 if (retval != -EINPROGRESS && retval != -EBUSY)
555 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
556 __FUNCTION__, retval);
558 spin_lock (&io->lock);
560 spin_unlock_irqrestore (&io->lock, flags);
563 /*-------------------------------------------------------------------*/
566 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
567 * @dev: the device whose descriptor is being retrieved
568 * @type: the descriptor type (USB_DT_*)
569 * @index: the number of the descriptor
570 * @buf: where to put the descriptor
571 * @size: how big is "buf"?
572 * Context: !in_interrupt ()
574 * Gets a USB descriptor. Convenience functions exist to simplify
575 * getting some types of descriptors. Use
576 * usb_get_string() or usb_string() for USB_DT_STRING.
577 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
578 * are part of the device structure.
579 * In addition to a number of USB-standard descriptors, some
580 * devices also use class-specific or vendor-specific descriptors.
582 * This call is synchronous, and may not be used in an interrupt context.
584 * Returns the number of bytes received on success, or else the status code
585 * returned by the underlying usb_control_msg() call.
587 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
592 memset(buf,0,size); // Make sure we parse really received data
594 for (i = 0; i < 3; ++i) {
595 /* retry on length 0 or stall; some devices are flakey */
596 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
597 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
598 (type << 8) + index, 0, buf, size,
599 USB_CTRL_GET_TIMEOUT);
600 if (result == 0 || result == -EPIPE)
602 if (result > 1 && ((u8 *)buf)[1] != type) {
612 * usb_get_string - gets a string descriptor
613 * @dev: the device whose string descriptor is being retrieved
614 * @langid: code for language chosen (from string descriptor zero)
615 * @index: the number of the descriptor
616 * @buf: where to put the string
617 * @size: how big is "buf"?
618 * Context: !in_interrupt ()
620 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
621 * in little-endian byte order).
622 * The usb_string() function will often be a convenient way to turn
623 * these strings into kernel-printable form.
625 * Strings may be referenced in device, configuration, interface, or other
626 * descriptors, and could also be used in vendor-specific ways.
628 * This call is synchronous, and may not be used in an interrupt context.
630 * Returns the number of bytes received on success, or else the status code
631 * returned by the underlying usb_control_msg() call.
633 int usb_get_string(struct usb_device *dev, unsigned short langid,
634 unsigned char index, void *buf, int size)
639 for (i = 0; i < 3; ++i) {
640 /* retry on length 0 or stall; some devices are flakey */
641 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
642 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
643 (USB_DT_STRING << 8) + index, langid, buf, size,
644 USB_CTRL_GET_TIMEOUT);
645 if (!(result == 0 || result == -EPIPE))
651 static void usb_try_string_workarounds(unsigned char *buf, int *length)
653 int newlength, oldlength = *length;
655 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
656 if (!isprint(buf[newlength]) || buf[newlength + 1])
665 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
666 unsigned int index, unsigned char *buf)
670 /* Try to read the string descriptor by asking for the maximum
671 * possible number of bytes */
672 rc = usb_get_string(dev, langid, index, buf, 255);
674 /* If that failed try to read the descriptor length, then
675 * ask for just that many bytes */
677 rc = usb_get_string(dev, langid, index, buf, 2);
679 rc = usb_get_string(dev, langid, index, buf, buf[0]);
683 if (!buf[0] && !buf[1])
684 usb_try_string_workarounds(buf, &rc);
686 /* There might be extra junk at the end of the descriptor */
690 rc = rc - (rc & 1); /* force a multiple of two */
694 rc = (rc < 0 ? rc : -EINVAL);
700 * usb_string - returns ISO 8859-1 version of a string descriptor
701 * @dev: the device whose string descriptor is being retrieved
702 * @index: the number of the descriptor
703 * @buf: where to put the string
704 * @size: how big is "buf"?
705 * Context: !in_interrupt ()
707 * This converts the UTF-16LE encoded strings returned by devices, from
708 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
709 * that are more usable in most kernel contexts. Note that all characters
710 * in the chosen descriptor that can't be encoded using ISO-8859-1
711 * are converted to the question mark ("?") character, and this function
712 * chooses strings in the first language supported by the device.
714 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
715 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
716 * and is appropriate for use many uses of English and several other
717 * Western European languages. (But it doesn't include the "Euro" symbol.)
719 * This call is synchronous, and may not be used in an interrupt context.
721 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
723 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
729 if (dev->state == USB_STATE_SUSPENDED)
730 return -EHOSTUNREACH;
731 if (size <= 0 || !buf || !index)
734 tbuf = kmalloc(256, GFP_KERNEL);
738 /* get langid for strings if it's not yet known */
739 if (!dev->have_langid) {
740 err = usb_string_sub(dev, 0, 0, tbuf);
743 "string descriptor 0 read error: %d\n",
746 } else if (err < 4) {
747 dev_err (&dev->dev, "string descriptor 0 too short\n");
751 dev->have_langid = -1;
752 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
753 /* always use the first langid listed */
754 dev_dbg (&dev->dev, "default language 0x%04x\n",
759 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
763 size--; /* leave room for trailing NULL char in output buffer */
764 for (idx = 0, u = 2; u < err; u += 2) {
767 if (tbuf[u+1]) /* high byte */
768 buf[idx++] = '?'; /* non ISO-8859-1 character */
770 buf[idx++] = tbuf[u];
775 if (tbuf[1] != USB_DT_STRING)
776 dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
784 * usb_cache_string - read a string descriptor and cache it for later use
785 * @udev: the device whose string descriptor is being read
786 * @index: the descriptor index
788 * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
789 * or NULL if the index is 0 or the string could not be read.
791 char *usb_cache_string(struct usb_device *udev, int index)
794 char *smallbuf = NULL;
797 if (index > 0 && (buf = kmalloc(256, GFP_KERNEL)) != NULL) {
798 if ((len = usb_string(udev, index, buf, 256)) > 0) {
799 if ((smallbuf = kmalloc(++len, GFP_KERNEL)) == NULL)
801 memcpy(smallbuf, buf, len);
809 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
810 * @dev: the device whose device descriptor is being updated
811 * @size: how much of the descriptor to read
812 * Context: !in_interrupt ()
814 * Updates the copy of the device descriptor stored in the device structure,
815 * which dedicates space for this purpose. Note that several fields are
816 * converted to the host CPU's byte order: the USB version (bcdUSB), and
817 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
818 * That lets device drivers compare against non-byteswapped constants.
820 * Not exported, only for use by the core. If drivers really want to read
821 * the device descriptor directly, they can call usb_get_descriptor() with
822 * type = USB_DT_DEVICE and index = 0.
824 * This call is synchronous, and may not be used in an interrupt context.
826 * Returns the number of bytes received on success, or else the status code
827 * returned by the underlying usb_control_msg() call.
829 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
831 struct usb_device_descriptor *desc;
834 if (size > sizeof(*desc))
836 desc = kmalloc(sizeof(*desc), GFP_NOIO);
840 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
842 memcpy(&dev->descriptor, desc, size);
848 * usb_get_status - issues a GET_STATUS call
849 * @dev: the device whose status is being checked
850 * @type: USB_RECIP_*; for device, interface, or endpoint
851 * @target: zero (for device), else interface or endpoint number
852 * @data: pointer to two bytes of bitmap data
853 * Context: !in_interrupt ()
855 * Returns device, interface, or endpoint status. Normally only of
856 * interest to see if the device is self powered, or has enabled the
857 * remote wakeup facility; or whether a bulk or interrupt endpoint
858 * is halted ("stalled").
860 * Bits in these status bitmaps are set using the SET_FEATURE request,
861 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
862 * function should be used to clear halt ("stall") status.
864 * This call is synchronous, and may not be used in an interrupt context.
866 * Returns the number of bytes received on success, or else the status code
867 * returned by the underlying usb_control_msg() call.
869 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
872 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
877 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
878 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
879 sizeof(*status), USB_CTRL_GET_TIMEOUT);
881 *(u16 *)data = *status;
887 * usb_clear_halt - tells device to clear endpoint halt/stall condition
888 * @dev: device whose endpoint is halted
889 * @pipe: endpoint "pipe" being cleared
890 * Context: !in_interrupt ()
892 * This is used to clear halt conditions for bulk and interrupt endpoints,
893 * as reported by URB completion status. Endpoints that are halted are
894 * sometimes referred to as being "stalled". Such endpoints are unable
895 * to transmit or receive data until the halt status is cleared. Any URBs
896 * queued for such an endpoint should normally be unlinked by the driver
897 * before clearing the halt condition, as described in sections 5.7.5
898 * and 5.8.5 of the USB 2.0 spec.
900 * Note that control and isochronous endpoints don't halt, although control
901 * endpoints report "protocol stall" (for unsupported requests) using the
902 * same status code used to report a true stall.
904 * This call is synchronous, and may not be used in an interrupt context.
906 * Returns zero on success, or else the status code returned by the
907 * underlying usb_control_msg() call.
909 int usb_clear_halt(struct usb_device *dev, int pipe)
912 int endp = usb_pipeendpoint(pipe);
914 if (usb_pipein (pipe))
917 /* we don't care if it wasn't halted first. in fact some devices
918 * (like some ibmcam model 1 units) seem to expect hosts to make
919 * this request for iso endpoints, which can't halt!
921 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
922 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
923 USB_ENDPOINT_HALT, endp, NULL, 0,
924 USB_CTRL_SET_TIMEOUT);
926 /* don't un-halt or force to DATA0 except on success */
930 /* NOTE: seems like Microsoft and Apple don't bother verifying
931 * the clear "took", so some devices could lock up if you check...
932 * such as the Hagiwara FlashGate DUAL. So we won't bother.
934 * NOTE: make sure the logic here doesn't diverge much from
935 * the copy in usb-storage, for as long as we need two copies.
938 /* toggle was reset by the clear */
939 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
945 * usb_disable_endpoint -- Disable an endpoint by address
946 * @dev: the device whose endpoint is being disabled
947 * @epaddr: the endpoint's address. Endpoint number for output,
948 * endpoint number + USB_DIR_IN for input
950 * Deallocates hcd/hardware state for this endpoint ... and nukes all
953 * If the HCD hasn't registered a disable() function, this sets the
954 * endpoint's maxpacket size to 0 to prevent further submissions.
956 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
958 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
959 struct usb_host_endpoint *ep;
964 if (usb_endpoint_out(epaddr)) {
965 ep = dev->ep_out[epnum];
966 dev->ep_out[epnum] = NULL;
968 ep = dev->ep_in[epnum];
969 dev->ep_in[epnum] = NULL;
971 if (ep && dev->bus && dev->bus->op && dev->bus->op->disable)
972 dev->bus->op->disable(dev, ep);
976 * usb_disable_interface -- Disable all endpoints for an interface
977 * @dev: the device whose interface is being disabled
978 * @intf: pointer to the interface descriptor
980 * Disables all the endpoints for the interface's current altsetting.
982 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
984 struct usb_host_interface *alt = intf->cur_altsetting;
987 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
988 usb_disable_endpoint(dev,
989 alt->endpoint[i].desc.bEndpointAddress);
994 * usb_disable_device - Disable all the endpoints for a USB device
995 * @dev: the device whose endpoints are being disabled
996 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
998 * Disables all the device's endpoints, potentially including endpoint 0.
999 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1000 * pending urbs) and usbcore state for the interfaces, so that usbcore
1001 * must usb_set_configuration() before any interfaces could be used.
1003 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1007 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
1008 skip_ep0 ? "non-ep0" : "all");
1009 for (i = skip_ep0; i < 16; ++i) {
1010 usb_disable_endpoint(dev, i);
1011 usb_disable_endpoint(dev, i + USB_DIR_IN);
1013 dev->toggle[0] = dev->toggle[1] = 0;
1015 /* getting rid of interfaces will disconnect
1016 * any drivers bound to them (a key side effect)
1018 if (dev->actconfig) {
1019 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1020 struct usb_interface *interface;
1022 /* remove this interface if it has been registered */
1023 interface = dev->actconfig->interface[i];
1024 if (!device_is_registered(&interface->dev))
1026 dev_dbg (&dev->dev, "unregistering interface %s\n",
1027 interface->dev.bus_id);
1028 usb_remove_sysfs_intf_files(interface);
1029 device_del (&interface->dev);
1032 /* Now that the interfaces are unbound, nobody should
1033 * try to access them.
1035 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1036 put_device (&dev->actconfig->interface[i]->dev);
1037 dev->actconfig->interface[i] = NULL;
1039 dev->actconfig = NULL;
1040 if (dev->state == USB_STATE_CONFIGURED)
1041 usb_set_device_state(dev, USB_STATE_ADDRESS);
1047 * usb_enable_endpoint - Enable an endpoint for USB communications
1048 * @dev: the device whose interface is being enabled
1051 * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
1052 * For control endpoints, both the input and output sides are handled.
1055 usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
1057 unsigned int epaddr = ep->desc.bEndpointAddress;
1058 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1061 is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1062 == USB_ENDPOINT_XFER_CONTROL);
1063 if (usb_endpoint_out(epaddr) || is_control) {
1064 usb_settoggle(dev, epnum, 1, 0);
1065 dev->ep_out[epnum] = ep;
1067 if (!usb_endpoint_out(epaddr) || is_control) {
1068 usb_settoggle(dev, epnum, 0, 0);
1069 dev->ep_in[epnum] = ep;
1074 * usb_enable_interface - Enable all the endpoints for an interface
1075 * @dev: the device whose interface is being enabled
1076 * @intf: pointer to the interface descriptor
1078 * Enables all the endpoints for the interface's current altsetting.
1080 static void usb_enable_interface(struct usb_device *dev,
1081 struct usb_interface *intf)
1083 struct usb_host_interface *alt = intf->cur_altsetting;
1086 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1087 usb_enable_endpoint(dev, &alt->endpoint[i]);
1091 * usb_set_interface - Makes a particular alternate setting be current
1092 * @dev: the device whose interface is being updated
1093 * @interface: the interface being updated
1094 * @alternate: the setting being chosen.
1095 * Context: !in_interrupt ()
1097 * This is used to enable data transfers on interfaces that may not
1098 * be enabled by default. Not all devices support such configurability.
1099 * Only the driver bound to an interface may change its setting.
1101 * Within any given configuration, each interface may have several
1102 * alternative settings. These are often used to control levels of
1103 * bandwidth consumption. For example, the default setting for a high
1104 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1105 * while interrupt transfers of up to 3KBytes per microframe are legal.
1106 * Also, isochronous endpoints may never be part of an
1107 * interface's default setting. To access such bandwidth, alternate
1108 * interface settings must be made current.
1110 * Note that in the Linux USB subsystem, bandwidth associated with
1111 * an endpoint in a given alternate setting is not reserved until an URB
1112 * is submitted that needs that bandwidth. Some other operating systems
1113 * allocate bandwidth early, when a configuration is chosen.
1115 * This call is synchronous, and may not be used in an interrupt context.
1116 * Also, drivers must not change altsettings while urbs are scheduled for
1117 * endpoints in that interface; all such urbs must first be completed
1118 * (perhaps forced by unlinking).
1120 * Returns zero on success, or else the status code returned by the
1121 * underlying usb_control_msg() call.
1123 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1125 struct usb_interface *iface;
1126 struct usb_host_interface *alt;
1130 if (dev->state == USB_STATE_SUSPENDED)
1131 return -EHOSTUNREACH;
1133 iface = usb_ifnum_to_if(dev, interface);
1135 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1140 alt = usb_altnum_to_altsetting(iface, alternate);
1142 warn("selecting invalid altsetting %d", alternate);
1146 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1147 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1148 alternate, interface, NULL, 0, 5000);
1150 /* 9.4.10 says devices don't need this and are free to STALL the
1151 * request if the interface only has one alternate setting.
1153 if (ret == -EPIPE && iface->num_altsetting == 1) {
1155 "manual set_interface for iface %d, alt %d\n",
1156 interface, alternate);
1161 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1162 * when they implement async or easily-killable versions of this or
1163 * other "should-be-internal" functions (like clear_halt).
1164 * should hcd+usbcore postprocess control requests?
1167 /* prevent submissions using previous endpoint settings */
1168 if (device_is_registered(&iface->dev))
1169 usb_remove_sysfs_intf_files(iface);
1170 usb_disable_interface(dev, iface);
1172 iface->cur_altsetting = alt;
1174 /* If the interface only has one altsetting and the device didn't
1175 * accept the request, we attempt to carry out the equivalent action
1176 * by manually clearing the HALT feature for each endpoint in the
1182 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1183 unsigned int epaddr =
1184 alt->endpoint[i].desc.bEndpointAddress;
1186 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
1187 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1189 usb_clear_halt(dev, pipe);
1193 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1196 * Despite EP0 is always present in all interfaces/AS, the list of
1197 * endpoints from the descriptor does not contain EP0. Due to its
1198 * omnipresence one might expect EP0 being considered "affected" by
1199 * any SetInterface request and hence assume toggles need to be reset.
1200 * However, EP0 toggles are re-synced for every individual transfer
1201 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1202 * (Likewise, EP0 never "halts" on well designed devices.)
1204 usb_enable_interface(dev, iface);
1205 if (device_is_registered(&iface->dev))
1206 usb_create_sysfs_intf_files(iface);
1212 * usb_reset_configuration - lightweight device reset
1213 * @dev: the device whose configuration is being reset
1215 * This issues a standard SET_CONFIGURATION request to the device using
1216 * the current configuration. The effect is to reset most USB-related
1217 * state in the device, including interface altsettings (reset to zero),
1218 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1219 * endpoints). Other usbcore state is unchanged, including bindings of
1220 * usb device drivers to interfaces.
1222 * Because this affects multiple interfaces, avoid using this with composite
1223 * (multi-interface) devices. Instead, the driver for each interface may
1224 * use usb_set_interface() on the interfaces it claims. Be careful though;
1225 * some devices don't support the SET_INTERFACE request, and others won't
1226 * reset all the interface state (notably data toggles). Resetting the whole
1227 * configuration would affect other drivers' interfaces.
1229 * The caller must own the device lock.
1231 * Returns zero on success, else a negative error code.
1233 int usb_reset_configuration(struct usb_device *dev)
1236 struct usb_host_config *config;
1238 if (dev->state == USB_STATE_SUSPENDED)
1239 return -EHOSTUNREACH;
1241 /* caller must have locked the device and must own
1242 * the usb bus readlock (so driver bindings are stable);
1243 * calls during probe() are fine
1246 for (i = 1; i < 16; ++i) {
1247 usb_disable_endpoint(dev, i);
1248 usb_disable_endpoint(dev, i + USB_DIR_IN);
1251 config = dev->actconfig;
1252 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1253 USB_REQ_SET_CONFIGURATION, 0,
1254 config->desc.bConfigurationValue, 0,
1255 NULL, 0, USB_CTRL_SET_TIMEOUT);
1259 dev->toggle[0] = dev->toggle[1] = 0;
1261 /* re-init hc/hcd interface/endpoint state */
1262 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1263 struct usb_interface *intf = config->interface[i];
1264 struct usb_host_interface *alt;
1266 if (device_is_registered(&intf->dev))
1267 usb_remove_sysfs_intf_files(intf);
1268 alt = usb_altnum_to_altsetting(intf, 0);
1270 /* No altsetting 0? We'll assume the first altsetting.
1271 * We could use a GetInterface call, but if a device is
1272 * so non-compliant that it doesn't have altsetting 0
1273 * then I wouldn't trust its reply anyway.
1276 alt = &intf->altsetting[0];
1278 intf->cur_altsetting = alt;
1279 usb_enable_interface(dev, intf);
1280 if (device_is_registered(&intf->dev))
1281 usb_create_sysfs_intf_files(intf);
1286 static void release_interface(struct device *dev)
1288 struct usb_interface *intf = to_usb_interface(dev);
1289 struct usb_interface_cache *intfc =
1290 altsetting_to_usb_interface_cache(intf->altsetting);
1292 kref_put(&intfc->ref, usb_release_interface_cache);
1297 * usb_set_configuration - Makes a particular device setting be current
1298 * @dev: the device whose configuration is being updated
1299 * @configuration: the configuration being chosen.
1300 * Context: !in_interrupt(), caller owns the device lock
1302 * This is used to enable non-default device modes. Not all devices
1303 * use this kind of configurability; many devices only have one
1306 * USB device configurations may affect Linux interoperability,
1307 * power consumption and the functionality available. For example,
1308 * the default configuration is limited to using 100mA of bus power,
1309 * so that when certain device functionality requires more power,
1310 * and the device is bus powered, that functionality should be in some
1311 * non-default device configuration. Other device modes may also be
1312 * reflected as configuration options, such as whether two ISDN
1313 * channels are available independently; and choosing between open
1314 * standard device protocols (like CDC) or proprietary ones.
1316 * Note that USB has an additional level of device configurability,
1317 * associated with interfaces. That configurability is accessed using
1318 * usb_set_interface().
1320 * This call is synchronous. The calling context must be able to sleep,
1321 * must own the device lock, and must not hold the driver model's USB
1322 * bus rwsem; usb device driver probe() methods cannot use this routine.
1324 * Returns zero on success, or else the status code returned by the
1325 * underlying call that failed. On successful completion, each interface
1326 * in the original device configuration has been destroyed, and each one
1327 * in the new configuration has been probed by all relevant usb device
1328 * drivers currently known to the kernel.
1330 int usb_set_configuration(struct usb_device *dev, int configuration)
1333 struct usb_host_config *cp = NULL;
1334 struct usb_interface **new_interfaces = NULL;
1337 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1338 if (dev->config[i].desc.bConfigurationValue == configuration) {
1339 cp = &dev->config[i];
1343 if ((!cp && configuration != 0))
1346 /* The USB spec says configuration 0 means unconfigured.
1347 * But if a device includes a configuration numbered 0,
1348 * we will accept it as a correctly configured state.
1350 if (cp && configuration == 0)
1351 dev_warn(&dev->dev, "config 0 descriptor??\n");
1353 if (dev->state == USB_STATE_SUSPENDED)
1354 return -EHOSTUNREACH;
1356 /* Allocate memory for new interfaces before doing anything else,
1357 * so that if we run out then nothing will have changed. */
1360 nintf = cp->desc.bNumInterfaces;
1361 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1363 if (!new_interfaces) {
1364 dev_err(&dev->dev, "Out of memory");
1368 for (; n < nintf; ++n) {
1369 new_interfaces[n] = kzalloc(
1370 sizeof(struct usb_interface),
1372 if (!new_interfaces[n]) {
1373 dev_err(&dev->dev, "Out of memory");
1377 kfree(new_interfaces[n]);
1378 kfree(new_interfaces);
1384 /* if it's already configured, clear out old state first.
1385 * getting rid of old interfaces means unbinding their drivers.
1387 if (dev->state != USB_STATE_ADDRESS)
1388 usb_disable_device (dev, 1); // Skip ep0
1390 i = dev->bus_mA - cp->desc.bMaxPower * 2;
1392 dev_warn(&dev->dev, "new config #%d exceeds power "
1396 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1397 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1398 NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0)
1399 goto free_interfaces;
1401 dev->actconfig = cp;
1403 usb_set_device_state(dev, USB_STATE_ADDRESS);
1405 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1407 /* Initialize the new interface structures and the
1408 * hc/hcd/usbcore interface/endpoint state.
1410 for (i = 0; i < nintf; ++i) {
1411 struct usb_interface_cache *intfc;
1412 struct usb_interface *intf;
1413 struct usb_host_interface *alt;
1415 cp->interface[i] = intf = new_interfaces[i];
1416 intfc = cp->intf_cache[i];
1417 intf->altsetting = intfc->altsetting;
1418 intf->num_altsetting = intfc->num_altsetting;
1419 kref_get(&intfc->ref);
1421 alt = usb_altnum_to_altsetting(intf, 0);
1423 /* No altsetting 0? We'll assume the first altsetting.
1424 * We could use a GetInterface call, but if a device is
1425 * so non-compliant that it doesn't have altsetting 0
1426 * then I wouldn't trust its reply anyway.
1429 alt = &intf->altsetting[0];
1431 intf->cur_altsetting = alt;
1432 usb_enable_interface(dev, intf);
1433 intf->dev.parent = &dev->dev;
1434 intf->dev.driver = NULL;
1435 intf->dev.bus = &usb_bus_type;
1436 intf->dev.dma_mask = dev->dev.dma_mask;
1437 intf->dev.release = release_interface;
1438 device_initialize (&intf->dev);
1439 mark_quiesced(intf);
1440 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1441 dev->bus->busnum, dev->devpath,
1443 alt->desc.bInterfaceNumber);
1445 kfree(new_interfaces);
1447 if (cp->string == NULL)
1448 cp->string = usb_cache_string(dev,
1449 cp->desc.iConfiguration);
1451 /* Now that all the interfaces are set up, register them
1452 * to trigger binding of drivers to interfaces. probe()
1453 * routines may install different altsettings and may
1454 * claim() any interfaces not yet bound. Many class drivers
1455 * need that: CDC, audio, video, etc.
1457 for (i = 0; i < nintf; ++i) {
1458 struct usb_interface *intf = cp->interface[i];
1461 "adding %s (config #%d, interface %d)\n",
1462 intf->dev.bus_id, configuration,
1463 intf->cur_altsetting->desc.bInterfaceNumber);
1464 ret = device_add (&intf->dev);
1467 "device_add(%s) --> %d\n",
1472 usb_create_sysfs_intf_files (intf);
1479 // synchronous request completion model
1480 EXPORT_SYMBOL(usb_control_msg);
1481 EXPORT_SYMBOL(usb_bulk_msg);
1483 EXPORT_SYMBOL(usb_sg_init);
1484 EXPORT_SYMBOL(usb_sg_cancel);
1485 EXPORT_SYMBOL(usb_sg_wait);
1487 // synchronous control message convenience routines
1488 EXPORT_SYMBOL(usb_get_descriptor);
1489 EXPORT_SYMBOL(usb_get_status);
1490 EXPORT_SYMBOL(usb_get_string);
1491 EXPORT_SYMBOL(usb_string);
1493 // synchronous calls that also maintain usbcore state
1494 EXPORT_SYMBOL(usb_clear_halt);
1495 EXPORT_SYMBOL(usb_reset_configuration);
1496 EXPORT_SYMBOL(usb_set_interface);