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, struct pt_regs *regs)
22 complete((struct completion *)urb->context);
26 static void timeout_kill(unsigned long data)
28 struct urb *urb = (struct urb *) data;
33 // Starts urb and waits for completion or timeout
34 // note that this call is NOT interruptible, while
35 // many device driver i/o requests should be interruptible
36 static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
38 struct completion done;
39 struct timer_list timer;
42 init_completion(&done);
44 urb->actual_length = 0;
45 status = usb_submit_urb(urb, GFP_NOIO);
50 timer.expires = jiffies + msecs_to_jiffies(timeout);
51 timer.data = (unsigned long)urb;
52 timer.function = timeout_kill;
53 /* grr. timeout _should_ include submit delays. */
56 wait_for_completion(&done);
58 /* note: HCDs return ETIMEDOUT for other reasons too */
59 if (status == -ECONNRESET) {
60 dev_dbg(&urb->dev->dev,
61 "%s timed out on ep%d%s len=%d/%d\n",
63 usb_pipeendpoint(urb->pipe),
64 usb_pipein(urb->pipe) ? "in" : "out",
66 urb->transfer_buffer_length
68 if (urb->actual_length > 0)
74 del_timer_sync(&timer);
78 *actual_length = urb->actual_length;
83 /*-------------------------------------------------------------------*/
84 // returns status (negative) or length (positive)
85 static int usb_internal_control_msg(struct usb_device *usb_dev,
87 struct usb_ctrlrequest *cmd,
88 void *data, int len, int timeout)
94 urb = usb_alloc_urb(0, GFP_NOIO);
98 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
99 len, usb_api_blocking_completion, NULL);
101 retv = usb_start_wait_urb(urb, timeout, &length);
109 * usb_control_msg - Builds a control urb, sends it off and waits for completion
110 * @dev: pointer to the usb device to send the message to
111 * @pipe: endpoint "pipe" to send the message to
112 * @request: USB message request value
113 * @requesttype: USB message request type value
114 * @value: USB message value
115 * @index: USB message index value
116 * @data: pointer to the data to send
117 * @size: length in bytes of the data to send
118 * @timeout: time in msecs to wait for the message to complete before
119 * timing out (if 0 the wait is forever)
120 * Context: !in_interrupt ()
122 * This function sends a simple control message to a specified endpoint
123 * and waits for the message to complete, or timeout.
125 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
127 * Don't use this function from within an interrupt context, like a
128 * bottom half handler. If you need an asynchronous message, or need to send
129 * a message from within interrupt context, use usb_submit_urb()
130 * If a thread in your driver uses this call, make sure your disconnect()
131 * method can wait for it to complete. Since you don't have a handle on
132 * the URB used, you can't cancel the request.
134 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
135 __u16 value, __u16 index, void *data, __u16 size, int timeout)
137 struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
143 dr->bRequestType= requesttype;
144 dr->bRequest = request;
145 dr->wValue = cpu_to_le16p(&value);
146 dr->wIndex = cpu_to_le16p(&index);
147 dr->wLength = cpu_to_le16p(&size);
149 //dbg("usb_control_msg");
151 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
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 in bytes
166 * @timeout: time in msecs to wait for the message to complete before
167 * timing out (if 0 the wait is forever)
168 * Context: !in_interrupt ()
170 * This function sends a simple interrupt message to a specified endpoint and
171 * waits for the message to complete, or timeout.
173 * If successful, it returns 0, otherwise a negative error number. The number
174 * of actual bytes transferred will be stored in the actual_length paramater.
176 * Don't use this function from within an interrupt context, like a bottom half
177 * handler. If you need an asynchronous message, or need to send a message
178 * from within interrupt context, use usb_submit_urb() If a thread in your
179 * driver uses this call, make sure your disconnect() method can wait for it to
180 * complete. Since you don't have a handle on the URB used, you can't cancel
183 int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
184 void *data, int len, int *actual_length, int timeout)
186 return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
188 EXPORT_SYMBOL_GPL(usb_interrupt_msg);
191 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
192 * @usb_dev: pointer to the usb device to send the message to
193 * @pipe: endpoint "pipe" to send the message to
194 * @data: pointer to the data to send
195 * @len: length in bytes of the data to send
196 * @actual_length: pointer to a location to put the actual length transferred in bytes
197 * @timeout: time in msecs to wait for the message to complete before
198 * timing out (if 0 the wait is forever)
199 * Context: !in_interrupt ()
201 * This function sends a simple bulk message to a specified endpoint
202 * and waits for the message to complete, or timeout.
204 * If successful, it returns 0, otherwise a negative error number.
205 * The number of actual bytes transferred will be stored in the
206 * actual_length paramater.
208 * Don't use this function from within an interrupt context, like a
209 * bottom half handler. If you need an asynchronous message, or need to
210 * send a message from within interrupt context, use usb_submit_urb()
211 * If a thread in your driver uses this call, make sure your disconnect()
212 * method can wait for it to complete. Since you don't have a handle on
213 * the URB used, you can't cancel the request.
215 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT
216 * ioctl, users are forced to abuse this routine by using it to submit
217 * URBs for interrupt endpoints. We will take the liberty of creating
218 * an interrupt URB (with the default interval) if the target is an
219 * interrupt endpoint.
221 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
222 void *data, int len, int *actual_length, int timeout)
225 struct usb_host_endpoint *ep;
227 ep = (usb_pipein(pipe) ? usb_dev->ep_in : usb_dev->ep_out)
228 [usb_pipeendpoint(pipe)];
232 urb = usb_alloc_urb(0, GFP_KERNEL);
236 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
237 USB_ENDPOINT_XFER_INT) {
238 pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
239 usb_fill_int_urb(urb, usb_dev, pipe, data, len,
240 usb_api_blocking_completion, NULL,
243 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
244 usb_api_blocking_completion, NULL);
246 return usb_start_wait_urb(urb, timeout, actual_length);
249 /*-------------------------------------------------------------------*/
251 static void sg_clean (struct usb_sg_request *io)
254 while (io->entries--)
255 usb_free_urb (io->urbs [io->entries]);
259 if (io->dev->dev.dma_mask != NULL)
260 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
264 static void sg_complete (struct urb *urb, struct pt_regs *regs)
266 struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
268 spin_lock (&io->lock);
270 /* In 2.5 we require hcds' endpoint queues not to progress after fault
271 * reports, until the completion callback (this!) returns. That lets
272 * device driver code (like this routine) unlink queued urbs first,
273 * if it needs to, since the HC won't work on them at all. So it's
274 * not possible for page N+1 to overwrite page N, and so on.
276 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
277 * complete before the HCD can get requests away from hardware,
278 * though never during cleanup after a hard fault.
281 && (io->status != -ECONNRESET
282 || urb->status != -ECONNRESET)
283 && urb->actual_length) {
284 dev_err (io->dev->bus->controller,
285 "dev %s ep%d%s scatterlist error %d/%d\n",
287 usb_pipeendpoint (urb->pipe),
288 usb_pipein (urb->pipe) ? "in" : "out",
289 urb->status, io->status);
293 if (io->status == 0 && urb->status && urb->status != -ECONNRESET) {
294 int i, found, status;
296 io->status = urb->status;
298 /* the previous urbs, and this one, completed already.
299 * unlink pending urbs so they won't rx/tx bad data.
300 * careful: unlink can sometimes be synchronous...
302 spin_unlock (&io->lock);
303 for (i = 0, found = 0; i < io->entries; i++) {
304 if (!io->urbs [i] || !io->urbs [i]->dev)
307 status = usb_unlink_urb (io->urbs [i]);
308 if (status != -EINPROGRESS
311 dev_err (&io->dev->dev,
312 "%s, unlink --> %d\n",
313 __FUNCTION__, status);
314 } else if (urb == io->urbs [i])
317 spin_lock (&io->lock);
321 /* on the last completion, signal usb_sg_wait() */
322 io->bytes += urb->actual_length;
325 complete (&io->complete);
327 spin_unlock (&io->lock);
332 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
333 * @io: request block being initialized. until usb_sg_wait() returns,
334 * treat this as a pointer to an opaque block of memory,
335 * @dev: the usb device that will send or receive the data
336 * @pipe: endpoint "pipe" used to transfer the data
337 * @period: polling rate for interrupt endpoints, in frames or
338 * (for high speed endpoints) microframes; ignored for bulk
339 * @sg: scatterlist entries
340 * @nents: how many entries in the scatterlist
341 * @length: how many bytes to send from the scatterlist, or zero to
342 * send every byte identified in the list.
343 * @mem_flags: SLAB_* flags affecting memory allocations in this call
345 * Returns zero for success, else a negative errno value. This initializes a
346 * scatter/gather request, allocating resources such as I/O mappings and urb
347 * memory (except maybe memory used by USB controller drivers).
349 * The request must be issued using usb_sg_wait(), which waits for the I/O to
350 * complete (or to be canceled) and then cleans up all resources allocated by
353 * The request may be canceled with usb_sg_cancel(), either before or after
354 * usb_sg_wait() is called.
357 struct usb_sg_request *io,
358 struct usb_device *dev,
361 struct scatterlist *sg,
371 if (!io || !dev || !sg
372 || usb_pipecontrol (pipe)
373 || usb_pipeisoc (pipe)
377 spin_lock_init (&io->lock);
383 /* not all host controllers use DMA (like the mainstream pci ones);
384 * they can use PIO (sl811) or be software over another transport.
386 dma = (dev->dev.dma_mask != NULL);
388 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
392 /* initialize all the urbs we'll use */
393 if (io->entries <= 0)
396 io->count = io->entries;
397 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
401 urb_flags = URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
402 if (usb_pipein (pipe))
403 urb_flags |= URB_SHORT_NOT_OK;
405 for (i = 0; i < io->entries; i++) {
408 io->urbs [i] = usb_alloc_urb (0, mem_flags);
414 io->urbs [i]->dev = NULL;
415 io->urbs [i]->pipe = pipe;
416 io->urbs [i]->interval = period;
417 io->urbs [i]->transfer_flags = urb_flags;
419 io->urbs [i]->complete = sg_complete;
420 io->urbs [i]->context = io;
421 io->urbs [i]->status = -EINPROGRESS;
422 io->urbs [i]->actual_length = 0;
425 /* hc may use _only_ transfer_dma */
426 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
427 len = sg_dma_len (sg + i);
429 /* hc may use _only_ transfer_buffer */
430 io->urbs [i]->transfer_buffer =
431 page_address (sg [i].page) + sg [i].offset;
436 len = min_t (unsigned, len, length);
441 io->urbs [i]->transfer_buffer_length = len;
443 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
445 /* transaction state */
448 init_completion (&io->complete);
458 * usb_sg_wait - synchronously execute scatter/gather request
459 * @io: request block handle, as initialized with usb_sg_init().
460 * some fields become accessible when this call returns.
461 * Context: !in_interrupt ()
463 * This function blocks until the specified I/O operation completes. It
464 * leverages the grouping of the related I/O requests to get good transfer
465 * rates, by queueing the requests. At higher speeds, such queuing can
466 * significantly improve USB throughput.
468 * There are three kinds of completion for this function.
469 * (1) success, where io->status is zero. The number of io->bytes
470 * transferred is as requested.
471 * (2) error, where io->status is a negative errno value. The number
472 * of io->bytes transferred before the error is usually less
473 * than requested, and can be nonzero.
474 * (3) cancellation, a type of error with status -ECONNRESET that
475 * is initiated by usb_sg_cancel().
477 * When this function returns, all memory allocated through usb_sg_init() or
478 * this call will have been freed. The request block parameter may still be
479 * passed to usb_sg_cancel(), or it may be freed. It could also be
480 * reinitialized and then reused.
482 * Data Transfer Rates:
484 * Bulk transfers are valid for full or high speed endpoints.
485 * The best full speed data rate is 19 packets of 64 bytes each
486 * per frame, or 1216 bytes per millisecond.
487 * The best high speed data rate is 13 packets of 512 bytes each
488 * per microframe, or 52 KBytes per millisecond.
490 * The reason to use interrupt transfers through this API would most likely
491 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
492 * could be transferred. That capability is less useful for low or full
493 * speed interrupt endpoints, which allow at most one packet per millisecond,
494 * of at most 8 or 64 bytes (respectively).
496 void usb_sg_wait (struct usb_sg_request *io)
498 int i, entries = io->entries;
500 /* queue the urbs. */
501 spin_lock_irq (&io->lock);
502 for (i = 0; i < entries && !io->status; i++) {
505 io->urbs [i]->dev = io->dev;
506 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
508 /* after we submit, let completions or cancelations fire;
509 * we handshake using io->status.
511 spin_unlock_irq (&io->lock);
513 /* maybe we retrying will recover */
514 case -ENXIO: // hc didn't queue this one
517 io->urbs[i]->dev = NULL;
523 /* no error? continue immediately.
525 * NOTE: to work better with UHCI (4K I/O buffer may
526 * need 3K of TDs) it may be good to limit how many
527 * URBs are queued at once; N milliseconds?
533 /* fail any uncompleted urbs */
535 io->urbs [i]->dev = NULL;
536 io->urbs [i]->status = retval;
537 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
538 __FUNCTION__, retval);
541 spin_lock_irq (&io->lock);
542 if (retval && (io->status == 0 || io->status == -ECONNRESET))
545 io->count -= entries - i;
547 complete (&io->complete);
548 spin_unlock_irq (&io->lock);
550 /* OK, yes, this could be packaged as non-blocking.
551 * So could the submit loop above ... but it's easier to
552 * solve neither problem than to solve both!
554 wait_for_completion (&io->complete);
560 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
561 * @io: request block, initialized with usb_sg_init()
563 * This stops a request after it has been started by usb_sg_wait().
564 * It can also prevents one initialized by usb_sg_init() from starting,
565 * so that call just frees resources allocated to the request.
567 void usb_sg_cancel (struct usb_sg_request *io)
571 spin_lock_irqsave (&io->lock, flags);
573 /* shut everything down, if it didn't already */
577 io->status = -ECONNRESET;
578 spin_unlock (&io->lock);
579 for (i = 0; i < io->entries; i++) {
582 if (!io->urbs [i]->dev)
584 retval = usb_unlink_urb (io->urbs [i]);
585 if (retval != -EINPROGRESS && retval != -EBUSY)
586 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
587 __FUNCTION__, retval);
589 spin_lock (&io->lock);
591 spin_unlock_irqrestore (&io->lock, flags);
594 /*-------------------------------------------------------------------*/
597 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
598 * @dev: the device whose descriptor is being retrieved
599 * @type: the descriptor type (USB_DT_*)
600 * @index: the number of the descriptor
601 * @buf: where to put the descriptor
602 * @size: how big is "buf"?
603 * Context: !in_interrupt ()
605 * Gets a USB descriptor. Convenience functions exist to simplify
606 * getting some types of descriptors. Use
607 * usb_get_string() or usb_string() for USB_DT_STRING.
608 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
609 * are part of the device structure.
610 * In addition to a number of USB-standard descriptors, some
611 * devices also use class-specific or vendor-specific descriptors.
613 * This call is synchronous, and may not be used in an interrupt context.
615 * Returns the number of bytes received on success, or else the status code
616 * returned by the underlying usb_control_msg() call.
618 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
623 memset(buf,0,size); // Make sure we parse really received data
625 for (i = 0; i < 3; ++i) {
626 /* retry on length 0 or stall; some devices are flakey */
627 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
628 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
629 (type << 8) + index, 0, buf, size,
630 USB_CTRL_GET_TIMEOUT);
631 if (result == 0 || result == -EPIPE)
633 if (result > 1 && ((u8 *)buf)[1] != type) {
643 * usb_get_string - gets a string descriptor
644 * @dev: the device whose string descriptor is being retrieved
645 * @langid: code for language chosen (from string descriptor zero)
646 * @index: the number of the descriptor
647 * @buf: where to put the string
648 * @size: how big is "buf"?
649 * Context: !in_interrupt ()
651 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
652 * in little-endian byte order).
653 * The usb_string() function will often be a convenient way to turn
654 * these strings into kernel-printable form.
656 * Strings may be referenced in device, configuration, interface, or other
657 * descriptors, and could also be used in vendor-specific ways.
659 * This call is synchronous, and may not be used in an interrupt context.
661 * Returns the number of bytes received on success, or else the status code
662 * returned by the underlying usb_control_msg() call.
664 static int usb_get_string(struct usb_device *dev, unsigned short langid,
665 unsigned char index, void *buf, int size)
670 for (i = 0; i < 3; ++i) {
671 /* retry on length 0 or stall; some devices are flakey */
672 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
673 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
674 (USB_DT_STRING << 8) + index, langid, buf, size,
675 USB_CTRL_GET_TIMEOUT);
676 if (!(result == 0 || result == -EPIPE))
682 static void usb_try_string_workarounds(unsigned char *buf, int *length)
684 int newlength, oldlength = *length;
686 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
687 if (!isprint(buf[newlength]) || buf[newlength + 1])
696 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
697 unsigned int index, unsigned char *buf)
701 /* Try to read the string descriptor by asking for the maximum
702 * possible number of bytes */
703 rc = usb_get_string(dev, langid, index, buf, 255);
705 /* If that failed try to read the descriptor length, then
706 * ask for just that many bytes */
708 rc = usb_get_string(dev, langid, index, buf, 2);
710 rc = usb_get_string(dev, langid, index, buf, buf[0]);
714 if (!buf[0] && !buf[1])
715 usb_try_string_workarounds(buf, &rc);
717 /* There might be extra junk at the end of the descriptor */
721 rc = rc - (rc & 1); /* force a multiple of two */
725 rc = (rc < 0 ? rc : -EINVAL);
731 * usb_string - returns ISO 8859-1 version of a string descriptor
732 * @dev: the device whose string descriptor is being retrieved
733 * @index: the number of the descriptor
734 * @buf: where to put the string
735 * @size: how big is "buf"?
736 * Context: !in_interrupt ()
738 * This converts the UTF-16LE encoded strings returned by devices, from
739 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
740 * that are more usable in most kernel contexts. Note that all characters
741 * in the chosen descriptor that can't be encoded using ISO-8859-1
742 * are converted to the question mark ("?") character, and this function
743 * chooses strings in the first language supported by the device.
745 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
746 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
747 * and is appropriate for use many uses of English and several other
748 * Western European languages. (But it doesn't include the "Euro" symbol.)
750 * This call is synchronous, and may not be used in an interrupt context.
752 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
754 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
760 if (dev->state == USB_STATE_SUSPENDED)
761 return -EHOSTUNREACH;
762 if (size <= 0 || !buf || !index)
765 tbuf = kmalloc(256, GFP_KERNEL);
769 /* get langid for strings if it's not yet known */
770 if (!dev->have_langid) {
771 err = usb_string_sub(dev, 0, 0, tbuf);
774 "string descriptor 0 read error: %d\n",
777 } else if (err < 4) {
778 dev_err (&dev->dev, "string descriptor 0 too short\n");
782 dev->have_langid = -1;
783 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
784 /* always use the first langid listed */
785 dev_dbg (&dev->dev, "default language 0x%04x\n",
790 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
794 size--; /* leave room for trailing NULL char in output buffer */
795 for (idx = 0, u = 2; u < err; u += 2) {
798 if (tbuf[u+1]) /* high byte */
799 buf[idx++] = '?'; /* non ISO-8859-1 character */
801 buf[idx++] = tbuf[u];
806 if (tbuf[1] != USB_DT_STRING)
807 dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
815 * usb_cache_string - read a string descriptor and cache it for later use
816 * @udev: the device whose string descriptor is being read
817 * @index: the descriptor index
819 * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
820 * or NULL if the index is 0 or the string could not be read.
822 char *usb_cache_string(struct usb_device *udev, int index)
825 char *smallbuf = NULL;
828 if (index > 0 && (buf = kmalloc(256, GFP_KERNEL)) != NULL) {
829 if ((len = usb_string(udev, index, buf, 256)) > 0) {
830 if ((smallbuf = kmalloc(++len, GFP_KERNEL)) == NULL)
832 memcpy(smallbuf, buf, len);
840 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
841 * @dev: the device whose device descriptor is being updated
842 * @size: how much of the descriptor to read
843 * Context: !in_interrupt ()
845 * Updates the copy of the device descriptor stored in the device structure,
846 * which dedicates space for this purpose. Note that several fields are
847 * converted to the host CPU's byte order: the USB version (bcdUSB), and
848 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
849 * That lets device drivers compare against non-byteswapped constants.
851 * Not exported, only for use by the core. If drivers really want to read
852 * the device descriptor directly, they can call usb_get_descriptor() with
853 * type = USB_DT_DEVICE and index = 0.
855 * This call is synchronous, and may not be used in an interrupt context.
857 * Returns the number of bytes received on success, or else the status code
858 * returned by the underlying usb_control_msg() call.
860 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
862 struct usb_device_descriptor *desc;
865 if (size > sizeof(*desc))
867 desc = kmalloc(sizeof(*desc), GFP_NOIO);
871 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
873 memcpy(&dev->descriptor, desc, size);
879 * usb_get_status - issues a GET_STATUS call
880 * @dev: the device whose status is being checked
881 * @type: USB_RECIP_*; for device, interface, or endpoint
882 * @target: zero (for device), else interface or endpoint number
883 * @data: pointer to two bytes of bitmap data
884 * Context: !in_interrupt ()
886 * Returns device, interface, or endpoint status. Normally only of
887 * interest to see if the device is self powered, or has enabled the
888 * remote wakeup facility; or whether a bulk or interrupt endpoint
889 * is halted ("stalled").
891 * Bits in these status bitmaps are set using the SET_FEATURE request,
892 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
893 * function should be used to clear halt ("stall") status.
895 * This call is synchronous, and may not be used in an interrupt context.
897 * Returns the number of bytes received on success, or else the status code
898 * returned by the underlying usb_control_msg() call.
900 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
903 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
908 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
909 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
910 sizeof(*status), USB_CTRL_GET_TIMEOUT);
912 *(u16 *)data = *status;
918 * usb_clear_halt - tells device to clear endpoint halt/stall condition
919 * @dev: device whose endpoint is halted
920 * @pipe: endpoint "pipe" being cleared
921 * Context: !in_interrupt ()
923 * This is used to clear halt conditions for bulk and interrupt endpoints,
924 * as reported by URB completion status. Endpoints that are halted are
925 * sometimes referred to as being "stalled". Such endpoints are unable
926 * to transmit or receive data until the halt status is cleared. Any URBs
927 * queued for such an endpoint should normally be unlinked by the driver
928 * before clearing the halt condition, as described in sections 5.7.5
929 * and 5.8.5 of the USB 2.0 spec.
931 * Note that control and isochronous endpoints don't halt, although control
932 * endpoints report "protocol stall" (for unsupported requests) using the
933 * same status code used to report a true stall.
935 * This call is synchronous, and may not be used in an interrupt context.
937 * Returns zero on success, or else the status code returned by the
938 * underlying usb_control_msg() call.
940 int usb_clear_halt(struct usb_device *dev, int pipe)
943 int endp = usb_pipeendpoint(pipe);
945 if (usb_pipein (pipe))
948 /* we don't care if it wasn't halted first. in fact some devices
949 * (like some ibmcam model 1 units) seem to expect hosts to make
950 * this request for iso endpoints, which can't halt!
952 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
953 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
954 USB_ENDPOINT_HALT, endp, NULL, 0,
955 USB_CTRL_SET_TIMEOUT);
957 /* don't un-halt or force to DATA0 except on success */
961 /* NOTE: seems like Microsoft and Apple don't bother verifying
962 * the clear "took", so some devices could lock up if you check...
963 * such as the Hagiwara FlashGate DUAL. So we won't bother.
965 * NOTE: make sure the logic here doesn't diverge much from
966 * the copy in usb-storage, for as long as we need two copies.
969 /* toggle was reset by the clear */
970 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
976 * usb_disable_endpoint -- Disable an endpoint by address
977 * @dev: the device whose endpoint is being disabled
978 * @epaddr: the endpoint's address. Endpoint number for output,
979 * endpoint number + USB_DIR_IN for input
981 * Deallocates hcd/hardware state for this endpoint ... and nukes all
984 * If the HCD hasn't registered a disable() function, this sets the
985 * endpoint's maxpacket size to 0 to prevent further submissions.
987 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
989 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
990 struct usb_host_endpoint *ep;
995 if (usb_endpoint_out(epaddr)) {
996 ep = dev->ep_out[epnum];
997 dev->ep_out[epnum] = NULL;
999 ep = dev->ep_in[epnum];
1000 dev->ep_in[epnum] = NULL;
1002 if (ep && dev->bus && dev->bus->op && dev->bus->op->disable)
1003 dev->bus->op->disable(dev, ep);
1007 * usb_disable_interface -- Disable all endpoints for an interface
1008 * @dev: the device whose interface is being disabled
1009 * @intf: pointer to the interface descriptor
1011 * Disables all the endpoints for the interface's current altsetting.
1013 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
1015 struct usb_host_interface *alt = intf->cur_altsetting;
1018 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1019 usb_disable_endpoint(dev,
1020 alt->endpoint[i].desc.bEndpointAddress);
1025 * usb_disable_device - Disable all the endpoints for a USB device
1026 * @dev: the device whose endpoints are being disabled
1027 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1029 * Disables all the device's endpoints, potentially including endpoint 0.
1030 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1031 * pending urbs) and usbcore state for the interfaces, so that usbcore
1032 * must usb_set_configuration() before any interfaces could be used.
1034 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1038 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
1039 skip_ep0 ? "non-ep0" : "all");
1040 for (i = skip_ep0; i < 16; ++i) {
1041 usb_disable_endpoint(dev, i);
1042 usb_disable_endpoint(dev, i + USB_DIR_IN);
1044 dev->toggle[0] = dev->toggle[1] = 0;
1046 /* getting rid of interfaces will disconnect
1047 * any drivers bound to them (a key side effect)
1049 if (dev->actconfig) {
1050 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1051 struct usb_interface *interface;
1053 /* remove this interface if it has been registered */
1054 interface = dev->actconfig->interface[i];
1055 if (!device_is_registered(&interface->dev))
1057 dev_dbg (&dev->dev, "unregistering interface %s\n",
1058 interface->dev.bus_id);
1059 usb_remove_sysfs_intf_files(interface);
1060 device_del (&interface->dev);
1063 /* Now that the interfaces are unbound, nobody should
1064 * try to access them.
1066 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1067 put_device (&dev->actconfig->interface[i]->dev);
1068 dev->actconfig->interface[i] = NULL;
1070 dev->actconfig = NULL;
1071 if (dev->state == USB_STATE_CONFIGURED)
1072 usb_set_device_state(dev, USB_STATE_ADDRESS);
1078 * usb_enable_endpoint - Enable an endpoint for USB communications
1079 * @dev: the device whose interface is being enabled
1082 * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
1083 * For control endpoints, both the input and output sides are handled.
1086 usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
1088 unsigned int epaddr = ep->desc.bEndpointAddress;
1089 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1092 is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1093 == USB_ENDPOINT_XFER_CONTROL);
1094 if (usb_endpoint_out(epaddr) || is_control) {
1095 usb_settoggle(dev, epnum, 1, 0);
1096 dev->ep_out[epnum] = ep;
1098 if (!usb_endpoint_out(epaddr) || is_control) {
1099 usb_settoggle(dev, epnum, 0, 0);
1100 dev->ep_in[epnum] = ep;
1105 * usb_enable_interface - Enable all the endpoints for an interface
1106 * @dev: the device whose interface is being enabled
1107 * @intf: pointer to the interface descriptor
1109 * Enables all the endpoints for the interface's current altsetting.
1111 static void usb_enable_interface(struct usb_device *dev,
1112 struct usb_interface *intf)
1114 struct usb_host_interface *alt = intf->cur_altsetting;
1117 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1118 usb_enable_endpoint(dev, &alt->endpoint[i]);
1122 * usb_set_interface - Makes a particular alternate setting be current
1123 * @dev: the device whose interface is being updated
1124 * @interface: the interface being updated
1125 * @alternate: the setting being chosen.
1126 * Context: !in_interrupt ()
1128 * This is used to enable data transfers on interfaces that may not
1129 * be enabled by default. Not all devices support such configurability.
1130 * Only the driver bound to an interface may change its setting.
1132 * Within any given configuration, each interface may have several
1133 * alternative settings. These are often used to control levels of
1134 * bandwidth consumption. For example, the default setting for a high
1135 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1136 * while interrupt transfers of up to 3KBytes per microframe are legal.
1137 * Also, isochronous endpoints may never be part of an
1138 * interface's default setting. To access such bandwidth, alternate
1139 * interface settings must be made current.
1141 * Note that in the Linux USB subsystem, bandwidth associated with
1142 * an endpoint in a given alternate setting is not reserved until an URB
1143 * is submitted that needs that bandwidth. Some other operating systems
1144 * allocate bandwidth early, when a configuration is chosen.
1146 * This call is synchronous, and may not be used in an interrupt context.
1147 * Also, drivers must not change altsettings while urbs are scheduled for
1148 * endpoints in that interface; all such urbs must first be completed
1149 * (perhaps forced by unlinking).
1151 * Returns zero on success, or else the status code returned by the
1152 * underlying usb_control_msg() call.
1154 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1156 struct usb_interface *iface;
1157 struct usb_host_interface *alt;
1161 if (dev->state == USB_STATE_SUSPENDED)
1162 return -EHOSTUNREACH;
1164 iface = usb_ifnum_to_if(dev, interface);
1166 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1171 alt = usb_altnum_to_altsetting(iface, alternate);
1173 warn("selecting invalid altsetting %d", alternate);
1177 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1178 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1179 alternate, interface, NULL, 0, 5000);
1181 /* 9.4.10 says devices don't need this and are free to STALL the
1182 * request if the interface only has one alternate setting.
1184 if (ret == -EPIPE && iface->num_altsetting == 1) {
1186 "manual set_interface for iface %d, alt %d\n",
1187 interface, alternate);
1192 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1193 * when they implement async or easily-killable versions of this or
1194 * other "should-be-internal" functions (like clear_halt).
1195 * should hcd+usbcore postprocess control requests?
1198 /* prevent submissions using previous endpoint settings */
1199 if (device_is_registered(&iface->dev))
1200 usb_remove_sysfs_intf_files(iface);
1201 usb_disable_interface(dev, iface);
1203 iface->cur_altsetting = alt;
1205 /* If the interface only has one altsetting and the device didn't
1206 * accept the request, we attempt to carry out the equivalent action
1207 * by manually clearing the HALT feature for each endpoint in the
1213 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1214 unsigned int epaddr =
1215 alt->endpoint[i].desc.bEndpointAddress;
1217 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
1218 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1220 usb_clear_halt(dev, pipe);
1224 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1227 * Despite EP0 is always present in all interfaces/AS, the list of
1228 * endpoints from the descriptor does not contain EP0. Due to its
1229 * omnipresence one might expect EP0 being considered "affected" by
1230 * any SetInterface request and hence assume toggles need to be reset.
1231 * However, EP0 toggles are re-synced for every individual transfer
1232 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1233 * (Likewise, EP0 never "halts" on well designed devices.)
1235 usb_enable_interface(dev, iface);
1236 if (device_is_registered(&iface->dev))
1237 usb_create_sysfs_intf_files(iface);
1243 * usb_reset_configuration - lightweight device reset
1244 * @dev: the device whose configuration is being reset
1246 * This issues a standard SET_CONFIGURATION request to the device using
1247 * the current configuration. The effect is to reset most USB-related
1248 * state in the device, including interface altsettings (reset to zero),
1249 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1250 * endpoints). Other usbcore state is unchanged, including bindings of
1251 * usb device drivers to interfaces.
1253 * Because this affects multiple interfaces, avoid using this with composite
1254 * (multi-interface) devices. Instead, the driver for each interface may
1255 * use usb_set_interface() on the interfaces it claims. Be careful though;
1256 * some devices don't support the SET_INTERFACE request, and others won't
1257 * reset all the interface state (notably data toggles). Resetting the whole
1258 * configuration would affect other drivers' interfaces.
1260 * The caller must own the device lock.
1262 * Returns zero on success, else a negative error code.
1264 int usb_reset_configuration(struct usb_device *dev)
1267 struct usb_host_config *config;
1269 if (dev->state == USB_STATE_SUSPENDED)
1270 return -EHOSTUNREACH;
1272 /* caller must have locked the device and must own
1273 * the usb bus readlock (so driver bindings are stable);
1274 * calls during probe() are fine
1277 for (i = 1; i < 16; ++i) {
1278 usb_disable_endpoint(dev, i);
1279 usb_disable_endpoint(dev, i + USB_DIR_IN);
1282 config = dev->actconfig;
1283 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1284 USB_REQ_SET_CONFIGURATION, 0,
1285 config->desc.bConfigurationValue, 0,
1286 NULL, 0, USB_CTRL_SET_TIMEOUT);
1290 dev->toggle[0] = dev->toggle[1] = 0;
1292 /* re-init hc/hcd interface/endpoint state */
1293 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1294 struct usb_interface *intf = config->interface[i];
1295 struct usb_host_interface *alt;
1297 if (device_is_registered(&intf->dev))
1298 usb_remove_sysfs_intf_files(intf);
1299 alt = usb_altnum_to_altsetting(intf, 0);
1301 /* No altsetting 0? We'll assume the first altsetting.
1302 * We could use a GetInterface call, but if a device is
1303 * so non-compliant that it doesn't have altsetting 0
1304 * then I wouldn't trust its reply anyway.
1307 alt = &intf->altsetting[0];
1309 intf->cur_altsetting = alt;
1310 usb_enable_interface(dev, intf);
1311 if (device_is_registered(&intf->dev))
1312 usb_create_sysfs_intf_files(intf);
1317 static void release_interface(struct device *dev)
1319 struct usb_interface *intf = to_usb_interface(dev);
1320 struct usb_interface_cache *intfc =
1321 altsetting_to_usb_interface_cache(intf->altsetting);
1323 kref_put(&intfc->ref, usb_release_interface_cache);
1328 * usb_set_configuration - Makes a particular device setting be current
1329 * @dev: the device whose configuration is being updated
1330 * @configuration: the configuration being chosen.
1331 * Context: !in_interrupt(), caller owns the device lock
1333 * This is used to enable non-default device modes. Not all devices
1334 * use this kind of configurability; many devices only have one
1337 * USB device configurations may affect Linux interoperability,
1338 * power consumption and the functionality available. For example,
1339 * the default configuration is limited to using 100mA of bus power,
1340 * so that when certain device functionality requires more power,
1341 * and the device is bus powered, that functionality should be in some
1342 * non-default device configuration. Other device modes may also be
1343 * reflected as configuration options, such as whether two ISDN
1344 * channels are available independently; and choosing between open
1345 * standard device protocols (like CDC) or proprietary ones.
1347 * Note that USB has an additional level of device configurability,
1348 * associated with interfaces. That configurability is accessed using
1349 * usb_set_interface().
1351 * This call is synchronous. The calling context must be able to sleep,
1352 * must own the device lock, and must not hold the driver model's USB
1353 * bus rwsem; usb device driver probe() methods cannot use this routine.
1355 * Returns zero on success, or else the status code returned by the
1356 * underlying call that failed. On successful completion, each interface
1357 * in the original device configuration has been destroyed, and each one
1358 * in the new configuration has been probed by all relevant usb device
1359 * drivers currently known to the kernel.
1361 int usb_set_configuration(struct usb_device *dev, int configuration)
1364 struct usb_host_config *cp = NULL;
1365 struct usb_interface **new_interfaces = NULL;
1368 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1369 if (dev->config[i].desc.bConfigurationValue == configuration) {
1370 cp = &dev->config[i];
1374 if ((!cp && configuration != 0))
1377 /* The USB spec says configuration 0 means unconfigured.
1378 * But if a device includes a configuration numbered 0,
1379 * we will accept it as a correctly configured state.
1381 if (cp && configuration == 0)
1382 dev_warn(&dev->dev, "config 0 descriptor??\n");
1384 if (dev->state == USB_STATE_SUSPENDED)
1385 return -EHOSTUNREACH;
1387 /* Allocate memory for new interfaces before doing anything else,
1388 * so that if we run out then nothing will have changed. */
1391 nintf = cp->desc.bNumInterfaces;
1392 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1394 if (!new_interfaces) {
1395 dev_err(&dev->dev, "Out of memory");
1399 for (; n < nintf; ++n) {
1400 new_interfaces[n] = kzalloc(
1401 sizeof(struct usb_interface),
1403 if (!new_interfaces[n]) {
1404 dev_err(&dev->dev, "Out of memory");
1408 kfree(new_interfaces[n]);
1409 kfree(new_interfaces);
1414 i = dev->bus_mA - cp->desc.bMaxPower * 2;
1416 dev_warn(&dev->dev, "new config #%d exceeds power "
1421 /* if it's already configured, clear out old state first.
1422 * getting rid of old interfaces means unbinding their drivers.
1424 if (dev->state != USB_STATE_ADDRESS)
1425 usb_disable_device (dev, 1); // Skip ep0
1427 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1428 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1429 NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0) {
1431 /* All the old state is gone, so what else can we do?
1432 * The device is probably useless now anyway.
1437 dev->actconfig = cp;
1439 usb_set_device_state(dev, USB_STATE_ADDRESS);
1440 goto free_interfaces;
1442 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1444 /* Initialize the new interface structures and the
1445 * hc/hcd/usbcore interface/endpoint state.
1447 for (i = 0; i < nintf; ++i) {
1448 struct usb_interface_cache *intfc;
1449 struct usb_interface *intf;
1450 struct usb_host_interface *alt;
1452 cp->interface[i] = intf = new_interfaces[i];
1453 intfc = cp->intf_cache[i];
1454 intf->altsetting = intfc->altsetting;
1455 intf->num_altsetting = intfc->num_altsetting;
1456 kref_get(&intfc->ref);
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.
1466 alt = &intf->altsetting[0];
1468 intf->cur_altsetting = alt;
1469 usb_enable_interface(dev, intf);
1470 intf->dev.parent = &dev->dev;
1471 intf->dev.driver = NULL;
1472 intf->dev.bus = &usb_bus_type;
1473 intf->dev.dma_mask = dev->dev.dma_mask;
1474 intf->dev.release = release_interface;
1475 device_initialize (&intf->dev);
1476 mark_quiesced(intf);
1477 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1478 dev->bus->busnum, dev->devpath,
1479 configuration, alt->desc.bInterfaceNumber);
1481 kfree(new_interfaces);
1483 if (cp->string == NULL)
1484 cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
1486 /* Now that all the interfaces are set up, register them
1487 * to trigger binding of drivers to interfaces. probe()
1488 * routines may install different altsettings and may
1489 * claim() any interfaces not yet bound. Many class drivers
1490 * need that: CDC, audio, video, etc.
1492 for (i = 0; i < nintf; ++i) {
1493 struct usb_interface *intf = cp->interface[i];
1496 "adding %s (config #%d, interface %d)\n",
1497 intf->dev.bus_id, configuration,
1498 intf->cur_altsetting->desc.bInterfaceNumber);
1499 ret = device_add (&intf->dev);
1501 dev_err(&dev->dev, "device_add(%s) --> %d\n",
1502 intf->dev.bus_id, ret);
1505 usb_create_sysfs_intf_files (intf);
1511 // synchronous request completion model
1512 EXPORT_SYMBOL(usb_control_msg);
1513 EXPORT_SYMBOL(usb_bulk_msg);
1515 EXPORT_SYMBOL(usb_sg_init);
1516 EXPORT_SYMBOL(usb_sg_cancel);
1517 EXPORT_SYMBOL(usb_sg_wait);
1519 // synchronous control message convenience routines
1520 EXPORT_SYMBOL(usb_get_descriptor);
1521 EXPORT_SYMBOL(usb_get_status);
1522 EXPORT_SYMBOL(usb_string);
1524 // synchronous calls that also maintain usbcore state
1525 EXPORT_SYMBOL(usb_clear_halt);
1526 EXPORT_SYMBOL(usb_reset_configuration);
1527 EXPORT_SYMBOL(usb_set_interface);