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
);
57 #if 0 // mask by Victor Yu. 06-13-20077
63 timer
.expires
= jiffies
+ timeout
;
64 timer
.data
= (unsigned long)urb
;
65 timer
.function
= timeout_kill
;
66 /* grr. timeout _should_ include submit delays. */
69 wait_for_completion(&done
);
71 /* note: HCDs return ETIMEDOUT for other reasons too */
72 if (status
== -ECONNRESET
)
75 del_timer_sync(&timer
);
79 *actual_length
= urb
->actual_length
;
84 /*-------------------------------------------------------------------*/
85 // returns status (negative) or length (positive)
86 int usb_internal_control_msg(struct usb_device
*usb_dev
, unsigned int pipe
,
87 struct usb_ctrlrequest
*cmd
, void *data
, int len
, int timeout
)
94 urb
= usb_alloc_urb(0, GFP_NOIO
);
100 usb_fill_control_urb(urb
, usb_dev
, pipe
, (unsigned char *)cmd
, data
,
101 len
, usb_api_blocking_completion
, NULL
);
104 retv
= usb_start_wait_urb(urb
, timeout
, &length
);
115 * usb_control_msg - Builds a control urb, sends it off and waits for completion
116 * @dev: pointer to the usb device to send the message to
117 * @pipe: endpoint "pipe" to send the message to
118 * @request: USB message request value
119 * @requesttype: USB message request type value
120 * @value: USB message value
121 * @index: USB message index value
122 * @data: pointer to the data to send
123 * @size: length in bytes of the data to send
124 * @timeout: time in jiffies to wait for the message to complete before
125 * timing out (if 0 the wait is forever)
126 * Context: !in_interrupt ()
128 * This function sends a simple control message to a specified endpoint
129 * and waits for the message to complete, or timeout.
131 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
133 * Don't use this function from within an interrupt context, like a
134 * bottom half handler. If you need an asynchronous message, or need to send
135 * a message from within interrupt context, use usb_submit_urb()
136 * If a thread in your driver uses this call, make sure your disconnect()
137 * method can wait for it to complete. Since you don't have a handle on
138 * the URB used, you can't cancel the request.
140 int usb_control_msg(struct usb_device
*dev
, unsigned int pipe
, __u8 request
, __u8 requesttype
,
141 __u16 value
, __u16 index
, void *data
, __u16 size
, int timeout
)
143 struct usb_ctrlrequest
*dr
= kmalloc(sizeof(struct usb_ctrlrequest
), GFP_NOIO
);
149 dr
->bRequestType
= requesttype
;
150 dr
->bRequest
= request
;
151 dr
->wValue
= cpu_to_le16p(&value
);
152 dr
->wIndex
= cpu_to_le16p(&index
);
153 dr
->wLength
= cpu_to_le16p(&size
);
155 //dbg("usb_control_msg");
158 ret
= usb_internal_control_msg(dev
, pipe
, dr
, data
, size
, timeout
);
168 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
169 * @usb_dev: pointer to the usb device to send the message to
170 * @pipe: endpoint "pipe" to send the message to
171 * @data: pointer to the data to send
172 * @len: length in bytes of the data to send
173 * @actual_length: pointer to a location to put the actual length transferred in bytes
174 * @timeout: time in jiffies to wait for the message to complete before
175 * timing out (if 0 the wait is forever)
176 * Context: !in_interrupt ()
178 * This function sends a simple bulk message to a specified endpoint
179 * and waits for the message to complete, or timeout.
181 * If successful, it returns 0, otherwise a negative error number.
182 * The number of actual bytes transferred will be stored in the
183 * actual_length paramater.
185 * Don't use this function from within an interrupt context, like a
186 * bottom half handler. If you need an asynchronous message, or need to
187 * send a message from within interrupt context, use usb_submit_urb()
188 * If a thread in your driver uses this call, make sure your disconnect()
189 * method can wait for it to complete. Since you don't have a handle on
190 * the URB used, you can't cancel the request.
192 int usb_bulk_msg(struct usb_device
*usb_dev
, unsigned int pipe
,
193 void *data
, int len
, int *actual_length
, int timeout
)
200 urb
=usb_alloc_urb(0, GFP_KERNEL
);
204 usb_fill_bulk_urb(urb
, usb_dev
, pipe
, data
, len
,
205 usb_api_blocking_completion
, NULL
);
207 return usb_start_wait_urb(urb
,timeout
,actual_length
);
210 /*-------------------------------------------------------------------*/
212 static void sg_clean (struct usb_sg_request
*io
)
215 while (io
->entries
--)
216 usb_free_urb (io
->urbs
[io
->entries
]);
220 if (io
->dev
->dev
.dma_mask
!= 0)
221 usb_buffer_unmap_sg (io
->dev
, io
->pipe
, io
->sg
, io
->nents
);
225 static void sg_complete (struct urb
*urb
, struct pt_regs
*regs
)
227 struct usb_sg_request
*io
= (struct usb_sg_request
*) urb
->context
;
229 spin_lock (&io
->lock
);
231 /* In 2.5 we require hcds' endpoint queues not to progress after fault
232 * reports, until the completion callback (this!) returns. That lets
233 * device driver code (like this routine) unlink queued urbs first,
234 * if it needs to, since the HC won't work on them at all. So it's
235 * not possible for page N+1 to overwrite page N, and so on.
237 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
238 * complete before the HCD can get requests away from hardware,
239 * though never during cleanup after a hard fault.
242 && (io
->status
!= -ECONNRESET
243 || urb
->status
!= -ECONNRESET
)
244 && urb
->actual_length
) {
245 dev_err (io
->dev
->bus
->controller
,
246 "dev %s ep%d%s scatterlist error %d/%d\n",
248 usb_pipeendpoint (urb
->pipe
),
249 usb_pipein (urb
->pipe
) ? "in" : "out",
250 urb
->status
, io
->status
);
254 if (urb
->status
&& urb
->status
!= -ECONNRESET
) {
255 int i
, found
, status
;
257 io
->status
= urb
->status
;
259 /* the previous urbs, and this one, completed already.
260 * unlink pending urbs so they won't rx/tx bad data.
262 for (i
= 0, found
= 0; i
< io
->entries
; i
++) {
263 if (!io
->urbs
[i
] || !io
->urbs
[i
]->dev
)
266 status
= usb_unlink_urb (io
->urbs
[i
]);
267 if (status
!= -EINPROGRESS
&& status
!= -EBUSY
)
268 dev_err (&io
->dev
->dev
,
269 "%s, unlink --> %d\n",
270 __FUNCTION__
, status
);
271 } else if (urb
== io
->urbs
[i
])
277 /* on the last completion, signal usb_sg_wait() */
278 io
->bytes
+= urb
->actual_length
;
281 complete (&io
->complete
);
283 spin_unlock (&io
->lock
);
288 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
289 * @io: request block being initialized. until usb_sg_wait() returns,
290 * treat this as a pointer to an opaque block of memory,
291 * @dev: the usb device that will send or receive the data
292 * @pipe: endpoint "pipe" used to transfer the data
293 * @period: polling rate for interrupt endpoints, in frames or
294 * (for high speed endpoints) microframes; ignored for bulk
295 * @sg: scatterlist entries
296 * @nents: how many entries in the scatterlist
297 * @length: how many bytes to send from the scatterlist, or zero to
298 * send every byte identified in the list.
299 * @mem_flags: SLAB_* flags affecting memory allocations in this call
301 * Returns zero for success, else a negative errno value. This initializes a
302 * scatter/gather request, allocating resources such as I/O mappings and urb
303 * memory (except maybe memory used by USB controller drivers).
305 * The request must be issued using usb_sg_wait(), which waits for the I/O to
306 * complete (or to be canceled) and then cleans up all resources allocated by
309 * The request may be canceled with usb_sg_cancel(), either before or after
310 * usb_sg_wait() is called.
313 struct usb_sg_request
*io
,
314 struct usb_device
*dev
,
317 struct scatterlist
*sg
,
327 if (!io
|| !dev
|| !sg
328 || usb_pipecontrol (pipe
)
329 || usb_pipeisoc (pipe
)
333 spin_lock_init (&io
->lock
);
339 /* not all host controllers use DMA (like the mainstream pci ones);
340 * they can use PIO (sl811) or be software over another transport.
342 dma
= (dev
->dev
.dma_mask
!= 0);
344 io
->entries
= usb_buffer_map_sg (dev
, pipe
, sg
, nents
);
348 /* initialize all the urbs we'll use */
349 if (io
->entries
<= 0)
352 io
->count
= io
->entries
;
353 io
->urbs
= kmalloc (io
->entries
* sizeof *io
->urbs
, mem_flags
);
357 urb_flags
= URB_ASYNC_UNLINK
| URB_NO_TRANSFER_DMA_MAP
359 if (usb_pipein (pipe
))
360 urb_flags
|= URB_SHORT_NOT_OK
;
362 for (i
= 0; i
< io
->entries
; i
++) {
365 io
->urbs
[i
] = usb_alloc_urb (0, mem_flags
);
371 io
->urbs
[i
]->dev
= NULL
;
372 io
->urbs
[i
]->pipe
= pipe
;
373 io
->urbs
[i
]->interval
= period
;
374 io
->urbs
[i
]->transfer_flags
= urb_flags
;
376 io
->urbs
[i
]->complete
= sg_complete
;
377 io
->urbs
[i
]->context
= io
;
378 io
->urbs
[i
]->status
= -EINPROGRESS
;
379 io
->urbs
[i
]->actual_length
= 0;
382 /* hc may use _only_ transfer_dma */
383 io
->urbs
[i
]->transfer_dma
= sg_dma_address (sg
+ i
);
384 len
= sg_dma_len (sg
+ i
);
386 /* hc may use _only_ transfer_buffer */
387 io
->urbs
[i
]->transfer_buffer
=
388 page_address (sg
[i
].page
) + sg
[i
].offset
;
393 len
= min_t (unsigned, len
, length
);
398 io
->urbs
[i
]->transfer_buffer_length
= len
;
400 io
->urbs
[--i
]->transfer_flags
&= ~URB_NO_INTERRUPT
;
402 /* transaction state */
405 init_completion (&io
->complete
);
415 * usb_sg_wait - synchronously execute scatter/gather request
416 * @io: request block handle, as initialized with usb_sg_init().
417 * some fields become accessible when this call returns.
418 * Context: !in_interrupt ()
420 * This function blocks until the specified I/O operation completes. It
421 * leverages the grouping of the related I/O requests to get good transfer
422 * rates, by queueing the requests. At higher speeds, such queuing can
423 * significantly improve USB throughput.
425 * There are three kinds of completion for this function.
426 * (1) success, where io->status is zero. The number of io->bytes
427 * transferred is as requested.
428 * (2) error, where io->status is a negative errno value. The number
429 * of io->bytes transferred before the error is usually less
430 * than requested, and can be nonzero.
431 * (3) cancelation, a type of error with status -ECONNRESET that
432 * is initiated by usb_sg_cancel().
434 * When this function returns, all memory allocated through usb_sg_init() or
435 * this call will have been freed. The request block parameter may still be
436 * passed to usb_sg_cancel(), or it may be freed. It could also be
437 * reinitialized and then reused.
439 * Data Transfer Rates:
441 * Bulk transfers are valid for full or high speed endpoints.
442 * The best full speed data rate is 19 packets of 64 bytes each
443 * per frame, or 1216 bytes per millisecond.
444 * The best high speed data rate is 13 packets of 512 bytes each
445 * per microframe, or 52 KBytes per millisecond.
447 * The reason to use interrupt transfers through this API would most likely
448 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
449 * could be transferred. That capability is less useful for low or full
450 * speed interrupt endpoints, which allow at most one packet per millisecond,
451 * of at most 8 or 64 bytes (respectively).
453 void usb_sg_wait (struct usb_sg_request
*io
)
455 int i
, entries
= io
->entries
;
457 /* queue the urbs. */
458 spin_lock_irq (&io
->lock
);
459 for (i
= 0; i
< entries
&& !io
->status
; i
++) {
462 io
->urbs
[i
]->dev
= io
->dev
;
463 retval
= usb_submit_urb (io
->urbs
[i
], SLAB_ATOMIC
);
465 /* after we submit, let completions or cancelations fire;
466 * we handshake using io->status.
468 spin_unlock_irq (&io
->lock
);
470 /* maybe we retrying will recover */
471 case -ENXIO
: // hc didn't queue this one
474 io
->urbs
[i
]->dev
= NULL
;
480 /* no error? continue immediately.
482 * NOTE: to work better with UHCI (4K I/O buffer may
483 * need 3K of TDs) it may be good to limit how many
484 * URBs are queued at once; N milliseconds?
490 /* fail any uncompleted urbs */
492 io
->urbs
[i
]->dev
= NULL
;
493 io
->urbs
[i
]->status
= retval
;
494 dev_dbg (&io
->dev
->dev
, "%s, submit --> %d\n",
495 __FUNCTION__
, retval
);
498 spin_lock_irq (&io
->lock
);
499 if (retval
&& (io
->status
== 0 || io
->status
== -ECONNRESET
))
502 io
->count
-= entries
- i
;
504 complete (&io
->complete
);
505 spin_unlock_irq (&io
->lock
);
507 /* OK, yes, this could be packaged as non-blocking.
508 * So could the submit loop above ... but it's easier to
509 * solve neither problem than to solve both!
511 wait_for_completion (&io
->complete
);
517 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
518 * @io: request block, initialized with usb_sg_init()
520 * This stops a request after it has been started by usb_sg_wait().
521 * It can also prevents one initialized by usb_sg_init() from starting,
522 * so that call just frees resources allocated to the request.
524 void usb_sg_cancel (struct usb_sg_request
*io
)
528 spin_lock_irqsave (&io
->lock
, flags
);
530 /* shut everything down, if it didn't already */
534 io
->status
= -ECONNRESET
;
535 for (i
= 0; i
< io
->entries
; i
++) {
538 if (!io
->urbs
[i
]->dev
)
540 retval
= usb_unlink_urb (io
->urbs
[i
]);
541 if (retval
!= -EINPROGRESS
&& retval
!= -EBUSY
)
542 dev_warn (&io
->dev
->dev
, "%s, unlink --> %d\n",
543 __FUNCTION__
, retval
);
546 spin_unlock_irqrestore (&io
->lock
, flags
);
549 /*-------------------------------------------------------------------*/
552 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
553 * @dev: the device whose descriptor is being retrieved
554 * @type: the descriptor type (USB_DT_*)
555 * @index: the number of the descriptor
556 * @buf: where to put the descriptor
557 * @size: how big is "buf"?
558 * Context: !in_interrupt ()
560 * Gets a USB descriptor. Convenience functions exist to simplify
561 * getting some types of descriptors. Use
562 * usb_get_device_descriptor() for USB_DT_DEVICE (not exported),
563 * and usb_get_string() or usb_string() for USB_DT_STRING.
564 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
565 * are part of the device structure.
566 * In addition to a number of USB-standard descriptors, some
567 * devices also use class-specific or vendor-specific descriptors.
569 * This call is synchronous, and may not be used in an interrupt context.
571 * Returns the number of bytes received on success, or else the status code
572 * returned by the underlying usb_control_msg() call.
574 int usb_get_descriptor(struct usb_device
*dev
, unsigned char type
, unsigned char index
, void *buf
, int size
)
579 memset(buf
,0,size
); // Make sure we parse really received data
581 for (i
= 0; i
< 3; ++i
) {
582 /* retry on length 0 or stall; some devices are flakey */
583 result
= usb_control_msg(dev
, usb_rcvctrlpipe(dev
, 0),
584 USB_REQ_GET_DESCRIPTOR
, USB_DIR_IN
,
585 (type
<< 8) + index
, 0, buf
, size
,
586 HZ
* USB_CTRL_GET_TIMEOUT
);
587 if (result
== 0 || result
== -EPIPE
)
589 if (result
> 1 && ((u8
*)buf
)[1] != type
) {
599 * usb_get_string - gets a string descriptor
600 * @dev: the device whose string descriptor is being retrieved
601 * @langid: code for language chosen (from string descriptor zero)
602 * @index: the number of the descriptor
603 * @buf: where to put the string
604 * @size: how big is "buf"?
605 * Context: !in_interrupt ()
607 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
608 * in little-endian byte order).
609 * The usb_string() function will often be a convenient way to turn
610 * these strings into kernel-printable form.
612 * Strings may be referenced in device, configuration, interface, or other
613 * descriptors, and could also be used in vendor-specific ways.
615 * This call is synchronous, and may not be used in an interrupt context.
617 * Returns the number of bytes received on success, or else the status code
618 * returned by the underlying usb_control_msg() call.
620 int usb_get_string(struct usb_device
*dev
, unsigned short langid
,
621 unsigned char index
, void *buf
, int size
)
626 for (i
= 0; i
< 3; ++i
) {
627 /* retry on length 0 or stall; some devices are flakey */
628 result
= usb_control_msg(dev
, usb_rcvctrlpipe(dev
, 0),
629 USB_REQ_GET_DESCRIPTOR
, USB_DIR_IN
,
630 (USB_DT_STRING
<< 8) + index
, langid
, buf
, size
,
631 HZ
* USB_CTRL_GET_TIMEOUT
);
632 if (!(result
== 0 || result
== -EPIPE
))
638 static int usb_string_sub(struct usb_device
*dev
, unsigned int langid
,
639 unsigned int index
, unsigned char *buf
)
643 /* Try to read the string descriptor by asking for the maximum
644 * possible number of bytes */
645 rc
= usb_get_string(dev
, langid
, index
, buf
, 255);
647 /* If that failed try to read the descriptor length, then
648 * ask for just that many bytes */
650 rc
= usb_get_string(dev
, langid
, index
, buf
, 2);
652 rc
= usb_get_string(dev
, langid
, index
, buf
, buf
[0]);
656 /* There might be extra junk at the end of the descriptor */
666 * usb_string - returns ISO 8859-1 version of a string descriptor
667 * @dev: the device whose string descriptor is being retrieved
668 * @index: the number of the descriptor
669 * @buf: where to put the string
670 * @size: how big is "buf"?
671 * Context: !in_interrupt ()
673 * This converts the UTF-16LE encoded strings returned by devices, from
674 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
675 * that are more usable in most kernel contexts. Note that all characters
676 * in the chosen descriptor that can't be encoded using ISO-8859-1
677 * are converted to the question mark ("?") character, and this function
678 * chooses strings in the first language supported by the device.
680 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
681 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
682 * and is appropriate for use many uses of English and several other
683 * Western European languages. (But it doesn't include the "Euro" symbol.)
685 * This call is synchronous, and may not be used in an interrupt context.
687 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
689 int usb_string(struct usb_device
*dev
, int index
, char *buf
, size_t size
)
695 if (size
<= 0 || !buf
|| !index
)
698 tbuf
= kmalloc(256, GFP_KERNEL
);
702 /* get langid for strings if it's not yet known */
703 if (!dev
->have_langid
) {
704 err
= usb_string_sub(dev
, 0, 0, tbuf
);
707 "string descriptor 0 read error: %d\n",
710 } else if (err
< 4) {
711 dev_err (&dev
->dev
, "string descriptor 0 too short\n");
715 dev
->have_langid
= -1;
716 dev
->string_langid
= tbuf
[2] | (tbuf
[3]<< 8);
717 /* always use the first langid listed */
718 dev_dbg (&dev
->dev
, "default language 0x%04x\n",
723 err
= usb_string_sub(dev
, dev
->string_langid
, index
, tbuf
);
727 size
--; /* leave room for trailing NULL char in output buffer */
728 for (idx
= 0, u
= 2; u
< err
; u
+= 2) {
731 if (tbuf
[u
+1]) /* high byte */
732 buf
[idx
++] = '?'; /* non ISO-8859-1 character */
734 buf
[idx
++] = tbuf
[u
];
745 * usb_get_device_descriptor - (re)reads the device descriptor
746 * @dev: the device whose device descriptor is being updated
747 * @size: how much of the descriptor to read
748 * Context: !in_interrupt ()
750 * Updates the copy of the device descriptor stored in the device structure,
751 * which dedicates space for this purpose. Note that several fields are
752 * converted to the host CPU's byte order: the USB version (bcdUSB), and
753 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
754 * That lets device drivers compare against non-byteswapped constants.
756 * Not exported, only for use by the core. If drivers really want to read
757 * the device descriptor directly, they can call usb_get_descriptor() with
758 * type = USB_DT_DEVICE and index = 0.
760 * This call is synchronous, and may not be used in an interrupt context.
762 * Returns the number of bytes received on success, or else the status code
763 * returned by the underlying usb_control_msg() call.
765 int usb_get_device_descriptor(struct usb_device
*dev
, unsigned int size
)
767 struct usb_device_descriptor
*desc
;
770 if (size
> sizeof(*desc
))
772 desc
= kmalloc(sizeof(*desc
), GFP_NOIO
);
776 ret
= usb_get_descriptor(dev
, USB_DT_DEVICE
, 0, desc
, size
);
778 le16_to_cpus(&desc
->bcdUSB
);
779 le16_to_cpus(&desc
->idVendor
);
780 le16_to_cpus(&desc
->idProduct
);
781 le16_to_cpus(&desc
->bcdDevice
);
782 memcpy(&dev
->descriptor
, desc
, size
);
789 * usb_get_status - issues a GET_STATUS call
790 * @dev: the device whose status is being checked
791 * @type: USB_RECIP_*; for device, interface, or endpoint
792 * @target: zero (for device), else interface or endpoint number
793 * @data: pointer to two bytes of bitmap data
794 * Context: !in_interrupt ()
796 * Returns device, interface, or endpoint status. Normally only of
797 * interest to see if the device is self powered, or has enabled the
798 * remote wakeup facility; or whether a bulk or interrupt endpoint
799 * is halted ("stalled").
801 * Bits in these status bitmaps are set using the SET_FEATURE request,
802 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
803 * function should be used to clear halt ("stall") status.
805 * This call is synchronous, and may not be used in an interrupt context.
807 * Returns the number of bytes received on success, or else the status code
808 * returned by the underlying usb_control_msg() call.
810 int usb_get_status(struct usb_device
*dev
, int type
, int target
, void *data
)
812 return usb_control_msg(dev
, usb_rcvctrlpipe(dev
, 0),
813 USB_REQ_GET_STATUS
, USB_DIR_IN
| type
, 0, target
, data
, 2,
814 HZ
* USB_CTRL_GET_TIMEOUT
);
818 * usb_clear_halt - tells device to clear endpoint halt/stall condition
819 * @dev: device whose endpoint is halted
820 * @pipe: endpoint "pipe" being cleared
821 * Context: !in_interrupt ()
823 * This is used to clear halt conditions for bulk and interrupt endpoints,
824 * as reported by URB completion status. Endpoints that are halted are
825 * sometimes referred to as being "stalled". Such endpoints are unable
826 * to transmit or receive data until the halt status is cleared. Any URBs
827 * queued for such an endpoint should normally be unlinked by the driver
828 * before clearing the halt condition, as described in sections 5.7.5
829 * and 5.8.5 of the USB 2.0 spec.
831 * Note that control and isochronous endpoints don't halt, although control
832 * endpoints report "protocol stall" (for unsupported requests) using the
833 * same status code used to report a true stall.
835 * This call is synchronous, and may not be used in an interrupt context.
837 * Returns zero on success, or else the status code returned by the
838 * underlying usb_control_msg() call.
840 int usb_clear_halt(struct usb_device
*dev
, int pipe
)
843 int endp
= usb_pipeendpoint(pipe
);
845 if (usb_pipein (pipe
))
848 /* we don't care if it wasn't halted first. in fact some devices
849 * (like some ibmcam model 1 units) seem to expect hosts to make
850 * this request for iso endpoints, which can't halt!
852 result
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
853 USB_REQ_CLEAR_FEATURE
, USB_RECIP_ENDPOINT
,
854 USB_ENDPOINT_HALT
, endp
, NULL
, 0,
855 HZ
* USB_CTRL_SET_TIMEOUT
);
857 /* don't un-halt or force to DATA0 except on success */
861 /* NOTE: seems like Microsoft and Apple don't bother verifying
862 * the clear "took", so some devices could lock up if you check...
863 * such as the Hagiwara FlashGate DUAL. So we won't bother.
865 * NOTE: make sure the logic here doesn't diverge much from
866 * the copy in usb-storage, for as long as we need two copies.
869 /* toggle was reset by the clear */
870 usb_settoggle(dev
, usb_pipeendpoint(pipe
), usb_pipeout(pipe
), 0);
876 * usb_disable_endpoint -- Disable an endpoint by address
877 * @dev: the device whose endpoint is being disabled
878 * @epaddr: the endpoint's address. Endpoint number for output,
879 * endpoint number + USB_DIR_IN for input
881 * Deallocates hcd/hardware state for this endpoint ... and nukes all
884 * If the HCD hasn't registered a disable() function, this sets the
885 * endpoint's maxpacket size to 0 to prevent further submissions.
887 void usb_disable_endpoint(struct usb_device
*dev
, unsigned int epaddr
)
889 if (dev
&& dev
->bus
&& dev
->bus
->op
&& dev
->bus
->op
->disable
)
890 dev
->bus
->op
->disable(dev
, epaddr
);
892 unsigned int epnum
= epaddr
& USB_ENDPOINT_NUMBER_MASK
;
894 if (usb_endpoint_out(epaddr
))
895 dev
->epmaxpacketout
[epnum
] = 0;
897 dev
->epmaxpacketin
[epnum
] = 0;
902 * usb_disable_interface -- Disable all endpoints for an interface
903 * @dev: the device whose interface is being disabled
904 * @intf: pointer to the interface descriptor
906 * Disables all the endpoints for the interface's current altsetting.
908 void usb_disable_interface(struct usb_device
*dev
, struct usb_interface
*intf
)
910 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
913 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
) {
914 usb_disable_endpoint(dev
,
915 alt
->endpoint
[i
].desc
.bEndpointAddress
);
920 * usb_disable_device - Disable all the endpoints for a USB device
921 * @dev: the device whose endpoints are being disabled
922 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
924 * Disables all the device's endpoints, potentially including endpoint 0.
925 * Deallocates hcd/hardware state for the endpoints (nuking all or most
926 * pending urbs) and usbcore state for the interfaces, so that usbcore
927 * must usb_set_configuration() before any interfaces could be used.
929 void usb_disable_device(struct usb_device
*dev
, int skip_ep0
)
933 dev_dbg(&dev
->dev
, "%s nuking %s URBs\n", __FUNCTION__
,
934 skip_ep0
? "non-ep0" : "all");
935 for (i
= skip_ep0
; i
< 16; ++i
) {
936 usb_disable_endpoint(dev
, i
);
937 usb_disable_endpoint(dev
, i
+ USB_DIR_IN
);
939 dev
->toggle
[0] = dev
->toggle
[1] = 0;
941 /* getting rid of interfaces will disconnect
942 * any drivers bound to them (a key side effect)
944 if (dev
->actconfig
) {
945 for (i
= 0; i
< dev
->actconfig
->desc
.bNumInterfaces
; i
++) {
946 struct usb_interface
*interface
;
948 /* remove this interface */
949 interface
= dev
->actconfig
->interface
[i
];
950 dev_dbg (&dev
->dev
, "unregistering interface %s\n",
951 interface
->dev
.bus_id
);
952 usb_remove_sysfs_intf_files(interface
);
953 device_del (&interface
->dev
);
956 /* Now that the interfaces are unbound, nobody should
957 * try to access them.
959 for (i
= 0; i
< dev
->actconfig
->desc
.bNumInterfaces
; i
++) {
960 put_device (&dev
->actconfig
->interface
[i
]->dev
);
961 dev
->actconfig
->interface
[i
] = NULL
;
963 dev
->actconfig
= NULL
;
964 if (dev
->state
== USB_STATE_CONFIGURED
)
965 usb_set_device_state(dev
, USB_STATE_ADDRESS
);
971 * usb_enable_endpoint - Enable an endpoint for USB communications
972 * @dev: the device whose interface is being enabled
973 * @epd: pointer to the endpoint descriptor
975 * Resets the endpoint toggle and stores its maxpacket value.
976 * For control endpoints, both the input and output sides are handled.
978 void usb_enable_endpoint(struct usb_device
*dev
,
979 struct usb_endpoint_descriptor
*epd
)
981 int maxsize
= epd
->wMaxPacketSize
;
982 unsigned int epaddr
= epd
->bEndpointAddress
;
983 unsigned int epnum
= epaddr
& USB_ENDPOINT_NUMBER_MASK
;
984 int is_control
= ((epd
->bmAttributes
& USB_ENDPOINT_XFERTYPE_MASK
) ==
985 USB_ENDPOINT_XFER_CONTROL
);
987 if (usb_endpoint_out(epaddr
) || is_control
) {
988 usb_settoggle(dev
, epnum
, 1, 0);
989 dev
->epmaxpacketout
[epnum
] = maxsize
;
991 if (!usb_endpoint_out(epaddr
) || is_control
) {
992 usb_settoggle(dev
, epnum
, 0, 0);
993 dev
->epmaxpacketin
[epnum
] = maxsize
;
998 * usb_enable_interface - Enable all the endpoints for an interface
999 * @dev: the device whose interface is being enabled
1000 * @intf: pointer to the interface descriptor
1002 * Enables all the endpoints for the interface's current altsetting.
1004 void usb_enable_interface(struct usb_device
*dev
,
1005 struct usb_interface
*intf
)
1007 struct usb_host_interface
*alt
= intf
->cur_altsetting
;
1010 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; ++i
)
1011 usb_enable_endpoint(dev
, &alt
->endpoint
[i
].desc
);
1015 * usb_set_interface - Makes a particular alternate setting be current
1016 * @dev: the device whose interface is being updated
1017 * @interface: the interface being updated
1018 * @alternate: the setting being chosen.
1019 * Context: !in_interrupt ()
1021 * This is used to enable data transfers on interfaces that may not
1022 * be enabled by default. Not all devices support such configurability.
1023 * Only the driver bound to an interface may change its setting.
1025 * Within any given configuration, each interface may have several
1026 * alternative settings. These are often used to control levels of
1027 * bandwidth consumption. For example, the default setting for a high
1028 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1029 * while interrupt transfers of up to 3KBytes per microframe are legal.
1030 * Also, isochronous endpoints may never be part of an
1031 * interface's default setting. To access such bandwidth, alternate
1032 * interface settings must be made current.
1034 * Note that in the Linux USB subsystem, bandwidth associated with
1035 * an endpoint in a given alternate setting is not reserved until an URB
1036 * is submitted that needs that bandwidth. Some other operating systems
1037 * allocate bandwidth early, when a configuration is chosen.
1039 * This call is synchronous, and may not be used in an interrupt context.
1040 * Also, drivers must not change altsettings while urbs are scheduled for
1041 * endpoints in that interface; all such urbs must first be completed
1042 * (perhaps forced by unlinking).
1044 * Returns zero on success, or else the status code returned by the
1045 * underlying usb_control_msg() call.
1047 int usb_set_interface(struct usb_device
*dev
, int interface
, int alternate
)
1049 struct usb_interface
*iface
;
1050 struct usb_host_interface
*alt
;
1054 if (dev
->state
== USB_STATE_SUSPENDED
)
1055 return -EHOSTUNREACH
;
1057 iface
= usb_ifnum_to_if(dev
, interface
);
1059 dev_dbg(&dev
->dev
, "selecting invalid interface %d\n",
1064 alt
= usb_altnum_to_altsetting(iface
, alternate
);
1066 warn("selecting invalid altsetting %d", alternate
);
1070 ret
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1071 USB_REQ_SET_INTERFACE
, USB_RECIP_INTERFACE
,
1072 alternate
, interface
, NULL
, 0, HZ
* 5);
1074 /* 9.4.10 says devices don't need this and are free to STALL the
1075 * request if the interface only has one alternate setting.
1077 if (ret
== -EPIPE
&& iface
->num_altsetting
== 1) {
1079 "manual set_interface for iface %d, alt %d\n",
1080 interface
, alternate
);
1085 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1086 * when they implement async or easily-killable versions of this or
1087 * other "should-be-internal" functions (like clear_halt).
1088 * should hcd+usbcore postprocess control requests?
1091 /* prevent submissions using previous endpoint settings */
1092 usb_disable_interface(dev
, iface
);
1094 iface
->cur_altsetting
= alt
;
1096 /* If the interface only has one altsetting and the device didn't
1097 * accept the request, we attempt to carry out the equivalent action
1098 * by manually clearing the HALT feature for each endpoint in the
1104 for (i
= 0; i
< alt
->desc
.bNumEndpoints
; i
++) {
1105 unsigned int epaddr
=
1106 alt
->endpoint
[i
].desc
.bEndpointAddress
;
1108 __create_pipe(dev
, USB_ENDPOINT_NUMBER_MASK
& epaddr
)
1109 | (usb_endpoint_out(epaddr
) ? USB_DIR_OUT
: USB_DIR_IN
);
1111 usb_clear_halt(dev
, pipe
);
1115 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1118 * Despite EP0 is always present in all interfaces/AS, the list of
1119 * endpoints from the descriptor does not contain EP0. Due to its
1120 * omnipresence one might expect EP0 being considered "affected" by
1121 * any SetInterface request and hence assume toggles need to be reset.
1122 * However, EP0 toggles are re-synced for every individual transfer
1123 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1124 * (Likewise, EP0 never "halts" on well designed devices.)
1126 usb_enable_interface(dev
, iface
);
1132 * usb_reset_configuration - lightweight device reset
1133 * @dev: the device whose configuration is being reset
1135 * This issues a standard SET_CONFIGURATION request to the device using
1136 * the current configuration. The effect is to reset most USB-related
1137 * state in the device, including interface altsettings (reset to zero),
1138 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1139 * endpoints). Other usbcore state is unchanged, including bindings of
1140 * usb device drivers to interfaces.
1142 * Because this affects multiple interfaces, avoid using this with composite
1143 * (multi-interface) devices. Instead, the driver for each interface may
1144 * use usb_set_interface() on the interfaces it claims. Resetting the whole
1145 * configuration would affect other drivers' interfaces.
1147 * Returns zero on success, else a negative error code.
1149 int usb_reset_configuration(struct usb_device
*dev
)
1152 struct usb_host_config
*config
;
1154 if (dev
->state
== USB_STATE_SUSPENDED
)
1155 return -EHOSTUNREACH
;
1157 /* caller must own dev->serialize (config won't change)
1158 * and the usb bus readlock (so driver bindings are stable);
1159 * so calls during probe() are fine
1162 for (i
= 1; i
< 16; ++i
) {
1163 usb_disable_endpoint(dev
, i
);
1164 usb_disable_endpoint(dev
, i
+ USB_DIR_IN
);
1167 config
= dev
->actconfig
;
1168 retval
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1169 USB_REQ_SET_CONFIGURATION
, 0,
1170 config
->desc
.bConfigurationValue
, 0,
1171 NULL
, 0, HZ
* USB_CTRL_SET_TIMEOUT
);
1173 usb_set_device_state(dev
, USB_STATE_ADDRESS
);
1177 dev
->toggle
[0] = dev
->toggle
[1] = 0;
1179 /* re-init hc/hcd interface/endpoint state */
1180 for (i
= 0; i
< config
->desc
.bNumInterfaces
; i
++) {
1181 struct usb_interface
*intf
= config
->interface
[i
];
1182 struct usb_host_interface
*alt
;
1184 alt
= usb_altnum_to_altsetting(intf
, 0);
1186 /* No altsetting 0? We'll assume the first altsetting.
1187 * We could use a GetInterface call, but if a device is
1188 * so non-compliant that it doesn't have altsetting 0
1189 * then I wouldn't trust its reply anyway.
1192 alt
= &intf
->altsetting
[0];
1194 intf
->cur_altsetting
= alt
;
1195 usb_enable_interface(dev
, intf
);
1200 static void release_interface(struct device
*dev
)
1202 struct usb_interface
*intf
= to_usb_interface(dev
);
1203 struct usb_interface_cache
*intfc
=
1204 altsetting_to_usb_interface_cache(intf
->altsetting
);
1206 kref_put(&intfc
->ref
, usb_release_interface_cache
);
1211 * usb_set_configuration - Makes a particular device setting be current
1212 * @dev: the device whose configuration is being updated
1213 * @configuration: the configuration being chosen.
1214 * Context: !in_interrupt(), caller holds dev->serialize
1216 * This is used to enable non-default device modes. Not all devices
1217 * use this kind of configurability; many devices only have one
1220 * USB device configurations may affect Linux interoperability,
1221 * power consumption and the functionality available. For example,
1222 * the default configuration is limited to using 100mA of bus power,
1223 * so that when certain device functionality requires more power,
1224 * and the device is bus powered, that functionality should be in some
1225 * non-default device configuration. Other device modes may also be
1226 * reflected as configuration options, such as whether two ISDN
1227 * channels are available independently; and choosing between open
1228 * standard device protocols (like CDC) or proprietary ones.
1230 * Note that USB has an additional level of device configurability,
1231 * associated with interfaces. That configurability is accessed using
1232 * usb_set_interface().
1234 * This call is synchronous. The calling context must be able to sleep,
1235 * and must not hold the driver model lock for USB; usb device driver
1236 * probe() methods may not use this routine.
1238 * Returns zero on success, or else the status code returned by the
1239 * underlying call that failed. On succesful completion, each interface
1240 * in the original device configuration has been destroyed, and each one
1241 * in the new configuration has been probed by all relevant usb device
1242 * drivers currently known to the kernel.
1244 int usb_set_configuration(struct usb_device
*dev
, int configuration
)
1247 struct usb_host_config
*cp
= NULL
;
1248 struct usb_interface
**new_interfaces
= NULL
;
1251 /* dev->serialize guards all config changes */
1253 for (i
= 0; i
< dev
->descriptor
.bNumConfigurations
; i
++) {
1254 if (dev
->config
[i
].desc
.bConfigurationValue
== configuration
) {
1255 cp
= &dev
->config
[i
];
1259 if ((!cp
&& configuration
!= 0))
1262 /* The USB spec says configuration 0 means unconfigured.
1263 * But if a device includes a configuration numbered 0,
1264 * we will accept it as a correctly configured state.
1266 if (cp
&& configuration
== 0)
1267 dev_warn(&dev
->dev
, "config 0 descriptor??\n");
1269 if (dev
->state
== USB_STATE_SUSPENDED
)
1270 return -EHOSTUNREACH
;
1272 /* Allocate memory for new interfaces before doing anything else,
1273 * so that if we run out then nothing will have changed. */
1276 nintf
= cp
->desc
.bNumInterfaces
;
1277 new_interfaces
= kmalloc(nintf
* sizeof(*new_interfaces
),
1279 if (!new_interfaces
) {
1280 dev_err(&dev
->dev
, "Out of memory");
1284 for (; n
< nintf
; ++n
) {
1285 new_interfaces
[n
] = kmalloc(
1286 sizeof(struct usb_interface
),
1288 if (!new_interfaces
[n
]) {
1289 dev_err(&dev
->dev
, "Out of memory");
1293 kfree(new_interfaces
[n
]);
1294 kfree(new_interfaces
);
1300 /* if it's already configured, clear out old state first.
1301 * getting rid of old interfaces means unbinding their drivers.
1303 if (dev
->state
!= USB_STATE_ADDRESS
)
1304 usb_disable_device (dev
, 1); // Skip ep0
1306 if ((ret
= usb_control_msg(dev
, usb_sndctrlpipe(dev
, 0),
1307 USB_REQ_SET_CONFIGURATION
, 0, configuration
, 0,
1308 NULL
, 0, HZ
* USB_CTRL_SET_TIMEOUT
)) < 0)
1309 goto free_interfaces
;
1311 dev
->actconfig
= cp
;
1313 usb_set_device_state(dev
, USB_STATE_ADDRESS
);
1315 usb_set_device_state(dev
, USB_STATE_CONFIGURED
);
1317 /* Initialize the new interface structures and the
1318 * hc/hcd/usbcore interface/endpoint state.
1320 for (i
= 0; i
< nintf
; ++i
) {
1321 struct usb_interface_cache
*intfc
;
1322 struct usb_interface
*intf
;
1323 struct usb_host_interface
*alt
;
1325 cp
->interface
[i
] = intf
= new_interfaces
[i
];
1326 memset(intf
, 0, sizeof(*intf
));
1327 intfc
= cp
->intf_cache
[i
];
1328 intf
->altsetting
= intfc
->altsetting
;
1329 intf
->num_altsetting
= intfc
->num_altsetting
;
1330 kref_get(&intfc
->ref
);
1332 alt
= usb_altnum_to_altsetting(intf
, 0);
1334 /* No altsetting 0? We'll assume the first altsetting.
1335 * We could use a GetInterface call, but if a device is
1336 * so non-compliant that it doesn't have altsetting 0
1337 * then I wouldn't trust its reply anyway.
1340 alt
= &intf
->altsetting
[0];
1342 intf
->cur_altsetting
= alt
;
1343 usb_enable_interface(dev
, intf
);
1344 intf
->dev
.parent
= &dev
->dev
;
1345 intf
->dev
.driver
= NULL
;
1346 intf
->dev
.bus
= &usb_bus_type
;
1347 intf
->dev
.dma_mask
= dev
->dev
.dma_mask
;
1348 intf
->dev
.release
= release_interface
;
1349 device_initialize (&intf
->dev
);
1350 sprintf (&intf
->dev
.bus_id
[0], "%d-%s:%d.%d",
1351 dev
->bus
->busnum
, dev
->devpath
,
1353 alt
->desc
.bInterfaceNumber
);
1355 kfree(new_interfaces
);
1357 /* Now that all the interfaces are set up, register them
1358 * to trigger binding of drivers to interfaces. probe()
1359 * routines may install different altsettings and may
1360 * claim() any interfaces not yet bound. Many class drivers
1361 * need that: CDC, audio, video, etc.
1363 for (i
= 0; i
< nintf
; ++i
) {
1364 struct usb_interface
*intf
= cp
->interface
[i
];
1365 struct usb_interface_descriptor
*desc
;
1367 desc
= &intf
->altsetting
[0].desc
;
1369 "adding %s (config #%d, interface %d)\n",
1370 intf
->dev
.bus_id
, configuration
,
1371 desc
->bInterfaceNumber
);
1372 ret
= device_add (&intf
->dev
);
1375 "device_add(%s) --> %d\n",
1380 usb_create_sysfs_intf_files (intf
);
1387 // synchronous request completion model
1388 EXPORT_SYMBOL(usb_control_msg
);
1389 EXPORT_SYMBOL(usb_bulk_msg
);
1391 EXPORT_SYMBOL(usb_sg_init
);
1392 EXPORT_SYMBOL(usb_sg_cancel
);
1393 EXPORT_SYMBOL(usb_sg_wait
);
1395 // synchronous control message convenience routines
1396 EXPORT_SYMBOL(usb_get_descriptor
);
1397 EXPORT_SYMBOL(usb_get_status
);
1398 EXPORT_SYMBOL(usb_get_string
);
1399 EXPORT_SYMBOL(usb_string
);
1401 // synchronous calls that also maintain usbcore state
1402 EXPORT_SYMBOL(usb_clear_halt
);
1403 EXPORT_SYMBOL(usb_reset_configuration
);
1404 EXPORT_SYMBOL(usb_set_interface
);