2 * message.c - synchronous message handling
5 #include <linux/pci.h> /* for scatterlist macros */
7 #include <linux/module.h>
8 #include <linux/slab.h>
9 #include <linux/init.h>
11 #include <linux/timer.h>
12 #include <linux/ctype.h>
13 #include <linux/device.h>
14 #include <asm/byteorder.h>
15 #include <asm/scatterlist.h>
17 #include "hcd.h" /* for usbcore internals */
20 static void usb_api_blocking_completion(struct urb *urb)
22 complete((struct completion *)urb->context);
27 * Starts urb and waits for completion or timeout. Note that this call
28 * is NOT interruptible. Many device driver i/o requests should be
29 * interruptible and therefore these drivers should implement their
30 * own interruptible routines.
32 static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
34 struct completion done;
38 init_completion(&done);
40 urb->actual_length = 0;
41 status = usb_submit_urb(urb, GFP_NOIO);
45 expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
46 if (!wait_for_completion_timeout(&done, expire)) {
48 dev_dbg(&urb->dev->dev,
49 "%s timed out on ep%d%s len=%d/%d\n",
51 usb_pipeendpoint(urb->pipe),
52 usb_pipein(urb->pipe) ? "in" : "out",
54 urb->transfer_buffer_length);
57 status = urb->status == -ENOENT ? -ETIMEDOUT : urb->status;
62 *actual_length = urb->actual_length;
68 /*-------------------------------------------------------------------*/
69 // returns status (negative) or length (positive)
70 static int usb_internal_control_msg(struct usb_device *usb_dev,
72 struct usb_ctrlrequest *cmd,
73 void *data, int len, int timeout)
79 urb = usb_alloc_urb(0, GFP_NOIO);
83 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
84 len, usb_api_blocking_completion, NULL);
86 retv = usb_start_wait_urb(urb, timeout, &length);
94 * usb_control_msg - Builds a control urb, sends it off and waits for completion
95 * @dev: pointer to the usb device to send the message to
96 * @pipe: endpoint "pipe" to send the message to
97 * @request: USB message request value
98 * @requesttype: USB message request type value
99 * @value: USB message value
100 * @index: USB message index value
101 * @data: pointer to the data to send
102 * @size: length in bytes of the data to send
103 * @timeout: time in msecs to wait for the message to complete before
104 * timing out (if 0 the wait is forever)
105 * Context: !in_interrupt ()
107 * This function sends a simple control message to a specified endpoint
108 * and waits for the message to complete, or timeout.
110 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
112 * Don't use this function from within an interrupt context, like a
113 * bottom half handler. If you need an asynchronous message, or need to send
114 * a message from within interrupt context, use usb_submit_urb()
115 * If a thread in your driver uses this call, make sure your disconnect()
116 * method can wait for it to complete. Since you don't have a handle on
117 * the URB used, you can't cancel the request.
119 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
120 __u16 value, __u16 index, void *data, __u16 size, int timeout)
122 struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
128 dr->bRequestType= requesttype;
129 dr->bRequest = request;
130 dr->wValue = cpu_to_le16p(&value);
131 dr->wIndex = cpu_to_le16p(&index);
132 dr->wLength = cpu_to_le16p(&size);
134 //dbg("usb_control_msg");
136 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
145 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
146 * @usb_dev: pointer to the usb device to send the message to
147 * @pipe: endpoint "pipe" to send the message to
148 * @data: pointer to the data to send
149 * @len: length in bytes of the data to send
150 * @actual_length: pointer to a location to put the actual length transferred in bytes
151 * @timeout: time in msecs to wait for the message to complete before
152 * timing out (if 0 the wait is forever)
153 * Context: !in_interrupt ()
155 * This function sends a simple interrupt message to a specified endpoint and
156 * waits for the message to complete, or timeout.
158 * If successful, it returns 0, otherwise a negative error number. The number
159 * of actual bytes transferred will be stored in the actual_length paramater.
161 * Don't use this function from within an interrupt context, like a bottom half
162 * handler. If you need an asynchronous message, or need to send a message
163 * from within interrupt context, use usb_submit_urb() If a thread in your
164 * driver uses this call, make sure your disconnect() method can wait for it to
165 * complete. Since you don't have a handle on the URB used, you can't cancel
168 int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
169 void *data, int len, int *actual_length, int timeout)
171 return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
173 EXPORT_SYMBOL_GPL(usb_interrupt_msg);
176 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
177 * @usb_dev: pointer to the usb device to send the message to
178 * @pipe: endpoint "pipe" to send the message to
179 * @data: pointer to the data to send
180 * @len: length in bytes of the data to send
181 * @actual_length: pointer to a location to put the actual length transferred in bytes
182 * @timeout: time in msecs to wait for the message to complete before
183 * timing out (if 0 the wait is forever)
184 * Context: !in_interrupt ()
186 * This function sends a simple bulk message to a specified endpoint
187 * and waits for the message to complete, or timeout.
189 * If successful, it returns 0, otherwise a negative error number.
190 * The number of actual bytes transferred will be stored in the
191 * actual_length paramater.
193 * Don't use this function from within an interrupt context, like a
194 * bottom half handler. If you need an asynchronous message, or need to
195 * send a message from within interrupt context, use usb_submit_urb()
196 * If a thread in your driver uses this call, make sure your disconnect()
197 * method can wait for it to complete. Since you don't have a handle on
198 * the URB used, you can't cancel the request.
200 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT
201 * ioctl, users are forced to abuse this routine by using it to submit
202 * URBs for interrupt endpoints. We will take the liberty of creating
203 * an interrupt URB (with the default interval) if the target is an
204 * interrupt endpoint.
206 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
207 void *data, int len, int *actual_length, int timeout)
210 struct usb_host_endpoint *ep;
212 ep = (usb_pipein(pipe) ? usb_dev->ep_in : usb_dev->ep_out)
213 [usb_pipeendpoint(pipe)];
217 urb = usb_alloc_urb(0, GFP_KERNEL);
221 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
222 USB_ENDPOINT_XFER_INT) {
223 pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
224 usb_fill_int_urb(urb, usb_dev, pipe, data, len,
225 usb_api_blocking_completion, NULL,
228 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
229 usb_api_blocking_completion, NULL);
231 return usb_start_wait_urb(urb, timeout, actual_length);
234 /*-------------------------------------------------------------------*/
236 static void sg_clean (struct usb_sg_request *io)
239 while (io->entries--)
240 usb_free_urb (io->urbs [io->entries]);
244 if (io->dev->dev.dma_mask != NULL)
245 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
249 static void sg_complete (struct urb *urb)
251 struct usb_sg_request *io = urb->context;
253 spin_lock (&io->lock);
255 /* In 2.5 we require hcds' endpoint queues not to progress after fault
256 * reports, until the completion callback (this!) returns. That lets
257 * device driver code (like this routine) unlink queued urbs first,
258 * if it needs to, since the HC won't work on them at all. So it's
259 * not possible for page N+1 to overwrite page N, and so on.
261 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
262 * complete before the HCD can get requests away from hardware,
263 * though never during cleanup after a hard fault.
266 && (io->status != -ECONNRESET
267 || urb->status != -ECONNRESET)
268 && urb->actual_length) {
269 dev_err (io->dev->bus->controller,
270 "dev %s ep%d%s scatterlist error %d/%d\n",
272 usb_pipeendpoint (urb->pipe),
273 usb_pipein (urb->pipe) ? "in" : "out",
274 urb->status, io->status);
278 if (io->status == 0 && urb->status && urb->status != -ECONNRESET) {
279 int i, found, status;
281 io->status = urb->status;
283 /* the previous urbs, and this one, completed already.
284 * unlink pending urbs so they won't rx/tx bad data.
285 * careful: unlink can sometimes be synchronous...
287 spin_unlock (&io->lock);
288 for (i = 0, found = 0; i < io->entries; i++) {
289 if (!io->urbs [i] || !io->urbs [i]->dev)
292 status = usb_unlink_urb (io->urbs [i]);
293 if (status != -EINPROGRESS
296 dev_err (&io->dev->dev,
297 "%s, unlink --> %d\n",
298 __FUNCTION__, status);
299 } else if (urb == io->urbs [i])
302 spin_lock (&io->lock);
306 /* on the last completion, signal usb_sg_wait() */
307 io->bytes += urb->actual_length;
310 complete (&io->complete);
312 spin_unlock (&io->lock);
317 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
318 * @io: request block being initialized. until usb_sg_wait() returns,
319 * treat this as a pointer to an opaque block of memory,
320 * @dev: the usb device that will send or receive the data
321 * @pipe: endpoint "pipe" used to transfer the data
322 * @period: polling rate for interrupt endpoints, in frames or
323 * (for high speed endpoints) microframes; ignored for bulk
324 * @sg: scatterlist entries
325 * @nents: how many entries in the scatterlist
326 * @length: how many bytes to send from the scatterlist, or zero to
327 * send every byte identified in the list.
328 * @mem_flags: SLAB_* flags affecting memory allocations in this call
330 * Returns zero for success, else a negative errno value. This initializes a
331 * scatter/gather request, allocating resources such as I/O mappings and urb
332 * memory (except maybe memory used by USB controller drivers).
334 * The request must be issued using usb_sg_wait(), which waits for the I/O to
335 * complete (or to be canceled) and then cleans up all resources allocated by
338 * The request may be canceled with usb_sg_cancel(), either before or after
339 * usb_sg_wait() is called.
342 struct usb_sg_request *io,
343 struct usb_device *dev,
346 struct scatterlist *sg,
356 if (!io || !dev || !sg
357 || usb_pipecontrol (pipe)
358 || usb_pipeisoc (pipe)
362 spin_lock_init (&io->lock);
368 /* not all host controllers use DMA (like the mainstream pci ones);
369 * they can use PIO (sl811) or be software over another transport.
371 dma = (dev->dev.dma_mask != NULL);
373 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
377 /* initialize all the urbs we'll use */
378 if (io->entries <= 0)
381 io->count = io->entries;
382 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
386 urb_flags = URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
387 if (usb_pipein (pipe))
388 urb_flags |= URB_SHORT_NOT_OK;
390 for (i = 0; i < io->entries; i++) {
393 io->urbs [i] = usb_alloc_urb (0, mem_flags);
399 io->urbs [i]->dev = NULL;
400 io->urbs [i]->pipe = pipe;
401 io->urbs [i]->interval = period;
402 io->urbs [i]->transfer_flags = urb_flags;
404 io->urbs [i]->complete = sg_complete;
405 io->urbs [i]->context = io;
406 io->urbs [i]->status = -EINPROGRESS;
407 io->urbs [i]->actual_length = 0;
410 /* hc may use _only_ transfer_dma */
411 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
412 len = sg_dma_len (sg + i);
414 /* hc may use _only_ transfer_buffer */
415 io->urbs [i]->transfer_buffer =
416 page_address (sg [i].page) + sg [i].offset;
421 len = min_t (unsigned, len, length);
426 io->urbs [i]->transfer_buffer_length = len;
428 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
430 /* transaction state */
433 init_completion (&io->complete);
443 * usb_sg_wait - synchronously execute scatter/gather request
444 * @io: request block handle, as initialized with usb_sg_init().
445 * some fields become accessible when this call returns.
446 * Context: !in_interrupt ()
448 * This function blocks until the specified I/O operation completes. It
449 * leverages the grouping of the related I/O requests to get good transfer
450 * rates, by queueing the requests. At higher speeds, such queuing can
451 * significantly improve USB throughput.
453 * There are three kinds of completion for this function.
454 * (1) success, where io->status is zero. The number of io->bytes
455 * transferred is as requested.
456 * (2) error, where io->status is a negative errno value. The number
457 * of io->bytes transferred before the error is usually less
458 * than requested, and can be nonzero.
459 * (3) cancellation, a type of error with status -ECONNRESET that
460 * is initiated by usb_sg_cancel().
462 * When this function returns, all memory allocated through usb_sg_init() or
463 * this call will have been freed. The request block parameter may still be
464 * passed to usb_sg_cancel(), or it may be freed. It could also be
465 * reinitialized and then reused.
467 * Data Transfer Rates:
469 * Bulk transfers are valid for full or high speed endpoints.
470 * The best full speed data rate is 19 packets of 64 bytes each
471 * per frame, or 1216 bytes per millisecond.
472 * The best high speed data rate is 13 packets of 512 bytes each
473 * per microframe, or 52 KBytes per millisecond.
475 * The reason to use interrupt transfers through this API would most likely
476 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
477 * could be transferred. That capability is less useful for low or full
478 * speed interrupt endpoints, which allow at most one packet per millisecond,
479 * of at most 8 or 64 bytes (respectively).
481 void usb_sg_wait (struct usb_sg_request *io)
483 int i, entries = io->entries;
485 /* queue the urbs. */
486 spin_lock_irq (&io->lock);
487 for (i = 0; i < entries && !io->status; i++) {
490 io->urbs [i]->dev = io->dev;
491 retval = usb_submit_urb (io->urbs [i], GFP_ATOMIC);
493 /* after we submit, let completions or cancelations fire;
494 * we handshake using io->status.
496 spin_unlock_irq (&io->lock);
498 /* maybe we retrying will recover */
499 case -ENXIO: // hc didn't queue this one
502 io->urbs[i]->dev = NULL;
508 /* no error? continue immediately.
510 * NOTE: to work better with UHCI (4K I/O buffer may
511 * need 3K of TDs) it may be good to limit how many
512 * URBs are queued at once; N milliseconds?
518 /* fail any uncompleted urbs */
520 io->urbs [i]->dev = NULL;
521 io->urbs [i]->status = retval;
522 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
523 __FUNCTION__, retval);
526 spin_lock_irq (&io->lock);
527 if (retval && (io->status == 0 || io->status == -ECONNRESET))
530 io->count -= entries - i;
532 complete (&io->complete);
533 spin_unlock_irq (&io->lock);
535 /* OK, yes, this could be packaged as non-blocking.
536 * So could the submit loop above ... but it's easier to
537 * solve neither problem than to solve both!
539 wait_for_completion (&io->complete);
545 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
546 * @io: request block, initialized with usb_sg_init()
548 * This stops a request after it has been started by usb_sg_wait().
549 * It can also prevents one initialized by usb_sg_init() from starting,
550 * so that call just frees resources allocated to the request.
552 void usb_sg_cancel (struct usb_sg_request *io)
556 spin_lock_irqsave (&io->lock, flags);
558 /* shut everything down, if it didn't already */
562 io->status = -ECONNRESET;
563 spin_unlock (&io->lock);
564 for (i = 0; i < io->entries; i++) {
567 if (!io->urbs [i]->dev)
569 retval = usb_unlink_urb (io->urbs [i]);
570 if (retval != -EINPROGRESS && retval != -EBUSY)
571 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
572 __FUNCTION__, retval);
574 spin_lock (&io->lock);
576 spin_unlock_irqrestore (&io->lock, flags);
579 /*-------------------------------------------------------------------*/
582 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
583 * @dev: the device whose descriptor is being retrieved
584 * @type: the descriptor type (USB_DT_*)
585 * @index: the number of the descriptor
586 * @buf: where to put the descriptor
587 * @size: how big is "buf"?
588 * Context: !in_interrupt ()
590 * Gets a USB descriptor. Convenience functions exist to simplify
591 * getting some types of descriptors. Use
592 * usb_get_string() or usb_string() for USB_DT_STRING.
593 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
594 * are part of the device structure.
595 * In addition to a number of USB-standard descriptors, some
596 * devices also use class-specific or vendor-specific descriptors.
598 * This call is synchronous, and may not be used in an interrupt context.
600 * Returns the number of bytes received on success, or else the status code
601 * returned by the underlying usb_control_msg() call.
603 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
608 memset(buf,0,size); // Make sure we parse really received data
610 for (i = 0; i < 3; ++i) {
611 /* retry on length 0 or stall; some devices are flakey */
612 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
613 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
614 (type << 8) + index, 0, buf, size,
615 USB_CTRL_GET_TIMEOUT);
616 if (result == 0 || result == -EPIPE)
618 if (result > 1 && ((u8 *)buf)[1] != type) {
628 * usb_get_string - gets a string descriptor
629 * @dev: the device whose string descriptor is being retrieved
630 * @langid: code for language chosen (from string descriptor zero)
631 * @index: the number of the descriptor
632 * @buf: where to put the string
633 * @size: how big is "buf"?
634 * Context: !in_interrupt ()
636 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
637 * in little-endian byte order).
638 * The usb_string() function will often be a convenient way to turn
639 * these strings into kernel-printable form.
641 * Strings may be referenced in device, configuration, interface, or other
642 * descriptors, and could also be used in vendor-specific ways.
644 * This call is synchronous, and may not be used in an interrupt context.
646 * Returns the number of bytes received on success, or else the status code
647 * returned by the underlying usb_control_msg() call.
649 static int usb_get_string(struct usb_device *dev, unsigned short langid,
650 unsigned char index, void *buf, int size)
655 for (i = 0; i < 3; ++i) {
656 /* retry on length 0 or stall; some devices are flakey */
657 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
658 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
659 (USB_DT_STRING << 8) + index, langid, buf, size,
660 USB_CTRL_GET_TIMEOUT);
661 if (!(result == 0 || result == -EPIPE))
667 static void usb_try_string_workarounds(unsigned char *buf, int *length)
669 int newlength, oldlength = *length;
671 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
672 if (!isprint(buf[newlength]) || buf[newlength + 1])
681 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
682 unsigned int index, unsigned char *buf)
686 /* Try to read the string descriptor by asking for the maximum
687 * possible number of bytes */
688 rc = usb_get_string(dev, langid, index, buf, 255);
690 /* If that failed try to read the descriptor length, then
691 * ask for just that many bytes */
693 rc = usb_get_string(dev, langid, index, buf, 2);
695 rc = usb_get_string(dev, langid, index, buf, buf[0]);
699 if (!buf[0] && !buf[1])
700 usb_try_string_workarounds(buf, &rc);
702 /* There might be extra junk at the end of the descriptor */
706 rc = rc - (rc & 1); /* force a multiple of two */
710 rc = (rc < 0 ? rc : -EINVAL);
716 * usb_string - returns ISO 8859-1 version of a string descriptor
717 * @dev: the device whose string descriptor is being retrieved
718 * @index: the number of the descriptor
719 * @buf: where to put the string
720 * @size: how big is "buf"?
721 * Context: !in_interrupt ()
723 * This converts the UTF-16LE encoded strings returned by devices, from
724 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
725 * that are more usable in most kernel contexts. Note that all characters
726 * in the chosen descriptor that can't be encoded using ISO-8859-1
727 * are converted to the question mark ("?") character, and this function
728 * chooses strings in the first language supported by the device.
730 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
731 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
732 * and is appropriate for use many uses of English and several other
733 * Western European languages. (But it doesn't include the "Euro" symbol.)
735 * This call is synchronous, and may not be used in an interrupt context.
737 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
739 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
745 if (dev->state == USB_STATE_SUSPENDED)
746 return -EHOSTUNREACH;
747 if (size <= 0 || !buf || !index)
750 tbuf = kmalloc(256, GFP_KERNEL);
754 /* get langid for strings if it's not yet known */
755 if (!dev->have_langid) {
756 err = usb_string_sub(dev, 0, 0, tbuf);
759 "string descriptor 0 read error: %d\n",
762 } else if (err < 4) {
763 dev_err (&dev->dev, "string descriptor 0 too short\n");
767 dev->have_langid = 1;
768 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
769 /* always use the first langid listed */
770 dev_dbg (&dev->dev, "default language 0x%04x\n",
775 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
779 size--; /* leave room for trailing NULL char in output buffer */
780 for (idx = 0, u = 2; u < err; u += 2) {
783 if (tbuf[u+1]) /* high byte */
784 buf[idx++] = '?'; /* non ISO-8859-1 character */
786 buf[idx++] = tbuf[u];
791 if (tbuf[1] != USB_DT_STRING)
792 dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
800 * usb_cache_string - read a string descriptor and cache it for later use
801 * @udev: the device whose string descriptor is being read
802 * @index: the descriptor index
804 * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
805 * or NULL if the index is 0 or the string could not be read.
807 char *usb_cache_string(struct usb_device *udev, int index)
810 char *smallbuf = NULL;
813 if (index > 0 && (buf = kmalloc(256, GFP_KERNEL)) != NULL) {
814 if ((len = usb_string(udev, index, buf, 256)) > 0) {
815 if ((smallbuf = kmalloc(++len, GFP_KERNEL)) == NULL)
817 memcpy(smallbuf, buf, len);
825 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
826 * @dev: the device whose device descriptor is being updated
827 * @size: how much of the descriptor to read
828 * Context: !in_interrupt ()
830 * Updates the copy of the device descriptor stored in the device structure,
831 * which dedicates space for this purpose.
833 * Not exported, only for use by the core. If drivers really want to read
834 * the device descriptor directly, they can call usb_get_descriptor() with
835 * type = USB_DT_DEVICE and index = 0.
837 * This call is synchronous, and may not be used in an interrupt context.
839 * Returns the number of bytes received on success, or else the status code
840 * returned by the underlying usb_control_msg() call.
842 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
844 struct usb_device_descriptor *desc;
847 if (size > sizeof(*desc))
849 desc = kmalloc(sizeof(*desc), GFP_NOIO);
853 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
855 memcpy(&dev->descriptor, desc, size);
861 * usb_get_status - issues a GET_STATUS call
862 * @dev: the device whose status is being checked
863 * @type: USB_RECIP_*; for device, interface, or endpoint
864 * @target: zero (for device), else interface or endpoint number
865 * @data: pointer to two bytes of bitmap data
866 * Context: !in_interrupt ()
868 * Returns device, interface, or endpoint status. Normally only of
869 * interest to see if the device is self powered, or has enabled the
870 * remote wakeup facility; or whether a bulk or interrupt endpoint
871 * is halted ("stalled").
873 * Bits in these status bitmaps are set using the SET_FEATURE request,
874 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
875 * function should be used to clear halt ("stall") status.
877 * This call is synchronous, and may not be used in an interrupt context.
879 * Returns the number of bytes received on success, or else the status code
880 * returned by the underlying usb_control_msg() call.
882 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
885 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
890 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
891 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
892 sizeof(*status), USB_CTRL_GET_TIMEOUT);
894 *(u16 *)data = *status;
900 * usb_clear_halt - tells device to clear endpoint halt/stall condition
901 * @dev: device whose endpoint is halted
902 * @pipe: endpoint "pipe" being cleared
903 * Context: !in_interrupt ()
905 * This is used to clear halt conditions for bulk and interrupt endpoints,
906 * as reported by URB completion status. Endpoints that are halted are
907 * sometimes referred to as being "stalled". Such endpoints are unable
908 * to transmit or receive data until the halt status is cleared. Any URBs
909 * queued for such an endpoint should normally be unlinked by the driver
910 * before clearing the halt condition, as described in sections 5.7.5
911 * and 5.8.5 of the USB 2.0 spec.
913 * Note that control and isochronous endpoints don't halt, although control
914 * endpoints report "protocol stall" (for unsupported requests) using the
915 * same status code used to report a true stall.
917 * This call is synchronous, and may not be used in an interrupt context.
919 * Returns zero on success, or else the status code returned by the
920 * underlying usb_control_msg() call.
922 int usb_clear_halt(struct usb_device *dev, int pipe)
925 int endp = usb_pipeendpoint(pipe);
927 if (usb_pipein (pipe))
930 /* we don't care if it wasn't halted first. in fact some devices
931 * (like some ibmcam model 1 units) seem to expect hosts to make
932 * this request for iso endpoints, which can't halt!
934 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
935 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
936 USB_ENDPOINT_HALT, endp, NULL, 0,
937 USB_CTRL_SET_TIMEOUT);
939 /* don't un-halt or force to DATA0 except on success */
943 /* NOTE: seems like Microsoft and Apple don't bother verifying
944 * the clear "took", so some devices could lock up if you check...
945 * such as the Hagiwara FlashGate DUAL. So we won't bother.
947 * NOTE: make sure the logic here doesn't diverge much from
948 * the copy in usb-storage, for as long as we need two copies.
951 /* toggle was reset by the clear */
952 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
958 * usb_disable_endpoint -- Disable an endpoint by address
959 * @dev: the device whose endpoint is being disabled
960 * @epaddr: the endpoint's address. Endpoint number for output,
961 * endpoint number + USB_DIR_IN for input
963 * Deallocates hcd/hardware state for this endpoint ... and nukes all
966 * If the HCD hasn't registered a disable() function, this sets the
967 * endpoint's maxpacket size to 0 to prevent further submissions.
969 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
971 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
972 struct usb_host_endpoint *ep;
977 if (usb_endpoint_out(epaddr)) {
978 ep = dev->ep_out[epnum];
979 dev->ep_out[epnum] = NULL;
981 ep = dev->ep_in[epnum];
982 dev->ep_in[epnum] = NULL;
985 usb_hcd_endpoint_disable(dev, ep);
989 * usb_disable_interface -- Disable all endpoints for an interface
990 * @dev: the device whose interface is being disabled
991 * @intf: pointer to the interface descriptor
993 * Disables all the endpoints for the interface's current altsetting.
995 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
997 struct usb_host_interface *alt = intf->cur_altsetting;
1000 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1001 usb_disable_endpoint(dev,
1002 alt->endpoint[i].desc.bEndpointAddress);
1007 * usb_disable_device - Disable all the endpoints for a USB device
1008 * @dev: the device whose endpoints are being disabled
1009 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1011 * Disables all the device's endpoints, potentially including endpoint 0.
1012 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1013 * pending urbs) and usbcore state for the interfaces, so that usbcore
1014 * must usb_set_configuration() before any interfaces could be used.
1016 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1020 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
1021 skip_ep0 ? "non-ep0" : "all");
1022 for (i = skip_ep0; i < 16; ++i) {
1023 usb_disable_endpoint(dev, i);
1024 usb_disable_endpoint(dev, i + USB_DIR_IN);
1026 dev->toggle[0] = dev->toggle[1] = 0;
1028 /* getting rid of interfaces will disconnect
1029 * any drivers bound to them (a key side effect)
1031 if (dev->actconfig) {
1032 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1033 struct usb_interface *interface;
1035 /* remove this interface if it has been registered */
1036 interface = dev->actconfig->interface[i];
1037 if (!device_is_registered(&interface->dev))
1039 dev_dbg (&dev->dev, "unregistering interface %s\n",
1040 interface->dev.bus_id);
1041 usb_remove_sysfs_intf_files(interface);
1042 device_del (&interface->dev);
1045 /* Now that the interfaces are unbound, nobody should
1046 * try to access them.
1048 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1049 put_device (&dev->actconfig->interface[i]->dev);
1050 dev->actconfig->interface[i] = NULL;
1052 dev->actconfig = NULL;
1053 if (dev->state == USB_STATE_CONFIGURED)
1054 usb_set_device_state(dev, USB_STATE_ADDRESS);
1060 * usb_enable_endpoint - Enable an endpoint for USB communications
1061 * @dev: the device whose interface is being enabled
1064 * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
1065 * For control endpoints, both the input and output sides are handled.
1068 usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
1070 unsigned int epaddr = ep->desc.bEndpointAddress;
1071 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1074 is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1075 == USB_ENDPOINT_XFER_CONTROL);
1076 if (usb_endpoint_out(epaddr) || is_control) {
1077 usb_settoggle(dev, epnum, 1, 0);
1078 dev->ep_out[epnum] = ep;
1080 if (!usb_endpoint_out(epaddr) || is_control) {
1081 usb_settoggle(dev, epnum, 0, 0);
1082 dev->ep_in[epnum] = ep;
1087 * usb_enable_interface - Enable all the endpoints for an interface
1088 * @dev: the device whose interface is being enabled
1089 * @intf: pointer to the interface descriptor
1091 * Enables all the endpoints for the interface's current altsetting.
1093 static void usb_enable_interface(struct usb_device *dev,
1094 struct usb_interface *intf)
1096 struct usb_host_interface *alt = intf->cur_altsetting;
1099 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1100 usb_enable_endpoint(dev, &alt->endpoint[i]);
1104 * usb_set_interface - Makes a particular alternate setting be current
1105 * @dev: the device whose interface is being updated
1106 * @interface: the interface being updated
1107 * @alternate: the setting being chosen.
1108 * Context: !in_interrupt ()
1110 * This is used to enable data transfers on interfaces that may not
1111 * be enabled by default. Not all devices support such configurability.
1112 * Only the driver bound to an interface may change its setting.
1114 * Within any given configuration, each interface may have several
1115 * alternative settings. These are often used to control levels of
1116 * bandwidth consumption. For example, the default setting for a high
1117 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1118 * while interrupt transfers of up to 3KBytes per microframe are legal.
1119 * Also, isochronous endpoints may never be part of an
1120 * interface's default setting. To access such bandwidth, alternate
1121 * interface settings must be made current.
1123 * Note that in the Linux USB subsystem, bandwidth associated with
1124 * an endpoint in a given alternate setting is not reserved until an URB
1125 * is submitted that needs that bandwidth. Some other operating systems
1126 * allocate bandwidth early, when a configuration is chosen.
1128 * This call is synchronous, and may not be used in an interrupt context.
1129 * Also, drivers must not change altsettings while urbs are scheduled for
1130 * endpoints in that interface; all such urbs must first be completed
1131 * (perhaps forced by unlinking).
1133 * Returns zero on success, or else the status code returned by the
1134 * underlying usb_control_msg() call.
1136 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1138 struct usb_interface *iface;
1139 struct usb_host_interface *alt;
1143 if (dev->state == USB_STATE_SUSPENDED)
1144 return -EHOSTUNREACH;
1146 iface = usb_ifnum_to_if(dev, interface);
1148 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1153 alt = usb_altnum_to_altsetting(iface, alternate);
1155 warn("selecting invalid altsetting %d", alternate);
1159 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1160 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1161 alternate, interface, NULL, 0, 5000);
1163 /* 9.4.10 says devices don't need this and are free to STALL the
1164 * request if the interface only has one alternate setting.
1166 if (ret == -EPIPE && iface->num_altsetting == 1) {
1168 "manual set_interface for iface %d, alt %d\n",
1169 interface, alternate);
1174 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1175 * when they implement async or easily-killable versions of this or
1176 * other "should-be-internal" functions (like clear_halt).
1177 * should hcd+usbcore postprocess control requests?
1180 /* prevent submissions using previous endpoint settings */
1181 if (device_is_registered(&iface->dev))
1182 usb_remove_sysfs_intf_files(iface);
1183 usb_disable_interface(dev, iface);
1185 iface->cur_altsetting = alt;
1187 /* If the interface only has one altsetting and the device didn't
1188 * accept the request, we attempt to carry out the equivalent action
1189 * by manually clearing the HALT feature for each endpoint in the
1195 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1196 unsigned int epaddr =
1197 alt->endpoint[i].desc.bEndpointAddress;
1199 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
1200 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1202 usb_clear_halt(dev, pipe);
1206 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1209 * Despite EP0 is always present in all interfaces/AS, the list of
1210 * endpoints from the descriptor does not contain EP0. Due to its
1211 * omnipresence one might expect EP0 being considered "affected" by
1212 * any SetInterface request and hence assume toggles need to be reset.
1213 * However, EP0 toggles are re-synced for every individual transfer
1214 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1215 * (Likewise, EP0 never "halts" on well designed devices.)
1217 usb_enable_interface(dev, iface);
1218 if (device_is_registered(&iface->dev))
1219 usb_create_sysfs_intf_files(iface);
1225 * usb_reset_configuration - lightweight device reset
1226 * @dev: the device whose configuration is being reset
1228 * This issues a standard SET_CONFIGURATION request to the device using
1229 * the current configuration. The effect is to reset most USB-related
1230 * state in the device, including interface altsettings (reset to zero),
1231 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1232 * endpoints). Other usbcore state is unchanged, including bindings of
1233 * usb device drivers to interfaces.
1235 * Because this affects multiple interfaces, avoid using this with composite
1236 * (multi-interface) devices. Instead, the driver for each interface may
1237 * use usb_set_interface() on the interfaces it claims. Be careful though;
1238 * some devices don't support the SET_INTERFACE request, and others won't
1239 * reset all the interface state (notably data toggles). Resetting the whole
1240 * configuration would affect other drivers' interfaces.
1242 * The caller must own the device lock.
1244 * Returns zero on success, else a negative error code.
1246 int usb_reset_configuration(struct usb_device *dev)
1249 struct usb_host_config *config;
1251 if (dev->state == USB_STATE_SUSPENDED)
1252 return -EHOSTUNREACH;
1254 /* caller must have locked the device and must own
1255 * the usb bus readlock (so driver bindings are stable);
1256 * calls during probe() are fine
1259 for (i = 1; i < 16; ++i) {
1260 usb_disable_endpoint(dev, i);
1261 usb_disable_endpoint(dev, i + USB_DIR_IN);
1264 config = dev->actconfig;
1265 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1266 USB_REQ_SET_CONFIGURATION, 0,
1267 config->desc.bConfigurationValue, 0,
1268 NULL, 0, USB_CTRL_SET_TIMEOUT);
1272 dev->toggle[0] = dev->toggle[1] = 0;
1274 /* re-init hc/hcd interface/endpoint state */
1275 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1276 struct usb_interface *intf = config->interface[i];
1277 struct usb_host_interface *alt;
1279 if (device_is_registered(&intf->dev))
1280 usb_remove_sysfs_intf_files(intf);
1281 alt = usb_altnum_to_altsetting(intf, 0);
1283 /* No altsetting 0? We'll assume the first altsetting.
1284 * We could use a GetInterface call, but if a device is
1285 * so non-compliant that it doesn't have altsetting 0
1286 * then I wouldn't trust its reply anyway.
1289 alt = &intf->altsetting[0];
1291 intf->cur_altsetting = alt;
1292 usb_enable_interface(dev, intf);
1293 if (device_is_registered(&intf->dev))
1294 usb_create_sysfs_intf_files(intf);
1299 static void release_interface(struct device *dev)
1301 struct usb_interface *intf = to_usb_interface(dev);
1302 struct usb_interface_cache *intfc =
1303 altsetting_to_usb_interface_cache(intf->altsetting);
1305 kref_put(&intfc->ref, usb_release_interface_cache);
1310 * usb_set_configuration - Makes a particular device setting be current
1311 * @dev: the device whose configuration is being updated
1312 * @configuration: the configuration being chosen.
1313 * Context: !in_interrupt(), caller owns the device lock
1315 * This is used to enable non-default device modes. Not all devices
1316 * use this kind of configurability; many devices only have one
1319 * USB device configurations may affect Linux interoperability,
1320 * power consumption and the functionality available. For example,
1321 * the default configuration is limited to using 100mA of bus power,
1322 * so that when certain device functionality requires more power,
1323 * and the device is bus powered, that functionality should be in some
1324 * non-default device configuration. Other device modes may also be
1325 * reflected as configuration options, such as whether two ISDN
1326 * channels are available independently; and choosing between open
1327 * standard device protocols (like CDC) or proprietary ones.
1329 * Note that USB has an additional level of device configurability,
1330 * associated with interfaces. That configurability is accessed using
1331 * usb_set_interface().
1333 * This call is synchronous. The calling context must be able to sleep,
1334 * must own the device lock, and must not hold the driver model's USB
1335 * bus rwsem; usb device driver probe() methods cannot use this routine.
1337 * Returns zero on success, or else the status code returned by the
1338 * underlying call that failed. On successful completion, each interface
1339 * in the original device configuration has been destroyed, and each one
1340 * in the new configuration has been probed by all relevant usb device
1341 * drivers currently known to the kernel.
1343 int usb_set_configuration(struct usb_device *dev, int configuration)
1346 struct usb_host_config *cp = NULL;
1347 struct usb_interface **new_interfaces = NULL;
1350 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1351 if (dev->config[i].desc.bConfigurationValue == configuration) {
1352 cp = &dev->config[i];
1356 if ((!cp && configuration != 0))
1359 /* The USB spec says configuration 0 means unconfigured.
1360 * But if a device includes a configuration numbered 0,
1361 * we will accept it as a correctly configured state.
1363 if (cp && configuration == 0)
1364 dev_warn(&dev->dev, "config 0 descriptor??\n");
1366 /* Allocate memory for new interfaces before doing anything else,
1367 * so that if we run out then nothing will have changed. */
1370 nintf = cp->desc.bNumInterfaces;
1371 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1373 if (!new_interfaces) {
1374 dev_err(&dev->dev, "Out of memory");
1378 for (; n < nintf; ++n) {
1379 new_interfaces[n] = kzalloc(
1380 sizeof(struct usb_interface),
1382 if (!new_interfaces[n]) {
1383 dev_err(&dev->dev, "Out of memory");
1387 kfree(new_interfaces[n]);
1388 kfree(new_interfaces);
1393 i = dev->bus_mA - cp->desc.bMaxPower * 2;
1395 dev_warn(&dev->dev, "new config #%d exceeds power "
1400 /* Wake up the device so we can send it the Set-Config request */
1401 ret = usb_autoresume_device(dev);
1403 goto free_interfaces;
1405 /* if it's already configured, clear out old state first.
1406 * getting rid of old interfaces means unbinding their drivers.
1408 if (dev->state != USB_STATE_ADDRESS)
1409 usb_disable_device (dev, 1); // Skip ep0
1411 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1412 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1413 NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0) {
1415 /* All the old state is gone, so what else can we do?
1416 * The device is probably useless now anyway.
1421 dev->actconfig = cp;
1423 usb_set_device_state(dev, USB_STATE_ADDRESS);
1424 usb_autosuspend_device(dev);
1425 goto free_interfaces;
1427 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1429 /* Initialize the new interface structures and the
1430 * hc/hcd/usbcore interface/endpoint state.
1432 for (i = 0; i < nintf; ++i) {
1433 struct usb_interface_cache *intfc;
1434 struct usb_interface *intf;
1435 struct usb_host_interface *alt;
1437 cp->interface[i] = intf = new_interfaces[i];
1438 intfc = cp->intf_cache[i];
1439 intf->altsetting = intfc->altsetting;
1440 intf->num_altsetting = intfc->num_altsetting;
1441 kref_get(&intfc->ref);
1443 alt = usb_altnum_to_altsetting(intf, 0);
1445 /* No altsetting 0? We'll assume the first altsetting.
1446 * We could use a GetInterface call, but if a device is
1447 * so non-compliant that it doesn't have altsetting 0
1448 * then I wouldn't trust its reply anyway.
1451 alt = &intf->altsetting[0];
1453 intf->cur_altsetting = alt;
1454 usb_enable_interface(dev, intf);
1455 intf->dev.parent = &dev->dev;
1456 intf->dev.driver = NULL;
1457 intf->dev.bus = &usb_bus_type;
1458 intf->dev.dma_mask = dev->dev.dma_mask;
1459 intf->dev.release = release_interface;
1460 device_initialize (&intf->dev);
1461 mark_quiesced(intf);
1462 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1463 dev->bus->busnum, dev->devpath,
1464 configuration, alt->desc.bInterfaceNumber);
1466 kfree(new_interfaces);
1468 if (cp->string == NULL)
1469 cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
1471 /* Now that all the interfaces are set up, register them
1472 * to trigger binding of drivers to interfaces. probe()
1473 * routines may install different altsettings and may
1474 * claim() any interfaces not yet bound. Many class drivers
1475 * need that: CDC, audio, video, etc.
1477 for (i = 0; i < nintf; ++i) {
1478 struct usb_interface *intf = cp->interface[i];
1481 "adding %s (config #%d, interface %d)\n",
1482 intf->dev.bus_id, configuration,
1483 intf->cur_altsetting->desc.bInterfaceNumber);
1484 ret = device_add (&intf->dev);
1486 dev_err(&dev->dev, "device_add(%s) --> %d\n",
1487 intf->dev.bus_id, ret);
1490 usb_create_sysfs_intf_files (intf);
1493 usb_autosuspend_device(dev);
1497 struct set_config_request {
1498 struct usb_device *udev;
1500 struct work_struct work;
1503 /* Worker routine for usb_driver_set_configuration() */
1504 static void driver_set_config_work(struct work_struct *work)
1506 struct set_config_request *req =
1507 container_of(work, struct set_config_request, work);
1509 usb_lock_device(req->udev);
1510 usb_set_configuration(req->udev, req->config);
1511 usb_unlock_device(req->udev);
1512 usb_put_dev(req->udev);
1517 * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1518 * @udev: the device whose configuration is being updated
1519 * @config: the configuration being chosen.
1520 * Context: In process context, must be able to sleep
1522 * Device interface drivers are not allowed to change device configurations.
1523 * This is because changing configurations will destroy the interface the
1524 * driver is bound to and create new ones; it would be like a floppy-disk
1525 * driver telling the computer to replace the floppy-disk drive with a
1528 * Still, in certain specialized circumstances the need may arise. This
1529 * routine gets around the normal restrictions by using a work thread to
1530 * submit the change-config request.
1532 * Returns 0 if the request was succesfully queued, error code otherwise.
1533 * The caller has no way to know whether the queued request will eventually
1536 int usb_driver_set_configuration(struct usb_device *udev, int config)
1538 struct set_config_request *req;
1540 req = kmalloc(sizeof(*req), GFP_KERNEL);
1544 req->config = config;
1545 INIT_WORK(&req->work, driver_set_config_work);
1548 schedule_work(&req->work);
1551 EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
1553 // synchronous request completion model
1554 EXPORT_SYMBOL(usb_control_msg);
1555 EXPORT_SYMBOL(usb_bulk_msg);
1557 EXPORT_SYMBOL(usb_sg_init);
1558 EXPORT_SYMBOL(usb_sg_cancel);
1559 EXPORT_SYMBOL(usb_sg_wait);
1561 // synchronous control message convenience routines
1562 EXPORT_SYMBOL(usb_get_descriptor);
1563 EXPORT_SYMBOL(usb_get_status);
1564 EXPORT_SYMBOL(usb_string);
1566 // synchronous calls that also maintain usbcore state
1567 EXPORT_SYMBOL(usb_clear_halt);
1568 EXPORT_SYMBOL(usb_reset_configuration);
1569 EXPORT_SYMBOL(usb_set_interface);