2 * message.c - synchronous message handling
5 #include <linux/pci.h> /* for scatterlist macros */
7 #include <linux/module.h>
8 #include <linux/slab.h>
10 #include <linux/timer.h>
11 #include <linux/ctype.h>
12 #include <linux/nls.h>
13 #include <linux/device.h>
14 #include <linux/scatterlist.h>
15 #include <linux/usb/quirks.h>
16 #include <linux/usb/hcd.h> /* for usbcore internals */
17 #include <asm/byteorder.h>
21 static void cancel_async_set_config(struct usb_device *udev);
24 struct completion done;
28 static void usb_api_blocking_completion(struct urb *urb)
30 struct api_context *ctx = urb->context;
32 ctx->status = urb->status;
38 * Starts urb and waits for completion or timeout. Note that this call
39 * is NOT interruptible. Many device driver i/o requests should be
40 * interruptible and therefore these drivers should implement their
41 * own interruptible routines.
43 static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
45 struct api_context ctx;
49 init_completion(&ctx.done);
51 urb->actual_length = 0;
52 retval = usb_submit_urb(urb, GFP_NOIO);
56 expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
57 if (!wait_for_completion_timeout(&ctx.done, expire)) {
59 retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
61 dev_dbg(&urb->dev->dev,
62 "%s timed out on ep%d%s len=%u/%u\n",
64 usb_endpoint_num(&urb->ep->desc),
65 usb_urb_dir_in(urb) ? "in" : "out",
67 urb->transfer_buffer_length);
72 *actual_length = urb->actual_length;
78 /*-------------------------------------------------------------------*/
79 /* returns status (negative) or length (positive) */
80 static int usb_internal_control_msg(struct usb_device *usb_dev,
82 struct usb_ctrlrequest *cmd,
83 void *data, int len, int timeout)
89 urb = usb_alloc_urb(0, GFP_NOIO);
93 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
94 len, usb_api_blocking_completion, NULL);
96 retv = usb_start_wait_urb(urb, timeout, &length);
104 * usb_control_msg - Builds a control urb, sends it off and waits for completion
105 * @dev: pointer to the usb device to send the message to
106 * @pipe: endpoint "pipe" to send the message to
107 * @request: USB message request value
108 * @requesttype: USB message request type value
109 * @value: USB message value
110 * @index: USB message index value
111 * @data: pointer to the data to send
112 * @size: length in bytes of the data to send
113 * @timeout: time in msecs to wait for the message to complete before timing
114 * out (if 0 the wait is forever)
116 * Context: !in_interrupt ()
118 * This function sends a simple control message to a specified endpoint and
119 * waits for the message to complete, or timeout.
121 * Don't use this function from within an interrupt context, like a bottom half
122 * handler. If you need an asynchronous message, or need to send a message
123 * from within interrupt context, use usb_submit_urb().
124 * If a thread in your driver uses this call, make sure your disconnect()
125 * method can wait for it to complete. Since you don't have a handle on the
126 * URB used, you can't cancel the request.
128 * Return: If successful, the number of bytes transferred. Otherwise, a negative
131 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
132 __u8 requesttype, __u16 value, __u16 index, void *data,
133 __u16 size, int timeout)
135 struct usb_ctrlrequest *dr;
138 dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
142 dr->bRequestType = requesttype;
143 dr->bRequest = request;
144 dr->wValue = cpu_to_le16(value);
145 dr->wIndex = cpu_to_le16(index);
146 dr->wLength = cpu_to_le16(size);
148 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
154 EXPORT_SYMBOL_GPL(usb_control_msg);
157 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
158 * @usb_dev: pointer to the usb device to send the message to
159 * @pipe: endpoint "pipe" to send the message to
160 * @data: pointer to the data to send
161 * @len: length in bytes of the data to send
162 * @actual_length: pointer to a location to put the actual length transferred
164 * @timeout: time in msecs to wait for the message to complete before
165 * timing out (if 0 the wait is forever)
167 * Context: !in_interrupt ()
169 * This function sends a simple interrupt message to a specified endpoint and
170 * waits for the message to complete, or timeout.
172 * Don't use this function from within an interrupt context, like a bottom half
173 * handler. If you need an asynchronous message, or need to send a message
174 * from within interrupt context, use usb_submit_urb() If a thread in your
175 * driver uses this call, make sure your disconnect() method can wait for it to
176 * complete. Since you don't have a handle on the URB used, you can't cancel
180 * If successful, 0. Otherwise a negative error number. The number of actual
181 * bytes transferred will be stored in the @actual_length parameter.
183 int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
184 void *data, int len, int *actual_length, int timeout)
186 return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
188 EXPORT_SYMBOL_GPL(usb_interrupt_msg);
191 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
192 * @usb_dev: pointer to the usb device to send the message to
193 * @pipe: endpoint "pipe" to send the message to
194 * @data: pointer to the data to send
195 * @len: length in bytes of the data to send
196 * @actual_length: pointer to a location to put the actual length transferred
198 * @timeout: time in msecs to wait for the message to complete before
199 * timing out (if 0 the wait is forever)
201 * Context: !in_interrupt ()
203 * This function sends a simple bulk message to a specified endpoint
204 * and waits for the message to complete, or timeout.
206 * Don't use this function from within an interrupt context, like a bottom half
207 * handler. If you need an asynchronous message, or need to send a message
208 * from within interrupt context, use usb_submit_urb() If a thread in your
209 * driver uses this call, make sure your disconnect() method can wait for it to
210 * complete. Since you don't have a handle on the URB used, you can't cancel
213 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
214 * users are forced to abuse this routine by using it to submit URBs for
215 * interrupt endpoints. We will take the liberty of creating an interrupt URB
216 * (with the default interval) if the target is an interrupt endpoint.
219 * If successful, 0. Otherwise a negative error number. The number of actual
220 * bytes transferred will be stored in the @actual_length parameter.
223 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
224 void *data, int len, int *actual_length, int timeout)
227 struct usb_host_endpoint *ep;
229 ep = usb_pipe_endpoint(usb_dev, pipe);
233 urb = usb_alloc_urb(0, GFP_KERNEL);
237 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
238 USB_ENDPOINT_XFER_INT) {
239 pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
240 usb_fill_int_urb(urb, usb_dev, pipe, data, len,
241 usb_api_blocking_completion, NULL,
244 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
245 usb_api_blocking_completion, NULL);
247 return usb_start_wait_urb(urb, timeout, actual_length);
249 EXPORT_SYMBOL_GPL(usb_bulk_msg);
251 /*-------------------------------------------------------------------*/
253 static void sg_clean(struct usb_sg_request *io)
256 while (io->entries--)
257 usb_free_urb(io->urbs[io->entries]);
264 static void sg_complete(struct urb *urb)
266 struct usb_sg_request *io = urb->context;
267 int status = urb->status;
269 spin_lock(&io->lock);
271 /* In 2.5 we require hcds' endpoint queues not to progress after fault
272 * reports, until the completion callback (this!) returns. That lets
273 * device driver code (like this routine) unlink queued urbs first,
274 * if it needs to, since the HC won't work on them at all. So it's
275 * not possible for page N+1 to overwrite page N, and so on.
277 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
278 * complete before the HCD can get requests away from hardware,
279 * though never during cleanup after a hard fault.
282 && (io->status != -ECONNRESET
283 || status != -ECONNRESET)
284 && urb->actual_length) {
285 dev_err(io->dev->bus->controller,
286 "dev %s ep%d%s scatterlist error %d/%d\n",
288 usb_endpoint_num(&urb->ep->desc),
289 usb_urb_dir_in(urb) ? "in" : "out",
294 if (io->status == 0 && status && status != -ECONNRESET) {
295 int i, found, retval;
299 /* the previous urbs, and this one, completed already.
300 * unlink pending urbs so they won't rx/tx bad data.
301 * careful: unlink can sometimes be synchronous...
303 spin_unlock(&io->lock);
304 for (i = 0, found = 0; i < io->entries; i++) {
308 usb_block_urb(io->urbs[i]);
309 retval = usb_unlink_urb(io->urbs[i]);
310 if (retval != -EINPROGRESS &&
314 dev_err(&io->dev->dev,
315 "%s, unlink --> %d\n",
317 } else if (urb == io->urbs[i])
320 spin_lock(&io->lock);
323 /* on the last completion, signal usb_sg_wait() */
324 io->bytes += urb->actual_length;
327 complete(&io->complete);
329 spin_unlock(&io->lock);
334 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
335 * @io: request block being initialized. until usb_sg_wait() returns,
336 * treat this as a pointer to an opaque block of memory,
337 * @dev: the usb device that will send or receive the data
338 * @pipe: endpoint "pipe" used to transfer the data
339 * @period: polling rate for interrupt endpoints, in frames or
340 * (for high speed endpoints) microframes; ignored for bulk
341 * @sg: scatterlist entries
342 * @nents: how many entries in the scatterlist
343 * @length: how many bytes to send from the scatterlist, or zero to
344 * send every byte identified in the list.
345 * @mem_flags: SLAB_* flags affecting memory allocations in this call
347 * This initializes a scatter/gather request, allocating resources such as
348 * I/O mappings and urb memory (except maybe memory used by USB controller
351 * The request must be issued using usb_sg_wait(), which waits for the I/O to
352 * complete (or to be canceled) and then cleans up all resources allocated by
355 * The request may be canceled with usb_sg_cancel(), either before or after
356 * usb_sg_wait() is called.
358 * Return: Zero for success, else a negative errno value.
360 int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
361 unsigned pipe, unsigned period, struct scatterlist *sg,
362 int nents, size_t length, gfp_t mem_flags)
368 if (!io || !dev || !sg
369 || usb_pipecontrol(pipe)
370 || usb_pipeisoc(pipe)
374 spin_lock_init(&io->lock);
378 if (dev->bus->sg_tablesize > 0) {
386 /* initialize all the urbs we'll use */
387 io->urbs = kmalloc(io->entries * sizeof(*io->urbs), mem_flags);
391 urb_flags = URB_NO_INTERRUPT;
392 if (usb_pipein(pipe))
393 urb_flags |= URB_SHORT_NOT_OK;
395 for_each_sg(sg, sg, io->entries, i) {
399 urb = usb_alloc_urb(0, mem_flags);
408 urb->interval = period;
409 urb->transfer_flags = urb_flags;
410 urb->complete = sg_complete;
415 /* There is no single transfer buffer */
416 urb->transfer_buffer = NULL;
417 urb->num_sgs = nents;
419 /* A length of zero means transfer the whole sg list */
422 struct scatterlist *sg2;
425 for_each_sg(sg, sg2, nents, j)
430 * Some systems can't use DMA; they use PIO instead.
431 * For their sakes, transfer_buffer is set whenever
434 if (!PageHighMem(sg_page(sg)))
435 urb->transfer_buffer = sg_virt(sg);
437 urb->transfer_buffer = NULL;
441 len = min_t(size_t, len, length);
447 urb->transfer_buffer_length = len;
449 io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
451 /* transaction state */
452 io->count = io->entries;
455 init_completion(&io->complete);
462 EXPORT_SYMBOL_GPL(usb_sg_init);
465 * usb_sg_wait - synchronously execute scatter/gather request
466 * @io: request block handle, as initialized with usb_sg_init().
467 * some fields become accessible when this call returns.
468 * Context: !in_interrupt ()
470 * This function blocks until the specified I/O operation completes. It
471 * leverages the grouping of the related I/O requests to get good transfer
472 * rates, by queueing the requests. At higher speeds, such queuing can
473 * significantly improve USB throughput.
475 * There are three kinds of completion for this function.
476 * (1) success, where io->status is zero. The number of io->bytes
477 * transferred is as requested.
478 * (2) error, where io->status is a negative errno value. The number
479 * of io->bytes transferred before the error is usually less
480 * than requested, and can be nonzero.
481 * (3) cancellation, a type of error with status -ECONNRESET that
482 * is initiated by usb_sg_cancel().
484 * When this function returns, all memory allocated through usb_sg_init() or
485 * this call will have been freed. The request block parameter may still be
486 * passed to usb_sg_cancel(), or it may be freed. It could also be
487 * reinitialized and then reused.
489 * Data Transfer Rates:
491 * Bulk transfers are valid for full or high speed endpoints.
492 * The best full speed data rate is 19 packets of 64 bytes each
493 * per frame, or 1216 bytes per millisecond.
494 * The best high speed data rate is 13 packets of 512 bytes each
495 * per microframe, or 52 KBytes per millisecond.
497 * The reason to use interrupt transfers through this API would most likely
498 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
499 * could be transferred. That capability is less useful for low or full
500 * speed interrupt endpoints, which allow at most one packet per millisecond,
501 * of at most 8 or 64 bytes (respectively).
503 * It is not necessary to call this function to reserve bandwidth for devices
504 * under an xHCI host controller, as the bandwidth is reserved when the
505 * configuration or interface alt setting is selected.
507 void usb_sg_wait(struct usb_sg_request *io)
510 int entries = io->entries;
512 /* queue the urbs. */
513 spin_lock_irq(&io->lock);
515 while (i < entries && !io->status) {
518 io->urbs[i]->dev = io->dev;
519 spin_unlock_irq(&io->lock);
521 retval = usb_submit_urb(io->urbs[i], GFP_NOIO);
524 /* maybe we retrying will recover */
525 case -ENXIO: /* hc didn't queue this one */
532 /* no error? continue immediately.
534 * NOTE: to work better with UHCI (4K I/O buffer may
535 * need 3K of TDs) it may be good to limit how many
536 * URBs are queued at once; N milliseconds?
543 /* fail any uncompleted urbs */
545 io->urbs[i]->status = retval;
546 dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
550 spin_lock_irq(&io->lock);
551 if (retval && (io->status == 0 || io->status == -ECONNRESET))
554 io->count -= entries - i;
556 complete(&io->complete);
557 spin_unlock_irq(&io->lock);
559 /* OK, yes, this could be packaged as non-blocking.
560 * So could the submit loop above ... but it's easier to
561 * solve neither problem than to solve both!
563 wait_for_completion(&io->complete);
567 EXPORT_SYMBOL_GPL(usb_sg_wait);
570 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
571 * @io: request block, initialized with usb_sg_init()
573 * This stops a request after it has been started by usb_sg_wait().
574 * It can also prevents one initialized by usb_sg_init() from starting,
575 * so that call just frees resources allocated to the request.
577 void usb_sg_cancel(struct usb_sg_request *io)
582 spin_lock_irqsave(&io->lock, flags);
584 spin_unlock_irqrestore(&io->lock, flags);
587 /* shut everything down */
588 io->status = -ECONNRESET;
589 spin_unlock_irqrestore(&io->lock, flags);
591 for (i = io->entries - 1; i >= 0; --i) {
592 usb_block_urb(io->urbs[i]);
594 retval = usb_unlink_urb(io->urbs[i]);
595 if (retval != -EINPROGRESS
599 dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
603 EXPORT_SYMBOL_GPL(usb_sg_cancel);
605 /*-------------------------------------------------------------------*/
608 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
609 * @dev: the device whose descriptor is being retrieved
610 * @type: the descriptor type (USB_DT_*)
611 * @index: the number of the descriptor
612 * @buf: where to put the descriptor
613 * @size: how big is "buf"?
614 * Context: !in_interrupt ()
616 * Gets a USB descriptor. Convenience functions exist to simplify
617 * getting some types of descriptors. Use
618 * usb_get_string() or usb_string() for USB_DT_STRING.
619 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
620 * are part of the device structure.
621 * In addition to a number of USB-standard descriptors, some
622 * devices also use class-specific or vendor-specific descriptors.
624 * This call is synchronous, and may not be used in an interrupt context.
626 * Return: The number of bytes received on success, or else the status code
627 * returned by the underlying usb_control_msg() call.
629 int usb_get_descriptor(struct usb_device *dev, unsigned char type,
630 unsigned char index, void *buf, int size)
635 memset(buf, 0, size); /* Make sure we parse really received data */
637 for (i = 0; i < 3; ++i) {
638 /* retry on length 0 or error; some devices are flakey */
639 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
640 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
641 (type << 8) + index, 0, buf, size,
642 USB_CTRL_GET_TIMEOUT);
643 if (result <= 0 && result != -ETIMEDOUT)
645 if (result > 1 && ((u8 *)buf)[1] != type) {
653 EXPORT_SYMBOL_GPL(usb_get_descriptor);
656 * usb_get_string - gets a string descriptor
657 * @dev: the device whose string descriptor is being retrieved
658 * @langid: code for language chosen (from string descriptor zero)
659 * @index: the number of the descriptor
660 * @buf: where to put the string
661 * @size: how big is "buf"?
662 * Context: !in_interrupt ()
664 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
665 * in little-endian byte order).
666 * The usb_string() function will often be a convenient way to turn
667 * these strings into kernel-printable form.
669 * Strings may be referenced in device, configuration, interface, or other
670 * descriptors, and could also be used in vendor-specific ways.
672 * This call is synchronous, and may not be used in an interrupt context.
674 * Return: The number of bytes received on success, or else the status code
675 * returned by the underlying usb_control_msg() call.
677 static int usb_get_string(struct usb_device *dev, unsigned short langid,
678 unsigned char index, void *buf, int size)
683 for (i = 0; i < 3; ++i) {
684 /* retry on length 0 or stall; some devices are flakey */
685 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
686 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
687 (USB_DT_STRING << 8) + index, langid, buf, size,
688 USB_CTRL_GET_TIMEOUT);
689 if (result == 0 || result == -EPIPE)
691 if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
700 static void usb_try_string_workarounds(unsigned char *buf, int *length)
702 int newlength, oldlength = *length;
704 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
705 if (!isprint(buf[newlength]) || buf[newlength + 1])
714 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
715 unsigned int index, unsigned char *buf)
719 /* Try to read the string descriptor by asking for the maximum
720 * possible number of bytes */
721 if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
724 rc = usb_get_string(dev, langid, index, buf, 255);
726 /* If that failed try to read the descriptor length, then
727 * ask for just that many bytes */
729 rc = usb_get_string(dev, langid, index, buf, 2);
731 rc = usb_get_string(dev, langid, index, buf, buf[0]);
735 if (!buf[0] && !buf[1])
736 usb_try_string_workarounds(buf, &rc);
738 /* There might be extra junk at the end of the descriptor */
742 rc = rc - (rc & 1); /* force a multiple of two */
746 rc = (rc < 0 ? rc : -EINVAL);
751 static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
755 if (dev->have_langid)
758 if (dev->string_langid < 0)
761 err = usb_string_sub(dev, 0, 0, tbuf);
763 /* If the string was reported but is malformed, default to english
765 if (err == -ENODATA || (err > 0 && err < 4)) {
766 dev->string_langid = 0x0409;
767 dev->have_langid = 1;
769 "language id specifier not provided by device, defaulting to English\n");
773 /* In case of all other errors, we assume the device is not able to
774 * deal with strings at all. Set string_langid to -1 in order to
775 * prevent any string to be retrieved from the device */
777 dev_err(&dev->dev, "string descriptor 0 read error: %d\n",
779 dev->string_langid = -1;
783 /* always use the first langid listed */
784 dev->string_langid = tbuf[2] | (tbuf[3] << 8);
785 dev->have_langid = 1;
786 dev_dbg(&dev->dev, "default language 0x%04x\n",
792 * usb_string - returns UTF-8 version of a string descriptor
793 * @dev: the device whose string descriptor is being retrieved
794 * @index: the number of the descriptor
795 * @buf: where to put the string
796 * @size: how big is "buf"?
797 * Context: !in_interrupt ()
799 * This converts the UTF-16LE encoded strings returned by devices, from
800 * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
801 * that are more usable in most kernel contexts. Note that this function
802 * chooses strings in the first language supported by the device.
804 * This call is synchronous, and may not be used in an interrupt context.
806 * Return: length of the string (>= 0) or usb_control_msg status (< 0).
808 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
813 if (dev->state == USB_STATE_SUSPENDED)
814 return -EHOSTUNREACH;
815 if (size <= 0 || !buf || !index)
818 tbuf = kmalloc(256, GFP_NOIO);
822 err = usb_get_langid(dev, tbuf);
826 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
830 size--; /* leave room for trailing NULL char in output buffer */
831 err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
832 UTF16_LITTLE_ENDIAN, buf, size);
835 if (tbuf[1] != USB_DT_STRING)
837 "wrong descriptor type %02x for string %d (\"%s\")\n",
838 tbuf[1], index, buf);
844 EXPORT_SYMBOL_GPL(usb_string);
846 /* one UTF-8-encoded 16-bit character has at most three bytes */
847 #define MAX_USB_STRING_SIZE (127 * 3 + 1)
850 * usb_cache_string - read a string descriptor and cache it for later use
851 * @udev: the device whose string descriptor is being read
852 * @index: the descriptor index
854 * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
855 * or %NULL if the index is 0 or the string could not be read.
857 char *usb_cache_string(struct usb_device *udev, int index)
860 char *smallbuf = NULL;
866 buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
868 len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
870 smallbuf = kmalloc(++len, GFP_NOIO);
873 memcpy(smallbuf, buf, len);
881 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
882 * @dev: the device whose device descriptor is being updated
883 * @size: how much of the descriptor to read
884 * Context: !in_interrupt ()
886 * Updates the copy of the device descriptor stored in the device structure,
887 * which dedicates space for this purpose.
889 * Not exported, only for use by the core. If drivers really want to read
890 * the device descriptor directly, they can call usb_get_descriptor() with
891 * type = USB_DT_DEVICE and index = 0.
893 * This call is synchronous, and may not be used in an interrupt context.
895 * Return: The number of bytes received on success, or else the status code
896 * returned by the underlying usb_control_msg() call.
898 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
900 struct usb_device_descriptor *desc;
903 if (size > sizeof(*desc))
905 desc = kmalloc(sizeof(*desc), GFP_NOIO);
909 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
911 memcpy(&dev->descriptor, desc, size);
917 * usb_get_status - issues a GET_STATUS call
918 * @dev: the device whose status is being checked
919 * @type: USB_RECIP_*; for device, interface, or endpoint
920 * @target: zero (for device), else interface or endpoint number
921 * @data: pointer to two bytes of bitmap data
922 * Context: !in_interrupt ()
924 * Returns device, interface, or endpoint status. Normally only of
925 * interest to see if the device is self powered, or has enabled the
926 * remote wakeup facility; or whether a bulk or interrupt endpoint
927 * is halted ("stalled").
929 * Bits in these status bitmaps are set using the SET_FEATURE request,
930 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
931 * function should be used to clear halt ("stall") status.
933 * This call is synchronous, and may not be used in an interrupt context.
935 * Returns 0 and the status value in *@data (in host byte order) on success,
936 * or else the status code from the underlying usb_control_msg() call.
938 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
941 __le16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
946 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
947 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
948 sizeof(*status), USB_CTRL_GET_TIMEOUT);
951 *(u16 *) data = le16_to_cpu(*status);
953 } else if (ret >= 0) {
959 EXPORT_SYMBOL_GPL(usb_get_status);
962 * usb_clear_halt - tells device to clear endpoint halt/stall condition
963 * @dev: device whose endpoint is halted
964 * @pipe: endpoint "pipe" being cleared
965 * Context: !in_interrupt ()
967 * This is used to clear halt conditions for bulk and interrupt endpoints,
968 * as reported by URB completion status. Endpoints that are halted are
969 * sometimes referred to as being "stalled". Such endpoints are unable
970 * to transmit or receive data until the halt status is cleared. Any URBs
971 * queued for such an endpoint should normally be unlinked by the driver
972 * before clearing the halt condition, as described in sections 5.7.5
973 * and 5.8.5 of the USB 2.0 spec.
975 * Note that control and isochronous endpoints don't halt, although control
976 * endpoints report "protocol stall" (for unsupported requests) using the
977 * same status code used to report a true stall.
979 * This call is synchronous, and may not be used in an interrupt context.
981 * Return: Zero on success, or else the status code returned by the
982 * underlying usb_control_msg() call.
984 int usb_clear_halt(struct usb_device *dev, int pipe)
987 int endp = usb_pipeendpoint(pipe);
989 if (usb_pipein(pipe))
992 /* we don't care if it wasn't halted first. in fact some devices
993 * (like some ibmcam model 1 units) seem to expect hosts to make
994 * this request for iso endpoints, which can't halt!
996 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
997 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
998 USB_ENDPOINT_HALT, endp, NULL, 0,
999 USB_CTRL_SET_TIMEOUT);
1001 /* don't un-halt or force to DATA0 except on success */
1005 /* NOTE: seems like Microsoft and Apple don't bother verifying
1006 * the clear "took", so some devices could lock up if you check...
1007 * such as the Hagiwara FlashGate DUAL. So we won't bother.
1009 * NOTE: make sure the logic here doesn't diverge much from
1010 * the copy in usb-storage, for as long as we need two copies.
1013 usb_reset_endpoint(dev, endp);
1017 EXPORT_SYMBOL_GPL(usb_clear_halt);
1019 static int create_intf_ep_devs(struct usb_interface *intf)
1021 struct usb_device *udev = interface_to_usbdev(intf);
1022 struct usb_host_interface *alt = intf->cur_altsetting;
1025 if (intf->ep_devs_created || intf->unregistering)
1028 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1029 (void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
1030 intf->ep_devs_created = 1;
1034 static void remove_intf_ep_devs(struct usb_interface *intf)
1036 struct usb_host_interface *alt = intf->cur_altsetting;
1039 if (!intf->ep_devs_created)
1042 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1043 usb_remove_ep_devs(&alt->endpoint[i]);
1044 intf->ep_devs_created = 0;
1048 * usb_disable_endpoint -- Disable an endpoint by address
1049 * @dev: the device whose endpoint is being disabled
1050 * @epaddr: the endpoint's address. Endpoint number for output,
1051 * endpoint number + USB_DIR_IN for input
1052 * @reset_hardware: flag to erase any endpoint state stored in the
1053 * controller hardware
1055 * Disables the endpoint for URB submission and nukes all pending URBs.
1056 * If @reset_hardware is set then also deallocates hcd/hardware state
1059 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
1060 bool reset_hardware)
1062 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1063 struct usb_host_endpoint *ep;
1068 if (usb_endpoint_out(epaddr)) {
1069 ep = dev->ep_out[epnum];
1071 dev->ep_out[epnum] = NULL;
1073 ep = dev->ep_in[epnum];
1075 dev->ep_in[epnum] = NULL;
1079 usb_hcd_flush_endpoint(dev, ep);
1081 usb_hcd_disable_endpoint(dev, ep);
1086 * usb_reset_endpoint - Reset an endpoint's state.
1087 * @dev: the device whose endpoint is to be reset
1088 * @epaddr: the endpoint's address. Endpoint number for output,
1089 * endpoint number + USB_DIR_IN for input
1091 * Resets any host-side endpoint state such as the toggle bit,
1092 * sequence number or current window.
1094 void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
1096 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1097 struct usb_host_endpoint *ep;
1099 if (usb_endpoint_out(epaddr))
1100 ep = dev->ep_out[epnum];
1102 ep = dev->ep_in[epnum];
1104 usb_hcd_reset_endpoint(dev, ep);
1106 EXPORT_SYMBOL_GPL(usb_reset_endpoint);
1110 * usb_disable_interface -- Disable all endpoints for an interface
1111 * @dev: the device whose interface is being disabled
1112 * @intf: pointer to the interface descriptor
1113 * @reset_hardware: flag to erase any endpoint state stored in the
1114 * controller hardware
1116 * Disables all the endpoints for the interface's current altsetting.
1118 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
1119 bool reset_hardware)
1121 struct usb_host_interface *alt = intf->cur_altsetting;
1124 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1125 usb_disable_endpoint(dev,
1126 alt->endpoint[i].desc.bEndpointAddress,
1132 * usb_disable_device - Disable all the endpoints for a USB device
1133 * @dev: the device whose endpoints are being disabled
1134 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1136 * Disables all the device's endpoints, potentially including endpoint 0.
1137 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1138 * pending urbs) and usbcore state for the interfaces, so that usbcore
1139 * must usb_set_configuration() before any interfaces could be used.
1141 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1144 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1146 /* getting rid of interfaces will disconnect
1147 * any drivers bound to them (a key side effect)
1149 if (dev->actconfig) {
1151 * FIXME: In order to avoid self-deadlock involving the
1152 * bandwidth_mutex, we have to mark all the interfaces
1153 * before unregistering any of them.
1155 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
1156 dev->actconfig->interface[i]->unregistering = 1;
1158 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1159 struct usb_interface *interface;
1161 /* remove this interface if it has been registered */
1162 interface = dev->actconfig->interface[i];
1163 if (!device_is_registered(&interface->dev))
1165 dev_dbg(&dev->dev, "unregistering interface %s\n",
1166 dev_name(&interface->dev));
1167 remove_intf_ep_devs(interface);
1168 device_del(&interface->dev);
1171 /* Now that the interfaces are unbound, nobody should
1172 * try to access them.
1174 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1175 put_device(&dev->actconfig->interface[i]->dev);
1176 dev->actconfig->interface[i] = NULL;
1179 if (dev->usb2_hw_lpm_enabled == 1)
1180 usb_set_usb2_hardware_lpm(dev, 0);
1181 usb_unlocked_disable_lpm(dev);
1182 usb_disable_ltm(dev);
1184 dev->actconfig = NULL;
1185 if (dev->state == USB_STATE_CONFIGURED)
1186 usb_set_device_state(dev, USB_STATE_ADDRESS);
1189 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
1190 skip_ep0 ? "non-ep0" : "all");
1191 if (hcd->driver->check_bandwidth) {
1192 /* First pass: Cancel URBs, leave endpoint pointers intact. */
1193 for (i = skip_ep0; i < 16; ++i) {
1194 usb_disable_endpoint(dev, i, false);
1195 usb_disable_endpoint(dev, i + USB_DIR_IN, false);
1197 /* Remove endpoints from the host controller internal state */
1198 mutex_lock(hcd->bandwidth_mutex);
1199 usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1200 mutex_unlock(hcd->bandwidth_mutex);
1201 /* Second pass: remove endpoint pointers */
1203 for (i = skip_ep0; i < 16; ++i) {
1204 usb_disable_endpoint(dev, i, true);
1205 usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1210 * usb_enable_endpoint - Enable an endpoint for USB communications
1211 * @dev: the device whose interface is being enabled
1213 * @reset_ep: flag to reset the endpoint state
1215 * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
1216 * For control endpoints, both the input and output sides are handled.
1218 void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
1221 int epnum = usb_endpoint_num(&ep->desc);
1222 int is_out = usb_endpoint_dir_out(&ep->desc);
1223 int is_control = usb_endpoint_xfer_control(&ep->desc);
1226 usb_hcd_reset_endpoint(dev, ep);
1227 if (is_out || is_control)
1228 dev->ep_out[epnum] = ep;
1229 if (!is_out || is_control)
1230 dev->ep_in[epnum] = ep;
1235 * usb_enable_interface - Enable all the endpoints for an interface
1236 * @dev: the device whose interface is being enabled
1237 * @intf: pointer to the interface descriptor
1238 * @reset_eps: flag to reset the endpoints' state
1240 * Enables all the endpoints for the interface's current altsetting.
1242 void usb_enable_interface(struct usb_device *dev,
1243 struct usb_interface *intf, bool reset_eps)
1245 struct usb_host_interface *alt = intf->cur_altsetting;
1248 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1249 usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
1253 * usb_set_interface - Makes a particular alternate setting be current
1254 * @dev: the device whose interface is being updated
1255 * @interface: the interface being updated
1256 * @alternate: the setting being chosen.
1257 * Context: !in_interrupt ()
1259 * This is used to enable data transfers on interfaces that may not
1260 * be enabled by default. Not all devices support such configurability.
1261 * Only the driver bound to an interface may change its setting.
1263 * Within any given configuration, each interface may have several
1264 * alternative settings. These are often used to control levels of
1265 * bandwidth consumption. For example, the default setting for a high
1266 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1267 * while interrupt transfers of up to 3KBytes per microframe are legal.
1268 * Also, isochronous endpoints may never be part of an
1269 * interface's default setting. To access such bandwidth, alternate
1270 * interface settings must be made current.
1272 * Note that in the Linux USB subsystem, bandwidth associated with
1273 * an endpoint in a given alternate setting is not reserved until an URB
1274 * is submitted that needs that bandwidth. Some other operating systems
1275 * allocate bandwidth early, when a configuration is chosen.
1277 * This call is synchronous, and may not be used in an interrupt context.
1278 * Also, drivers must not change altsettings while urbs are scheduled for
1279 * endpoints in that interface; all such urbs must first be completed
1280 * (perhaps forced by unlinking).
1282 * Return: Zero on success, or else the status code returned by the
1283 * underlying usb_control_msg() call.
1285 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1287 struct usb_interface *iface;
1288 struct usb_host_interface *alt;
1289 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1290 int i, ret, manual = 0;
1291 unsigned int epaddr;
1294 if (dev->state == USB_STATE_SUSPENDED)
1295 return -EHOSTUNREACH;
1297 iface = usb_ifnum_to_if(dev, interface);
1299 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1303 if (iface->unregistering)
1306 alt = usb_altnum_to_altsetting(iface, alternate);
1308 dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
1313 /* Make sure we have enough bandwidth for this alternate interface.
1314 * Remove the current alt setting and add the new alt setting.
1316 mutex_lock(hcd->bandwidth_mutex);
1317 /* Disable LPM, and re-enable it once the new alt setting is installed,
1318 * so that the xHCI driver can recalculate the U1/U2 timeouts.
1320 if (usb_disable_lpm(dev)) {
1321 dev_err(&iface->dev, "%s Failed to disable LPM\n.", __func__);
1322 mutex_unlock(hcd->bandwidth_mutex);
1325 /* Changing alt-setting also frees any allocated streams */
1326 for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
1327 iface->cur_altsetting->endpoint[i].streams = 0;
1329 ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
1331 dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
1333 usb_enable_lpm(dev);
1334 mutex_unlock(hcd->bandwidth_mutex);
1338 if (dev->quirks & USB_QUIRK_NO_SET_INTF)
1341 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1342 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1343 alternate, interface, NULL, 0, 5000);
1345 /* 9.4.10 says devices don't need this and are free to STALL the
1346 * request if the interface only has one alternate setting.
1348 if (ret == -EPIPE && iface->num_altsetting == 1) {
1350 "manual set_interface for iface %d, alt %d\n",
1351 interface, alternate);
1353 } else if (ret < 0) {
1354 /* Re-instate the old alt setting */
1355 usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
1356 usb_enable_lpm(dev);
1357 mutex_unlock(hcd->bandwidth_mutex);
1360 mutex_unlock(hcd->bandwidth_mutex);
1362 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1363 * when they implement async or easily-killable versions of this or
1364 * other "should-be-internal" functions (like clear_halt).
1365 * should hcd+usbcore postprocess control requests?
1368 /* prevent submissions using previous endpoint settings */
1369 if (iface->cur_altsetting != alt) {
1370 remove_intf_ep_devs(iface);
1371 usb_remove_sysfs_intf_files(iface);
1373 usb_disable_interface(dev, iface, true);
1375 iface->cur_altsetting = alt;
1377 /* Now that the interface is installed, re-enable LPM. */
1378 usb_unlocked_enable_lpm(dev);
1380 /* If the interface only has one altsetting and the device didn't
1381 * accept the request, we attempt to carry out the equivalent action
1382 * by manually clearing the HALT feature for each endpoint in the
1386 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1387 epaddr = alt->endpoint[i].desc.bEndpointAddress;
1388 pipe = __create_pipe(dev,
1389 USB_ENDPOINT_NUMBER_MASK & epaddr) |
1390 (usb_endpoint_out(epaddr) ?
1391 USB_DIR_OUT : USB_DIR_IN);
1393 usb_clear_halt(dev, pipe);
1397 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1400 * Despite EP0 is always present in all interfaces/AS, the list of
1401 * endpoints from the descriptor does not contain EP0. Due to its
1402 * omnipresence one might expect EP0 being considered "affected" by
1403 * any SetInterface request and hence assume toggles need to be reset.
1404 * However, EP0 toggles are re-synced for every individual transfer
1405 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1406 * (Likewise, EP0 never "halts" on well designed devices.)
1408 usb_enable_interface(dev, iface, true);
1409 if (device_is_registered(&iface->dev)) {
1410 usb_create_sysfs_intf_files(iface);
1411 create_intf_ep_devs(iface);
1415 EXPORT_SYMBOL_GPL(usb_set_interface);
1418 * usb_reset_configuration - lightweight device reset
1419 * @dev: the device whose configuration is being reset
1421 * This issues a standard SET_CONFIGURATION request to the device using
1422 * the current configuration. The effect is to reset most USB-related
1423 * state in the device, including interface altsettings (reset to zero),
1424 * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
1425 * endpoints). Other usbcore state is unchanged, including bindings of
1426 * usb device drivers to interfaces.
1428 * Because this affects multiple interfaces, avoid using this with composite
1429 * (multi-interface) devices. Instead, the driver for each interface may
1430 * use usb_set_interface() on the interfaces it claims. Be careful though;
1431 * some devices don't support the SET_INTERFACE request, and others won't
1432 * reset all the interface state (notably endpoint state). Resetting the whole
1433 * configuration would affect other drivers' interfaces.
1435 * The caller must own the device lock.
1437 * Return: Zero on success, else a negative error code.
1439 int usb_reset_configuration(struct usb_device *dev)
1442 struct usb_host_config *config;
1443 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1445 if (dev->state == USB_STATE_SUSPENDED)
1446 return -EHOSTUNREACH;
1448 /* caller must have locked the device and must own
1449 * the usb bus readlock (so driver bindings are stable);
1450 * calls during probe() are fine
1453 for (i = 1; i < 16; ++i) {
1454 usb_disable_endpoint(dev, i, true);
1455 usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1458 config = dev->actconfig;
1460 mutex_lock(hcd->bandwidth_mutex);
1461 /* Disable LPM, and re-enable it once the configuration is reset, so
1462 * that the xHCI driver can recalculate the U1/U2 timeouts.
1464 if (usb_disable_lpm(dev)) {
1465 dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
1466 mutex_unlock(hcd->bandwidth_mutex);
1469 /* Make sure we have enough bandwidth for each alternate setting 0 */
1470 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1471 struct usb_interface *intf = config->interface[i];
1472 struct usb_host_interface *alt;
1474 alt = usb_altnum_to_altsetting(intf, 0);
1476 alt = &intf->altsetting[0];
1477 if (alt != intf->cur_altsetting)
1478 retval = usb_hcd_alloc_bandwidth(dev, NULL,
1479 intf->cur_altsetting, alt);
1483 /* If not, reinstate the old alternate settings */
1486 for (i--; i >= 0; i--) {
1487 struct usb_interface *intf = config->interface[i];
1488 struct usb_host_interface *alt;
1490 alt = usb_altnum_to_altsetting(intf, 0);
1492 alt = &intf->altsetting[0];
1493 if (alt != intf->cur_altsetting)
1494 usb_hcd_alloc_bandwidth(dev, NULL,
1495 alt, intf->cur_altsetting);
1497 usb_enable_lpm(dev);
1498 mutex_unlock(hcd->bandwidth_mutex);
1501 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1502 USB_REQ_SET_CONFIGURATION, 0,
1503 config->desc.bConfigurationValue, 0,
1504 NULL, 0, USB_CTRL_SET_TIMEOUT);
1506 goto reset_old_alts;
1507 mutex_unlock(hcd->bandwidth_mutex);
1509 /* re-init hc/hcd interface/endpoint state */
1510 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1511 struct usb_interface *intf = config->interface[i];
1512 struct usb_host_interface *alt;
1514 alt = usb_altnum_to_altsetting(intf, 0);
1516 /* No altsetting 0? We'll assume the first altsetting.
1517 * We could use a GetInterface call, but if a device is
1518 * so non-compliant that it doesn't have altsetting 0
1519 * then I wouldn't trust its reply anyway.
1522 alt = &intf->altsetting[0];
1524 if (alt != intf->cur_altsetting) {
1525 remove_intf_ep_devs(intf);
1526 usb_remove_sysfs_intf_files(intf);
1528 intf->cur_altsetting = alt;
1529 usb_enable_interface(dev, intf, true);
1530 if (device_is_registered(&intf->dev)) {
1531 usb_create_sysfs_intf_files(intf);
1532 create_intf_ep_devs(intf);
1535 /* Now that the interfaces are installed, re-enable LPM. */
1536 usb_unlocked_enable_lpm(dev);
1539 EXPORT_SYMBOL_GPL(usb_reset_configuration);
1541 static void usb_release_interface(struct device *dev)
1543 struct usb_interface *intf = to_usb_interface(dev);
1544 struct usb_interface_cache *intfc =
1545 altsetting_to_usb_interface_cache(intf->altsetting);
1547 kref_put(&intfc->ref, usb_release_interface_cache);
1548 usb_put_dev(interface_to_usbdev(intf));
1553 * usb_deauthorize_interface - deauthorize an USB interface
1555 * @intf: USB interface structure
1557 void usb_deauthorize_interface(struct usb_interface *intf)
1559 struct device *dev = &intf->dev;
1561 device_lock(dev->parent);
1563 if (intf->authorized) {
1565 intf->authorized = 0;
1568 usb_forced_unbind_intf(intf);
1571 device_unlock(dev->parent);
1575 * usb_authorize_interface - authorize an USB interface
1577 * @intf: USB interface structure
1579 void usb_authorize_interface(struct usb_interface *intf)
1581 struct device *dev = &intf->dev;
1583 if (!intf->authorized) {
1585 intf->authorized = 1; /* authorize interface */
1590 static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1592 struct usb_device *usb_dev;
1593 struct usb_interface *intf;
1594 struct usb_host_interface *alt;
1596 intf = to_usb_interface(dev);
1597 usb_dev = interface_to_usbdev(intf);
1598 alt = intf->cur_altsetting;
1600 if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
1601 alt->desc.bInterfaceClass,
1602 alt->desc.bInterfaceSubClass,
1603 alt->desc.bInterfaceProtocol))
1606 if (add_uevent_var(env,
1608 "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
1609 le16_to_cpu(usb_dev->descriptor.idVendor),
1610 le16_to_cpu(usb_dev->descriptor.idProduct),
1611 le16_to_cpu(usb_dev->descriptor.bcdDevice),
1612 usb_dev->descriptor.bDeviceClass,
1613 usb_dev->descriptor.bDeviceSubClass,
1614 usb_dev->descriptor.bDeviceProtocol,
1615 alt->desc.bInterfaceClass,
1616 alt->desc.bInterfaceSubClass,
1617 alt->desc.bInterfaceProtocol,
1618 alt->desc.bInterfaceNumber))
1624 struct device_type usb_if_device_type = {
1625 .name = "usb_interface",
1626 .release = usb_release_interface,
1627 .uevent = usb_if_uevent,
1630 static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1631 struct usb_host_config *config,
1634 struct usb_interface_assoc_descriptor *retval = NULL;
1635 struct usb_interface_assoc_descriptor *intf_assoc;
1640 for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
1641 intf_assoc = config->intf_assoc[i];
1642 if (intf_assoc->bInterfaceCount == 0)
1645 first_intf = intf_assoc->bFirstInterface;
1646 last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
1647 if (inum >= first_intf && inum <= last_intf) {
1649 retval = intf_assoc;
1651 dev_err(&dev->dev, "Interface #%d referenced"
1652 " by multiple IADs\n", inum);
1661 * Internal function to queue a device reset
1662 * See usb_queue_reset_device() for more details
1664 static void __usb_queue_reset_device(struct work_struct *ws)
1667 struct usb_interface *iface =
1668 container_of(ws, struct usb_interface, reset_ws);
1669 struct usb_device *udev = interface_to_usbdev(iface);
1671 rc = usb_lock_device_for_reset(udev, iface);
1673 usb_reset_device(udev);
1674 usb_unlock_device(udev);
1676 usb_put_intf(iface); /* Undo _get_ in usb_queue_reset_device() */
1681 * usb_set_configuration - Makes a particular device setting be current
1682 * @dev: the device whose configuration is being updated
1683 * @configuration: the configuration being chosen.
1684 * Context: !in_interrupt(), caller owns the device lock
1686 * This is used to enable non-default device modes. Not all devices
1687 * use this kind of configurability; many devices only have one
1690 * @configuration is the value of the configuration to be installed.
1691 * According to the USB spec (e.g. section 9.1.1.5), configuration values
1692 * must be non-zero; a value of zero indicates that the device in
1693 * unconfigured. However some devices erroneously use 0 as one of their
1694 * configuration values. To help manage such devices, this routine will
1695 * accept @configuration = -1 as indicating the device should be put in
1696 * an unconfigured state.
1698 * USB device configurations may affect Linux interoperability,
1699 * power consumption and the functionality available. For example,
1700 * the default configuration is limited to using 100mA of bus power,
1701 * so that when certain device functionality requires more power,
1702 * and the device is bus powered, that functionality should be in some
1703 * non-default device configuration. Other device modes may also be
1704 * reflected as configuration options, such as whether two ISDN
1705 * channels are available independently; and choosing between open
1706 * standard device protocols (like CDC) or proprietary ones.
1708 * Note that a non-authorized device (dev->authorized == 0) will only
1709 * be put in unconfigured mode.
1711 * Note that USB has an additional level of device configurability,
1712 * associated with interfaces. That configurability is accessed using
1713 * usb_set_interface().
1715 * This call is synchronous. The calling context must be able to sleep,
1716 * must own the device lock, and must not hold the driver model's USB
1717 * bus mutex; usb interface driver probe() methods cannot use this routine.
1719 * Returns zero on success, or else the status code returned by the
1720 * underlying call that failed. On successful completion, each interface
1721 * in the original device configuration has been destroyed, and each one
1722 * in the new configuration has been probed by all relevant usb device
1723 * drivers currently known to the kernel.
1725 int usb_set_configuration(struct usb_device *dev, int configuration)
1728 struct usb_host_config *cp = NULL;
1729 struct usb_interface **new_interfaces = NULL;
1730 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1733 if (dev->authorized == 0 || configuration == -1)
1736 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1737 if (dev->config[i].desc.bConfigurationValue ==
1739 cp = &dev->config[i];
1744 if ((!cp && configuration != 0))
1747 /* The USB spec says configuration 0 means unconfigured.
1748 * But if a device includes a configuration numbered 0,
1749 * we will accept it as a correctly configured state.
1750 * Use -1 if you really want to unconfigure the device.
1752 if (cp && configuration == 0)
1753 dev_warn(&dev->dev, "config 0 descriptor??\n");
1755 /* Allocate memory for new interfaces before doing anything else,
1756 * so that if we run out then nothing will have changed. */
1759 nintf = cp->desc.bNumInterfaces;
1760 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1762 if (!new_interfaces) {
1763 dev_err(&dev->dev, "Out of memory\n");
1767 for (; n < nintf; ++n) {
1768 new_interfaces[n] = kzalloc(
1769 sizeof(struct usb_interface),
1771 if (!new_interfaces[n]) {
1772 dev_err(&dev->dev, "Out of memory\n");
1776 kfree(new_interfaces[n]);
1777 kfree(new_interfaces);
1782 i = dev->bus_mA - usb_get_max_power(dev, cp);
1784 dev_warn(&dev->dev, "new config #%d exceeds power "
1789 /* Wake up the device so we can send it the Set-Config request */
1790 ret = usb_autoresume_device(dev);
1792 goto free_interfaces;
1794 /* if it's already configured, clear out old state first.
1795 * getting rid of old interfaces means unbinding their drivers.
1797 if (dev->state != USB_STATE_ADDRESS)
1798 usb_disable_device(dev, 1); /* Skip ep0 */
1800 /* Get rid of pending async Set-Config requests for this device */
1801 cancel_async_set_config(dev);
1803 /* Make sure we have bandwidth (and available HCD resources) for this
1804 * configuration. Remove endpoints from the schedule if we're dropping
1805 * this configuration to set configuration 0. After this point, the
1806 * host controller will not allow submissions to dropped endpoints. If
1807 * this call fails, the device state is unchanged.
1809 mutex_lock(hcd->bandwidth_mutex);
1810 /* Disable LPM, and re-enable it once the new configuration is
1811 * installed, so that the xHCI driver can recalculate the U1/U2
1814 if (dev->actconfig && usb_disable_lpm(dev)) {
1815 dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
1816 mutex_unlock(hcd->bandwidth_mutex);
1818 goto free_interfaces;
1820 ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
1823 usb_enable_lpm(dev);
1824 mutex_unlock(hcd->bandwidth_mutex);
1825 usb_autosuspend_device(dev);
1826 goto free_interfaces;
1830 * Initialize the new interface structures and the
1831 * hc/hcd/usbcore interface/endpoint state.
1833 for (i = 0; i < nintf; ++i) {
1834 struct usb_interface_cache *intfc;
1835 struct usb_interface *intf;
1836 struct usb_host_interface *alt;
1838 cp->interface[i] = intf = new_interfaces[i];
1839 intfc = cp->intf_cache[i];
1840 intf->altsetting = intfc->altsetting;
1841 intf->num_altsetting = intfc->num_altsetting;
1842 intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
1843 kref_get(&intfc->ref);
1845 alt = usb_altnum_to_altsetting(intf, 0);
1847 /* No altsetting 0? We'll assume the first altsetting.
1848 * We could use a GetInterface call, but if a device is
1849 * so non-compliant that it doesn't have altsetting 0
1850 * then I wouldn't trust its reply anyway.
1853 alt = &intf->altsetting[0];
1856 find_iad(dev, cp, alt->desc.bInterfaceNumber);
1857 intf->cur_altsetting = alt;
1858 usb_enable_interface(dev, intf, true);
1859 intf->dev.parent = &dev->dev;
1860 intf->dev.driver = NULL;
1861 intf->dev.bus = &usb_bus_type;
1862 intf->dev.type = &usb_if_device_type;
1863 intf->dev.groups = usb_interface_groups;
1864 intf->dev.dma_mask = dev->dev.dma_mask;
1865 INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
1867 device_initialize(&intf->dev);
1868 pm_runtime_no_callbacks(&intf->dev);
1869 dev_set_name(&intf->dev, "%d-%s:%d.%d",
1870 dev->bus->busnum, dev->devpath,
1871 configuration, alt->desc.bInterfaceNumber);
1874 kfree(new_interfaces);
1876 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1877 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1878 NULL, 0, USB_CTRL_SET_TIMEOUT);
1879 if (ret < 0 && cp) {
1881 * All the old state is gone, so what else can we do?
1882 * The device is probably useless now anyway.
1884 usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1885 for (i = 0; i < nintf; ++i) {
1886 usb_disable_interface(dev, cp->interface[i], true);
1887 put_device(&cp->interface[i]->dev);
1888 cp->interface[i] = NULL;
1893 dev->actconfig = cp;
1894 mutex_unlock(hcd->bandwidth_mutex);
1897 usb_set_device_state(dev, USB_STATE_ADDRESS);
1899 /* Leave LPM disabled while the device is unconfigured. */
1900 usb_autosuspend_device(dev);
1903 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1905 if (cp->string == NULL &&
1906 !(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
1907 cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
1909 /* Now that the interfaces are installed, re-enable LPM. */
1910 usb_unlocked_enable_lpm(dev);
1911 /* Enable LTM if it was turned off by usb_disable_device. */
1912 usb_enable_ltm(dev);
1914 /* Now that all the interfaces are set up, register them
1915 * to trigger binding of drivers to interfaces. probe()
1916 * routines may install different altsettings and may
1917 * claim() any interfaces not yet bound. Many class drivers
1918 * need that: CDC, audio, video, etc.
1920 for (i = 0; i < nintf; ++i) {
1921 struct usb_interface *intf = cp->interface[i];
1924 "adding %s (config #%d, interface %d)\n",
1925 dev_name(&intf->dev), configuration,
1926 intf->cur_altsetting->desc.bInterfaceNumber);
1927 device_enable_async_suspend(&intf->dev);
1928 ret = device_add(&intf->dev);
1930 dev_err(&dev->dev, "device_add(%s) --> %d\n",
1931 dev_name(&intf->dev), ret);
1934 create_intf_ep_devs(intf);
1937 usb_autosuspend_device(dev);
1940 EXPORT_SYMBOL_GPL(usb_set_configuration);
1942 static LIST_HEAD(set_config_list);
1943 static DEFINE_SPINLOCK(set_config_lock);
1945 struct set_config_request {
1946 struct usb_device *udev;
1948 struct work_struct work;
1949 struct list_head node;
1952 /* Worker routine for usb_driver_set_configuration() */
1953 static void driver_set_config_work(struct work_struct *work)
1955 struct set_config_request *req =
1956 container_of(work, struct set_config_request, work);
1957 struct usb_device *udev = req->udev;
1959 usb_lock_device(udev);
1960 spin_lock(&set_config_lock);
1961 list_del(&req->node);
1962 spin_unlock(&set_config_lock);
1964 if (req->config >= -1) /* Is req still valid? */
1965 usb_set_configuration(udev, req->config);
1966 usb_unlock_device(udev);
1971 /* Cancel pending Set-Config requests for a device whose configuration
1974 static void cancel_async_set_config(struct usb_device *udev)
1976 struct set_config_request *req;
1978 spin_lock(&set_config_lock);
1979 list_for_each_entry(req, &set_config_list, node) {
1980 if (req->udev == udev)
1981 req->config = -999; /* Mark as cancelled */
1983 spin_unlock(&set_config_lock);
1987 * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1988 * @udev: the device whose configuration is being updated
1989 * @config: the configuration being chosen.
1990 * Context: In process context, must be able to sleep
1992 * Device interface drivers are not allowed to change device configurations.
1993 * This is because changing configurations will destroy the interface the
1994 * driver is bound to and create new ones; it would be like a floppy-disk
1995 * driver telling the computer to replace the floppy-disk drive with a
1998 * Still, in certain specialized circumstances the need may arise. This
1999 * routine gets around the normal restrictions by using a work thread to
2000 * submit the change-config request.
2002 * Return: 0 if the request was successfully queued, error code otherwise.
2003 * The caller has no way to know whether the queued request will eventually
2006 int usb_driver_set_configuration(struct usb_device *udev, int config)
2008 struct set_config_request *req;
2010 req = kmalloc(sizeof(*req), GFP_KERNEL);
2014 req->config = config;
2015 INIT_WORK(&req->work, driver_set_config_work);
2017 spin_lock(&set_config_lock);
2018 list_add(&req->node, &set_config_list);
2019 spin_unlock(&set_config_lock);
2022 schedule_work(&req->work);
2025 EXPORT_SYMBOL_GPL(usb_driver_set_configuration);