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;
218 spin_lock_irqsave (&io->lock, flags);
220 /* In 2.5 we require hcds' endpoint queues not to progress after fault
221 * reports, until the completion callback (this!) returns. That lets
222 * device driver code (like this routine) unlink queued urbs first,
223 * if it needs to, since the HC won't work on them at all. So it's
224 * not possible for page N+1 to overwrite page N, and so on.
226 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
227 * complete before the HCD can get requests away from hardware,
228 * though never during cleanup after a hard fault.
231 && (io->status != -ECONNRESET
232 || urb->status != -ECONNRESET)
233 && urb->actual_length) {
234 dev_err (io->dev->bus->controller,
235 "dev %s ep%d%s scatterlist error %d/%d\n",
237 usb_pipeendpoint (urb->pipe),
238 usb_pipein (urb->pipe) ? "in" : "out",
239 urb->status, io->status);
243 if (urb->status && urb->status != -ECONNRESET) {
244 int i, found, status;
246 io->status = urb->status;
248 /* the previous urbs, and this one, completed already.
249 * unlink pending urbs so they won't rx/tx bad data.
251 for (i = 0, found = 0; i < io->entries; i++) {
255 status = usb_unlink_urb (io->urbs [i]);
256 if (status != -EINPROGRESS && status != -EBUSY)
257 dev_err (&io->dev->dev,
258 "%s, unlink --> %d\n",
259 __FUNCTION__, status);
260 } else if (urb == io->urbs [i])
266 /* on the last completion, signal usb_sg_wait() */
267 io->bytes += urb->actual_length;
270 complete (&io->complete);
272 spin_unlock_irqrestore (&io->lock, flags);
277 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
278 * @io: request block being initialized. until usb_sg_wait() returns,
279 * treat this as a pointer to an opaque block of memory,
280 * @dev: the usb device that will send or receive the data
281 * @pipe: endpoint "pipe" used to transfer the data
282 * @period: polling rate for interrupt endpoints, in frames or
283 * (for high speed endpoints) microframes; ignored for bulk
284 * @sg: scatterlist entries
285 * @nents: how many entries in the scatterlist
286 * @length: how many bytes to send from the scatterlist, or zero to
287 * send every byte identified in the list.
288 * @mem_flags: SLAB_* flags affecting memory allocations in this call
290 * Returns zero for success, else a negative errno value. This initializes a
291 * scatter/gather request, allocating resources such as I/O mappings and urb
292 * memory (except maybe memory used by USB controller drivers).
294 * The request must be issued using usb_sg_wait(), which waits for the I/O to
295 * complete (or to be canceled) and then cleans up all resources allocated by
298 * The request may be canceled with usb_sg_cancel(), either before or after
299 * usb_sg_wait() is called.
302 struct usb_sg_request *io,
303 struct usb_device *dev,
306 struct scatterlist *sg,
316 if (!io || !dev || !sg
317 || usb_pipecontrol (pipe)
318 || usb_pipeisoc (pipe)
322 spin_lock_init (&io->lock);
328 /* not all host controllers use DMA (like the mainstream pci ones);
329 * they can use PIO (sl811) or be software over another transport.
331 dma = (dev->dev.dma_mask != 0);
333 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
337 /* initialize all the urbs we'll use */
338 if (io->entries <= 0)
342 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
346 urb_flags = URB_ASYNC_UNLINK | URB_NO_TRANSFER_DMA_MAP
348 if (usb_pipein (pipe))
349 urb_flags |= URB_SHORT_NOT_OK;
351 for (i = 0; i < io->entries; i++, io->count = i) {
354 io->urbs [i] = usb_alloc_urb (0, mem_flags);
360 io->urbs [i]->dev = 0;
361 io->urbs [i]->pipe = pipe;
362 io->urbs [i]->interval = period;
363 io->urbs [i]->transfer_flags = urb_flags;
365 io->urbs [i]->complete = sg_complete;
366 io->urbs [i]->context = io;
367 io->urbs [i]->status = -EINPROGRESS;
368 io->urbs [i]->actual_length = 0;
371 /* hc may use _only_ transfer_dma */
372 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
373 len = sg_dma_len (sg + i);
375 /* hc may use _only_ transfer_buffer */
376 io->urbs [i]->transfer_buffer =
377 page_address (sg [i].page) + sg [i].offset;
382 len = min_t (unsigned, len, length);
387 io->urbs [i]->transfer_buffer_length = len;
389 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
391 /* transaction state */
394 init_completion (&io->complete);
404 * usb_sg_wait - synchronously execute scatter/gather request
405 * @io: request block handle, as initialized with usb_sg_init().
406 * some fields become accessible when this call returns.
407 * Context: !in_interrupt ()
409 * This function blocks until the specified I/O operation completes. It
410 * leverages the grouping of the related I/O requests to get good transfer
411 * rates, by queueing the requests. At higher speeds, such queuing can
412 * significantly improve USB throughput.
414 * There are three kinds of completion for this function.
415 * (1) success, where io->status is zero. The number of io->bytes
416 * transferred is as requested.
417 * (2) error, where io->status is a negative errno value. The number
418 * of io->bytes transferred before the error is usually less
419 * than requested, and can be nonzero.
420 * (3) cancelation, a type of error with status -ECONNRESET that
421 * is initiated by usb_sg_cancel().
423 * When this function returns, all memory allocated through usb_sg_init() or
424 * this call will have been freed. The request block parameter may still be
425 * passed to usb_sg_cancel(), or it may be freed. It could also be
426 * reinitialized and then reused.
428 * Data Transfer Rates:
430 * Bulk transfers are valid for full or high speed endpoints.
431 * The best full speed data rate is 19 packets of 64 bytes each
432 * per frame, or 1216 bytes per millisecond.
433 * The best high speed data rate is 13 packets of 512 bytes each
434 * per microframe, or 52 KBytes per millisecond.
436 * The reason to use interrupt transfers through this API would most likely
437 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
438 * could be transferred. That capability is less useful for low or full
439 * speed interrupt endpoints, which allow at most one packet per millisecond,
440 * of at most 8 or 64 bytes (respectively).
442 void usb_sg_wait (struct usb_sg_request *io)
447 /* queue the urbs. */
448 spin_lock_irqsave (&io->lock, flags);
449 for (i = 0; i < io->entries && !io->status; i++) {
452 io->urbs [i]->dev = io->dev;
453 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
455 /* after we submit, let completions or cancelations fire;
456 * we handshake using io->status.
458 spin_unlock_irqrestore (&io->lock, flags);
460 /* maybe we retrying will recover */
461 case -ENXIO: // hc didn't queue this one
464 io->urbs [i]->dev = 0;
470 /* no error? continue immediately.
472 * NOTE: to work better with UHCI (4K I/O buffer may
473 * need 3K of TDs) it may be good to limit how many
474 * URBs are queued at once; N milliseconds?
480 /* fail any uncompleted urbs */
482 io->urbs [i]->dev = 0;
483 io->urbs [i]->status = retval;
484 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
485 __FUNCTION__, retval);
488 spin_lock_irqsave (&io->lock, flags);
489 if (retval && io->status == -ECONNRESET)
492 spin_unlock_irqrestore (&io->lock, flags);
494 /* OK, yes, this could be packaged as non-blocking.
495 * So could the submit loop above ... but it's easier to
496 * solve neither problem than to solve both!
498 wait_for_completion (&io->complete);
504 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
505 * @io: request block, initialized with usb_sg_init()
507 * This stops a request after it has been started by usb_sg_wait().
508 * It can also prevents one initialized by usb_sg_init() from starting,
509 * so that call just frees resources allocated to the request.
511 void usb_sg_cancel (struct usb_sg_request *io)
515 spin_lock_irqsave (&io->lock, flags);
517 /* shut everything down, if it didn't already */
521 io->status = -ECONNRESET;
522 for (i = 0; i < io->entries; i++) {
525 if (!io->urbs [i]->dev)
527 retval = usb_unlink_urb (io->urbs [i]);
528 if (retval != -EINPROGRESS && retval != -EBUSY)
529 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
530 __FUNCTION__, retval);
533 spin_unlock_irqrestore (&io->lock, flags);
536 /*-------------------------------------------------------------------*/
539 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
540 * @dev: the device whose descriptor is being retrieved
541 * @type: the descriptor type (USB_DT_*)
542 * @index: the number of the descriptor
543 * @buf: where to put the descriptor
544 * @size: how big is "buf"?
545 * Context: !in_interrupt ()
547 * Gets a USB descriptor. Convenience functions exist to simplify
548 * getting some types of descriptors. Use
549 * usb_get_device_descriptor() for USB_DT_DEVICE (not exported),
550 * and usb_get_string() or usb_string() for USB_DT_STRING.
551 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
552 * are part of the device structure.
553 * In addition to a number of USB-standard descriptors, some
554 * devices also use class-specific or vendor-specific descriptors.
556 * This call is synchronous, and may not be used in an interrupt context.
558 * Returns the number of bytes received on success, or else the status code
559 * returned by the underlying usb_control_msg() call.
561 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
566 memset(buf,0,size); // Make sure we parse really received data
569 /* retries if the returned length was 0; flakey device */
570 if ((result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
571 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
572 (type << 8) + index, 0, buf, size,
573 HZ * USB_CTRL_GET_TIMEOUT)) > 0
581 * usb_get_string - gets a string descriptor
582 * @dev: the device whose string descriptor is being retrieved
583 * @langid: code for language chosen (from string descriptor zero)
584 * @index: the number of the descriptor
585 * @buf: where to put the string
586 * @size: how big is "buf"?
587 * Context: !in_interrupt ()
589 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
590 * in little-endian byte order).
591 * The usb_string() function will often be a convenient way to turn
592 * these strings into kernel-printable form.
594 * Strings may be referenced in device, configuration, interface, or other
595 * descriptors, and could also be used in vendor-specific ways.
597 * This call is synchronous, and may not be used in an interrupt context.
599 * Returns the number of bytes received on success, or else the status code
600 * returned by the underlying usb_control_msg() call.
602 int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
604 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
605 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
606 (USB_DT_STRING << 8) + index, langid, buf, size,
607 HZ * USB_CTRL_GET_TIMEOUT);
611 * usb_get_device_descriptor - (re)reads the device descriptor
612 * @dev: the device whose device descriptor is being updated
613 * @size: how much of the descriptor to read
614 * Context: !in_interrupt ()
616 * Updates the copy of the device descriptor stored in the device structure,
617 * which dedicates space for this purpose. Note that several fields are
618 * converted to the host CPU's byte order: the USB version (bcdUSB), and
619 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
620 * That lets device drivers compare against non-byteswapped constants.
622 * Not exported, only for use by the core. If drivers really want to read
623 * the device descriptor directly, they can call usb_get_descriptor() with
624 * type = USB_DT_DEVICE and index = 0.
626 * This call is synchronous, and may not be used in an interrupt context.
628 * Returns the number of bytes received on success, or else the status code
629 * returned by the underlying usb_control_msg() call.
631 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
633 struct usb_device_descriptor *desc;
636 if (size > sizeof(*desc))
638 desc = kmalloc(sizeof(*desc), GFP_NOIO);
642 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
644 le16_to_cpus(&desc->bcdUSB);
645 le16_to_cpus(&desc->idVendor);
646 le16_to_cpus(&desc->idProduct);
647 le16_to_cpus(&desc->bcdDevice);
648 memcpy(&dev->descriptor, desc, size);
655 * usb_get_status - issues a GET_STATUS call
656 * @dev: the device whose status is being checked
657 * @type: USB_RECIP_*; for device, interface, or endpoint
658 * @target: zero (for device), else interface or endpoint number
659 * @data: pointer to two bytes of bitmap data
660 * Context: !in_interrupt ()
662 * Returns device, interface, or endpoint status. Normally only of
663 * interest to see if the device is self powered, or has enabled the
664 * remote wakeup facility; or whether a bulk or interrupt endpoint
665 * is halted ("stalled").
667 * Bits in these status bitmaps are set using the SET_FEATURE request,
668 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
669 * function should be used to clear halt ("stall") status.
671 * This call is synchronous, and may not be used in an interrupt context.
673 * Returns the number of bytes received on success, or else the status code
674 * returned by the underlying usb_control_msg() call.
676 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
678 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
679 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, data, 2,
680 HZ * USB_CTRL_GET_TIMEOUT);
684 * usb_clear_halt - tells device to clear endpoint halt/stall condition
685 * @dev: device whose endpoint is halted
686 * @pipe: endpoint "pipe" being cleared
687 * Context: !in_interrupt ()
689 * This is used to clear halt conditions for bulk and interrupt endpoints,
690 * as reported by URB completion status. Endpoints that are halted are
691 * sometimes referred to as being "stalled". Such endpoints are unable
692 * to transmit or receive data until the halt status is cleared. Any URBs
693 * queued for such an endpoint should normally be unlinked by the driver
694 * before clearing the halt condition, as described in sections 5.7.5
695 * and 5.8.5 of the USB 2.0 spec.
697 * Note that control and isochronous endpoints don't halt, although control
698 * endpoints report "protocol stall" (for unsupported requests) using the
699 * same status code used to report a true stall.
701 * This call is synchronous, and may not be used in an interrupt context.
703 * Returns zero on success, or else the status code returned by the
704 * underlying usb_control_msg() call.
706 int usb_clear_halt(struct usb_device *dev, int pipe)
709 int endp = usb_pipeendpoint(pipe);
711 if (usb_pipein (pipe))
714 /* we don't care if it wasn't halted first. in fact some devices
715 * (like some ibmcam model 1 units) seem to expect hosts to make
716 * this request for iso endpoints, which can't halt!
718 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
719 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0, endp, NULL, 0,
720 HZ * USB_CTRL_SET_TIMEOUT);
722 /* don't un-halt or force to DATA0 except on success */
726 /* NOTE: seems like Microsoft and Apple don't bother verifying
727 * the clear "took", so some devices could lock up if you check...
728 * such as the Hagiwara FlashGate DUAL. So we won't bother.
730 * NOTE: make sure the logic here doesn't diverge much from
731 * the copy in usb-storage, for as long as we need two copies.
734 /* toggle was reset by the clear, then ep was reactivated */
735 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
736 usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
742 * usb_disable_endpoint -- Disable an endpoint by address
743 * @dev: the device whose endpoint is being disabled
744 * @epaddr: the endpoint's address. Endpoint number for output,
745 * endpoint number + USB_DIR_IN for input
747 * Deallocates hcd/hardware state for this endpoint ... and nukes all
750 * If the HCD hasn't registered a disable() function, this marks the
751 * endpoint as halted and sets its maxpacket size to 0 to prevent
752 * further submissions.
754 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
756 if (dev && dev->bus && dev->bus->op && dev->bus->op->disable)
757 dev->bus->op->disable(dev, epaddr);
759 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
761 if (usb_endpoint_out(epaddr)) {
762 usb_endpoint_halt(dev, epnum, 1);
763 dev->epmaxpacketout[epnum] = 0;
765 usb_endpoint_halt(dev, epnum, 0);
766 dev->epmaxpacketin[epnum] = 0;
772 * usb_disable_interface -- Disable all endpoints for an interface
773 * @dev: the device whose interface is being disabled
774 * @intf: pointer to the interface descriptor
776 * Disables all the endpoints for the interface's current altsetting.
778 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
780 struct usb_host_interface *hintf =
781 &intf->altsetting[intf->act_altsetting];
784 for (i = 0; i < hintf->desc.bNumEndpoints; ++i) {
785 usb_disable_endpoint(dev,
786 hintf->endpoint[i].desc.bEndpointAddress);
791 * usb_disable_device - Disable all the endpoints for a USB device
792 * @dev: the device whose endpoints are being disabled
793 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
795 * Disables all the device's endpoints, potentially including endpoint 0.
796 * Deallocates hcd/hardware state for the endpoints (nuking all or most
797 * pending urbs) and usbcore state for the interfaces, so that usbcore
798 * must usb_set_configuration() before any interfaces could be used.
800 void usb_disable_device(struct usb_device *dev, int skip_ep0)
804 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
805 skip_ep0 ? "non-ep0" : "all");
806 for (i = skip_ep0; i < 16; ++i) {
807 usb_disable_endpoint(dev, i);
808 usb_disable_endpoint(dev, i + USB_DIR_IN);
810 dev->toggle[0] = dev->toggle[1] = 0;
811 dev->halted[0] = dev->halted[1] = 0;
813 /* getting rid of interfaces will disconnect
814 * any drivers bound to them (a key side effect)
816 if (dev->actconfig) {
817 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
818 struct usb_interface *interface;
820 /* remove this interface */
821 interface = dev->actconfig->interface[i];
822 dev_dbg (&dev->dev, "unregistering interface %s\n",
823 interface->dev.bus_id);
824 device_del(&interface->dev);
827 if (dev->state == USB_STATE_CONFIGURED)
828 dev->state = USB_STATE_ADDRESS;
834 * usb_enable_endpoint - Enable an endpoint for USB communications
835 * @dev: the device whose interface is being enabled
836 * @epd: pointer to the endpoint descriptor
838 * Marks the endpoint as running, resets its toggle, and stores
839 * its maxpacket value. For control endpoints, both the input
840 * and output sides are handled.
842 void usb_enable_endpoint(struct usb_device *dev,
843 struct usb_endpoint_descriptor *epd)
845 int maxsize = epd->wMaxPacketSize;
846 unsigned int epaddr = epd->bEndpointAddress;
847 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
848 int is_control = ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
849 USB_ENDPOINT_XFER_CONTROL);
851 if (usb_endpoint_out(epaddr) || is_control) {
852 usb_endpoint_running(dev, epnum, 1);
853 usb_settoggle(dev, epnum, 1, 0);
854 dev->epmaxpacketout[epnum] = maxsize;
856 if (!usb_endpoint_out(epaddr) || is_control) {
857 usb_endpoint_running(dev, epnum, 0);
858 usb_settoggle(dev, epnum, 0, 0);
859 dev->epmaxpacketin[epnum] = maxsize;
864 * usb_enable_interface - Enable all the endpoints for an interface
865 * @dev: the device whose interface is being enabled
866 * @intf: pointer to the interface descriptor
868 * Enables all the endpoints for the interface's current altsetting.
870 void usb_enable_interface(struct usb_device *dev,
871 struct usb_interface *intf)
873 struct usb_host_interface *hintf =
874 &intf->altsetting[intf->act_altsetting];
877 for (i = 0; i < hintf->desc.bNumEndpoints; ++i)
878 usb_enable_endpoint(dev, &hintf->endpoint[i].desc);
882 * usb_set_interface - Makes a particular alternate setting be current
883 * @dev: the device whose interface is being updated
884 * @interface: the interface being updated
885 * @alternate: the setting being chosen.
886 * Context: !in_interrupt ()
888 * This is used to enable data transfers on interfaces that may not
889 * be enabled by default. Not all devices support such configurability.
890 * Only the driver bound to an interface may change its setting.
892 * Within any given configuration, each interface may have several
893 * alternative settings. These are often used to control levels of
894 * bandwidth consumption. For example, the default setting for a high
895 * speed interrupt endpoint may not send more than 64 bytes per microframe,
896 * while interrupt transfers of up to 3KBytes per microframe are legal.
897 * Also, isochronous endpoints may never be part of an
898 * interface's default setting. To access such bandwidth, alternate
899 * interface settings must be made current.
901 * Note that in the Linux USB subsystem, bandwidth associated with
902 * an endpoint in a given alternate setting is not reserved until an URB
903 * is submitted that needs that bandwidth. Some other operating systems
904 * allocate bandwidth early, when a configuration is chosen.
906 * This call is synchronous, and may not be used in an interrupt context.
907 * Also, drivers must not change altsettings while urbs are scheduled for
908 * endpoints in that interface; all such urbs must first be completed
909 * (perhaps forced by unlinking).
911 * Returns zero on success, or else the status code returned by the
912 * underlying usb_control_msg() call.
914 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
916 struct usb_interface *iface;
920 iface = usb_ifnum_to_if(dev, interface);
922 warn("selecting invalid interface %d", interface);
926 if (alternate < 0 || alternate >= iface->num_altsetting)
929 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
930 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
931 iface->altsetting[alternate]
932 .desc.bAlternateSetting,
933 interface, NULL, 0, HZ * 5);
935 /* 9.4.10 says devices don't need this and are free to STALL the
936 * request if the interface only has one alternate setting.
938 if (ret == -EPIPE && iface->num_altsetting == 1) {
939 dbg("manual set_interface for dev %d, iface %d, alt %d",
940 dev->devnum, interface, alternate);
945 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
946 * when they implement async or easily-killable versions of this or
947 * other "should-be-internal" functions (like clear_halt).
948 * should hcd+usbcore postprocess control requests?
951 /* prevent submissions using previous endpoint settings */
952 usb_disable_interface(dev, iface);
954 iface->act_altsetting = alternate;
956 /* If the interface only has one altsetting and the device didn't
957 * accept the request, we attempt to carry out the equivalent action
958 * by manually clearing the HALT feature for each endpoint in the
962 struct usb_host_interface *iface_as =
963 &iface->altsetting[alternate];
966 for (i = 0; i < iface_as->desc.bNumEndpoints; i++) {
967 unsigned int epaddr =
968 iface_as->endpoint[i].desc.bEndpointAddress;
970 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
971 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
973 usb_clear_halt(dev, pipe);
977 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
980 * Despite EP0 is always present in all interfaces/AS, the list of
981 * endpoints from the descriptor does not contain EP0. Due to its
982 * omnipresence one might expect EP0 being considered "affected" by
983 * any SetInterface request and hence assume toggles need to be reset.
984 * However, EP0 toggles are re-synced for every individual transfer
985 * during the SETUP stage - hence EP0 toggles are "don't care" here.
986 * (Likewise, EP0 never "halts" on well designed devices.)
988 usb_enable_interface(dev, iface);
994 * usb_reset_configuration - lightweight device reset
995 * @dev: the device whose configuration is being reset
997 * This issues a standard SET_CONFIGURATION request to the device using
998 * the current configuration. The effect is to reset most USB-related
999 * state in the device, including interface altsettings (reset to zero),
1000 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1001 * endpoints). Other usbcore state is unchanged, including bindings of
1002 * usb device drivers to interfaces.
1004 * Because this affects multiple interfaces, avoid using this with composite
1005 * (multi-interface) devices. Instead, the driver for each interface may
1006 * use usb_set_interface() on the interfaces it claims. Resetting the whole
1007 * configuration would affect other drivers' interfaces.
1009 * Returns zero on success, else a negative error code.
1011 int usb_reset_configuration(struct usb_device *dev)
1014 struct usb_host_config *config;
1016 /* caller must own dev->serialize (config won't change)
1017 * and the usb bus readlock (so driver bindings are stable);
1018 * so calls during probe() are fine
1021 for (i = 1; i < 16; ++i) {
1022 usb_disable_endpoint(dev, i);
1023 usb_disable_endpoint(dev, i + USB_DIR_IN);
1026 config = dev->actconfig;
1027 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1028 USB_REQ_SET_CONFIGURATION, 0,
1029 config->desc.bConfigurationValue, 0,
1030 NULL, 0, HZ * USB_CTRL_SET_TIMEOUT);
1032 dev->state = USB_STATE_ADDRESS;
1036 dev->toggle[0] = dev->toggle[1] = 0;
1037 dev->halted[0] = dev->halted[1] = 0;
1039 /* re-init hc/hcd interface/endpoint state */
1040 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1041 struct usb_interface *intf = config->interface[i];
1043 intf->act_altsetting = 0;
1044 usb_enable_interface(dev, intf);
1050 * usb_set_configuration - Makes a particular device setting be current
1051 * @dev: the device whose configuration is being updated
1052 * @configuration: the configuration being chosen.
1053 * Context: !in_interrupt ()
1055 * This is used to enable non-default device modes. Not all devices
1056 * use this kind of configurability; many devices only have one
1059 * USB device configurations may affect Linux interoperability,
1060 * power consumption and the functionality available. For example,
1061 * the default configuration is limited to using 100mA of bus power,
1062 * so that when certain device functionality requires more power,
1063 * and the device is bus powered, that functionality should be in some
1064 * non-default device configuration. Other device modes may also be
1065 * reflected as configuration options, such as whether two ISDN
1066 * channels are available independently; and choosing between open
1067 * standard device protocols (like CDC) or proprietary ones.
1069 * Note that USB has an additional level of device configurability,
1070 * associated with interfaces. That configurability is accessed using
1071 * usb_set_interface().
1073 * This call is synchronous. The calling context must be able to sleep,
1074 * and must not hold the driver model lock for USB; usb device driver
1075 * probe() methods may not use this routine.
1077 * Returns zero on success, or else the status code returned by the
1078 * underlying call that failed. On succesful completion, each interface
1079 * in the original device configuration has been destroyed, and each one
1080 * in the new configuration has been probed by all relevant usb device
1081 * drivers currently known to the kernel.
1083 int usb_set_configuration(struct usb_device *dev, int configuration)
1086 struct usb_host_config *cp = NULL;
1088 /* dev->serialize guards all config changes */
1089 down(&dev->serialize);
1091 for (i=0; i<dev->descriptor.bNumConfigurations; i++) {
1092 if (dev->config[i].desc.bConfigurationValue == configuration) {
1093 cp = &dev->config[i];
1097 if ((!cp && configuration != 0)) {
1102 /* The USB spec says configuration 0 means unconfigured.
1103 * But if a device includes a configuration numbered 0,
1104 * we will accept it as a correctly configured state.
1106 if (cp && configuration == 0)
1107 dev_warn(&dev->dev, "config 0 descriptor??\n");
1109 /* if it's already configured, clear out old state first.
1110 * getting rid of old interfaces means unbinding their drivers.
1112 if (dev->state != USB_STATE_ADDRESS)
1113 usb_disable_device (dev, 1); // Skip ep0
1115 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1116 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1117 NULL, 0, HZ * USB_CTRL_SET_TIMEOUT)) < 0)
1120 dev->actconfig = cp;
1122 dev->state = USB_STATE_ADDRESS;
1124 dev->state = USB_STATE_CONFIGURED;
1126 /* re-initialize hc/hcd/usbcore interface/endpoint state.
1127 * this triggers binding of drivers to interfaces; and
1128 * maybe probe() calls will choose different altsettings.
1130 for (i = 0; i < cp->desc.bNumInterfaces; ++i) {
1131 struct usb_interface *intf = cp->interface[i];
1132 struct usb_interface_descriptor *desc;
1134 intf->act_altsetting = 0;
1135 desc = &intf->altsetting [0].desc;
1136 usb_enable_interface(dev, intf);
1138 intf->dev.parent = &dev->dev;
1139 intf->dev.driver = NULL;
1140 intf->dev.bus = &usb_bus_type;
1141 intf->dev.dma_mask = dev->dev.dma_mask;
1142 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1143 dev->bus->busnum, dev->devpath,
1145 desc->bInterfaceNumber);
1147 "registering %s (config #%d, interface %d)\n",
1148 intf->dev.bus_id, configuration,
1149 desc->bInterfaceNumber);
1150 device_add (&intf->dev);
1151 usb_create_driverfs_intf_files (intf);
1156 up(&dev->serialize);
1161 * usb_string - returns ISO 8859-1 version of a string descriptor
1162 * @dev: the device whose string descriptor is being retrieved
1163 * @index: the number of the descriptor
1164 * @buf: where to put the string
1165 * @size: how big is "buf"?
1166 * Context: !in_interrupt ()
1168 * This converts the UTF-16LE encoded strings returned by devices, from
1169 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
1170 * that are more usable in most kernel contexts. Note that all characters
1171 * in the chosen descriptor that can't be encoded using ISO-8859-1
1172 * are converted to the question mark ("?") character, and this function
1173 * chooses strings in the first language supported by the device.
1175 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
1176 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
1177 * and is appropriate for use many uses of English and several other
1178 * Western European languages. (But it doesn't include the "Euro" symbol.)
1180 * This call is synchronous, and may not be used in an interrupt context.
1182 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
1184 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
1186 unsigned char *tbuf;
1188 unsigned int u, idx;
1190 if (size <= 0 || !buf || !index)
1193 tbuf = kmalloc(256, GFP_KERNEL);
1197 /* get langid for strings if it's not yet known */
1198 if (!dev->have_langid) {
1199 err = usb_get_string(dev, 0, 0, tbuf, 4);
1201 err("error getting string descriptor 0 (error=%d)", err);
1203 } else if (err < 4 || tbuf[0] < 4) {
1204 err("string descriptor 0 too short");
1208 dev->have_langid = -1;
1209 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
1210 /* always use the first langid listed */
1211 dbg("USB device number %d default language ID 0x%x",
1212 dev->devnum, dev->string_langid);
1217 * ask for the length of the string
1220 err = usb_get_string(dev, dev->string_langid, index, tbuf, 2);
1225 err = usb_get_string(dev, dev->string_langid, index, tbuf, len);
1229 size--; /* leave room for trailing NULL char in output buffer */
1230 for (idx = 0, u = 2; u < err; u += 2) {
1233 if (tbuf[u+1]) /* high byte */
1234 buf[idx++] = '?'; /* non ISO-8859-1 character */
1236 buf[idx++] = tbuf[u];
1246 // synchronous request completion model
1247 EXPORT_SYMBOL(usb_control_msg);
1248 EXPORT_SYMBOL(usb_bulk_msg);
1250 EXPORT_SYMBOL(usb_sg_init);
1251 EXPORT_SYMBOL(usb_sg_cancel);
1252 EXPORT_SYMBOL(usb_sg_wait);
1254 // synchronous control message convenience routines
1255 EXPORT_SYMBOL(usb_get_descriptor);
1256 EXPORT_SYMBOL(usb_get_status);
1257 EXPORT_SYMBOL(usb_get_string);
1258 EXPORT_SYMBOL(usb_string);
1260 // synchronous calls that also maintain usbcore state
1261 EXPORT_SYMBOL(usb_clear_halt);
1262 EXPORT_SYMBOL(usb_reset_configuration);
1263 EXPORT_SYMBOL(usb_set_configuration);
1264 EXPORT_SYMBOL(usb_set_interface);