2 * message.c - synchronous message handling
5 #include <linux/config.h>
7 #ifdef CONFIG_USB_DEBUG
13 #include <linux/pci.h> /* for scatterlist macros */
14 #include <linux/usb.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/init.h>
19 #include <linux/timer.h>
20 #include <linux/ctype.h>
21 #include <linux/device.h>
22 #include <asm/byteorder.h>
24 #include "hcd.h" /* for usbcore internals */
27 static void usb_api_blocking_completion(struct urb *urb, struct pt_regs *regs)
29 complete((struct completion *)urb->context);
33 static void timeout_kill(unsigned long data)
35 struct urb *urb = (struct urb *) data;
40 // Starts urb and waits for completion or timeout
41 // note that this call is NOT interruptible, while
42 // many device driver i/o requests should be interruptible
43 static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
45 struct completion done;
46 struct timer_list timer;
49 init_completion(&done);
51 urb->actual_length = 0;
52 status = usb_submit_urb(urb, GFP_NOIO);
57 timer.expires = jiffies + msecs_to_jiffies(timeout);
58 timer.data = (unsigned long)urb;
59 timer.function = timeout_kill;
60 /* grr. timeout _should_ include submit delays. */
63 wait_for_completion(&done);
65 /* note: HCDs return ETIMEDOUT for other reasons too */
66 if (status == -ECONNRESET) {
67 dev_dbg(&urb->dev->dev,
68 "%s timed out on ep%d%s len=%d/%d\n",
70 usb_pipeendpoint(urb->pipe),
71 usb_pipein(urb->pipe) ? "in" : "out",
73 urb->transfer_buffer_length
75 if (urb->actual_length > 0)
81 del_timer_sync(&timer);
85 *actual_length = urb->actual_length;
90 /*-------------------------------------------------------------------*/
91 // returns status (negative) or length (positive)
92 static int usb_internal_control_msg(struct usb_device *usb_dev,
94 struct usb_ctrlrequest *cmd,
95 void *data, int len, int timeout)
101 urb = usb_alloc_urb(0, GFP_NOIO);
105 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
106 len, usb_api_blocking_completion, NULL);
108 retv = usb_start_wait_urb(urb, timeout, &length);
116 * usb_control_msg - Builds a control urb, sends it off and waits for completion
117 * @dev: pointer to the usb device to send the message to
118 * @pipe: endpoint "pipe" to send the message to
119 * @request: USB message request value
120 * @requesttype: USB message request type value
121 * @value: USB message value
122 * @index: USB message index value
123 * @data: pointer to the data to send
124 * @size: length in bytes of the data to send
125 * @timeout: time in msecs to wait for the message to complete before
126 * timing out (if 0 the wait is forever)
127 * Context: !in_interrupt ()
129 * This function sends a simple control message to a specified endpoint
130 * and waits for the message to complete, or timeout.
132 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
134 * Don't use this function from within an interrupt context, like a
135 * bottom half handler. If you need an asynchronous message, or need to send
136 * a message from within interrupt context, use usb_submit_urb()
137 * If a thread in your driver uses this call, make sure your disconnect()
138 * method can wait for it to complete. Since you don't have a handle on
139 * the URB used, you can't cancel the request.
141 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
142 __u16 value, __u16 index, void *data, __u16 size, int timeout)
144 struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
150 dr->bRequestType= requesttype;
151 dr->bRequest = request;
152 dr->wValue = cpu_to_le16p(&value);
153 dr->wIndex = cpu_to_le16p(&index);
154 dr->wLength = cpu_to_le16p(&size);
156 //dbg("usb_control_msg");
158 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
167 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
168 * @usb_dev: pointer to the usb device to send the message to
169 * @pipe: endpoint "pipe" to send the message to
170 * @data: pointer to the data to send
171 * @len: length in bytes of the data to send
172 * @actual_length: pointer to a location to put the actual length transferred in bytes
173 * @timeout: time in msecs to wait for the message to complete before
174 * timing out (if 0 the wait is forever)
175 * Context: !in_interrupt ()
177 * This function sends a simple bulk message to a specified endpoint
178 * and waits for the message to complete, or timeout.
180 * If successful, it returns 0, otherwise a negative error number.
181 * The number of actual bytes transferred will be stored in the
182 * actual_length paramater.
184 * Don't use this function from within an interrupt context, like a
185 * bottom half handler. If you need an asynchronous message, or need to
186 * send a message from within interrupt context, use usb_submit_urb()
187 * If a thread in your driver uses this call, make sure your disconnect()
188 * method can wait for it to complete. Since you don't have a handle on
189 * the URB used, you can't cancel the request.
191 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT
192 * ioctl, users are forced to abuse this routine by using it to submit
193 * URBs for interrupt endpoints. We will take the liberty of creating
194 * an interrupt URB (with the default interval) if the target is an
195 * interrupt endpoint.
197 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
198 void *data, int len, int *actual_length, int timeout)
201 struct usb_host_endpoint *ep;
203 ep = (usb_pipein(pipe) ? usb_dev->ep_in : usb_dev->ep_out)
204 [usb_pipeendpoint(pipe)];
208 urb = usb_alloc_urb(0, GFP_KERNEL);
212 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
213 USB_ENDPOINT_XFER_INT) {
214 pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
215 usb_fill_int_urb(urb, usb_dev, pipe, data, len,
216 usb_api_blocking_completion, NULL,
219 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
220 usb_api_blocking_completion, NULL);
222 return usb_start_wait_urb(urb, timeout, actual_length);
225 /*-------------------------------------------------------------------*/
227 static void sg_clean (struct usb_sg_request *io)
230 while (io->entries--)
231 usb_free_urb (io->urbs [io->entries]);
235 if (io->dev->dev.dma_mask != NULL)
236 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
240 static void sg_complete (struct urb *urb, struct pt_regs *regs)
242 struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
244 spin_lock (&io->lock);
246 /* In 2.5 we require hcds' endpoint queues not to progress after fault
247 * reports, until the completion callback (this!) returns. That lets
248 * device driver code (like this routine) unlink queued urbs first,
249 * if it needs to, since the HC won't work on them at all. So it's
250 * not possible for page N+1 to overwrite page N, and so on.
252 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
253 * complete before the HCD can get requests away from hardware,
254 * though never during cleanup after a hard fault.
257 && (io->status != -ECONNRESET
258 || urb->status != -ECONNRESET)
259 && urb->actual_length) {
260 dev_err (io->dev->bus->controller,
261 "dev %s ep%d%s scatterlist error %d/%d\n",
263 usb_pipeendpoint (urb->pipe),
264 usb_pipein (urb->pipe) ? "in" : "out",
265 urb->status, io->status);
269 if (io->status == 0 && urb->status && urb->status != -ECONNRESET) {
270 int i, found, status;
272 io->status = urb->status;
274 /* the previous urbs, and this one, completed already.
275 * unlink pending urbs so they won't rx/tx bad data.
276 * careful: unlink can sometimes be synchronous...
278 spin_unlock (&io->lock);
279 for (i = 0, found = 0; i < io->entries; i++) {
280 if (!io->urbs [i] || !io->urbs [i]->dev)
283 status = usb_unlink_urb (io->urbs [i]);
284 if (status != -EINPROGRESS
287 dev_err (&io->dev->dev,
288 "%s, unlink --> %d\n",
289 __FUNCTION__, status);
290 } else if (urb == io->urbs [i])
293 spin_lock (&io->lock);
297 /* on the last completion, signal usb_sg_wait() */
298 io->bytes += urb->actual_length;
301 complete (&io->complete);
303 spin_unlock (&io->lock);
308 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
309 * @io: request block being initialized. until usb_sg_wait() returns,
310 * treat this as a pointer to an opaque block of memory,
311 * @dev: the usb device that will send or receive the data
312 * @pipe: endpoint "pipe" used to transfer the data
313 * @period: polling rate for interrupt endpoints, in frames or
314 * (for high speed endpoints) microframes; ignored for bulk
315 * @sg: scatterlist entries
316 * @nents: how many entries in the scatterlist
317 * @length: how many bytes to send from the scatterlist, or zero to
318 * send every byte identified in the list.
319 * @mem_flags: SLAB_* flags affecting memory allocations in this call
321 * Returns zero for success, else a negative errno value. This initializes a
322 * scatter/gather request, allocating resources such as I/O mappings and urb
323 * memory (except maybe memory used by USB controller drivers).
325 * The request must be issued using usb_sg_wait(), which waits for the I/O to
326 * complete (or to be canceled) and then cleans up all resources allocated by
329 * The request may be canceled with usb_sg_cancel(), either before or after
330 * usb_sg_wait() is called.
333 struct usb_sg_request *io,
334 struct usb_device *dev,
337 struct scatterlist *sg,
347 if (!io || !dev || !sg
348 || usb_pipecontrol (pipe)
349 || usb_pipeisoc (pipe)
353 spin_lock_init (&io->lock);
359 /* not all host controllers use DMA (like the mainstream pci ones);
360 * they can use PIO (sl811) or be software over another transport.
362 dma = (dev->dev.dma_mask != NULL);
364 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
368 /* initialize all the urbs we'll use */
369 if (io->entries <= 0)
372 io->count = io->entries;
373 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
377 urb_flags = URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
378 if (usb_pipein (pipe))
379 urb_flags |= URB_SHORT_NOT_OK;
381 for (i = 0; i < io->entries; i++) {
384 io->urbs [i] = usb_alloc_urb (0, mem_flags);
390 io->urbs [i]->dev = NULL;
391 io->urbs [i]->pipe = pipe;
392 io->urbs [i]->interval = period;
393 io->urbs [i]->transfer_flags = urb_flags;
395 io->urbs [i]->complete = sg_complete;
396 io->urbs [i]->context = io;
397 io->urbs [i]->status = -EINPROGRESS;
398 io->urbs [i]->actual_length = 0;
401 /* hc may use _only_ transfer_dma */
402 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
403 len = sg_dma_len (sg + i);
405 /* hc may use _only_ transfer_buffer */
406 io->urbs [i]->transfer_buffer =
407 page_address (sg [i].page) + sg [i].offset;
412 len = min_t (unsigned, len, length);
417 io->urbs [i]->transfer_buffer_length = len;
419 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
421 /* transaction state */
424 init_completion (&io->complete);
434 * usb_sg_wait - synchronously execute scatter/gather request
435 * @io: request block handle, as initialized with usb_sg_init().
436 * some fields become accessible when this call returns.
437 * Context: !in_interrupt ()
439 * This function blocks until the specified I/O operation completes. It
440 * leverages the grouping of the related I/O requests to get good transfer
441 * rates, by queueing the requests. At higher speeds, such queuing can
442 * significantly improve USB throughput.
444 * There are three kinds of completion for this function.
445 * (1) success, where io->status is zero. The number of io->bytes
446 * transferred is as requested.
447 * (2) error, where io->status is a negative errno value. The number
448 * of io->bytes transferred before the error is usually less
449 * than requested, and can be nonzero.
450 * (3) cancellation, a type of error with status -ECONNRESET that
451 * is initiated by usb_sg_cancel().
453 * When this function returns, all memory allocated through usb_sg_init() or
454 * this call will have been freed. The request block parameter may still be
455 * passed to usb_sg_cancel(), or it may be freed. It could also be
456 * reinitialized and then reused.
458 * Data Transfer Rates:
460 * Bulk transfers are valid for full or high speed endpoints.
461 * The best full speed data rate is 19 packets of 64 bytes each
462 * per frame, or 1216 bytes per millisecond.
463 * The best high speed data rate is 13 packets of 512 bytes each
464 * per microframe, or 52 KBytes per millisecond.
466 * The reason to use interrupt transfers through this API would most likely
467 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
468 * could be transferred. That capability is less useful for low or full
469 * speed interrupt endpoints, which allow at most one packet per millisecond,
470 * of at most 8 or 64 bytes (respectively).
472 void usb_sg_wait (struct usb_sg_request *io)
474 int i, entries = io->entries;
476 /* queue the urbs. */
477 spin_lock_irq (&io->lock);
478 for (i = 0; i < entries && !io->status; i++) {
481 io->urbs [i]->dev = io->dev;
482 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
484 /* after we submit, let completions or cancelations fire;
485 * we handshake using io->status.
487 spin_unlock_irq (&io->lock);
489 /* maybe we retrying will recover */
490 case -ENXIO: // hc didn't queue this one
493 io->urbs[i]->dev = NULL;
499 /* no error? continue immediately.
501 * NOTE: to work better with UHCI (4K I/O buffer may
502 * need 3K of TDs) it may be good to limit how many
503 * URBs are queued at once; N milliseconds?
509 /* fail any uncompleted urbs */
511 io->urbs [i]->dev = NULL;
512 io->urbs [i]->status = retval;
513 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
514 __FUNCTION__, retval);
517 spin_lock_irq (&io->lock);
518 if (retval && (io->status == 0 || io->status == -ECONNRESET))
521 io->count -= entries - i;
523 complete (&io->complete);
524 spin_unlock_irq (&io->lock);
526 /* OK, yes, this could be packaged as non-blocking.
527 * So could the submit loop above ... but it's easier to
528 * solve neither problem than to solve both!
530 wait_for_completion (&io->complete);
536 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
537 * @io: request block, initialized with usb_sg_init()
539 * This stops a request after it has been started by usb_sg_wait().
540 * It can also prevents one initialized by usb_sg_init() from starting,
541 * so that call just frees resources allocated to the request.
543 void usb_sg_cancel (struct usb_sg_request *io)
547 spin_lock_irqsave (&io->lock, flags);
549 /* shut everything down, if it didn't already */
553 io->status = -ECONNRESET;
554 spin_unlock (&io->lock);
555 for (i = 0; i < io->entries; i++) {
558 if (!io->urbs [i]->dev)
560 retval = usb_unlink_urb (io->urbs [i]);
561 if (retval != -EINPROGRESS && retval != -EBUSY)
562 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
563 __FUNCTION__, retval);
565 spin_lock (&io->lock);
567 spin_unlock_irqrestore (&io->lock, flags);
570 /*-------------------------------------------------------------------*/
573 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
574 * @dev: the device whose descriptor is being retrieved
575 * @type: the descriptor type (USB_DT_*)
576 * @index: the number of the descriptor
577 * @buf: where to put the descriptor
578 * @size: how big is "buf"?
579 * Context: !in_interrupt ()
581 * Gets a USB descriptor. Convenience functions exist to simplify
582 * getting some types of descriptors. Use
583 * usb_get_string() or usb_string() for USB_DT_STRING.
584 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
585 * are part of the device structure.
586 * In addition to a number of USB-standard descriptors, some
587 * devices also use class-specific or vendor-specific descriptors.
589 * This call is synchronous, and may not be used in an interrupt context.
591 * Returns the number of bytes received on success, or else the status code
592 * returned by the underlying usb_control_msg() call.
594 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
599 memset(buf,0,size); // Make sure we parse really received data
601 for (i = 0; i < 3; ++i) {
602 /* retry on length 0 or stall; some devices are flakey */
603 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
604 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
605 (type << 8) + index, 0, buf, size,
606 USB_CTRL_GET_TIMEOUT);
607 if (result == 0 || result == -EPIPE)
609 if (result > 1 && ((u8 *)buf)[1] != type) {
619 * usb_get_string - gets a string descriptor
620 * @dev: the device whose string descriptor is being retrieved
621 * @langid: code for language chosen (from string descriptor zero)
622 * @index: the number of the descriptor
623 * @buf: where to put the string
624 * @size: how big is "buf"?
625 * Context: !in_interrupt ()
627 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
628 * in little-endian byte order).
629 * The usb_string() function will often be a convenient way to turn
630 * these strings into kernel-printable form.
632 * Strings may be referenced in device, configuration, interface, or other
633 * descriptors, and could also be used in vendor-specific ways.
635 * This call is synchronous, and may not be used in an interrupt context.
637 * Returns the number of bytes received on success, or else the status code
638 * returned by the underlying usb_control_msg() call.
640 int usb_get_string(struct usb_device *dev, unsigned short langid,
641 unsigned char index, void *buf, int size)
646 for (i = 0; i < 3; ++i) {
647 /* retry on length 0 or stall; some devices are flakey */
648 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
649 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
650 (USB_DT_STRING << 8) + index, langid, buf, size,
651 USB_CTRL_GET_TIMEOUT);
652 if (!(result == 0 || result == -EPIPE))
658 static void usb_try_string_workarounds(unsigned char *buf, int *length)
660 int newlength, oldlength = *length;
662 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
663 if (!isprint(buf[newlength]) || buf[newlength + 1])
672 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
673 unsigned int index, unsigned char *buf)
677 /* Try to read the string descriptor by asking for the maximum
678 * possible number of bytes */
679 rc = usb_get_string(dev, langid, index, buf, 255);
681 /* If that failed try to read the descriptor length, then
682 * ask for just that many bytes */
684 rc = usb_get_string(dev, langid, index, buf, 2);
686 rc = usb_get_string(dev, langid, index, buf, buf[0]);
690 if (!buf[0] && !buf[1])
691 usb_try_string_workarounds(buf, &rc);
693 /* There might be extra junk at the end of the descriptor */
697 rc = rc - (rc & 1); /* force a multiple of two */
701 rc = (rc < 0 ? rc : -EINVAL);
707 * usb_string - returns ISO 8859-1 version of a string descriptor
708 * @dev: the device whose string descriptor is being retrieved
709 * @index: the number of the descriptor
710 * @buf: where to put the string
711 * @size: how big is "buf"?
712 * Context: !in_interrupt ()
714 * This converts the UTF-16LE encoded strings returned by devices, from
715 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
716 * that are more usable in most kernel contexts. Note that all characters
717 * in the chosen descriptor that can't be encoded using ISO-8859-1
718 * are converted to the question mark ("?") character, and this function
719 * chooses strings in the first language supported by the device.
721 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
722 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
723 * and is appropriate for use many uses of English and several other
724 * Western European languages. (But it doesn't include the "Euro" symbol.)
726 * This call is synchronous, and may not be used in an interrupt context.
728 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
730 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
736 if (dev->state == USB_STATE_SUSPENDED)
737 return -EHOSTUNREACH;
738 if (size <= 0 || !buf || !index)
741 tbuf = kmalloc(256, GFP_KERNEL);
745 /* get langid for strings if it's not yet known */
746 if (!dev->have_langid) {
747 err = usb_string_sub(dev, 0, 0, tbuf);
750 "string descriptor 0 read error: %d\n",
753 } else if (err < 4) {
754 dev_err (&dev->dev, "string descriptor 0 too short\n");
758 dev->have_langid = -1;
759 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
760 /* always use the first langid listed */
761 dev_dbg (&dev->dev, "default language 0x%04x\n",
766 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
770 size--; /* leave room for trailing NULL char in output buffer */
771 for (idx = 0, u = 2; u < err; u += 2) {
774 if (tbuf[u+1]) /* high byte */
775 buf[idx++] = '?'; /* non ISO-8859-1 character */
777 buf[idx++] = tbuf[u];
782 if (tbuf[1] != USB_DT_STRING)
783 dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
791 * usb_cache_string - read a string descriptor and cache it for later use
792 * @udev: the device whose string descriptor is being read
793 * @index: the descriptor index
795 * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
796 * or NULL if the index is 0 or the string could not be read.
798 char *usb_cache_string(struct usb_device *udev, int index)
801 char *smallbuf = NULL;
804 if (index > 0 && (buf = kmalloc(256, GFP_KERNEL)) != NULL) {
805 if ((len = usb_string(udev, index, buf, 256)) > 0) {
806 if ((smallbuf = kmalloc(++len, GFP_KERNEL)) == NULL)
808 memcpy(smallbuf, buf, len);
816 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
817 * @dev: the device whose device descriptor is being updated
818 * @size: how much of the descriptor to read
819 * Context: !in_interrupt ()
821 * Updates the copy of the device descriptor stored in the device structure,
822 * which dedicates space for this purpose. Note that several fields are
823 * converted to the host CPU's byte order: the USB version (bcdUSB), and
824 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
825 * That lets device drivers compare against non-byteswapped constants.
827 * Not exported, only for use by the core. If drivers really want to read
828 * the device descriptor directly, they can call usb_get_descriptor() with
829 * type = USB_DT_DEVICE and index = 0.
831 * This call is synchronous, and may not be used in an interrupt context.
833 * Returns the number of bytes received on success, or else the status code
834 * returned by the underlying usb_control_msg() call.
836 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
838 struct usb_device_descriptor *desc;
841 if (size > sizeof(*desc))
843 desc = kmalloc(sizeof(*desc), GFP_NOIO);
847 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
849 memcpy(&dev->descriptor, desc, size);
855 * usb_get_status - issues a GET_STATUS call
856 * @dev: the device whose status is being checked
857 * @type: USB_RECIP_*; for device, interface, or endpoint
858 * @target: zero (for device), else interface or endpoint number
859 * @data: pointer to two bytes of bitmap data
860 * Context: !in_interrupt ()
862 * Returns device, interface, or endpoint status. Normally only of
863 * interest to see if the device is self powered, or has enabled the
864 * remote wakeup facility; or whether a bulk or interrupt endpoint
865 * is halted ("stalled").
867 * Bits in these status bitmaps are set using the SET_FEATURE request,
868 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
869 * function should be used to clear halt ("stall") status.
871 * This call is synchronous, and may not be used in an interrupt context.
873 * Returns the number of bytes received on success, or else the status code
874 * returned by the underlying usb_control_msg() call.
876 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
879 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
884 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
885 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
886 sizeof(*status), USB_CTRL_GET_TIMEOUT);
888 *(u16 *)data = *status;
894 * usb_clear_halt - tells device to clear endpoint halt/stall condition
895 * @dev: device whose endpoint is halted
896 * @pipe: endpoint "pipe" being cleared
897 * Context: !in_interrupt ()
899 * This is used to clear halt conditions for bulk and interrupt endpoints,
900 * as reported by URB completion status. Endpoints that are halted are
901 * sometimes referred to as being "stalled". Such endpoints are unable
902 * to transmit or receive data until the halt status is cleared. Any URBs
903 * queued for such an endpoint should normally be unlinked by the driver
904 * before clearing the halt condition, as described in sections 5.7.5
905 * and 5.8.5 of the USB 2.0 spec.
907 * Note that control and isochronous endpoints don't halt, although control
908 * endpoints report "protocol stall" (for unsupported requests) using the
909 * same status code used to report a true stall.
911 * This call is synchronous, and may not be used in an interrupt context.
913 * Returns zero on success, or else the status code returned by the
914 * underlying usb_control_msg() call.
916 int usb_clear_halt(struct usb_device *dev, int pipe)
919 int endp = usb_pipeendpoint(pipe);
921 if (usb_pipein (pipe))
924 /* we don't care if it wasn't halted first. in fact some devices
925 * (like some ibmcam model 1 units) seem to expect hosts to make
926 * this request for iso endpoints, which can't halt!
928 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
929 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
930 USB_ENDPOINT_HALT, endp, NULL, 0,
931 USB_CTRL_SET_TIMEOUT);
933 /* don't un-halt or force to DATA0 except on success */
937 /* NOTE: seems like Microsoft and Apple don't bother verifying
938 * the clear "took", so some devices could lock up if you check...
939 * such as the Hagiwara FlashGate DUAL. So we won't bother.
941 * NOTE: make sure the logic here doesn't diverge much from
942 * the copy in usb-storage, for as long as we need two copies.
945 /* toggle was reset by the clear */
946 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
952 * usb_disable_endpoint -- Disable an endpoint by address
953 * @dev: the device whose endpoint is being disabled
954 * @epaddr: the endpoint's address. Endpoint number for output,
955 * endpoint number + USB_DIR_IN for input
957 * Deallocates hcd/hardware state for this endpoint ... and nukes all
960 * If the HCD hasn't registered a disable() function, this sets the
961 * endpoint's maxpacket size to 0 to prevent further submissions.
963 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
965 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
966 struct usb_host_endpoint *ep;
971 if (usb_endpoint_out(epaddr)) {
972 ep = dev->ep_out[epnum];
973 dev->ep_out[epnum] = NULL;
975 ep = dev->ep_in[epnum];
976 dev->ep_in[epnum] = NULL;
978 if (ep && dev->bus && dev->bus->op && dev->bus->op->disable)
979 dev->bus->op->disable(dev, ep);
983 * usb_disable_interface -- Disable all endpoints for an interface
984 * @dev: the device whose interface is being disabled
985 * @intf: pointer to the interface descriptor
987 * Disables all the endpoints for the interface's current altsetting.
989 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
991 struct usb_host_interface *alt = intf->cur_altsetting;
994 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
995 usb_disable_endpoint(dev,
996 alt->endpoint[i].desc.bEndpointAddress);
1001 * usb_disable_device - Disable all the endpoints for a USB device
1002 * @dev: the device whose endpoints are being disabled
1003 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1005 * Disables all the device's endpoints, potentially including endpoint 0.
1006 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1007 * pending urbs) and usbcore state for the interfaces, so that usbcore
1008 * must usb_set_configuration() before any interfaces could be used.
1010 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1014 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
1015 skip_ep0 ? "non-ep0" : "all");
1016 for (i = skip_ep0; i < 16; ++i) {
1017 usb_disable_endpoint(dev, i);
1018 usb_disable_endpoint(dev, i + USB_DIR_IN);
1020 dev->toggle[0] = dev->toggle[1] = 0;
1022 /* getting rid of interfaces will disconnect
1023 * any drivers bound to them (a key side effect)
1025 if (dev->actconfig) {
1026 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1027 struct usb_interface *interface;
1029 /* remove this interface if it has been registered */
1030 interface = dev->actconfig->interface[i];
1031 if (!device_is_registered(&interface->dev))
1033 dev_dbg (&dev->dev, "unregistering interface %s\n",
1034 interface->dev.bus_id);
1035 usb_remove_sysfs_intf_files(interface);
1036 device_del (&interface->dev);
1039 /* Now that the interfaces are unbound, nobody should
1040 * try to access them.
1042 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1043 put_device (&dev->actconfig->interface[i]->dev);
1044 dev->actconfig->interface[i] = NULL;
1046 dev->actconfig = NULL;
1047 if (dev->state == USB_STATE_CONFIGURED)
1048 usb_set_device_state(dev, USB_STATE_ADDRESS);
1054 * usb_enable_endpoint - Enable an endpoint for USB communications
1055 * @dev: the device whose interface is being enabled
1058 * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
1059 * For control endpoints, both the input and output sides are handled.
1062 usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
1064 unsigned int epaddr = ep->desc.bEndpointAddress;
1065 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1068 is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1069 == USB_ENDPOINT_XFER_CONTROL);
1070 if (usb_endpoint_out(epaddr) || is_control) {
1071 usb_settoggle(dev, epnum, 1, 0);
1072 dev->ep_out[epnum] = ep;
1074 if (!usb_endpoint_out(epaddr) || is_control) {
1075 usb_settoggle(dev, epnum, 0, 0);
1076 dev->ep_in[epnum] = ep;
1081 * usb_enable_interface - Enable all the endpoints for an interface
1082 * @dev: the device whose interface is being enabled
1083 * @intf: pointer to the interface descriptor
1085 * Enables all the endpoints for the interface's current altsetting.
1087 static void usb_enable_interface(struct usb_device *dev,
1088 struct usb_interface *intf)
1090 struct usb_host_interface *alt = intf->cur_altsetting;
1093 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1094 usb_enable_endpoint(dev, &alt->endpoint[i]);
1098 * usb_set_interface - Makes a particular alternate setting be current
1099 * @dev: the device whose interface is being updated
1100 * @interface: the interface being updated
1101 * @alternate: the setting being chosen.
1102 * Context: !in_interrupt ()
1104 * This is used to enable data transfers on interfaces that may not
1105 * be enabled by default. Not all devices support such configurability.
1106 * Only the driver bound to an interface may change its setting.
1108 * Within any given configuration, each interface may have several
1109 * alternative settings. These are often used to control levels of
1110 * bandwidth consumption. For example, the default setting for a high
1111 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1112 * while interrupt transfers of up to 3KBytes per microframe are legal.
1113 * Also, isochronous endpoints may never be part of an
1114 * interface's default setting. To access such bandwidth, alternate
1115 * interface settings must be made current.
1117 * Note that in the Linux USB subsystem, bandwidth associated with
1118 * an endpoint in a given alternate setting is not reserved until an URB
1119 * is submitted that needs that bandwidth. Some other operating systems
1120 * allocate bandwidth early, when a configuration is chosen.
1122 * This call is synchronous, and may not be used in an interrupt context.
1123 * Also, drivers must not change altsettings while urbs are scheduled for
1124 * endpoints in that interface; all such urbs must first be completed
1125 * (perhaps forced by unlinking).
1127 * Returns zero on success, or else the status code returned by the
1128 * underlying usb_control_msg() call.
1130 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1132 struct usb_interface *iface;
1133 struct usb_host_interface *alt;
1137 if (dev->state == USB_STATE_SUSPENDED)
1138 return -EHOSTUNREACH;
1140 iface = usb_ifnum_to_if(dev, interface);
1142 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1147 alt = usb_altnum_to_altsetting(iface, alternate);
1149 warn("selecting invalid altsetting %d", alternate);
1153 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1154 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1155 alternate, interface, NULL, 0, 5000);
1157 /* 9.4.10 says devices don't need this and are free to STALL the
1158 * request if the interface only has one alternate setting.
1160 if (ret == -EPIPE && iface->num_altsetting == 1) {
1162 "manual set_interface for iface %d, alt %d\n",
1163 interface, alternate);
1168 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1169 * when they implement async or easily-killable versions of this or
1170 * other "should-be-internal" functions (like clear_halt).
1171 * should hcd+usbcore postprocess control requests?
1174 /* prevent submissions using previous endpoint settings */
1175 if (device_is_registered(&iface->dev))
1176 usb_remove_sysfs_intf_files(iface);
1177 usb_disable_interface(dev, iface);
1179 iface->cur_altsetting = alt;
1181 /* If the interface only has one altsetting and the device didn't
1182 * accept the request, we attempt to carry out the equivalent action
1183 * by manually clearing the HALT feature for each endpoint in the
1189 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1190 unsigned int epaddr =
1191 alt->endpoint[i].desc.bEndpointAddress;
1193 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
1194 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1196 usb_clear_halt(dev, pipe);
1200 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1203 * Despite EP0 is always present in all interfaces/AS, the list of
1204 * endpoints from the descriptor does not contain EP0. Due to its
1205 * omnipresence one might expect EP0 being considered "affected" by
1206 * any SetInterface request and hence assume toggles need to be reset.
1207 * However, EP0 toggles are re-synced for every individual transfer
1208 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1209 * (Likewise, EP0 never "halts" on well designed devices.)
1211 usb_enable_interface(dev, iface);
1212 if (device_is_registered(&iface->dev))
1213 usb_create_sysfs_intf_files(iface);
1219 * usb_reset_configuration - lightweight device reset
1220 * @dev: the device whose configuration is being reset
1222 * This issues a standard SET_CONFIGURATION request to the device using
1223 * the current configuration. The effect is to reset most USB-related
1224 * state in the device, including interface altsettings (reset to zero),
1225 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1226 * endpoints). Other usbcore state is unchanged, including bindings of
1227 * usb device drivers to interfaces.
1229 * Because this affects multiple interfaces, avoid using this with composite
1230 * (multi-interface) devices. Instead, the driver for each interface may
1231 * use usb_set_interface() on the interfaces it claims. Be careful though;
1232 * some devices don't support the SET_INTERFACE request, and others won't
1233 * reset all the interface state (notably data toggles). Resetting the whole
1234 * configuration would affect other drivers' interfaces.
1236 * The caller must own the device lock.
1238 * Returns zero on success, else a negative error code.
1240 int usb_reset_configuration(struct usb_device *dev)
1243 struct usb_host_config *config;
1245 if (dev->state == USB_STATE_SUSPENDED)
1246 return -EHOSTUNREACH;
1248 /* caller must have locked the device and must own
1249 * the usb bus readlock (so driver bindings are stable);
1250 * calls during probe() are fine
1253 for (i = 1; i < 16; ++i) {
1254 usb_disable_endpoint(dev, i);
1255 usb_disable_endpoint(dev, i + USB_DIR_IN);
1258 config = dev->actconfig;
1259 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1260 USB_REQ_SET_CONFIGURATION, 0,
1261 config->desc.bConfigurationValue, 0,
1262 NULL, 0, USB_CTRL_SET_TIMEOUT);
1266 dev->toggle[0] = dev->toggle[1] = 0;
1268 /* re-init hc/hcd interface/endpoint state */
1269 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1270 struct usb_interface *intf = config->interface[i];
1271 struct usb_host_interface *alt;
1273 if (device_is_registered(&intf->dev))
1274 usb_remove_sysfs_intf_files(intf);
1275 alt = usb_altnum_to_altsetting(intf, 0);
1277 /* No altsetting 0? We'll assume the first altsetting.
1278 * We could use a GetInterface call, but if a device is
1279 * so non-compliant that it doesn't have altsetting 0
1280 * then I wouldn't trust its reply anyway.
1283 alt = &intf->altsetting[0];
1285 intf->cur_altsetting = alt;
1286 usb_enable_interface(dev, intf);
1287 if (device_is_registered(&intf->dev))
1288 usb_create_sysfs_intf_files(intf);
1293 static void release_interface(struct device *dev)
1295 struct usb_interface *intf = to_usb_interface(dev);
1296 struct usb_interface_cache *intfc =
1297 altsetting_to_usb_interface_cache(intf->altsetting);
1299 kref_put(&intfc->ref, usb_release_interface_cache);
1304 * usb_set_configuration - Makes a particular device setting be current
1305 * @dev: the device whose configuration is being updated
1306 * @configuration: the configuration being chosen.
1307 * Context: !in_interrupt(), caller owns the device lock
1309 * This is used to enable non-default device modes. Not all devices
1310 * use this kind of configurability; many devices only have one
1313 * USB device configurations may affect Linux interoperability,
1314 * power consumption and the functionality available. For example,
1315 * the default configuration is limited to using 100mA of bus power,
1316 * so that when certain device functionality requires more power,
1317 * and the device is bus powered, that functionality should be in some
1318 * non-default device configuration. Other device modes may also be
1319 * reflected as configuration options, such as whether two ISDN
1320 * channels are available independently; and choosing between open
1321 * standard device protocols (like CDC) or proprietary ones.
1323 * Note that USB has an additional level of device configurability,
1324 * associated with interfaces. That configurability is accessed using
1325 * usb_set_interface().
1327 * This call is synchronous. The calling context must be able to sleep,
1328 * must own the device lock, and must not hold the driver model's USB
1329 * bus rwsem; usb device driver probe() methods cannot use this routine.
1331 * Returns zero on success, or else the status code returned by the
1332 * underlying call that failed. On successful completion, each interface
1333 * in the original device configuration has been destroyed, and each one
1334 * in the new configuration has been probed by all relevant usb device
1335 * drivers currently known to the kernel.
1337 int usb_set_configuration(struct usb_device *dev, int configuration)
1340 struct usb_host_config *cp = NULL;
1341 struct usb_interface **new_interfaces = NULL;
1344 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1345 if (dev->config[i].desc.bConfigurationValue == configuration) {
1346 cp = &dev->config[i];
1350 if ((!cp && configuration != 0))
1353 /* The USB spec says configuration 0 means unconfigured.
1354 * But if a device includes a configuration numbered 0,
1355 * we will accept it as a correctly configured state.
1357 if (cp && configuration == 0)
1358 dev_warn(&dev->dev, "config 0 descriptor??\n");
1360 if (dev->state == USB_STATE_SUSPENDED)
1361 return -EHOSTUNREACH;
1363 /* Allocate memory for new interfaces before doing anything else,
1364 * so that if we run out then nothing will have changed. */
1367 nintf = cp->desc.bNumInterfaces;
1368 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1370 if (!new_interfaces) {
1371 dev_err(&dev->dev, "Out of memory");
1375 for (; n < nintf; ++n) {
1376 new_interfaces[n] = kzalloc(
1377 sizeof(struct usb_interface),
1379 if (!new_interfaces[n]) {
1380 dev_err(&dev->dev, "Out of memory");
1384 kfree(new_interfaces[n]);
1385 kfree(new_interfaces);
1391 /* if it's already configured, clear out old state first.
1392 * getting rid of old interfaces means unbinding their drivers.
1394 if (dev->state != USB_STATE_ADDRESS)
1395 usb_disable_device (dev, 1); // Skip ep0
1397 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1398 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1399 NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0)
1400 goto free_interfaces;
1402 dev->actconfig = cp;
1404 usb_set_device_state(dev, USB_STATE_ADDRESS);
1406 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1408 /* Initialize the new interface structures and the
1409 * hc/hcd/usbcore interface/endpoint state.
1411 for (i = 0; i < nintf; ++i) {
1412 struct usb_interface_cache *intfc;
1413 struct usb_interface *intf;
1414 struct usb_host_interface *alt;
1416 cp->interface[i] = intf = new_interfaces[i];
1417 intfc = cp->intf_cache[i];
1418 intf->altsetting = intfc->altsetting;
1419 intf->num_altsetting = intfc->num_altsetting;
1420 kref_get(&intfc->ref);
1422 alt = usb_altnum_to_altsetting(intf, 0);
1424 /* No altsetting 0? We'll assume the first altsetting.
1425 * We could use a GetInterface call, but if a device is
1426 * so non-compliant that it doesn't have altsetting 0
1427 * then I wouldn't trust its reply anyway.
1430 alt = &intf->altsetting[0];
1432 intf->cur_altsetting = alt;
1433 usb_enable_interface(dev, intf);
1434 intf->dev.parent = &dev->dev;
1435 intf->dev.driver = NULL;
1436 intf->dev.bus = &usb_bus_type;
1437 intf->dev.dma_mask = dev->dev.dma_mask;
1438 intf->dev.release = release_interface;
1439 device_initialize (&intf->dev);
1440 mark_quiesced(intf);
1441 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1442 dev->bus->busnum, dev->devpath,
1444 alt->desc.bInterfaceNumber);
1446 kfree(new_interfaces);
1448 if (cp->string == NULL)
1449 cp->string = usb_cache_string(dev,
1450 cp->desc.iConfiguration);
1452 /* Now that all the interfaces are set up, register them
1453 * to trigger binding of drivers to interfaces. probe()
1454 * routines may install different altsettings and may
1455 * claim() any interfaces not yet bound. Many class drivers
1456 * need that: CDC, audio, video, etc.
1458 for (i = 0; i < nintf; ++i) {
1459 struct usb_interface *intf = cp->interface[i];
1460 struct usb_host_interface *alt = intf->cur_altsetting;
1463 "adding %s (config #%d, interface %d)\n",
1464 intf->dev.bus_id, configuration,
1465 alt->desc.bInterfaceNumber);
1466 ret = device_add (&intf->dev);
1469 "device_add(%s) --> %d\n",
1474 usb_create_sysfs_intf_files (intf);
1481 // synchronous request completion model
1482 EXPORT_SYMBOL(usb_control_msg);
1483 EXPORT_SYMBOL(usb_bulk_msg);
1485 EXPORT_SYMBOL(usb_sg_init);
1486 EXPORT_SYMBOL(usb_sg_cancel);
1487 EXPORT_SYMBOL(usb_sg_wait);
1489 // synchronous control message convenience routines
1490 EXPORT_SYMBOL(usb_get_descriptor);
1491 EXPORT_SYMBOL(usb_get_status);
1492 EXPORT_SYMBOL(usb_get_string);
1493 EXPORT_SYMBOL(usb_string);
1495 // synchronous calls that also maintain usbcore state
1496 EXPORT_SYMBOL(usb_clear_halt);
1497 EXPORT_SYMBOL(usb_reset_configuration);
1498 EXPORT_SYMBOL(usb_set_interface);