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
);
150 /* Linger a bit, prior to the next control message. */
151 if (dev
->quirks
& USB_QUIRK_DELAY_CTRL_MSG
)
158 EXPORT_SYMBOL_GPL(usb_control_msg
);
161 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
162 * @usb_dev: pointer to the usb device to send the message to
163 * @pipe: endpoint "pipe" to send the message to
164 * @data: pointer to the data to send
165 * @len: length in bytes of the data to send
166 * @actual_length: pointer to a location to put the actual length transferred
168 * @timeout: time in msecs to wait for the message to complete before
169 * timing out (if 0 the wait is forever)
171 * Context: !in_interrupt ()
173 * This function sends a simple interrupt message to a specified endpoint and
174 * waits for the message to complete, or timeout.
176 * Don't use this function from within an interrupt context, like a bottom half
177 * handler. If you need an asynchronous message, or need to send a message
178 * from within interrupt context, use usb_submit_urb() If a thread in your
179 * driver uses this call, make sure your disconnect() method can wait for it to
180 * complete. Since you don't have a handle on the URB used, you can't cancel
184 * If successful, 0. Otherwise a negative error number. The number of actual
185 * bytes transferred will be stored in the @actual_length parameter.
187 int usb_interrupt_msg(struct usb_device
*usb_dev
, unsigned int pipe
,
188 void *data
, int len
, int *actual_length
, int timeout
)
190 return usb_bulk_msg(usb_dev
, pipe
, data
, len
, actual_length
, timeout
);
192 EXPORT_SYMBOL_GPL(usb_interrupt_msg
);
195 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
196 * @usb_dev: pointer to the usb device to send the message to
197 * @pipe: endpoint "pipe" to send the message to
198 * @data: pointer to the data to send
199 * @len: length in bytes of the data to send
200 * @actual_length: pointer to a location to put the actual length transferred
202 * @timeout: time in msecs to wait for the message to complete before
203 * timing out (if 0 the wait is forever)
205 * Context: !in_interrupt ()
207 * This function sends a simple bulk message to a specified endpoint
208 * and waits for the message to complete, or timeout.
210 * Don't use this function from within an interrupt context, like a bottom half
211 * handler. If you need an asynchronous message, or need to send a message
212 * from within interrupt context, use usb_submit_urb() If a thread in your
213 * driver uses this call, make sure your disconnect() method can wait for it to
214 * complete. Since you don't have a handle on the URB used, you can't cancel
217 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
218 * users are forced to abuse this routine by using it to submit URBs for
219 * interrupt endpoints. We will take the liberty of creating an interrupt URB
220 * (with the default interval) if the target is an interrupt endpoint.
223 * If successful, 0. Otherwise a negative error number. The number of actual
224 * bytes transferred will be stored in the @actual_length parameter.
227 int usb_bulk_msg(struct usb_device
*usb_dev
, unsigned int pipe
,
228 void *data
, int len
, int *actual_length
, int timeout
)
231 struct usb_host_endpoint
*ep
;
233 ep
= usb_pipe_endpoint(usb_dev
, pipe
);
237 urb
= usb_alloc_urb(0, GFP_KERNEL
);
241 if ((ep
->desc
.bmAttributes
& USB_ENDPOINT_XFERTYPE_MASK
) ==
242 USB_ENDPOINT_XFER_INT
) {
243 pipe
= (pipe
& ~(3 << 30)) | (PIPE_INTERRUPT
<< 30);
244 usb_fill_int_urb(urb
, usb_dev
, pipe
, data
, len
,
245 usb_api_blocking_completion
, NULL
,
248 usb_fill_bulk_urb(urb
, usb_dev
, pipe
, data
, len
,
249 usb_api_blocking_completion
, NULL
);
251 return usb_start_wait_urb(urb
, timeout
, actual_length
);
253 EXPORT_SYMBOL_GPL(usb_bulk_msg
);
255 /*-------------------------------------------------------------------*/
257 static void sg_clean(struct usb_sg_request
*io
)
260 while (io
->entries
--)
261 usb_free_urb(io
->urbs
[io
->entries
]);
268 static void sg_complete(struct urb
*urb
)
270 struct usb_sg_request
*io
= urb
->context
;
271 int status
= urb
->status
;
273 spin_lock(&io
->lock
);
275 /* In 2.5 we require hcds' endpoint queues not to progress after fault
276 * reports, until the completion callback (this!) returns. That lets
277 * device driver code (like this routine) unlink queued urbs first,
278 * if it needs to, since the HC won't work on them at all. So it's
279 * not possible for page N+1 to overwrite page N, and so on.
281 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
282 * complete before the HCD can get requests away from hardware,
283 * though never during cleanup after a hard fault.
286 && (io
->status
!= -ECONNRESET
287 || status
!= -ECONNRESET
)
288 && urb
->actual_length
) {
289 dev_err(io
->dev
->bus
->controller
,
290 "dev %s ep%d%s scatterlist error %d/%d\n",
292 usb_endpoint_num(&urb
->ep
->desc
),
293 usb_urb_dir_in(urb
) ? "in" : "out",
298 if (io
->status
== 0 && status
&& status
!= -ECONNRESET
) {
299 int i
, found
, retval
;
303 /* the previous urbs, and this one, completed already.
304 * unlink pending urbs so they won't rx/tx bad data.
305 * careful: unlink can sometimes be synchronous...
307 spin_unlock(&io
->lock
);
308 for (i
= 0, found
= 0; i
< io
->entries
; i
++) {
309 if (!io
->urbs
[i
] || !io
->urbs
[i
]->dev
)
312 retval
= usb_unlink_urb(io
->urbs
[i
]);
313 if (retval
!= -EINPROGRESS
&&
317 dev_err(&io
->dev
->dev
,
318 "%s, unlink --> %d\n",
320 } else if (urb
== io
->urbs
[i
])
323 spin_lock(&io
->lock
);
326 /* on the last completion, signal usb_sg_wait() */
327 io
->bytes
+= urb
->actual_length
;
330 complete(&io
->complete
);
332 spin_unlock(&io
->lock
);
337 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
338 * @io: request block being initialized. until usb_sg_wait() returns,
339 * treat this as a pointer to an opaque block of memory,
340 * @dev: the usb device that will send or receive the data
341 * @pipe: endpoint "pipe" used to transfer the data
342 * @period: polling rate for interrupt endpoints, in frames or
343 * (for high speed endpoints) microframes; ignored for bulk
344 * @sg: scatterlist entries
345 * @nents: how many entries in the scatterlist
346 * @length: how many bytes to send from the scatterlist, or zero to
347 * send every byte identified in the list.
348 * @mem_flags: SLAB_* flags affecting memory allocations in this call
350 * This initializes a scatter/gather request, allocating resources such as
351 * I/O mappings and urb memory (except maybe memory used by USB controller
354 * The request must be issued using usb_sg_wait(), which waits for the I/O to
355 * complete (or to be canceled) and then cleans up all resources allocated by
358 * The request may be canceled with usb_sg_cancel(), either before or after
359 * usb_sg_wait() is called.
361 * Return: Zero for success, else a negative errno value.
363 int usb_sg_init(struct usb_sg_request
*io
, struct usb_device
*dev
,
364 unsigned pipe
, unsigned period
, struct scatterlist
*sg
,
365 int nents
, size_t length
, gfp_t mem_flags
)
371 if (!io
|| !dev
|| !sg
372 || usb_pipecontrol(pipe
)
373 || usb_pipeisoc(pipe
)
377 spin_lock_init(&io
->lock
);
381 if (dev
->bus
->sg_tablesize
> 0) {
389 /* initialize all the urbs we'll use */
390 io
->urbs
= kmalloc(io
->entries
* sizeof(*io
->urbs
), mem_flags
);
394 urb_flags
= URB_NO_INTERRUPT
;
395 if (usb_pipein(pipe
))
396 urb_flags
|= URB_SHORT_NOT_OK
;
398 for_each_sg(sg
, sg
, io
->entries
, i
) {
402 urb
= usb_alloc_urb(0, mem_flags
);
411 urb
->interval
= period
;
412 urb
->transfer_flags
= urb_flags
;
413 urb
->complete
= sg_complete
;
418 /* There is no single transfer buffer */
419 urb
->transfer_buffer
= NULL
;
420 urb
->num_sgs
= nents
;
422 /* A length of zero means transfer the whole sg list */
425 struct scatterlist
*sg2
;
428 for_each_sg(sg
, sg2
, nents
, j
)
433 * Some systems can't use DMA; they use PIO instead.
434 * For their sakes, transfer_buffer is set whenever
437 if (!PageHighMem(sg_page(sg
)))
438 urb
->transfer_buffer
= sg_virt(sg
);
440 urb
->transfer_buffer
= NULL
;
444 len
= min_t(size_t, len
, length
);
450 urb
->transfer_buffer_length
= len
;
452 io
->urbs
[--i
]->transfer_flags
&= ~URB_NO_INTERRUPT
;
454 /* transaction state */
455 io
->count
= io
->entries
;
458 init_completion(&io
->complete
);
465 EXPORT_SYMBOL_GPL(usb_sg_init
);
468 * usb_sg_wait - synchronously execute scatter/gather request
469 * @io: request block handle, as initialized with usb_sg_init().
470 * some fields become accessible when this call returns.
471 * Context: !in_interrupt ()
473 * This function blocks until the specified I/O operation completes. It
474 * leverages the grouping of the related I/O requests to get good transfer
475 * rates, by queueing the requests. At higher speeds, such queuing can
476 * significantly improve USB throughput.
478 * There are three kinds of completion for this function.
479 * (1) success, where io->status is zero. The number of io->bytes
480 * transferred is as requested.
481 * (2) error, where io->status is a negative errno value. The number
482 * of io->bytes transferred before the error is usually less
483 * than requested, and can be nonzero.
484 * (3) cancellation, a type of error with status -ECONNRESET that
485 * is initiated by usb_sg_cancel().
487 * When this function returns, all memory allocated through usb_sg_init() or
488 * this call will have been freed. The request block parameter may still be
489 * passed to usb_sg_cancel(), or it may be freed. It could also be
490 * reinitialized and then reused.
492 * Data Transfer Rates:
494 * Bulk transfers are valid for full or high speed endpoints.
495 * The best full speed data rate is 19 packets of 64 bytes each
496 * per frame, or 1216 bytes per millisecond.
497 * The best high speed data rate is 13 packets of 512 bytes each
498 * per microframe, or 52 KBytes per millisecond.
500 * The reason to use interrupt transfers through this API would most likely
501 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
502 * could be transferred. That capability is less useful for low or full
503 * speed interrupt endpoints, which allow at most one packet per millisecond,
504 * of at most 8 or 64 bytes (respectively).
506 * It is not necessary to call this function to reserve bandwidth for devices
507 * under an xHCI host controller, as the bandwidth is reserved when the
508 * configuration or interface alt setting is selected.
510 void usb_sg_wait(struct usb_sg_request
*io
)
513 int entries
= io
->entries
;
515 /* queue the urbs. */
516 spin_lock_irq(&io
->lock
);
518 while (i
< entries
&& !io
->status
) {
521 io
->urbs
[i
]->dev
= io
->dev
;
522 retval
= usb_submit_urb(io
->urbs
[i
], GFP_ATOMIC
);
524 /* after we submit, let completions or cancellations fire;
525 * we handshake using io->status.
527 spin_unlock_irq(&io
->lock
);
529 /* maybe we retrying will recover */
530 case -ENXIO
: /* hc didn't queue this one */
537 /* no error? continue immediately.
539 * NOTE: to work better with UHCI (4K I/O buffer may
540 * need 3K of TDs) it may be good to limit how many
541 * URBs are queued at once; N milliseconds?
548 /* fail any uncompleted urbs */
550 io
->urbs
[i
]->status
= retval
;
551 dev_dbg(&io
->dev
->dev
, "%s, submit --> %d\n",
555 spin_lock_irq(&io
->lock
);
556 if (retval
&& (io
->status
== 0 || io
->status
== -ECONNRESET
))
559 io
->count
-= entries
- i
;
561 complete(&io
->complete
);
562 spin_unlock_irq(&io
->lock
);
564 /* OK, yes, this could be packaged as non-blocking.
565 * So could the submit loop above ... but it's easier to
566 * solve neither problem than to solve both!
568 wait_for_completion(&io
->complete
);
572 EXPORT_SYMBOL_GPL(usb_sg_wait
);
575 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
576 * @io: request block, initialized with usb_sg_init()
578 * This stops a request after it has been started by usb_sg_wait().
579 * It can also prevents one initialized by usb_sg_init() from starting,
580 * so that call just frees resources allocated to the request.
582 void usb_sg_cancel(struct usb_sg_request
*io
)
586 spin_lock_irqsave(&io
->lock
, flags
);
588 /* shut everything down, if it didn't already */
592 io
->status
= -ECONNRESET
;
593 spin_unlock(&io
->lock
);
594 for (i
= 0; i
< io
->entries
; i
++) {
597 if (!io
->urbs
[i
]->dev
)
599 retval
= usb_unlink_urb(io
->urbs
[i
]);
600 if (retval
!= -EINPROGRESS
604 dev_warn(&io
->dev
->dev
, "%s, unlink --> %d\n",
607 spin_lock(&io
->lock
);
609 spin_unlock_irqrestore(&io
->lock
, flags
);
611 EXPORT_SYMBOL_GPL(usb_sg_cancel
);
613 /*-------------------------------------------------------------------*/
616 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
617 * @dev: the device whose descriptor is being retrieved
618 * @type: the descriptor type (USB_DT_*)
619 * @index: the number of the descriptor
620 * @buf: where to put the descriptor
621 * @size: how big is "buf"?
622 * Context: !in_interrupt ()
624 * Gets a USB descriptor. Convenience functions exist to simplify
625 * getting some types of descriptors. Use
626 * usb_get_string() or usb_string() for USB_DT_STRING.
627 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
628 * are part of the device structure.
629 * In addition to a number of USB-standard descriptors, some
630 * devices also use class-specific or vendor-specific descriptors.
632 * This call is synchronous, and may not be used in an interrupt context.
634 * Return: The number of bytes received on success, or else the status code
635 * returned by the underlying usb_control_msg() call.
637 int usb_get_descriptor(struct usb_device
*dev
, unsigned char type
,
638 unsigned char index
, void *buf
, int size
)
643 memset(buf
, 0, size
); /* Make sure we parse really received data */
645 for (i
= 0; i
< 3; ++i
) {
646 /* retry on length 0 or error; some devices are flakey */
647 result
= usb_control_msg(dev
, usb_rcvctrlpipe(dev
, 0),
648 USB_REQ_GET_DESCRIPTOR
, USB_DIR_IN
,
649 (type
<< 8) + index
, 0, buf
, size
,
650 USB_CTRL_GET_TIMEOUT
);
651 if (result
<= 0 && result
!= -ETIMEDOUT
)
653 if (result
> 1 && ((u8
*)buf
)[1] != type
) {
661 EXPORT_SYMBOL_GPL(usb_get_descriptor
);
664 * usb_get_string - gets a string descriptor
665 * @dev: the device whose string descriptor is being retrieved
666 * @langid: code for language chosen (from string descriptor zero)
667 * @index: the number of the descriptor
668 * @buf: where to put the string
669 * @size: how big is "buf"?
670 * Context: !in_interrupt ()
672 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
673 * in little-endian byte order).
674 * The usb_string() function will often be a convenient way to turn
675 * these strings into kernel-printable form.
677 * Strings may be referenced in device, configuration, interface, or other
678 * descriptors, and could also be used in vendor-specific ways.
680 * This call is synchronous, and may not be used in an interrupt context.
682 * Return: The number of bytes received on success, or else the status code
683 * returned by the underlying usb_control_msg() call.
685 static int usb_get_string(struct usb_device
*dev
, unsigned short langid
,
686 unsigned char index
, void *buf
, int size
)
691 for (i
= 0; i
< 3; ++i
) {
692 /* retry on length 0 or stall; some devices are flakey */
693 result
= usb_control_msg(dev
, usb_rcvctrlpipe(dev
, 0),
694 USB_REQ_GET_DESCRIPTOR
, USB_DIR_IN
,
695 (USB_DT_STRING
<< 8) + index
, langid
, buf
, size
,
696 USB_CTRL_GET_TIMEOUT
);
697 if (result
== 0 || result
== -EPIPE
)
699 if (result
> 1 && ((u8
*) buf
)[1] != USB_DT_STRING
) {
708 static void usb_try_string_workarounds(unsigned char *buf
, int *length
)
710 int newlength
, oldlength
= *length
;
712 for (newlength
= 2; newlength
+ 1 < oldlength
; newlength
+= 2)
713 if (!isprint(buf
[newlength
]) || buf
[newlength
+ 1])
722 static int usb_string_sub(struct usb_device
*dev
, unsigned int langid
,
723 unsigned int index
, unsigned char *buf
)
727 /* Try to read the string descriptor by asking for the maximum
728 * possible number of bytes */
729 if (dev
->quirks
& USB_QUIRK_STRING_FETCH_255
)
732 rc
= usb_get_string(dev
, langid
, index
, buf
, 255);
734 /* If that failed try to read the descriptor length, then
735 * ask for just that many bytes */
737 rc
= usb_get_string(dev
, langid
, index
, buf
, 2);
739 rc
= usb_get_string(dev
, langid
, index
, buf
, buf
[0]);
743 if (!buf
[0] && !buf
[1])
744 usb_try_string_workarounds(buf
, &rc
);
746 /* There might be extra junk at the end of the descriptor */
750 rc
= rc
- (rc
& 1); /* force a multiple of two */
754 rc
= (rc
< 0 ? rc
: -EINVAL
);
759 static int usb_get_langid(struct usb_device
*dev
, unsigned char *tbuf
)
763 if (dev
->have_langid
)
766 if (dev
->string_langid
< 0)
769 err
= usb_string_sub(dev
, 0, 0, tbuf
);
771 /* If the string was reported but is malformed, default to english
773 if (err
== -ENODATA
|| (err
> 0 && err
< 4)) {
774 dev
->string_langid
= 0x0409;
775 dev
->have_langid
= 1;
777 "language id specifier not provided by device, defaulting to English\n");
781 /* In case of all other errors, we assume the device is not able to
782 * deal with strings at all. Set string_langid to -1 in order to
783 * prevent any string to be retrieved from the device */
785 dev_err(&dev
->dev
, "string descriptor 0 read error: %d\n",
787 dev
->string_langid
= -1;
791 /* always use the first langid listed */
792 dev
->string_langid
= tbuf
[2] | (tbuf
[3] << 8);
793 dev
->have_langid
= 1;
794 dev_dbg(&dev
->dev
, "default language 0x%04x\n",
800 * usb_string - returns UTF-8 version of a string descriptor
801 * @dev: the device whose string descriptor is being retrieved
802 * @index: the number of the descriptor
803 * @buf: where to put the string
804 * @size: how big is "buf"?
805 * Context: !in_interrupt ()
807 * This converts the UTF-16LE encoded strings returned by devices, from
808 * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
809 * that are more usable in most kernel contexts. Note that this function
810 * chooses strings in the first language supported by the device.
812 * This call is synchronous, and may not be used in an interrupt context.
814 * Return: length of the string (>= 0) or usb_control_msg status (< 0).
816 int usb_string(struct usb_device
*dev
, int index
, char *buf
, size_t size
)
821 if (dev
->state
== USB_STATE_SUSPENDED
)
822 return -EHOSTUNREACH
;
823 if (size
<= 0 || !buf
|| !index
)
826 tbuf
= kmalloc(256, GFP_NOIO
);
830 err
= usb_get_langid(dev
, tbuf
);
834 err
= usb_string_sub(dev
, dev
->string_langid
, index
, tbuf
);
838 size
--; /* leave room for trailing NULL char in output buffer */
839 err
= utf16s_to_utf8s((wchar_t *) &tbuf
[2], (err
- 2) / 2,
840 UTF16_LITTLE_ENDIAN
, buf
, size
);
843 if (tbuf
[1] != USB_DT_STRING
)
845 "wrong descriptor type %02x for string %d (\"%s\")\n",
846 tbuf
[1], index
, buf
);
852 EXPORT_SYMBOL_GPL(usb_string
);
854 /* one UTF-8-encoded 16-bit character has at most three bytes */
855 #define MAX_USB_STRING_SIZE (127 * 3 + 1)
858 * usb_cache_string - read a string descriptor and cache it for later use
859 * @udev: the device whose string descriptor is being read
860 * @index: the descriptor index
862 * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
863 * or %NULL if the index is 0 or the string could not be read.
865 char *usb_cache_string(struct usb_device
*udev
, int index
)
868 char *smallbuf
= NULL
;
874 buf
= kmalloc(MAX_USB_STRING_SIZE
, GFP_NOIO
);
876 len
= usb_string(udev
, index
, buf
, MAX_USB_STRING_SIZE
);
878 smallbuf
= kmalloc(++len
, GFP_NOIO
);
881 memcpy(smallbuf
, buf
, len
);
889 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
890 * @dev: the device whose device descriptor is being updated
891 * @size: how much of the descriptor to read
892 * Context: !in_interrupt ()
894 * Updates the copy of the device descriptor stored in the device structure,
895 * which dedicates space for this purpose.
897 * Not exported, only for use by the core. If drivers really want to read
898 * the device descriptor directly, they can call usb_get_descriptor() with
899 * type = USB_DT_DEVICE and index = 0.
901 * This call is synchronous, and may not be used in an interrupt context.
903 * Return: The number of bytes received on success, or else the status code
904 * returned by the underlying usb_control_msg() call.
906 int usb_get_device_descriptor(struct usb_device
*dev
, unsigned int size
)
908 struct usb_device_descriptor
*desc
;
911 if (size
> sizeof(*desc
))
913 desc
= kmalloc(sizeof(*desc
), GFP_NOIO
);
917 ret
= usb_get_descriptor(dev
, USB_DT_DEVICE
, 0, desc
, size
);
919 memcpy(&dev
->descriptor
, desc
, size
);
925 * usb_get_status - issues a GET_STATUS call
926 * @dev: the device whose status is being checked
927 * @type: USB_RECIP_*; for device, interface, or endpoint
928 * @target: zero (for device), else interface or endpoint number
929 * @data: pointer to two bytes of bitmap data
930 * Context: !in_interrupt ()
932 * Returns device, interface, or endpoint status. Normally only of
933 * interest to see if the device is self powered, or has enabled the
934 * remote wakeup facility; or whether a bulk or interrupt endpoint
935 * is halted ("stalled").
937 * Bits in these status bitmaps are set using the SET_FEATURE request,
938 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
939 * function should be used to clear halt ("stall") status.
941 * This call is synchronous, and may not be used in an interrupt context.
943 * Returns 0 and the status value in *@data (in host byte order) on success,
944 * or else the status code from the underlying usb_control_msg() call.
946 int usb_get_status(struct usb_device
*dev
, int type
, int target
, void *data
)
949 __le16
*status
= kmalloc(sizeof(*status
), GFP_KERNEL
);
954 ret
= usb_control_msg(dev
, usb_rcvctrlpipe(dev
, 0),
955 USB_REQ_GET_STATUS
, USB_DIR_IN
| type
, 0, target
, status
,
956 sizeof(*status
), USB_CTRL_GET_TIMEOUT
);
959 *(u16
*) data
= le16_to_cpu(*status
);
961 } else if (ret
>= 0) {
967 EXPORT_SYMBOL_GPL(usb_get_status
);
970 * usb_clear_halt - tells device to clear endpoint halt/stall condition
971 * @dev: device whose endpoint is halted
972 * @pipe: endpoint "pipe" being cleared
973 * Context: !in_interrupt ()
975 * This is used to clear halt conditions for bulk and interrupt endpoints,
976 * as reported by URB completion status. Endpoints that are halted are
977 * sometimes referred to as being "stalled". Such endpoints are unable
978 * to transmit or receive data until the halt status is cleared. Any URBs
979 * queued for such an endpoint should normally be unlinked by the driver
980 * before clearing the halt condition, as described in sections 5.7.5
981 * and 5.8.5 of the USB 2.0 spec.
983 * Note that control and isochronous endpoints don't halt, although control
984 * endpoints report "protocol stall" (for unsupported requests) using the
985 * same status code used to report a true stall.
987 * This call is synchronous, and may not be used in an interrupt context.
989 * Return: Zero on success, or else the status code returned by the
990 * underlying usb_control_msg() call.
992 int usb_clear_halt(struct usb_device
*dev
, int pipe
)
995 int endp
= usb_pipeendpoint(pipe
);
997 if (usb_pipein(pipe
))
1000 /* we don't care if it wasn't halted first. in fact some devices
1001 * (like some ibmcam model 1 units) seem to expect hosts to make
1002 * this request for iso endpoints, which can't halt!
1004 result
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1005 USB_REQ_CLEAR_FEATURE
, USB_RECIP_ENDPOINT
,
1006 USB_ENDPOINT_HALT
, endp
, NULL
, 0,
1007 USB_CTRL_SET_TIMEOUT
);
1009 /* don't un-halt or force to DATA0 except on success */
1013 /* NOTE: seems like Microsoft and Apple don't bother verifying
1014 * the clear "took", so some devices could lock up if you check...
1015 * such as the Hagiwara FlashGate DUAL. So we won't bother.
1017 * NOTE: make sure the logic here doesn't diverge much from
1018 * the copy in usb-storage, for as long as we need two copies.
1021 usb_reset_endpoint(dev
, endp
);
1025 EXPORT_SYMBOL_GPL(usb_clear_halt
);
1027 static int create_intf_ep_devs(struct usb_interface
*intf
)
1029 struct usb_device
*udev
= interface_to_usbdev(intf
);
1030 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
1033 if (intf
->ep_devs_created
|| intf
->unregistering
)
1036 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
)
1037 (void) usb_create_ep_devs(&intf
->dev
, &alt
->endpoint
[i
], udev
);
1038 intf
->ep_devs_created
= 1;
1042 static void remove_intf_ep_devs(struct usb_interface
*intf
)
1044 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
1047 if (!intf
->ep_devs_created
)
1050 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
)
1051 usb_remove_ep_devs(&alt
->endpoint
[i
]);
1052 intf
->ep_devs_created
= 0;
1056 * usb_disable_endpoint -- Disable an endpoint by address
1057 * @dev: the device whose endpoint is being disabled
1058 * @epaddr: the endpoint's address. Endpoint number for output,
1059 * endpoint number + USB_DIR_IN for input
1060 * @reset_hardware: flag to erase any endpoint state stored in the
1061 * controller hardware
1063 * Disables the endpoint for URB submission and nukes all pending URBs.
1064 * If @reset_hardware is set then also deallocates hcd/hardware state
1067 void usb_disable_endpoint(struct usb_device
*dev
, unsigned int epaddr
,
1068 bool reset_hardware
)
1070 unsigned int epnum
= epaddr
& USB_ENDPOINT_NUMBER_MASK
;
1071 struct usb_host_endpoint
*ep
;
1076 if (usb_endpoint_out(epaddr
)) {
1077 ep
= dev
->ep_out
[epnum
];
1079 dev
->ep_out
[epnum
] = NULL
;
1081 ep
= dev
->ep_in
[epnum
];
1083 dev
->ep_in
[epnum
] = NULL
;
1087 usb_hcd_flush_endpoint(dev
, ep
);
1089 usb_hcd_disable_endpoint(dev
, ep
);
1094 * usb_reset_endpoint - Reset an endpoint's state.
1095 * @dev: the device whose endpoint is to be reset
1096 * @epaddr: the endpoint's address. Endpoint number for output,
1097 * endpoint number + USB_DIR_IN for input
1099 * Resets any host-side endpoint state such as the toggle bit,
1100 * sequence number or current window.
1102 void usb_reset_endpoint(struct usb_device
*dev
, unsigned int epaddr
)
1104 unsigned int epnum
= epaddr
& USB_ENDPOINT_NUMBER_MASK
;
1105 struct usb_host_endpoint
*ep
;
1107 if (usb_endpoint_out(epaddr
))
1108 ep
= dev
->ep_out
[epnum
];
1110 ep
= dev
->ep_in
[epnum
];
1112 usb_hcd_reset_endpoint(dev
, ep
);
1114 EXPORT_SYMBOL_GPL(usb_reset_endpoint
);
1118 * usb_disable_interface -- Disable all endpoints for an interface
1119 * @dev: the device whose interface is being disabled
1120 * @intf: pointer to the interface descriptor
1121 * @reset_hardware: flag to erase any endpoint state stored in the
1122 * controller hardware
1124 * Disables all the endpoints for the interface's current altsetting.
1126 void usb_disable_interface(struct usb_device
*dev
, struct usb_interface
*intf
,
1127 bool reset_hardware
)
1129 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
1132 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
) {
1133 usb_disable_endpoint(dev
,
1134 alt
->endpoint
[i
].desc
.bEndpointAddress
,
1140 * usb_disable_device - Disable all the endpoints for a USB device
1141 * @dev: the device whose endpoints are being disabled
1142 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1144 * Disables all the device's endpoints, potentially including endpoint 0.
1145 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1146 * pending urbs) and usbcore state for the interfaces, so that usbcore
1147 * must usb_set_configuration() before any interfaces could be used.
1149 void usb_disable_device(struct usb_device
*dev
, int skip_ep0
)
1152 struct usb_hcd
*hcd
= bus_to_hcd(dev
->bus
);
1154 /* getting rid of interfaces will disconnect
1155 * any drivers bound to them (a key side effect)
1157 if (dev
->actconfig
) {
1159 * FIXME: In order to avoid self-deadlock involving the
1160 * bandwidth_mutex, we have to mark all the interfaces
1161 * before unregistering any of them.
1163 for (i
= 0; i
< dev
->actconfig
->desc
.bNumInterfaces
; i
++)
1164 dev
->actconfig
->interface
[i
]->unregistering
= 1;
1166 for (i
= 0; i
< dev
->actconfig
->desc
.bNumInterfaces
; i
++) {
1167 struct usb_interface
*interface
;
1169 /* remove this interface if it has been registered */
1170 interface
= dev
->actconfig
->interface
[i
];
1171 if (!device_is_registered(&interface
->dev
))
1173 dev_dbg(&dev
->dev
, "unregistering interface %s\n",
1174 dev_name(&interface
->dev
));
1175 remove_intf_ep_devs(interface
);
1176 device_del(&interface
->dev
);
1179 /* Now that the interfaces are unbound, nobody should
1180 * try to access them.
1182 for (i
= 0; i
< dev
->actconfig
->desc
.bNumInterfaces
; i
++) {
1183 put_device(&dev
->actconfig
->interface
[i
]->dev
);
1184 dev
->actconfig
->interface
[i
] = NULL
;
1187 if (dev
->usb2_hw_lpm_enabled
== 1)
1188 usb_set_usb2_hardware_lpm(dev
, 0);
1189 usb_unlocked_disable_lpm(dev
);
1190 usb_disable_ltm(dev
);
1192 dev
->actconfig
= NULL
;
1193 if (dev
->state
== USB_STATE_CONFIGURED
)
1194 usb_set_device_state(dev
, USB_STATE_ADDRESS
);
1197 dev_dbg(&dev
->dev
, "%s nuking %s URBs\n", __func__
,
1198 skip_ep0
? "non-ep0" : "all");
1199 if (hcd
->driver
->check_bandwidth
) {
1200 /* First pass: Cancel URBs, leave endpoint pointers intact. */
1201 for (i
= skip_ep0
; i
< 16; ++i
) {
1202 usb_disable_endpoint(dev
, i
, false);
1203 usb_disable_endpoint(dev
, i
+ USB_DIR_IN
, false);
1205 /* Remove endpoints from the host controller internal state */
1206 mutex_lock(hcd
->bandwidth_mutex
);
1207 usb_hcd_alloc_bandwidth(dev
, NULL
, NULL
, NULL
);
1208 mutex_unlock(hcd
->bandwidth_mutex
);
1209 /* Second pass: remove endpoint pointers */
1211 for (i
= skip_ep0
; i
< 16; ++i
) {
1212 usb_disable_endpoint(dev
, i
, true);
1213 usb_disable_endpoint(dev
, i
+ USB_DIR_IN
, true);
1218 * usb_enable_endpoint - Enable an endpoint for USB communications
1219 * @dev: the device whose interface is being enabled
1221 * @reset_ep: flag to reset the endpoint state
1223 * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
1224 * For control endpoints, both the input and output sides are handled.
1226 void usb_enable_endpoint(struct usb_device
*dev
, struct usb_host_endpoint
*ep
,
1229 int epnum
= usb_endpoint_num(&ep
->desc
);
1230 int is_out
= usb_endpoint_dir_out(&ep
->desc
);
1231 int is_control
= usb_endpoint_xfer_control(&ep
->desc
);
1234 usb_hcd_reset_endpoint(dev
, ep
);
1235 if (is_out
|| is_control
)
1236 dev
->ep_out
[epnum
] = ep
;
1237 if (!is_out
|| is_control
)
1238 dev
->ep_in
[epnum
] = ep
;
1243 * usb_enable_interface - Enable all the endpoints for an interface
1244 * @dev: the device whose interface is being enabled
1245 * @intf: pointer to the interface descriptor
1246 * @reset_eps: flag to reset the endpoints' state
1248 * Enables all the endpoints for the interface's current altsetting.
1250 void usb_enable_interface(struct usb_device
*dev
,
1251 struct usb_interface
*intf
, bool reset_eps
)
1253 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
1256 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
)
1257 usb_enable_endpoint(dev
, &alt
->endpoint
[i
], reset_eps
);
1261 * usb_set_interface - Makes a particular alternate setting be current
1262 * @dev: the device whose interface is being updated
1263 * @interface: the interface being updated
1264 * @alternate: the setting being chosen.
1265 * Context: !in_interrupt ()
1267 * This is used to enable data transfers on interfaces that may not
1268 * be enabled by default. Not all devices support such configurability.
1269 * Only the driver bound to an interface may change its setting.
1271 * Within any given configuration, each interface may have several
1272 * alternative settings. These are often used to control levels of
1273 * bandwidth consumption. For example, the default setting for a high
1274 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1275 * while interrupt transfers of up to 3KBytes per microframe are legal.
1276 * Also, isochronous endpoints may never be part of an
1277 * interface's default setting. To access such bandwidth, alternate
1278 * interface settings must be made current.
1280 * Note that in the Linux USB subsystem, bandwidth associated with
1281 * an endpoint in a given alternate setting is not reserved until an URB
1282 * is submitted that needs that bandwidth. Some other operating systems
1283 * allocate bandwidth early, when a configuration is chosen.
1285 * xHCI reserves bandwidth and configures the alternate setting in
1286 * usb_hcd_alloc_bandwidth(). If it fails the original interface altsetting
1287 * may be disabled. Drivers cannot rely on any particular alternate
1288 * setting being in effect after a failure.
1290 * This call is synchronous, and may not be used in an interrupt context.
1291 * Also, drivers must not change altsettings while urbs are scheduled for
1292 * endpoints in that interface; all such urbs must first be completed
1293 * (perhaps forced by unlinking).
1295 * Return: Zero on success, or else the status code returned by the
1296 * underlying usb_control_msg() call.
1298 int usb_set_interface(struct usb_device
*dev
, int interface
, int alternate
)
1300 struct usb_interface
*iface
;
1301 struct usb_host_interface
*alt
;
1302 struct usb_hcd
*hcd
= bus_to_hcd(dev
->bus
);
1303 int i
, ret
, manual
= 0;
1304 unsigned int epaddr
;
1307 if (dev
->state
== USB_STATE_SUSPENDED
)
1308 return -EHOSTUNREACH
;
1310 iface
= usb_ifnum_to_if(dev
, interface
);
1312 dev_dbg(&dev
->dev
, "selecting invalid interface %d\n",
1316 if (iface
->unregistering
)
1319 alt
= usb_altnum_to_altsetting(iface
, alternate
);
1321 dev_warn(&dev
->dev
, "selecting invalid altsetting %d\n",
1326 * usb3 hosts configure the interface in usb_hcd_alloc_bandwidth,
1327 * including freeing dropped endpoint ring buffers.
1328 * Make sure the interface endpoints are flushed before that
1330 usb_disable_interface(dev
, iface
, false);
1332 /* Make sure we have enough bandwidth for this alternate interface.
1333 * Remove the current alt setting and add the new alt setting.
1335 mutex_lock(hcd
->bandwidth_mutex
);
1336 /* Disable LPM, and re-enable it once the new alt setting is installed,
1337 * so that the xHCI driver can recalculate the U1/U2 timeouts.
1339 if (usb_disable_lpm(dev
)) {
1340 dev_err(&iface
->dev
, "%s Failed to disable LPM\n.", __func__
);
1341 mutex_unlock(hcd
->bandwidth_mutex
);
1344 /* Changing alt-setting also frees any allocated streams */
1345 for (i
= 0; i
< iface
->cur_altsetting
->desc
.bNumEndpoints
; i
++)
1346 iface
->cur_altsetting
->endpoint
[i
].streams
= 0;
1348 ret
= usb_hcd_alloc_bandwidth(dev
, NULL
, iface
->cur_altsetting
, alt
);
1350 dev_info(&dev
->dev
, "Not enough bandwidth for altsetting %d\n",
1352 usb_enable_lpm(dev
);
1353 mutex_unlock(hcd
->bandwidth_mutex
);
1357 if (dev
->quirks
& USB_QUIRK_NO_SET_INTF
)
1360 ret
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1361 USB_REQ_SET_INTERFACE
, USB_RECIP_INTERFACE
,
1362 alternate
, interface
, NULL
, 0, 5000);
1364 /* 9.4.10 says devices don't need this and are free to STALL the
1365 * request if the interface only has one alternate setting.
1367 if (ret
== -EPIPE
&& iface
->num_altsetting
== 1) {
1369 "manual set_interface for iface %d, alt %d\n",
1370 interface
, alternate
);
1372 } else if (ret
< 0) {
1373 /* Re-instate the old alt setting */
1374 usb_hcd_alloc_bandwidth(dev
, NULL
, alt
, iface
->cur_altsetting
);
1375 usb_enable_lpm(dev
);
1376 mutex_unlock(hcd
->bandwidth_mutex
);
1379 mutex_unlock(hcd
->bandwidth_mutex
);
1381 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1382 * when they implement async or easily-killable versions of this or
1383 * other "should-be-internal" functions (like clear_halt).
1384 * should hcd+usbcore postprocess control requests?
1387 /* prevent submissions using previous endpoint settings */
1388 if (iface
->cur_altsetting
!= alt
) {
1389 remove_intf_ep_devs(iface
);
1390 usb_remove_sysfs_intf_files(iface
);
1392 usb_disable_interface(dev
, iface
, true);
1394 iface
->cur_altsetting
= alt
;
1396 /* Now that the interface is installed, re-enable LPM. */
1397 usb_unlocked_enable_lpm(dev
);
1399 /* If the interface only has one altsetting and the device didn't
1400 * accept the request, we attempt to carry out the equivalent action
1401 * by manually clearing the HALT feature for each endpoint in the
1407 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; i
++) {
1408 epaddr
= alt
->endpoint
[i
].desc
.bEndpointAddress
;
1409 pipe
= __create_pipe(dev
,
1410 USB_ENDPOINT_NUMBER_MASK
& epaddr
) |
1411 (usb_endpoint_out(epaddr
) ?
1412 USB_DIR_OUT
: USB_DIR_IN
);
1414 usb_clear_halt(dev
, pipe
);
1418 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1421 * Despite EP0 is always present in all interfaces/AS, the list of
1422 * endpoints from the descriptor does not contain EP0. Due to its
1423 * omnipresence one might expect EP0 being considered "affected" by
1424 * any SetInterface request and hence assume toggles need to be reset.
1425 * However, EP0 toggles are re-synced for every individual transfer
1426 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1427 * (Likewise, EP0 never "halts" on well designed devices.)
1429 usb_enable_interface(dev
, iface
, true);
1430 if (device_is_registered(&iface
->dev
)) {
1431 usb_create_sysfs_intf_files(iface
);
1432 create_intf_ep_devs(iface
);
1436 EXPORT_SYMBOL_GPL(usb_set_interface
);
1439 * usb_reset_configuration - lightweight device reset
1440 * @dev: the device whose configuration is being reset
1442 * This issues a standard SET_CONFIGURATION request to the device using
1443 * the current configuration. The effect is to reset most USB-related
1444 * state in the device, including interface altsettings (reset to zero),
1445 * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
1446 * endpoints). Other usbcore state is unchanged, including bindings of
1447 * usb device drivers to interfaces.
1449 * Because this affects multiple interfaces, avoid using this with composite
1450 * (multi-interface) devices. Instead, the driver for each interface may
1451 * use usb_set_interface() on the interfaces it claims. Be careful though;
1452 * some devices don't support the SET_INTERFACE request, and others won't
1453 * reset all the interface state (notably endpoint state). Resetting the whole
1454 * configuration would affect other drivers' interfaces.
1456 * The caller must own the device lock.
1458 * Return: Zero on success, else a negative error code.
1460 int usb_reset_configuration(struct usb_device
*dev
)
1463 struct usb_host_config
*config
;
1464 struct usb_hcd
*hcd
= bus_to_hcd(dev
->bus
);
1466 if (dev
->state
== USB_STATE_SUSPENDED
)
1467 return -EHOSTUNREACH
;
1469 /* caller must have locked the device and must own
1470 * the usb bus readlock (so driver bindings are stable);
1471 * calls during probe() are fine
1474 for (i
= 1; i
< 16; ++i
) {
1475 usb_disable_endpoint(dev
, i
, true);
1476 usb_disable_endpoint(dev
, i
+ USB_DIR_IN
, true);
1479 config
= dev
->actconfig
;
1481 mutex_lock(hcd
->bandwidth_mutex
);
1482 /* Disable LPM, and re-enable it once the configuration is reset, so
1483 * that the xHCI driver can recalculate the U1/U2 timeouts.
1485 if (usb_disable_lpm(dev
)) {
1486 dev_err(&dev
->dev
, "%s Failed to disable LPM\n.", __func__
);
1487 mutex_unlock(hcd
->bandwidth_mutex
);
1490 /* Make sure we have enough bandwidth for each alternate setting 0 */
1491 for (i
= 0; i
< config
->desc
.bNumInterfaces
; i
++) {
1492 struct usb_interface
*intf
= config
->interface
[i
];
1493 struct usb_host_interface
*alt
;
1495 alt
= usb_altnum_to_altsetting(intf
, 0);
1497 alt
= &intf
->altsetting
[0];
1498 if (alt
!= intf
->cur_altsetting
)
1499 retval
= usb_hcd_alloc_bandwidth(dev
, NULL
,
1500 intf
->cur_altsetting
, alt
);
1504 /* If not, reinstate the old alternate settings */
1507 for (i
--; i
>= 0; i
--) {
1508 struct usb_interface
*intf
= config
->interface
[i
];
1509 struct usb_host_interface
*alt
;
1511 alt
= usb_altnum_to_altsetting(intf
, 0);
1513 alt
= &intf
->altsetting
[0];
1514 if (alt
!= intf
->cur_altsetting
)
1515 usb_hcd_alloc_bandwidth(dev
, NULL
,
1516 alt
, intf
->cur_altsetting
);
1518 usb_enable_lpm(dev
);
1519 mutex_unlock(hcd
->bandwidth_mutex
);
1522 retval
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1523 USB_REQ_SET_CONFIGURATION
, 0,
1524 config
->desc
.bConfigurationValue
, 0,
1525 NULL
, 0, USB_CTRL_SET_TIMEOUT
);
1527 goto reset_old_alts
;
1528 mutex_unlock(hcd
->bandwidth_mutex
);
1530 /* re-init hc/hcd interface/endpoint state */
1531 for (i
= 0; i
< config
->desc
.bNumInterfaces
; i
++) {
1532 struct usb_interface
*intf
= config
->interface
[i
];
1533 struct usb_host_interface
*alt
;
1535 alt
= usb_altnum_to_altsetting(intf
, 0);
1537 /* No altsetting 0? We'll assume the first altsetting.
1538 * We could use a GetInterface call, but if a device is
1539 * so non-compliant that it doesn't have altsetting 0
1540 * then I wouldn't trust its reply anyway.
1543 alt
= &intf
->altsetting
[0];
1545 if (alt
!= intf
->cur_altsetting
) {
1546 remove_intf_ep_devs(intf
);
1547 usb_remove_sysfs_intf_files(intf
);
1549 intf
->cur_altsetting
= alt
;
1550 usb_enable_interface(dev
, intf
, true);
1551 if (device_is_registered(&intf
->dev
)) {
1552 usb_create_sysfs_intf_files(intf
);
1553 create_intf_ep_devs(intf
);
1556 /* Now that the interfaces are installed, re-enable LPM. */
1557 usb_unlocked_enable_lpm(dev
);
1560 EXPORT_SYMBOL_GPL(usb_reset_configuration
);
1562 static void usb_release_interface(struct device
*dev
)
1564 struct usb_interface
*intf
= to_usb_interface(dev
);
1565 struct usb_interface_cache
*intfc
=
1566 altsetting_to_usb_interface_cache(intf
->altsetting
);
1568 kref_put(&intfc
->ref
, usb_release_interface_cache
);
1569 usb_put_dev(interface_to_usbdev(intf
));
1573 static int usb_if_uevent(struct device
*dev
, struct kobj_uevent_env
*env
)
1575 struct usb_device
*usb_dev
;
1576 struct usb_interface
*intf
;
1577 struct usb_host_interface
*alt
;
1579 intf
= to_usb_interface(dev
);
1580 usb_dev
= interface_to_usbdev(intf
);
1581 alt
= intf
->cur_altsetting
;
1583 if (add_uevent_var(env
, "INTERFACE=%d/%d/%d",
1584 alt
->desc
.bInterfaceClass
,
1585 alt
->desc
.bInterfaceSubClass
,
1586 alt
->desc
.bInterfaceProtocol
))
1589 if (add_uevent_var(env
,
1591 "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
1592 le16_to_cpu(usb_dev
->descriptor
.idVendor
),
1593 le16_to_cpu(usb_dev
->descriptor
.idProduct
),
1594 le16_to_cpu(usb_dev
->descriptor
.bcdDevice
),
1595 usb_dev
->descriptor
.bDeviceClass
,
1596 usb_dev
->descriptor
.bDeviceSubClass
,
1597 usb_dev
->descriptor
.bDeviceProtocol
,
1598 alt
->desc
.bInterfaceClass
,
1599 alt
->desc
.bInterfaceSubClass
,
1600 alt
->desc
.bInterfaceProtocol
,
1601 alt
->desc
.bInterfaceNumber
))
1607 struct device_type usb_if_device_type
= {
1608 .name
= "usb_interface",
1609 .release
= usb_release_interface
,
1610 .uevent
= usb_if_uevent
,
1613 static struct usb_interface_assoc_descriptor
*find_iad(struct usb_device
*dev
,
1614 struct usb_host_config
*config
,
1617 struct usb_interface_assoc_descriptor
*retval
= NULL
;
1618 struct usb_interface_assoc_descriptor
*intf_assoc
;
1623 for (i
= 0; (i
< USB_MAXIADS
&& config
->intf_assoc
[i
]); i
++) {
1624 intf_assoc
= config
->intf_assoc
[i
];
1625 if (intf_assoc
->bInterfaceCount
== 0)
1628 first_intf
= intf_assoc
->bFirstInterface
;
1629 last_intf
= first_intf
+ (intf_assoc
->bInterfaceCount
- 1);
1630 if (inum
>= first_intf
&& inum
<= last_intf
) {
1632 retval
= intf_assoc
;
1634 dev_err(&dev
->dev
, "Interface #%d referenced"
1635 " by multiple IADs\n", inum
);
1644 * Internal function to queue a device reset
1645 * See usb_queue_reset_device() for more details
1647 static void __usb_queue_reset_device(struct work_struct
*ws
)
1650 struct usb_interface
*iface
=
1651 container_of(ws
, struct usb_interface
, reset_ws
);
1652 struct usb_device
*udev
= interface_to_usbdev(iface
);
1654 rc
= usb_lock_device_for_reset(udev
, iface
);
1656 usb_reset_device(udev
);
1657 usb_unlock_device(udev
);
1659 usb_put_intf(iface
); /* Undo _get_ in usb_queue_reset_device() */
1664 * usb_set_configuration - Makes a particular device setting be current
1665 * @dev: the device whose configuration is being updated
1666 * @configuration: the configuration being chosen.
1667 * Context: !in_interrupt(), caller owns the device lock
1669 * This is used to enable non-default device modes. Not all devices
1670 * use this kind of configurability; many devices only have one
1673 * @configuration is the value of the configuration to be installed.
1674 * According to the USB spec (e.g. section 9.1.1.5), configuration values
1675 * must be non-zero; a value of zero indicates that the device in
1676 * unconfigured. However some devices erroneously use 0 as one of their
1677 * configuration values. To help manage such devices, this routine will
1678 * accept @configuration = -1 as indicating the device should be put in
1679 * an unconfigured state.
1681 * USB device configurations may affect Linux interoperability,
1682 * power consumption and the functionality available. For example,
1683 * the default configuration is limited to using 100mA of bus power,
1684 * so that when certain device functionality requires more power,
1685 * and the device is bus powered, that functionality should be in some
1686 * non-default device configuration. Other device modes may also be
1687 * reflected as configuration options, such as whether two ISDN
1688 * channels are available independently; and choosing between open
1689 * standard device protocols (like CDC) or proprietary ones.
1691 * Note that a non-authorized device (dev->authorized == 0) will only
1692 * be put in unconfigured mode.
1694 * Note that USB has an additional level of device configurability,
1695 * associated with interfaces. That configurability is accessed using
1696 * usb_set_interface().
1698 * This call is synchronous. The calling context must be able to sleep,
1699 * must own the device lock, and must not hold the driver model's USB
1700 * bus mutex; usb interface driver probe() methods cannot use this routine.
1702 * Returns zero on success, or else the status code returned by the
1703 * underlying call that failed. On successful completion, each interface
1704 * in the original device configuration has been destroyed, and each one
1705 * in the new configuration has been probed by all relevant usb device
1706 * drivers currently known to the kernel.
1708 int usb_set_configuration(struct usb_device
*dev
, int configuration
)
1711 struct usb_host_config
*cp
= NULL
;
1712 struct usb_interface
**new_interfaces
= NULL
;
1713 struct usb_hcd
*hcd
= bus_to_hcd(dev
->bus
);
1716 if (dev
->authorized
== 0 || configuration
== -1)
1719 for (i
= 0; i
< dev
->descriptor
.bNumConfigurations
; i
++) {
1720 if (dev
->config
[i
].desc
.bConfigurationValue
==
1722 cp
= &dev
->config
[i
];
1727 if ((!cp
&& configuration
!= 0))
1730 /* The USB spec says configuration 0 means unconfigured.
1731 * But if a device includes a configuration numbered 0,
1732 * we will accept it as a correctly configured state.
1733 * Use -1 if you really want to unconfigure the device.
1735 if (cp
&& configuration
== 0)
1736 dev_warn(&dev
->dev
, "config 0 descriptor??\n");
1738 /* Allocate memory for new interfaces before doing anything else,
1739 * so that if we run out then nothing will have changed. */
1742 nintf
= cp
->desc
.bNumInterfaces
;
1743 new_interfaces
= kmalloc(nintf
* sizeof(*new_interfaces
),
1745 if (!new_interfaces
) {
1746 dev_err(&dev
->dev
, "Out of memory\n");
1750 for (; n
< nintf
; ++n
) {
1751 new_interfaces
[n
] = kzalloc(
1752 sizeof(struct usb_interface
),
1754 if (!new_interfaces
[n
]) {
1755 dev_err(&dev
->dev
, "Out of memory\n");
1759 kfree(new_interfaces
[n
]);
1760 kfree(new_interfaces
);
1765 i
= dev
->bus_mA
- usb_get_max_power(dev
, cp
);
1767 dev_warn(&dev
->dev
, "new config #%d exceeds power "
1772 /* Wake up the device so we can send it the Set-Config request */
1773 ret
= usb_autoresume_device(dev
);
1775 goto free_interfaces
;
1777 /* if it's already configured, clear out old state first.
1778 * getting rid of old interfaces means unbinding their drivers.
1780 if (dev
->state
!= USB_STATE_ADDRESS
)
1781 usb_disable_device(dev
, 1); /* Skip ep0 */
1783 /* Get rid of pending async Set-Config requests for this device */
1784 cancel_async_set_config(dev
);
1786 /* Make sure we have bandwidth (and available HCD resources) for this
1787 * configuration. Remove endpoints from the schedule if we're dropping
1788 * this configuration to set configuration 0. After this point, the
1789 * host controller will not allow submissions to dropped endpoints. If
1790 * this call fails, the device state is unchanged.
1792 mutex_lock(hcd
->bandwidth_mutex
);
1793 /* Disable LPM, and re-enable it once the new configuration is
1794 * installed, so that the xHCI driver can recalculate the U1/U2
1797 if (dev
->actconfig
&& usb_disable_lpm(dev
)) {
1798 dev_err(&dev
->dev
, "%s Failed to disable LPM\n.", __func__
);
1799 mutex_unlock(hcd
->bandwidth_mutex
);
1801 goto free_interfaces
;
1803 ret
= usb_hcd_alloc_bandwidth(dev
, cp
, NULL
, NULL
);
1806 usb_enable_lpm(dev
);
1807 mutex_unlock(hcd
->bandwidth_mutex
);
1808 usb_autosuspend_device(dev
);
1809 goto free_interfaces
;
1813 * Initialize the new interface structures and the
1814 * hc/hcd/usbcore interface/endpoint state.
1816 for (i
= 0; i
< nintf
; ++i
) {
1817 struct usb_interface_cache
*intfc
;
1818 struct usb_interface
*intf
;
1819 struct usb_host_interface
*alt
;
1821 cp
->interface
[i
] = intf
= new_interfaces
[i
];
1822 intfc
= cp
->intf_cache
[i
];
1823 intf
->altsetting
= intfc
->altsetting
;
1824 intf
->num_altsetting
= intfc
->num_altsetting
;
1825 kref_get(&intfc
->ref
);
1827 alt
= usb_altnum_to_altsetting(intf
, 0);
1829 /* No altsetting 0? We'll assume the first altsetting.
1830 * We could use a GetInterface call, but if a device is
1831 * so non-compliant that it doesn't have altsetting 0
1832 * then I wouldn't trust its reply anyway.
1835 alt
= &intf
->altsetting
[0];
1838 find_iad(dev
, cp
, alt
->desc
.bInterfaceNumber
);
1839 intf
->cur_altsetting
= alt
;
1840 usb_enable_interface(dev
, intf
, true);
1841 intf
->dev
.parent
= &dev
->dev
;
1842 intf
->dev
.driver
= NULL
;
1843 intf
->dev
.bus
= &usb_bus_type
;
1844 intf
->dev
.type
= &usb_if_device_type
;
1845 intf
->dev
.groups
= usb_interface_groups
;
1846 intf
->dev
.dma_mask
= dev
->dev
.dma_mask
;
1847 INIT_WORK(&intf
->reset_ws
, __usb_queue_reset_device
);
1849 device_initialize(&intf
->dev
);
1850 pm_runtime_no_callbacks(&intf
->dev
);
1851 dev_set_name(&intf
->dev
, "%d-%s:%d.%d",
1852 dev
->bus
->busnum
, dev
->devpath
,
1853 configuration
, alt
->desc
.bInterfaceNumber
);
1856 kfree(new_interfaces
);
1858 ret
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1859 USB_REQ_SET_CONFIGURATION
, 0, configuration
, 0,
1860 NULL
, 0, USB_CTRL_SET_TIMEOUT
);
1861 if (ret
< 0 && cp
) {
1863 * All the old state is gone, so what else can we do?
1864 * The device is probably useless now anyway.
1866 usb_hcd_alloc_bandwidth(dev
, NULL
, NULL
, NULL
);
1867 for (i
= 0; i
< nintf
; ++i
) {
1868 usb_disable_interface(dev
, cp
->interface
[i
], true);
1869 put_device(&cp
->interface
[i
]->dev
);
1870 cp
->interface
[i
] = NULL
;
1875 dev
->actconfig
= cp
;
1876 mutex_unlock(hcd
->bandwidth_mutex
);
1879 usb_set_device_state(dev
, USB_STATE_ADDRESS
);
1881 /* Leave LPM disabled while the device is unconfigured. */
1882 usb_autosuspend_device(dev
);
1885 usb_set_device_state(dev
, USB_STATE_CONFIGURED
);
1887 if (cp
->string
== NULL
&&
1888 !(dev
->quirks
& USB_QUIRK_CONFIG_INTF_STRINGS
))
1889 cp
->string
= usb_cache_string(dev
, cp
->desc
.iConfiguration
);
1891 /* Now that the interfaces are installed, re-enable LPM. */
1892 usb_unlocked_enable_lpm(dev
);
1893 /* Enable LTM if it was turned off by usb_disable_device. */
1894 usb_enable_ltm(dev
);
1896 /* Now that all the interfaces are set up, register them
1897 * to trigger binding of drivers to interfaces. probe()
1898 * routines may install different altsettings and may
1899 * claim() any interfaces not yet bound. Many class drivers
1900 * need that: CDC, audio, video, etc.
1902 for (i
= 0; i
< nintf
; ++i
) {
1903 struct usb_interface
*intf
= cp
->interface
[i
];
1906 "adding %s (config #%d, interface %d)\n",
1907 dev_name(&intf
->dev
), configuration
,
1908 intf
->cur_altsetting
->desc
.bInterfaceNumber
);
1909 device_enable_async_suspend(&intf
->dev
);
1910 ret
= device_add(&intf
->dev
);
1912 dev_err(&dev
->dev
, "device_add(%s) --> %d\n",
1913 dev_name(&intf
->dev
), ret
);
1916 create_intf_ep_devs(intf
);
1919 usb_autosuspend_device(dev
);
1922 EXPORT_SYMBOL_GPL(usb_set_configuration
);
1924 static LIST_HEAD(set_config_list
);
1925 static DEFINE_SPINLOCK(set_config_lock
);
1927 struct set_config_request
{
1928 struct usb_device
*udev
;
1930 struct work_struct work
;
1931 struct list_head node
;
1934 /* Worker routine for usb_driver_set_configuration() */
1935 static void driver_set_config_work(struct work_struct
*work
)
1937 struct set_config_request
*req
=
1938 container_of(work
, struct set_config_request
, work
);
1939 struct usb_device
*udev
= req
->udev
;
1941 usb_lock_device(udev
);
1942 spin_lock(&set_config_lock
);
1943 list_del(&req
->node
);
1944 spin_unlock(&set_config_lock
);
1946 if (req
->config
>= -1) /* Is req still valid? */
1947 usb_set_configuration(udev
, req
->config
);
1948 usb_unlock_device(udev
);
1953 /* Cancel pending Set-Config requests for a device whose configuration
1956 static void cancel_async_set_config(struct usb_device
*udev
)
1958 struct set_config_request
*req
;
1960 spin_lock(&set_config_lock
);
1961 list_for_each_entry(req
, &set_config_list
, node
) {
1962 if (req
->udev
== udev
)
1963 req
->config
= -999; /* Mark as cancelled */
1965 spin_unlock(&set_config_lock
);
1969 * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1970 * @udev: the device whose configuration is being updated
1971 * @config: the configuration being chosen.
1972 * Context: In process context, must be able to sleep
1974 * Device interface drivers are not allowed to change device configurations.
1975 * This is because changing configurations will destroy the interface the
1976 * driver is bound to and create new ones; it would be like a floppy-disk
1977 * driver telling the computer to replace the floppy-disk drive with a
1980 * Still, in certain specialized circumstances the need may arise. This
1981 * routine gets around the normal restrictions by using a work thread to
1982 * submit the change-config request.
1984 * Return: 0 if the request was successfully queued, error code otherwise.
1985 * The caller has no way to know whether the queued request will eventually
1988 int usb_driver_set_configuration(struct usb_device
*udev
, int config
)
1990 struct set_config_request
*req
;
1992 req
= kmalloc(sizeof(*req
), GFP_KERNEL
);
1996 req
->config
= config
;
1997 INIT_WORK(&req
->work
, driver_set_config_work
);
1999 spin_lock(&set_config_lock
);
2000 list_add(&req
->node
, &set_config_list
);
2001 spin_unlock(&set_config_lock
);
2004 schedule_work(&req
->work
);
2007 EXPORT_SYMBOL_GPL(usb_driver_set_configuration
);