2 * message.c - synchronous message handling
5 #include <linux/config.h>
7 #ifdef CONFIG_USB_DEBUG
13 #include <linux/pci.h> /* for scatterlist macros */
14 #include <linux/usb.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/init.h>
19 #include <linux/timer.h>
20 #include <linux/ctype.h>
21 #include <linux/device.h>
22 #include <asm/byteorder.h>
24 #include "hcd.h" /* for usbcore internals */
27 static void usb_api_blocking_completion(struct urb *urb, struct pt_regs *regs)
29 complete((struct completion *)urb->context);
33 static void timeout_kill(unsigned long data)
35 struct urb *urb = (struct urb *) data;
40 // Starts urb and waits for completion or timeout
41 // note that this call is NOT interruptible, while
42 // many device driver i/o requests should be interruptible
43 static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
45 struct completion done;
46 struct timer_list timer;
49 init_completion(&done);
51 urb->transfer_flags |= URB_ASYNC_UNLINK;
52 urb->actual_length = 0;
53 status = usb_submit_urb(urb, GFP_NOIO);
58 timer.expires = jiffies + timeout;
59 timer.data = (unsigned long)urb;
60 timer.function = timeout_kill;
61 /* grr. timeout _should_ include submit delays. */
64 wait_for_completion(&done);
66 /* note: HCDs return ETIMEDOUT for other reasons too */
67 if (status == -ECONNRESET) {
68 dev_warn(&urb->dev->dev,
69 "%s timed out on ep%d%s\n",
71 usb_pipeendpoint(urb->pipe),
72 usb_pipein(urb->pipe) ? "in" : "out");
76 del_timer_sync(&timer);
80 *actual_length = urb->actual_length;
85 /*-------------------------------------------------------------------*/
86 // returns status (negative) or length (positive)
87 int usb_internal_control_msg(struct usb_device *usb_dev, unsigned int pipe,
88 struct usb_ctrlrequest *cmd, 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 jiffies 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_bulk_msg - Builds a bulk 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 jiffies 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 bulk message to a specified endpoint
171 * and waits for the message to complete, or timeout.
173 * If successful, it returns 0, otherwise a negative error number.
174 * The number of actual bytes transferred will be stored in the
175 * actual_length paramater.
177 * Don't use this function from within an interrupt context, like a
178 * bottom half handler. If you need an asynchronous message, or need to
179 * send a message from within interrupt context, use usb_submit_urb()
180 * If a thread in your driver uses this call, make sure your disconnect()
181 * method can wait for it to complete. Since you don't have a handle on
182 * the URB used, you can't cancel the request.
184 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
185 void *data, int len, int *actual_length, int timeout)
192 urb=usb_alloc_urb(0, GFP_KERNEL);
196 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
197 usb_api_blocking_completion, NULL);
199 return usb_start_wait_urb(urb,timeout,actual_length);
202 /*-------------------------------------------------------------------*/
204 static void sg_clean (struct usb_sg_request *io)
207 while (io->entries--)
208 usb_free_urb (io->urbs [io->entries]);
212 if (io->dev->dev.dma_mask != NULL)
213 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
217 static void sg_complete (struct urb *urb, struct pt_regs *regs)
219 struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
221 spin_lock (&io->lock);
223 /* In 2.5 we require hcds' endpoint queues not to progress after fault
224 * reports, until the completion callback (this!) returns. That lets
225 * device driver code (like this routine) unlink queued urbs first,
226 * if it needs to, since the HC won't work on them at all. So it's
227 * not possible for page N+1 to overwrite page N, and so on.
229 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
230 * complete before the HCD can get requests away from hardware,
231 * though never during cleanup after a hard fault.
234 && (io->status != -ECONNRESET
235 || urb->status != -ECONNRESET)
236 && urb->actual_length) {
237 dev_err (io->dev->bus->controller,
238 "dev %s ep%d%s scatterlist error %d/%d\n",
240 usb_pipeendpoint (urb->pipe),
241 usb_pipein (urb->pipe) ? "in" : "out",
242 urb->status, io->status);
246 if (io->status == 0 && urb->status && urb->status != -ECONNRESET) {
247 int i, found, status;
249 io->status = urb->status;
251 /* the previous urbs, and this one, completed already.
252 * unlink pending urbs so they won't rx/tx bad data.
253 * careful: unlink can sometimes be synchronous...
255 spin_unlock (&io->lock);
256 for (i = 0, found = 0; i < io->entries; i++) {
257 if (!io->urbs [i] || !io->urbs [i]->dev)
260 status = usb_unlink_urb (io->urbs [i]);
261 if (status != -EINPROGRESS && status != -EBUSY)
262 dev_err (&io->dev->dev,
263 "%s, unlink --> %d\n",
264 __FUNCTION__, status);
265 } else if (urb == io->urbs [i])
268 spin_lock (&io->lock);
272 /* on the last completion, signal usb_sg_wait() */
273 io->bytes += urb->actual_length;
276 complete (&io->complete);
278 spin_unlock (&io->lock);
283 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
284 * @io: request block being initialized. until usb_sg_wait() returns,
285 * treat this as a pointer to an opaque block of memory,
286 * @dev: the usb device that will send or receive the data
287 * @pipe: endpoint "pipe" used to transfer the data
288 * @period: polling rate for interrupt endpoints, in frames or
289 * (for high speed endpoints) microframes; ignored for bulk
290 * @sg: scatterlist entries
291 * @nents: how many entries in the scatterlist
292 * @length: how many bytes to send from the scatterlist, or zero to
293 * send every byte identified in the list.
294 * @mem_flags: SLAB_* flags affecting memory allocations in this call
296 * Returns zero for success, else a negative errno value. This initializes a
297 * scatter/gather request, allocating resources such as I/O mappings and urb
298 * memory (except maybe memory used by USB controller drivers).
300 * The request must be issued using usb_sg_wait(), which waits for the I/O to
301 * complete (or to be canceled) and then cleans up all resources allocated by
304 * The request may be canceled with usb_sg_cancel(), either before or after
305 * usb_sg_wait() is called.
308 struct usb_sg_request *io,
309 struct usb_device *dev,
312 struct scatterlist *sg,
322 if (!io || !dev || !sg
323 || usb_pipecontrol (pipe)
324 || usb_pipeisoc (pipe)
328 spin_lock_init (&io->lock);
334 /* not all host controllers use DMA (like the mainstream pci ones);
335 * they can use PIO (sl811) or be software over another transport.
337 dma = (dev->dev.dma_mask != NULL);
339 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
343 /* initialize all the urbs we'll use */
344 if (io->entries <= 0)
347 io->count = io->entries;
348 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
352 urb_flags = URB_ASYNC_UNLINK | URB_NO_TRANSFER_DMA_MAP
354 if (usb_pipein (pipe))
355 urb_flags |= URB_SHORT_NOT_OK;
357 for (i = 0; i < io->entries; i++) {
360 io->urbs [i] = usb_alloc_urb (0, mem_flags);
366 io->urbs [i]->dev = NULL;
367 io->urbs [i]->pipe = pipe;
368 io->urbs [i]->interval = period;
369 io->urbs [i]->transfer_flags = urb_flags;
371 io->urbs [i]->complete = sg_complete;
372 io->urbs [i]->context = io;
373 io->urbs [i]->status = -EINPROGRESS;
374 io->urbs [i]->actual_length = 0;
377 /* hc may use _only_ transfer_dma */
378 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
379 len = sg_dma_len (sg + i);
381 /* hc may use _only_ transfer_buffer */
382 io->urbs [i]->transfer_buffer =
383 page_address (sg [i].page) + sg [i].offset;
388 len = min_t (unsigned, len, length);
393 io->urbs [i]->transfer_buffer_length = len;
395 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
397 /* transaction state */
400 init_completion (&io->complete);
410 * usb_sg_wait - synchronously execute scatter/gather request
411 * @io: request block handle, as initialized with usb_sg_init().
412 * some fields become accessible when this call returns.
413 * Context: !in_interrupt ()
415 * This function blocks until the specified I/O operation completes. It
416 * leverages the grouping of the related I/O requests to get good transfer
417 * rates, by queueing the requests. At higher speeds, such queuing can
418 * significantly improve USB throughput.
420 * There are three kinds of completion for this function.
421 * (1) success, where io->status is zero. The number of io->bytes
422 * transferred is as requested.
423 * (2) error, where io->status is a negative errno value. The number
424 * of io->bytes transferred before the error is usually less
425 * than requested, and can be nonzero.
426 * (3) cancelation, a type of error with status -ECONNRESET that
427 * is initiated by usb_sg_cancel().
429 * When this function returns, all memory allocated through usb_sg_init() or
430 * this call will have been freed. The request block parameter may still be
431 * passed to usb_sg_cancel(), or it may be freed. It could also be
432 * reinitialized and then reused.
434 * Data Transfer Rates:
436 * Bulk transfers are valid for full or high speed endpoints.
437 * The best full speed data rate is 19 packets of 64 bytes each
438 * per frame, or 1216 bytes per millisecond.
439 * The best high speed data rate is 13 packets of 512 bytes each
440 * per microframe, or 52 KBytes per millisecond.
442 * The reason to use interrupt transfers through this API would most likely
443 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
444 * could be transferred. That capability is less useful for low or full
445 * speed interrupt endpoints, which allow at most one packet per millisecond,
446 * of at most 8 or 64 bytes (respectively).
448 void usb_sg_wait (struct usb_sg_request *io)
450 int i, entries = io->entries;
452 /* queue the urbs. */
453 spin_lock_irq (&io->lock);
454 for (i = 0; i < entries && !io->status; i++) {
457 io->urbs [i]->dev = io->dev;
458 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
460 /* after we submit, let completions or cancelations fire;
461 * we handshake using io->status.
463 spin_unlock_irq (&io->lock);
465 /* maybe we retrying will recover */
466 case -ENXIO: // hc didn't queue this one
469 io->urbs[i]->dev = NULL;
475 /* no error? continue immediately.
477 * NOTE: to work better with UHCI (4K I/O buffer may
478 * need 3K of TDs) it may be good to limit how many
479 * URBs are queued at once; N milliseconds?
485 /* fail any uncompleted urbs */
487 io->urbs [i]->dev = NULL;
488 io->urbs [i]->status = retval;
489 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
490 __FUNCTION__, retval);
493 spin_lock_irq (&io->lock);
494 if (retval && (io->status == 0 || io->status == -ECONNRESET))
497 io->count -= entries - i;
499 complete (&io->complete);
500 spin_unlock_irq (&io->lock);
502 /* OK, yes, this could be packaged as non-blocking.
503 * So could the submit loop above ... but it's easier to
504 * solve neither problem than to solve both!
506 wait_for_completion (&io->complete);
512 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
513 * @io: request block, initialized with usb_sg_init()
515 * This stops a request after it has been started by usb_sg_wait().
516 * It can also prevents one initialized by usb_sg_init() from starting,
517 * so that call just frees resources allocated to the request.
519 void usb_sg_cancel (struct usb_sg_request *io)
523 spin_lock_irqsave (&io->lock, flags);
525 /* shut everything down, if it didn't already */
529 io->status = -ECONNRESET;
530 spin_unlock (&io->lock);
531 for (i = 0; i < io->entries; i++) {
534 if (!io->urbs [i]->dev)
536 retval = usb_unlink_urb (io->urbs [i]);
537 if (retval != -EINPROGRESS && retval != -EBUSY)
538 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
539 __FUNCTION__, retval);
541 spin_lock (&io->lock);
543 spin_unlock_irqrestore (&io->lock, flags);
546 /*-------------------------------------------------------------------*/
549 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
550 * @dev: the device whose descriptor is being retrieved
551 * @type: the descriptor type (USB_DT_*)
552 * @index: the number of the descriptor
553 * @buf: where to put the descriptor
554 * @size: how big is "buf"?
555 * Context: !in_interrupt ()
557 * Gets a USB descriptor. Convenience functions exist to simplify
558 * getting some types of descriptors. Use
559 * usb_get_string() or usb_string() for USB_DT_STRING.
560 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
561 * are part of the device structure.
562 * In addition to a number of USB-standard descriptors, some
563 * devices also use class-specific or vendor-specific descriptors.
565 * This call is synchronous, and may not be used in an interrupt context.
567 * Returns the number of bytes received on success, or else the status code
568 * returned by the underlying usb_control_msg() call.
570 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
575 memset(buf,0,size); // Make sure we parse really received data
577 for (i = 0; i < 3; ++i) {
578 /* retry on length 0 or stall; some devices are flakey */
579 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
580 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
581 (type << 8) + index, 0, buf, size,
582 HZ * USB_CTRL_GET_TIMEOUT);
583 if (result == 0 || result == -EPIPE)
585 if (result > 1 && ((u8 *)buf)[1] != type) {
595 * usb_get_string - gets a string descriptor
596 * @dev: the device whose string descriptor is being retrieved
597 * @langid: code for language chosen (from string descriptor zero)
598 * @index: the number of the descriptor
599 * @buf: where to put the string
600 * @size: how big is "buf"?
601 * Context: !in_interrupt ()
603 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
604 * in little-endian byte order).
605 * The usb_string() function will often be a convenient way to turn
606 * these strings into kernel-printable form.
608 * Strings may be referenced in device, configuration, interface, or other
609 * descriptors, and could also be used in vendor-specific ways.
611 * This call is synchronous, and may not be used in an interrupt context.
613 * Returns the number of bytes received on success, or else the status code
614 * returned by the underlying usb_control_msg() call.
616 int usb_get_string(struct usb_device *dev, unsigned short langid,
617 unsigned char index, void *buf, int size)
622 for (i = 0; i < 3; ++i) {
623 /* retry on length 0 or stall; some devices are flakey */
624 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
625 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
626 (USB_DT_STRING << 8) + index, langid, buf, size,
627 HZ * USB_CTRL_GET_TIMEOUT);
628 if (!(result == 0 || result == -EPIPE))
634 static void usb_try_string_workarounds(unsigned char *buf, int *length)
636 int newlength, oldlength = *length;
638 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
639 if (!isprint(buf[newlength]) || buf[newlength + 1])
648 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
649 unsigned int index, unsigned char *buf)
653 /* Try to read the string descriptor by asking for the maximum
654 * possible number of bytes */
655 rc = usb_get_string(dev, langid, index, buf, 255);
657 /* If that failed try to read the descriptor length, then
658 * ask for just that many bytes */
660 rc = usb_get_string(dev, langid, index, buf, 2);
662 rc = usb_get_string(dev, langid, index, buf, buf[0]);
666 if (!buf[0] && !buf[1])
667 usb_try_string_workarounds(buf, &rc);
669 /* There might be extra junk at the end of the descriptor */
673 rc = rc - (rc & 1); /* force a multiple of two */
677 rc = (rc < 0 ? rc : -EINVAL);
683 * usb_string - returns ISO 8859-1 version of a string descriptor
684 * @dev: the device whose string descriptor is being retrieved
685 * @index: the number of the descriptor
686 * @buf: where to put the string
687 * @size: how big is "buf"?
688 * Context: !in_interrupt ()
690 * This converts the UTF-16LE encoded strings returned by devices, from
691 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
692 * that are more usable in most kernel contexts. Note that all characters
693 * in the chosen descriptor that can't be encoded using ISO-8859-1
694 * are converted to the question mark ("?") character, and this function
695 * chooses strings in the first language supported by the device.
697 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
698 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
699 * and is appropriate for use many uses of English and several other
700 * Western European languages. (But it doesn't include the "Euro" symbol.)
702 * This call is synchronous, and may not be used in an interrupt context.
704 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
706 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
712 if (dev->state == USB_STATE_SUSPENDED)
713 return -EHOSTUNREACH;
714 if (size <= 0 || !buf || !index)
717 tbuf = kmalloc(256, GFP_KERNEL);
721 /* get langid for strings if it's not yet known */
722 if (!dev->have_langid) {
723 err = usb_string_sub(dev, 0, 0, tbuf);
726 "string descriptor 0 read error: %d\n",
729 } else if (err < 4) {
730 dev_err (&dev->dev, "string descriptor 0 too short\n");
734 dev->have_langid = -1;
735 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
736 /* always use the first langid listed */
737 dev_dbg (&dev->dev, "default language 0x%04x\n",
742 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
746 size--; /* leave room for trailing NULL char in output buffer */
747 for (idx = 0, u = 2; u < err; u += 2) {
750 if (tbuf[u+1]) /* high byte */
751 buf[idx++] = '?'; /* non ISO-8859-1 character */
753 buf[idx++] = tbuf[u];
758 if (tbuf[1] != USB_DT_STRING)
759 dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
767 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
768 * @dev: the device whose device descriptor is being updated
769 * @size: how much of the descriptor to read
770 * Context: !in_interrupt ()
772 * Updates the copy of the device descriptor stored in the device structure,
773 * which dedicates space for this purpose. Note that several fields are
774 * converted to the host CPU's byte order: the USB version (bcdUSB), and
775 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
776 * That lets device drivers compare against non-byteswapped constants.
778 * Not exported, only for use by the core. If drivers really want to read
779 * the device descriptor directly, they can call usb_get_descriptor() with
780 * type = USB_DT_DEVICE and index = 0.
782 * This call is synchronous, and may not be used in an interrupt context.
784 * Returns the number of bytes received on success, or else the status code
785 * returned by the underlying usb_control_msg() call.
787 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
789 struct usb_device_descriptor *desc;
792 if (size > sizeof(*desc))
794 desc = kmalloc(sizeof(*desc), GFP_NOIO);
798 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
800 memcpy(&dev->descriptor, desc, size);
806 * usb_get_status - issues a GET_STATUS call
807 * @dev: the device whose status is being checked
808 * @type: USB_RECIP_*; for device, interface, or endpoint
809 * @target: zero (for device), else interface or endpoint number
810 * @data: pointer to two bytes of bitmap data
811 * Context: !in_interrupt ()
813 * Returns device, interface, or endpoint status. Normally only of
814 * interest to see if the device is self powered, or has enabled the
815 * remote wakeup facility; or whether a bulk or interrupt endpoint
816 * is halted ("stalled").
818 * Bits in these status bitmaps are set using the SET_FEATURE request,
819 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
820 * function should be used to clear halt ("stall") status.
822 * This call is synchronous, and may not be used in an interrupt context.
824 * Returns the number of bytes received on success, or else the status code
825 * returned by the underlying usb_control_msg() call.
827 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
830 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
835 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
836 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
837 sizeof(*status), HZ * USB_CTRL_GET_TIMEOUT);
839 *(u16 *)data = *status;
845 * usb_clear_halt - tells device to clear endpoint halt/stall condition
846 * @dev: device whose endpoint is halted
847 * @pipe: endpoint "pipe" being cleared
848 * Context: !in_interrupt ()
850 * This is used to clear halt conditions for bulk and interrupt endpoints,
851 * as reported by URB completion status. Endpoints that are halted are
852 * sometimes referred to as being "stalled". Such endpoints are unable
853 * to transmit or receive data until the halt status is cleared. Any URBs
854 * queued for such an endpoint should normally be unlinked by the driver
855 * before clearing the halt condition, as described in sections 5.7.5
856 * and 5.8.5 of the USB 2.0 spec.
858 * Note that control and isochronous endpoints don't halt, although control
859 * endpoints report "protocol stall" (for unsupported requests) using the
860 * same status code used to report a true stall.
862 * This call is synchronous, and may not be used in an interrupt context.
864 * Returns zero on success, or else the status code returned by the
865 * underlying usb_control_msg() call.
867 int usb_clear_halt(struct usb_device *dev, int pipe)
870 int endp = usb_pipeendpoint(pipe);
872 if (usb_pipein (pipe))
875 /* we don't care if it wasn't halted first. in fact some devices
876 * (like some ibmcam model 1 units) seem to expect hosts to make
877 * this request for iso endpoints, which can't halt!
879 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
880 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
881 USB_ENDPOINT_HALT, endp, NULL, 0,
882 HZ * USB_CTRL_SET_TIMEOUT);
884 /* don't un-halt or force to DATA0 except on success */
888 /* NOTE: seems like Microsoft and Apple don't bother verifying
889 * the clear "took", so some devices could lock up if you check...
890 * such as the Hagiwara FlashGate DUAL. So we won't bother.
892 * NOTE: make sure the logic here doesn't diverge much from
893 * the copy in usb-storage, for as long as we need two copies.
896 /* toggle was reset by the clear */
897 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
903 * usb_disable_endpoint -- Disable an endpoint by address
904 * @dev: the device whose endpoint is being disabled
905 * @epaddr: the endpoint's address. Endpoint number for output,
906 * endpoint number + USB_DIR_IN for input
908 * Deallocates hcd/hardware state for this endpoint ... and nukes all
911 * If the HCD hasn't registered a disable() function, this sets the
912 * endpoint's maxpacket size to 0 to prevent further submissions.
914 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
916 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
917 struct usb_host_endpoint *ep;
922 if (usb_endpoint_out(epaddr)) {
923 ep = dev->ep_out[epnum];
924 dev->ep_out[epnum] = NULL;
926 ep = dev->ep_in[epnum];
927 dev->ep_in[epnum] = NULL;
929 if (ep && dev->bus && dev->bus->op && dev->bus->op->disable)
930 dev->bus->op->disable(dev, ep);
934 * usb_disable_interface -- Disable all endpoints for an interface
935 * @dev: the device whose interface is being disabled
936 * @intf: pointer to the interface descriptor
938 * Disables all the endpoints for the interface's current altsetting.
940 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
942 struct usb_host_interface *alt = intf->cur_altsetting;
945 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
946 usb_disable_endpoint(dev,
947 alt->endpoint[i].desc.bEndpointAddress);
952 * usb_disable_device - Disable all the endpoints for a USB device
953 * @dev: the device whose endpoints are being disabled
954 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
956 * Disables all the device's endpoints, potentially including endpoint 0.
957 * Deallocates hcd/hardware state for the endpoints (nuking all or most
958 * pending urbs) and usbcore state for the interfaces, so that usbcore
959 * must usb_set_configuration() before any interfaces could be used.
961 void usb_disable_device(struct usb_device *dev, int skip_ep0)
965 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
966 skip_ep0 ? "non-ep0" : "all");
967 for (i = skip_ep0; i < 16; ++i) {
968 usb_disable_endpoint(dev, i);
969 usb_disable_endpoint(dev, i + USB_DIR_IN);
971 dev->toggle[0] = dev->toggle[1] = 0;
973 /* getting rid of interfaces will disconnect
974 * any drivers bound to them (a key side effect)
976 if (dev->actconfig) {
977 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
978 struct usb_interface *interface;
980 /* remove this interface */
981 interface = dev->actconfig->interface[i];
982 dev_dbg (&dev->dev, "unregistering interface %s\n",
983 interface->dev.bus_id);
984 usb_remove_sysfs_intf_files(interface);
985 device_del (&interface->dev);
988 /* Now that the interfaces are unbound, nobody should
989 * try to access them.
991 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
992 put_device (&dev->actconfig->interface[i]->dev);
993 dev->actconfig->interface[i] = NULL;
995 dev->actconfig = NULL;
996 if (dev->state == USB_STATE_CONFIGURED)
997 usb_set_device_state(dev, USB_STATE_ADDRESS);
1003 * usb_enable_endpoint - Enable an endpoint for USB communications
1004 * @dev: the device whose interface is being enabled
1007 * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
1008 * For control endpoints, both the input and output sides are handled.
1011 usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
1013 unsigned int epaddr = ep->desc.bEndpointAddress;
1014 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1017 is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1018 == USB_ENDPOINT_XFER_CONTROL);
1019 if (usb_endpoint_out(epaddr) || is_control) {
1020 usb_settoggle(dev, epnum, 1, 0);
1021 dev->ep_out[epnum] = ep;
1023 if (!usb_endpoint_out(epaddr) || is_control) {
1024 usb_settoggle(dev, epnum, 0, 0);
1025 dev->ep_in[epnum] = ep;
1030 * usb_enable_interface - Enable all the endpoints for an interface
1031 * @dev: the device whose interface is being enabled
1032 * @intf: pointer to the interface descriptor
1034 * Enables all the endpoints for the interface's current altsetting.
1036 void usb_enable_interface(struct usb_device *dev,
1037 struct usb_interface *intf)
1039 struct usb_host_interface *alt = intf->cur_altsetting;
1042 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1043 usb_enable_endpoint(dev, &alt->endpoint[i]);
1047 * usb_set_interface - Makes a particular alternate setting be current
1048 * @dev: the device whose interface is being updated
1049 * @interface: the interface being updated
1050 * @alternate: the setting being chosen.
1051 * Context: !in_interrupt ()
1053 * This is used to enable data transfers on interfaces that may not
1054 * be enabled by default. Not all devices support such configurability.
1055 * Only the driver bound to an interface may change its setting.
1057 * Within any given configuration, each interface may have several
1058 * alternative settings. These are often used to control levels of
1059 * bandwidth consumption. For example, the default setting for a high
1060 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1061 * while interrupt transfers of up to 3KBytes per microframe are legal.
1062 * Also, isochronous endpoints may never be part of an
1063 * interface's default setting. To access such bandwidth, alternate
1064 * interface settings must be made current.
1066 * Note that in the Linux USB subsystem, bandwidth associated with
1067 * an endpoint in a given alternate setting is not reserved until an URB
1068 * is submitted that needs that bandwidth. Some other operating systems
1069 * allocate bandwidth early, when a configuration is chosen.
1071 * This call is synchronous, and may not be used in an interrupt context.
1072 * Also, drivers must not change altsettings while urbs are scheduled for
1073 * endpoints in that interface; all such urbs must first be completed
1074 * (perhaps forced by unlinking).
1076 * Returns zero on success, or else the status code returned by the
1077 * underlying usb_control_msg() call.
1079 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1081 struct usb_interface *iface;
1082 struct usb_host_interface *alt;
1086 if (dev->state == USB_STATE_SUSPENDED)
1087 return -EHOSTUNREACH;
1089 iface = usb_ifnum_to_if(dev, interface);
1091 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1096 alt = usb_altnum_to_altsetting(iface, alternate);
1098 warn("selecting invalid altsetting %d", alternate);
1102 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1103 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1104 alternate, interface, NULL, 0, HZ * 5);
1106 /* 9.4.10 says devices don't need this and are free to STALL the
1107 * request if the interface only has one alternate setting.
1109 if (ret == -EPIPE && iface->num_altsetting == 1) {
1111 "manual set_interface for iface %d, alt %d\n",
1112 interface, alternate);
1117 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1118 * when they implement async or easily-killable versions of this or
1119 * other "should-be-internal" functions (like clear_halt).
1120 * should hcd+usbcore postprocess control requests?
1123 /* prevent submissions using previous endpoint settings */
1124 usb_disable_interface(dev, iface);
1126 iface->cur_altsetting = alt;
1128 /* If the interface only has one altsetting and the device didn't
1129 * accept the request, we attempt to carry out the equivalent action
1130 * by manually clearing the HALT feature for each endpoint in the
1136 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1137 unsigned int epaddr =
1138 alt->endpoint[i].desc.bEndpointAddress;
1140 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
1141 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1143 usb_clear_halt(dev, pipe);
1147 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1150 * Despite EP0 is always present in all interfaces/AS, the list of
1151 * endpoints from the descriptor does not contain EP0. Due to its
1152 * omnipresence one might expect EP0 being considered "affected" by
1153 * any SetInterface request and hence assume toggles need to be reset.
1154 * However, EP0 toggles are re-synced for every individual transfer
1155 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1156 * (Likewise, EP0 never "halts" on well designed devices.)
1158 usb_enable_interface(dev, iface);
1164 * usb_reset_configuration - lightweight device reset
1165 * @dev: the device whose configuration is being reset
1167 * This issues a standard SET_CONFIGURATION request to the device using
1168 * the current configuration. The effect is to reset most USB-related
1169 * state in the device, including interface altsettings (reset to zero),
1170 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1171 * endpoints). Other usbcore state is unchanged, including bindings of
1172 * usb device drivers to interfaces.
1174 * Because this affects multiple interfaces, avoid using this with composite
1175 * (multi-interface) devices. Instead, the driver for each interface may
1176 * use usb_set_interface() on the interfaces it claims. Resetting the whole
1177 * configuration would affect other drivers' interfaces.
1179 * The caller must own the device lock.
1181 * Returns zero on success, else a negative error code.
1183 int usb_reset_configuration(struct usb_device *dev)
1186 struct usb_host_config *config;
1188 if (dev->state == USB_STATE_SUSPENDED)
1189 return -EHOSTUNREACH;
1191 /* caller must have locked the device and must own
1192 * the usb bus readlock (so driver bindings are stable);
1193 * calls during probe() are fine
1196 for (i = 1; i < 16; ++i) {
1197 usb_disable_endpoint(dev, i);
1198 usb_disable_endpoint(dev, i + USB_DIR_IN);
1201 config = dev->actconfig;
1202 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1203 USB_REQ_SET_CONFIGURATION, 0,
1204 config->desc.bConfigurationValue, 0,
1205 NULL, 0, HZ * USB_CTRL_SET_TIMEOUT);
1207 usb_set_device_state(dev, USB_STATE_ADDRESS);
1211 dev->toggle[0] = dev->toggle[1] = 0;
1213 /* re-init hc/hcd interface/endpoint state */
1214 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1215 struct usb_interface *intf = config->interface[i];
1216 struct usb_host_interface *alt;
1218 alt = usb_altnum_to_altsetting(intf, 0);
1220 /* No altsetting 0? We'll assume the first altsetting.
1221 * We could use a GetInterface call, but if a device is
1222 * so non-compliant that it doesn't have altsetting 0
1223 * then I wouldn't trust its reply anyway.
1226 alt = &intf->altsetting[0];
1228 intf->cur_altsetting = alt;
1229 usb_enable_interface(dev, intf);
1234 static void release_interface(struct device *dev)
1236 struct usb_interface *intf = to_usb_interface(dev);
1237 struct usb_interface_cache *intfc =
1238 altsetting_to_usb_interface_cache(intf->altsetting);
1240 kref_put(&intfc->ref, usb_release_interface_cache);
1245 * usb_set_configuration - Makes a particular device setting be current
1246 * @dev: the device whose configuration is being updated
1247 * @configuration: the configuration being chosen.
1248 * Context: !in_interrupt(), caller owns the device lock
1250 * This is used to enable non-default device modes. Not all devices
1251 * use this kind of configurability; many devices only have one
1254 * USB device configurations may affect Linux interoperability,
1255 * power consumption and the functionality available. For example,
1256 * the default configuration is limited to using 100mA of bus power,
1257 * so that when certain device functionality requires more power,
1258 * and the device is bus powered, that functionality should be in some
1259 * non-default device configuration. Other device modes may also be
1260 * reflected as configuration options, such as whether two ISDN
1261 * channels are available independently; and choosing between open
1262 * standard device protocols (like CDC) or proprietary ones.
1264 * Note that USB has an additional level of device configurability,
1265 * associated with interfaces. That configurability is accessed using
1266 * usb_set_interface().
1268 * This call is synchronous. The calling context must be able to sleep,
1269 * must own the device lock, and must not hold the driver model's USB
1270 * bus rwsem; usb device driver probe() methods cannot use this routine.
1272 * Returns zero on success, or else the status code returned by the
1273 * underlying call that failed. On succesful completion, each interface
1274 * in the original device configuration has been destroyed, and each one
1275 * in the new configuration has been probed by all relevant usb device
1276 * drivers currently known to the kernel.
1278 int usb_set_configuration(struct usb_device *dev, int configuration)
1281 struct usb_host_config *cp = NULL;
1282 struct usb_interface **new_interfaces = NULL;
1285 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1286 if (dev->config[i].desc.bConfigurationValue == configuration) {
1287 cp = &dev->config[i];
1291 if ((!cp && configuration != 0))
1294 /* The USB spec says configuration 0 means unconfigured.
1295 * But if a device includes a configuration numbered 0,
1296 * we will accept it as a correctly configured state.
1298 if (cp && configuration == 0)
1299 dev_warn(&dev->dev, "config 0 descriptor??\n");
1301 if (dev->state == USB_STATE_SUSPENDED)
1302 return -EHOSTUNREACH;
1304 /* Allocate memory for new interfaces before doing anything else,
1305 * so that if we run out then nothing will have changed. */
1308 nintf = cp->desc.bNumInterfaces;
1309 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1311 if (!new_interfaces) {
1312 dev_err(&dev->dev, "Out of memory");
1316 for (; n < nintf; ++n) {
1317 new_interfaces[n] = kmalloc(
1318 sizeof(struct usb_interface),
1320 if (!new_interfaces[n]) {
1321 dev_err(&dev->dev, "Out of memory");
1325 kfree(new_interfaces[n]);
1326 kfree(new_interfaces);
1332 /* if it's already configured, clear out old state first.
1333 * getting rid of old interfaces means unbinding their drivers.
1335 if (dev->state != USB_STATE_ADDRESS)
1336 usb_disable_device (dev, 1); // Skip ep0
1338 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1339 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1340 NULL, 0, HZ * USB_CTRL_SET_TIMEOUT)) < 0)
1341 goto free_interfaces;
1343 dev->actconfig = cp;
1345 usb_set_device_state(dev, USB_STATE_ADDRESS);
1347 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1349 /* Initialize the new interface structures and the
1350 * hc/hcd/usbcore interface/endpoint state.
1352 for (i = 0; i < nintf; ++i) {
1353 struct usb_interface_cache *intfc;
1354 struct usb_interface *intf;
1355 struct usb_host_interface *alt;
1357 cp->interface[i] = intf = new_interfaces[i];
1358 memset(intf, 0, sizeof(*intf));
1359 intfc = cp->intf_cache[i];
1360 intf->altsetting = intfc->altsetting;
1361 intf->num_altsetting = intfc->num_altsetting;
1362 kref_get(&intfc->ref);
1364 alt = usb_altnum_to_altsetting(intf, 0);
1366 /* No altsetting 0? We'll assume the first altsetting.
1367 * We could use a GetInterface call, but if a device is
1368 * so non-compliant that it doesn't have altsetting 0
1369 * then I wouldn't trust its reply anyway.
1372 alt = &intf->altsetting[0];
1374 intf->cur_altsetting = alt;
1375 usb_enable_interface(dev, intf);
1376 intf->dev.parent = &dev->dev;
1377 intf->dev.driver = NULL;
1378 intf->dev.bus = &usb_bus_type;
1379 intf->dev.dma_mask = dev->dev.dma_mask;
1380 intf->dev.release = release_interface;
1381 device_initialize (&intf->dev);
1382 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1383 dev->bus->busnum, dev->devpath,
1385 alt->desc.bInterfaceNumber);
1387 kfree(new_interfaces);
1389 /* Now that all the interfaces are set up, register them
1390 * to trigger binding of drivers to interfaces. probe()
1391 * routines may install different altsettings and may
1392 * claim() any interfaces not yet bound. Many class drivers
1393 * need that: CDC, audio, video, etc.
1395 for (i = 0; i < nintf; ++i) {
1396 struct usb_interface *intf = cp->interface[i];
1397 struct usb_interface_descriptor *desc;
1399 desc = &intf->altsetting [0].desc;
1401 "adding %s (config #%d, interface %d)\n",
1402 intf->dev.bus_id, configuration,
1403 desc->bInterfaceNumber);
1404 ret = device_add (&intf->dev);
1407 "device_add(%s) --> %d\n",
1412 usb_create_sysfs_intf_files (intf);
1419 // synchronous request completion model
1420 EXPORT_SYMBOL(usb_control_msg);
1421 EXPORT_SYMBOL(usb_bulk_msg);
1423 EXPORT_SYMBOL(usb_sg_init);
1424 EXPORT_SYMBOL(usb_sg_cancel);
1425 EXPORT_SYMBOL(usb_sg_wait);
1427 // synchronous control message convenience routines
1428 EXPORT_SYMBOL(usb_get_descriptor);
1429 EXPORT_SYMBOL(usb_get_status);
1430 EXPORT_SYMBOL(usb_get_string);
1431 EXPORT_SYMBOL(usb_string);
1433 // synchronous calls that also maintain usbcore state
1434 EXPORT_SYMBOL(usb_clear_halt);
1435 EXPORT_SYMBOL(usb_reset_configuration);
1436 EXPORT_SYMBOL(usb_set_interface);