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 <asm/byteorder.h>
22 #include "hcd.h" /* for usbcore internals */
25 static void usb_api_blocking_completion(struct urb *urb, struct pt_regs *regs)
27 complete((struct completion *)urb->context);
31 static void timeout_kill(unsigned long data)
33 struct urb *urb = (struct urb *) data;
35 dev_warn(&urb->dev->dev, "%s timeout on ep%d%s\n",
36 usb_pipecontrol(urb->pipe) ? "control" : "bulk",
37 usb_pipeendpoint(urb->pipe),
38 usb_pipein(urb->pipe) ? "in" : "out");
42 // Starts urb and waits for completion or timeout
43 // note that this call is NOT interruptible, while
44 // many device driver i/o requests should be interruptible
45 static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
47 struct completion done;
48 struct timer_list timer;
51 init_completion(&done);
53 urb->transfer_flags |= URB_ASYNC_UNLINK;
54 urb->actual_length = 0;
55 status = usb_submit_urb(urb, GFP_NOIO);
60 timer.expires = jiffies + timeout;
61 timer.data = (unsigned long)urb;
62 timer.function = timeout_kill;
63 /* grr. timeout _should_ include submit delays. */
66 wait_for_completion(&done);
68 /* note: HCDs return ETIMEDOUT for other reasons too */
69 if (status == -ECONNRESET)
72 del_timer_sync(&timer);
76 *actual_length = urb->actual_length;
81 /*-------------------------------------------------------------------*/
82 // returns status (negative) or length (positive)
83 int usb_internal_control_msg(struct usb_device *usb_dev, unsigned int pipe,
84 struct usb_ctrlrequest *cmd, void *data, int len, int timeout)
90 urb = usb_alloc_urb(0, GFP_NOIO);
94 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char*)cmd, data, len,
95 usb_api_blocking_completion, 0);
97 retv = usb_start_wait_urb(urb, timeout, &length);
105 * usb_control_msg - Builds a control urb, sends it off and waits for completion
106 * @dev: pointer to the usb device to send the message to
107 * @pipe: endpoint "pipe" to send the message to
108 * @request: USB message request value
109 * @requesttype: USB message request type value
110 * @value: USB message value
111 * @index: USB message index value
112 * @data: pointer to the data to send
113 * @size: length in bytes of the data to send
114 * @timeout: time in jiffies to wait for the message to complete before
115 * timing out (if 0 the wait is forever)
116 * Context: !in_interrupt ()
118 * This function sends a simple control message to a specified endpoint
119 * and waits for the message to complete, or timeout.
121 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
123 * Don't use this function from within an interrupt context, like a
124 * bottom half handler. If you need an asynchronous message, or need to send
125 * a message from within interrupt context, use usb_submit_urb()
126 * If a thread in your driver uses this call, make sure your disconnect()
127 * method can wait for it to complete. Since you don't have a handle on
128 * the URB used, you can't cancel the request.
130 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
131 __u16 value, __u16 index, void *data, __u16 size, int timeout)
133 struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
139 dr->bRequestType= requesttype;
140 dr->bRequest = request;
141 dr->wValue = cpu_to_le16p(&value);
142 dr->wIndex = cpu_to_le16p(&index);
143 dr->wLength = cpu_to_le16p(&size);
145 //dbg("usb_control_msg");
147 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
156 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
157 * @usb_dev: pointer to the usb device to send the message to
158 * @pipe: endpoint "pipe" to send the message to
159 * @data: pointer to the data to send
160 * @len: length in bytes of the data to send
161 * @actual_length: pointer to a location to put the actual length transferred in bytes
162 * @timeout: time in jiffies to wait for the message to complete before
163 * timing out (if 0 the wait is forever)
164 * Context: !in_interrupt ()
166 * This function sends a simple bulk message to a specified endpoint
167 * and waits for the message to complete, or timeout.
169 * If successful, it returns 0, otherwise a negative error number.
170 * The number of actual bytes transferred will be stored in the
171 * actual_length paramater.
173 * Don't use this function from within an interrupt context, like a
174 * bottom half handler. If you need an asynchronous message, or need to
175 * send a message from within interrupt context, use usb_submit_urb()
176 * If a thread in your driver uses this call, make sure your disconnect()
177 * method can wait for it to complete. Since you don't have a handle on
178 * the URB used, you can't cancel the request.
180 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
181 void *data, int len, int *actual_length, int timeout)
188 urb=usb_alloc_urb(0, GFP_KERNEL);
192 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
193 usb_api_blocking_completion, 0);
195 return usb_start_wait_urb(urb,timeout,actual_length);
198 /*-------------------------------------------------------------------*/
200 static void sg_clean (struct usb_sg_request *io)
203 while (io->entries--)
204 usb_free_urb (io->urbs [io->entries]);
208 if (io->dev->dev.dma_mask != 0)
209 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
213 static void sg_complete (struct urb *urb, struct pt_regs *regs)
215 struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
217 spin_lock (&io->lock);
219 /* In 2.5 we require hcds' endpoint queues not to progress after fault
220 * reports, until the completion callback (this!) returns. That lets
221 * device driver code (like this routine) unlink queued urbs first,
222 * if it needs to, since the HC won't work on them at all. So it's
223 * not possible for page N+1 to overwrite page N, and so on.
225 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
226 * complete before the HCD can get requests away from hardware,
227 * though never during cleanup after a hard fault.
230 && (io->status != -ECONNRESET
231 || urb->status != -ECONNRESET)
232 && urb->actual_length) {
233 dev_err (io->dev->bus->controller,
234 "dev %s ep%d%s scatterlist error %d/%d\n",
236 usb_pipeendpoint (urb->pipe),
237 usb_pipein (urb->pipe) ? "in" : "out",
238 urb->status, io->status);
242 if (urb->status && urb->status != -ECONNRESET) {
243 int i, found, status;
245 io->status = urb->status;
247 /* the previous urbs, and this one, completed already.
248 * unlink pending urbs so they won't rx/tx bad data.
250 for (i = 0, found = 0; i < io->entries; i++) {
254 status = usb_unlink_urb (io->urbs [i]);
255 if (status != -EINPROGRESS && status != -EBUSY)
256 dev_err (&io->dev->dev,
257 "%s, unlink --> %d\n",
258 __FUNCTION__, status);
259 } else if (urb == io->urbs [i])
265 /* on the last completion, signal usb_sg_wait() */
266 io->bytes += urb->actual_length;
269 complete (&io->complete);
271 spin_unlock (&io->lock);
276 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
277 * @io: request block being initialized. until usb_sg_wait() returns,
278 * treat this as a pointer to an opaque block of memory,
279 * @dev: the usb device that will send or receive the data
280 * @pipe: endpoint "pipe" used to transfer the data
281 * @period: polling rate for interrupt endpoints, in frames or
282 * (for high speed endpoints) microframes; ignored for bulk
283 * @sg: scatterlist entries
284 * @nents: how many entries in the scatterlist
285 * @length: how many bytes to send from the scatterlist, or zero to
286 * send every byte identified in the list.
287 * @mem_flags: SLAB_* flags affecting memory allocations in this call
289 * Returns zero for success, else a negative errno value. This initializes a
290 * scatter/gather request, allocating resources such as I/O mappings and urb
291 * memory (except maybe memory used by USB controller drivers).
293 * The request must be issued using usb_sg_wait(), which waits for the I/O to
294 * complete (or to be canceled) and then cleans up all resources allocated by
297 * The request may be canceled with usb_sg_cancel(), either before or after
298 * usb_sg_wait() is called.
301 struct usb_sg_request *io,
302 struct usb_device *dev,
305 struct scatterlist *sg,
315 if (!io || !dev || !sg
316 || usb_pipecontrol (pipe)
317 || usb_pipeisoc (pipe)
321 spin_lock_init (&io->lock);
327 /* not all host controllers use DMA (like the mainstream pci ones);
328 * they can use PIO (sl811) or be software over another transport.
330 dma = (dev->dev.dma_mask != 0);
332 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
336 /* initialize all the urbs we'll use */
337 if (io->entries <= 0)
341 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
345 urb_flags = URB_ASYNC_UNLINK | URB_NO_TRANSFER_DMA_MAP
347 if (usb_pipein (pipe))
348 urb_flags |= URB_SHORT_NOT_OK;
350 for (i = 0; i < io->entries; i++, io->count = i) {
353 io->urbs [i] = usb_alloc_urb (0, mem_flags);
359 io->urbs [i]->dev = 0;
360 io->urbs [i]->pipe = pipe;
361 io->urbs [i]->interval = period;
362 io->urbs [i]->transfer_flags = urb_flags;
364 io->urbs [i]->complete = sg_complete;
365 io->urbs [i]->context = io;
366 io->urbs [i]->status = -EINPROGRESS;
367 io->urbs [i]->actual_length = 0;
370 /* hc may use _only_ transfer_dma */
371 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
372 len = sg_dma_len (sg + i);
374 /* hc may use _only_ transfer_buffer */
375 io->urbs [i]->transfer_buffer =
376 page_address (sg [i].page) + sg [i].offset;
381 len = min_t (unsigned, len, length);
386 io->urbs [i]->transfer_buffer_length = len;
388 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
390 /* transaction state */
393 init_completion (&io->complete);
403 * usb_sg_wait - synchronously execute scatter/gather request
404 * @io: request block handle, as initialized with usb_sg_init().
405 * some fields become accessible when this call returns.
406 * Context: !in_interrupt ()
408 * This function blocks until the specified I/O operation completes. It
409 * leverages the grouping of the related I/O requests to get good transfer
410 * rates, by queueing the requests. At higher speeds, such queuing can
411 * significantly improve USB throughput.
413 * There are three kinds of completion for this function.
414 * (1) success, where io->status is zero. The number of io->bytes
415 * transferred is as requested.
416 * (2) error, where io->status is a negative errno value. The number
417 * of io->bytes transferred before the error is usually less
418 * than requested, and can be nonzero.
419 * (3) cancelation, a type of error with status -ECONNRESET that
420 * is initiated by usb_sg_cancel().
422 * When this function returns, all memory allocated through usb_sg_init() or
423 * this call will have been freed. The request block parameter may still be
424 * passed to usb_sg_cancel(), or it may be freed. It could also be
425 * reinitialized and then reused.
427 * Data Transfer Rates:
429 * Bulk transfers are valid for full or high speed endpoints.
430 * The best full speed data rate is 19 packets of 64 bytes each
431 * per frame, or 1216 bytes per millisecond.
432 * The best high speed data rate is 13 packets of 512 bytes each
433 * per microframe, or 52 KBytes per millisecond.
435 * The reason to use interrupt transfers through this API would most likely
436 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
437 * could be transferred. That capability is less useful for low or full
438 * speed interrupt endpoints, which allow at most one packet per millisecond,
439 * of at most 8 or 64 bytes (respectively).
441 void usb_sg_wait (struct usb_sg_request *io)
443 int i, entries = io->entries;
445 /* queue the urbs. */
446 spin_lock_irq (&io->lock);
447 for (i = 0; i < entries && !io->status; i++) {
450 io->urbs [i]->dev = io->dev;
451 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
453 /* after we submit, let completions or cancelations fire;
454 * we handshake using io->status.
456 spin_unlock_irq (&io->lock);
458 /* maybe we retrying will recover */
459 case -ENXIO: // hc didn't queue this one
462 io->urbs [i]->dev = 0;
468 /* no error? continue immediately.
470 * NOTE: to work better with UHCI (4K I/O buffer may
471 * need 3K of TDs) it may be good to limit how many
472 * URBs are queued at once; N milliseconds?
478 /* fail any uncompleted urbs */
480 spin_lock_irq (&io->lock);
481 io->count -= entries - i;
482 if (io->status == -EINPROGRESS)
485 complete (&io->complete);
486 spin_unlock_irq (&io->lock);
488 io->urbs [i]->dev = 0;
489 io->urbs [i]->status = retval;
490 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
491 __FUNCTION__, retval);
494 spin_lock_irq (&io->lock);
495 if (retval && io->status == -ECONNRESET)
498 spin_unlock_irq (&io->lock);
500 /* OK, yes, this could be packaged as non-blocking.
501 * So could the submit loop above ... but it's easier to
502 * solve neither problem than to solve both!
504 wait_for_completion (&io->complete);
510 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
511 * @io: request block, initialized with usb_sg_init()
513 * This stops a request after it has been started by usb_sg_wait().
514 * It can also prevents one initialized by usb_sg_init() from starting,
515 * so that call just frees resources allocated to the request.
517 void usb_sg_cancel (struct usb_sg_request *io)
521 spin_lock_irqsave (&io->lock, flags);
523 /* shut everything down, if it didn't already */
527 io->status = -ECONNRESET;
528 for (i = 0; i < io->entries; i++) {
531 if (!io->urbs [i]->dev)
533 retval = usb_unlink_urb (io->urbs [i]);
534 if (retval != -EINPROGRESS && retval != -EBUSY)
535 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
536 __FUNCTION__, retval);
539 spin_unlock_irqrestore (&io->lock, flags);
542 /*-------------------------------------------------------------------*/
545 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
546 * @dev: the device whose descriptor is being retrieved
547 * @type: the descriptor type (USB_DT_*)
548 * @index: the number of the descriptor
549 * @buf: where to put the descriptor
550 * @size: how big is "buf"?
551 * Context: !in_interrupt ()
553 * Gets a USB descriptor. Convenience functions exist to simplify
554 * getting some types of descriptors. Use
555 * usb_get_device_descriptor() for USB_DT_DEVICE (not exported),
556 * and usb_get_string() or usb_string() for USB_DT_STRING.
557 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
558 * are part of the device structure.
559 * In addition to a number of USB-standard descriptors, some
560 * devices also use class-specific or vendor-specific descriptors.
562 * This call is synchronous, and may not be used in an interrupt context.
564 * Returns the number of bytes received on success, or else the status code
565 * returned by the underlying usb_control_msg() call.
567 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
572 memset(buf,0,size); // Make sure we parse really received data
574 for (i = 0; i < 3; ++i) {
575 /* retry on length 0 or stall; some devices are flakey */
576 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
577 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
578 (type << 8) + index, 0, buf, size,
579 HZ * USB_CTRL_GET_TIMEOUT);
580 if (!(result == 0 || result == -EPIPE))
587 * usb_get_string - gets a string descriptor
588 * @dev: the device whose string descriptor is being retrieved
589 * @langid: code for language chosen (from string descriptor zero)
590 * @index: the number of the descriptor
591 * @buf: where to put the string
592 * @size: how big is "buf"?
593 * Context: !in_interrupt ()
595 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
596 * in little-endian byte order).
597 * The usb_string() function will often be a convenient way to turn
598 * these strings into kernel-printable form.
600 * Strings may be referenced in device, configuration, interface, or other
601 * descriptors, and could also be used in vendor-specific ways.
603 * This call is synchronous, and may not be used in an interrupt context.
605 * Returns the number of bytes received on success, or else the status code
606 * returned by the underlying usb_control_msg() call.
608 int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
610 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
611 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
612 (USB_DT_STRING << 8) + index, langid, buf, size,
613 HZ * USB_CTRL_GET_TIMEOUT);
617 * usb_get_device_descriptor - (re)reads the device descriptor
618 * @dev: the device whose device descriptor is being updated
619 * @size: how much of the descriptor to read
620 * Context: !in_interrupt ()
622 * Updates the copy of the device descriptor stored in the device structure,
623 * which dedicates space for this purpose. Note that several fields are
624 * converted to the host CPU's byte order: the USB version (bcdUSB), and
625 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
626 * That lets device drivers compare against non-byteswapped constants.
628 * Not exported, only for use by the core. If drivers really want to read
629 * the device descriptor directly, they can call usb_get_descriptor() with
630 * type = USB_DT_DEVICE and index = 0.
632 * This call is synchronous, and may not be used in an interrupt context.
634 * Returns the number of bytes received on success, or else the status code
635 * returned by the underlying usb_control_msg() call.
637 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
639 struct usb_device_descriptor *desc;
642 if (size > sizeof(*desc))
644 desc = kmalloc(sizeof(*desc), GFP_NOIO);
648 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
650 le16_to_cpus(&desc->bcdUSB);
651 le16_to_cpus(&desc->idVendor);
652 le16_to_cpus(&desc->idProduct);
653 le16_to_cpus(&desc->bcdDevice);
654 memcpy(&dev->descriptor, desc, size);
661 * usb_get_status - issues a GET_STATUS call
662 * @dev: the device whose status is being checked
663 * @type: USB_RECIP_*; for device, interface, or endpoint
664 * @target: zero (for device), else interface or endpoint number
665 * @data: pointer to two bytes of bitmap data
666 * Context: !in_interrupt ()
668 * Returns device, interface, or endpoint status. Normally only of
669 * interest to see if the device is self powered, or has enabled the
670 * remote wakeup facility; or whether a bulk or interrupt endpoint
671 * is halted ("stalled").
673 * Bits in these status bitmaps are set using the SET_FEATURE request,
674 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
675 * function should be used to clear halt ("stall") status.
677 * This call is synchronous, and may not be used in an interrupt context.
679 * Returns the number of bytes received on success, or else the status code
680 * returned by the underlying usb_control_msg() call.
682 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
684 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
685 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, data, 2,
686 HZ * USB_CTRL_GET_TIMEOUT);
690 * usb_clear_halt - tells device to clear endpoint halt/stall condition
691 * @dev: device whose endpoint is halted
692 * @pipe: endpoint "pipe" being cleared
693 * Context: !in_interrupt ()
695 * This is used to clear halt conditions for bulk and interrupt endpoints,
696 * as reported by URB completion status. Endpoints that are halted are
697 * sometimes referred to as being "stalled". Such endpoints are unable
698 * to transmit or receive data until the halt status is cleared. Any URBs
699 * queued for such an endpoint should normally be unlinked by the driver
700 * before clearing the halt condition, as described in sections 5.7.5
701 * and 5.8.5 of the USB 2.0 spec.
703 * Note that control and isochronous endpoints don't halt, although control
704 * endpoints report "protocol stall" (for unsupported requests) using the
705 * same status code used to report a true stall.
707 * This call is synchronous, and may not be used in an interrupt context.
709 * Returns zero on success, or else the status code returned by the
710 * underlying usb_control_msg() call.
712 int usb_clear_halt(struct usb_device *dev, int pipe)
715 int endp = usb_pipeendpoint(pipe);
717 if (usb_pipein (pipe))
720 /* we don't care if it wasn't halted first. in fact some devices
721 * (like some ibmcam model 1 units) seem to expect hosts to make
722 * this request for iso endpoints, which can't halt!
724 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
725 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
726 USB_ENDPOINT_HALT, endp, NULL, 0,
727 HZ * USB_CTRL_SET_TIMEOUT);
729 /* don't un-halt or force to DATA0 except on success */
733 /* NOTE: seems like Microsoft and Apple don't bother verifying
734 * the clear "took", so some devices could lock up if you check...
735 * such as the Hagiwara FlashGate DUAL. So we won't bother.
737 * NOTE: make sure the logic here doesn't diverge much from
738 * the copy in usb-storage, for as long as we need two copies.
741 /* toggle was reset by the clear, then ep was reactivated */
742 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
743 usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
749 * usb_disable_endpoint -- Disable an endpoint by address
750 * @dev: the device whose endpoint is being disabled
751 * @epaddr: the endpoint's address. Endpoint number for output,
752 * endpoint number + USB_DIR_IN for input
754 * Deallocates hcd/hardware state for this endpoint ... and nukes all
757 * If the HCD hasn't registered a disable() function, this marks the
758 * endpoint as halted and sets its maxpacket size to 0 to prevent
759 * further submissions.
761 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
763 if (dev && dev->bus && dev->bus->op && dev->bus->op->disable)
764 dev->bus->op->disable(dev, epaddr);
766 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
768 if (usb_endpoint_out(epaddr)) {
769 usb_endpoint_halt(dev, epnum, 1);
770 dev->epmaxpacketout[epnum] = 0;
772 usb_endpoint_halt(dev, epnum, 0);
773 dev->epmaxpacketin[epnum] = 0;
779 * usb_disable_interface -- Disable all endpoints for an interface
780 * @dev: the device whose interface is being disabled
781 * @intf: pointer to the interface descriptor
783 * Disables all the endpoints for the interface's current altsetting.
785 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
787 struct usb_host_interface *alt = intf->cur_altsetting;
790 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
791 usb_disable_endpoint(dev,
792 alt->endpoint[i].desc.bEndpointAddress);
797 * usb_disable_device - Disable all the endpoints for a USB device
798 * @dev: the device whose endpoints are being disabled
799 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
801 * Disables all the device's endpoints, potentially including endpoint 0.
802 * Deallocates hcd/hardware state for the endpoints (nuking all or most
803 * pending urbs) and usbcore state for the interfaces, so that usbcore
804 * must usb_set_configuration() before any interfaces could be used.
806 void usb_disable_device(struct usb_device *dev, int skip_ep0)
810 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
811 skip_ep0 ? "non-ep0" : "all");
812 for (i = skip_ep0; i < 16; ++i) {
813 usb_disable_endpoint(dev, i);
814 usb_disable_endpoint(dev, i + USB_DIR_IN);
816 dev->toggle[0] = dev->toggle[1] = 0;
817 dev->halted[0] = dev->halted[1] = 0;
819 /* getting rid of interfaces will disconnect
820 * any drivers bound to them (a key side effect)
822 if (dev->actconfig) {
823 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
824 struct usb_interface *interface;
826 /* remove this interface */
827 interface = dev->actconfig->interface[i];
828 dev_dbg (&dev->dev, "unregistering interface %s\n",
829 interface->dev.bus_id);
830 usb_remove_sysfs_intf_files(interface);
831 device_del (&interface->dev);
834 /* Now that the interfaces are unbound, nobody should
835 * try to access them.
837 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
838 put_device (&dev->actconfig->interface[i]->dev);
839 dev->actconfig->interface[i] = NULL;
842 if (dev->state == USB_STATE_CONFIGURED)
843 usb_set_device_state(dev, USB_STATE_ADDRESS);
849 * usb_enable_endpoint - Enable an endpoint for USB communications
850 * @dev: the device whose interface is being enabled
851 * @epd: pointer to the endpoint descriptor
853 * Marks the endpoint as running, resets its toggle, and stores
854 * its maxpacket value. For control endpoints, both the input
855 * and output sides are handled.
857 void usb_enable_endpoint(struct usb_device *dev,
858 struct usb_endpoint_descriptor *epd)
860 int maxsize = epd->wMaxPacketSize;
861 unsigned int epaddr = epd->bEndpointAddress;
862 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
863 int is_control = ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
864 USB_ENDPOINT_XFER_CONTROL);
866 if (usb_endpoint_out(epaddr) || is_control) {
867 usb_endpoint_running(dev, epnum, 1);
868 usb_settoggle(dev, epnum, 1, 0);
869 dev->epmaxpacketout[epnum] = maxsize;
871 if (!usb_endpoint_out(epaddr) || is_control) {
872 usb_endpoint_running(dev, epnum, 0);
873 usb_settoggle(dev, epnum, 0, 0);
874 dev->epmaxpacketin[epnum] = maxsize;
879 * usb_enable_interface - Enable all the endpoints for an interface
880 * @dev: the device whose interface is being enabled
881 * @intf: pointer to the interface descriptor
883 * Enables all the endpoints for the interface's current altsetting.
885 void usb_enable_interface(struct usb_device *dev,
886 struct usb_interface *intf)
888 struct usb_host_interface *alt = intf->cur_altsetting;
891 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
892 usb_enable_endpoint(dev, &alt->endpoint[i].desc);
896 * usb_set_interface - Makes a particular alternate setting be current
897 * @dev: the device whose interface is being updated
898 * @interface: the interface being updated
899 * @alternate: the setting being chosen.
900 * Context: !in_interrupt ()
902 * This is used to enable data transfers on interfaces that may not
903 * be enabled by default. Not all devices support such configurability.
904 * Only the driver bound to an interface may change its setting.
906 * Within any given configuration, each interface may have several
907 * alternative settings. These are often used to control levels of
908 * bandwidth consumption. For example, the default setting for a high
909 * speed interrupt endpoint may not send more than 64 bytes per microframe,
910 * while interrupt transfers of up to 3KBytes per microframe are legal.
911 * Also, isochronous endpoints may never be part of an
912 * interface's default setting. To access such bandwidth, alternate
913 * interface settings must be made current.
915 * Note that in the Linux USB subsystem, bandwidth associated with
916 * an endpoint in a given alternate setting is not reserved until an URB
917 * is submitted that needs that bandwidth. Some other operating systems
918 * allocate bandwidth early, when a configuration is chosen.
920 * This call is synchronous, and may not be used in an interrupt context.
921 * Also, drivers must not change altsettings while urbs are scheduled for
922 * endpoints in that interface; all such urbs must first be completed
923 * (perhaps forced by unlinking).
925 * Returns zero on success, or else the status code returned by the
926 * underlying usb_control_msg() call.
928 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
930 struct usb_interface *iface;
931 struct usb_host_interface *alt;
935 iface = usb_ifnum_to_if(dev, interface);
937 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
942 alt = usb_altnum_to_altsetting(iface, alternate);
944 warn("selecting invalid altsetting %d", alternate);
948 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
949 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
950 alternate, interface, NULL, 0, HZ * 5);
952 /* 9.4.10 says devices don't need this and are free to STALL the
953 * request if the interface only has one alternate setting.
955 if (ret == -EPIPE && iface->num_altsetting == 1) {
957 "manual set_interface for iface %d, alt %d\n",
958 interface, alternate);
963 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
964 * when they implement async or easily-killable versions of this or
965 * other "should-be-internal" functions (like clear_halt).
966 * should hcd+usbcore postprocess control requests?
969 /* prevent submissions using previous endpoint settings */
970 usb_disable_interface(dev, iface);
972 iface->cur_altsetting = alt;
974 /* If the interface only has one altsetting and the device didn't
975 * accept the request, we attempt to carry out the equivalent action
976 * by manually clearing the HALT feature for each endpoint in the
982 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
983 unsigned int epaddr =
984 alt->endpoint[i].desc.bEndpointAddress;
986 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
987 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
989 usb_clear_halt(dev, pipe);
993 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
996 * Despite EP0 is always present in all interfaces/AS, the list of
997 * endpoints from the descriptor does not contain EP0. Due to its
998 * omnipresence one might expect EP0 being considered "affected" by
999 * any SetInterface request and hence assume toggles need to be reset.
1000 * However, EP0 toggles are re-synced for every individual transfer
1001 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1002 * (Likewise, EP0 never "halts" on well designed devices.)
1004 usb_enable_interface(dev, iface);
1010 * usb_reset_configuration - lightweight device reset
1011 * @dev: the device whose configuration is being reset
1013 * This issues a standard SET_CONFIGURATION request to the device using
1014 * the current configuration. The effect is to reset most USB-related
1015 * state in the device, including interface altsettings (reset to zero),
1016 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1017 * endpoints). Other usbcore state is unchanged, including bindings of
1018 * usb device drivers to interfaces.
1020 * Because this affects multiple interfaces, avoid using this with composite
1021 * (multi-interface) devices. Instead, the driver for each interface may
1022 * use usb_set_interface() on the interfaces it claims. Resetting the whole
1023 * configuration would affect other drivers' interfaces.
1025 * Returns zero on success, else a negative error code.
1027 int usb_reset_configuration(struct usb_device *dev)
1030 struct usb_host_config *config;
1032 /* caller must own dev->serialize (config won't change)
1033 * and the usb bus readlock (so driver bindings are stable);
1034 * so calls during probe() are fine
1037 for (i = 1; i < 16; ++i) {
1038 usb_disable_endpoint(dev, i);
1039 usb_disable_endpoint(dev, i + USB_DIR_IN);
1042 config = dev->actconfig;
1043 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1044 USB_REQ_SET_CONFIGURATION, 0,
1045 config->desc.bConfigurationValue, 0,
1046 NULL, 0, HZ * USB_CTRL_SET_TIMEOUT);
1048 usb_set_device_state(dev, USB_STATE_ADDRESS);
1052 dev->toggle[0] = dev->toggle[1] = 0;
1053 dev->halted[0] = dev->halted[1] = 0;
1055 /* re-init hc/hcd interface/endpoint state */
1056 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1057 struct usb_interface *intf = config->interface[i];
1058 struct usb_host_interface *alt;
1060 alt = usb_altnum_to_altsetting(intf, 0);
1062 /* No altsetting 0? We'll assume the first altsetting.
1063 * We could use a GetInterface call, but if a device is
1064 * so non-compliant that it doesn't have altsetting 0
1065 * then I wouldn't trust its reply anyway.
1068 alt = &intf->altsetting[0];
1070 intf->cur_altsetting = alt;
1071 usb_enable_interface(dev, intf);
1076 static void release_interface(struct device *dev)
1078 struct usb_interface *intf = to_usb_interface(dev);
1079 struct usb_interface_cache *intfc =
1080 altsetting_to_usb_interface_cache(intf->altsetting);
1082 kref_put(&intfc->ref);
1087 * usb_set_configuration - Makes a particular device setting be current
1088 * @dev: the device whose configuration is being updated
1089 * @configuration: the configuration being chosen.
1090 * Context: !in_interrupt(), caller holds dev->serialize
1092 * This is used to enable non-default device modes. Not all devices
1093 * use this kind of configurability; many devices only have one
1096 * USB device configurations may affect Linux interoperability,
1097 * power consumption and the functionality available. For example,
1098 * the default configuration is limited to using 100mA of bus power,
1099 * so that when certain device functionality requires more power,
1100 * and the device is bus powered, that functionality should be in some
1101 * non-default device configuration. Other device modes may also be
1102 * reflected as configuration options, such as whether two ISDN
1103 * channels are available independently; and choosing between open
1104 * standard device protocols (like CDC) or proprietary ones.
1106 * Note that USB has an additional level of device configurability,
1107 * associated with interfaces. That configurability is accessed using
1108 * usb_set_interface().
1110 * This call is synchronous. The calling context must be able to sleep,
1111 * and must not hold the driver model lock for USB; usb device driver
1112 * probe() methods may not use this routine.
1114 * Returns zero on success, or else the status code returned by the
1115 * underlying call that failed. On succesful completion, each interface
1116 * in the original device configuration has been destroyed, and each one
1117 * in the new configuration has been probed by all relevant usb device
1118 * drivers currently known to the kernel.
1120 int usb_set_configuration(struct usb_device *dev, int configuration)
1123 struct usb_host_config *cp = NULL;
1124 struct usb_interface **new_interfaces = NULL;
1127 /* dev->serialize guards all config changes */
1129 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1130 if (dev->config[i].desc.bConfigurationValue == configuration) {
1131 cp = &dev->config[i];
1135 if ((!cp && configuration != 0))
1138 /* The USB spec says configuration 0 means unconfigured.
1139 * But if a device includes a configuration numbered 0,
1140 * we will accept it as a correctly configured state.
1142 if (cp && configuration == 0)
1143 dev_warn(&dev->dev, "config 0 descriptor??\n");
1145 /* Allocate memory for new interfaces before doing anything else,
1146 * so that if we run out then nothing will have changed. */
1149 nintf = cp->desc.bNumInterfaces;
1150 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1152 if (!new_interfaces) {
1153 dev_err(&dev->dev, "Out of memory");
1157 for (; n < nintf; ++n) {
1158 new_interfaces[n] = kmalloc(
1159 sizeof(struct usb_interface),
1161 if (!new_interfaces[n]) {
1162 dev_err(&dev->dev, "Out of memory");
1166 kfree(new_interfaces[n]);
1167 kfree(new_interfaces);
1173 /* if it's already configured, clear out old state first.
1174 * getting rid of old interfaces means unbinding their drivers.
1176 if (dev->state != USB_STATE_ADDRESS)
1177 usb_disable_device (dev, 1); // Skip ep0
1179 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1180 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1181 NULL, 0, HZ * USB_CTRL_SET_TIMEOUT)) < 0)
1182 goto free_interfaces;
1184 dev->actconfig = cp;
1186 usb_set_device_state(dev, USB_STATE_ADDRESS);
1188 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1190 /* Initialize the new interface structures and the
1191 * hc/hcd/usbcore interface/endpoint state.
1193 for (i = 0; i < nintf; ++i) {
1194 struct usb_interface_cache *intfc;
1195 struct usb_interface *intf;
1196 struct usb_host_interface *alt;
1198 cp->interface[i] = intf = new_interfaces[i];
1199 memset(intf, 0, sizeof(*intf));
1200 intfc = cp->intf_cache[i];
1201 intf->altsetting = intfc->altsetting;
1202 intf->num_altsetting = intfc->num_altsetting;
1203 kref_get(&intfc->ref);
1205 alt = usb_altnum_to_altsetting(intf, 0);
1207 /* No altsetting 0? We'll assume the first altsetting.
1208 * We could use a GetInterface call, but if a device is
1209 * so non-compliant that it doesn't have altsetting 0
1210 * then I wouldn't trust its reply anyway.
1213 alt = &intf->altsetting[0];
1215 intf->cur_altsetting = alt;
1216 usb_enable_interface(dev, intf);
1217 intf->dev.parent = &dev->dev;
1218 intf->dev.driver = NULL;
1219 intf->dev.bus = &usb_bus_type;
1220 intf->dev.dma_mask = dev->dev.dma_mask;
1221 intf->dev.release = release_interface;
1222 device_initialize (&intf->dev);
1223 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1224 dev->bus->busnum, dev->devpath,
1226 alt->desc.bInterfaceNumber);
1228 kfree(new_interfaces);
1230 /* Now that all the interfaces are set up, register them
1231 * to trigger binding of drivers to interfaces. probe()
1232 * routines may install different altsettings and may
1233 * claim() any interfaces not yet bound. Many class drivers
1234 * need that: CDC, audio, video, etc.
1236 for (i = 0; i < nintf; ++i) {
1237 struct usb_interface *intf = cp->interface[i];
1238 struct usb_interface_descriptor *desc;
1240 desc = &intf->altsetting [0].desc;
1242 "adding %s (config #%d, interface %d)\n",
1243 intf->dev.bus_id, configuration,
1244 desc->bInterfaceNumber);
1245 ret = device_add (&intf->dev);
1248 "device_add(%s) --> %d\n",
1253 usb_create_sysfs_intf_files (intf);
1261 * usb_string - returns ISO 8859-1 version of a string descriptor
1262 * @dev: the device whose string descriptor is being retrieved
1263 * @index: the number of the descriptor
1264 * @buf: where to put the string
1265 * @size: how big is "buf"?
1266 * Context: !in_interrupt ()
1268 * This converts the UTF-16LE encoded strings returned by devices, from
1269 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
1270 * that are more usable in most kernel contexts. Note that all characters
1271 * in the chosen descriptor that can't be encoded using ISO-8859-1
1272 * are converted to the question mark ("?") character, and this function
1273 * chooses strings in the first language supported by the device.
1275 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
1276 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
1277 * and is appropriate for use many uses of English and several other
1278 * Western European languages. (But it doesn't include the "Euro" symbol.)
1280 * This call is synchronous, and may not be used in an interrupt context.
1282 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
1284 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
1286 unsigned char *tbuf;
1288 unsigned int u, idx;
1290 if (size <= 0 || !buf || !index)
1293 tbuf = kmalloc(256, GFP_KERNEL);
1297 /* get langid for strings if it's not yet known */
1298 if (!dev->have_langid) {
1299 err = usb_get_descriptor(dev, USB_DT_STRING, 0, tbuf, 4);
1302 "string descriptor 0 read error: %d\n",
1305 } else if (err < 4 || tbuf[0] < 4) {
1306 dev_err (&dev->dev, "string descriptor 0 too short\n");
1310 dev->have_langid = -1;
1311 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
1312 /* always use the first langid listed */
1313 dev_dbg (&dev->dev, "default language 0x%04x\n",
1314 dev->string_langid);
1319 * ask for the length of the string
1322 err = usb_get_string(dev, dev->string_langid, index, tbuf, 2);
1323 if (err == -EPIPE || err == 0) {
1324 dev_dbg(&dev->dev, "RETRY string %d read/%d\n", index, 2);
1325 err = usb_get_string(dev, dev->string_langid, index, tbuf, 2);
1331 err = usb_get_string(dev, dev->string_langid, index, tbuf, len);
1332 if (err == -EPIPE || err == 0) {
1333 dev_dbg(&dev->dev, "RETRY string %d read/%d\n", index, len);
1334 err = usb_get_string(dev, dev->string_langid, index, tbuf, len);
1339 size--; /* leave room for trailing NULL char in output buffer */
1340 for (idx = 0, u = 2; u < err; u += 2) {
1343 if (tbuf[u+1]) /* high byte */
1344 buf[idx++] = '?'; /* non ISO-8859-1 character */
1346 buf[idx++] = tbuf[u];
1356 // synchronous request completion model
1357 EXPORT_SYMBOL(usb_control_msg);
1358 EXPORT_SYMBOL(usb_bulk_msg);
1360 EXPORT_SYMBOL(usb_sg_init);
1361 EXPORT_SYMBOL(usb_sg_cancel);
1362 EXPORT_SYMBOL(usb_sg_wait);
1364 // synchronous control message convenience routines
1365 EXPORT_SYMBOL(usb_get_descriptor);
1366 EXPORT_SYMBOL(usb_get_status);
1367 EXPORT_SYMBOL(usb_get_string);
1368 EXPORT_SYMBOL(usb_string);
1370 // synchronous calls that also maintain usbcore state
1371 EXPORT_SYMBOL(usb_clear_halt);
1372 EXPORT_SYMBOL(usb_reset_configuration);
1373 EXPORT_SYMBOL(usb_set_interface);