writeback: split writeback_inodes_wb
[linux-2.6/next.git] / drivers / usb / core / message.c
bloba73e08fdab36336fee6f14bacef1c7dd1ec58764
1 /*
2 * message.c - synchronous message handling
3 */
5 #include <linux/pci.h> /* for scatterlist macros */
6 #include <linux/usb.h>
7 #include <linux/module.h>
8 #include <linux/slab.h>
9 #include <linux/init.h>
10 #include <linux/mm.h>
11 #include <linux/timer.h>
12 #include <linux/ctype.h>
13 #include <linux/nls.h>
14 #include <linux/device.h>
15 #include <linux/scatterlist.h>
16 #include <linux/usb/quirks.h>
17 #include <linux/usb/hcd.h> /* for usbcore internals */
18 #include <asm/byteorder.h>
20 #include "usb.h"
22 static void cancel_async_set_config(struct usb_device *udev);
24 struct api_context {
25 struct completion done;
26 int status;
29 static void usb_api_blocking_completion(struct urb *urb)
31 struct api_context *ctx = urb->context;
33 ctx->status = urb->status;
34 complete(&ctx->done);
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;
47 unsigned long expire;
48 int retval;
50 init_completion(&ctx.done);
51 urb->context = &ctx;
52 urb->actual_length = 0;
53 retval = usb_submit_urb(urb, GFP_NOIO);
54 if (unlikely(retval))
55 goto out;
57 expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
58 if (!wait_for_completion_timeout(&ctx.done, expire)) {
59 usb_kill_urb(urb);
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",
64 current->comm,
65 usb_endpoint_num(&urb->ep->desc),
66 usb_urb_dir_in(urb) ? "in" : "out",
67 urb->actual_length,
68 urb->transfer_buffer_length);
69 } else
70 retval = ctx.status;
71 out:
72 if (actual_length)
73 *actual_length = urb->actual_length;
75 usb_free_urb(urb);
76 return retval;
79 /*-------------------------------------------------------------------*/
80 /* returns status (negative) or length (positive) */
81 static int usb_internal_control_msg(struct usb_device *usb_dev,
82 unsigned int pipe,
83 struct usb_ctrlrequest *cmd,
84 void *data, int len, int timeout)
86 struct urb *urb;
87 int retv;
88 int length;
90 urb = usb_alloc_urb(0, GFP_NOIO);
91 if (!urb)
92 return -ENOMEM;
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);
98 if (retv < 0)
99 return retv;
100 else
101 return 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 * If successful, it returns the number of bytes transferred, otherwise a
123 * negative error number.
125 * Don't use this function from within an interrupt context, like a bottom half
126 * handler. If you need an asynchronous message, or need to send a message
127 * from within interrupt context, use usb_submit_urb().
128 * If a thread in your driver uses this call, make sure your disconnect()
129 * method can wait for it to complete. Since you don't have a handle on the
130 * URB used, you can't cancel the request.
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;
137 int ret;
139 dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
140 if (!dr)
141 return -ENOMEM;
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 /* dbg("usb_control_msg"); */
151 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
153 kfree(dr);
155 return ret;
157 EXPORT_SYMBOL_GPL(usb_control_msg);
160 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
161 * @usb_dev: pointer to the usb device to send the message to
162 * @pipe: endpoint "pipe" to send the message to
163 * @data: pointer to the data to send
164 * @len: length in bytes of the data to send
165 * @actual_length: pointer to a location to put the actual length transferred
166 * in bytes
167 * @timeout: time in msecs to wait for the message to complete before
168 * timing out (if 0 the wait is forever)
170 * Context: !in_interrupt ()
172 * This function sends a simple interrupt message to a specified endpoint and
173 * waits for the message to complete, or timeout.
175 * If successful, it returns 0, otherwise a negative error number. The number
176 * of actual bytes transferred will be stored in the actual_length paramater.
178 * Don't use this function from within an interrupt context, like a bottom half
179 * handler. If you need an asynchronous message, or need to send a message
180 * from within interrupt context, use usb_submit_urb() If a thread in your
181 * driver uses this call, make sure your disconnect() method can wait for it to
182 * complete. Since you don't have a handle on the URB used, you can't cancel
183 * the request.
185 int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
186 void *data, int len, int *actual_length, int timeout)
188 return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
190 EXPORT_SYMBOL_GPL(usb_interrupt_msg);
193 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
194 * @usb_dev: pointer to the usb device to send the message to
195 * @pipe: endpoint "pipe" to send the message to
196 * @data: pointer to the data to send
197 * @len: length in bytes of the data to send
198 * @actual_length: pointer to a location to put the actual length transferred
199 * in bytes
200 * @timeout: time in msecs to wait for the message to complete before
201 * timing out (if 0 the wait is forever)
203 * Context: !in_interrupt ()
205 * This function sends a simple bulk message to a specified endpoint
206 * and waits for the message to complete, or timeout.
208 * If successful, it returns 0, otherwise a negative error number. The number
209 * of actual bytes transferred will be stored in the actual_length paramater.
211 * Don't use this function from within an interrupt context, like a bottom half
212 * handler. If you need an asynchronous message, or need to send a message
213 * from within interrupt context, use usb_submit_urb() If a thread in your
214 * driver uses this call, make sure your disconnect() method can wait for it to
215 * complete. Since you don't have a handle on the URB used, you can't cancel
216 * the request.
218 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
219 * users are forced to abuse this routine by using it to submit URBs for
220 * interrupt endpoints. We will take the liberty of creating an interrupt URB
221 * (with the default interval) if the target is an interrupt endpoint.
223 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
224 void *data, int len, int *actual_length, int timeout)
226 struct urb *urb;
227 struct usb_host_endpoint *ep;
229 ep = usb_pipe_endpoint(usb_dev, pipe);
230 if (!ep || len < 0)
231 return -EINVAL;
233 urb = usb_alloc_urb(0, GFP_KERNEL);
234 if (!urb)
235 return -ENOMEM;
237 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
238 USB_ENDPOINT_XFER_INT) {
239 pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
240 usb_fill_int_urb(urb, usb_dev, pipe, data, len,
241 usb_api_blocking_completion, NULL,
242 ep->desc.bInterval);
243 } else
244 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
245 usb_api_blocking_completion, NULL);
247 return usb_start_wait_urb(urb, timeout, actual_length);
249 EXPORT_SYMBOL_GPL(usb_bulk_msg);
251 /*-------------------------------------------------------------------*/
253 static void sg_clean(struct usb_sg_request *io)
255 if (io->urbs) {
256 while (io->entries--)
257 usb_free_urb(io->urbs [io->entries]);
258 kfree(io->urbs);
259 io->urbs = NULL;
261 io->dev = NULL;
264 static void sg_complete(struct urb *urb)
266 struct usb_sg_request *io = urb->context;
267 int status = urb->status;
269 spin_lock(&io->lock);
271 /* In 2.5 we require hcds' endpoint queues not to progress after fault
272 * reports, until the completion callback (this!) returns. That lets
273 * device driver code (like this routine) unlink queued urbs first,
274 * if it needs to, since the HC won't work on them at all. So it's
275 * not possible for page N+1 to overwrite page N, and so on.
277 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
278 * complete before the HCD can get requests away from hardware,
279 * though never during cleanup after a hard fault.
281 if (io->status
282 && (io->status != -ECONNRESET
283 || status != -ECONNRESET)
284 && urb->actual_length) {
285 dev_err(io->dev->bus->controller,
286 "dev %s ep%d%s scatterlist error %d/%d\n",
287 io->dev->devpath,
288 usb_endpoint_num(&urb->ep->desc),
289 usb_urb_dir_in(urb) ? "in" : "out",
290 status, io->status);
291 /* BUG (); */
294 if (io->status == 0 && status && status != -ECONNRESET) {
295 int i, found, retval;
297 io->status = status;
299 /* the previous urbs, and this one, completed already.
300 * unlink pending urbs so they won't rx/tx bad data.
301 * careful: unlink can sometimes be synchronous...
303 spin_unlock(&io->lock);
304 for (i = 0, found = 0; i < io->entries; i++) {
305 if (!io->urbs [i] || !io->urbs [i]->dev)
306 continue;
307 if (found) {
308 retval = usb_unlink_urb(io->urbs [i]);
309 if (retval != -EINPROGRESS &&
310 retval != -ENODEV &&
311 retval != -EBUSY)
312 dev_err(&io->dev->dev,
313 "%s, unlink --> %d\n",
314 __func__, retval);
315 } else if (urb == io->urbs [i])
316 found = 1;
318 spin_lock(&io->lock);
320 urb->dev = NULL;
322 /* on the last completion, signal usb_sg_wait() */
323 io->bytes += urb->actual_length;
324 io->count--;
325 if (!io->count)
326 complete(&io->complete);
328 spin_unlock(&io->lock);
333 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
334 * @io: request block being initialized. until usb_sg_wait() returns,
335 * treat this as a pointer to an opaque block of memory,
336 * @dev: the usb device that will send or receive the data
337 * @pipe: endpoint "pipe" used to transfer the data
338 * @period: polling rate for interrupt endpoints, in frames or
339 * (for high speed endpoints) microframes; ignored for bulk
340 * @sg: scatterlist entries
341 * @nents: how many entries in the scatterlist
342 * @length: how many bytes to send from the scatterlist, or zero to
343 * send every byte identified in the list.
344 * @mem_flags: SLAB_* flags affecting memory allocations in this call
346 * Returns zero for success, else a negative errno value. This initializes a
347 * scatter/gather request, allocating resources such as I/O mappings and urb
348 * memory (except maybe memory used by USB controller drivers).
350 * The request must be issued using usb_sg_wait(), which waits for the I/O to
351 * complete (or to be canceled) and then cleans up all resources allocated by
352 * usb_sg_init().
354 * The request may be canceled with usb_sg_cancel(), either before or after
355 * usb_sg_wait() is called.
357 int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
358 unsigned pipe, unsigned period, struct scatterlist *sg,
359 int nents, size_t length, gfp_t mem_flags)
361 int i;
362 int urb_flags;
363 int use_sg;
365 if (!io || !dev || !sg
366 || usb_pipecontrol(pipe)
367 || usb_pipeisoc(pipe)
368 || nents <= 0)
369 return -EINVAL;
371 spin_lock_init(&io->lock);
372 io->dev = dev;
373 io->pipe = pipe;
375 if (dev->bus->sg_tablesize > 0) {
376 use_sg = true;
377 io->entries = 1;
378 } else {
379 use_sg = false;
380 io->entries = nents;
383 /* initialize all the urbs we'll use */
384 io->urbs = kmalloc(io->entries * sizeof *io->urbs, mem_flags);
385 if (!io->urbs)
386 goto nomem;
388 urb_flags = URB_NO_INTERRUPT;
389 if (usb_pipein(pipe))
390 urb_flags |= URB_SHORT_NOT_OK;
392 for_each_sg(sg, sg, io->entries, i) {
393 struct urb *urb;
394 unsigned len;
396 urb = usb_alloc_urb(0, mem_flags);
397 if (!urb) {
398 io->entries = i;
399 goto nomem;
401 io->urbs[i] = urb;
403 urb->dev = NULL;
404 urb->pipe = pipe;
405 urb->interval = period;
406 urb->transfer_flags = urb_flags;
407 urb->complete = sg_complete;
408 urb->context = io;
409 urb->sg = sg;
411 if (use_sg) {
412 /* There is no single transfer buffer */
413 urb->transfer_buffer = NULL;
414 urb->num_sgs = nents;
416 /* A length of zero means transfer the whole sg list */
417 len = length;
418 if (len == 0) {
419 for_each_sg(sg, sg, nents, i)
420 len += sg->length;
422 } else {
424 * Some systems can't use DMA; they use PIO instead.
425 * For their sakes, transfer_buffer is set whenever
426 * possible.
428 if (!PageHighMem(sg_page(sg)))
429 urb->transfer_buffer = sg_virt(sg);
430 else
431 urb->transfer_buffer = NULL;
433 len = sg->length;
434 if (length) {
435 len = min_t(unsigned, len, length);
436 length -= len;
437 if (length == 0)
438 io->entries = i + 1;
441 urb->transfer_buffer_length = len;
443 io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
445 /* transaction state */
446 io->count = io->entries;
447 io->status = 0;
448 io->bytes = 0;
449 init_completion(&io->complete);
450 return 0;
452 nomem:
453 sg_clean(io);
454 return -ENOMEM;
456 EXPORT_SYMBOL_GPL(usb_sg_init);
459 * usb_sg_wait - synchronously execute scatter/gather request
460 * @io: request block handle, as initialized with usb_sg_init().
461 * some fields become accessible when this call returns.
462 * Context: !in_interrupt ()
464 * This function blocks until the specified I/O operation completes. It
465 * leverages the grouping of the related I/O requests to get good transfer
466 * rates, by queueing the requests. At higher speeds, such queuing can
467 * significantly improve USB throughput.
469 * There are three kinds of completion for this function.
470 * (1) success, where io->status is zero. The number of io->bytes
471 * transferred is as requested.
472 * (2) error, where io->status is a negative errno value. The number
473 * of io->bytes transferred before the error is usually less
474 * than requested, and can be nonzero.
475 * (3) cancellation, a type of error with status -ECONNRESET that
476 * is initiated by usb_sg_cancel().
478 * When this function returns, all memory allocated through usb_sg_init() or
479 * this call will have been freed. The request block parameter may still be
480 * passed to usb_sg_cancel(), or it may be freed. It could also be
481 * reinitialized and then reused.
483 * Data Transfer Rates:
485 * Bulk transfers are valid for full or high speed endpoints.
486 * The best full speed data rate is 19 packets of 64 bytes each
487 * per frame, or 1216 bytes per millisecond.
488 * The best high speed data rate is 13 packets of 512 bytes each
489 * per microframe, or 52 KBytes per millisecond.
491 * The reason to use interrupt transfers through this API would most likely
492 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
493 * could be transferred. That capability is less useful for low or full
494 * speed interrupt endpoints, which allow at most one packet per millisecond,
495 * of at most 8 or 64 bytes (respectively).
497 * It is not necessary to call this function to reserve bandwidth for devices
498 * under an xHCI host controller, as the bandwidth is reserved when the
499 * configuration or interface alt setting is selected.
501 void usb_sg_wait(struct usb_sg_request *io)
503 int i;
504 int entries = io->entries;
506 /* queue the urbs. */
507 spin_lock_irq(&io->lock);
508 i = 0;
509 while (i < entries && !io->status) {
510 int retval;
512 io->urbs[i]->dev = io->dev;
513 retval = usb_submit_urb(io->urbs [i], GFP_ATOMIC);
515 /* after we submit, let completions or cancelations fire;
516 * we handshake using io->status.
518 spin_unlock_irq(&io->lock);
519 switch (retval) {
520 /* maybe we retrying will recover */
521 case -ENXIO: /* hc didn't queue this one */
522 case -EAGAIN:
523 case -ENOMEM:
524 io->urbs[i]->dev = NULL;
525 retval = 0;
526 yield();
527 break;
529 /* no error? continue immediately.
531 * NOTE: to work better with UHCI (4K I/O buffer may
532 * need 3K of TDs) it may be good to limit how many
533 * URBs are queued at once; N milliseconds?
535 case 0:
536 ++i;
537 cpu_relax();
538 break;
540 /* fail any uncompleted urbs */
541 default:
542 io->urbs[i]->dev = NULL;
543 io->urbs[i]->status = retval;
544 dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
545 __func__, retval);
546 usb_sg_cancel(io);
548 spin_lock_irq(&io->lock);
549 if (retval && (io->status == 0 || io->status == -ECONNRESET))
550 io->status = retval;
552 io->count -= entries - i;
553 if (io->count == 0)
554 complete(&io->complete);
555 spin_unlock_irq(&io->lock);
557 /* OK, yes, this could be packaged as non-blocking.
558 * So could the submit loop above ... but it's easier to
559 * solve neither problem than to solve both!
561 wait_for_completion(&io->complete);
563 sg_clean(io);
565 EXPORT_SYMBOL_GPL(usb_sg_wait);
568 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
569 * @io: request block, initialized with usb_sg_init()
571 * This stops a request after it has been started by usb_sg_wait().
572 * It can also prevents one initialized by usb_sg_init() from starting,
573 * so that call just frees resources allocated to the request.
575 void usb_sg_cancel(struct usb_sg_request *io)
577 unsigned long flags;
579 spin_lock_irqsave(&io->lock, flags);
581 /* shut everything down, if it didn't already */
582 if (!io->status) {
583 int i;
585 io->status = -ECONNRESET;
586 spin_unlock(&io->lock);
587 for (i = 0; i < io->entries; i++) {
588 int retval;
590 if (!io->urbs [i]->dev)
591 continue;
592 retval = usb_unlink_urb(io->urbs [i]);
593 if (retval != -EINPROGRESS && retval != -EBUSY)
594 dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
595 __func__, retval);
597 spin_lock(&io->lock);
599 spin_unlock_irqrestore(&io->lock, flags);
601 EXPORT_SYMBOL_GPL(usb_sg_cancel);
603 /*-------------------------------------------------------------------*/
606 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
607 * @dev: the device whose descriptor is being retrieved
608 * @type: the descriptor type (USB_DT_*)
609 * @index: the number of the descriptor
610 * @buf: where to put the descriptor
611 * @size: how big is "buf"?
612 * Context: !in_interrupt ()
614 * Gets a USB descriptor. Convenience functions exist to simplify
615 * getting some types of descriptors. Use
616 * usb_get_string() or usb_string() for USB_DT_STRING.
617 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
618 * are part of the device structure.
619 * In addition to a number of USB-standard descriptors, some
620 * devices also use class-specific or vendor-specific descriptors.
622 * This call is synchronous, and may not be used in an interrupt context.
624 * Returns the number of bytes received on success, or else the status code
625 * returned by the underlying usb_control_msg() call.
627 int usb_get_descriptor(struct usb_device *dev, unsigned char type,
628 unsigned char index, void *buf, int size)
630 int i;
631 int result;
633 memset(buf, 0, size); /* Make sure we parse really received data */
635 for (i = 0; i < 3; ++i) {
636 /* retry on length 0 or error; some devices are flakey */
637 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
638 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
639 (type << 8) + index, 0, buf, size,
640 USB_CTRL_GET_TIMEOUT);
641 if (result <= 0 && result != -ETIMEDOUT)
642 continue;
643 if (result > 1 && ((u8 *)buf)[1] != type) {
644 result = -ENODATA;
645 continue;
647 break;
649 return result;
651 EXPORT_SYMBOL_GPL(usb_get_descriptor);
654 * usb_get_string - gets a string descriptor
655 * @dev: the device whose string descriptor is being retrieved
656 * @langid: code for language chosen (from string descriptor zero)
657 * @index: the number of the descriptor
658 * @buf: where to put the string
659 * @size: how big is "buf"?
660 * Context: !in_interrupt ()
662 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
663 * in little-endian byte order).
664 * The usb_string() function will often be a convenient way to turn
665 * these strings into kernel-printable form.
667 * Strings may be referenced in device, configuration, interface, or other
668 * descriptors, and could also be used in vendor-specific ways.
670 * This call is synchronous, and may not be used in an interrupt context.
672 * Returns the number of bytes received on success, or else the status code
673 * returned by the underlying usb_control_msg() call.
675 static int usb_get_string(struct usb_device *dev, unsigned short langid,
676 unsigned char index, void *buf, int size)
678 int i;
679 int result;
681 for (i = 0; i < 3; ++i) {
682 /* retry on length 0 or stall; some devices are flakey */
683 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
684 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
685 (USB_DT_STRING << 8) + index, langid, buf, size,
686 USB_CTRL_GET_TIMEOUT);
687 if (result == 0 || result == -EPIPE)
688 continue;
689 if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
690 result = -ENODATA;
691 continue;
693 break;
695 return result;
698 static void usb_try_string_workarounds(unsigned char *buf, int *length)
700 int newlength, oldlength = *length;
702 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
703 if (!isprint(buf[newlength]) || buf[newlength + 1])
704 break;
706 if (newlength > 2) {
707 buf[0] = newlength;
708 *length = newlength;
712 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
713 unsigned int index, unsigned char *buf)
715 int rc;
717 /* Try to read the string descriptor by asking for the maximum
718 * possible number of bytes */
719 if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
720 rc = -EIO;
721 else
722 rc = usb_get_string(dev, langid, index, buf, 255);
724 /* If that failed try to read the descriptor length, then
725 * ask for just that many bytes */
726 if (rc < 2) {
727 rc = usb_get_string(dev, langid, index, buf, 2);
728 if (rc == 2)
729 rc = usb_get_string(dev, langid, index, buf, buf[0]);
732 if (rc >= 2) {
733 if (!buf[0] && !buf[1])
734 usb_try_string_workarounds(buf, &rc);
736 /* There might be extra junk at the end of the descriptor */
737 if (buf[0] < rc)
738 rc = buf[0];
740 rc = rc - (rc & 1); /* force a multiple of two */
743 if (rc < 2)
744 rc = (rc < 0 ? rc : -EINVAL);
746 return rc;
749 static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
751 int err;
753 if (dev->have_langid)
754 return 0;
756 if (dev->string_langid < 0)
757 return -EPIPE;
759 err = usb_string_sub(dev, 0, 0, tbuf);
761 /* If the string was reported but is malformed, default to english
762 * (0x0409) */
763 if (err == -ENODATA || (err > 0 && err < 4)) {
764 dev->string_langid = 0x0409;
765 dev->have_langid = 1;
766 dev_err(&dev->dev,
767 "string descriptor 0 malformed (err = %d), "
768 "defaulting to 0x%04x\n",
769 err, dev->string_langid);
770 return 0;
773 /* In case of all other errors, we assume the device is not able to
774 * deal with strings at all. Set string_langid to -1 in order to
775 * prevent any string to be retrieved from the device */
776 if (err < 0) {
777 dev_err(&dev->dev, "string descriptor 0 read error: %d\n",
778 err);
779 dev->string_langid = -1;
780 return -EPIPE;
783 /* always use the first langid listed */
784 dev->string_langid = tbuf[2] | (tbuf[3] << 8);
785 dev->have_langid = 1;
786 dev_dbg(&dev->dev, "default language 0x%04x\n",
787 dev->string_langid);
788 return 0;
792 * usb_string - returns UTF-8 version of a string descriptor
793 * @dev: the device whose string descriptor is being retrieved
794 * @index: the number of the descriptor
795 * @buf: where to put the string
796 * @size: how big is "buf"?
797 * Context: !in_interrupt ()
799 * This converts the UTF-16LE encoded strings returned by devices, from
800 * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
801 * that are more usable in most kernel contexts. Note that this function
802 * chooses strings in the first language supported by the device.
804 * This call is synchronous, and may not be used in an interrupt context.
806 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
808 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
810 unsigned char *tbuf;
811 int err;
813 if (dev->state == USB_STATE_SUSPENDED)
814 return -EHOSTUNREACH;
815 if (size <= 0 || !buf || !index)
816 return -EINVAL;
817 buf[0] = 0;
818 tbuf = kmalloc(256, GFP_NOIO);
819 if (!tbuf)
820 return -ENOMEM;
822 err = usb_get_langid(dev, tbuf);
823 if (err < 0)
824 goto errout;
826 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
827 if (err < 0)
828 goto errout;
830 size--; /* leave room for trailing NULL char in output buffer */
831 err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
832 UTF16_LITTLE_ENDIAN, buf, size);
833 buf[err] = 0;
835 if (tbuf[1] != USB_DT_STRING)
836 dev_dbg(&dev->dev,
837 "wrong descriptor type %02x for string %d (\"%s\")\n",
838 tbuf[1], index, buf);
840 errout:
841 kfree(tbuf);
842 return err;
844 EXPORT_SYMBOL_GPL(usb_string);
846 /* one UTF-8-encoded 16-bit character has at most three bytes */
847 #define MAX_USB_STRING_SIZE (127 * 3 + 1)
850 * usb_cache_string - read a string descriptor and cache it for later use
851 * @udev: the device whose string descriptor is being read
852 * @index: the descriptor index
854 * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
855 * or NULL if the index is 0 or the string could not be read.
857 char *usb_cache_string(struct usb_device *udev, int index)
859 char *buf;
860 char *smallbuf = NULL;
861 int len;
863 if (index <= 0)
864 return NULL;
866 buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
867 if (buf) {
868 len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
869 if (len > 0) {
870 smallbuf = kmalloc(++len, GFP_NOIO);
871 if (!smallbuf)
872 return buf;
873 memcpy(smallbuf, buf, len);
875 kfree(buf);
877 return smallbuf;
881 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
882 * @dev: the device whose device descriptor is being updated
883 * @size: how much of the descriptor to read
884 * Context: !in_interrupt ()
886 * Updates the copy of the device descriptor stored in the device structure,
887 * which dedicates space for this purpose.
889 * Not exported, only for use by the core. If drivers really want to read
890 * the device descriptor directly, they can call usb_get_descriptor() with
891 * type = USB_DT_DEVICE and index = 0.
893 * This call is synchronous, and may not be used in an interrupt context.
895 * Returns the number of bytes received on success, or else the status code
896 * returned by the underlying usb_control_msg() call.
898 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
900 struct usb_device_descriptor *desc;
901 int ret;
903 if (size > sizeof(*desc))
904 return -EINVAL;
905 desc = kmalloc(sizeof(*desc), GFP_NOIO);
906 if (!desc)
907 return -ENOMEM;
909 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
910 if (ret >= 0)
911 memcpy(&dev->descriptor, desc, size);
912 kfree(desc);
913 return ret;
917 * usb_get_status - issues a GET_STATUS call
918 * @dev: the device whose status is being checked
919 * @type: USB_RECIP_*; for device, interface, or endpoint
920 * @target: zero (for device), else interface or endpoint number
921 * @data: pointer to two bytes of bitmap data
922 * Context: !in_interrupt ()
924 * Returns device, interface, or endpoint status. Normally only of
925 * interest to see if the device is self powered, or has enabled the
926 * remote wakeup facility; or whether a bulk or interrupt endpoint
927 * is halted ("stalled").
929 * Bits in these status bitmaps are set using the SET_FEATURE request,
930 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
931 * function should be used to clear halt ("stall") status.
933 * This call is synchronous, and may not be used in an interrupt context.
935 * Returns the number of bytes received on success, or else the status code
936 * returned by the underlying usb_control_msg() call.
938 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
940 int ret;
941 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
943 if (!status)
944 return -ENOMEM;
946 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
947 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
948 sizeof(*status), USB_CTRL_GET_TIMEOUT);
950 *(u16 *)data = *status;
951 kfree(status);
952 return ret;
954 EXPORT_SYMBOL_GPL(usb_get_status);
957 * usb_clear_halt - tells device to clear endpoint halt/stall condition
958 * @dev: device whose endpoint is halted
959 * @pipe: endpoint "pipe" being cleared
960 * Context: !in_interrupt ()
962 * This is used to clear halt conditions for bulk and interrupt endpoints,
963 * as reported by URB completion status. Endpoints that are halted are
964 * sometimes referred to as being "stalled". Such endpoints are unable
965 * to transmit or receive data until the halt status is cleared. Any URBs
966 * queued for such an endpoint should normally be unlinked by the driver
967 * before clearing the halt condition, as described in sections 5.7.5
968 * and 5.8.5 of the USB 2.0 spec.
970 * Note that control and isochronous endpoints don't halt, although control
971 * endpoints report "protocol stall" (for unsupported requests) using the
972 * same status code used to report a true stall.
974 * This call is synchronous, and may not be used in an interrupt context.
976 * Returns zero on success, or else the status code returned by the
977 * underlying usb_control_msg() call.
979 int usb_clear_halt(struct usb_device *dev, int pipe)
981 int result;
982 int endp = usb_pipeendpoint(pipe);
984 if (usb_pipein(pipe))
985 endp |= USB_DIR_IN;
987 /* we don't care if it wasn't halted first. in fact some devices
988 * (like some ibmcam model 1 units) seem to expect hosts to make
989 * this request for iso endpoints, which can't halt!
991 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
992 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
993 USB_ENDPOINT_HALT, endp, NULL, 0,
994 USB_CTRL_SET_TIMEOUT);
996 /* don't un-halt or force to DATA0 except on success */
997 if (result < 0)
998 return result;
1000 /* NOTE: seems like Microsoft and Apple don't bother verifying
1001 * the clear "took", so some devices could lock up if you check...
1002 * such as the Hagiwara FlashGate DUAL. So we won't bother.
1004 * NOTE: make sure the logic here doesn't diverge much from
1005 * the copy in usb-storage, for as long as we need two copies.
1008 usb_reset_endpoint(dev, endp);
1010 return 0;
1012 EXPORT_SYMBOL_GPL(usb_clear_halt);
1014 static int create_intf_ep_devs(struct usb_interface *intf)
1016 struct usb_device *udev = interface_to_usbdev(intf);
1017 struct usb_host_interface *alt = intf->cur_altsetting;
1018 int i;
1020 if (intf->ep_devs_created || intf->unregistering)
1021 return 0;
1023 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1024 (void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
1025 intf->ep_devs_created = 1;
1026 return 0;
1029 static void remove_intf_ep_devs(struct usb_interface *intf)
1031 struct usb_host_interface *alt = intf->cur_altsetting;
1032 int i;
1034 if (!intf->ep_devs_created)
1035 return;
1037 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1038 usb_remove_ep_devs(&alt->endpoint[i]);
1039 intf->ep_devs_created = 0;
1043 * usb_disable_endpoint -- Disable an endpoint by address
1044 * @dev: the device whose endpoint is being disabled
1045 * @epaddr: the endpoint's address. Endpoint number for output,
1046 * endpoint number + USB_DIR_IN for input
1047 * @reset_hardware: flag to erase any endpoint state stored in the
1048 * controller hardware
1050 * Disables the endpoint for URB submission and nukes all pending URBs.
1051 * If @reset_hardware is set then also deallocates hcd/hardware state
1052 * for the endpoint.
1054 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
1055 bool reset_hardware)
1057 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1058 struct usb_host_endpoint *ep;
1060 if (!dev)
1061 return;
1063 if (usb_endpoint_out(epaddr)) {
1064 ep = dev->ep_out[epnum];
1065 if (reset_hardware)
1066 dev->ep_out[epnum] = NULL;
1067 } else {
1068 ep = dev->ep_in[epnum];
1069 if (reset_hardware)
1070 dev->ep_in[epnum] = NULL;
1072 if (ep) {
1073 ep->enabled = 0;
1074 usb_hcd_flush_endpoint(dev, ep);
1075 if (reset_hardware)
1076 usb_hcd_disable_endpoint(dev, ep);
1081 * usb_reset_endpoint - Reset an endpoint's state.
1082 * @dev: the device whose endpoint is to be reset
1083 * @epaddr: the endpoint's address. Endpoint number for output,
1084 * endpoint number + USB_DIR_IN for input
1086 * Resets any host-side endpoint state such as the toggle bit,
1087 * sequence number or current window.
1089 void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
1091 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1092 struct usb_host_endpoint *ep;
1094 if (usb_endpoint_out(epaddr))
1095 ep = dev->ep_out[epnum];
1096 else
1097 ep = dev->ep_in[epnum];
1098 if (ep)
1099 usb_hcd_reset_endpoint(dev, ep);
1101 EXPORT_SYMBOL_GPL(usb_reset_endpoint);
1105 * usb_disable_interface -- Disable all endpoints for an interface
1106 * @dev: the device whose interface is being disabled
1107 * @intf: pointer to the interface descriptor
1108 * @reset_hardware: flag to erase any endpoint state stored in the
1109 * controller hardware
1111 * Disables all the endpoints for the interface's current altsetting.
1113 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
1114 bool reset_hardware)
1116 struct usb_host_interface *alt = intf->cur_altsetting;
1117 int i;
1119 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1120 usb_disable_endpoint(dev,
1121 alt->endpoint[i].desc.bEndpointAddress,
1122 reset_hardware);
1127 * usb_disable_device - Disable all the endpoints for a USB device
1128 * @dev: the device whose endpoints are being disabled
1129 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1131 * Disables all the device's endpoints, potentially including endpoint 0.
1132 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1133 * pending urbs) and usbcore state for the interfaces, so that usbcore
1134 * must usb_set_configuration() before any interfaces could be used.
1136 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1138 int i;
1140 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
1141 skip_ep0 ? "non-ep0" : "all");
1142 for (i = skip_ep0; i < 16; ++i) {
1143 usb_disable_endpoint(dev, i, true);
1144 usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1147 /* getting rid of interfaces will disconnect
1148 * any drivers bound to them (a key side effect)
1150 if (dev->actconfig) {
1151 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1152 struct usb_interface *interface;
1154 /* remove this interface if it has been registered */
1155 interface = dev->actconfig->interface[i];
1156 if (!device_is_registered(&interface->dev))
1157 continue;
1158 dev_dbg(&dev->dev, "unregistering interface %s\n",
1159 dev_name(&interface->dev));
1160 interface->unregistering = 1;
1161 remove_intf_ep_devs(interface);
1162 device_del(&interface->dev);
1165 /* Now that the interfaces are unbound, nobody should
1166 * try to access them.
1168 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1169 put_device(&dev->actconfig->interface[i]->dev);
1170 dev->actconfig->interface[i] = NULL;
1172 dev->actconfig = NULL;
1173 if (dev->state == USB_STATE_CONFIGURED)
1174 usb_set_device_state(dev, USB_STATE_ADDRESS);
1179 * usb_enable_endpoint - Enable an endpoint for USB communications
1180 * @dev: the device whose interface is being enabled
1181 * @ep: the endpoint
1182 * @reset_ep: flag to reset the endpoint state
1184 * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
1185 * For control endpoints, both the input and output sides are handled.
1187 void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
1188 bool reset_ep)
1190 int epnum = usb_endpoint_num(&ep->desc);
1191 int is_out = usb_endpoint_dir_out(&ep->desc);
1192 int is_control = usb_endpoint_xfer_control(&ep->desc);
1194 if (reset_ep)
1195 usb_hcd_reset_endpoint(dev, ep);
1196 if (is_out || is_control)
1197 dev->ep_out[epnum] = ep;
1198 if (!is_out || is_control)
1199 dev->ep_in[epnum] = ep;
1200 ep->enabled = 1;
1204 * usb_enable_interface - Enable all the endpoints for an interface
1205 * @dev: the device whose interface is being enabled
1206 * @intf: pointer to the interface descriptor
1207 * @reset_eps: flag to reset the endpoints' state
1209 * Enables all the endpoints for the interface's current altsetting.
1211 void usb_enable_interface(struct usb_device *dev,
1212 struct usb_interface *intf, bool reset_eps)
1214 struct usb_host_interface *alt = intf->cur_altsetting;
1215 int i;
1217 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1218 usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
1222 * usb_set_interface - Makes a particular alternate setting be current
1223 * @dev: the device whose interface is being updated
1224 * @interface: the interface being updated
1225 * @alternate: the setting being chosen.
1226 * Context: !in_interrupt ()
1228 * This is used to enable data transfers on interfaces that may not
1229 * be enabled by default. Not all devices support such configurability.
1230 * Only the driver bound to an interface may change its setting.
1232 * Within any given configuration, each interface may have several
1233 * alternative settings. These are often used to control levels of
1234 * bandwidth consumption. For example, the default setting for a high
1235 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1236 * while interrupt transfers of up to 3KBytes per microframe are legal.
1237 * Also, isochronous endpoints may never be part of an
1238 * interface's default setting. To access such bandwidth, alternate
1239 * interface settings must be made current.
1241 * Note that in the Linux USB subsystem, bandwidth associated with
1242 * an endpoint in a given alternate setting is not reserved until an URB
1243 * is submitted that needs that bandwidth. Some other operating systems
1244 * allocate bandwidth early, when a configuration is chosen.
1246 * This call is synchronous, and may not be used in an interrupt context.
1247 * Also, drivers must not change altsettings while urbs are scheduled for
1248 * endpoints in that interface; all such urbs must first be completed
1249 * (perhaps forced by unlinking).
1251 * Returns zero on success, or else the status code returned by the
1252 * underlying usb_control_msg() call.
1254 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1256 struct usb_interface *iface;
1257 struct usb_host_interface *alt;
1258 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1259 int ret;
1260 int manual = 0;
1261 unsigned int epaddr;
1262 unsigned int pipe;
1264 if (dev->state == USB_STATE_SUSPENDED)
1265 return -EHOSTUNREACH;
1267 iface = usb_ifnum_to_if(dev, interface);
1268 if (!iface) {
1269 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1270 interface);
1271 return -EINVAL;
1274 alt = usb_altnum_to_altsetting(iface, alternate);
1275 if (!alt) {
1276 dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
1277 alternate);
1278 return -EINVAL;
1281 /* Make sure we have enough bandwidth for this alternate interface.
1282 * Remove the current alt setting and add the new alt setting.
1284 mutex_lock(&hcd->bandwidth_mutex);
1285 ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
1286 if (ret < 0) {
1287 dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
1288 alternate);
1289 mutex_unlock(&hcd->bandwidth_mutex);
1290 return ret;
1293 if (dev->quirks & USB_QUIRK_NO_SET_INTF)
1294 ret = -EPIPE;
1295 else
1296 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1297 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1298 alternate, interface, NULL, 0, 5000);
1300 /* 9.4.10 says devices don't need this and are free to STALL the
1301 * request if the interface only has one alternate setting.
1303 if (ret == -EPIPE && iface->num_altsetting == 1) {
1304 dev_dbg(&dev->dev,
1305 "manual set_interface for iface %d, alt %d\n",
1306 interface, alternate);
1307 manual = 1;
1308 } else if (ret < 0) {
1309 /* Re-instate the old alt setting */
1310 usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
1311 mutex_unlock(&hcd->bandwidth_mutex);
1312 return ret;
1314 mutex_unlock(&hcd->bandwidth_mutex);
1316 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1317 * when they implement async or easily-killable versions of this or
1318 * other "should-be-internal" functions (like clear_halt).
1319 * should hcd+usbcore postprocess control requests?
1322 /* prevent submissions using previous endpoint settings */
1323 if (iface->cur_altsetting != alt) {
1324 remove_intf_ep_devs(iface);
1325 usb_remove_sysfs_intf_files(iface);
1327 usb_disable_interface(dev, iface, true);
1329 iface->cur_altsetting = alt;
1331 /* If the interface only has one altsetting and the device didn't
1332 * accept the request, we attempt to carry out the equivalent action
1333 * by manually clearing the HALT feature for each endpoint in the
1334 * new altsetting.
1336 if (manual) {
1337 int i;
1339 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1340 epaddr = alt->endpoint[i].desc.bEndpointAddress;
1341 pipe = __create_pipe(dev,
1342 USB_ENDPOINT_NUMBER_MASK & epaddr) |
1343 (usb_endpoint_out(epaddr) ?
1344 USB_DIR_OUT : USB_DIR_IN);
1346 usb_clear_halt(dev, pipe);
1350 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1352 * Note:
1353 * Despite EP0 is always present in all interfaces/AS, the list of
1354 * endpoints from the descriptor does not contain EP0. Due to its
1355 * omnipresence one might expect EP0 being considered "affected" by
1356 * any SetInterface request and hence assume toggles need to be reset.
1357 * However, EP0 toggles are re-synced for every individual transfer
1358 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1359 * (Likewise, EP0 never "halts" on well designed devices.)
1361 usb_enable_interface(dev, iface, true);
1362 if (device_is_registered(&iface->dev)) {
1363 usb_create_sysfs_intf_files(iface);
1364 create_intf_ep_devs(iface);
1366 return 0;
1368 EXPORT_SYMBOL_GPL(usb_set_interface);
1371 * usb_reset_configuration - lightweight device reset
1372 * @dev: the device whose configuration is being reset
1374 * This issues a standard SET_CONFIGURATION request to the device using
1375 * the current configuration. The effect is to reset most USB-related
1376 * state in the device, including interface altsettings (reset to zero),
1377 * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
1378 * endpoints). Other usbcore state is unchanged, including bindings of
1379 * usb device drivers to interfaces.
1381 * Because this affects multiple interfaces, avoid using this with composite
1382 * (multi-interface) devices. Instead, the driver for each interface may
1383 * use usb_set_interface() on the interfaces it claims. Be careful though;
1384 * some devices don't support the SET_INTERFACE request, and others won't
1385 * reset all the interface state (notably endpoint state). Resetting the whole
1386 * configuration would affect other drivers' interfaces.
1388 * The caller must own the device lock.
1390 * Returns zero on success, else a negative error code.
1392 int usb_reset_configuration(struct usb_device *dev)
1394 int i, retval;
1395 struct usb_host_config *config;
1396 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1398 if (dev->state == USB_STATE_SUSPENDED)
1399 return -EHOSTUNREACH;
1401 /* caller must have locked the device and must own
1402 * the usb bus readlock (so driver bindings are stable);
1403 * calls during probe() are fine
1406 for (i = 1; i < 16; ++i) {
1407 usb_disable_endpoint(dev, i, true);
1408 usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1411 config = dev->actconfig;
1412 retval = 0;
1413 mutex_lock(&hcd->bandwidth_mutex);
1414 /* Make sure we have enough bandwidth for each alternate setting 0 */
1415 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1416 struct usb_interface *intf = config->interface[i];
1417 struct usb_host_interface *alt;
1419 alt = usb_altnum_to_altsetting(intf, 0);
1420 if (!alt)
1421 alt = &intf->altsetting[0];
1422 if (alt != intf->cur_altsetting)
1423 retval = usb_hcd_alloc_bandwidth(dev, NULL,
1424 intf->cur_altsetting, alt);
1425 if (retval < 0)
1426 break;
1428 /* If not, reinstate the old alternate settings */
1429 if (retval < 0) {
1430 reset_old_alts:
1431 for (i--; i >= 0; i--) {
1432 struct usb_interface *intf = config->interface[i];
1433 struct usb_host_interface *alt;
1435 alt = usb_altnum_to_altsetting(intf, 0);
1436 if (!alt)
1437 alt = &intf->altsetting[0];
1438 if (alt != intf->cur_altsetting)
1439 usb_hcd_alloc_bandwidth(dev, NULL,
1440 alt, intf->cur_altsetting);
1442 mutex_unlock(&hcd->bandwidth_mutex);
1443 return retval;
1445 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1446 USB_REQ_SET_CONFIGURATION, 0,
1447 config->desc.bConfigurationValue, 0,
1448 NULL, 0, USB_CTRL_SET_TIMEOUT);
1449 if (retval < 0)
1450 goto reset_old_alts;
1451 mutex_unlock(&hcd->bandwidth_mutex);
1453 /* re-init hc/hcd interface/endpoint state */
1454 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1455 struct usb_interface *intf = config->interface[i];
1456 struct usb_host_interface *alt;
1458 alt = usb_altnum_to_altsetting(intf, 0);
1460 /* No altsetting 0? We'll assume the first altsetting.
1461 * We could use a GetInterface call, but if a device is
1462 * so non-compliant that it doesn't have altsetting 0
1463 * then I wouldn't trust its reply anyway.
1465 if (!alt)
1466 alt = &intf->altsetting[0];
1468 if (alt != intf->cur_altsetting) {
1469 remove_intf_ep_devs(intf);
1470 usb_remove_sysfs_intf_files(intf);
1472 intf->cur_altsetting = alt;
1473 usb_enable_interface(dev, intf, true);
1474 if (device_is_registered(&intf->dev)) {
1475 usb_create_sysfs_intf_files(intf);
1476 create_intf_ep_devs(intf);
1479 return 0;
1481 EXPORT_SYMBOL_GPL(usb_reset_configuration);
1483 static void usb_release_interface(struct device *dev)
1485 struct usb_interface *intf = to_usb_interface(dev);
1486 struct usb_interface_cache *intfc =
1487 altsetting_to_usb_interface_cache(intf->altsetting);
1489 kref_put(&intfc->ref, usb_release_interface_cache);
1490 kfree(intf);
1493 #ifdef CONFIG_HOTPLUG
1494 static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1496 struct usb_device *usb_dev;
1497 struct usb_interface *intf;
1498 struct usb_host_interface *alt;
1500 intf = to_usb_interface(dev);
1501 usb_dev = interface_to_usbdev(intf);
1502 alt = intf->cur_altsetting;
1504 if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
1505 alt->desc.bInterfaceClass,
1506 alt->desc.bInterfaceSubClass,
1507 alt->desc.bInterfaceProtocol))
1508 return -ENOMEM;
1510 if (add_uevent_var(env,
1511 "MODALIAS=usb:"
1512 "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X",
1513 le16_to_cpu(usb_dev->descriptor.idVendor),
1514 le16_to_cpu(usb_dev->descriptor.idProduct),
1515 le16_to_cpu(usb_dev->descriptor.bcdDevice),
1516 usb_dev->descriptor.bDeviceClass,
1517 usb_dev->descriptor.bDeviceSubClass,
1518 usb_dev->descriptor.bDeviceProtocol,
1519 alt->desc.bInterfaceClass,
1520 alt->desc.bInterfaceSubClass,
1521 alt->desc.bInterfaceProtocol))
1522 return -ENOMEM;
1524 return 0;
1527 #else
1529 static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1531 return -ENODEV;
1533 #endif /* CONFIG_HOTPLUG */
1535 struct device_type usb_if_device_type = {
1536 .name = "usb_interface",
1537 .release = usb_release_interface,
1538 .uevent = usb_if_uevent,
1541 static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1542 struct usb_host_config *config,
1543 u8 inum)
1545 struct usb_interface_assoc_descriptor *retval = NULL;
1546 struct usb_interface_assoc_descriptor *intf_assoc;
1547 int first_intf;
1548 int last_intf;
1549 int i;
1551 for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
1552 intf_assoc = config->intf_assoc[i];
1553 if (intf_assoc->bInterfaceCount == 0)
1554 continue;
1556 first_intf = intf_assoc->bFirstInterface;
1557 last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
1558 if (inum >= first_intf && inum <= last_intf) {
1559 if (!retval)
1560 retval = intf_assoc;
1561 else
1562 dev_err(&dev->dev, "Interface #%d referenced"
1563 " by multiple IADs\n", inum);
1567 return retval;
1572 * Internal function to queue a device reset
1574 * This is initialized into the workstruct in 'struct
1575 * usb_device->reset_ws' that is launched by
1576 * message.c:usb_set_configuration() when initializing each 'struct
1577 * usb_interface'.
1579 * It is safe to get the USB device without reference counts because
1580 * the life cycle of @iface is bound to the life cycle of @udev. Then,
1581 * this function will be ran only if @iface is alive (and before
1582 * freeing it any scheduled instances of it will have been cancelled).
1584 * We need to set a flag (usb_dev->reset_running) because when we call
1585 * the reset, the interfaces might be unbound. The current interface
1586 * cannot try to remove the queued work as it would cause a deadlock
1587 * (you cannot remove your work from within your executing
1588 * workqueue). This flag lets it know, so that
1589 * usb_cancel_queued_reset() doesn't try to do it.
1591 * See usb_queue_reset_device() for more details
1593 static void __usb_queue_reset_device(struct work_struct *ws)
1595 int rc;
1596 struct usb_interface *iface =
1597 container_of(ws, struct usb_interface, reset_ws);
1598 struct usb_device *udev = interface_to_usbdev(iface);
1600 rc = usb_lock_device_for_reset(udev, iface);
1601 if (rc >= 0) {
1602 iface->reset_running = 1;
1603 usb_reset_device(udev);
1604 iface->reset_running = 0;
1605 usb_unlock_device(udev);
1611 * usb_set_configuration - Makes a particular device setting be current
1612 * @dev: the device whose configuration is being updated
1613 * @configuration: the configuration being chosen.
1614 * Context: !in_interrupt(), caller owns the device lock
1616 * This is used to enable non-default device modes. Not all devices
1617 * use this kind of configurability; many devices only have one
1618 * configuration.
1620 * @configuration is the value of the configuration to be installed.
1621 * According to the USB spec (e.g. section 9.1.1.5), configuration values
1622 * must be non-zero; a value of zero indicates that the device in
1623 * unconfigured. However some devices erroneously use 0 as one of their
1624 * configuration values. To help manage such devices, this routine will
1625 * accept @configuration = -1 as indicating the device should be put in
1626 * an unconfigured state.
1628 * USB device configurations may affect Linux interoperability,
1629 * power consumption and the functionality available. For example,
1630 * the default configuration is limited to using 100mA of bus power,
1631 * so that when certain device functionality requires more power,
1632 * and the device is bus powered, that functionality should be in some
1633 * non-default device configuration. Other device modes may also be
1634 * reflected as configuration options, such as whether two ISDN
1635 * channels are available independently; and choosing between open
1636 * standard device protocols (like CDC) or proprietary ones.
1638 * Note that a non-authorized device (dev->authorized == 0) will only
1639 * be put in unconfigured mode.
1641 * Note that USB has an additional level of device configurability,
1642 * associated with interfaces. That configurability is accessed using
1643 * usb_set_interface().
1645 * This call is synchronous. The calling context must be able to sleep,
1646 * must own the device lock, and must not hold the driver model's USB
1647 * bus mutex; usb interface driver probe() methods cannot use this routine.
1649 * Returns zero on success, or else the status code returned by the
1650 * underlying call that failed. On successful completion, each interface
1651 * in the original device configuration has been destroyed, and each one
1652 * in the new configuration has been probed by all relevant usb device
1653 * drivers currently known to the kernel.
1655 int usb_set_configuration(struct usb_device *dev, int configuration)
1657 int i, ret;
1658 struct usb_host_config *cp = NULL;
1659 struct usb_interface **new_interfaces = NULL;
1660 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1661 int n, nintf;
1663 if (dev->authorized == 0 || configuration == -1)
1664 configuration = 0;
1665 else {
1666 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1667 if (dev->config[i].desc.bConfigurationValue ==
1668 configuration) {
1669 cp = &dev->config[i];
1670 break;
1674 if ((!cp && configuration != 0))
1675 return -EINVAL;
1677 /* The USB spec says configuration 0 means unconfigured.
1678 * But if a device includes a configuration numbered 0,
1679 * we will accept it as a correctly configured state.
1680 * Use -1 if you really want to unconfigure the device.
1682 if (cp && configuration == 0)
1683 dev_warn(&dev->dev, "config 0 descriptor??\n");
1685 /* Allocate memory for new interfaces before doing anything else,
1686 * so that if we run out then nothing will have changed. */
1687 n = nintf = 0;
1688 if (cp) {
1689 nintf = cp->desc.bNumInterfaces;
1690 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1691 GFP_NOIO);
1692 if (!new_interfaces) {
1693 dev_err(&dev->dev, "Out of memory\n");
1694 return -ENOMEM;
1697 for (; n < nintf; ++n) {
1698 new_interfaces[n] = kzalloc(
1699 sizeof(struct usb_interface),
1700 GFP_NOIO);
1701 if (!new_interfaces[n]) {
1702 dev_err(&dev->dev, "Out of memory\n");
1703 ret = -ENOMEM;
1704 free_interfaces:
1705 while (--n >= 0)
1706 kfree(new_interfaces[n]);
1707 kfree(new_interfaces);
1708 return ret;
1712 i = dev->bus_mA - cp->desc.bMaxPower * 2;
1713 if (i < 0)
1714 dev_warn(&dev->dev, "new config #%d exceeds power "
1715 "limit by %dmA\n",
1716 configuration, -i);
1719 /* Wake up the device so we can send it the Set-Config request */
1720 ret = usb_autoresume_device(dev);
1721 if (ret)
1722 goto free_interfaces;
1724 /* Make sure we have bandwidth (and available HCD resources) for this
1725 * configuration. Remove endpoints from the schedule if we're dropping
1726 * this configuration to set configuration 0. After this point, the
1727 * host controller will not allow submissions to dropped endpoints. If
1728 * this call fails, the device state is unchanged.
1730 mutex_lock(&hcd->bandwidth_mutex);
1731 ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
1732 if (ret < 0) {
1733 usb_autosuspend_device(dev);
1734 mutex_unlock(&hcd->bandwidth_mutex);
1735 goto free_interfaces;
1738 /* if it's already configured, clear out old state first.
1739 * getting rid of old interfaces means unbinding their drivers.
1741 if (dev->state != USB_STATE_ADDRESS)
1742 usb_disable_device(dev, 1); /* Skip ep0 */
1744 /* Get rid of pending async Set-Config requests for this device */
1745 cancel_async_set_config(dev);
1747 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1748 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1749 NULL, 0, USB_CTRL_SET_TIMEOUT);
1750 if (ret < 0) {
1751 /* All the old state is gone, so what else can we do?
1752 * The device is probably useless now anyway.
1754 cp = NULL;
1757 dev->actconfig = cp;
1758 if (!cp) {
1759 usb_set_device_state(dev, USB_STATE_ADDRESS);
1760 usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1761 usb_autosuspend_device(dev);
1762 mutex_unlock(&hcd->bandwidth_mutex);
1763 goto free_interfaces;
1765 mutex_unlock(&hcd->bandwidth_mutex);
1766 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1768 /* Initialize the new interface structures and the
1769 * hc/hcd/usbcore interface/endpoint state.
1771 for (i = 0; i < nintf; ++i) {
1772 struct usb_interface_cache *intfc;
1773 struct usb_interface *intf;
1774 struct usb_host_interface *alt;
1776 cp->interface[i] = intf = new_interfaces[i];
1777 intfc = cp->intf_cache[i];
1778 intf->altsetting = intfc->altsetting;
1779 intf->num_altsetting = intfc->num_altsetting;
1780 intf->intf_assoc = find_iad(dev, cp, i);
1781 kref_get(&intfc->ref);
1783 alt = usb_altnum_to_altsetting(intf, 0);
1785 /* No altsetting 0? We'll assume the first altsetting.
1786 * We could use a GetInterface call, but if a device is
1787 * so non-compliant that it doesn't have altsetting 0
1788 * then I wouldn't trust its reply anyway.
1790 if (!alt)
1791 alt = &intf->altsetting[0];
1793 intf->cur_altsetting = alt;
1794 usb_enable_interface(dev, intf, true);
1795 intf->dev.parent = &dev->dev;
1796 intf->dev.driver = NULL;
1797 intf->dev.bus = &usb_bus_type;
1798 intf->dev.type = &usb_if_device_type;
1799 intf->dev.groups = usb_interface_groups;
1800 intf->dev.dma_mask = dev->dev.dma_mask;
1801 INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
1802 device_initialize(&intf->dev);
1803 dev_set_name(&intf->dev, "%d-%s:%d.%d",
1804 dev->bus->busnum, dev->devpath,
1805 configuration, alt->desc.bInterfaceNumber);
1807 kfree(new_interfaces);
1809 if (cp->string == NULL &&
1810 !(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
1811 cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
1813 /* Now that all the interfaces are set up, register them
1814 * to trigger binding of drivers to interfaces. probe()
1815 * routines may install different altsettings and may
1816 * claim() any interfaces not yet bound. Many class drivers
1817 * need that: CDC, audio, video, etc.
1819 for (i = 0; i < nintf; ++i) {
1820 struct usb_interface *intf = cp->interface[i];
1822 dev_dbg(&dev->dev,
1823 "adding %s (config #%d, interface %d)\n",
1824 dev_name(&intf->dev), configuration,
1825 intf->cur_altsetting->desc.bInterfaceNumber);
1826 device_enable_async_suspend(&intf->dev);
1827 ret = device_add(&intf->dev);
1828 if (ret != 0) {
1829 dev_err(&dev->dev, "device_add(%s) --> %d\n",
1830 dev_name(&intf->dev), ret);
1831 continue;
1833 create_intf_ep_devs(intf);
1836 usb_autosuspend_device(dev);
1837 return 0;
1840 static LIST_HEAD(set_config_list);
1841 static DEFINE_SPINLOCK(set_config_lock);
1843 struct set_config_request {
1844 struct usb_device *udev;
1845 int config;
1846 struct work_struct work;
1847 struct list_head node;
1850 /* Worker routine for usb_driver_set_configuration() */
1851 static void driver_set_config_work(struct work_struct *work)
1853 struct set_config_request *req =
1854 container_of(work, struct set_config_request, work);
1855 struct usb_device *udev = req->udev;
1857 usb_lock_device(udev);
1858 spin_lock(&set_config_lock);
1859 list_del(&req->node);
1860 spin_unlock(&set_config_lock);
1862 if (req->config >= -1) /* Is req still valid? */
1863 usb_set_configuration(udev, req->config);
1864 usb_unlock_device(udev);
1865 usb_put_dev(udev);
1866 kfree(req);
1869 /* Cancel pending Set-Config requests for a device whose configuration
1870 * was just changed
1872 static void cancel_async_set_config(struct usb_device *udev)
1874 struct set_config_request *req;
1876 spin_lock(&set_config_lock);
1877 list_for_each_entry(req, &set_config_list, node) {
1878 if (req->udev == udev)
1879 req->config = -999; /* Mark as cancelled */
1881 spin_unlock(&set_config_lock);
1885 * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1886 * @udev: the device whose configuration is being updated
1887 * @config: the configuration being chosen.
1888 * Context: In process context, must be able to sleep
1890 * Device interface drivers are not allowed to change device configurations.
1891 * This is because changing configurations will destroy the interface the
1892 * driver is bound to and create new ones; it would be like a floppy-disk
1893 * driver telling the computer to replace the floppy-disk drive with a
1894 * tape drive!
1896 * Still, in certain specialized circumstances the need may arise. This
1897 * routine gets around the normal restrictions by using a work thread to
1898 * submit the change-config request.
1900 * Returns 0 if the request was successfully queued, error code otherwise.
1901 * The caller has no way to know whether the queued request will eventually
1902 * succeed.
1904 int usb_driver_set_configuration(struct usb_device *udev, int config)
1906 struct set_config_request *req;
1908 req = kmalloc(sizeof(*req), GFP_KERNEL);
1909 if (!req)
1910 return -ENOMEM;
1911 req->udev = udev;
1912 req->config = config;
1913 INIT_WORK(&req->work, driver_set_config_work);
1915 spin_lock(&set_config_lock);
1916 list_add(&req->node, &set_config_list);
1917 spin_unlock(&set_config_lock);
1919 usb_get_dev(udev);
1920 schedule_work(&req->work);
1921 return 0;
1923 EXPORT_SYMBOL_GPL(usb_driver_set_configuration);