The Linux-USB Host Side API¶
Introduction to USB on Linux¶
A Universal Serial Bus (USB) is used to connect a host, such as a PC or workstation, to a number of peripheral devices. USB uses a tree structure, with the host as the root (the system’s master), hubs as interior nodes, and peripherals as leaves (and slaves). Modern PCs support several such trees of USB devices, usually a few USB 3.0 (5 GBit/s) or USB 3.1 (10 GBit/s) and some legacy USB 2.0 (480 MBit/s) busses just in case.
That master/slave asymmetry was designed-in for a number of reasons, one being ease of use. It is not physically possible to mistake upstream and downstream or it does not matter with a type C plug (or they are built into the peripheral). Also, the host software doesn’t need to deal with distributed auto-configuration since the pre-designated master node manages all that.
Kernel developers added USB support to Linux early in the 2.2 kernel series and have been developing it further since then. Besides support for each new generation of USB, various host controllers gained support, new drivers for peripherals have been added and advanced features for latency measurement and improved power management introduced.
Linux can run inside USB devices as well as on the hosts that control the devices. But USB device drivers running inside those peripherals don’t do the same things as the ones running inside hosts, so they’ve been given a different name: gadget drivers. This document does not cover gadget drivers.
USB Host-Side API Model¶
Host-side drivers for USB devices talk to the “usbcore” APIs. There are two. One is intended for general-purpose drivers (exposed through driver frameworks), and the other is for drivers that are part of the core. Such core drivers include the hub driver (which manages trees of USB devices) and several different kinds of host controller drivers, which control individual busses.
The device model seen by USB drivers is relatively complex.
USB supports four kinds of data transfers (control, bulk, interrupt, and isochronous). Two of them (control and bulk) use bandwidth as it’s available, while the other two (interrupt and isochronous) are scheduled to provide guaranteed bandwidth.
The device description model includes one or more “configurations” per device, only one of which is active at a time. Devices are supposed to be capable of operating at lower than their top speeds and may provide a BOS descriptor showing the lowest speed they remain fully operational at.
From USB 3.0 on configurations have one or more “functions”, which provide a common functionality and are grouped together for purposes of power management.
Configurations or functions have one or more “interfaces”, each of which may have “alternate settings”. Interfaces may be standardized by USB “Class” specifications, or may be specific to a vendor or device.
USB device drivers actually bind to interfaces, not devices. Think of them as “interface drivers”, though you may not see many devices where the distinction is important. Most USB devices are simple, with only one function, one configuration, one interface, and one alternate setting.
Interfaces have one or more “endpoints”, each of which supports one type and direction of data transfer such as “bulk out” or “interrupt in”. The entire configuration may have up to sixteen endpoints in each direction, allocated as needed among all the interfaces.
Data transfer on USB is packetized; each endpoint has a maximum packet size. Drivers must often be aware of conventions such as flagging the end of bulk transfers using “short” (including zero length) packets.
The Linux USB API supports synchronous calls for control and bulk messages. It also supports asynchronous calls for all kinds of data transfer, using request structures called “URBs” (USB Request Blocks).
Accordingly, the USB Core API exposed to device drivers covers quite a lot of territory. You’ll probably need to consult the USB 3.0 specification, available online from www.usb.org at no cost, as well as class or device specifications.
The only host-side drivers that actually touch hardware (reading/writing registers, handling IRQs, and so on) are the HCDs. In theory, all HCDs provide the same functionality through the same API. In practice, that’s becoming more true, but there are still differences that crop up especially with fault handling on the less common controllers. Different controllers don’t necessarily report the same aspects of failures, and recovery from faults (including software-induced ones like unlinking an URB) isn’t yet fully consistent. Device driver authors should make a point of doing disconnect testing (while the device is active) with each different host controller driver, to make sure drivers don’t have bugs of their own as well as to make sure they aren’t relying on some HCD-specific behavior.
USB-Standard Types¶
In include/uapi/linux/usb/ch9.h
you will find the USB data types defined
in chapter 9 of the USB specification. These data types are used throughout
USB, and in APIs including this host side API, gadget APIs, usb character
devices and debugfs interfaces. That file is itself included by
include/linux/usb/ch9.h
, which also contains declarations of a few
utility routines for manipulating these data types; the implementations
are in drivers/usb/common/common.c
.
-
const char *
usb_ep_type_string
(int ep_type)¶ Returns human readable-name of the endpoint type.
Parameters
int ep_type
The endpoint type to return human-readable name for. If it’s not any of the types: USB_ENDPOINT_XFER_{CONTROL, ISOC, BULK, INT}, usually got by usb_endpoint_type(), the string ‘unknown’ will be returned.
-
const char *
usb_speed_string
(enum usb_device_speed speed)¶ Returns human readable-name of the speed.
Parameters
enum usb_device_speed speed
The speed to return human-readable name for. If it’s not any of the speeds defined in usb_device_speed enum, string for USB_SPEED_UNKNOWN will be returned.
-
enum usb_device_speed
usb_get_maximum_speed
(struct device *dev)¶ Get maximum requested speed for a given USB controller.
Parameters
struct device *dev
Pointer to the given USB controller device
Description
The function gets the maximum speed string from property “maximum-speed”, and returns the corresponding enum usb_device_speed.
-
enum usb_ssp_rate
usb_get_maximum_ssp_rate
(struct device *dev)¶ Get the signaling rate generation and lane count of a SuperSpeed Plus capable device.
Parameters
struct device *dev
Pointer to the given USB controller device
Description
If the string from “maximum-speed” property is super-speed-plus-genXxY where ‘X’ is the generation number and ‘Y’ is the number of lanes, then this function returns the corresponding enum usb_ssp_rate.
-
const char *
usb_state_string
(enum usb_device_state state)¶ Returns human readable name for the state.
Parameters
enum usb_device_state state
The state to return a human-readable name for. If it’s not any of the states devices in usb_device_state_string enum, the string UNKNOWN will be returned.
-
enum usb_dr_mode
usb_get_role_switch_default_mode
(struct device *dev)¶ Get default mode for given device
Parameters
struct device *dev
Pointer to the given device
Description
The function gets string from property ‘role-switch-default-mode’, and returns the corresponding enum usb_dr_mode.
-
unsigned int
usb_decode_interval
(const struct usb_endpoint_descriptor *epd, enum usb_device_speed speed)¶ Decode bInterval into the time expressed in 1us unit
Parameters
const struct usb_endpoint_descriptor *epd
The descriptor of the endpoint
enum usb_device_speed speed
The speed that the endpoint works as
Description
Function returns the interval expressed in 1us unit for servicing endpoint for data transfers.
-
enum usb_dr_mode
of_usb_get_dr_mode_by_phy
(struct device_node *np, int arg0)¶ Get dual role mode for the controller device which is associated with the given phy device_node
Parameters
struct device_node *np
Pointer to the given phy device_node
int arg0
phandle args[0] for phy’s with #phy-cells >= 1, or -1 for phys which do not have phy-cells
Description
In dts a usb controller associates with phy devices. The function gets the string from property ‘dr_mode’ of the controller associated with the given phy device node, and returns the correspondig enum usb_dr_mode.
-
bool
of_usb_host_tpl_support
(struct device_node *np)¶ to get if Targeted Peripheral List is supported for given targeted hosts (non-PC hosts)
Parameters
struct device_node *np
Pointer to the given device_node
Description
The function gets if the targeted hosts support TPL or not
-
int
of_usb_update_otg_caps
(struct device_node *np, struct usb_otg_caps *otg_caps)¶ to update usb otg capabilities according to the passed properties in DT.
Parameters
struct device_node *np
Pointer to the given device_node
struct usb_otg_caps *otg_caps
Pointer to the target usb_otg_caps to be set
Description
The function updates the otg capabilities
-
struct device *
usb_of_get_companion_dev
(struct device *dev)¶ Find the companion device
Parameters
struct device *dev
the device pointer to find a companion
Description
Find the companion device from platform bus.
Takes a reference to the returned struct device which needs to be dropped after use.
Return
On success, a pointer to the companion device, NULL
on failure.
In addition, some functions useful for creating debugging output are
defined in drivers/usb/common/debug.c
.
Host-Side Data Types and Macros¶
The host side API exposes several layers to drivers, some of which are more necessary than others. These support lifecycle models for host side drivers and devices, and support passing buffers through usbcore to some HCD that performs the I/O for the device driver.
Error
kernel-doc missing
USB Core APIs¶
There are two basic I/O models in the USB API. The most elemental one is asynchronous: drivers submit requests in the form of an URB, and the URB’s completion callback handles the next step. All USB transfer types support that model, although there are special cases for control URBs (which always have setup and status stages, but may not have a data stage) and isochronous URBs (which allow large packets and include per-packet fault reports). Built on top of that is synchronous API support, where a driver calls a routine that allocates one or more URBs, submits them, and waits until they complete. There are synchronous wrappers for single-buffer control and bulk transfers (which are awkward to use in some driver disconnect scenarios), and for scatterlist based streaming i/o (bulk or interrupt).
USB drivers need to provide buffers that can be used for DMA, although they don’t necessarily need to provide the DMA mapping themselves. There are APIs to use used when allocating DMA buffers, which can prevent use of bounce buffers on some systems. In some cases, drivers may be able to rely on 64bit DMA to eliminate another kind of bounce buffer.
-
void
usb_init_urb
(struct urb *urb)¶ initializes a urb so that it can be used by a USB driver
Parameters
struct urb *urb
pointer to the urb to initialize
Description
Initializes a urb so that the USB subsystem can use it properly.
If a urb is created with a call to usb_alloc_urb()
it is not
necessary to call this function. Only use this if you allocate the
space for a struct urb on your own. If you call this function, be
careful when freeing the memory for your urb that it is no longer in
use by the USB core.
Only use this function if you _really_ understand what you are doing.
-
struct urb *
usb_alloc_urb
(int iso_packets, gfp_t mem_flags)¶ creates a new urb for a USB driver to use
Parameters
int iso_packets
number of iso packets for this urb
gfp_t mem_flags
the type of memory to allocate, see
kmalloc()
for a list of valid options for this.
Description
Creates an urb for the USB driver to use, initializes a few internal structures, increments the usage counter, and returns a pointer to it.
If the driver want to use this urb for interrupt, control, or bulk endpoints, pass ‘0’ as the number of iso packets.
The driver must call usb_free_urb()
when it is finished with the urb.
Return
A pointer to the new urb, or NULL
if no memory is available.
-
void
usb_free_urb
(struct urb *urb)¶ frees the memory used by a urb when all users of it are finished
Parameters
struct urb *urb
pointer to the urb to free, may be NULL
Description
Must be called when a user of a urb is finished with it. When the last user of the urb calls this function, the memory of the urb is freed.
Note
The transfer buffer associated with the urb is not freed unless the URB_FREE_BUFFER transfer flag is set.
-
struct urb *
usb_get_urb
(struct urb *urb)¶ increments the reference count of the urb
Parameters
struct urb *urb
pointer to the urb to modify, may be NULL
Description
This must be called whenever a urb is transferred from a device driver to a host controller driver. This allows proper reference counting to happen for urbs.
Return
A pointer to the urb with the incremented reference counter.
-
void
usb_anchor_urb
(struct urb *urb, struct usb_anchor *anchor)¶ anchors an URB while it is processed
Parameters
struct urb *urb
pointer to the urb to anchor
struct usb_anchor *anchor
pointer to the anchor
Description
This can be called to have access to URBs which are to be executed without bothering to track them
-
void
usb_unanchor_urb
(struct urb *urb)¶ unanchors an URB
Parameters
struct urb *urb
pointer to the urb to anchor
Description
Call this to stop the system keeping track of this URB
-
int
usb_pipe_type_check
(struct usb_device *dev, unsigned int pipe)¶ sanity check of a specific pipe for a usb device
Parameters
struct usb_device *dev
struct usb_device to be checked
unsigned int pipe
pipe to check
Description
This performs a light-weight sanity check for the endpoint in the given usb device. It returns 0 if the pipe is valid for the specific usb device, otherwise a negative error code.
-
int
usb_urb_ep_type_check
(const struct urb *urb)¶ sanity check of endpoint in the given urb
Parameters
const struct urb *urb
urb to be checked
Description
This performs a light-weight sanity check for the endpoint in the given urb. It returns 0 if the urb contains a valid endpoint, otherwise a negative error code.
-
int
usb_submit_urb
(struct urb *urb, gfp_t mem_flags)¶ issue an asynchronous transfer request for an endpoint
Parameters
struct urb *urb
pointer to the urb describing the request
gfp_t mem_flags
the type of memory to allocate, see
kmalloc()
for a list of valid options for this.
Description
This submits a transfer request, and transfers control of the URB describing that request to the USB subsystem. Request completion will be indicated later, asynchronously, by calling the completion handler. The three types of completion are success, error, and unlink (a software-induced fault, also called “request cancellation”).
URBs may be submitted in interrupt context.
The caller must have correctly initialized the URB before submitting it. Functions such as usb_fill_bulk_urb() and usb_fill_control_urb() are available to ensure that most fields are correctly initialized, for the particular kind of transfer, although they will not initialize any transfer flags.
If the submission is successful, the complete() callback from the URB will be called exactly once, when the USB core and Host Controller Driver (HCD) are finished with the URB. When the completion function is called, control of the URB is returned to the device driver which issued the request. The completion handler may then immediately free or reuse that URB.
With few exceptions, USB device drivers should never access URB fields provided by usbcore or the HCD until its complete() is called. The exceptions relate to periodic transfer scheduling. For both interrupt and isochronous urbs, as part of successful URB submission urb->interval is modified to reflect the actual transfer period used (normally some power of two units). And for isochronous urbs, urb->start_frame is modified to reflect when the URB’s transfers were scheduled to start.
Not all isochronous transfer scheduling policies will work, but most host controller drivers should easily handle ISO queues going from now until 10-200 msec into the future. Drivers should try to keep at least one or two msec of data in the queue; many controllers require that new transfers start at least 1 msec in the future when they are added. If the driver is unable to keep up and the queue empties out, the behavior for new submissions is governed by the URB_ISO_ASAP flag. If the flag is set, or if the queue is idle, then the URB is always assigned to the first available (and not yet expired) slot in the endpoint’s schedule. If the flag is not set and the queue is active then the URB is always assigned to the next slot in the schedule following the end of the endpoint’s previous URB, even if that slot is in the past. When a packet is assigned in this way to a slot that has already expired, the packet is not transmitted and the corresponding usb_iso_packet_descriptor’s status field will return -EXDEV. If this would happen to all the packets in the URB, submission fails with a -EXDEV error code.
For control endpoints, the synchronous usb_control_msg()
call is
often used (in non-interrupt context) instead of this call.
That is often used through convenience wrappers, for the requests
that are standardized in the USB 2.0 specification. For bulk
endpoints, a synchronous usb_bulk_msg()
call is available.
Request Queuing:
URBs may be submitted to endpoints before previous ones complete, to minimize the impact of interrupt latencies and system overhead on data throughput. With that queuing policy, an endpoint’s queue would never be empty. This is required for continuous isochronous data streams, and may also be required for some kinds of interrupt transfers. Such queuing also maximizes bandwidth utilization by letting USB controllers start work on later requests before driver software has finished the completion processing for earlier (successful) requests.
As of Linux 2.6, all USB endpoint transfer queues support depths greater than one. This was previously a HCD-specific behavior, except for ISO transfers. Non-isochronous endpoint queues are inactive during cleanup after faults (transfer errors or cancellation).
Reserved Bandwidth Transfers:
Periodic transfers (interrupt or isochronous) are performed repeatedly, using the interval specified in the urb. Submitting the first urb to the endpoint reserves the bandwidth necessary to make those transfers. If the USB subsystem can’t allocate sufficient bandwidth to perform the periodic request, submitting such a periodic request should fail.
For devices under xHCI, the bandwidth is reserved at configuration time, or when the alt setting is selected. If there is not enough bus bandwidth, the configuration/alt setting request will fail. Therefore, submissions to periodic endpoints on devices under xHCI should never fail due to bandwidth constraints.
Device drivers must explicitly request that repetition, by ensuring that some URB is always on the endpoint’s queue (except possibly for short periods during completion callbacks). When there is no longer an urb queued, the endpoint’s bandwidth reservation is canceled. This means drivers can use their completion handlers to ensure they keep bandwidth they need, by reinitializing and resubmitting the just-completed urb until the driver longer needs that periodic bandwidth.
Memory Flags:
The general rules for how to decide which mem_flags to use are the same as for kmalloc. There are four different possible values; GFP_KERNEL, GFP_NOFS, GFP_NOIO and GFP_ATOMIC.
GFP_NOFS is not ever used, as it has not been implemented yet.
- GFP_ATOMIC is used when
you are inside a completion handler, an interrupt, bottom half, tasklet or timer, or
you are holding a spinlock or rwlock (does not apply to semaphores), or
current->state != TASK_RUNNING, this is the case only after you’ve changed it.
GFP_NOIO is used in the block io path and error handling of storage devices.
All other situations use GFP_KERNEL.
- Some more specific rules for mem_flags can be inferred, such as
start_xmit, timeout, and receive methods of network drivers must use GFP_ATOMIC (they are called with a spinlock held);
queuecommand methods of scsi drivers must use GFP_ATOMIC (also called with a spinlock held);
If you use a kernel thread with a network driver you must use GFP_NOIO, unless (b) or (c) apply;
after you have done a down() you can use GFP_KERNEL, unless (b) or (c) apply or your are in a storage driver’s block io path;
USB probe and disconnect can use GFP_KERNEL unless (b) or (c) apply; and
changing firmware on a running storage or net device uses GFP_NOIO, unless b) or c) apply
Return
0 on successful submissions. A negative error number otherwise.
-
int
usb_unlink_urb
(struct urb *urb)¶ abort/cancel a transfer request for an endpoint
Parameters
struct urb *urb
pointer to urb describing a previously submitted request, may be NULL
Description
This routine cancels an in-progress request. URBs complete only once per submission, and may be canceled only once per submission. Successful cancellation means termination of urb will be expedited and the completion handler will be called with a status code indicating that the request has been canceled (rather than any other code).
Drivers should not call this routine or related routines, such as
usb_kill_urb()
or usb_unlink_anchored_urbs()
, after their disconnect
method has returned. The disconnect function should synchronize with
a driver’s I/O routines to insure that all URB-related activity has
completed before it returns.
This request is asynchronous, however the HCD might call the ->complete()
callback during unlink. Therefore when drivers call usb_unlink_urb()
, they
must not hold any locks that may be taken by the completion function.
Success is indicated by returning -EINPROGRESS, at which time the URB will
probably not yet have been given back to the device driver. When it is
eventually called, the completion function will see urb->status ==
-ECONNRESET.
Failure is indicated by usb_unlink_urb()
returning any other value.
Unlinking will fail when urb is not currently “linked” (i.e., it was
never submitted, or it was unlinked before, or the hardware is already
finished with it), even if the completion handler has not yet run.
The URB must not be deallocated while this routine is running. In particular, when a driver calls this routine, it must insure that the completion handler cannot deallocate the URB.
Unlinking and Endpoint Queues:
[The behaviors and guarantees described below do not apply to virtual root hubs but only to endpoint queues for physical USB devices.]
Host Controller Drivers (HCDs) place all the URBs for a particular endpoint in a queue. Normally the queue advances as the controller hardware processes each request. But when an URB terminates with an error its queue generally stops (see below), at least until that URB’s completion routine returns. It is guaranteed that a stopped queue will not restart until all its unlinked URBs have been fully retired, with their completion routines run, even if that’s not until some time after the original completion handler returns. The same behavior and guarantee apply when an URB terminates because it was unlinked.
Bulk and interrupt endpoint queues are guaranteed to stop whenever an URB terminates with any sort of error, including -ECONNRESET, -ENOENT, and -EREMOTEIO. Control endpoint queues behave the same way except that they are not guaranteed to stop for -EREMOTEIO errors. Queues for isochronous endpoints are treated differently, because they must advance at fixed rates. Such queues do not stop when an URB encounters an error or is unlinked. An unlinked isochronous URB may leave a gap in the stream of packets; it is undefined whether such gaps can be filled in.
Note that early termination of an URB because a short packet was received will generate a -EREMOTEIO error if and only if the URB_SHORT_NOT_OK flag is set. By setting this flag, USB device drivers can build deep queues for large or complex bulk transfers and clean them up reliably after any sort of aborted transfer by unlinking all pending URBs at the first fault.
When a control URB terminates with an error other than -EREMOTEIO, it is quite likely that the status stage of the transfer will not take place.
Return
-EINPROGRESS on success. See description for other values on failure.
-
void
usb_kill_urb
(struct urb *urb)¶ cancel a transfer request and wait for it to finish
Parameters
struct urb *urb
pointer to URB describing a previously submitted request, may be NULL
Description
This routine cancels an in-progress request. It is guaranteed that upon return all completion handlers will have finished and the URB will be totally idle and available for reuse. These features make this an ideal way to stop I/O in a disconnect() callback or close() function. If the request has not already finished or been unlinked the completion handler will see urb->status == -ENOENT.
While the routine is running, attempts to resubmit the URB will fail with error -EPERM. Thus even if the URB’s completion handler always tries to resubmit, it will not succeed and the URB will become idle.
The URB must not be deallocated while this routine is running. In particular, when a driver calls this routine, it must insure that the completion handler cannot deallocate the URB.
This routine may not be used in an interrupt context (such as a bottom half or a completion handler), or when holding a spinlock, or in other situations where the caller can’t schedule().
This routine should not be called by a driver after its disconnect method has returned.
-
void
usb_poison_urb
(struct urb *urb)¶ reliably kill a transfer and prevent further use of an URB
Parameters
struct urb *urb
pointer to URB describing a previously submitted request, may be NULL
Description
This routine cancels an in-progress request. It is guaranteed that upon return all completion handlers will have finished and the URB will be totally idle and cannot be reused. These features make this an ideal way to stop I/O in a disconnect() callback. If the request has not already finished or been unlinked the completion handler will see urb->status == -ENOENT.
After and while the routine runs, attempts to resubmit the URB will fail with error -EPERM. Thus even if the URB’s completion handler always tries to resubmit, it will not succeed and the URB will become idle.
The URB must not be deallocated while this routine is running. In particular, when a driver calls this routine, it must insure that the completion handler cannot deallocate the URB.
This routine may not be used in an interrupt context (such as a bottom half or a completion handler), or when holding a spinlock, or in other situations where the caller can’t schedule().
This routine should not be called by a driver after its disconnect method has returned.
-
void
usb_block_urb
(struct urb *urb)¶ reliably prevent further use of an URB
Parameters
struct urb *urb
pointer to URB to be blocked, may be NULL
Description
After the routine has run, attempts to resubmit the URB will fail with error -EPERM. Thus even if the URB’s completion handler always tries to resubmit, it will not succeed and the URB will become idle.
The URB must not be deallocated while this routine is running. In particular, when a driver calls this routine, it must insure that the completion handler cannot deallocate the URB.
-
void
usb_kill_anchored_urbs
(struct usb_anchor *anchor)¶ kill all URBs associated with an anchor
Parameters
struct usb_anchor *anchor
anchor the requests are bound to
Description
This kills all outstanding URBs starting from the back of the queue, with guarantee that no completer callbacks will take place from the anchor after this function returns.
This routine should not be called by a driver after its disconnect method has returned.
-
void
usb_poison_anchored_urbs
(struct usb_anchor *anchor)¶ cease all traffic from an anchor
Parameters
struct usb_anchor *anchor
anchor the requests are bound to
Description
this allows all outstanding URBs to be poisoned starting from the back of the queue. Newly added URBs will also be poisoned
This routine should not be called by a driver after its disconnect method has returned.
-
void
usb_unpoison_anchored_urbs
(struct usb_anchor *anchor)¶ let an anchor be used successfully again
Parameters
struct usb_anchor *anchor
anchor the requests are bound to
Description
Reverses the effect of usb_poison_anchored_urbs the anchor can be used normally after it returns
-
void
usb_unlink_anchored_urbs
(struct usb_anchor *anchor)¶ asynchronously cancel transfer requests en masse
Parameters
struct usb_anchor *anchor
anchor the requests are bound to
Description
this allows all outstanding URBs to be unlinked starting from the back of the queue. This function is asynchronous. The unlinking is just triggered. It may happen after this function has returned.
This routine should not be called by a driver after its disconnect method has returned.
-
void
usb_anchor_suspend_wakeups
(struct usb_anchor *anchor)¶
Parameters
struct usb_anchor *anchor
the anchor you want to suspend wakeups on
Description
Call this to stop the last urb being unanchored from waking up any usb_wait_anchor_empty_timeout waiters. This is used in the hcd urb give- back path to delay waking up until after the completion handler has run.
-
void
usb_anchor_resume_wakeups
(struct usb_anchor *anchor)¶
Parameters
struct usb_anchor *anchor
the anchor you want to resume wakeups on
Description
Allow usb_wait_anchor_empty_timeout waiters to be woken up again, and wake up any current waiters if the anchor is empty.
-
int
usb_wait_anchor_empty_timeout
(struct usb_anchor *anchor, unsigned int timeout)¶ wait for an anchor to be unused
Parameters
struct usb_anchor *anchor
the anchor you want to become unused
unsigned int timeout
how long you are willing to wait in milliseconds
Description
Call this is you want to be sure all an anchor’s URBs have finished
Return
Non-zero if the anchor became unused. Zero on timeout.
-
struct urb *
usb_get_from_anchor
(struct usb_anchor *anchor)¶ get an anchor’s oldest urb
Parameters
struct usb_anchor *anchor
the anchor whose urb you want
Description
This will take the oldest urb from an anchor, unanchor and return it
Return
The oldest urb from anchor, or NULL
if anchor has no
urbs associated with it.
-
void
usb_scuttle_anchored_urbs
(struct usb_anchor *anchor)¶ unanchor all an anchor’s urbs
Parameters
struct usb_anchor *anchor
the anchor whose urbs you want to unanchor
Description
use this to get rid of all an anchor’s urbs
-
int
usb_anchor_empty
(struct usb_anchor *anchor)¶ is an anchor empty
Parameters
struct usb_anchor *anchor
the anchor you want to query
Return
1 if the anchor has no urbs associated with it.
-
int
usb_control_msg
(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *data, __u16 size, int timeout)¶ Builds a control urb, sends it off and waits for completion
Parameters
struct usb_device *dev
pointer to the usb device to send the message to
unsigned int pipe
endpoint “pipe” to send the message to
__u8 request
USB message request value
__u8 requesttype
USB message request type value
__u16 value
USB message value
__u16 index
USB message index value
void *data
pointer to the data to send
__u16 size
length in bytes of the data to send
int timeout
time in msecs to wait for the message to complete before timing out (if 0 the wait is forever)
Context
task context, might sleep.
Description
This function sends a simple control message to a specified endpoint and waits for the message to complete, or timeout.
Don’t use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use usb_submit_urb()
. If a thread in your driver uses this call,
make sure your disconnect() method can wait for it to complete. Since you
don’t have a handle on the URB used, you can’t cancel the request.
Return
If successful, the number of bytes transferred. Otherwise, a negative error number.
-
int
usb_control_msg_send
(struct usb_device *dev, __u8 endpoint, __u8 request, __u8 requesttype, __u16 value, __u16 index, const void *driver_data, __u16 size, int timeout, gfp_t memflags)¶ Builds a control “send” message, sends it off and waits for completion
Parameters
struct usb_device *dev
pointer to the usb device to send the message to
__u8 endpoint
endpoint to send the message to
__u8 request
USB message request value
__u8 requesttype
USB message request type value
__u16 value
USB message value
__u16 index
USB message index value
const void *driver_data
pointer to the data to send
__u16 size
length in bytes of the data to send
int timeout
time in msecs to wait for the message to complete before timing out (if 0 the wait is forever)
gfp_t memflags
the flags for memory allocation for buffers
Context
!in_interrupt ()
Description
This function sends a control message to a specified endpoint that is not expected to fill in a response (i.e. a “send message”) and waits for the message to complete, or timeout.
Do not use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use usb_submit_urb()
. If a thread in your driver uses this call,
make sure your disconnect() method can wait for it to complete. Since you
don’t have a handle on the URB used, you can’t cancel the request.
The data pointer can be made to a reference on the stack, or anywhere else,
as it will not be modified at all. This does not have the restriction that
usb_control_msg()
has where the data pointer must be to dynamically allocated
memory (i.e. memory that can be successfully DMAed to a device).
Return
If successful, 0 is returned, Otherwise, a negative error number.
-
int
usb_control_msg_recv
(struct usb_device *dev, __u8 endpoint, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *driver_data, __u16 size, int timeout, gfp_t memflags)¶ Builds a control “receive” message, sends it off and waits for completion
Parameters
struct usb_device *dev
pointer to the usb device to send the message to
__u8 endpoint
endpoint to send the message to
__u8 request
USB message request value
__u8 requesttype
USB message request type value
__u16 value
USB message value
__u16 index
USB message index value
void *driver_data
pointer to the data to be filled in by the message
__u16 size
length in bytes of the data to be received
int timeout
time in msecs to wait for the message to complete before timing out (if 0 the wait is forever)
gfp_t memflags
the flags for memory allocation for buffers
Context
!in_interrupt ()
Description
This function sends a control message to a specified endpoint that is expected to fill in a response (i.e. a “receive message”) and waits for the message to complete, or timeout.
Do not use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use usb_submit_urb()
. If a thread in your driver uses this call,
make sure your disconnect() method can wait for it to complete. Since you
don’t have a handle on the URB used, you can’t cancel the request.
The data pointer can be made to a reference on the stack, or anywhere else
that can be successfully written to. This function does not have the
restriction that usb_control_msg()
has where the data pointer must be to
dynamically allocated memory (i.e. memory that can be successfully DMAed to a
device).
The “whole” message must be properly received from the device in order for this function to be successful. If a device returns less than the expected amount of data, then the function will fail. Do not use this for messages where a variable amount of data might be returned.
Return
If successful, 0 is returned, Otherwise, a negative error number.
-
int
usb_interrupt_msg
(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout)¶ Builds an interrupt urb, sends it off and waits for completion
Parameters
struct usb_device *usb_dev
pointer to the usb device to send the message to
unsigned int pipe
endpoint “pipe” to send the message to
void *data
pointer to the data to send
int len
length in bytes of the data to send
int *actual_length
pointer to a location to put the actual length transferred in bytes
int timeout
time in msecs to wait for the message to complete before timing out (if 0 the wait is forever)
Context
task context, might sleep.
Description
This function sends a simple interrupt message to a specified endpoint and waits for the message to complete, or timeout.
Don’t use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use usb_submit_urb()
If a thread in your driver uses this call,
make sure your disconnect() method can wait for it to complete. Since you
don’t have a handle on the URB used, you can’t cancel the request.
Return
If successful, 0. Otherwise a negative error number. The number of actual bytes transferred will be stored in the actual_length parameter.
-
int
usb_bulk_msg
(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout)¶ Builds a bulk urb, sends it off and waits for completion
Parameters
struct usb_device *usb_dev
pointer to the usb device to send the message to
unsigned int pipe
endpoint “pipe” to send the message to
void *data
pointer to the data to send
int len
length in bytes of the data to send
int *actual_length
pointer to a location to put the actual length transferred in bytes
int timeout
time in msecs to wait for the message to complete before timing out (if 0 the wait is forever)
Context
task context, might sleep.
Description
This function sends a simple bulk message to a specified endpoint and waits for the message to complete, or timeout.
Don’t use this function from within an interrupt context. If you need
an asynchronous message, or need to send a message from within interrupt
context, use usb_submit_urb()
If a thread in your driver uses this call,
make sure your disconnect() method can wait for it to complete. Since you
don’t have a handle on the URB used, you can’t cancel the request.
Because there is no usb_interrupt_msg()
and no USBDEVFS_INTERRUPT ioctl,
users are forced to abuse this routine by using it to submit URBs for
interrupt endpoints. We will take the liberty of creating an interrupt URB
(with the default interval) if the target is an interrupt endpoint.
Return
If successful, 0. Otherwise a negative error number. The number of actual bytes transferred will be stored in the actual_length parameter.
-
int
usb_sg_init
(struct usb_sg_request *io, struct usb_device *dev, unsigned pipe, unsigned period, struct scatterlist *sg, int nents, size_t length, gfp_t mem_flags)¶ initializes scatterlist-based bulk/interrupt I/O request
Parameters
struct usb_sg_request *io
request block being initialized. until
usb_sg_wait()
returns, treat this as a pointer to an opaque block of memory,struct usb_device *dev
the usb device that will send or receive the data
unsigned pipe
endpoint “pipe” used to transfer the data
unsigned period
polling rate for interrupt endpoints, in frames or (for high speed endpoints) microframes; ignored for bulk
struct scatterlist *sg
scatterlist entries
int nents
how many entries in the scatterlist
size_t length
how many bytes to send from the scatterlist, or zero to send every byte identified in the list.
gfp_t mem_flags
SLAB_* flags affecting memory allocations in this call
Description
This initializes a scatter/gather request, allocating resources such as I/O mappings and urb memory (except maybe memory used by USB controller drivers).
The request must be issued using usb_sg_wait()
, which waits for the I/O to
complete (or to be canceled) and then cleans up all resources allocated by
usb_sg_init()
.
The request may be canceled with usb_sg_cancel()
, either before or after
usb_sg_wait()
is called.
Return
Zero for success, else a negative errno value.
-
void
usb_sg_wait
(struct usb_sg_request *io)¶ synchronously execute scatter/gather request
Parameters
struct usb_sg_request *io
request block handle, as initialized with
usb_sg_init()
. some fields become accessible when this call returns.
Context
task context, might sleep.
Description
This function blocks until the specified I/O operation completes. It leverages the grouping of the related I/O requests to get good transfer rates, by queueing the requests. At higher speeds, such queuing can significantly improve USB throughput.
There are three kinds of completion for this function.
success, where io->status is zero. The number of io->bytes transferred is as requested.
error, where io->status is a negative errno value. The number of io->bytes transferred before the error is usually less than requested, and can be nonzero.
cancellation, a type of error with status -ECONNRESET that is initiated by
usb_sg_cancel()
.
When this function returns, all memory allocated through usb_sg_init()
or
this call will have been freed. The request block parameter may still be
passed to usb_sg_cancel()
, or it may be freed. It could also be
reinitialized and then reused.
Data Transfer Rates:
Bulk transfers are valid for full or high speed endpoints. The best full speed data rate is 19 packets of 64 bytes each per frame, or 1216 bytes per millisecond. The best high speed data rate is 13 packets of 512 bytes each per microframe, or 52 KBytes per millisecond.
The reason to use interrupt transfers through this API would most likely be to reserve high speed bandwidth, where up to 24 KBytes per millisecond could be transferred. That capability is less useful for low or full speed interrupt endpoints, which allow at most one packet per millisecond, of at most 8 or 64 bytes (respectively).
It is not necessary to call this function to reserve bandwidth for devices under an xHCI host controller, as the bandwidth is reserved when the configuration or interface alt setting is selected.
-
void
usb_sg_cancel
(struct usb_sg_request *io)¶ stop scatter/gather i/o issued by
usb_sg_wait()
Parameters
struct usb_sg_request *io
request block, initialized with
usb_sg_init()
Description
This stops a request after it has been started by usb_sg_wait()
.
It can also prevents one initialized by usb_sg_init()
from starting,
so that call just frees resources allocated to the request.
-
int
usb_get_descriptor
(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)¶ issues a generic GET_DESCRIPTOR request
Parameters
struct usb_device *dev
the device whose descriptor is being retrieved
unsigned char type
the descriptor type (USB_DT_*)
unsigned char index
the number of the descriptor
void *buf
where to put the descriptor
int size
how big is “buf”?
Context
task context, might sleep.
Description
Gets a USB descriptor. Convenience functions exist to simplify
getting some types of descriptors. Use
usb_get_string() or usb_string()
for USB_DT_STRING.
Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
are part of the device structure.
In addition to a number of USB-standard descriptors, some
devices also use class-specific or vendor-specific descriptors.
This call is synchronous, and may not be used in an interrupt context.
Return
The number of bytes received on success, or else the status code
returned by the underlying usb_control_msg()
call.
-
int
usb_string
(struct usb_device *dev, int index, char *buf, size_t size)¶ returns UTF-8 version of a string descriptor
Parameters
struct usb_device *dev
the device whose string descriptor is being retrieved
int index
the number of the descriptor
char *buf
where to put the string
size_t size
how big is “buf”?
Context
task context, might sleep.
Description
This converts the UTF-16LE encoded strings returned by devices, from usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones that are more usable in most kernel contexts. Note that this function chooses strings in the first language supported by the device.
This call is synchronous, and may not be used in an interrupt context.
Return
length of the string (>= 0) or usb_control_msg status (< 0).
-
int
usb_get_status
(struct usb_device *dev, int recip, int type, int target, void *data)¶ issues a GET_STATUS call
Parameters
struct usb_device *dev
the device whose status is being checked
int recip
USB_RECIP_*; for device, interface, or endpoint
int type
USB_STATUS_TYPE_*; for standard or PTM status types
int target
zero (for device), else interface or endpoint number
void *data
pointer to two bytes of bitmap data
Context
task context, might sleep.
Description
Returns device, interface, or endpoint status. Normally only of interest to see if the device is self powered, or has enabled the remote wakeup facility; or whether a bulk or interrupt endpoint is halted (“stalled”).
Bits in these status bitmaps are set using the SET_FEATURE request,
and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
function should be used to clear halt (“stall”) status.
This call is synchronous, and may not be used in an interrupt context.
Returns 0 and the status value in *data (in host byte order) on success,
or else the status code from the underlying usb_control_msg()
call.
-
int
usb_clear_halt
(struct usb_device *dev, int pipe)¶ tells device to clear endpoint halt/stall condition
Parameters
struct usb_device *dev
device whose endpoint is halted
int pipe
endpoint “pipe” being cleared
Context
task context, might sleep.
Description
This is used to clear halt conditions for bulk and interrupt endpoints, as reported by URB completion status. Endpoints that are halted are sometimes referred to as being “stalled”. Such endpoints are unable to transmit or receive data until the halt status is cleared. Any URBs queued for such an endpoint should normally be unlinked by the driver before clearing the halt condition, as described in sections 5.7.5 and 5.8.5 of the USB 2.0 spec.
Note that control and isochronous endpoints don’t halt, although control endpoints report “protocol stall” (for unsupported requests) using the same status code used to report a true stall.
This call is synchronous, and may not be used in an interrupt context.
Return
Zero on success, or else the status code returned by the
underlying usb_control_msg()
call.
-
void
usb_reset_endpoint
(struct usb_device *dev, unsigned int epaddr)¶ Reset an endpoint’s state.
Parameters
struct usb_device *dev
the device whose endpoint is to be reset
unsigned int epaddr
the endpoint’s address. Endpoint number for output, endpoint number + USB_DIR_IN for input
Description
Resets any host-side endpoint state such as the toggle bit, sequence number or current window.
-
int
usb_set_interface
(struct usb_device *dev, int interface, int alternate)¶ Makes a particular alternate setting be current
Parameters
struct usb_device *dev
the device whose interface is being updated
int interface
the interface being updated
int alternate
the setting being chosen.
Context
task context, might sleep.
Description
This is used to enable data transfers on interfaces that may not be enabled by default. Not all devices support such configurability. Only the driver bound to an interface may change its setting.
Within any given configuration, each interface may have several alternative settings. These are often used to control levels of bandwidth consumption. For example, the default setting for a high speed interrupt endpoint may not send more than 64 bytes per microframe, while interrupt transfers of up to 3KBytes per microframe are legal. Also, isochronous endpoints may never be part of an interface’s default setting. To access such bandwidth, alternate interface settings must be made current.
Note that in the Linux USB subsystem, bandwidth associated with an endpoint in a given alternate setting is not reserved until an URB is submitted that needs that bandwidth. Some other operating systems allocate bandwidth early, when a configuration is chosen.
xHCI reserves bandwidth and configures the alternate setting in usb_hcd_alloc_bandwidth(). If it fails the original interface altsetting may be disabled. Drivers cannot rely on any particular alternate setting being in effect after a failure.
This call is synchronous, and may not be used in an interrupt context. Also, drivers must not change altsettings while urbs are scheduled for endpoints in that interface; all such urbs must first be completed (perhaps forced by unlinking).
Return
Zero on success, or else the status code returned by the
underlying usb_control_msg()
call.
-
int
usb_reset_configuration
(struct usb_device *dev)¶ lightweight device reset
Parameters
struct usb_device *dev
the device whose configuration is being reset
Description
This issues a standard SET_CONFIGURATION request to the device using the current configuration. The effect is to reset most USB-related state in the device, including interface altsettings (reset to zero), endpoint halts (cleared), and endpoint state (only for bulk and interrupt endpoints). Other usbcore state is unchanged, including bindings of usb device drivers to interfaces.
Because this affects multiple interfaces, avoid using this with composite
(multi-interface) devices. Instead, the driver for each interface may
use usb_set_interface()
on the interfaces it claims. Be careful though;
some devices don’t support the SET_INTERFACE request, and others won’t
reset all the interface state (notably endpoint state). Resetting the whole
configuration would affect other drivers’ interfaces.
The caller must own the device lock.
If this routine fails the device will probably be in an unusable state with endpoints disabled, and interfaces only partially enabled.
Return
Zero on success, else a negative error code.
-
int
usb_driver_set_configuration
(struct usb_device *udev, int config)¶ Provide a way for drivers to change device configurations
Parameters
struct usb_device *udev
the device whose configuration is being updated
int config
the configuration being chosen.
Context
In process context, must be able to sleep
Description
Device interface drivers are not allowed to change device configurations. This is because changing configurations will destroy the interface the driver is bound to and create new ones; it would be like a floppy-disk driver telling the computer to replace the floppy-disk drive with a tape drive!
Still, in certain specialized circumstances the need may arise. This routine gets around the normal restrictions by using a work thread to submit the change-config request.
Return
0 if the request was successfully queued, error code otherwise. The caller has no way to know whether the queued request will eventually succeed.
-
int
cdc_parse_cdc_header
(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen)¶ parse the extra headers present in CDC devices
Parameters
struct usb_cdc_parsed_header *hdr
the place to put the results of the parsing
struct usb_interface *intf
the interface for which parsing is requested
u8 *buffer
pointer to the extra headers to be parsed
int buflen
length of the extra headers
Description
This evaluates the extra headers present in CDC devices which bind the interfaces for data and control and provide details about the capabilities of the device.
Return
number of descriptors parsed or -EINVAL if the header is contradictory beyond salvage
-
int
usb_register_dev
(struct usb_interface *intf, struct usb_class_driver *class_driver)¶ register a USB device, and ask for a minor number
Parameters
struct usb_interface *intf
pointer to the usb_interface that is being registered
struct usb_class_driver *class_driver
pointer to the usb_class_driver for this device
Description
This should be called by all USB drivers that use the USB major number. If CONFIG_USB_DYNAMIC_MINORS is enabled, the minor number will be dynamically allocated out of the list of available ones. If it is not enabled, the minor number will be based on the next available free minor, starting at the class_driver->minor_base.
This function also creates a usb class device in the sysfs tree.
usb_deregister_dev()
must be called when the driver is done with
the minor numbers given out by this function.
Return
-EINVAL if something bad happens with trying to register a device, and 0 on success.
-
void
usb_deregister_dev
(struct usb_interface *intf, struct usb_class_driver *class_driver)¶ deregister a USB device’s dynamic minor.
Parameters
struct usb_interface *intf
pointer to the usb_interface that is being deregistered
struct usb_class_driver *class_driver
pointer to the usb_class_driver for this device
Description
Used in conjunction with usb_register_dev()
. This function is called
when the USB driver is finished with the minor numbers gotten from a
call to usb_register_dev()
(usually when the device is disconnected
from the system.)
This function also removes the usb class device from the sysfs tree.
This should be called by all drivers that use the USB major number.
-
int
usb_driver_claim_interface
(struct usb_driver *driver, struct usb_interface *iface, void *data)¶ bind a driver to an interface
Parameters
struct usb_driver *driver
the driver to be bound
struct usb_interface *iface
the interface to which it will be bound; must be in the usb device’s active configuration
void *data
driver data associated with that interface
Description
This is used by usb device drivers that need to claim more than one interface on a device when probing (audio and acm are current examples). No device driver should directly modify internal usb_interface or usb_device structure members.
Callers must own the device lock, so driver probe() entries don’t need extra locking, but other call contexts may need to explicitly claim that lock.
Return
0 on success.
-
void
usb_driver_release_interface
(struct usb_driver *driver, struct usb_interface *iface)¶ unbind a driver from an interface
Parameters
struct usb_driver *driver
the driver to be unbound
struct usb_interface *iface
the interface from which it will be unbound
Description
This can be used by drivers to release an interface without waiting for their disconnect() methods to be called. In typical cases this also causes the driver disconnect() method to be called.
This call is synchronous, and may not be used in an interrupt context. Callers must own the device lock, so driver disconnect() entries don’t need extra locking, but other call contexts may need to explicitly claim that lock.
-
const struct usb_device_id *
usb_match_id
(struct usb_interface *interface, const struct usb_device_id *id)¶ find first usb_device_id matching device or interface
Parameters
struct usb_interface *interface
the interface of interest
const struct usb_device_id *id
array of usb_device_id structures, terminated by zero entry
Description
usb_match_id searches an array of usb_device_id’s and returns the first one matching the device or interface, or null. This is used when binding (or rebinding) a driver to an interface. Most USB device drivers will use this indirectly, through the usb core, but some layered driver frameworks use it directly. These device tables are exported with MODULE_DEVICE_TABLE, through modutils, to support the driver loading functionality of USB hotplugging.
What Matches:
The “match_flags” element in a usb_device_id controls which members are used. If the corresponding bit is set, the value in the device_id must match its corresponding member in the device or interface descriptor, or else the device_id does not match.
“driver_info” is normally used only by device drivers, but you can create a wildcard “matches anything” usb_device_id as a driver’s “modules.usbmap” entry if you provide an id with only a nonzero “driver_info” field. If you do this, the USB device driver’s probe() routine should use additional intelligence to decide whether to bind to the specified interface.
What Makes Good usb_device_id Tables:
The match algorithm is very simple, so that intelligence in driver selection must come from smart driver id records. Unless you have good reasons to use another selection policy, provide match elements only in related groups, and order match specifiers from specific to general. Use the macros provided for that purpose if you can.
The most specific match specifiers use device descriptor data. These are commonly used with product-specific matches; the USB_DEVICE macro lets you provide vendor and product IDs, and you can also match against ranges of product revisions. These are widely used for devices with application or vendor specific bDeviceClass values.
Matches based on device class/subclass/protocol specifications are slightly more general; use the USB_DEVICE_INFO macro, or its siblings. These are used with single-function devices where bDeviceClass doesn’t specify that each interface has its own class.
Matches based on interface class/subclass/protocol are the most general; they let drivers bind to any interface on a multiple-function device. Use the USB_INTERFACE_INFO macro, or its siblings, to match class-per-interface style devices (as recorded in bInterfaceClass).
Note that an entry created by USB_INTERFACE_INFO won’t match any interface if the device class is set to Vendor-Specific. This is deliberate; according to the USB spec the meanings of the interface class/subclass/protocol for these devices are also vendor-specific, and hence matching against a standard product class wouldn’t work anyway. If you really want to use an interface-based match for such a device, create a match record that also specifies the vendor ID. (Unforunately there isn’t a standard macro for creating records like this.)
Within those groups, remember that not all combinations are meaningful. For example, don’t give a product version range without vendor and product IDs; or specify a protocol without its associated class and subclass.
Return
The first matching usb_device_id, or NULL
.
-
int
usb_register_device_driver
(struct usb_device_driver *new_udriver, struct module *owner)¶ register a USB device (not interface) driver
Parameters
struct usb_device_driver *new_udriver
USB operations for the device driver
struct module *owner
module owner of this driver.
Description
Registers a USB device driver with the USB core. The list of unattached devices will be rescanned whenever a new driver is added, allowing the new driver to attach to any recognized devices.
Return
A negative error code on failure and 0 on success.
-
void
usb_deregister_device_driver
(struct usb_device_driver *udriver)¶ unregister a USB device (not interface) driver
Parameters
struct usb_device_driver *udriver
USB operations of the device driver to unregister
Context
must be able to sleep
Description
Unlinks the specified driver from the internal USB driver list.
-
int
usb_register_driver
(struct usb_driver *new_driver, struct module *owner, const char *mod_name)¶ register a USB interface driver
Parameters
struct usb_driver *new_driver
USB operations for the interface driver
struct module *owner
module owner of this driver.
const char *mod_name
module name string
Description
Registers a USB interface driver with the USB core. The list of unattached interfaces will be rescanned whenever a new driver is added, allowing the new driver to attach to any recognized interfaces.
Return
A negative error code on failure and 0 on success.
NOTE
if you want your driver to use the USB major number, you must call
usb_register_dev()
to enable that functionality. This function no longer
takes care of that.
-
void
usb_deregister
(struct usb_driver *driver)¶ unregister a USB interface driver
Parameters
struct usb_driver *driver
USB operations of the interface driver to unregister
Context
must be able to sleep
Description
Unlinks the specified driver from the internal USB driver list.
NOTE
If you called usb_register_dev()
, you still need to call
usb_deregister_dev()
to clean up your driver’s allocated minor numbers,
this * call will no longer do it for you.
-
void
usb_enable_autosuspend
(struct usb_device *udev)¶ allow a USB device to be autosuspended
Parameters
struct usb_device *udev
the USB device which may be autosuspended
Description
This routine allows udev to be autosuspended. An autosuspend won’t take place until the autosuspend_delay has elapsed and all the other necessary conditions are satisfied.
The caller must hold udev’s device lock.
-
void
usb_disable_autosuspend
(struct usb_device *udev)¶ prevent a USB device from being autosuspended
Parameters
struct usb_device *udev
the USB device which may not be autosuspended
Description
This routine prevents udev from being autosuspended and wakes it up if it is already autosuspended.
The caller must hold udev’s device lock.
-
void
usb_autopm_put_interface
(struct usb_interface *intf)¶ decrement a USB interface’s PM-usage counter
Parameters
struct usb_interface *intf
the usb_interface whose counter should be decremented
Description
This routine should be called by an interface driver when it is finished using intf and wants to allow it to autosuspend. A typical example would be a character-device driver when its device file is closed.
The routine decrements intf’s usage counter. When the counter reaches 0, a delayed autosuspend request for intf’s device is attempted. The attempt may fail (see autosuspend_check()).
This routine can run only in process context.
-
void
usb_autopm_put_interface_async
(struct usb_interface *intf)¶ decrement a USB interface’s PM-usage counter
Parameters
struct usb_interface *intf
the usb_interface whose counter should be decremented
Description
This routine does much the same thing as usb_autopm_put_interface()
:
It decrements intf’s usage counter and schedules a delayed
autosuspend request if the counter is <= 0. The difference is that it
does not perform any synchronization; callers should hold a private
lock and handle all synchronization issues themselves.
Typically a driver would call this routine during an URB’s completion handler, if no more URBs were pending.
This routine can run in atomic context.
-
void
usb_autopm_put_interface_no_suspend
(struct usb_interface *intf)¶ decrement a USB interface’s PM-usage counter
Parameters
struct usb_interface *intf
the usb_interface whose counter should be decremented
Description
This routine decrements intf’s usage counter but does not carry out an autosuspend.
This routine can run in atomic context.
-
int
usb_autopm_get_interface
(struct usb_interface *intf)¶ increment a USB interface’s PM-usage counter
Parameters
struct usb_interface *intf
the usb_interface whose counter should be incremented
Description
This routine should be called by an interface driver when it wants to
use intf and needs to guarantee that it is not suspended. In addition,
the routine prevents intf from being autosuspended subsequently. (Note
that this will not prevent suspend events originating in the PM core.)
This prevention will persist until usb_autopm_put_interface()
is called
or intf is unbound. A typical example would be a character-device
driver when its device file is opened.
intf’s usage counter is incremented to prevent subsequent autosuspends. However if the autoresume fails then the counter is re-decremented.
This routine can run only in process context.
Return
0 on success.
-
int
usb_autopm_get_interface_async
(struct usb_interface *intf)¶ increment a USB interface’s PM-usage counter
Parameters
struct usb_interface *intf
the usb_interface whose counter should be incremented
Description
This routine does much the same thing as
usb_autopm_get_interface()
: It increments intf’s usage counter and
queues an autoresume request if the device is suspended. The
differences are that it does not perform any synchronization (callers
should hold a private lock and handle all synchronization issues
themselves), and it does not autoresume the device directly (it only
queues a request). After a successful call, the device may not yet be
resumed.
This routine can run in atomic context.
Return
0 on success. A negative error code otherwise.
-
void
usb_autopm_get_interface_no_resume
(struct usb_interface *intf)¶ increment a USB interface’s PM-usage counter
Parameters
struct usb_interface *intf
the usb_interface whose counter should be incremented
Description
This routine increments intf’s usage counter but does not carry out an autoresume.
This routine can run in atomic context.
-
int
usb_find_common_endpoints
(struct usb_host_interface *alt, struct usb_endpoint_descriptor **bulk_in, struct usb_endpoint_descriptor **bulk_out, struct usb_endpoint_descriptor **int_in, struct usb_endpoint_descriptor **int_out)¶ look up common endpoint descriptors
Parameters
struct usb_host_interface *alt
alternate setting to search
struct usb_endpoint_descriptor **bulk_in
pointer to descriptor pointer, or NULL
struct usb_endpoint_descriptor **bulk_out
pointer to descriptor pointer, or NULL
struct usb_endpoint_descriptor **int_in
pointer to descriptor pointer, or NULL
struct usb_endpoint_descriptor **int_out
pointer to descriptor pointer, or NULL
Description
Search the alternate setting’s endpoint descriptors for the first bulk-in, bulk-out, interrupt-in and interrupt-out endpoints and return them in the provided pointers (unless they are NULL).
If a requested endpoint is not found, the corresponding pointer is set to NULL.
Return
Zero if all requested descriptors were found, or -ENXIO otherwise.
-
int
usb_find_common_endpoints_reverse
(struct usb_host_interface *alt, struct usb_endpoint_descriptor **bulk_in, struct usb_endpoint_descriptor **bulk_out, struct usb_endpoint_descriptor **int_in, struct usb_endpoint_descriptor **int_out)¶ look up common endpoint descriptors
Parameters
struct usb_host_interface *alt
alternate setting to search
struct usb_endpoint_descriptor **bulk_in
pointer to descriptor pointer, or NULL
struct usb_endpoint_descriptor **bulk_out
pointer to descriptor pointer, or NULL
struct usb_endpoint_descriptor **int_in
pointer to descriptor pointer, or NULL
struct usb_endpoint_descriptor **int_out
pointer to descriptor pointer, or NULL
Description
Search the alternate setting’s endpoint descriptors for the last bulk-in, bulk-out, interrupt-in and interrupt-out endpoints and return them in the provided pointers (unless they are NULL).
If a requested endpoint is not found, the corresponding pointer is set to NULL.
Return
Zero if all requested descriptors were found, or -ENXIO otherwise.
-
bool
usb_check_bulk_endpoints
(const struct usb_interface *intf, const u8 *ep_addrs)¶ Check whether an interface’s current altsetting contains a set of bulk endpoints with the given addresses.
Parameters
const struct usb_interface *intf
the interface whose current altsetting should be searched
const u8 *ep_addrs
0-terminated array of the endpoint addresses (number and direction) to look for
Description
Search for endpoints with the specified addresses and check their types.
Return
true
if all the endpoints are found and are bulk, false
otherwise.
-
bool
usb_check_int_endpoints
(const struct usb_interface *intf, const u8 *ep_addrs)¶ Check whether an interface’s current altsetting contains a set of interrupt endpoints with the given addresses.
Parameters
const struct usb_interface *intf
the interface whose current altsetting should be searched
const u8 *ep_addrs
0-terminated array of the endpoint addresses (number and direction) to look for
Description
Search for endpoints with the specified addresses and check their types.
Return
true
if all the endpoints are found and are interrupt,
false
otherwise.
-
struct usb_host_interface *
usb_find_alt_setting
(struct usb_host_config *config, unsigned int iface_num, unsigned int alt_num)¶ Given a configuration, find the alternate setting for the given interface.
Parameters
struct usb_host_config *config
the configuration to search (not necessarily the current config).
unsigned int iface_num
interface number to search in
unsigned int alt_num
alternate interface setting number to search for.
Description
Search the configuration’s interface cache for the given alt setting.
Return
The alternate setting, if found. NULL
otherwise.
-
struct usb_interface *
usb_ifnum_to_if
(const struct usb_device *dev, unsigned ifnum)¶ get the interface object with a given interface number
Parameters
const struct usb_device *dev
the device whose current configuration is considered
unsigned ifnum
the desired interface
Description
This walks the device descriptor for the currently active configuration to find the interface object with the particular interface number.
Note that configuration descriptors are not required to assign interface numbers sequentially, so that it would be incorrect to assume that the first interface in that descriptor corresponds to interface zero. This routine helps device drivers avoid such mistakes. However, you should make sure that you do the right thing with any alternate settings available for this interfaces.
Don’t call this function unless you are bound to one of the interfaces on this device or you have locked the device!
Return
A pointer to the interface that has ifnum as interface number,
if found. NULL
otherwise.
-
struct usb_host_interface *
usb_altnum_to_altsetting
(const struct usb_interface *intf, unsigned int altnum)¶ get the altsetting structure with a given alternate setting number.
Parameters
const struct usb_interface *intf
the interface containing the altsetting in question
unsigned int altnum
the desired alternate setting number
Description
This searches the altsetting array of the specified interface for an entry with the correct bAlternateSetting value.
Note that altsettings need not be stored sequentially by number, so it would be incorrect to assume that the first altsetting entry in the array corresponds to altsetting zero. This routine helps device drivers avoid such mistakes.
Don’t call this function unless you are bound to the intf interface or you have locked the device!
Return
A pointer to the entry of the altsetting array of intf that
has altnum as the alternate setting number. NULL
if not found.
-
struct usb_interface *
usb_find_interface
(struct usb_driver *drv, int minor)¶ find usb_interface pointer for driver and device
Parameters
struct usb_driver *drv
the driver whose current configuration is considered
int minor
the minor number of the desired device
Description
This walks the bus device list and returns a pointer to the interface with the matching minor and driver. Note, this only works for devices that share the USB major number.
Return
A pointer to the interface with the matching major and minor.
-
int
usb_for_each_dev
(void *data, int (*fn)(struct usb_device *, void *))¶ iterate over all USB devices in the system
Parameters
void *data
data pointer that will be handed to the callback function
int (*fn)(struct usb_device *, void *)
callback function to be called for each USB device
Description
Iterate over all USB devices and call fn for each, passing it data. If it returns anything other than 0, we break the iteration prematurely and return that value.
-
int
usb_for_each_port
(void *data, int (*fn)(struct device *, void *))¶ interate over all USB ports in the system
Parameters
void *data
data pointer that will be handed to the callback function
int (*fn)(struct device *, void *)
callback function to be called for each USB port
Description
Iterate over all USB ports and call fn for each, passing it data. If it returns anything other than 0, we break the iteration prematurely and return that value.
-
struct usb_device *
usb_alloc_dev
(struct usb_device *parent, struct usb_bus *bus, unsigned port1)¶ usb device constructor (usbcore-internal)
Parameters
struct usb_device *parent
hub to which device is connected; null to allocate a root hub
struct usb_bus *bus
bus used to access the device
unsigned port1
one-based index of port; ignored for root hubs
Context
task context, might sleep.
Description
Only hub drivers (including virtual root hub drivers for host controllers) should ever call this.
This call may not be used in a non-sleeping context.
Return
On success, a pointer to the allocated usb device. NULL
on
failure.
-
struct usb_device *
usb_get_dev
(struct usb_device *dev)¶ increments the reference count of the usb device structure
Parameters
struct usb_device *dev
the device being referenced
Description
Each live reference to a device should be refcounted.
Drivers for USB interfaces should normally record such references in
their probe() methods, when they bind to an interface, and release
them by calling usb_put_dev()
, in their disconnect() methods.
However, if a driver does not access the usb_device structure after
its disconnect() method returns then refcounting is not necessary,
because the USB core guarantees that a usb_device will not be
deallocated until after all of its interface drivers have been unbound.
Return
A pointer to the device with the incremented reference counter.
-
void
usb_put_dev
(struct usb_device *dev)¶ release a use of the usb device structure
Parameters
struct usb_device *dev
device that’s been disconnected
Description
Must be called when a user of a device is finished with it. When the last user of the device calls this function, the memory of the device is freed.
-
struct usb_interface *
usb_get_intf
(struct usb_interface *intf)¶ increments the reference count of the usb interface structure
Parameters
struct usb_interface *intf
the interface being referenced
Description
Each live reference to a interface must be refcounted.
Drivers for USB interfaces should normally record such references in
their probe() methods, when they bind to an interface, and release
them by calling usb_put_intf()
, in their disconnect() methods.
However, if a driver does not access the usb_interface structure after
its disconnect() method returns then refcounting is not necessary,
because the USB core guarantees that a usb_interface will not be
deallocated until after its driver has been unbound.
Return
A pointer to the interface with the incremented reference counter.
-
void
usb_put_intf
(struct usb_interface *intf)¶ release a use of the usb interface structure
Parameters
struct usb_interface *intf
interface that’s been decremented
Description
Must be called when a user of an interface is finished with it. When the last user of the interface calls this function, the memory of the interface is freed.
-
struct device *
usb_intf_get_dma_device
(struct usb_interface *intf)¶ acquire a reference on the usb interface’s DMA endpoint
Parameters
struct usb_interface *intf
the usb interface
Description
While a USB device cannot perform DMA operations by itself, many USB
controllers can. A call to usb_intf_get_dma_device()
returns the DMA endpoint
for the given USB interface, if any. The returned device structure must be
released with put_device()
.
See also usb_get_dma_device().
Return
- A reference to the usb interface’s DMA endpoint; or NULL if none
exists.
-
int
usb_lock_device_for_reset
(struct usb_device *udev, const struct usb_interface *iface)¶ cautiously acquire the lock for a usb device structure
Parameters
struct usb_device *udev
device that’s being locked
const struct usb_interface *iface
interface bound to the driver making the request (optional)
Description
Attempts to acquire the device lock, but fails if the device is NOTATTACHED or SUSPENDED, or if iface is specified and the interface is neither BINDING nor BOUND. Rather than sleeping to wait for the lock, the routine polls repeatedly. This is to prevent deadlock with disconnect; in some drivers (such as usb-storage) the disconnect() or suspend() method will block waiting for a device reset to complete.
Return
A negative error code for failure, otherwise 0.
-
int
usb_get_current_frame_number
(struct usb_device *dev)¶ return current bus frame number
Parameters
struct usb_device *dev
the device whose bus is being queried
Return
The current frame number for the USB host controller used with the given USB device. This can be used when scheduling isochronous requests.
Note
Different kinds of host controller have different “scheduling horizons”. While one type might support scheduling only 32 frames into the future, others could support scheduling up to 1024 frames into the future.
-
void *
usb_alloc_coherent
(struct usb_device *dev, size_t size, gfp_t mem_flags, dma_addr_t *dma)¶ allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
Parameters
struct usb_device *dev
device the buffer will be used with
size_t size
requested buffer size
gfp_t mem_flags
affect whether allocation may block
dma_addr_t *dma
used to return DMA address of buffer
Return
Either null (indicating no buffer could be allocated), or the cpu-space pointer to a buffer that may be used to perform DMA to the specified device. Such cpu-space buffers are returned along with the DMA address (through the pointer provided).
Note
These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags to avoid behaviors like using “DMA bounce buffers”, or thrashing IOMMU hardware during URB completion/resubmit. The implementation varies between platforms, depending on details of how DMA will work to this device. Using these buffers also eliminates cacheline sharing problems on architectures where CPU caches are not DMA-coherent. On systems without bus-snooping caches, these buffers are uncached.
Description
When the buffer is no longer used, free it with usb_free_coherent()
.
-
void
usb_free_coherent
(struct usb_device *dev, size_t size, void *addr, dma_addr_t dma)¶ free memory allocated with
usb_alloc_coherent()
Parameters
struct usb_device *dev
device the buffer was used with
size_t size
requested buffer size
void *addr
CPU address of buffer
dma_addr_t dma
DMA address of buffer
Description
This reclaims an I/O buffer, letting it be reused. The memory must have
been allocated using usb_alloc_coherent()
, and the parameters must match
those provided in that allocation request.
-
int
usb_hub_clear_tt_buffer
(struct urb *urb)¶ clear control/bulk TT state in high speed hub
Parameters
struct urb *urb
an URB associated with the failed or incomplete split transaction
Description
High speed HCDs use this to tell the hub driver that some split control or bulk transaction failed in a way that requires clearing internal state of a transaction translator. This is normally detected (and reported) from interrupt context.
It may not be possible for that hub to handle additional full (or low) speed transactions until that state is fully cleared out.
Return
0 if successful. A negative error code otherwise.
-
void
usb_set_device_state
(struct usb_device *udev, enum usb_device_state new_state)¶ change a device’s current state (usbcore, hcds)
Parameters
struct usb_device *udev
pointer to device whose state should be changed
enum usb_device_state new_state
new state value to be stored
Description
udev->state is _not_ fully protected by the device lock. Although most transitions are made only while holding the lock, the state can can change to USB_STATE_NOTATTACHED at almost any time. This is so that devices can be marked as disconnected as soon as possible, without having to wait for any semaphores to be released. As a result, all changes to any device’s state must be protected by the device_state_lock spinlock.
Once a device has been added to the device tree, all changes to its state should be made using this routine. The state should _not_ be set directly.
If udev->state is already USB_STATE_NOTATTACHED then no change is made. Otherwise udev->state is set to new_state, and if new_state is USB_STATE_NOTATTACHED then all of udev’s descendants’ states are also set to USB_STATE_NOTATTACHED.
-
void
usb_root_hub_lost_power
(struct usb_device *rhdev)¶ called by HCD if the root hub lost Vbus power
Parameters
struct usb_device *rhdev
struct usb_device for the root hub
Description
The USB host controller driver calls this function when its root hub is resumed and Vbus power has been interrupted or the controller has been reset. The routine marks rhdev as having lost power. When the hub driver is resumed it will take notice and carry out power-session recovery for all the “USB-PERSIST”-enabled child devices; the others will be disconnected.
-
int
usb_reset_device
(struct usb_device *udev)¶ warn interface drivers and perform a USB port reset
Parameters
struct usb_device *udev
device to reset (not in NOTATTACHED state)
Description
Warns all drivers bound to registered interfaces (using their pre_reset method), performs the port reset, and then lets the drivers know that the reset is over (using their post_reset method).
If an interface is currently being probed or disconnected, we assume its driver knows how to handle resets. For all other interfaces, if the driver doesn’t have pre_reset and post_reset methods then we attempt to unbind it and rebind afterward.
Return
The same as for usb_reset_and_verify_device(). However, if a reset is already in progress (for instance, if a driver doesn’t have pre_reset() or post_reset() callbacks, and while being unbound or re-bound during the ongoing reset its disconnect() or probe() routine tries to perform a second, nested reset), the routine returns -EINPROGRESS.
Note
The caller must own the device lock. For example, it’s safe to use
this from a driver probe() routine after downloading new firmware.
For calls that might not occur during probe(), drivers should lock
the device using usb_lock_device_for_reset()
.
-
void
usb_queue_reset_device
(struct usb_interface *iface)¶ Reset a USB device from an atomic context
Parameters
struct usb_interface *iface
USB interface belonging to the device to reset
Description
This function can be used to reset a USB device from an atomic
context, where usb_reset_device()
won’t work (as it blocks).
Doing a reset via this method is functionally equivalent to calling
usb_reset_device()
, except for the fact that it is delayed to a
workqueue. This means that any drivers bound to other interfaces
might be unbound, as well as users from usbfs in user space.
Corner cases:
Scheduling two resets at the same time from two different drivers attached to two different interfaces of the same device is possible; depending on how the driver attached to each interface handles ->pre_reset(), the second reset might happen or not.
If the reset is delayed so long that the interface is unbound from its driver, the reset will be skipped.
This function can be called during .probe(). It can also be called during .disconnect(), but doing so is pointless because the reset will not occur. If you really want to reset the device during .disconnect(), call
usb_reset_device()
directly – but watch out for nested unbinding issues!
-
struct usb_device *
usb_hub_find_child
(struct usb_device *hdev, int port1)¶ Get the pointer of child device attached to the port which is specified by port1.
Parameters
struct usb_device *hdev
USB device belonging to the usb hub
int port1
port num to indicate which port the child device is attached to.
Description
USB drivers call this function to get hub’s child device pointer.
Return
NULL
if input param is invalid and
child’s usb_device pointer if non-NULL.
Host Controller APIs¶
These APIs are only for use by host controller drivers, most of which implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI was one of the first interfaces, designed by Intel and also used by VIA; it doesn’t do much in hardware. OHCI was designed later, to have the hardware do more work (bigger transfers, tracking protocol state, and so on). EHCI was designed with USB 2.0; its design has features that resemble OHCI (hardware does much more work) as well as UHCI (some parts of ISO support, TD list processing). XHCI was designed with USB 3.0. It continues to shift support for functionality into hardware.
There are host controllers other than the “big three”, although most PCI based controllers (and a few non-PCI based ones) use one of those interfaces. Not all host controllers use DMA; some use PIO, and there is also a simulator and a virtual host controller to pipe USB over the network.
The same basic APIs are available to drivers for all those controllers.
For historical reasons they are in two layers: struct
usb_bus
is a rather thin layer that became available
in the 2.2 kernels, while struct usb_hcd
is a more featureful layer
that lets HCDs share common code, to shrink driver size and
significantly reduce hcd-specific behaviors.
-
long
usb_calc_bus_time
(int speed, int is_input, int isoc, int bytecount)¶ approximate periodic transaction time in nanoseconds
Parameters
int speed
from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
int is_input
true iff the transaction sends data to the host
int isoc
true for isochronous transactions, false for interrupt ones
int bytecount
how many bytes in the transaction.
Return
Approximate bus time in nanoseconds for a periodic transaction.
Note
See USB 2.0 spec section 5.11.3; only periodic transfers need to be scheduled in software, this function is only used for such scheduling.
-
int
usb_hcd_link_urb_to_ep
(struct usb_hcd *hcd, struct urb *urb)¶ add an URB to its endpoint queue
Parameters
struct usb_hcd *hcd
host controller to which urb was submitted
struct urb *urb
URB being submitted
Description
Host controller drivers should call this routine in their enqueue() method. The HCD’s private spinlock must be held and interrupts must be disabled. The actions carried out here are required for URB submission, as well as for endpoint shutdown and for usb_kill_urb.
Return
0 for no error, otherwise a negative error code (in which case
the enqueue() method must fail). If no error occurs but enqueue() fails
anyway, it must call usb_hcd_unlink_urb_from_ep()
before releasing
the private spinlock and returning.
-
int
usb_hcd_check_unlink_urb
(struct usb_hcd *hcd, struct urb *urb, int status)¶ check whether an URB may be unlinked
Parameters
struct usb_hcd *hcd
host controller to which urb was submitted
struct urb *urb
URB being checked for unlinkability
int status
error code to store in urb if the unlink succeeds
Description
Host controller drivers should call this routine in their dequeue() method. The HCD’s private spinlock must be held and interrupts must be disabled. The actions carried out here are required for making sure than an unlink is valid.
Return
0 for no error, otherwise a negative error code (in which case the dequeue() method must fail). The possible error codes are:
- -EIDRM: urb was not submitted or has already completed.
The completion function may not have been called yet.
-EBUSY: urb has already been unlinked.
-
void
usb_hcd_unlink_urb_from_ep
(struct usb_hcd *hcd, struct urb *urb)¶ remove an URB from its endpoint queue
Parameters
struct usb_hcd *hcd
host controller to which urb was submitted
struct urb *urb
URB being unlinked
Description
Host controller drivers should call this routine before calling
usb_hcd_giveback_urb()
. The HCD’s private spinlock must be held and
interrupts must be disabled. The actions carried out here are required
for URB completion.
-
void
usb_hcd_giveback_urb
(struct usb_hcd *hcd, struct urb *urb, int status)¶ return URB from HCD to device driver
Parameters
struct usb_hcd *hcd
host controller returning the URB
struct urb *urb
urb being returned to the USB device driver.
int status
completion status code for the URB.
Context
atomic. The completion callback is invoked in caller’s context. For HCDs with HCD_BH flag set, the completion callback is invoked in tasklet context (except for URBs submitted to the root hub which always complete in caller’s context).
Description
This hands the URB from HCD to its USB device driver, using its completion function. The HCD has freed all per-urb resources (and is done using urb->hcpriv). It also released all HCD locks; the device driver won’t cause problems if it frees, modifies, or resubmits this URB.
If urb was unlinked, the value of status will be overridden by urb->unlinked. Erroneous short transfers are detected in case the HCD hasn’t checked for them.
-
int
usb_alloc_streams
(struct usb_interface *interface, struct usb_host_endpoint **eps, unsigned int num_eps, unsigned int num_streams, gfp_t mem_flags)¶ allocate bulk endpoint stream IDs.
Parameters
struct usb_interface *interface
alternate setting that includes all endpoints.
struct usb_host_endpoint **eps
array of endpoints that need streams.
unsigned int num_eps
number of endpoints in the array.
unsigned int num_streams
number of streams to allocate.
gfp_t mem_flags
flags hcd should use to allocate memory.
Description
Sets up a group of bulk endpoints to have num_streams stream IDs available. Drivers may queue multiple transfers to different stream IDs, which may complete in a different order than they were queued.
Return
On success, the number of allocated streams. On failure, a negative error code.
-
int
usb_free_streams
(struct usb_interface *interface, struct usb_host_endpoint **eps, unsigned int num_eps, gfp_t mem_flags)¶ free bulk endpoint stream IDs.
Parameters
struct usb_interface *interface
alternate setting that includes all endpoints.
struct usb_host_endpoint **eps
array of endpoints to remove streams from.
unsigned int num_eps
number of endpoints in the array.
gfp_t mem_flags
flags hcd should use to allocate memory.
Description
Reverts a group of bulk endpoints back to not using stream IDs. Can fail if we are given bad arguments, or HCD is broken.
Return
0 on success. On failure, a negative error code.
-
void
usb_hcd_resume_root_hub
(struct usb_hcd *hcd)¶ called by HCD to resume its root hub
Parameters
struct usb_hcd *hcd
host controller for this root hub
Description
The USB host controller calls this function when its root hub is suspended (with the remote wakeup feature enabled) and a remote wakeup request is received. The routine submits a workqueue request to resume the root hub (that is, manage its downstream ports again).
-
int
usb_bus_start_enum
(struct usb_bus *bus, unsigned port_num)¶ start immediate enumeration (for OTG)
Parameters
struct usb_bus *bus
the bus (must use hcd framework)
unsigned port_num
1-based number of port; usually bus->otg_port
Context
atomic
Description
Starts enumeration, with an immediate reset followed later by hub_wq identifying and possibly configuring the device. This is needed by OTG controller drivers, where it helps meet HNP protocol timing requirements for starting a port reset.
Return
0 if successful.
-
irqreturn_t
usb_hcd_irq
(int irq, void *__hcd)¶ hook IRQs to HCD framework (bus glue)
Parameters
int irq
the IRQ being raised
void *__hcd
pointer to the HCD whose IRQ is being signaled
Description
If the controller isn’t HALTed, calls the driver’s irq handler. Checks whether the controller is now dead.
Return
IRQ_HANDLED
if the IRQ was handled. IRQ_NONE
otherwise.
-
void
usb_hc_died
(struct usb_hcd *hcd)¶ report abnormal shutdown of a host controller (bus glue)
Parameters
struct usb_hcd *hcd
pointer to the HCD representing the controller
Description
This is called by bus glue to report a USB host controller that died while operations may still have been pending. It’s called automatically by the PCI glue, so only glue for non-PCI busses should need to call it.
Only call this function with the primary HCD.
create and initialize an HCD structure
Parameters
const struct hc_driver *driver
HC driver that will use this hcd
struct device *dev
device for this HC, stored in hcd->self.controller
const char *bus_name
value to store in hcd->self.bus_name
struct usb_hcd *primary_hcd
a pointer to the usb_hcd structure that is sharing the PCI device. Only allocate certain resources for the primary HCD
Context
task context, might sleep.
Description
Allocate a struct usb_hcd, with extra space at the end for the HC driver’s private data. Initialize the generic members of the hcd structure.
Return
On success, a pointer to the created and initialized HCD structure.
On failure (e.g. if memory is unavailable), NULL
.
-
struct usb_hcd *
usb_create_hcd
(const struct hc_driver *driver, struct device *dev, const char *bus_name)¶ create and initialize an HCD structure
Parameters
const struct hc_driver *driver
HC driver that will use this hcd
struct device *dev
device for this HC, stored in hcd->self.controller
const char *bus_name
value to store in hcd->self.bus_name
Context
task context, might sleep.
Description
Allocate a struct usb_hcd, with extra space at the end for the HC driver’s private data. Initialize the generic members of the hcd structure.
Return
On success, a pointer to the created and initialized HCD
structure. On failure (e.g. if memory is unavailable), NULL
.
-
int
usb_add_hcd
(struct usb_hcd *hcd, unsigned int irqnum, unsigned long irqflags)¶ finish generic HCD structure initialization and register
Parameters
struct usb_hcd *hcd
the usb_hcd structure to initialize
unsigned int irqnum
Interrupt line to allocate
unsigned long irqflags
Interrupt type flags
Description
Finish the remaining parts of generic HCD initialization: allocate the
buffers of consistent memory, register the bus, request the IRQ line,
and call the driver’s reset() and start()
routines.
-
void
usb_remove_hcd
(struct usb_hcd *hcd)¶ shutdown processing for generic HCDs
Parameters
struct usb_hcd *hcd
the usb_hcd structure to remove
Context
task context, might sleep.
Description
Disconnects the root hub, then reverses the effects of usb_add_hcd()
,
invoking the HCD’s stop()
method.
-
int
usb_hcd_pci_probe
(struct pci_dev *dev, const struct hc_driver *driver)¶ initialize PCI-based HCDs
Parameters
struct pci_dev *dev
USB Host Controller being probed
const struct hc_driver *driver
USB HC driver handle
Context
task context, might sleep
Description
Allocates basic PCI resources for this USB host controller, and
then invokes the start()
method for the HCD associated with it
through the hotplug entry’s driver_data.
Store this function in the HCD’s struct pci_driver
as probe().
Return
0 if successful.
-
void
usb_hcd_pci_remove
(struct pci_dev *dev)¶ shutdown processing for PCI-based HCDs
Parameters
struct pci_dev *dev
USB Host Controller being removed
Context
task context, might sleep
Description
Reverses the effect of usb_hcd_pci_probe()
, first invoking
the HCD’s stop()
method. It is always called from a thread
context, normally “rmmod”, “apmd”, or something similar.
Store this function in the HCD’s struct pci_driver
as remove().
-
void
usb_hcd_pci_shutdown
(struct pci_dev *dev)¶ shutdown host controller
Parameters
struct pci_dev *dev
USB Host Controller being shutdown
-
int
hcd_buffer_create
(struct usb_hcd *hcd)¶ initialize buffer pools
Parameters
struct usb_hcd *hcd
the bus whose buffer pools are to be initialized
Context
task context, might sleep
Description
Call this as part of initializing a host controller that uses the dma memory allocators. It initializes some pools of dma-coherent memory that will be shared by all drivers using that controller.
Call hcd_buffer_destroy()
to clean up after using those pools.
Return
0 if successful. A negative errno value otherwise.
-
void
hcd_buffer_destroy
(struct usb_hcd *hcd)¶ deallocate buffer pools
Parameters
struct usb_hcd *hcd
the bus whose buffer pools are to be destroyed
Context
task context, might sleep
Description
This frees the buffer pools created by hcd_buffer_create()
.
The USB character device nodes¶
This chapter presents the Linux character device nodes. You may prefer to avoid writing new kernel code for your USB driver. User mode device drivers are usually packaged as applications or libraries, and may use character devices through some programming library that wraps it. Such libraries include:
Some old information about it can be seen at the “USB Device Filesystem” section of the USB Guide. The latest copy of the USB Guide can be found at http://www.linux-usb.org/
Note
They were used to be implemented via usbfs, but this is not part of the sysfs debug interface.
This particular documentation is incomplete, especially with respect to the asynchronous mode. As of kernel 2.5.66 the code and this (new) documentation need to be cross-reviewed.
What files are in “devtmpfs”?¶
Conventionally mounted at /dev/bus/usb/
, usbfs features include:
/dev/bus/usb/BBB/DDD
… magic files exposing the each device’s configuration descriptors, and supporting a series of ioctls for making device requests, including I/O to devices. (Purely for access by programs.)
Each bus is given a number (BBB
) based on when it was enumerated; within
each bus, each device is given a similar number (DDD
). Those BBB/DDD
paths are not “stable” identifiers; expect them to change even if you
always leave the devices plugged in to the same hub port. Don’t even
think of saving these in application configuration files. Stable
identifiers are available, for user mode applications that want to use
them. HID and networking devices expose these stable IDs, so that for
example you can be sure that you told the right UPS to power down its
second server. Pleast note that it doesn’t (yet) expose those IDs.
/dev/bus/usb/BBB/DDD¶
Use these files in one of these basic ways:
They can be read, producing first the device descriptor (18 bytes) and then the descriptors for the current configuration. See the USB 2.0 spec for details about those binary data formats. You’ll need to convert most multibyte values from little endian format to your native host byte order, although a few of the fields in the device descriptor (both of the BCD-encoded fields, and the vendor and product IDs) will be byteswapped for you. Note that configuration descriptors include descriptors for interfaces, altsettings, endpoints, and maybe additional class descriptors.
Perform USB operations using ioctl() requests to make endpoint I/O requests (synchronously or asynchronously) or manage the device. These requests need the
CAP_SYS_RAWIO
capability, as well as filesystem access permissions. Only one ioctl request can be made on one of these device files at a time. This means that if you are synchronously reading an endpoint from one thread, you won’t be able to write to a different endpoint from another thread until the read completes. This works for half duplex protocols, but otherwise you’d use asynchronous i/o requests.
Each connected USB device has one file. The BBB
indicates the bus
number. The DDD
indicates the device address on that bus. Both
of these numbers are assigned sequentially, and can be reused, so
you can’t rely on them for stable access to devices. For example,
it’s relatively common for devices to re-enumerate while they are
still connected (perhaps someone jostled their power supply, hub,
or USB cable), so a device might be 002/027
when you first connect
it and 002/048
sometime later.
These files can be read as binary data. The binary data consists
of first the device descriptor, then the descriptors for each
configuration of the device. Multi-byte fields in the device descriptor
are converted to host endianness by the kernel. The configuration
descriptors are in bus endian format! The configuration descriptor
are wTotalLength bytes apart. If a device returns less configuration
descriptor data than indicated by wTotalLength there will be a hole in
the file for the missing bytes. This information is also shown
in text form by the /sys/kernel/debug/usb/devices
file, described later.
These files may also be used to write user-level drivers for the USB
devices. You would open the /dev/bus/usb/BBB/DDD
file read/write,
read its descriptors to make sure it’s the device you expect, and then
bind to an interface (or perhaps several) using an ioctl call. You
would issue more ioctls to the device to communicate to it using
control, bulk, or other kinds of USB transfers. The IOCTLs are
listed in the <linux/usbdevice_fs.h>
file, and at this writing the
source code (linux/drivers/usb/core/devio.c
) is the primary reference
for how to access devices through those files.
Note that since by default these BBB/DDD
files are writable only by
root, only root can write such user mode drivers. You can selectively
grant read/write permissions to other users by using chmod
. Also,
usbfs mount options such as devmode=0666
may be helpful.
Life Cycle of User Mode Drivers¶
Such a driver first needs to find a device file for a device it knows
how to handle. Maybe it was told about it because a /sbin/hotplug
event handling agent chose that driver to handle the new device. Or
maybe it’s an application that scans all the /dev/bus/usb
device files,
and ignores most devices. In either case, it should read()
all the descriptors from the device file, and check them against what it
knows how to handle. It might just reject everything except a particular
vendor and product ID, or need a more complex policy.
Never assume there will only be one such device on the system at a time! If your code can’t handle more than one device at a time, at least detect when there’s more than one, and have your users choose which device to use.
Once your user mode driver knows what device to use, it interacts with it in either of two styles. The simple style is to make only control requests; some devices don’t need more complex interactions than those. (An example might be software using vendor-specific control requests for some initialization or configuration tasks, with a kernel driver for the rest.)
More likely, you need a more complex style driver: one using non-control endpoints, reading or writing data and claiming exclusive use of an interface. Bulk transfers are easiest to use, but only their sibling interrupt transfers work with low speed devices. Both interrupt and isochronous transfers offer service guarantees because their bandwidth is reserved. Such “periodic” transfers are awkward to use through usbfs, unless you’re using the asynchronous calls. However, interrupt transfers can also be used in a synchronous “one shot” style.
Your user-mode driver should never need to worry about cleaning up request state when the device is disconnected, although it should close its open file descriptors as soon as it starts seeing the ENODEV errors.
The ioctl() Requests¶
To use these ioctls, you need to include the following headers in your userspace program:
#include <linux/usb.h>
#include <linux/usbdevice_fs.h>
#include <asm/byteorder.h>
The standard USB device model requests, from “Chapter 9” of the USB 2.0
specification, are automatically included from the <linux/usb/ch9.h>
header.
Unless noted otherwise, the ioctl requests described here will update the modification time on the usbfs file to which they are applied (unless they fail). A return of zero indicates success; otherwise, a standard USB error code is returned (These are documented in USB Error codes).
Each of these files multiplexes access to several I/O streams, one per endpoint. Each device has one control endpoint (endpoint zero) which supports a limited RPC style RPC access. Devices are configured by hub_wq (in the kernel) setting a device-wide configuration that affects things like power consumption and basic functionality. The endpoints are part of USB interfaces, which may have altsettings affecting things like which endpoints are available. Many devices only have a single configuration and interface, so drivers for them will ignore configurations and altsettings.
Management/Status Requests¶
A number of usbfs requests don’t deal very directly with device I/O. They mostly relate to device management and status. These are all synchronous requests.
- USBDEVFS_CLAIMINTERFACE
This is used to force usbfs to claim a specific interface, which has not previously been claimed by usbfs or any other kernel driver. The ioctl parameter is an integer holding the number of the interface (bInterfaceNumber from descriptor).
Note that if your driver doesn’t claim an interface before trying to use one of its endpoints, and no other driver has bound to it, then the interface is automatically claimed by usbfs.
This claim will be released by a RELEASEINTERFACE ioctl, or by closing the file descriptor. File modification time is not updated by this request.
- USBDEVFS_CONNECTINFO
Says whether the device is lowspeed. The ioctl parameter points to a structure like this:
struct usbdevfs_connectinfo { unsigned int devnum; unsigned char slow; };
File modification time is not updated by this request.
You can’t tell whether a “not slow” device is connected at high speed (480 MBit/sec) or just full speed (12 MBit/sec). You should know the devnum value already, it’s the DDD value of the device file name.
- USBDEVFS_GETDRIVER
Returns the name of the kernel driver bound to a given interface (a string). Parameter is a pointer to this structure, which is modified:
struct usbdevfs_getdriver { unsigned int interface; char driver[USBDEVFS_MAXDRIVERNAME + 1]; };
File modification time is not updated by this request.
- USBDEVFS_IOCTL
Passes a request from userspace through to a kernel driver that has an ioctl entry in the struct usb_driver it registered:
struct usbdevfs_ioctl { int ifno; int ioctl_code; void *data; }; /* user mode call looks like this. * 'request' becomes the driver->ioctl() 'code' parameter. * the size of 'param' is encoded in 'request', and that data * is copied to or from the driver->ioctl() 'buf' parameter. */ static int usbdev_ioctl (int fd, int ifno, unsigned request, void *param) { struct usbdevfs_ioctl wrapper; wrapper.ifno = ifno; wrapper.ioctl_code = request; wrapper.data = param; return ioctl (fd, USBDEVFS_IOCTL, &wrapper); }
File modification time is not updated by this request.
This request lets kernel drivers talk to user mode code through filesystem operations even when they don’t create a character or block special device. It’s also been used to do things like ask devices what device special file should be used. Two pre-defined ioctls are used to disconnect and reconnect kernel drivers, so that user mode code can completely manage binding and configuration of devices.
- USBDEVFS_RELEASEINTERFACE
This is used to release the claim usbfs made on interface, either implicitly or because of a USBDEVFS_CLAIMINTERFACE call, before the file descriptor is closed. The ioctl parameter is an integer holding the number of the interface (bInterfaceNumber from descriptor); File modification time is not updated by this request.
Warning
No security check is made to ensure that the task which made the claim is the one which is releasing it. This means that user mode driver may interfere other ones.
- USBDEVFS_RESETEP
Resets the data toggle value for an endpoint (bulk or interrupt) to DATA0. The ioctl parameter is an integer endpoint number (1 to 15, as identified in the endpoint descriptor), with USB_DIR_IN added if the device’s endpoint sends data to the host.
Warning
Avoid using this request. It should probably be removed. Using it typically means the device and driver will lose toggle synchronization. If you really lost synchronization, you likely need to completely handshake with the device, using a request like CLEAR_HALT or SET_INTERFACE.
- USBDEVFS_DROP_PRIVILEGES
This is used to relinquish the ability to do certain operations which are considered to be privileged on a usbfs file descriptor. This includes claiming arbitrary interfaces, resetting a device on which there are currently claimed interfaces from other users, and issuing USBDEVFS_IOCTL calls. The ioctl parameter is a 32 bit mask of interfaces the user is allowed to claim on this file descriptor. You may issue this ioctl more than one time to narrow said mask.
Synchronous I/O Support¶
Synchronous requests involve the kernel blocking until the user mode request completes, either by finishing successfully or by reporting an error. In most cases this is the simplest way to use usbfs, although as noted above it does prevent performing I/O to more than one endpoint at a time.
- USBDEVFS_BULK
Issues a bulk read or write request to the device. The ioctl parameter is a pointer to this structure:
struct usbdevfs_bulktransfer { unsigned int ep; unsigned int len; unsigned int timeout; /* in milliseconds */ void *data; };
The
ep
value identifies a bulk endpoint number (1 to 15, as identified in an endpoint descriptor), masked with USB_DIR_IN when referring to an endpoint which sends data to the host from the device. The length of the data buffer is identified bylen
; Recent kernels support requests up to about 128KBytes. FIXME say how read length is returned, and how short reads are handled..- USBDEVFS_CLEAR_HALT
Clears endpoint halt (stall) and resets the endpoint toggle. This is only meaningful for bulk or interrupt endpoints. The ioctl parameter is an integer endpoint number (1 to 15, as identified in an endpoint descriptor), masked with USB_DIR_IN when referring to an endpoint which sends data to the host from the device.
Use this on bulk or interrupt endpoints which have stalled, returning
-EPIPE
status to a data transfer request. Do not issue the control request directly, since that could invalidate the host’s record of the data toggle.- USBDEVFS_CONTROL
Issues a control request to the device. The ioctl parameter points to a structure like this:
struct usbdevfs_ctrltransfer { __u8 bRequestType; __u8 bRequest; __u16 wValue; __u16 wIndex; __u16 wLength; __u32 timeout; /* in milliseconds */ void *data; };
The first eight bytes of this structure are the contents of the SETUP packet to be sent to the device; see the USB 2.0 specification for details. The bRequestType value is composed by combining a
USB_TYPE_*
value, aUSB_DIR_*
value, and aUSB_RECIP_*
value (fromlinux/usb.h
). If wLength is nonzero, it describes the length of the data buffer, which is either written to the device (USB_DIR_OUT) or read from the device (USB_DIR_IN).At this writing, you can’t transfer more than 4 KBytes of data to or from a device; usbfs has a limit, and some host controller drivers have a limit. (That’s not usually a problem.) Also there’s no way to say it’s not OK to get a short read back from the device.
- USBDEVFS_RESET
Does a USB level device reset. The ioctl parameter is ignored. After the reset, this rebinds all device interfaces. File modification time is not updated by this request.
Warning
Avoid using this call until some usbcore bugs get fixed, since it does not fully synchronize device, interface, and driver (not just usbfs) state.
- USBDEVFS_SETINTERFACE
Sets the alternate setting for an interface. The ioctl parameter is a pointer to a structure like this:
struct usbdevfs_setinterface { unsigned int interface; unsigned int altsetting; };
File modification time is not updated by this request.
Those struct members are from some interface descriptor applying to the current configuration. The interface number is the bInterfaceNumber value, and the altsetting number is the bAlternateSetting value. (This resets each endpoint in the interface.)
- USBDEVFS_SETCONFIGURATION
Issues the
usb_set_configuration()
call for the device. The parameter is an integer holding the number of a configuration (bConfigurationValue from descriptor). File modification time is not updated by this request.
Warning
Avoid using this call until some usbcore bugs get fixed, since it does not fully synchronize device, interface, and driver (not just usbfs) state.
Asynchronous I/O Support¶
As mentioned above, there are situations where it may be important to initiate concurrent operations from user mode code. This is particularly important for periodic transfers (interrupt and isochronous), but it can be used for other kinds of USB requests too. In such cases, the asynchronous requests described here are essential. Rather than submitting one request and having the kernel block until it completes, the blocking is separate.
These requests are packaged into a structure that resembles the URB used
by kernel device drivers. (No POSIX Async I/O support here, sorry.) It
identifies the endpoint type (USBDEVFS_URB_TYPE_*
), endpoint
(number, masked with USB_DIR_IN as appropriate), buffer and length,
and a user “context” value serving to uniquely identify each request.
(It’s usually a pointer to per-request data.) Flags can modify requests
(not as many as supported for kernel drivers).
Each request can specify a realtime signal number (between SIGRTMIN and SIGRTMAX, inclusive) to request a signal be sent when the request completes.
When usbfs returns these urbs, the status value is updated, and the buffer may have been modified. Except for isochronous transfers, the actual_length is updated to say how many bytes were transferred; if the USBDEVFS_URB_DISABLE_SPD flag is set (“short packets are not OK”), if fewer bytes were read than were requested then you get an error report:
struct usbdevfs_iso_packet_desc {
unsigned int length;
unsigned int actual_length;
unsigned int status;
};
struct usbdevfs_urb {
unsigned char type;
unsigned char endpoint;
int status;
unsigned int flags;
void *buffer;
int buffer_length;
int actual_length;
int start_frame;
int number_of_packets;
int error_count;
unsigned int signr;
void *usercontext;
struct usbdevfs_iso_packet_desc iso_frame_desc[];
};
For these asynchronous requests, the file modification time reflects when the request was initiated. This contrasts with their use with the synchronous requests, where it reflects when requests complete.
- USBDEVFS_DISCARDURB
TBS File modification time is not updated by this request.
- USBDEVFS_DISCSIGNAL
TBS File modification time is not updated by this request.
- USBDEVFS_REAPURB
TBS File modification time is not updated by this request.
- USBDEVFS_REAPURBNDELAY
TBS File modification time is not updated by this request.
- USBDEVFS_SUBMITURB
TBS
The USB devices¶
The USB devices are now exported via debugfs:
/sys/kernel/debug/usb/devices
… a text file showing each of the USB devices on known to the kernel, and their configuration descriptors. You can also poll() this to learn about new devices.
/sys/kernel/debug/usb/devices¶
This file is handy for status viewing tools in user mode, which can scan the text format and ignore most of it. More detailed device status (including class and vendor status) is available from device-specific files. For information about the current format of this file, see below.
This file, in combination with the poll() system call, can also be used to detect when devices are added or removed:
int fd;
struct pollfd pfd;
fd = open("/sys/kernel/debug/usb/devices", O_RDONLY);
pfd = { fd, POLLIN, 0 };
for (;;) {
/* The first time through, this call will return immediately. */
poll(&pfd, 1, -1);
/* To see what's changed, compare the file's previous and current
contents or scan the filesystem. (Scanning is more precise.) */
}
Note that this behavior is intended to be used for informational and debug purposes. It would be more appropriate to use programs such as udev or HAL to initialize a device or start a user-mode helper program, for instance.
In this file, each device’s output has multiple lines of ASCII output.
I made it ASCII instead of binary on purpose, so that someone
can obtain some useful data from it without the use of an
auxiliary program. However, with an auxiliary program, the numbers
in the first 4 columns of each T:
line (topology info:
Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.
Each line is tagged with a one-character ID for that line:
T = Topology (etc.)
B = Bandwidth (applies only to USB host controllers, which are
virtualized as root hubs)
D = Device descriptor info.
P = Product ID info. (from Device descriptor, but they won't fit
together on one line)
S = String descriptors.
C = Configuration descriptor info. (* = active configuration)
I = Interface descriptor info.
E = Endpoint descriptor info.
/sys/kernel/debug/usb/devices output format¶
- Legend::
d = decimal number (may have leading spaces or 0’s) x = hexadecimal number (may have leading spaces or 0’s) s = string
Topology info¶
T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=dddd MxCh=dd
| | | | | | | | |__MaxChildren
| | | | | | | |__Device Speed in Mbps
| | | | | | |__DeviceNumber
| | | | | |__Count of devices at this level
| | | | |__Connector/Port on Parent for this device
| | | |__Parent DeviceNumber
| | |__Level in topology for this bus
| |__Bus number
|__Topology info tag
Speed may be:
1.5
Mbit/s for low speed USB
12
Mbit/s for full speed USB
480
Mbit/s for high speed USB (added for USB 2.0); also used for Wireless USB, which has no fixed speed
5000
Mbit/s for SuperSpeed USB (added for USB 3.0)
For reasons lost in the mists of time, the Port number is always
too low by 1. For example, a device plugged into port 4 will
show up with Port=03
.
Bandwidth info¶
B: Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
| | | |__Number of isochronous requests
| | |__Number of interrupt requests
| |__Total Bandwidth allocated to this bus
|__Bandwidth info tag
Bandwidth allocation is an approximation of how much of one frame (millisecond) is in use. It reflects only periodic transfers, which are the only transfers that reserve bandwidth. Control and bulk transfers use all other bandwidth, including reserved bandwidth that is not used for transfers (such as for short packets).
The percentage is how much of the “reserved” bandwidth is scheduled by those transfers. For a low or full speed bus (loosely, “USB 1.1”), 90% of the bus bandwidth is reserved. For a high speed bus (loosely, “USB 2.0”) 80% is reserved.
Device descriptor info & Product ID info¶
D: Ver=x.xx Cls=xx(s) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
where:
D: Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
| | | | | | |__NumberConfigurations
| | | | | |__MaxPacketSize of Default Endpoint
| | | | |__DeviceProtocol
| | | |__DeviceSubClass
| | |__DeviceClass
| |__Device USB version
|__Device info tag #1
where:
P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
| | | |__Product revision number
| | |__Product ID code
| |__Vendor ID code
|__Device info tag #2
String descriptor info¶
S: Manufacturer=ssss
| |__Manufacturer of this device as read from the device.
| For USB host controller drivers (virtual root hubs) this may
| be omitted, or (for newer drivers) will identify the kernel
| version and the driver which provides this hub emulation.
|__String info tag
S: Product=ssss
| |__Product description of this device as read from the device.
| For older USB host controller drivers (virtual root hubs) this
| indicates the driver; for newer ones, it's a product (and vendor)
| description that often comes from the kernel's PCI ID database.
|__String info tag
S: SerialNumber=ssss
| |__Serial Number of this device as read from the device.
| For USB host controller drivers (virtual root hubs) this is
| some unique ID, normally a bus ID (address or slot name) that
| can't be shared with any other device.
|__String info tag
Configuration descriptor info¶
C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
| | | | | |__MaxPower in mA
| | | | |__Attributes
| | | |__ConfiguratioNumber
| | |__NumberOfInterfaces
| |__ "*" indicates the active configuration (others are " ")
|__Config info tag
USB devices may have multiple configurations, each of which act rather differently. For example, a bus-powered configuration might be much less capable than one that is self-powered. Only one device configuration can be active at a time; most devices have only one configuration.
Each configuration consists of one or more interfaces. Each interface serves a distinct “function”, which is typically bound to a different USB device driver. One common example is a USB speaker with an audio interface for playback, and a HID interface for use with software volume control.
Interface descriptor info (can be multiple per Config)¶
I:* If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
| | | | | | | | |__Driver name
| | | | | | | | or "(none)"
| | | | | | | |__InterfaceProtocol
| | | | | | |__InterfaceSubClass
| | | | | |__InterfaceClass
| | | | |__NumberOfEndpoints
| | | |__AlternateSettingNumber
| | |__InterfaceNumber
| |__ "*" indicates the active altsetting (others are " ")
|__Interface info tag
A given interface may have one or more “alternate” settings. For example, default settings may not use more than a small amount of periodic bandwidth. To use significant fractions of bus bandwidth, drivers must select a non-default altsetting.
Only one setting for an interface may be active at a time, and only one driver may bind to an interface at a time. Most devices have only one alternate setting per interface.
Endpoint descriptor info (can be multiple per Interface)¶
E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddss
| | | | |__Interval (max) between transfers
| | | |__EndpointMaxPacketSize
| | |__Attributes(EndpointType)
| |__EndpointAddress(I=In,O=Out)
|__Endpoint info tag
The interval is nonzero for all periodic (interrupt or isochronous) endpoints. For high speed endpoints the transfer interval may be measured in microseconds rather than milliseconds.
For high speed periodic endpoints, the EndpointMaxPacketSize
reflects
the per-microframe data transfer size. For “high bandwidth”
endpoints, that can reflect two or three packets (for up to
3KBytes every 125 usec) per endpoint.
With the Linux-USB stack, periodic bandwidth reservations use the transfer intervals and sizes provided by URBs, which can be less than those found in endpoint descriptor.
Usage examples¶
If a user or script is interested only in Topology info, for
example, use something like grep ^T: /sys/kernel/debug/usb/devices
for only the Topology lines. A command like
grep -i ^[tdp]: /sys/kernel/debug/usb/devices
can be used to list
only the lines that begin with the characters in square brackets,
where the valid characters are TDPCIE. With a slightly more able
script, it can display any selected lines (for example, only T, D,
and P lines) and change their output format. (The procusb
Perl script is the beginning of this idea. It will list only
selected lines [selected from TBDPSCIE] or “All” lines from
/sys/kernel/debug/usb/devices
.)
The Topology lines can be used to generate a graphic/pictorial of the USB devices on a system’s root hub. (See more below on how to do this.)
The Interface lines can be used to determine what driver is being used for each device, and which altsetting it activated.
The Configuration lines could be used to list maximum power
(in milliamps) that a system’s USB devices are using.
For example, grep ^C: /sys/kernel/debug/usb/devices
.
Here’s an example, from a system which has a UHCI root hub, an external hub connected to the root hub, and a mouse and a serial converter connected to the external hub.
T: Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#= 1 Spd=12 MxCh= 2
B: Alloc= 28/900 us ( 3%), #Int= 2, #Iso= 0
D: Ver= 1.00 Cls=09(hub ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=0000 ProdID=0000 Rev= 0.00
S: Product=USB UHCI Root Hub
S: SerialNumber=dce0
C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr= 0mA
I: If#= 0 Alt= 0 #EPs= 1 Cls=09(hub ) Sub=00 Prot=00 Driver=hub
E: Ad=81(I) Atr=03(Int.) MxPS= 8 Ivl=255ms
T: Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#= 2 Spd=12 MxCh= 4
D: Ver= 1.00 Cls=09(hub ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=0451 ProdID=1446 Rev= 1.00
C:* #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=100mA
I: If#= 0 Alt= 0 #EPs= 1 Cls=09(hub ) Sub=00 Prot=00 Driver=hub
E: Ad=81(I) Atr=03(Int.) MxPS= 1 Ivl=255ms
T: Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#= 3 Spd=1.5 MxCh= 0
D: Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=04b4 ProdID=0001 Rev= 0.00
C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
I: If#= 0 Alt= 0 #EPs= 1 Cls=03(HID ) Sub=01 Prot=02 Driver=mouse
E: Ad=81(I) Atr=03(Int.) MxPS= 3 Ivl= 10ms
T: Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#= 4 Spd=12 MxCh= 0
D: Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=0565 ProdID=0001 Rev= 1.08
S: Manufacturer=Peracom Networks, Inc.
S: Product=Peracom USB to Serial Converter
C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=100mA
I: If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
E: Ad=81(I) Atr=02(Bulk) MxPS= 64 Ivl= 16ms
E: Ad=01(O) Atr=02(Bulk) MxPS= 16 Ivl= 16ms
E: Ad=82(I) Atr=03(Int.) MxPS= 8 Ivl= 8ms
Selecting only the T:
and I:
lines from this (for example, by using
procusb ti
), we have
T: Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#= 1 Spd=12 MxCh= 2
T: Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#= 2 Spd=12 MxCh= 4
I: If#= 0 Alt= 0 #EPs= 1 Cls=09(hub ) Sub=00 Prot=00 Driver=hub
T: Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#= 3 Spd=1.5 MxCh= 0
I: If#= 0 Alt= 0 #EPs= 1 Cls=03(HID ) Sub=01 Prot=02 Driver=mouse
T: Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#= 4 Spd=12 MxCh= 0
I: If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
Physically this looks like (or could be converted to):
+------------------+
| PC/root_hub (12)| Dev# = 1
+------------------+ (nn) is Mbps.
Level 0 | CN.0 | CN.1 | [CN = connector/port #]
+------------------+
/
/
+-----------------------+
Level 1 | Dev#2: 4-port hub (12)|
+-----------------------+
|CN.0 |CN.1 |CN.2 |CN.3 |
+-----------------------+
\ \____________________
\_____ \
\ \
+--------------------+ +--------------------+
Level 2 | Dev# 3: mouse (1.5)| | Dev# 4: serial (12)|
+--------------------+ +--------------------+
Or, in a more tree-like structure (ports [Connectors] without connections could be omitted):
PC: Dev# 1, root hub, 2 ports, 12 Mbps
|_ CN.0: Dev# 2, hub, 4 ports, 12 Mbps
|_ CN.0: Dev #3, mouse, 1.5 Mbps
|_ CN.1:
|_ CN.2: Dev #4, serial, 12 Mbps
|_ CN.3:
|_ CN.1: