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/cdc.h>
16 #include <linux/usb/quirks.h>
17 #include <linux/usb/hcd.h> /* for usbcore internals */
18 #include <asm/byteorder.h>
22 static void cancel_async_set_config(struct usb_device
*udev
);
25 struct completion done
;
29 static void usb_api_blocking_completion(struct urb
*urb
)
31 struct api_context
*ctx
= urb
->context
;
33 ctx
->status
= urb
->status
;
39 * Starts urb and waits for completion or timeout. Note that this call
40 * is NOT interruptible. Many device driver i/o requests should be
41 * interruptible and therefore these drivers should implement their
42 * own interruptible routines.
44 static int usb_start_wait_urb(struct urb
*urb
, int timeout
, int *actual_length
)
46 struct api_context ctx
;
50 init_completion(&ctx
.done
);
52 urb
->actual_length
= 0;
53 retval
= usb_submit_urb(urb
, GFP_NOIO
);
57 expire
= timeout
? msecs_to_jiffies(timeout
) : MAX_SCHEDULE_TIMEOUT
;
58 if (!wait_for_completion_timeout(&ctx
.done
, expire
)) {
60 retval
= (ctx
.status
== -ENOENT
? -ETIMEDOUT
: ctx
.status
);
62 dev_dbg(&urb
->dev
->dev
,
63 "%s timed out on ep%d%s len=%u/%u\n",
65 usb_endpoint_num(&urb
->ep
->desc
),
66 usb_urb_dir_in(urb
) ? "in" : "out",
68 urb
->transfer_buffer_length
);
73 *actual_length
= urb
->actual_length
;
79 /*-------------------------------------------------------------------*/
80 /* returns status (negative) or length (positive) */
81 static int usb_internal_control_msg(struct usb_device
*usb_dev
,
83 struct usb_ctrlrequest
*cmd
,
84 void *data
, int len
, int timeout
)
90 urb
= usb_alloc_urb(0, GFP_NOIO
);
94 usb_fill_control_urb(urb
, usb_dev
, pipe
, (unsigned char *)cmd
, data
,
95 len
, usb_api_blocking_completion
, NULL
);
97 retv
= usb_start_wait_urb(urb
, timeout
, &length
);
105 * usb_control_msg - Builds a control urb, sends it off and waits for completion
106 * @dev: pointer to the usb device to send the message to
107 * @pipe: endpoint "pipe" to send the message to
108 * @request: USB message request value
109 * @requesttype: USB message request type value
110 * @value: USB message value
111 * @index: USB message index value
112 * @data: pointer to the data to send
113 * @size: length in bytes of the data to send
114 * @timeout: time in msecs to wait for the message to complete before timing
115 * out (if 0 the wait is forever)
117 * Context: !in_interrupt ()
119 * This function sends a simple control message to a specified endpoint and
120 * waits for the message to complete, or timeout.
122 * Don't use this function from within an interrupt context, like a bottom half
123 * handler. If you need an asynchronous message, or need to send a message
124 * from within interrupt context, use usb_submit_urb().
125 * If a thread in your driver uses this call, make sure your disconnect()
126 * method can wait for it to complete. Since you don't have a handle on the
127 * URB used, you can't cancel the request.
129 * Return: If successful, the number of bytes transferred. Otherwise, a negative
132 int usb_control_msg(struct usb_device
*dev
, unsigned int pipe
, __u8 request
,
133 __u8 requesttype
, __u16 value
, __u16 index
, void *data
,
134 __u16 size
, int timeout
)
136 struct usb_ctrlrequest
*dr
;
139 dr
= kmalloc(sizeof(struct usb_ctrlrequest
), GFP_NOIO
);
143 dr
->bRequestType
= requesttype
;
144 dr
->bRequest
= request
;
145 dr
->wValue
= cpu_to_le16(value
);
146 dr
->wIndex
= cpu_to_le16(index
);
147 dr
->wLength
= cpu_to_le16(size
);
149 ret
= usb_internal_control_msg(dev
, pipe
, dr
, data
, size
, timeout
);
155 EXPORT_SYMBOL_GPL(usb_control_msg
);
158 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
159 * @usb_dev: pointer to the usb device to send the message to
160 * @pipe: endpoint "pipe" to send the message to
161 * @data: pointer to the data to send
162 * @len: length in bytes of the data to send
163 * @actual_length: pointer to a location to put the actual length transferred
165 * @timeout: time in msecs to wait for the message to complete before
166 * timing out (if 0 the wait is forever)
168 * Context: !in_interrupt ()
170 * This function sends a simple interrupt message to a specified endpoint and
171 * waits for the message to complete, or timeout.
173 * Don't use this function from within an interrupt context, like a bottom half
174 * handler. If you need an asynchronous message, or need to send a message
175 * from within interrupt context, use usb_submit_urb() If a thread in your
176 * driver uses this call, make sure your disconnect() method can wait for it to
177 * complete. Since you don't have a handle on the URB used, you can't cancel
181 * If successful, 0. Otherwise a negative error number. The number of actual
182 * bytes transferred will be stored in the @actual_length parameter.
184 int usb_interrupt_msg(struct usb_device
*usb_dev
, unsigned int pipe
,
185 void *data
, int len
, int *actual_length
, int timeout
)
187 return usb_bulk_msg(usb_dev
, pipe
, data
, len
, actual_length
, timeout
);
189 EXPORT_SYMBOL_GPL(usb_interrupt_msg
);
192 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
193 * @usb_dev: pointer to the usb device to send the message to
194 * @pipe: endpoint "pipe" to send the message to
195 * @data: pointer to the data to send
196 * @len: length in bytes of the data to send
197 * @actual_length: pointer to a location to put the actual length transferred
199 * @timeout: time in msecs to wait for the message to complete before
200 * timing out (if 0 the wait is forever)
202 * Context: !in_interrupt ()
204 * This function sends a simple bulk message to a specified endpoint
205 * and waits for the message to complete, or timeout.
207 * Don't use this function from within an interrupt context, like a bottom half
208 * handler. If you need an asynchronous message, or need to send a message
209 * from within interrupt context, use usb_submit_urb() If a thread in your
210 * driver uses this call, make sure your disconnect() method can wait for it to
211 * complete. Since you don't have a handle on the URB used, you can't cancel
214 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
215 * users are forced to abuse this routine by using it to submit URBs for
216 * interrupt endpoints. We will take the liberty of creating an interrupt URB
217 * (with the default interval) if the target is an interrupt endpoint.
220 * If successful, 0. Otherwise a negative error number. The number of actual
221 * bytes transferred will be stored in the @actual_length parameter.
224 int usb_bulk_msg(struct usb_device
*usb_dev
, unsigned int pipe
,
225 void *data
, int len
, int *actual_length
, int timeout
)
228 struct usb_host_endpoint
*ep
;
230 ep
= usb_pipe_endpoint(usb_dev
, pipe
);
234 urb
= usb_alloc_urb(0, GFP_KERNEL
);
238 if ((ep
->desc
.bmAttributes
& USB_ENDPOINT_XFERTYPE_MASK
) ==
239 USB_ENDPOINT_XFER_INT
) {
240 pipe
= (pipe
& ~(3 << 30)) | (PIPE_INTERRUPT
<< 30);
241 usb_fill_int_urb(urb
, usb_dev
, pipe
, data
, len
,
242 usb_api_blocking_completion
, NULL
,
245 usb_fill_bulk_urb(urb
, usb_dev
, pipe
, data
, len
,
246 usb_api_blocking_completion
, NULL
);
248 return usb_start_wait_urb(urb
, timeout
, actual_length
);
250 EXPORT_SYMBOL_GPL(usb_bulk_msg
);
252 /*-------------------------------------------------------------------*/
254 static void sg_clean(struct usb_sg_request
*io
)
257 while (io
->entries
--)
258 usb_free_urb(io
->urbs
[io
->entries
]);
265 static void sg_complete(struct urb
*urb
)
267 struct usb_sg_request
*io
= urb
->context
;
268 int status
= urb
->status
;
270 spin_lock(&io
->lock
);
272 /* In 2.5 we require hcds' endpoint queues not to progress after fault
273 * reports, until the completion callback (this!) returns. That lets
274 * device driver code (like this routine) unlink queued urbs first,
275 * if it needs to, since the HC won't work on them at all. So it's
276 * not possible for page N+1 to overwrite page N, and so on.
278 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
279 * complete before the HCD can get requests away from hardware,
280 * though never during cleanup after a hard fault.
283 && (io
->status
!= -ECONNRESET
284 || status
!= -ECONNRESET
)
285 && urb
->actual_length
) {
286 dev_err(io
->dev
->bus
->controller
,
287 "dev %s ep%d%s scatterlist error %d/%d\n",
289 usb_endpoint_num(&urb
->ep
->desc
),
290 usb_urb_dir_in(urb
) ? "in" : "out",
295 if (io
->status
== 0 && status
&& status
!= -ECONNRESET
) {
296 int i
, found
, retval
;
300 /* the previous urbs, and this one, completed already.
301 * unlink pending urbs so they won't rx/tx bad data.
302 * careful: unlink can sometimes be synchronous...
304 spin_unlock(&io
->lock
);
305 for (i
= 0, found
= 0; i
< io
->entries
; i
++) {
309 usb_block_urb(io
->urbs
[i
]);
310 retval
= usb_unlink_urb(io
->urbs
[i
]);
311 if (retval
!= -EINPROGRESS
&&
315 dev_err(&io
->dev
->dev
,
316 "%s, unlink --> %d\n",
318 } else if (urb
== io
->urbs
[i
])
321 spin_lock(&io
->lock
);
324 /* on the last completion, signal usb_sg_wait() */
325 io
->bytes
+= urb
->actual_length
;
328 complete(&io
->complete
);
330 spin_unlock(&io
->lock
);
335 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
336 * @io: request block being initialized. until usb_sg_wait() returns,
337 * treat this as a pointer to an opaque block of memory,
338 * @dev: the usb device that will send or receive the data
339 * @pipe: endpoint "pipe" used to transfer the data
340 * @period: polling rate for interrupt endpoints, in frames or
341 * (for high speed endpoints) microframes; ignored for bulk
342 * @sg: scatterlist entries
343 * @nents: how many entries in the scatterlist
344 * @length: how many bytes to send from the scatterlist, or zero to
345 * send every byte identified in the list.
346 * @mem_flags: SLAB_* flags affecting memory allocations in this call
348 * This initializes a scatter/gather request, allocating resources such as
349 * I/O mappings and urb memory (except maybe memory used by USB controller
352 * The request must be issued using usb_sg_wait(), which waits for the I/O to
353 * complete (or to be canceled) and then cleans up all resources allocated by
356 * The request may be canceled with usb_sg_cancel(), either before or after
357 * usb_sg_wait() is called.
359 * Return: Zero for success, else a negative errno value.
361 int usb_sg_init(struct usb_sg_request
*io
, struct usb_device
*dev
,
362 unsigned pipe
, unsigned period
, struct scatterlist
*sg
,
363 int nents
, size_t length
, gfp_t mem_flags
)
369 if (!io
|| !dev
|| !sg
370 || usb_pipecontrol(pipe
)
371 || usb_pipeisoc(pipe
)
375 spin_lock_init(&io
->lock
);
379 if (dev
->bus
->sg_tablesize
> 0) {
387 /* initialize all the urbs we'll use */
388 io
->urbs
= kmalloc(io
->entries
* sizeof(*io
->urbs
), mem_flags
);
392 urb_flags
= URB_NO_INTERRUPT
;
393 if (usb_pipein(pipe
))
394 urb_flags
|= URB_SHORT_NOT_OK
;
396 for_each_sg(sg
, sg
, io
->entries
, i
) {
400 urb
= usb_alloc_urb(0, mem_flags
);
409 urb
->interval
= period
;
410 urb
->transfer_flags
= urb_flags
;
411 urb
->complete
= sg_complete
;
416 /* There is no single transfer buffer */
417 urb
->transfer_buffer
= NULL
;
418 urb
->num_sgs
= nents
;
420 /* A length of zero means transfer the whole sg list */
423 struct scatterlist
*sg2
;
426 for_each_sg(sg
, sg2
, nents
, j
)
431 * Some systems can't use DMA; they use PIO instead.
432 * For their sakes, transfer_buffer is set whenever
435 if (!PageHighMem(sg_page(sg
)))
436 urb
->transfer_buffer
= sg_virt(sg
);
438 urb
->transfer_buffer
= NULL
;
442 len
= min_t(size_t, len
, length
);
448 urb
->transfer_buffer_length
= len
;
450 io
->urbs
[--i
]->transfer_flags
&= ~URB_NO_INTERRUPT
;
452 /* transaction state */
453 io
->count
= io
->entries
;
456 init_completion(&io
->complete
);
463 EXPORT_SYMBOL_GPL(usb_sg_init
);
466 * usb_sg_wait - synchronously execute scatter/gather request
467 * @io: request block handle, as initialized with usb_sg_init().
468 * some fields become accessible when this call returns.
469 * Context: !in_interrupt ()
471 * This function blocks until the specified I/O operation completes. It
472 * leverages the grouping of the related I/O requests to get good transfer
473 * rates, by queueing the requests. At higher speeds, such queuing can
474 * significantly improve USB throughput.
476 * There are three kinds of completion for this function.
477 * (1) success, where io->status is zero. The number of io->bytes
478 * transferred is as requested.
479 * (2) error, where io->status is a negative errno value. The number
480 * of io->bytes transferred before the error is usually less
481 * than requested, and can be nonzero.
482 * (3) cancellation, a type of error with status -ECONNRESET that
483 * is initiated by usb_sg_cancel().
485 * When this function returns, all memory allocated through usb_sg_init() or
486 * this call will have been freed. The request block parameter may still be
487 * passed to usb_sg_cancel(), or it may be freed. It could also be
488 * reinitialized and then reused.
490 * Data Transfer Rates:
492 * Bulk transfers are valid for full or high speed endpoints.
493 * The best full speed data rate is 19 packets of 64 bytes each
494 * per frame, or 1216 bytes per millisecond.
495 * The best high speed data rate is 13 packets of 512 bytes each
496 * per microframe, or 52 KBytes per millisecond.
498 * The reason to use interrupt transfers through this API would most likely
499 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
500 * could be transferred. That capability is less useful for low or full
501 * speed interrupt endpoints, which allow at most one packet per millisecond,
502 * of at most 8 or 64 bytes (respectively).
504 * It is not necessary to call this function to reserve bandwidth for devices
505 * under an xHCI host controller, as the bandwidth is reserved when the
506 * configuration or interface alt setting is selected.
508 void usb_sg_wait(struct usb_sg_request
*io
)
511 int entries
= io
->entries
;
513 /* queue the urbs. */
514 spin_lock_irq(&io
->lock
);
516 while (i
< entries
&& !io
->status
) {
519 io
->urbs
[i
]->dev
= io
->dev
;
520 spin_unlock_irq(&io
->lock
);
522 retval
= usb_submit_urb(io
->urbs
[i
], GFP_NOIO
);
525 /* maybe we retrying will recover */
526 case -ENXIO
: /* hc didn't queue this one */
533 /* no error? continue immediately.
535 * NOTE: to work better with UHCI (4K I/O buffer may
536 * need 3K of TDs) it may be good to limit how many
537 * URBs are queued at once; N milliseconds?
544 /* fail any uncompleted urbs */
546 io
->urbs
[i
]->status
= retval
;
547 dev_dbg(&io
->dev
->dev
, "%s, submit --> %d\n",
551 spin_lock_irq(&io
->lock
);
552 if (retval
&& (io
->status
== 0 || io
->status
== -ECONNRESET
))
555 io
->count
-= entries
- i
;
557 complete(&io
->complete
);
558 spin_unlock_irq(&io
->lock
);
560 /* OK, yes, this could be packaged as non-blocking.
561 * So could the submit loop above ... but it's easier to
562 * solve neither problem than to solve both!
564 wait_for_completion(&io
->complete
);
568 EXPORT_SYMBOL_GPL(usb_sg_wait
);
571 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
572 * @io: request block, initialized with usb_sg_init()
574 * This stops a request after it has been started by usb_sg_wait().
575 * It can also prevents one initialized by usb_sg_init() from starting,
576 * so that call just frees resources allocated to the request.
578 void usb_sg_cancel(struct usb_sg_request
*io
)
583 spin_lock_irqsave(&io
->lock
, flags
);
585 spin_unlock_irqrestore(&io
->lock
, flags
);
588 /* shut everything down */
589 io
->status
= -ECONNRESET
;
590 spin_unlock_irqrestore(&io
->lock
, flags
);
592 for (i
= io
->entries
- 1; i
>= 0; --i
) {
593 usb_block_urb(io
->urbs
[i
]);
595 retval
= usb_unlink_urb(io
->urbs
[i
]);
596 if (retval
!= -EINPROGRESS
600 dev_warn(&io
->dev
->dev
, "%s, unlink --> %d\n",
604 EXPORT_SYMBOL_GPL(usb_sg_cancel
);
606 /*-------------------------------------------------------------------*/
609 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
610 * @dev: the device whose descriptor is being retrieved
611 * @type: the descriptor type (USB_DT_*)
612 * @index: the number of the descriptor
613 * @buf: where to put the descriptor
614 * @size: how big is "buf"?
615 * Context: !in_interrupt ()
617 * Gets a USB descriptor. Convenience functions exist to simplify
618 * getting some types of descriptors. Use
619 * usb_get_string() or usb_string() for USB_DT_STRING.
620 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
621 * are part of the device structure.
622 * In addition to a number of USB-standard descriptors, some
623 * devices also use class-specific or vendor-specific descriptors.
625 * This call is synchronous, and may not be used in an interrupt context.
627 * Return: The number of bytes received on success, or else the status code
628 * returned by the underlying usb_control_msg() call.
630 int usb_get_descriptor(struct usb_device
*dev
, unsigned char type
,
631 unsigned char index
, void *buf
, int size
)
636 memset(buf
, 0, size
); /* Make sure we parse really received data */
638 for (i
= 0; i
< 3; ++i
) {
639 /* retry on length 0 or error; some devices are flakey */
640 result
= usb_control_msg(dev
, usb_rcvctrlpipe(dev
, 0),
641 USB_REQ_GET_DESCRIPTOR
, USB_DIR_IN
,
642 (type
<< 8) + index
, 0, buf
, size
,
643 USB_CTRL_GET_TIMEOUT
);
644 if (result
<= 0 && result
!= -ETIMEDOUT
)
646 if (result
> 1 && ((u8
*)buf
)[1] != type
) {
654 EXPORT_SYMBOL_GPL(usb_get_descriptor
);
657 * usb_get_string - gets a string descriptor
658 * @dev: the device whose string descriptor is being retrieved
659 * @langid: code for language chosen (from string descriptor zero)
660 * @index: the number of the descriptor
661 * @buf: where to put the string
662 * @size: how big is "buf"?
663 * Context: !in_interrupt ()
665 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
666 * in little-endian byte order).
667 * The usb_string() function will often be a convenient way to turn
668 * these strings into kernel-printable form.
670 * Strings may be referenced in device, configuration, interface, or other
671 * descriptors, and could also be used in vendor-specific ways.
673 * This call is synchronous, and may not be used in an interrupt context.
675 * Return: The number of bytes received on success, or else the status code
676 * returned by the underlying usb_control_msg() call.
678 static int usb_get_string(struct usb_device
*dev
, unsigned short langid
,
679 unsigned char index
, void *buf
, int size
)
684 for (i
= 0; i
< 3; ++i
) {
685 /* retry on length 0 or stall; some devices are flakey */
686 result
= usb_control_msg(dev
, usb_rcvctrlpipe(dev
, 0),
687 USB_REQ_GET_DESCRIPTOR
, USB_DIR_IN
,
688 (USB_DT_STRING
<< 8) + index
, langid
, buf
, size
,
689 USB_CTRL_GET_TIMEOUT
);
690 if (result
== 0 || result
== -EPIPE
)
692 if (result
> 1 && ((u8
*) buf
)[1] != USB_DT_STRING
) {
701 static void usb_try_string_workarounds(unsigned char *buf
, int *length
)
703 int newlength
, oldlength
= *length
;
705 for (newlength
= 2; newlength
+ 1 < oldlength
; newlength
+= 2)
706 if (!isprint(buf
[newlength
]) || buf
[newlength
+ 1])
715 static int usb_string_sub(struct usb_device
*dev
, unsigned int langid
,
716 unsigned int index
, unsigned char *buf
)
720 /* Try to read the string descriptor by asking for the maximum
721 * possible number of bytes */
722 if (dev
->quirks
& USB_QUIRK_STRING_FETCH_255
)
725 rc
= usb_get_string(dev
, langid
, index
, buf
, 255);
727 /* If that failed try to read the descriptor length, then
728 * ask for just that many bytes */
730 rc
= usb_get_string(dev
, langid
, index
, buf
, 2);
732 rc
= usb_get_string(dev
, langid
, index
, buf
, buf
[0]);
736 if (!buf
[0] && !buf
[1])
737 usb_try_string_workarounds(buf
, &rc
);
739 /* There might be extra junk at the end of the descriptor */
743 rc
= rc
- (rc
& 1); /* force a multiple of two */
747 rc
= (rc
< 0 ? rc
: -EINVAL
);
752 static int usb_get_langid(struct usb_device
*dev
, unsigned char *tbuf
)
756 if (dev
->have_langid
)
759 if (dev
->string_langid
< 0)
762 err
= usb_string_sub(dev
, 0, 0, tbuf
);
764 /* If the string was reported but is malformed, default to english
766 if (err
== -ENODATA
|| (err
> 0 && err
< 4)) {
767 dev
->string_langid
= 0x0409;
768 dev
->have_langid
= 1;
770 "language id specifier not provided by device, defaulting to English\n");
774 /* In case of all other errors, we assume the device is not able to
775 * deal with strings at all. Set string_langid to -1 in order to
776 * prevent any string to be retrieved from the device */
778 dev_err(&dev
->dev
, "string descriptor 0 read error: %d\n",
780 dev
->string_langid
= -1;
784 /* always use the first langid listed */
785 dev
->string_langid
= tbuf
[2] | (tbuf
[3] << 8);
786 dev
->have_langid
= 1;
787 dev_dbg(&dev
->dev
, "default language 0x%04x\n",
793 * usb_string - returns UTF-8 version of a string descriptor
794 * @dev: the device whose string descriptor is being retrieved
795 * @index: the number of the descriptor
796 * @buf: where to put the string
797 * @size: how big is "buf"?
798 * Context: !in_interrupt ()
800 * This converts the UTF-16LE encoded strings returned by devices, from
801 * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
802 * that are more usable in most kernel contexts. Note that this function
803 * chooses strings in the first language supported by the device.
805 * This call is synchronous, and may not be used in an interrupt context.
807 * Return: length of the string (>= 0) or usb_control_msg status (< 0).
809 int usb_string(struct usb_device
*dev
, int index
, char *buf
, size_t size
)
814 if (dev
->state
== USB_STATE_SUSPENDED
)
815 return -EHOSTUNREACH
;
816 if (size
<= 0 || !buf
|| !index
)
819 tbuf
= kmalloc(256, GFP_NOIO
);
823 err
= usb_get_langid(dev
, tbuf
);
827 err
= usb_string_sub(dev
, dev
->string_langid
, index
, tbuf
);
831 size
--; /* leave room for trailing NULL char in output buffer */
832 err
= utf16s_to_utf8s((wchar_t *) &tbuf
[2], (err
- 2) / 2,
833 UTF16_LITTLE_ENDIAN
, buf
, size
);
836 if (tbuf
[1] != USB_DT_STRING
)
838 "wrong descriptor type %02x for string %d (\"%s\")\n",
839 tbuf
[1], index
, buf
);
845 EXPORT_SYMBOL_GPL(usb_string
);
847 /* one UTF-8-encoded 16-bit character has at most three bytes */
848 #define MAX_USB_STRING_SIZE (127 * 3 + 1)
851 * usb_cache_string - read a string descriptor and cache it for later use
852 * @udev: the device whose string descriptor is being read
853 * @index: the descriptor index
855 * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
856 * or %NULL if the index is 0 or the string could not be read.
858 char *usb_cache_string(struct usb_device
*udev
, int index
)
861 char *smallbuf
= NULL
;
867 buf
= kmalloc(MAX_USB_STRING_SIZE
, GFP_NOIO
);
869 len
= usb_string(udev
, index
, buf
, MAX_USB_STRING_SIZE
);
871 smallbuf
= kmalloc(++len
, GFP_NOIO
);
874 memcpy(smallbuf
, buf
, len
);
882 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
883 * @dev: the device whose device descriptor is being updated
884 * @size: how much of the descriptor to read
885 * Context: !in_interrupt ()
887 * Updates the copy of the device descriptor stored in the device structure,
888 * which dedicates space for this purpose.
890 * Not exported, only for use by the core. If drivers really want to read
891 * the device descriptor directly, they can call usb_get_descriptor() with
892 * type = USB_DT_DEVICE and index = 0.
894 * This call is synchronous, and may not be used in an interrupt context.
896 * Return: The number of bytes received on success, or else the status code
897 * returned by the underlying usb_control_msg() call.
899 int usb_get_device_descriptor(struct usb_device
*dev
, unsigned int size
)
901 struct usb_device_descriptor
*desc
;
904 if (size
> sizeof(*desc
))
906 desc
= kmalloc(sizeof(*desc
), GFP_NOIO
);
910 ret
= usb_get_descriptor(dev
, USB_DT_DEVICE
, 0, desc
, size
);
912 memcpy(&dev
->descriptor
, desc
, size
);
918 * usb_get_status - issues a GET_STATUS call
919 * @dev: the device whose status is being checked
920 * @type: USB_RECIP_*; for device, interface, or endpoint
921 * @target: zero (for device), else interface or endpoint number
922 * @data: pointer to two bytes of bitmap data
923 * Context: !in_interrupt ()
925 * Returns device, interface, or endpoint status. Normally only of
926 * interest to see if the device is self powered, or has enabled the
927 * remote wakeup facility; or whether a bulk or interrupt endpoint
928 * is halted ("stalled").
930 * Bits in these status bitmaps are set using the SET_FEATURE request,
931 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
932 * function should be used to clear halt ("stall") status.
934 * This call is synchronous, and may not be used in an interrupt context.
936 * Returns 0 and the status value in *@data (in host byte order) on success,
937 * or else the status code from the underlying usb_control_msg() call.
939 int usb_get_status(struct usb_device
*dev
, int type
, int target
, void *data
)
942 __le16
*status
= kmalloc(sizeof(*status
), GFP_KERNEL
);
947 ret
= usb_control_msg(dev
, usb_rcvctrlpipe(dev
, 0),
948 USB_REQ_GET_STATUS
, USB_DIR_IN
| type
, 0, target
, status
,
949 sizeof(*status
), USB_CTRL_GET_TIMEOUT
);
952 *(u16
*) data
= le16_to_cpu(*status
);
954 } else if (ret
>= 0) {
960 EXPORT_SYMBOL_GPL(usb_get_status
);
963 * usb_clear_halt - tells device to clear endpoint halt/stall condition
964 * @dev: device whose endpoint is halted
965 * @pipe: endpoint "pipe" being cleared
966 * Context: !in_interrupt ()
968 * This is used to clear halt conditions for bulk and interrupt endpoints,
969 * as reported by URB completion status. Endpoints that are halted are
970 * sometimes referred to as being "stalled". Such endpoints are unable
971 * to transmit or receive data until the halt status is cleared. Any URBs
972 * queued for such an endpoint should normally be unlinked by the driver
973 * before clearing the halt condition, as described in sections 5.7.5
974 * and 5.8.5 of the USB 2.0 spec.
976 * Note that control and isochronous endpoints don't halt, although control
977 * endpoints report "protocol stall" (for unsupported requests) using the
978 * same status code used to report a true stall.
980 * This call is synchronous, and may not be used in an interrupt context.
982 * Return: Zero on success, or else the status code returned by the
983 * underlying usb_control_msg() call.
985 int usb_clear_halt(struct usb_device
*dev
, int pipe
)
988 int endp
= usb_pipeendpoint(pipe
);
990 if (usb_pipein(pipe
))
993 /* we don't care if it wasn't halted first. in fact some devices
994 * (like some ibmcam model 1 units) seem to expect hosts to make
995 * this request for iso endpoints, which can't halt!
997 result
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
998 USB_REQ_CLEAR_FEATURE
, USB_RECIP_ENDPOINT
,
999 USB_ENDPOINT_HALT
, endp
, NULL
, 0,
1000 USB_CTRL_SET_TIMEOUT
);
1002 /* don't un-halt or force to DATA0 except on success */
1006 /* NOTE: seems like Microsoft and Apple don't bother verifying
1007 * the clear "took", so some devices could lock up if you check...
1008 * such as the Hagiwara FlashGate DUAL. So we won't bother.
1010 * NOTE: make sure the logic here doesn't diverge much from
1011 * the copy in usb-storage, for as long as we need two copies.
1014 usb_reset_endpoint(dev
, endp
);
1018 EXPORT_SYMBOL_GPL(usb_clear_halt
);
1020 static int create_intf_ep_devs(struct usb_interface
*intf
)
1022 struct usb_device
*udev
= interface_to_usbdev(intf
);
1023 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
1026 if (intf
->ep_devs_created
|| intf
->unregistering
)
1029 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
)
1030 (void) usb_create_ep_devs(&intf
->dev
, &alt
->endpoint
[i
], udev
);
1031 intf
->ep_devs_created
= 1;
1035 static void remove_intf_ep_devs(struct usb_interface
*intf
)
1037 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
1040 if (!intf
->ep_devs_created
)
1043 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
)
1044 usb_remove_ep_devs(&alt
->endpoint
[i
]);
1045 intf
->ep_devs_created
= 0;
1049 * usb_disable_endpoint -- Disable an endpoint by address
1050 * @dev: the device whose endpoint is being disabled
1051 * @epaddr: the endpoint's address. Endpoint number for output,
1052 * endpoint number + USB_DIR_IN for input
1053 * @reset_hardware: flag to erase any endpoint state stored in the
1054 * controller hardware
1056 * Disables the endpoint for URB submission and nukes all pending URBs.
1057 * If @reset_hardware is set then also deallocates hcd/hardware state
1060 void usb_disable_endpoint(struct usb_device
*dev
, unsigned int epaddr
,
1061 bool reset_hardware
)
1063 unsigned int epnum
= epaddr
& USB_ENDPOINT_NUMBER_MASK
;
1064 struct usb_host_endpoint
*ep
;
1069 if (usb_endpoint_out(epaddr
)) {
1070 ep
= dev
->ep_out
[epnum
];
1072 dev
->ep_out
[epnum
] = NULL
;
1074 ep
= dev
->ep_in
[epnum
];
1076 dev
->ep_in
[epnum
] = NULL
;
1080 usb_hcd_flush_endpoint(dev
, ep
);
1082 usb_hcd_disable_endpoint(dev
, ep
);
1087 * usb_reset_endpoint - Reset an endpoint's state.
1088 * @dev: the device whose endpoint is to be reset
1089 * @epaddr: the endpoint's address. Endpoint number for output,
1090 * endpoint number + USB_DIR_IN for input
1092 * Resets any host-side endpoint state such as the toggle bit,
1093 * sequence number or current window.
1095 void usb_reset_endpoint(struct usb_device
*dev
, unsigned int epaddr
)
1097 unsigned int epnum
= epaddr
& USB_ENDPOINT_NUMBER_MASK
;
1098 struct usb_host_endpoint
*ep
;
1100 if (usb_endpoint_out(epaddr
))
1101 ep
= dev
->ep_out
[epnum
];
1103 ep
= dev
->ep_in
[epnum
];
1105 usb_hcd_reset_endpoint(dev
, ep
);
1107 EXPORT_SYMBOL_GPL(usb_reset_endpoint
);
1111 * usb_disable_interface -- Disable all endpoints for an interface
1112 * @dev: the device whose interface is being disabled
1113 * @intf: pointer to the interface descriptor
1114 * @reset_hardware: flag to erase any endpoint state stored in the
1115 * controller hardware
1117 * Disables all the endpoints for the interface's current altsetting.
1119 void usb_disable_interface(struct usb_device
*dev
, struct usb_interface
*intf
,
1120 bool reset_hardware
)
1122 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
1125 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
) {
1126 usb_disable_endpoint(dev
,
1127 alt
->endpoint
[i
].desc
.bEndpointAddress
,
1133 * usb_disable_device - Disable all the endpoints for a USB device
1134 * @dev: the device whose endpoints are being disabled
1135 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1137 * Disables all the device's endpoints, potentially including endpoint 0.
1138 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1139 * pending urbs) and usbcore state for the interfaces, so that usbcore
1140 * must usb_set_configuration() before any interfaces could be used.
1142 void usb_disable_device(struct usb_device
*dev
, int skip_ep0
)
1145 struct usb_hcd
*hcd
= bus_to_hcd(dev
->bus
);
1147 /* getting rid of interfaces will disconnect
1148 * any drivers bound to them (a key side effect)
1150 if (dev
->actconfig
) {
1152 * FIXME: In order to avoid self-deadlock involving the
1153 * bandwidth_mutex, we have to mark all the interfaces
1154 * before unregistering any of them.
1156 for (i
= 0; i
< dev
->actconfig
->desc
.bNumInterfaces
; i
++)
1157 dev
->actconfig
->interface
[i
]->unregistering
= 1;
1159 for (i
= 0; i
< dev
->actconfig
->desc
.bNumInterfaces
; i
++) {
1160 struct usb_interface
*interface
;
1162 /* remove this interface if it has been registered */
1163 interface
= dev
->actconfig
->interface
[i
];
1164 if (!device_is_registered(&interface
->dev
))
1166 dev_dbg(&dev
->dev
, "unregistering interface %s\n",
1167 dev_name(&interface
->dev
));
1168 remove_intf_ep_devs(interface
);
1169 device_del(&interface
->dev
);
1172 /* Now that the interfaces are unbound, nobody should
1173 * try to access them.
1175 for (i
= 0; i
< dev
->actconfig
->desc
.bNumInterfaces
; i
++) {
1176 put_device(&dev
->actconfig
->interface
[i
]->dev
);
1177 dev
->actconfig
->interface
[i
] = NULL
;
1180 if (dev
->usb2_hw_lpm_enabled
== 1)
1181 usb_set_usb2_hardware_lpm(dev
, 0);
1182 usb_unlocked_disable_lpm(dev
);
1183 usb_disable_ltm(dev
);
1185 dev
->actconfig
= NULL
;
1186 if (dev
->state
== USB_STATE_CONFIGURED
)
1187 usb_set_device_state(dev
, USB_STATE_ADDRESS
);
1190 dev_dbg(&dev
->dev
, "%s nuking %s URBs\n", __func__
,
1191 skip_ep0
? "non-ep0" : "all");
1192 if (hcd
->driver
->check_bandwidth
) {
1193 /* First pass: Cancel URBs, leave endpoint pointers intact. */
1194 for (i
= skip_ep0
; i
< 16; ++i
) {
1195 usb_disable_endpoint(dev
, i
, false);
1196 usb_disable_endpoint(dev
, i
+ USB_DIR_IN
, false);
1198 /* Remove endpoints from the host controller internal state */
1199 mutex_lock(hcd
->bandwidth_mutex
);
1200 usb_hcd_alloc_bandwidth(dev
, NULL
, NULL
, NULL
);
1201 mutex_unlock(hcd
->bandwidth_mutex
);
1202 /* Second pass: remove endpoint pointers */
1204 for (i
= skip_ep0
; i
< 16; ++i
) {
1205 usb_disable_endpoint(dev
, i
, true);
1206 usb_disable_endpoint(dev
, i
+ USB_DIR_IN
, true);
1211 * usb_enable_endpoint - Enable an endpoint for USB communications
1212 * @dev: the device whose interface is being enabled
1214 * @reset_ep: flag to reset the endpoint state
1216 * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
1217 * For control endpoints, both the input and output sides are handled.
1219 void usb_enable_endpoint(struct usb_device
*dev
, struct usb_host_endpoint
*ep
,
1222 int epnum
= usb_endpoint_num(&ep
->desc
);
1223 int is_out
= usb_endpoint_dir_out(&ep
->desc
);
1224 int is_control
= usb_endpoint_xfer_control(&ep
->desc
);
1227 usb_hcd_reset_endpoint(dev
, ep
);
1228 if (is_out
|| is_control
)
1229 dev
->ep_out
[epnum
] = ep
;
1230 if (!is_out
|| is_control
)
1231 dev
->ep_in
[epnum
] = ep
;
1236 * usb_enable_interface - Enable all the endpoints for an interface
1237 * @dev: the device whose interface is being enabled
1238 * @intf: pointer to the interface descriptor
1239 * @reset_eps: flag to reset the endpoints' state
1241 * Enables all the endpoints for the interface's current altsetting.
1243 void usb_enable_interface(struct usb_device
*dev
,
1244 struct usb_interface
*intf
, bool reset_eps
)
1246 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
1249 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
)
1250 usb_enable_endpoint(dev
, &alt
->endpoint
[i
], reset_eps
);
1254 * usb_set_interface - Makes a particular alternate setting be current
1255 * @dev: the device whose interface is being updated
1256 * @interface: the interface being updated
1257 * @alternate: the setting being chosen.
1258 * Context: !in_interrupt ()
1260 * This is used to enable data transfers on interfaces that may not
1261 * be enabled by default. Not all devices support such configurability.
1262 * Only the driver bound to an interface may change its setting.
1264 * Within any given configuration, each interface may have several
1265 * alternative settings. These are often used to control levels of
1266 * bandwidth consumption. For example, the default setting for a high
1267 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1268 * while interrupt transfers of up to 3KBytes per microframe are legal.
1269 * Also, isochronous endpoints may never be part of an
1270 * interface's default setting. To access such bandwidth, alternate
1271 * interface settings must be made current.
1273 * Note that in the Linux USB subsystem, bandwidth associated with
1274 * an endpoint in a given alternate setting is not reserved until an URB
1275 * is submitted that needs that bandwidth. Some other operating systems
1276 * allocate bandwidth early, when a configuration is chosen.
1278 * This call is synchronous, and may not be used in an interrupt context.
1279 * Also, drivers must not change altsettings while urbs are scheduled for
1280 * endpoints in that interface; all such urbs must first be completed
1281 * (perhaps forced by unlinking).
1283 * Return: Zero on success, or else the status code returned by the
1284 * underlying usb_control_msg() call.
1286 int usb_set_interface(struct usb_device
*dev
, int interface
, int alternate
)
1288 struct usb_interface
*iface
;
1289 struct usb_host_interface
*alt
;
1290 struct usb_hcd
*hcd
= bus_to_hcd(dev
->bus
);
1291 int i
, ret
, manual
= 0;
1292 unsigned int epaddr
;
1295 if (dev
->state
== USB_STATE_SUSPENDED
)
1296 return -EHOSTUNREACH
;
1298 iface
= usb_ifnum_to_if(dev
, interface
);
1300 dev_dbg(&dev
->dev
, "selecting invalid interface %d\n",
1304 if (iface
->unregistering
)
1307 alt
= usb_altnum_to_altsetting(iface
, alternate
);
1309 dev_warn(&dev
->dev
, "selecting invalid altsetting %d\n",
1314 /* Make sure we have enough bandwidth for this alternate interface.
1315 * Remove the current alt setting and add the new alt setting.
1317 mutex_lock(hcd
->bandwidth_mutex
);
1318 /* Disable LPM, and re-enable it once the new alt setting is installed,
1319 * so that the xHCI driver can recalculate the U1/U2 timeouts.
1321 if (usb_disable_lpm(dev
)) {
1322 dev_err(&iface
->dev
, "%s Failed to disable LPM\n.", __func__
);
1323 mutex_unlock(hcd
->bandwidth_mutex
);
1326 /* Changing alt-setting also frees any allocated streams */
1327 for (i
= 0; i
< iface
->cur_altsetting
->desc
.bNumEndpoints
; i
++)
1328 iface
->cur_altsetting
->endpoint
[i
].streams
= 0;
1330 ret
= usb_hcd_alloc_bandwidth(dev
, NULL
, iface
->cur_altsetting
, alt
);
1332 dev_info(&dev
->dev
, "Not enough bandwidth for altsetting %d\n",
1334 usb_enable_lpm(dev
);
1335 mutex_unlock(hcd
->bandwidth_mutex
);
1339 if (dev
->quirks
& USB_QUIRK_NO_SET_INTF
)
1342 ret
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1343 USB_REQ_SET_INTERFACE
, USB_RECIP_INTERFACE
,
1344 alternate
, interface
, NULL
, 0, 5000);
1346 /* 9.4.10 says devices don't need this and are free to STALL the
1347 * request if the interface only has one alternate setting.
1349 if (ret
== -EPIPE
&& iface
->num_altsetting
== 1) {
1351 "manual set_interface for iface %d, alt %d\n",
1352 interface
, alternate
);
1354 } else if (ret
< 0) {
1355 /* Re-instate the old alt setting */
1356 usb_hcd_alloc_bandwidth(dev
, NULL
, alt
, iface
->cur_altsetting
);
1357 usb_enable_lpm(dev
);
1358 mutex_unlock(hcd
->bandwidth_mutex
);
1361 mutex_unlock(hcd
->bandwidth_mutex
);
1363 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1364 * when they implement async or easily-killable versions of this or
1365 * other "should-be-internal" functions (like clear_halt).
1366 * should hcd+usbcore postprocess control requests?
1369 /* prevent submissions using previous endpoint settings */
1370 if (iface
->cur_altsetting
!= alt
) {
1371 remove_intf_ep_devs(iface
);
1372 usb_remove_sysfs_intf_files(iface
);
1374 usb_disable_interface(dev
, iface
, true);
1376 iface
->cur_altsetting
= alt
;
1378 /* Now that the interface is installed, re-enable LPM. */
1379 usb_unlocked_enable_lpm(dev
);
1381 /* If the interface only has one altsetting and the device didn't
1382 * accept the request, we attempt to carry out the equivalent action
1383 * by manually clearing the HALT feature for each endpoint in the
1387 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; i
++) {
1388 epaddr
= alt
->endpoint
[i
].desc
.bEndpointAddress
;
1389 pipe
= __create_pipe(dev
,
1390 USB_ENDPOINT_NUMBER_MASK
& epaddr
) |
1391 (usb_endpoint_out(epaddr
) ?
1392 USB_DIR_OUT
: USB_DIR_IN
);
1394 usb_clear_halt(dev
, pipe
);
1398 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1401 * Despite EP0 is always present in all interfaces/AS, the list of
1402 * endpoints from the descriptor does not contain EP0. Due to its
1403 * omnipresence one might expect EP0 being considered "affected" by
1404 * any SetInterface request and hence assume toggles need to be reset.
1405 * However, EP0 toggles are re-synced for every individual transfer
1406 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1407 * (Likewise, EP0 never "halts" on well designed devices.)
1409 usb_enable_interface(dev
, iface
, true);
1410 if (device_is_registered(&iface
->dev
)) {
1411 usb_create_sysfs_intf_files(iface
);
1412 create_intf_ep_devs(iface
);
1416 EXPORT_SYMBOL_GPL(usb_set_interface
);
1419 * usb_reset_configuration - lightweight device reset
1420 * @dev: the device whose configuration is being reset
1422 * This issues a standard SET_CONFIGURATION request to the device using
1423 * the current configuration. The effect is to reset most USB-related
1424 * state in the device, including interface altsettings (reset to zero),
1425 * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
1426 * endpoints). Other usbcore state is unchanged, including bindings of
1427 * usb device drivers to interfaces.
1429 * Because this affects multiple interfaces, avoid using this with composite
1430 * (multi-interface) devices. Instead, the driver for each interface may
1431 * use usb_set_interface() on the interfaces it claims. Be careful though;
1432 * some devices don't support the SET_INTERFACE request, and others won't
1433 * reset all the interface state (notably endpoint state). Resetting the whole
1434 * configuration would affect other drivers' interfaces.
1436 * The caller must own the device lock.
1438 * Return: Zero on success, else a negative error code.
1440 int usb_reset_configuration(struct usb_device
*dev
)
1443 struct usb_host_config
*config
;
1444 struct usb_hcd
*hcd
= bus_to_hcd(dev
->bus
);
1446 if (dev
->state
== USB_STATE_SUSPENDED
)
1447 return -EHOSTUNREACH
;
1449 /* caller must have locked the device and must own
1450 * the usb bus readlock (so driver bindings are stable);
1451 * calls during probe() are fine
1454 for (i
= 1; i
< 16; ++i
) {
1455 usb_disable_endpoint(dev
, i
, true);
1456 usb_disable_endpoint(dev
, i
+ USB_DIR_IN
, true);
1459 config
= dev
->actconfig
;
1461 mutex_lock(hcd
->bandwidth_mutex
);
1462 /* Disable LPM, and re-enable it once the configuration is reset, so
1463 * that the xHCI driver can recalculate the U1/U2 timeouts.
1465 if (usb_disable_lpm(dev
)) {
1466 dev_err(&dev
->dev
, "%s Failed to disable LPM\n.", __func__
);
1467 mutex_unlock(hcd
->bandwidth_mutex
);
1470 /* Make sure we have enough bandwidth for each alternate setting 0 */
1471 for (i
= 0; i
< config
->desc
.bNumInterfaces
; i
++) {
1472 struct usb_interface
*intf
= config
->interface
[i
];
1473 struct usb_host_interface
*alt
;
1475 alt
= usb_altnum_to_altsetting(intf
, 0);
1477 alt
= &intf
->altsetting
[0];
1478 if (alt
!= intf
->cur_altsetting
)
1479 retval
= usb_hcd_alloc_bandwidth(dev
, NULL
,
1480 intf
->cur_altsetting
, alt
);
1484 /* If not, reinstate the old alternate settings */
1487 for (i
--; i
>= 0; i
--) {
1488 struct usb_interface
*intf
= config
->interface
[i
];
1489 struct usb_host_interface
*alt
;
1491 alt
= usb_altnum_to_altsetting(intf
, 0);
1493 alt
= &intf
->altsetting
[0];
1494 if (alt
!= intf
->cur_altsetting
)
1495 usb_hcd_alloc_bandwidth(dev
, NULL
,
1496 alt
, intf
->cur_altsetting
);
1498 usb_enable_lpm(dev
);
1499 mutex_unlock(hcd
->bandwidth_mutex
);
1502 retval
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1503 USB_REQ_SET_CONFIGURATION
, 0,
1504 config
->desc
.bConfigurationValue
, 0,
1505 NULL
, 0, USB_CTRL_SET_TIMEOUT
);
1507 goto reset_old_alts
;
1508 mutex_unlock(hcd
->bandwidth_mutex
);
1510 /* re-init hc/hcd interface/endpoint state */
1511 for (i
= 0; i
< config
->desc
.bNumInterfaces
; i
++) {
1512 struct usb_interface
*intf
= config
->interface
[i
];
1513 struct usb_host_interface
*alt
;
1515 alt
= usb_altnum_to_altsetting(intf
, 0);
1517 /* No altsetting 0? We'll assume the first altsetting.
1518 * We could use a GetInterface call, but if a device is
1519 * so non-compliant that it doesn't have altsetting 0
1520 * then I wouldn't trust its reply anyway.
1523 alt
= &intf
->altsetting
[0];
1525 if (alt
!= intf
->cur_altsetting
) {
1526 remove_intf_ep_devs(intf
);
1527 usb_remove_sysfs_intf_files(intf
);
1529 intf
->cur_altsetting
= alt
;
1530 usb_enable_interface(dev
, intf
, true);
1531 if (device_is_registered(&intf
->dev
)) {
1532 usb_create_sysfs_intf_files(intf
);
1533 create_intf_ep_devs(intf
);
1536 /* Now that the interfaces are installed, re-enable LPM. */
1537 usb_unlocked_enable_lpm(dev
);
1540 EXPORT_SYMBOL_GPL(usb_reset_configuration
);
1542 static void usb_release_interface(struct device
*dev
)
1544 struct usb_interface
*intf
= to_usb_interface(dev
);
1545 struct usb_interface_cache
*intfc
=
1546 altsetting_to_usb_interface_cache(intf
->altsetting
);
1548 kref_put(&intfc
->ref
, usb_release_interface_cache
);
1549 usb_put_dev(interface_to_usbdev(intf
));
1554 * usb_deauthorize_interface - deauthorize an USB interface
1556 * @intf: USB interface structure
1558 void usb_deauthorize_interface(struct usb_interface
*intf
)
1560 struct device
*dev
= &intf
->dev
;
1562 device_lock(dev
->parent
);
1564 if (intf
->authorized
) {
1566 intf
->authorized
= 0;
1569 usb_forced_unbind_intf(intf
);
1572 device_unlock(dev
->parent
);
1576 * usb_authorize_interface - authorize an USB interface
1578 * @intf: USB interface structure
1580 void usb_authorize_interface(struct usb_interface
*intf
)
1582 struct device
*dev
= &intf
->dev
;
1584 if (!intf
->authorized
) {
1586 intf
->authorized
= 1; /* authorize interface */
1591 static int usb_if_uevent(struct device
*dev
, struct kobj_uevent_env
*env
)
1593 struct usb_device
*usb_dev
;
1594 struct usb_interface
*intf
;
1595 struct usb_host_interface
*alt
;
1597 intf
= to_usb_interface(dev
);
1598 usb_dev
= interface_to_usbdev(intf
);
1599 alt
= intf
->cur_altsetting
;
1601 if (add_uevent_var(env
, "INTERFACE=%d/%d/%d",
1602 alt
->desc
.bInterfaceClass
,
1603 alt
->desc
.bInterfaceSubClass
,
1604 alt
->desc
.bInterfaceProtocol
))
1607 if (add_uevent_var(env
,
1609 "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
1610 le16_to_cpu(usb_dev
->descriptor
.idVendor
),
1611 le16_to_cpu(usb_dev
->descriptor
.idProduct
),
1612 le16_to_cpu(usb_dev
->descriptor
.bcdDevice
),
1613 usb_dev
->descriptor
.bDeviceClass
,
1614 usb_dev
->descriptor
.bDeviceSubClass
,
1615 usb_dev
->descriptor
.bDeviceProtocol
,
1616 alt
->desc
.bInterfaceClass
,
1617 alt
->desc
.bInterfaceSubClass
,
1618 alt
->desc
.bInterfaceProtocol
,
1619 alt
->desc
.bInterfaceNumber
))
1625 struct device_type usb_if_device_type
= {
1626 .name
= "usb_interface",
1627 .release
= usb_release_interface
,
1628 .uevent
= usb_if_uevent
,
1631 static struct usb_interface_assoc_descriptor
*find_iad(struct usb_device
*dev
,
1632 struct usb_host_config
*config
,
1635 struct usb_interface_assoc_descriptor
*retval
= NULL
;
1636 struct usb_interface_assoc_descriptor
*intf_assoc
;
1641 for (i
= 0; (i
< USB_MAXIADS
&& config
->intf_assoc
[i
]); i
++) {
1642 intf_assoc
= config
->intf_assoc
[i
];
1643 if (intf_assoc
->bInterfaceCount
== 0)
1646 first_intf
= intf_assoc
->bFirstInterface
;
1647 last_intf
= first_intf
+ (intf_assoc
->bInterfaceCount
- 1);
1648 if (inum
>= first_intf
&& inum
<= last_intf
) {
1650 retval
= intf_assoc
;
1652 dev_err(&dev
->dev
, "Interface #%d referenced"
1653 " by multiple IADs\n", inum
);
1662 * Internal function to queue a device reset
1663 * See usb_queue_reset_device() for more details
1665 static void __usb_queue_reset_device(struct work_struct
*ws
)
1668 struct usb_interface
*iface
=
1669 container_of(ws
, struct usb_interface
, reset_ws
);
1670 struct usb_device
*udev
= interface_to_usbdev(iface
);
1672 rc
= usb_lock_device_for_reset(udev
, iface
);
1674 usb_reset_device(udev
);
1675 usb_unlock_device(udev
);
1677 usb_put_intf(iface
); /* Undo _get_ in usb_queue_reset_device() */
1682 * usb_set_configuration - Makes a particular device setting be current
1683 * @dev: the device whose configuration is being updated
1684 * @configuration: the configuration being chosen.
1685 * Context: !in_interrupt(), caller owns the device lock
1687 * This is used to enable non-default device modes. Not all devices
1688 * use this kind of configurability; many devices only have one
1691 * @configuration is the value of the configuration to be installed.
1692 * According to the USB spec (e.g. section 9.1.1.5), configuration values
1693 * must be non-zero; a value of zero indicates that the device in
1694 * unconfigured. However some devices erroneously use 0 as one of their
1695 * configuration values. To help manage such devices, this routine will
1696 * accept @configuration = -1 as indicating the device should be put in
1697 * an unconfigured state.
1699 * USB device configurations may affect Linux interoperability,
1700 * power consumption and the functionality available. For example,
1701 * the default configuration is limited to using 100mA of bus power,
1702 * so that when certain device functionality requires more power,
1703 * and the device is bus powered, that functionality should be in some
1704 * non-default device configuration. Other device modes may also be
1705 * reflected as configuration options, such as whether two ISDN
1706 * channels are available independently; and choosing between open
1707 * standard device protocols (like CDC) or proprietary ones.
1709 * Note that a non-authorized device (dev->authorized == 0) will only
1710 * be put in unconfigured mode.
1712 * Note that USB has an additional level of device configurability,
1713 * associated with interfaces. That configurability is accessed using
1714 * usb_set_interface().
1716 * This call is synchronous. The calling context must be able to sleep,
1717 * must own the device lock, and must not hold the driver model's USB
1718 * bus mutex; usb interface driver probe() methods cannot use this routine.
1720 * Returns zero on success, or else the status code returned by the
1721 * underlying call that failed. On successful completion, each interface
1722 * in the original device configuration has been destroyed, and each one
1723 * in the new configuration has been probed by all relevant usb device
1724 * drivers currently known to the kernel.
1726 int usb_set_configuration(struct usb_device
*dev
, int configuration
)
1729 struct usb_host_config
*cp
= NULL
;
1730 struct usb_interface
**new_interfaces
= NULL
;
1731 struct usb_hcd
*hcd
= bus_to_hcd(dev
->bus
);
1734 if (dev
->authorized
== 0 || configuration
== -1)
1737 for (i
= 0; i
< dev
->descriptor
.bNumConfigurations
; i
++) {
1738 if (dev
->config
[i
].desc
.bConfigurationValue
==
1740 cp
= &dev
->config
[i
];
1745 if ((!cp
&& configuration
!= 0))
1748 /* The USB spec says configuration 0 means unconfigured.
1749 * But if a device includes a configuration numbered 0,
1750 * we will accept it as a correctly configured state.
1751 * Use -1 if you really want to unconfigure the device.
1753 if (cp
&& configuration
== 0)
1754 dev_warn(&dev
->dev
, "config 0 descriptor??\n");
1756 /* Allocate memory for new interfaces before doing anything else,
1757 * so that if we run out then nothing will have changed. */
1760 nintf
= cp
->desc
.bNumInterfaces
;
1761 new_interfaces
= kmalloc(nintf
* sizeof(*new_interfaces
),
1763 if (!new_interfaces
)
1766 for (; n
< nintf
; ++n
) {
1767 new_interfaces
[n
] = kzalloc(
1768 sizeof(struct usb_interface
),
1770 if (!new_interfaces
[n
]) {
1774 kfree(new_interfaces
[n
]);
1775 kfree(new_interfaces
);
1780 i
= dev
->bus_mA
- usb_get_max_power(dev
, cp
);
1782 dev_warn(&dev
->dev
, "new config #%d exceeds power "
1787 /* Wake up the device so we can send it the Set-Config request */
1788 ret
= usb_autoresume_device(dev
);
1790 goto free_interfaces
;
1792 /* if it's already configured, clear out old state first.
1793 * getting rid of old interfaces means unbinding their drivers.
1795 if (dev
->state
!= USB_STATE_ADDRESS
)
1796 usb_disable_device(dev
, 1); /* Skip ep0 */
1798 /* Get rid of pending async Set-Config requests for this device */
1799 cancel_async_set_config(dev
);
1801 /* Make sure we have bandwidth (and available HCD resources) for this
1802 * configuration. Remove endpoints from the schedule if we're dropping
1803 * this configuration to set configuration 0. After this point, the
1804 * host controller will not allow submissions to dropped endpoints. If
1805 * this call fails, the device state is unchanged.
1807 mutex_lock(hcd
->bandwidth_mutex
);
1808 /* Disable LPM, and re-enable it once the new configuration is
1809 * installed, so that the xHCI driver can recalculate the U1/U2
1812 if (dev
->actconfig
&& usb_disable_lpm(dev
)) {
1813 dev_err(&dev
->dev
, "%s Failed to disable LPM\n.", __func__
);
1814 mutex_unlock(hcd
->bandwidth_mutex
);
1816 goto free_interfaces
;
1818 ret
= usb_hcd_alloc_bandwidth(dev
, cp
, NULL
, NULL
);
1821 usb_enable_lpm(dev
);
1822 mutex_unlock(hcd
->bandwidth_mutex
);
1823 usb_autosuspend_device(dev
);
1824 goto free_interfaces
;
1828 * Initialize the new interface structures and the
1829 * hc/hcd/usbcore interface/endpoint state.
1831 for (i
= 0; i
< nintf
; ++i
) {
1832 struct usb_interface_cache
*intfc
;
1833 struct usb_interface
*intf
;
1834 struct usb_host_interface
*alt
;
1836 cp
->interface
[i
] = intf
= new_interfaces
[i
];
1837 intfc
= cp
->intf_cache
[i
];
1838 intf
->altsetting
= intfc
->altsetting
;
1839 intf
->num_altsetting
= intfc
->num_altsetting
;
1840 intf
->authorized
= !!HCD_INTF_AUTHORIZED(hcd
);
1841 kref_get(&intfc
->ref
);
1843 alt
= usb_altnum_to_altsetting(intf
, 0);
1845 /* No altsetting 0? We'll assume the first altsetting.
1846 * We could use a GetInterface call, but if a device is
1847 * so non-compliant that it doesn't have altsetting 0
1848 * then I wouldn't trust its reply anyway.
1851 alt
= &intf
->altsetting
[0];
1854 find_iad(dev
, cp
, alt
->desc
.bInterfaceNumber
);
1855 intf
->cur_altsetting
= alt
;
1856 usb_enable_interface(dev
, intf
, true);
1857 intf
->dev
.parent
= &dev
->dev
;
1858 intf
->dev
.driver
= NULL
;
1859 intf
->dev
.bus
= &usb_bus_type
;
1860 intf
->dev
.type
= &usb_if_device_type
;
1861 intf
->dev
.groups
= usb_interface_groups
;
1863 * Please refer to usb_alloc_dev() to see why we set
1864 * dma_mask and dma_pfn_offset.
1866 intf
->dev
.dma_mask
= dev
->dev
.dma_mask
;
1867 intf
->dev
.dma_pfn_offset
= dev
->dev
.dma_pfn_offset
;
1868 INIT_WORK(&intf
->reset_ws
, __usb_queue_reset_device
);
1870 device_initialize(&intf
->dev
);
1871 pm_runtime_no_callbacks(&intf
->dev
);
1872 dev_set_name(&intf
->dev
, "%d-%s:%d.%d",
1873 dev
->bus
->busnum
, dev
->devpath
,
1874 configuration
, alt
->desc
.bInterfaceNumber
);
1877 kfree(new_interfaces
);
1879 ret
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1880 USB_REQ_SET_CONFIGURATION
, 0, configuration
, 0,
1881 NULL
, 0, USB_CTRL_SET_TIMEOUT
);
1882 if (ret
< 0 && cp
) {
1884 * All the old state is gone, so what else can we do?
1885 * The device is probably useless now anyway.
1887 usb_hcd_alloc_bandwidth(dev
, NULL
, NULL
, NULL
);
1888 for (i
= 0; i
< nintf
; ++i
) {
1889 usb_disable_interface(dev
, cp
->interface
[i
], true);
1890 put_device(&cp
->interface
[i
]->dev
);
1891 cp
->interface
[i
] = NULL
;
1896 dev
->actconfig
= cp
;
1897 mutex_unlock(hcd
->bandwidth_mutex
);
1900 usb_set_device_state(dev
, USB_STATE_ADDRESS
);
1902 /* Leave LPM disabled while the device is unconfigured. */
1903 usb_autosuspend_device(dev
);
1906 usb_set_device_state(dev
, USB_STATE_CONFIGURED
);
1908 if (cp
->string
== NULL
&&
1909 !(dev
->quirks
& USB_QUIRK_CONFIG_INTF_STRINGS
))
1910 cp
->string
= usb_cache_string(dev
, cp
->desc
.iConfiguration
);
1912 /* Now that the interfaces are installed, re-enable LPM. */
1913 usb_unlocked_enable_lpm(dev
);
1914 /* Enable LTM if it was turned off by usb_disable_device. */
1915 usb_enable_ltm(dev
);
1917 /* Now that all the interfaces are set up, register them
1918 * to trigger binding of drivers to interfaces. probe()
1919 * routines may install different altsettings and may
1920 * claim() any interfaces not yet bound. Many class drivers
1921 * need that: CDC, audio, video, etc.
1923 for (i
= 0; i
< nintf
; ++i
) {
1924 struct usb_interface
*intf
= cp
->interface
[i
];
1927 "adding %s (config #%d, interface %d)\n",
1928 dev_name(&intf
->dev
), configuration
,
1929 intf
->cur_altsetting
->desc
.bInterfaceNumber
);
1930 device_enable_async_suspend(&intf
->dev
);
1931 ret
= device_add(&intf
->dev
);
1933 dev_err(&dev
->dev
, "device_add(%s) --> %d\n",
1934 dev_name(&intf
->dev
), ret
);
1937 create_intf_ep_devs(intf
);
1940 usb_autosuspend_device(dev
);
1943 EXPORT_SYMBOL_GPL(usb_set_configuration
);
1945 static LIST_HEAD(set_config_list
);
1946 static DEFINE_SPINLOCK(set_config_lock
);
1948 struct set_config_request
{
1949 struct usb_device
*udev
;
1951 struct work_struct work
;
1952 struct list_head node
;
1955 /* Worker routine for usb_driver_set_configuration() */
1956 static void driver_set_config_work(struct work_struct
*work
)
1958 struct set_config_request
*req
=
1959 container_of(work
, struct set_config_request
, work
);
1960 struct usb_device
*udev
= req
->udev
;
1962 usb_lock_device(udev
);
1963 spin_lock(&set_config_lock
);
1964 list_del(&req
->node
);
1965 spin_unlock(&set_config_lock
);
1967 if (req
->config
>= -1) /* Is req still valid? */
1968 usb_set_configuration(udev
, req
->config
);
1969 usb_unlock_device(udev
);
1974 /* Cancel pending Set-Config requests for a device whose configuration
1977 static void cancel_async_set_config(struct usb_device
*udev
)
1979 struct set_config_request
*req
;
1981 spin_lock(&set_config_lock
);
1982 list_for_each_entry(req
, &set_config_list
, node
) {
1983 if (req
->udev
== udev
)
1984 req
->config
= -999; /* Mark as cancelled */
1986 spin_unlock(&set_config_lock
);
1990 * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1991 * @udev: the device whose configuration is being updated
1992 * @config: the configuration being chosen.
1993 * Context: In process context, must be able to sleep
1995 * Device interface drivers are not allowed to change device configurations.
1996 * This is because changing configurations will destroy the interface the
1997 * driver is bound to and create new ones; it would be like a floppy-disk
1998 * driver telling the computer to replace the floppy-disk drive with a
2001 * Still, in certain specialized circumstances the need may arise. This
2002 * routine gets around the normal restrictions by using a work thread to
2003 * submit the change-config request.
2005 * Return: 0 if the request was successfully queued, error code otherwise.
2006 * The caller has no way to know whether the queued request will eventually
2009 int usb_driver_set_configuration(struct usb_device
*udev
, int config
)
2011 struct set_config_request
*req
;
2013 req
= kmalloc(sizeof(*req
), GFP_KERNEL
);
2017 req
->config
= config
;
2018 INIT_WORK(&req
->work
, driver_set_config_work
);
2020 spin_lock(&set_config_lock
);
2021 list_add(&req
->node
, &set_config_list
);
2022 spin_unlock(&set_config_lock
);
2025 schedule_work(&req
->work
);
2028 EXPORT_SYMBOL_GPL(usb_driver_set_configuration
);
2031 * cdc_parse_cdc_header - parse the extra headers present in CDC devices
2032 * @hdr: the place to put the results of the parsing
2033 * @intf: the interface for which parsing is requested
2034 * @buffer: pointer to the extra headers to be parsed
2035 * @buflen: length of the extra headers
2037 * This evaluates the extra headers present in CDC devices which
2038 * bind the interfaces for data and control and provide details
2039 * about the capabilities of the device.
2041 * Return: number of descriptors parsed or -EINVAL
2042 * if the header is contradictory beyond salvage
2045 int cdc_parse_cdc_header(struct usb_cdc_parsed_header
*hdr
,
2046 struct usb_interface
*intf
,
2050 /* duplicates are ignored */
2051 struct usb_cdc_union_desc
*union_header
= NULL
;
2053 /* duplicates are not tolerated */
2054 struct usb_cdc_header_desc
*header
= NULL
;
2055 struct usb_cdc_ether_desc
*ether
= NULL
;
2056 struct usb_cdc_mdlm_detail_desc
*detail
= NULL
;
2057 struct usb_cdc_mdlm_desc
*desc
= NULL
;
2059 unsigned int elength
;
2062 memset(hdr
, 0x00, sizeof(struct usb_cdc_parsed_header
));
2063 hdr
->phonet_magic_present
= false;
2064 while (buflen
> 0) {
2065 elength
= buffer
[0];
2067 dev_err(&intf
->dev
, "skipping garbage byte\n");
2071 if (buffer
[1] != USB_DT_CS_INTERFACE
) {
2072 dev_err(&intf
->dev
, "skipping garbage\n");
2076 switch (buffer
[2]) {
2077 case USB_CDC_UNION_TYPE
: /* we've found it */
2078 if (elength
< sizeof(struct usb_cdc_union_desc
))
2081 dev_err(&intf
->dev
, "More than one union descriptor, skipping ...\n");
2084 union_header
= (struct usb_cdc_union_desc
*)buffer
;
2086 case USB_CDC_COUNTRY_TYPE
:
2087 if (elength
< sizeof(struct usb_cdc_country_functional_desc
))
2089 hdr
->usb_cdc_country_functional_desc
=
2090 (struct usb_cdc_country_functional_desc
*)buffer
;
2092 case USB_CDC_HEADER_TYPE
:
2093 if (elength
!= sizeof(struct usb_cdc_header_desc
))
2097 header
= (struct usb_cdc_header_desc
*)buffer
;
2099 case USB_CDC_ACM_TYPE
:
2100 if (elength
< sizeof(struct usb_cdc_acm_descriptor
))
2102 hdr
->usb_cdc_acm_descriptor
=
2103 (struct usb_cdc_acm_descriptor
*)buffer
;
2105 case USB_CDC_ETHERNET_TYPE
:
2106 if (elength
!= sizeof(struct usb_cdc_ether_desc
))
2110 ether
= (struct usb_cdc_ether_desc
*)buffer
;
2112 case USB_CDC_CALL_MANAGEMENT_TYPE
:
2113 if (elength
< sizeof(struct usb_cdc_call_mgmt_descriptor
))
2115 hdr
->usb_cdc_call_mgmt_descriptor
=
2116 (struct usb_cdc_call_mgmt_descriptor
*)buffer
;
2118 case USB_CDC_DMM_TYPE
:
2119 if (elength
< sizeof(struct usb_cdc_dmm_desc
))
2121 hdr
->usb_cdc_dmm_desc
=
2122 (struct usb_cdc_dmm_desc
*)buffer
;
2124 case USB_CDC_MDLM_TYPE
:
2125 if (elength
< sizeof(struct usb_cdc_mdlm_desc
*))
2129 desc
= (struct usb_cdc_mdlm_desc
*)buffer
;
2131 case USB_CDC_MDLM_DETAIL_TYPE
:
2132 if (elength
< sizeof(struct usb_cdc_mdlm_detail_desc
*))
2136 detail
= (struct usb_cdc_mdlm_detail_desc
*)buffer
;
2138 case USB_CDC_NCM_TYPE
:
2139 if (elength
< sizeof(struct usb_cdc_ncm_desc
))
2141 hdr
->usb_cdc_ncm_desc
= (struct usb_cdc_ncm_desc
*)buffer
;
2143 case USB_CDC_MBIM_TYPE
:
2144 if (elength
< sizeof(struct usb_cdc_mbim_desc
))
2147 hdr
->usb_cdc_mbim_desc
= (struct usb_cdc_mbim_desc
*)buffer
;
2149 case USB_CDC_MBIM_EXTENDED_TYPE
:
2150 if (elength
< sizeof(struct usb_cdc_mbim_extended_desc
))
2152 hdr
->usb_cdc_mbim_extended_desc
=
2153 (struct usb_cdc_mbim_extended_desc
*)buffer
;
2155 case CDC_PHONET_MAGIC_NUMBER
:
2156 hdr
->phonet_magic_present
= true;
2160 * there are LOTS more CDC descriptors that
2161 * could legitimately be found here.
2163 dev_dbg(&intf
->dev
, "Ignoring descriptor: type %02x, length %ud\n",
2164 buffer
[2], elength
);
2172 hdr
->usb_cdc_union_desc
= union_header
;
2173 hdr
->usb_cdc_header_desc
= header
;
2174 hdr
->usb_cdc_mdlm_detail_desc
= detail
;
2175 hdr
->usb_cdc_mdlm_desc
= desc
;
2176 hdr
->usb_cdc_ether_desc
= ether
;
2180 EXPORT_SYMBOL(cdc_parse_cdc_header
);