USB
Single-page view · as markdown
Linux USB API
Peios Kernel / Hardware and drivers / Driver development / USB
- The Linux-USB Host Side API
- USB Gadget API for Linux
- USB Anchors
- USB bulk streams
- USB core callbacks
- USB DMA
- USB Request Block (URB)
- Power Management for USB
- USB hotplugging
- USB device persistence during system suspend
- USB Error codes
- Writing USB Device Drivers
- Synopsys DesignWare Core SuperSpeed USB 3.0 Controller
- writing_musb_glue_layer
- USB Type-C connector class
- API for USB Type-C Alternate Mode drivers
- USB3 debug port
USB Request Block (URB)
Peios Kernel / Hardware and drivers / Driver development / USB
Revised: 2000-Dec-05
Again: 2002-Jul-06
Again: 2005-Sep-19
Again: 2017-Mar-29
Basic concept or 'What is an URB?' #
The basic idea of the new driver is message passing, the message itself is called USB Request Block, or URB for short.
-
An URB consists of all relevant information to execute any USB transaction and deliver the data and status back.
-
Execution of an URB is inherently an asynchronous operation, i.e. the
usb_submit_urb()call returns immediately after it has successfully queued the requested action. -
Transfers for one URB can be canceled with
usb_unlink_urb()at any time. -
Each URB has a completion handler, which is called after the action has been successfully completed or canceled. The URB also contains a context-pointer for passing information to the completion handler.
-
Each endpoint for a device logically supports a queue of requests. You can fill that queue, so that the USB hardware can still transfer data to an endpoint while your driver handles completion of another. This maximizes use of USB bandwidth, and supports seamless streaming of data to (or from) devices when using periodic transfer modes.
The URB structure #
Some of the fields in struct urb are:
struct urb
{
// (IN) device and pipe specify the endpoint queue
struct usb_device *dev; // pointer to associated USB device
unsigned int pipe; // endpoint information
unsigned int transfer_flags; // URB_ISO_ASAP, URB_SHORT_NOT_OK, etc.
// (IN) all urbs need completion routines
void *context; // context for completion routine
usb_complete_t complete; // pointer to completion routine
// (OUT) status after each completion
int status; // returned status
// (IN) buffer used for data transfers
void *transfer_buffer; // associated data buffer
u32 transfer_buffer_length; // data buffer length
int number_of_packets; // size of iso_frame_desc
// (OUT) sometimes only part of CTRL/BULK/INTR transfer_buffer is used
u32 actual_length; // actual data buffer length
// (IN) setup stage for CTRL (pass a struct usb_ctrlrequest)
unsigned char *setup_packet; // setup packet (control only)
// Only for PERIODIC transfers (ISO, INTERRUPT)
// (IN/OUT) start_frame is set unless URB_ISO_ASAP isn't set
int start_frame; // start frame
int interval; // polling interval
// ISO only: packets are only "best effort"; each can have errors
int error_count; // number of errors
struct usb_iso_packet_descriptor iso_frame_desc[0];
};
Your driver must create the "pipe" value using values from the appropriate endpoint descriptor in an interface that it's claimed.
How to get an URB? #
URBs are allocated by calling usb_alloc_urb():
struct urb *usb_alloc_urb(int isoframes, int mem_flags)
Return value is a pointer to the allocated URB, 0 if allocation failed. The parameter isoframes specifies the number of isochronous transfer frames you want to schedule. For CTRL/BULK/INT, use 0. The mem_flags parameter holds standard memory allocation flags, letting you control (among other things) whether the underlying code may block or not.
To free an URB, use usb_free_urb():
void usb_free_urb(struct urb *urb)
You may free an urb that you've submitted, but which hasn't yet been returned to you in a completion callback. It will automatically be deallocated when it is no longer in use.
What has to be filled in? #
Depending on the type of transaction, there are some inline functions defined in linux/usb.h to simplify the initialization, such as usb_fill_control_urb(), usb_fill_bulk_urb() and usb_fill_int_urb(). In general, they need the usb device pointer, the pipe (usual format from usb.h), the transfer buffer, the desired transfer length, the completion handler, and its context. Take a look at the some existing drivers to see how they're used.
Flags:
-
For ISO there are two startup behaviors: Specified start_frame or ASAP.
-
For ASAP set
URB_ISO_ASAPin transfer_flags.
If short packets should NOT be tolerated, set URB_SHORT_NOT_OK in transfer_flags.
How to submit an URB? #
Just call usb_submit_urb():
int usb_submit_urb(struct urb *urb, int mem_flags)
The mem_flags parameter, such as GFP_ATOMIC, controls memory allocation, such as whether the lower levels may block when memory is tight.
It immediately returns, either with status 0 (request queued) or some error code, usually caused by the following:
-
Out of memory (
-ENOMEM) -
Unplugged device (
-ENODEV) -
Stalled endpoint (
-EPIPE) -
Too many queued ISO transfers (
-EAGAIN) -
Too many requested ISO frames (
-EFBIG) -
Invalid INT interval (
-EINVAL) -
More than one packet for INT (
-EINVAL)
After submission, urb->status is -EINPROGRESS; however, you should never look at that value except in your completion callback.
For isochronous endpoints, your completion handlers should (re)submit URBs to the same endpoint with the URB_ISO_ASAP flag, using multi-buffering, to get seamless ISO streaming.
How to cancel an already running URB? #
There are two ways to cancel an URB you've submitted but which hasn't been returned to your driver yet. For an asynchronous cancel, call usb_unlink_urb():
int usb_unlink_urb(struct urb *urb)
It removes the urb from the internal list and frees all allocated HW descriptors. The status is changed to reflect unlinking. Note that the URB will not normally have finished when usb_unlink_urb() returns; you must still wait for the completion handler to be called.
To cancel an URB synchronously, call usb_kill_urb():
void usb_kill_urb(struct urb *urb)
It does everything usb_unlink_urb() does, and in addition it waits until after the URB has been returned and the completion handler has finished. It also marks the URB as temporarily unusable, so that if the completion handler or anyone else tries to resubmit it they will get a -EPERM error. Thus you can be sure that when usb_kill_urb() returns, the URB is totally idle.
There is a lifetime issue to consider. An URB may complete at any time, and the completion handler may free the URB. If this happens while usb_unlink_urb() or usb_kill_urb() is running, it will cause a memory-access violation. The driver is responsible for avoiding this, which often means some sort of lock will be needed to prevent the URB from being deallocated while it is still in use.
On the other hand, since usb_unlink_urb may end up calling the completion handler, the handler must not take any lock that is held when usb_unlink_urb is invoked. The general solution to this problem is to increment the URB's reference count while holding the lock, then drop the lock and call usb_unlink_urb or usb_kill_urb, and then decrement the URB's reference count. You increment the reference count by calling :c:func`usb_get_urb`:
struct urb *usb_get_urb(struct urb *urb)
(ignore the return value; it is the same as the argument) and decrement the reference count by calling usb_free_urb(). Of course, none of this is necessary if there's no danger of the URB being freed by the completion handler.
What about the completion handler? #
The handler is of the following type:
typedef void (*usb_complete_t)(struct urb *)
I.e., it gets the URB that caused the completion call. In the completion handler, you should have a look at urb->status to detect any USB errors. Since the context parameter is included in the URB, you can pass information to the completion handler.
Note that even when an error (or unlink) is reported, data may have been transferred. That's because USB transfers are packetized; it might take sixteen packets to transfer your 1KByte buffer, and ten of them might have transferred successfully before the completion was called.
In the current kernel, completion handlers run with local interrupts disabled, but in the future this will be changed, so don't assume that local IRQs are always disabled inside completion handlers.
How to do isochronous (ISO) transfers? #
Besides the fields present on a bulk transfer, for ISO, you also have to set urb->interval to say how often to make transfers; it's often one per frame (which is once every microframe for highspeed devices). The actual interval used will be a power of two that's no bigger than what you specify. You can use the usb_fill_int_urb() macro to fill most ISO transfer fields.
For ISO transfers you also have to fill a usb_iso_packet_descriptor structure, allocated at the end of the URB by usb_alloc_urb(), for each packet you want to schedule.
The usb_submit_urb() call modifies urb->interval to the implemented interval value that is less than or equal to the requested interval value. If URB_ISO_ASAP scheduling is used, urb->start_frame is also updated.
For each entry you have to specify the data offset for this frame (base is transfer_buffer), and the length you want to write/expect to read. After completion, actual_length contains the actual transferred length and status contains the resulting status for the ISO transfer for this frame. It is allowed to specify a varying length from frame to frame (e.g. for audio synchronisation/adaptive transfer rates). You can also use the length 0 to omit one or more frames (striping).
For scheduling you can choose your own start frame or URB_ISO_ASAP. As explained earlier, if you always keep at least one URB queued and your completion keeps (re)submitting a later URB, you'll get smooth ISO streaming (if usb bandwidth utilization allows).
If you specify your own start frame, make sure it's several frames in advance of the current frame. You might want this model if you're synchronizing ISO data with some other event stream.
How to start interrupt (INT) transfers? #
Interrupt transfers, like isochronous transfers, are periodic, and happen in intervals that are powers of two (1, 2, 4 etc) units. Units are frames for full and low speed devices, and microframes for high speed ones. You can use the usb_fill_int_urb() macro to fill INT transfer fields.
The usb_submit_urb() call modifies urb->interval to the implemented interval value that is less than or equal to the requested interval value.
In Linux 2.6, unlike earlier versions, interrupt URBs are not automagically restarted when they complete. They end when the completion handler is called, just like other URBs. If you want an interrupt URB to be restarted, your completion handler must resubmit it. s
USB Anchors
Peios Kernel / Hardware and drivers / Driver development / USB
What is anchor? #
A USB driver needs to support some callbacks requiring a driver to cease all IO to an interface. To do so, a driver has to keep track of the URBs it has submitted to know they've all completed or to call usb_kill_urb for them. The anchor is a data structure takes care of keeping track of URBs and provides methods to deal with multiple URBs.
Allocation and Initialisation #
There's no API to allocate an anchor. It is simply declared as struct usb_anchor. init_usb_anchor() must be called to initialise the data structure.
Deallocation #
Once it has no more URBs associated with it, the anchor can be freed with normal memory management operations.
Association and disassociation of URBs with anchors #
An association of URBs to an anchor is made by an explicit call to usb_anchor_urb(). The association is maintained until an URB is finished by (successful) completion. Thus disassociation is automatic. A function is provided to forcibly finish (kill) all URBs associated with an anchor. Furthermore, disassociation can be made with usb_unanchor_urb()
Operations on multitudes of URBs #
usb_kill_anchored_urbs() #
This function kills all URBs associated with an anchor. The URBs are called in the reverse temporal order they were submitted. This way no data can be reordered.
usb_scuttle_anchored_urbs() #
All URBs of an anchor are unanchored en masse.
usb_wait_anchor_empty_timeout() #
This function waits for all URBs associated with an anchor to finish or a timeout, whichever comes first. Its return value will tell you whether the timeout was reached.
usb_anchor_empty() #
Returns true if no URBs are associated with an anchor. Locking is the caller's responsibility.
usb_get_from_anchor() #
Returns the oldest anchored URB of an anchor. The URB is unanchored and returned with a reference. As you may mix URBs to several destinations in one anchor you have no guarantee the chronologically first submitted URB is returned.
USB bulk streams
Peios Kernel / Hardware and drivers / Driver development / USB
Background #
Bulk endpoint streams were added in the USB 3.0 specification. Streams allow a device driver to overload a bulk endpoint so that multiple transfers can be queued at once.
Streams are defined in sections 4.4.6.4 and 8.12.1.4 of the Universal Serial Bus 3.0 specification at https://www.usb.org/developers/docs/ The USB Attached SCSI Protocol, which uses streams to queue multiple SCSI commands, can be found on the T10 website (https://t10.org/).
Device-side implications #
Once a buffer has been queued to a stream ring, the device is notified (through an out-of-band mechanism on another endpoint) that data is ready for that stream ID. The device then tells the host which "stream" it wants to start. The host can also initiate a transfer on a stream without the device asking, but the device can refuse that transfer. Devices can switch between streams at any time.
Driver implications #
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);
Device drivers will call this API to request that the host controller driver allocate memory so the driver can use up to num_streams stream IDs. They must pass an array of usb_host_endpoints that need to be setup with similar stream IDs. This is to ensure that a UASP driver will be able to use the same stream ID for the bulk IN and OUT endpoints used in a Bi-directional command sequence.
The return value is an error condition (if one of the endpoints doesn't support streams, or the xHCI driver ran out of memory), or the number of streams the host controller allocated for this endpoint. The xHCI host controller hardware declares how many stream IDs it can support, and each bulk endpoint on a SuperSpeed device will say how many stream IDs it can handle. Therefore, drivers should be able to deal with being allocated less stream IDs than they requested.
Do NOT call this function if you have URBs enqueued for any of the endpoints passed in as arguments. Do not call this function to request less than two streams.
Drivers will only be allowed to call this API once for the same endpoint without calling usb_free_streams(). This is a simplification for the xHCI host controller driver, and may change in the future.
Picking new Stream IDs to use #
Stream ID 0 is reserved, and should not be used to communicate with devices. If usb_alloc_streams() returns with a value of N, you may use streams 1 though N. To queue an URB for a specific stream, set the urb->stream_id value. If the endpoint does not support streams, an error will be returned.
Note that new API to choose the next stream ID will have to be added if the xHCI driver supports secondary stream IDs.
Clean up #
If a driver wishes to stop using streams to communicate with the device, it should call:
void usb_free_streams(struct usb_interface *interface,
struct usb_host_endpoint **eps, unsigned int num_eps,
gfp_t mem_flags);
All stream IDs will be deallocated when the driver releases the interface, to ensure that drivers that don't support streams will be able to use the endpoint.
USB core callbacks
Peios Kernel / Hardware and drivers / Driver development / USB
What callbacks will usbcore do? #
Usbcore will call into a driver through callbacks defined in the driver structure and through the completion handler of URBs a driver submits. Only the former are in the scope of this document. These two kinds of callbacks are completely independent of each other. Information on the completion callback can be found in USB Request Block (URB).
The callbacks defined in the driver structure are:
- Hotplugging callbacks:
@probe:
Called to see if the driver is willing to manage a particular interface on a device.
@disconnect:
Called when the interface is no longer accessible, usually because its device has been (or is being) disconnected or the driver module is being unloaded.
- Odd backdoor through usbfs:
@ioctl:
Used for drivers that want to talk to userspace through the "usbfs" filesystem. This lets devices provide ways to expose information to user space regardless of where they do (or don't) show up otherwise in the filesystem.
- Power management (PM) callbacks:
@suspend:
Called when the device is going to be suspended.
@resume:
Called when the device is being resumed.
@reset_resume:
Called when the suspended device has been reset instead of being resumed.
- Device level operations:
@pre_reset:
Called when the device is about to be reset.
@post_reset:
Called after the device has been reset
The ioctl interface (2) should be used only if you have a very good reason. Sysfs is preferred these days. The PM callbacks are covered separately in Power Management for USB.
Calling conventions #
All callbacks are mutually exclusive. There's no need for locking against other USB callbacks. All callbacks are called from a task context. You may sleep. However, it is important that all sleeps have a small fixed upper limit in time. In particular you must not call out to user space and await results.
Hotplugging callbacks #
These callbacks are intended to associate and disassociate a driver with an interface. A driver's bond to an interface is exclusive.
The probe() callback #
int (*probe) (struct usb_interface *intf,
const struct usb_device_id *id);
Accept or decline an interface. If you accept the device return 0, otherwise -ENODEV or -ENXIO. Other error codes should be used only if a genuine error occurred during initialisation which prevented a driver from accepting a device that would else have been accepted. You are strongly encouraged to use usbcore's facility, usb_set_intfdata(), to associate a data structure with an interface, so that you know which internal state and identity you associate with a particular interface. The device will not be suspended and you may do IO to the interface you are called for and endpoint 0 of the device. Device initialisation that doesn't take too long is a good idea here.
The disconnect() callback #
void (*disconnect) (struct usb_interface *intf);
This callback is a signal to break any connection with an interface. You are not allowed any IO to a device after returning from this callback. You also may not do any other operation that may interfere with another driver bound to the interface, eg. a power management operation. Outstanding operations on the device must be completed or aborted before this callback may return.
If you are called due to a physical disconnection, all your URBs will be killed by usbcore. Note that in this case disconnect will be called some time after the physical disconnection. Thus your driver must be prepared to deal with failing IO even prior to the callback.
Device level callbacks #
pre_reset #
int (*pre_reset)(struct usb_interface *intf);
A driver or user space is triggering a reset on the device which contains the interface passed as an argument. Cease IO, wait for all outstanding URBs to complete, and save any device state you need to restore. No more URBs may be submitted until the post_reset method is called.
If you need to allocate memory here, use GFP_NOIO or GFP_ATOMIC, if you are in atomic context.
post_reset #
int (*post_reset)(struct usb_interface *intf);
The reset has completed. Restore any saved device state and begin using the device again.
If you need to allocate memory here, use GFP_NOIO or GFP_ATOMIC, if you are in atomic context.
Call sequences #
No callbacks other than probe will be invoked for an interface that isn't bound to your driver.
Probe will never be called for an interface bound to a driver. Hence following a successful probe, disconnect will be called before there is another probe for the same interface.
Once your driver is bound to an interface, disconnect can be called at any time except in between pre_reset and post_reset. pre_reset is always followed by post_reset, even if the reset failed or the device has been unplugged.
suspend is always followed by one of: resume, reset_resume, or disconnect.
USB DMA
Peios Kernel / Hardware and drivers / Driver development / USB
In Linux 2.5 kernels (and later), USB device drivers have additional control over how DMA may be used to perform I/O operations. The APIs are detailed in the kernel usb programming guide (kerneldoc, from the source code).
API overview #
The big picture is that USB drivers can continue to ignore most DMA issues, though they still must provide DMA-ready buffers (see Documentation/core-api/dma-api-howto.rst). That's how they've worked through the 2.4 (and earlier) kernels, or they can now be DMA-aware.
DMA-aware usb drivers:
-
New calls enable DMA-aware drivers, letting them allocate dma buffers and manage dma mappings for existing dma-ready buffers (see below).
-
URBs have an additional "transfer_dma" field, as well as a transfer_flags bit saying if it's valid. (Control requests also have "setup_dma", but drivers must not use it.)
-
"usbcore" will map this DMA address, if a DMA-aware driver didn't do it first and set
URB_NO_TRANSFER_DMA_MAP. HCDs don't manage dma mappings for URBs. -
There's a new "generic DMA API", parts of which are usable by USB device drivers. Never use dma_set_mask() on any USB interface or device; that would potentially break all devices sharing that bus.
Eliminating copies #
It's good to avoid making CPUs copy data needlessly. The costs can add up, and effects like cache-trashing can impose subtle penalties.
-
If you're doing lots of small data transfers from the same buffer all the time, that can really burn up resources on systems which use an IOMMU to manage the DMA mappings. It can cost MUCH more to set up and tear down the IOMMU mappings with each request than perform the I/O!
For those specific cases, USB has primitives to allocate less expensive memory. They work like kmalloc and kfree versions that give you the right kind of addresses to store in urb->transfer_buffer and urb->transfer_dma. You'd also set
URB_NO_TRANSFER_DMA_MAPin urb->transfer_flags:void *usb_alloc_coherent (struct usb_device *dev, size_t size, int mem_flags, dma_addr_t *dma); void usb_free_coherent (struct usb_device *dev, size_t size, void *addr, dma_addr_t dma);Most drivers should NOT be using these primitives; they don't need to use this type of memory ("dma-coherent"), and memory returned from
kmalloc()will work just fine.The memory buffer returned is "dma-coherent"; sometimes you might need to force a consistent memory access ordering by using memory barriers. It's not using a streaming DMA mapping, so it's good for small transfers on systems where the I/O would otherwise thrash an IOMMU mapping. (See Documentation/core-api/dma-api-howto.rst for definitions of "coherent" and "streaming" DMA mappings.)
Asking for 1/Nth of a page (as well as asking for N pages) is reasonably space-efficient.
On most systems the memory returned will be uncached, because the semantics of dma-coherent memory require either bypassing CPU caches or using cache hardware with bus-snooping support. While x86 hardware has such bus-snooping, many other systems use software to flush cache lines to prevent DMA conflicts.
-
Devices on some EHCI controllers could handle DMA to/from high memory.
Unfortunately, the current Linux DMA infrastructure doesn't have a sane way to expose these capabilities ... and in any case, HIGHMEM is mostly a design wart specific to x86_32. So your best bet is to ensure you never pass a highmem buffer into a USB driver. That's easy; it's the default behavior. Just don't override it; e.g. with
NETIF_F_HIGHDMA.This may force your callers to do some bounce buffering, copying from high memory to "normal" DMA memory. If you can come up with a good way to fix this issue (for x86_32 machines with over 1 GByte of memory), feel free to submit patches.
Working with existing buffers #
Existing buffers aren't usable for DMA without first being mapped into the DMA address space of the device. However, most buffers passed to your driver can safely be used with such DMA mapping. (See the first section of Documentation/core-api/dma-api-howto.rst, titled "What memory is DMA-able?")
-
When you have the scatterlists which have been mapped for the USB controller, you could use the new
usb_sg_*()calls, which would turn scatterlist into URBs: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); void usb_sg_wait(struct usb_sg_request *io); void usb_sg_cancel(struct usb_sg_request *io);When the USB controller doesn't support DMA, the
usb_sg_init()would try to submit URBs in PIO way as long as the page in scatterlists is not in the Highmem, which could be very rare in modern architectures.
Synopsys DesignWare Core SuperSpeed USB 3.0 Controller
Peios Kernel / Hardware and drivers / Driver development / USB
Author: Felipe Balbi <felipe.balbi@linux.intel.com>
Date: April 2017
Introduction #
The Synopsys DesignWare Core SuperSpeed USB 3.0 Controller (hereinafter referred to as DWC3) is a USB SuperSpeed compliant controller which can be configured in one of 4 ways:
Peripheral-only configuration
Host-only configuration
Dual-Role configuration
Hub configuration
Linux currently supports several versions of this controller. In all likelihood, the version in your SoC is already supported. At the time of this writing, known tested versions range from 2.02a to 3.10a. As a rule of thumb, anything above 2.02a should work reliably well.
Currently, we have many known users for this driver. In alphabetical order:
Cavium
Intel Corporation
Qualcomm
Rockchip
ST
Samsung
Texas Instruments
Xilinx
Summary of Features #
For details about features supported by your version of DWC3, consult your IP team and/or Synopsys DesignWare Core SuperSpeed USB 3.0 Controller Databook. Following is a list of features supported by the driver at the time of this writing:
Up to 16 bidirectional endpoints (including the control pipe - ep0)
Flexible endpoint configuration
Simultaneous IN and OUT transfer support
Scatter-list support
Up to 256 TRBs 1 per endpoint
Support for all transfer types (Control, Bulk, Interrupt, and Isochronous)
SuperSpeed Bulk Streams
Link Power Management
Trace Events for debugging
DebugFS 3 interface
These features have all been exercised with many of the in-tree gadget drivers. We have verified both ConfigFS 4 and legacy gadget drivers.
Driver Design #
The DWC3 driver sits on the drivers/usb/dwc3/ directory. All files related to this driver are in this one directory. This makes it easy for new-comers to read the code and understand how it behaves.
Because of DWC3's configuration flexibility, the driver is a little complex in some places but it should be rather straightforward to understand.
The biggest part of the driver refers to the Gadget API.
Known Limitations #
Like any other HW, DWC3 has its own set of limitations. To avoid constant questions about such problems, we decided to document them here and have a single location to where we could point users.
OUT Transfer Size Requirements #
According to Synopsys Databook, all OUT transfer TRBs 1 must have their size field set to a value which is integer divisible by the endpoint's wMaxPacketSize. This means that e.g. in order to receive a Mass Storage CBW 5, req->length must either be set to a value that's divisible by wMaxPacketSize (1024 on SuperSpeed, 512 on HighSpeed, etc), or DWC3 driver must add a Chained TRB pointing to a throw-away buffer for the remaining length. Without this, OUT transfers will NOT start.
Note that as of this writing, this won't be a problem because DWC3 is fully capable of appending a chained TRB for the remaining length and completely hide this detail from the gadget driver. It's still worth mentioning because this seems to be the largest source of queries about DWC3 and non-working transfers.
TRB Ring Size Limitation #
We, currently, have a hard limit of 256 TRBs 1 per endpoint, with the last TRB being a Link TRB 2 pointing back to the first. This limit is arbitrary but it has the benefit of adding up to exactly 4096 bytes, or 1 Page.
DWC3 driver will try its best to cope with more than 255 requests and, for the most part, it should work normally. However this is not something that has been exercised very frequently. If you experience any problems, see section Reporting Bugs below.
Reporting Bugs #
Whenever you encounter a problem with DWC3, first and foremost you should make sure that:
You're running latest tag from Linus' tree
You can reproduce the error without any out-of-tree changes to DWC3
You have checked that it's not a fault on the host machine
After all these are verified, then here's how to capture enough information so we can be of any help to you.
Required Information #
DWC3 relies exclusively on Trace Events for debugging. Everything is exposed there, with some extra bits being exposed to DebugFS 3.
In order to capture DWC3's Trace Events you should run the following commands before plugging the USB cable to a host machine:
# mkdir -p /d
# mkdir -p /t
# mount -t debugfs none /d
# mount -t tracefs none /t
# echo 81920 > /t/buffer_size_kb
# echo 1 > /t/events/dwc3/enable
After this is done, you can connect your USB cable and reproduce the problem. As soon as the fault is reproduced, make a copy of files trace and regdump, like so:
# cp /t/trace /root/trace.txt
# cat /d/*dwc3*/regdump > /root/regdump.txt
Make sure to compress trace.txt and regdump.txt in a tarball and email it to me with linux-usb in Cc. If you want to be extra sure that I'll help you, write your subject line in the following format:
[BUG REPORT] usb: dwc3: Bug while doing XYZ
On the email body, make sure to detail what you doing, which gadget driver you were using, how to reproduce the problem, what SoC you're using, which OS (and its version) was running on the Host machine.
With all this information, we should be able to understand what's going on and be helpful to you.
Debugging #
First and foremost a disclaimer:
DISCLAIMER: The information available on DebugFS and/or TraceFS can
change at any time at any Major Linux Kernel Release. If writing
scripts, do **NOT** assume information to be available in the
current format.
With that out of the way, let's carry on.
If you're willing to debug your own problem, you deserve a round of applause :-)
Anyway, there isn't much to say here other than Trace Events will be really helpful in figuring out issues with DWC3. Also, access to Synopsys Databook will be really valuable in this case.
A USB Sniffer can be helpful at times but it's not entirely required, there's a lot that can be understood without looking at the wire.
Feel free to email me and Cc linux-usb if you need any help.
DebugFS #
DebugFS is very good for gathering snapshots of what's going on with DWC3 and/or any endpoint.
On DWC3's DebugFS directory, you will find the following files and directories:
ep[0..15]{in,out}/ link_state regdump testmode
link_state #
When read, link_state will print out one of U0, U1, U2, U3, SS.Disabled, RX.Detect, SS.Inactive, Polling, Recovery, Hot Reset, Compliance, Loopback, Reset, Resume or UNKNOWN link state.
This file can also be written to in order to force link to one of the states above.
regdump #
File name is self-explanatory. When read, regdump will print out a register dump of DWC3. Note that this file can be grepped to find the information you want.
testmode #
When read, testmode will print out a name of one of the specified USB 2.0 Testmodes (test_j, test_k, test_se0_nak, test_packet, test_force_enable) or the string no test in case no tests are currently being executed.
In order to start any of these test modes, the same strings can be written to the file and DWC3 will enter the requested test mode.
ep[0..15]{in,out} #
For each endpoint we expose one directory following the naming convention ep$num$dir (ep0in, ep0out, ep1in, ...). Inside each of these directories you will find the following files:
descriptor_fetch_queue event_queue rx_fifo_queue rx_info_queue rx_request_queue transfer_type trb_ring tx_fifo_queue tx_request_queue
With access to Synopsys Databook, you can decode the information on them.
transfer_type #
When read, transfer_type will print out one of control, bulk, interrupt or isochronous depending on what the endpoint descriptor says. If the endpoint hasn't been enabled yet, it will print --.
trb_ring #
When read, trb_ring will print out details about all TRBs on the ring. It will also tell you where our enqueue and dequeue pointers are located in the ring:
Trace Events #
DWC3 also provides several trace events which help us gathering information about the behavior of the driver during runtime.
In order to use these events, you must enable CONFIG_FTRACE in your kernel config.
For details about how enable DWC3 events, see section Reporting Bugs.
The following subsections will give details about each Event Class and each Event defined by DWC3.
MMIO #
It is sometimes useful to look at every MMIO access when looking for bugs. Because of that, DWC3 offers two Trace Events (one for dwc3_readl() and one for dwc3_writel()). TP_printk follows:
TP_printk("addr %p value %08x", __entry->base + __entry->offset,
__entry->value)
Interrupt Events #
Every IRQ event can be logged and decoded into a human readable string. Because every event will be different, we don't give an example other than the TP_printk format used:
TP_printk("event (%08x): %s", __entry->event,
dwc3_decode_event(__entry->event, __entry->ep0state))
Control Request #
Every USB Control Request can be logged to the trace buffer. The output format is:
TP_printk("%s", dwc3_decode_ctrl(__entry->bRequestType,
__entry->bRequest, __entry->wValue,
__entry->wIndex, __entry->wLength)
)
Note that Standard Control Requests will be decoded into human-readable strings with their respective arguments. Class and Vendor requests will be printed out a sequence of 8 bytes in hex format.
Lifetime of a struct usb_request #
The entire lifetime of a struct usb_request can be tracked on the trace buffer. We have one event for each of allocation, free, queueing, dequeueing, and giveback. Output format is:
TP_printk("%s: req %p length %u/%u %s%s%s ==> %d",
__get_str(name), __entry->req, __entry->actual, __entry->length,
__entry->zero ? "Z" : "z",
__entry->short_not_ok ? "S" : "s",
__entry->no_interrupt ? "i" : "I",
__entry->status
)
Generic Commands #
We can log and decode every Generic Command with its completion code. Format is:
TP_printk("cmd '%s' [%x] param %08x --> status: %s",
dwc3_gadget_generic_cmd_string(__entry->cmd),
__entry->cmd, __entry->param,
dwc3_gadget_generic_cmd_status_string(__entry->status)
)
Endpoint Commands #
Endpoints commands can also be logged together with completion code. Format is:
TP_printk("%s: cmd '%s' [%d] params %08x %08x %08x --> status: %s",
__get_str(name), dwc3_gadget_ep_cmd_string(__entry->cmd),
__entry->cmd, __entry->param0,
__entry->param1, __entry->param2,
dwc3_ep_cmd_status_string(__entry->cmd_status)
)
Lifetime of a TRB #
A TRB Lifetime is simple. We are either preparing a TRB or completing it. With these two events, we can see how a TRB changes over time. Format is:
TP_printk("%s: %d/%d trb %p buf %08x%08x size %s%d ctrl %08x (%c%c%c%c:%c%c:%s)",
__get_str(name), __entry->queued, __entry->allocated,
__entry->trb, __entry->bph, __entry->bpl,
({char *s;
int pcm = ((__entry->size >> 24) & 3) + 1;
switch (__entry->type) {
case USB_ENDPOINT_XFER_INT:
case USB_ENDPOINT_XFER_ISOC:
switch (pcm) {
case 1:
s = "1x ";
break;
case 2:
s = "2x ";
break;
case 3:
s = "3x ";
break;
}
default:
s = "";
} s; }),
DWC3_TRB_SIZE_LENGTH(__entry->size), __entry->ctrl,
__entry->ctrl & DWC3_TRB_CTRL_HWO ? 'H' : 'h',
__entry->ctrl & DWC3_TRB_CTRL_LST ? 'L' : 'l',
__entry->ctrl & DWC3_TRB_CTRL_CHN ? 'C' : 'c',
__entry->ctrl & DWC3_TRB_CTRL_CSP ? 'S' : 's',
__entry->ctrl & DWC3_TRB_CTRL_ISP_IMI ? 'S' : 's',
__entry->ctrl & DWC3_TRB_CTRL_IOC ? 'C' : 'c',
dwc3_trb_type_string(DWC3_TRBCTL_TYPE(__entry->ctrl))
)
Lifetime of an Endpoint #
And endpoint's lifetime is summarized with enable and disable operations, both of which can be traced. Format is:
TP_printk("%s: mps %d/%d streams %d burst %d ring %d/%d flags %c:%c%c%c%c%c:%c:%c",
__get_str(name), __entry->maxpacket,
__entry->maxpacket_limit, __entry->max_streams,
__entry->maxburst, __entry->trb_enqueue,
__entry->trb_dequeue,
__entry->flags & DWC3_EP_ENABLED ? 'E' : 'e',
__entry->flags & DWC3_EP_STALL ? 'S' : 's',
__entry->flags & DWC3_EP_WEDGE ? 'W' : 'w',
__entry->flags & DWC3_EP_TRANSFER_STARTED ? 'B' : 'b',
__entry->flags & DWC3_EP_PENDING_REQUEST ? 'P' : 'p',
__entry->flags & DWC3_EP_END_TRANSFER_PENDING ? 'E' : 'e',
__entry->direction ? '<' : '>'
)
Structures, Methods and Definitions #
struct dwc3_event_buffer #
Software event buffer representation
Definition
;
Members
buf: THE buffercache: The buffer cache used in the threaded interruptlength: size of this bufferlpos: event offsetcount: cache of last read event count registerflags: flags related to this event bufferdma: dma_addr_tdwc: pointer to DWC controller
struct dwc3_ep #
device side endpoint representation
Definition
;
Members
endpoint: usb endpointnostream_work: work for handling bulk NoStreamcancelled_list: list of cancelled requests for this endpointpending_list: list of pending requests for this endpointstarted_list: list of started requests on this endpointtrb_pool: array of transaction bufferstrb_pool_dma: dma address of trb_pooldwc: pointer to DWC controllersaved_state: ep state saved during hibernationflags: endpoint flags (wedged, stalled, ...)trb_enqueue: enqueue 'pointer' into TRB arraytrb_dequeue: dequeue 'pointer' into TRB arraynumber: endpoint number (1 - 15)type: set to bmAttributes & USB_ENDPOINT_XFERTYPE_MASKresource_index: Resource transfer indexframe_number: set to the frame number we want this transfer to start (ISOC)interval: the interval on which the ISOC transfer is startedname: a human readable name e.g. ep1out-bulkdirection: true for TX, false for RXstream_capable: true when streams are enabledcombo_num: the test combination BIT[15:14] of the frame number to test isochronous START TRANSFER command failure workaroundstart_cmd_status: the status of testing START TRANSFER command with combo_num = 'b00
struct dwc3_trb #
transfer request block (hw format)
Definition
;
Members
bpl: DW0-3bph: DW4-7size: DW8-Bctrl: DWC-F
struct dwc3_hwparams #
copy of HWPARAMS registers
Definition
;
Members
hwparams0: GHWPARAMS0hwparams1: GHWPARAMS1hwparams2: GHWPARAMS2hwparams3: GHWPARAMS3hwparams4: GHWPARAMS4hwparams5: GHWPARAMS5hwparams6: GHWPARAMS6hwparams7: GHWPARAMS7hwparams8: GHWPARAMS8hwparams9: GHWPARAMS9
struct dwc3_request #
representation of a transfer request
Definition
;
Members
request: struct usb_request to be transferredlist: a list_head used for request queueingdep: struct dwc3_ep owning this requeststart_sg: pointer to the sg which should be queued nextnum_pending_sgs: counter to pending sgsremaining: amount of data remainingstatus: internal dwc3 request status trackingepnum: endpoint number to which this request referstrb: pointer to struct dwc3_trbtrb_dma: DMA address of trbnum_trbs: number of TRBs used by this requestdirection: IN or OUT direction flagmapped: true when request has been dma-mapped
struct dwc3_glue_ops #
The ops indicate the notifications that need to be passed on to glue layer
Definition
;
Members
pre_set_role: Notify glue of role switch notificationspre_run_stop: Notify run stop enable/disable information to glue
struct dwc3 #
representation of our controller
Definition
;
Members
drd_work: workqueue used for role swappingep0_trb: trb which is used for the ctrl_reqbounce: address of bounce buffersetup_buf: used while precessing STD USB requestsep0_trb_addr: dma address of ep0_trbbounce_addr: dma address of bounceep0_usb_req: dummy req used while handling STD USB requestsep0_in_setup: one control transfer is completed and enter setup phaselock: for synchronizingmutex: for mode switchingdev: pointer to our struct devicesysdev: pointer to the DMA-capable devicexhci: pointer to our xHCI childxhci_resources: struct resources for our xhci childev_buf: struct dwc3_event_buffer pointereps: endpoint arraygadget: device side representation of the peripheral controllergadget_driver: pointer to the gadget driverglue_ops: Vendor callbacks for flattened device implementations.bus_clk: clock for accessing the registersref_clk: reference clocksusp_clk: clock used when the SS phy is in low power (S3) stateutmi_clk: clock used for USB2 PHY communicationpipe_clk: clock used for USB3 PHY communicationreset: reset controlusb2_phy: pointer to USB2 PHYusb3_phy: pointer to USB3 PHYusb2_generic_phy: pointer to array of USB2 PHYsusb3_generic_phy: pointer to array of USB3 PHYsnum_usb2_ports: number of USB2 portsnum_usb3_ports: number of USB3 portsphys_ready: flag to indicate that PHYs are readyulpi: pointer to ulpi interfaceulpi_ready: flag to indicate that ULPI is initializedregs: base address for our registersregs_size: address space sizedr_mode: requested mode of operationcurrent_dr_role: current role of operation when in dual-role modedesired_dr_role: desired role of operation when in dual-role modeedev: extcon handleedev_nb: extcon notifierhsphy_mode: UTMI phy mode, one of following:- USBPHY_INTERFACE_MODE_UTMI
- USBPHY_INTERFACE_MODE_UTMIW
role_sw: usb_role_switch handlerole_switch_default_mode: default operation mode of controller while usb role is USB_ROLE_NONE.usb_psy: pointer to power supply interface.vbus_draw_work: Work to set the vbus drawing limitcurrent_limit: How much current to draw from vbus, in milliAmperes.fladj: frame length adjustmentref_clk_per: reference clock period configurationirq_gadget: peripheral controller's IRQ numberotg_irq: IRQ number for OTG IRQscurrent_otg_role: current role of operation while using the OTG blockdesired_otg_role: desired role of operation while using the OTG blockotg_restart_host: flag that OTG controller needs to restart hostu1u2: only used on revisions <1.83a for workaroundmaximum_speed: maximum speed requested (mainly for testing purposes)gadget_max_speed: maximum gadget speed requestedmax_ssp_rate: SuperSpeed Plus maximum signaling rate and lane countgadget_ssp_rate: Gadget driver's maximum supported SuperSpeed Plus signaling rate and lane count.ip: controller's IDrevision: controller's version of an IPversion_type: VERSIONTYPE register contents, a sub release of a revisionep0_next_event: hold the next expected eventep0state: state of endpoint zerolink_state: link stateu2sel: parameter from Set SEL request.u2pel: parameter from Set SEL request.u1sel: parameter from Set SEL request.u1pel: parameter from Set SEL request.speed: device speed (super, high, full, low)num_eps: number of endpointshwparams: copy of hwparams registersregset: debugfs pointer to regdump filedbg_lsp_select: current debug lsp mux register selectiontest_mode: true when we're entering a USB test modetest_mode_nr: test feature selectorlpm_nyet_threshold: LPM NYET response thresholdhird_threshold: HIRD thresholdrx_thr_num_pkt: USB receive packet countrx_max_burst: max USB receive burst sizetx_thr_num_pkt: USB transmit packet counttx_max_burst: max USB transmit burst sizerx_thr_num_pkt_prd: periodic ESS receive packet countrx_max_burst_prd: max periodic ESS receive burst sizetx_thr_num_pkt_prd: periodic ESS transmit packet counttx_max_burst_prd: max periodic ESS transmit burst sizetx_fifo_resize_max_num: max number of fifos allocated during txfifo resizeclear_stall_protocol: endpoint number that requires a delayed status phasenum_hc_interrupters: number of host controller interruptershsphy_interface: "utmi" or "ulpi"connected: true when we're connected to a host, false otherwisesoftconnect: true when gadget connect is called, false when disconnect runsdelayed_status: true when gadget driver asks for delayed statusep0_bounced: true when we used bounce bufferep0_expect_in: true when we expect a DATA IN transfersysdev_is_parent: true when dwc3 device has a parent driverhas_lpm_erratum: true when core was configured with LPM Erratum. Note that there's now way for software to detect this in runtime.is_utmi_l1_suspend: the core asserts output signal 0 - utmi_sleep_n 1 - utmi_l1_suspend_nis_fpga: true when we are using the FPGA boardpending_events: true when we have pending IRQs to be handleddo_fifo_resize: true when txfifo resizing is enabled for dwc3 endpointspullups_connected: true when Run/Stop bit is setsetup_packet_pending: true when there's a Setup Packet in FIFO. Workaroundthree_stage_setup: set if we perform a three phase setupdis_start_transfer_quirk: set if start_transfer failure SW workaround is not needed for DWC_usb31 version 1.70a-ea06 and belowusb3_lpm_capable: set if hadrware supports Link Power Managementusb2_lpm_disable: set to disable usb2 lpm for hostusb2_gadget_lpm_disable: set to disable usb2 lpm for gadgetdisable_scramble_quirk: set if we enable the disable scramble quirku2exit_lfps_quirk: set if we enable u2exit lfps quirku2ss_inp3_quirk: set if we enable P3 OK for U2/SS Inactive quirkreq_p1p2p3_quirk: set if we enable request p1p2p3 quirkdel_p1p2p3_quirk: set if we enable delay p1p2p3 quirkdel_phy_power_chg_quirk: set if we enable delay phy power change quirklfps_filter_quirk: set if we enable LFPS filter quirkrx_detect_poll_quirk: set if we enable rx_detect to polling lfps quirkdis_u3_susphy_quirk: set if we disable usb3 suspend phydis_u2_susphy_quirk: set if we disable usb2 suspend phydis_enblslpm_quirk: set if we clear enblslpm in GUSB2PHYCFG, disabling the suspend signal to the PHY.dis_u1_entry_quirk: set if link entering into U1 state needs to be disabled.dis_u2_entry_quirk: set if link entering into U2 state needs to be disabled.dis_rxdet_inp3_quirk: set if we disable Rx.Detect in P3dis_u2_freeclk_exists_quirk: set if we clear u2_freeclk_exists in GUSB2PHYCFG, specify that USB2 PHY doesn't provide a free-running PHY clock.dis_del_phy_power_chg_quirk: set if we disable delay phy power change quirk.dis_tx_ipgap_linecheck_quirk: set if we disable u2mac linestate check during HS transmit.resume_hs_terminations: Set if we enable quirk for fixing improper crc generation after resume from suspend.ulpi_ext_vbus_drv: Set to confiure the upli chip to drives CPEN pin VBUS with an external supply.parkmode_disable_ss_quirk: set if we need to disable all SuperSpeed instances in park mode.parkmode_disable_hs_quirk: set if we need to disable all HishSpeed instances in park mode.gfladj_refclk_lpm_sel: set if we need to enable SOF/ITP counter running based on ref_clktx_de_emphasis_quirk: set if we enable Tx de-emphasis quirktx_de_emphasis: Tx de-emphasis value 0 - -6dB de-emphasis 1 - -3.5dB de-emphasis 2 - No de-emphasis 3 - Reserveddis_metastability_quirk: set to disable metastability quirk.dis_split_quirk: set to disable split boundary.async_callbacks: if set, indicate that async callbacks will be used.sys_wakeup: set if the device may do system wakeup.wakeup_configured: set if the device is configured for remote wakeup.suspended: set to track suspend event due to U3/L2.susphy_state: state of DWC3_GUSB2PHYCFG_SUSPHY + DWC3_GUSB3PIPECTL_SUSPHY before PM suspend.imod_interval: set the interrupt moderation interval in 250ns increments or 0 to disable.max_cfg_eps: current max number of IN eps used across all USB configs.last_fifo_depth: last fifo depth used to determine next fifo ram start address.num_ep_resized: carries the current number endpoints which have had its tx fifo resized.debug_root: root debugfs directory for this device to put its files in.gsbuscfg0_reqinfo: store GSBUSCFG0.DATRDREQINFO, DESRDREQINFO, DATWRREQINFO, and DESWRREQINFO value passed from glue driver.wakeup_pending_funcs: Indicates whether any interface has requested for function wakeup in bitmap format where bit position represents interface_id.
struct dwc3_event_depevt #
Device Endpoint Events
Definition
;
Members
one_bit: indicates this is an endpoint event (not used)endpoint_number: number of the endpointendpoint_event: The event we have: 0x00 - Reserved 0x01 - XferComplete 0x02 - XferInProgress 0x03 - XferNotReady 0x04 - RxTxFifoEvt (IN->Underrun, OUT->Overrun) 0x05 - Reserved 0x06 - StreamEvt 0x07 - EPCmdCmpltreserved11_10: Reserved, don't use.status: Indicates the status of the event. Refer to databook for more information.parameters: Parameters of the current event. Refer to databook for more information.
struct dwc3_event_devt #
Device Events
Definition
;
Members
one_bit: indicates this is a non-endpoint event (not used)device_event: indicates it's a device event. Should read as 0x00type: indicates the type of device event. 0 - DisconnEvt 1 - USBRst 2 - ConnectDone 3 - ULStChng 4 - WkUpEvt 5 - Reserved 6 - Suspend (EOPF on revisions 2.10a and prior) 7 - SOF 8 - Reserved 9 - ErrticErr 10 - CmdCmplt 11 - EvntOverflow 12 - VndrDevTstRcvedreserved15_12: Reserved, not usedevent_info: Information about this eventreserved31_25: Reserved, not used
struct dwc3_event_gevt #
Other Core Events
Definition
;
Members
one_bit: indicates this is a non-endpoint event (not used)device_event: indicates it's (0x03) Carkit or (0x04) I2C event.phy_port_number: self-explanatoryreserved31_12: Reserved, not used.
union dwc3_event #
representation of Event Buffer contents
Definition
;
Members
raw: raw 32-bit eventtype: the type of the eventdepevt: Device Endpoint Eventdevt: Device Eventgevt: Global Event
struct dwc3_gadget_ep_cmd_params #
representation of endpoint command parameters
Definition
;
Members
param2: third parameterparam1: second parameterparam0: first parameter
dwc3_mdwidth() #
u32 get MDWIDTH value in bits
Parameters
struct dwc3 *dwc: pointer to our context structure
Description
Return MDWIDTH configuration value in bits.
next_request() #
struct dwc3_request * gets the next request on the given list
Parameters
struct list_head *list: the request list to operate on
Description
Caller should take care of locking. This function return NULL or the first
request available on list.
dwc3_gadget_move_started_request() #
void move req to the started_list
Parameters
struct dwc3_request *req: the request to be moved
Description
Caller should take care of locking. This function will move req from its current list to the endpoint's started_list.
dwc3_gadget_move_cancelled_request() #
void move req to the cancelled_list
Parameters
struct dwc3_request *req: the request to be movedunsigned int reason: cancelled reason for the dwc3 request
Description
Caller should take care of locking. This function will move req from its current list to the endpoint's cancelled_list.
dwc3_gadget_ep_get_transfer_index() #
void Gets transfer index from HW
Parameters
struct dwc3_ep *dep: dwc3 endpoint
Description
Caller should take care of locking. Returns the transfer resource index for a given endpoint.
dwc3_gadget_dctl_write_safe() #
void write to DCTL safe from link state change
Parameters
struct dwc3 *dwc: pointer to our context structureu32 value: value to write to DCTL
Description
Use this function when doing read-modify-write to DCTL. It will not send link state change request.
dwc3_gadget_set_test_mode() #
int enables usb2 test modes
Parameters
struct dwc3 *dwc: pointer to our context structureint mode: the mode to set (J, K SE0 NAK, Force Enable)
Description
Caller should take care of locking. This function will return 0 on success or -EINVAL if wrong Test Selector is passed.
dwc3_gadget_get_link_state() #
int gets current state of usb link
Parameters
struct dwc3 *dwc: pointer to our context structure
Description
Caller should take care of locking. This function will return the link state on success (>= 0) or -ETIMEDOUT.
dwc3_gadget_set_link_state() #
int sets usb link to a particular state
Parameters
struct dwc3 *dwc: pointer to our context structureenum dwc3_link_state state: the state to put link into
Description
Caller should take care of locking. This function will return 0 on success or -ETIMEDOUT.
dwc3_ep_inc_trb() #
void increment a trb index.
Parameters
u8 *index: Pointer to the TRB index to increment.
Description
The index should never point to the link TRB. After incrementing, if it is point to the link TRB, wrap around to the beginning. The link TRB is always at the last TRB entry.
dwc3_ep_inc_enq() #
void increment endpoint's enqueue pointer
Parameters
struct dwc3_ep *dep: The endpoint whose enqueue pointer we're incrementing
dwc3_ep_inc_deq() #
void increment endpoint's dequeue pointer
Parameters
struct dwc3_ep *dep: The endpoint whose enqueue pointer we're incrementing
dwc3_gadget_giveback() #
void call struct usb_request's ->complete callback
Parameters
struct dwc3_ep *dep: The endpoint to whom the request belongs tostruct dwc3_request *req: The request we're giving backint status: completion code for the request
Description
Must be called with controller's lock held and interrupts disabled. This
function will unmap req and call its ->complete() callback to notify upper
layers that it has completed.
dwc3_send_gadget_generic_command() #
int issue a generic command for the controller
Parameters
struct dwc3 *dwc: pointer to the controller contextunsigned int cmd: the command to be issuedu32 param: command parameter
Description
Caller should take care of locking. Issue cmd with a given param to dwc and wait for its completion.
dwc3_send_gadget_ep_cmd() #
int issue an endpoint command
Parameters
struct dwc3_ep *dep: the endpoint to which the command is going to be issuedunsigned int cmd: the command to be issuedstruct dwc3_gadget_ep_cmd_params *params: parameters to the command
Description
Caller should handle locking. This function will issue cmd with given params to dep and wait for its completion.
According to the programming guide, if the link state is in L1/L2/U3, then sending the Start Transfer command may not complete. The programming guide suggested to bring the link state back to ON/U0 by performing remote wakeup prior to sending the command. However, don't initiate remote wakeup when the user/function does not send wakeup request via wakeup ops. Send the command when it's allowed.
Notes
For L1 link state, issuing a command requires the clearing of GUSB2PHYCFG.SUSPENDUSB2, which turns on the signal required to complete the given command (usually within 50us). This should happen within the command timeout set by driver. No additional step is needed.
For L2 or U3 link state, the gadget is in USB suspend. Care should be taken when sending Start Transfer command to ensure that it's done after USB resume.
dwc3_gadget_start_config() #
int reset endpoint resources
Parameters
struct dwc3 *dwc: pointer to the DWC3 contextunsigned int resource_index: DEPSTARTCFG.XferRscIdx value (must be 0 or 2)
Description
Set resource_index=0 to reset all endpoints' resources allocation. Do this as part of the power-on/soft-reset initialization.
Set resource_index=2 to reset only non-control endpoints' resources. Do this on receiving the SET_CONFIGURATION request or hibernation resume.
dwc3_gadget_calc_tx_fifo_size() #
int calculates the txfifo size value
Parameters
struct dwc3 *dwc: pointer to the DWC3 contextint mult: multiplier to be used when calculating the fifo_size
Description
Calculates the size value based on the equation below:
DWC3 revision 280A and prior: fifo_size = mult * (max_packet / mdwidth) + 1;
DWC3 revision 290A and onwards: fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
The max packet size is set to 1024, as the txfifo requirements mainly apply to super speed USB use cases. However, it is safe to overestimate the fifo allocations for other scenarios, i.e. high speed USB.
dwc3_gadget_calc_ram_depth() #
int calculates the ram depth for txfifo
Parameters
struct dwc3 *dwc: pointer to the DWC3 context
dwc3_gadget_clear_tx_fifos() #
void Clears txfifo allocation
Parameters
struct dwc3 *dwc: pointer to the DWC3 context
Description
Iterates through all the endpoint registers and clears the previous txfifo allocations.
__dwc3_gadget_ep_enable() #
int initializes a hw endpoint
Parameters
struct dwc3_ep *dep: endpoint to be initializedunsigned int action: one of INIT, MODIFY or RESTORE
Description
Caller should take care of locking. Execute all necessary commands to initialize a HW endpoint so it can be used by a gadget driver.
__dwc3_gadget_ep_disable() #
int disables a hw endpoint
Parameters
struct dwc3_ep *dep: the endpoint to disable
Description
This function undoes what __dwc3_gadget_ep_enable did and also removes requests which are currently being processed by the hardware and those which are not yet scheduled.
Caller should take care of locking.
dwc3_ep_prev_trb() #
struct dwc3_trb * returns the previous TRB in the ring
Parameters
struct dwc3_ep *dep: The endpoint with the TRB ringu8 index: The index of the current TRB in the ring
Description
Returns the TRB prior to the one pointed to by the index. If the index is 0, we will wrap backwards, skip the link TRB, and return the one just before that.
dwc3_prepare_one_trb() #
void setup one TRB from one request
Parameters
struct dwc3_ep *dep: endpoint for which this request is preparedstruct dwc3_request *req: dwc3_request pointerunsigned int trb_length: buffer size of the TRBunsigned int chain: should this TRB be chained to the next?unsigned int node: only for isochronous endpoints. First TRB needs different type.bool use_bounce_buffer: set to use bounce bufferbool must_interrupt: set to interrupt on TRB completion
dwc3_prepare_last_sg() #
int prepare TRBs for the last SG entry
Parameters
struct dwc3_ep *dep: The endpoint that the request belongs tostruct dwc3_request *req: The request to prepareunsigned int entry_length: The last SG entry sizeunsigned int node: Indicates whether this is not the first entry (for isoc only)
Description
Return the number of TRBs prepared.
__dwc3_stop_active_transfer() #
int stop the current active transfer
Parameters
struct dwc3_ep *dep: isoc endpointbool force: set forcerm bit in the commandbool interrupt: command complete interrupt after End Transfer command
Description
When setting force, the ForceRM bit will be set. In that case the controller won't update the TRB progress on command completion. It also won't clear the HWO bit in the TRB. The command will also not complete immediately in that case.
dwc3_gadget_start_isoc_quirk() #
int workaround invalid frame number
Parameters
struct dwc3_ep *dep: isoc endpoint
Description
This function tests for the correct combination of BIT[15:14] from the 16-bit microframe number reported by the XferNotReady event for the future frame number to start the isoc transfer.
In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the XferNotReady event are invalid. The driver uses this number to schedule the isochronous transfer and passes it to the START TRANSFER command. Because this number is invalid, the command may fail. If BIT[15:14] matches the internal 16-bit microframe, the START TRANSFER command will pass and the transfer will start at the scheduled time, if it is off by 1, the command will still pass, but the transfer will start 2 seconds in the future. For all other conditions, the START TRANSFER command will fail with bus-expiry.
In order to workaround this issue, we can test for the correct combination of BIT[15:14] by sending START TRANSFER commands with different values of BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart (or 2 seconds). 4 seconds into the future will result in a bus-expiry status. As the result, within the 4 possible combinations for BIT[15:14], there will be 2 successful and 2 failure START COMMAND status. One of the 2 successful command status will result in a 2-second delay start. The smaller BIT[15:14] value is the correct combination.
Since there are only 4 outcomes and the results are ordered, we can simply test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to deduce the smaller successful combination.
Let test0 = test status for combination 'b00 and test1 = test status for 'b01 of BIT[15:14]. The correct combination is as follow:
if test0 fails and test1 passes, BIT[15:14] is 'b01 if test0 fails and test1 fails, BIT[15:14] is 'b10 if test0 passes and test1 fails, BIT[15:14] is 'b11 if test0 passes and test1 passes, BIT[15:14] is 'b00
Synopsys STAR 9001202023: Wrong microframe number for isochronous IN endpoints.
dwc3_gadget_setup_nump() #
void calculate and initialize NUMP field of DWC3_DCFG
Parameters
struct dwc3 *dwc: pointer to our context structure
Description
The following looks like complex but it's actually very simple. In order to calculate the number of packets we can burst at once on OUT transfers, we're gonna use RxFIFO size.
To calculate RxFIFO size we need two numbers: MDWIDTH = size, in bits, of the internal memory bus RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
Given these two numbers, the formula is simple:
RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
24 bytes is for 3x SETUP packets 16 bytes is a clock domain crossing tolerance
Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
dwc3_gadget_check_config() #
int ensure dwc3 can support the USB configuration
Parameters
struct usb_gadget *g: pointer to the USB gadget
Description
Used to record the maximum number of endpoints being used in a USB composite device. (across all configurations) This is to be used in the calculation of the TXFIFO sizes when resizing internal memory for individual endpoints. It will help ensured that the resizing logic reserves enough space for at least one max packet.
dwc3_get_dr_mode() #
int Validates and sets dr_mode
Parameters
struct dwc3 *dwc: pointer to our context structure
dwc3_core_soft_reset() #
int Issues core soft reset and PHY reset
Parameters
struct dwc3 *dwc: pointer to our context structure
dwc3_ref_clk_period() #
void Reference clock period configuration Default reference clock period depends on hardware configuration. For systems with reference clock that differs from the default, this will set clock period in DWC3_GUCTL register.
Parameters
struct dwc3 *dwc: Pointer to our controller context structure
dwc3_free_one_event_buffer() #
void Frees one event buffer
Parameters
struct dwc3 *dwc: Pointer to our controller context structurestruct dwc3_event_buffer *evt: Pointer to event buffer to be freed
dwc3_alloc_one_event_buffer() #
struct dwc3_event_buffer * Allocates one event buffer structure
Parameters
struct dwc3 *dwc: Pointer to our controller context structureunsigned int length: size of the event buffer
Description
Returns a pointer to the allocated event buffer structure on success otherwise ERR_PTR(errno).
dwc3_free_event_buffers() #
void frees all allocated event buffers
Parameters
struct dwc3 *dwc: Pointer to our controller context structure
dwc3_alloc_event_buffers() #
int Allocates num event buffers of size length
Parameters
struct dwc3 *dwc: pointer to our controller context structureunsigned int length: size of event buffer
Description
Returns 0 on success otherwise negative errno. In the error case, dwc may contain some buffers allocated but not all which were requested.
dwc3_event_buffers_setup() #
int setup our allocated event buffers
Parameters
struct dwc3 *dwc: pointer to our controller context structure
Description
Returns 0 on success otherwise negative errno.
dwc3_phy_setup() #
int Configure USB PHY Interface of DWC3 Core
Parameters
struct dwc3 *dwc: Pointer to our controller context structure
Description
Returns 0 on success. The USB PHY interfaces are configured but not initialized. The PHY interfaces and the PHYs get initialized together with the core in dwc3_core_init.
[1] Transfer Request Block
[2] Transfer Request Block pointing to another Transfer Request Block.
[3] The Debug File System
[4] The Config File System
[5] Command Block Wrapper
USB Error codes
Peios Kernel / Hardware and drivers / Driver development / USB
Revised: 2004-Oct-21
This is the documentation of (hopefully) all possible error codes (and their interpretation) that can be returned from usbcore.
Some of them are returned by the Host Controller Drivers (HCDs), which device drivers only see through usbcore. As a rule, all the HCDs should behave the same except for transfer speed dependent behaviors and the way certain faults are reported.
Error codes returned by usb_submit_urb() #
Non-USB-specific:
|
0 |
URB submission went fine |
|
|
no memory for allocation of internal structures |
USB-specific:
|
|
The URB is already active. |
|
|
specified USB-device or bus doesn't exist |
|
|
specified interface or endpoint does not exist or is not enabled |
|
|
host controller driver does not support queuing of this type of urb. (treat as a host controller bug.) |
|
|
|
|
|
ISO: |
|
|
Host controller driver can't schedule that many ISO frames. |
|
|
The pipe type specified in the URB doesn't match the endpoint's actual type. |
|
|
|
|
|
The wLength value in a control URB's setup packet does not match the URB's transfer_buffer_length. |
|
|
This request would overcommit the usb bandwidth reserved for periodic transfers (interrupt, isochronous). |
|
|
The device or host controller has been disabled due to some problem that could not be worked around. |
|
|
Submission failed because |
|
|
URB was rejected because the device is suspended. |
|
|
A control URB doesn't contain a Setup packet. |
Error codes returned by in urb->status or in iso_frame_desc[n].status (for ISO) #
USB device drivers may only test urb status values in completion handlers. This is because otherwise there would be a race between HCDs updating these values on one CPU, and device drivers testing them on another CPU.
A transfer's actual_length may be positive even when an error has been reported. That's because transfers often involve several packets, so that one or more packets could finish before an error stops further endpoint I/O.
For isochronous URBs, the urb status value is non-zero only if the URB is unlinked, the device is removed, the host controller is disabled, or the total transferred length is less than the requested length and the URB_SHORT_NOT_OK flag is set. Completion handlers for isochronous URBs should only see urb->status set to zero, -ENOENT, -ECONNRESET, -ESHUTDOWN, or -EREMOTEIO. Individual frame descriptor status fields may report more status codes.
|
0 |
Transfer completed successfully |
|
|
URB was synchronously unlinked by |
|
|
URB still pending, no results yet (That is, if drivers see this it's a bug.) |
|
|
Note that often the controller hardware does not distinguish among cases a), b), and c), so a driver cannot tell whether there was a protocol error, a failure to respond (often caused by device disconnect), or some other fault. |
|
|
|
No response packet received within the prescribed bus turn-around time. This error may instead be reported as |
|
|
Synchronous USB message functions use this code to indicate timeout expired before the transfer completed, and no other error was reported by HC. |
|
|
Endpoint stalled. For non-control endpoints, reset this status with |
|
|
During an IN transfer, the host controller received data from an endpoint faster than it could be written to system memory |
|
|
During an OUT transfer, the host controller could not retrieve data from system memory fast enough to keep up with the USB data rate |
|
|
The amount of data returned by the endpoint was greater than either the max packet size of the endpoint or the remaining buffer size. "Babble". |
|
|
The data read from the endpoint did not fill the specified buffer, and |
|
|
Device was removed. Often preceded by a burst of other errors, since the hub driver doesn't detect device removal events immediately. |
|
|
ISO transfer only partially completed (only set in |
|
|
ISO madness, if this happens: Log off and go home |
|
|
URB was asynchronously unlinked by |
|
|
The device or host controller has been disabled due to some problem that could not be worked around, such as a physical disconnect. |
[1] Error codes like -EPROTO, -EILSEQ and -EOVERFLOW normally indicate hardware problems such as bad devices (including firmware) or cables.
[2] This is also one of several codes that different kinds of host controller use to indicate a transfer has failed because of device disconnect. In the interval before the hub driver starts disconnect processing, devices may receive such fault reports for every request.
Error codes returned by usbcore-functions #
usb_register():
|
|
error during registering new driver |
usb_get_*/usb_set_*(), usb_control_msg(), usb_bulk_msg():
|
|
Timeout expired before the transfer completed. |
USB Gadget API for Linux
Peios Kernel / Hardware and drivers / Driver development / USB
Author: David Brownell
Date: 20 August 2004
Introduction #
This document presents a Linux-USB "Gadget" kernel mode API, for use within peripherals and other USB devices that embed Linux. It provides an overview of the API structure, and shows how that fits into a system development project. This is the first such API released on Linux to address a number of important problems, including:
-
Supports USB 2.0, for high speed devices which can stream data at several dozen megabytes per second.
-
Handles devices with dozens of endpoints just as well as ones with just two fixed-function ones. Gadget drivers can be written so they're easy to port to new hardware.
-
Flexible enough to expose more complex USB device capabilities such as multiple configurations, multiple interfaces, composite devices, and alternate interface settings.
-
USB "On-The-Go" (OTG) support, in conjunction with updates to the Linux-USB host side.
-
Sharing data structures and API models with the Linux-USB host side API. This helps the OTG support, and looks forward to more-symmetric frameworks (where the same I/O model is used by both host and device side drivers).
-
Minimalist, so it's easier to support new device controller hardware. I/O processing doesn't imply large demands for memory or CPU resources.
Most Linux developers will not be able to use this API, since they have USB host hardware in a PC, workstation, or server. Linux users with embedded systems are more likely to have USB peripheral hardware. To distinguish drivers running inside such hardware from the more familiar Linux "USB device drivers", which are host side proxies for the real USB devices, a different term is used: the drivers inside the peripherals are "USB gadget drivers". In USB protocol interactions, the device driver is the master (or "client driver") and the gadget driver is the slave (or "function driver").
The gadget API resembles the host side Linux-USB API in that both use queues of request objects to package I/O buffers, and those requests may be submitted or canceled. They share common definitions for the standard USB Chapter 9 messages, structures, and constants. Also, both APIs bind and unbind drivers to devices. The APIs differ in detail, since the host side's current URB framework exposes a number of implementation details and assumptions that are inappropriate for a gadget API. While the model for control transfers and configuration management is necessarily different (one side is a hardware-neutral master, the other is a hardware-aware slave), the endpoint I/0 API used here should also be usable for an overhead-reduced host side API.
Structure of Gadget Drivers #
A system running inside a USB peripheral normally has at least three layers inside the kernel to handle USB protocol processing, and may have additional layers in user space code. The gadget API is used by the middle layer to interact with the lowest level (which directly handles hardware).
In Linux, from the bottom up, these layers are:
-
USB Controller Driver
This is the lowest software level. It is the only layer that talks to hardware, through registers, fifos, dma, irqs, and the like. The
<linux/usb/gadget.h>API abstracts the peripheral controller endpoint hardware. That hardware is exposed through endpoint objects, which accept streams of IN/OUT buffers, and through callbacks that interact with gadget drivers. Since normal USB devices only have one upstream port, they only have one of these drivers. The controller driver can support any number of different gadget drivers, but only one of them can be used at a time.Examples of such controller hardware include the PCI-based NetChip 2280 USB 2.0 high speed controller, the SA-11x0 or PXA-25x UDC (found within many PDAs), and a variety of other products.
-
Gadget Driver
The lower boundary of this driver implements hardware-neutral USB functions, using calls to the controller driver. Because such hardware varies widely in capabilities and restrictions, and is used in embedded environments where space is at a premium, the gadget driver is often configured at compile time to work with endpoints supported by one particular controller. Gadget drivers may be portable to several different controllers, using conditional compilation. (Recent kernels substantially simplify the work involved in supporting new hardware, by autoconfiguring endpoints automatically for many bulk-oriented drivers.) Gadget driver responsibilities include:
-
handling setup requests (ep0 protocol responses) possibly including class-specific functionality
-
returning configuration and string descriptors
-
(re)setting configurations and interface altsettings, including enabling and configuring endpoints
-
handling life cycle events, such as managing bindings to hardware, USB suspend/resume, remote wakeup, and disconnection from the USB host.
-
managing IN and OUT transfers on all currently enabled endpoints
Such drivers may be modules of proprietary code, although that approach is discouraged in the Linux community.
-
-
Upper Level
Most gadget drivers have an upper boundary that connects to some Linux driver or framework in Linux. Through that boundary flows the data which the gadget driver produces and/or consumes through protocol transfers over USB. Examples include:
-
user mode code, using generic (gadgetfs) or application specific files in
/dev -
networking subsystem (for network gadgets, like the CDC Ethernet Model gadget driver)
-
data capture drivers, perhaps video4Linux or a scanner driver; or test and measurement hardware.
-
input subsystem (for HID gadgets)
-
sound subsystem (for audio gadgets)
-
file system (for PTP gadgets)
-
block i/o subsystem (for usb-storage gadgets)
-
... and more
-
-
Additional Layers
Other layers may exist. These could include kernel layers, such as network protocol stacks, as well as user mode applications building on standard POSIX system call APIs such as
open(),close(),read()andwrite(). On newer systems, POSIX Async I/O calls may be an option. Such user mode code will not necessarily be subject to the GNU General Public License (GPL).
OTG-capable systems will also need to include a standard Linux-USB host side stack, with usbcore, one or more Host Controller Drivers (HCDs), USB Device Drivers to support the OTG "Targeted Peripheral List", and so forth. There will also be an OTG Controller Driver, which is visible to gadget and device driver developers only indirectly. That helps the host and device side USB controllers implement the two new OTG protocols (HNP and SRP). Roles switch (host to peripheral, or vice versa) using HNP during USB suspend processing, and SRP can be viewed as a more battery-friendly kind of device wakeup protocol.
Over time, reusable utilities are evolving to help make some gadget driver tasks simpler. For example, building configuration descriptors from vectors of descriptors for the configurations interfaces and endpoints is now automated, and many drivers now use autoconfiguration to choose hardware endpoints and initialize their descriptors. A potential example of particular interest is code implementing standard USB-IF protocols for HID, networking, storage, or audio classes. Some developers are interested in KDB or KGDB hooks, to let target hardware be remotely debugged. Most such USB protocol code doesn't need to be hardware-specific, any more than network protocols like X11, HTTP, or NFS are. Such gadget-side interface drivers should eventually be combined, to implement composite devices.
Kernel Mode Gadget API #
Gadget drivers declare themselves through a struct usb_gadget_driver, which is responsible for most parts of enumeration for a struct usb_gadget. The response to a set_configuration usually involves enabling one or more of the struct usb_ep objects exposed by the gadget, and submitting one or more struct usb_request buffers to transfer data. Understand those four data types, and their operations, and you will understand how this API works.
The core API does not expose every possible hardware feature, only the most widely available ones. There are significant hardware features, such as device-to-device DMA (without temporary storage in a memory buffer) that would be added using hardware-specific APIs.
This API allows drivers to use conditional compilation to handle endpoint capabilities of different hardware, but doesn't require that. Hardware tends to have arbitrary restrictions, relating to transfer types, addressing, packet sizes, buffering, and availability. As a rule, such differences only matter for "endpoint zero" logic that handles device configuration and management. The API supports limited run-time detection of capabilities, through naming conventions for endpoints. Many drivers will be able to at least partially autoconfigure themselves. In particular, driver init sections will often have endpoint autoconfiguration logic that scans the hardware's list of endpoints to find ones matching the driver requirements (relying on those conventions), to eliminate some of the most common reasons for conditional compilation.
Like the Linux-USB host side API, this API exposes the "chunky" nature of USB messages: I/O requests are in terms of one or more "packets", and packet boundaries are visible to drivers. Compared to RS-232 serial protocols, USB resembles synchronous protocols like HDLC (N bytes per frame, multipoint addressing, host as the primary station and devices as secondary stations) more than asynchronous ones (tty style: 8 data bits per frame, no parity, one stop bit). So for example the controller drivers won't buffer two single byte writes into a single two-byte USB IN packet, although gadget drivers may do so when they implement protocols where packet boundaries (and "short packets") are not significant.
Driver Life Cycle #
Gadget drivers make endpoint I/O requests to hardware without needing to know many details of the hardware, but driver setup/configuration code needs to handle some differences. Use the API like this:
-
Register a driver for the particular device side usb controller hardware, such as the net2280 on PCI (USB 2.0), sa11x0 or pxa25x as found in Linux PDAs, and so on. At this point the device is logically in the USB ch9 initial state (
attached), drawing no power and not usable (since it does not yet support enumeration). Any host should not see the device, since it's not activated the data line pullup used by the host to detect a device, even if VBUS power is available. -
Register a gadget driver that implements some higher level device function. That will then bind() to a
usb_gadget, which activates the data line pullup sometime after detecting VBUS. -
The hardware driver can now start enumerating. The steps it handles are to accept USB
powerandset_addressrequests. Other steps are handled by the gadget driver. If the gadget driver module is unloaded before the host starts to enumerate, steps before step 7 are skipped. -
The gadget driver's
setup()call returns usb descriptors, based both on what the bus interface hardware provides and on the functionality being implemented. That can involve alternate settings or configurations, unless the hardware prevents such operation. For OTG devices, each configuration descriptor includes an OTG descriptor. -
The gadget driver handles the last step of enumeration, when the USB host issues a
set_configurationcall. It enables all endpoints used in that configuration, with all interfaces in their default settings. That involves using a list of the hardware's endpoints, enabling each endpoint according to its descriptor. It may also involve usingusb_gadget_vbus_drawto let more power be drawn from VBUS, as allowed by that configuration. For OTG devices, setting a configuration may also involve reporting HNP capabilities through a user interface. -
Do real work and perform data transfers, possibly involving changes to interface settings or switching to new configurations, until the device is disconnect()ed from the host. Queue any number of transfer requests to each endpoint. It may be suspended and resumed several times before being disconnected. On disconnect, the drivers go back to step 3 (above).
-
When the gadget driver module is being unloaded, the driver unbind() callback is issued. That lets the controller driver be unloaded.
Drivers will normally be arranged so that just loading the gadget driver module (or statically linking it into a Linux kernel) allows the peripheral device to be enumerated, but some drivers will defer enumeration until some higher level component (like a user mode daemon) enables it. Note that at this lowest level there are no policies about how ep0 configuration logic is implemented, except that it should obey USB specifications. Such issues are in the domain of gadget drivers, including knowing about implementation constraints imposed by some USB controllers or understanding that composite devices might happen to be built by integrating reusable components.
Note that the lifecycle above can be slightly different for OTG devices. Other than providing an additional OTG descriptor in each configuration, only the HNP-related differences are particularly visible to driver code. They involve reporting requirements during the SET_CONFIGURATION request, and the option to invoke HNP during some suspend callbacks. Also, SRP changes the semantics of usb_gadget_wakeup slightly.
USB 2.0 Chapter 9 Types and Constants #
Gadget drivers rely on common USB structures and constants defined in the linux/usb/ch9.h header file, which is standard in Linux 2.6+ kernels. These are the same types and constants used by host side drivers (and usbcore).
Core Objects and Methods #
These are declared in <linux/usb/gadget.h>, and are used by gadget drivers to interact with USB peripheral controller drivers.
struct usb_request #
describes one i/o request
Definition
;
Members
ep: The associated endpoint set byusb_ep_alloc_request().buf: Buffer used for data. Always provide this; some controllers only use PIO, or don't use DMA for some endpoints.length: Length of that datadma: DMA address corresponding to 'buf'. If you don't set this field, and the usb controller needs one, it is responsible for mapping and unmapping the buffer.sg: a scatterlist for SG-capable controllers.num_sgs: number of SG entriesnum_mapped_sgs: number of SG entries mapped to DMA (internal)stream_id: The stream id, when USB3.0 bulk streams are being usedis_last: Indicates if this is the last request of a stream_id before switching to a different stream (required for DWC3 controllers).no_interrupt: If true, hints that no completion irq is needed. Helpful sometimes with deep request queues that are handled directly by DMA controllers.zero: If true, when writing data, makes the last packet be "short" by adding a zero length packet as needed;short_not_ok: When reading data, makes short packets be treated as errors (queue stops advancing till cleanup).dma_mapped: Indicates if request has been mapped to DMA (internal)sg_was_mapped: Set if the scatterlist has been mapped before the requestcomplete: Function called when request completes, so this request and its buffer may be re-used. The function will always be called with interrupts disabled, and it must not sleep. Reads terminate with a short packet, or when the buffer fills, whichever comes first. When writes terminate, some data bytes will usually still be in flight (often in a hardware fifo). Errors (for reads or writes) stop the queue from advancing until the completion function returns, so that any transfers invalidated by the error may first be dequeued.context: For use by the completion callbacklist: For use by the gadget driver.frame_number: Reports the interval number in (micro)frame in which the isochronous transfer was transmitted or received.status: Reports completion code, zero or a negative errno. Normally, faults block the transfer queue from advancing until the completion callback returns. Code "-ESHUTDOWN" indicates completion caused by device disconnect, or when the driver disabled the endpoint.actual: Reports bytes transferred to/from the buffer. For reads (OUT transfers) this may be less than the requested length. If the short_not_ok flag is set, short reads are treated as errors even when status otherwise indicates successful completion. Note that for writes (IN transfers) some data bytes may still reside in a device-side FIFO when the request is reported as complete.
Description
These are allocated/freed through the endpoint they're used with. The hardware's driver can add extra per-request data to the memory it returns, which often avoids separate memory allocations (potential failures), later when the request is queued.
Request flags affect request handling, such as whether a zero length packet is written (the "zero" flag), whether a short read should be treated as an error (blocking request queue advance, the "short_not_ok" flag), or hinting that an interrupt is not required (the "no_interrupt" flag, for use with deep request queues).
Bulk endpoints can use any size buffers, and can also be used for interrupt transfers. interrupt-only endpoints can be much less functional.
NOTE
this is analogous to 'struct urb' on the host side, except that it's thinner and promotes more pre-allocation.
struct usb_ep_caps #
endpoint capabilities description
Definition
;
Members
type_control: Endpoint supports control type (reserved for ep0).type_iso: Endpoint supports isochronous transfers.type_bulk: Endpoint supports bulk transfers.type_int: Endpoint supports interrupt transfers.dir_in: Endpoint supports IN direction.dir_out: Endpoint supports OUT direction.
struct usb_ep #
device side representation of USB endpoint
Definition
;
Members
driver_data: for use by the gadget driver.name: identifier for the endpoint, such as "ep-a" or "ep9in-bulk"ops: Function pointers used to access hardware-specific operations.desc: endpoint descriptor. This pointer is set before the endpoint is enabled and remains valid until the endpoint is disabled.comp_desc: In case of SuperSpeed support, this is the endpoint companion descriptor that is used to configure the endpointep_list: the gadget's ep_list holds all of its endpointscaps: The structure describing types and directions supported by endpoint.claimed: True if this endpoint is claimed by a function.enabled: The current endpoint enabled/disabled state.mult: multiplier, 'mult' value for SS Isoc EPsmaxburst: the maximum number of bursts supported by this EP (for usb3)address: used to identify the endpoint when finding descriptor that matches connection speedmaxpacket: The maximum packet size used on this endpoint. The initial value can sometimes be reduced (hardware allowing), according to the endpoint descriptor used to configure the endpoint.maxpacket_limit: The maximum packet size value which can be handled by this endpoint. It's set once by UDC driver when endpoint is initialized, and should not be changed. Should not be confused with maxpacket.max_streams: The maximum number of streams supported by this EP (0 - 16, actual number is 2^n)
Description
the bus controller driver lists all the general purpose endpoints in
gadget->ep_list. the control endpoint (gadget->ep0) is not in that list,
and is accessed only in response to a driver setup() callback.
free_usb_request() #
void frees a usb_request object and its buffer
Parameters
struct usb_request *req: the request being freed
Description
This helper function frees both the request's buffer and the request object
itself by calling usb_ep_free_request(). Its signature is designed to be used
with DEFINE_FREE() to enable automatic, scope-based cleanup for usb_request
pointers.
struct usb_gadget #
represents a usb device
Definition
;
Members
work: (internal use) Workqueue to be used forsysfs_notify()udc: struct usb_udc pointer for this gadgetops: Function pointers used to access hardware-specific operations.ep0: Endpoint zero, used when reading or writing responses to driversetup()requestsep_list: List of other endpoints supported by the device.speed: Speed of current connection to USB host.max_speed: Maximal speed the UDC can handle. UDC must support this and all slower speeds.ssp_rate: Current connected SuperSpeed Plus signaling rate and lane count.max_ssp_rate: Maximum SuperSpeed Plus signaling rate and lane count the UDC can handle. The UDC must support this and all slower speeds and lower number of lanes.state: the state we are now (attached, suspended, configured, etc)state_lock: Spinlock protecting thestateandteardownmembers.teardown: True if the device is undergoing teardown, used to prevent new work from being scheduled during cleanup.name: Identifies the controller hardware type. Used in diagnostics and sometimes configuration.dev: Driver model state for this abstract device.isoch_delay: value from Set Isoch Delay request. Only valid on SS/SSPout_epnum: last used out ep numberin_epnum: last used in ep numbermA: last set mA valueotg_caps: OTG capabilities of this gadget.sg_supported: true if we can handle scatter-gatheris_otg: True if the USB device port uses a Mini-AB jack, so that the gadget driver must provide a USB OTG descriptor.is_a_peripheral: False unless is_otg, the "A" end of a USB cable is in the Mini-AB jack, and HNP has been used to switch roles so that the "A" device currently acts as A-Peripheral, not A-Host.b_hnp_enable: OTG device feature flag, indicating that the A-Host enabled HNP support.a_hnp_support: OTG device feature flag, indicating that the A-Host supports HNP at this port.a_alt_hnp_support: OTG device feature flag, indicating that the A-Host only supports HNP on a different root port.hnp_polling_support: OTG device feature flag, indicating if the OTG device in peripheral mode can support HNP polling.host_request_flag: OTG device feature flag, indicating if A-Peripheral or B-Peripheral wants to take host role.quirk_ep_out_aligned_size: epout requires buffer size to be aligned to MaxPacketSize.quirk_altset_not_supp: UDC controller doesn't support alt settings.quirk_stall_not_supp: UDC controller doesn't support stalling.quirk_zlp_not_supp: UDC controller doesn't support ZLP.quirk_avoids_skb_reserve: udc/platform wants to avoidskb_reserve()in u_ether.c to improve performance.is_selfpowered: if the gadget is self-powered.deactivated: True if gadget is deactivated - in deactivated state it cannot be connected.connected: True if gadget is connected.lpm_capable: If the gadget max_speed is FULL or HIGH, this flag indicates that it supports LPM as per the LPM ECN & errata.wakeup_capable: True if gadget is capable of sending remote wakeup.wakeup_armed: True if gadget is armed by the host for remote wakeup.irq: the interrupt number for device controller.id_number: a unique ID number for ensuring that gadget names are distinct
Description
Gadgets have a mostly-portable "gadget driver" implementing device functions, handling all usb configurations and interfaces. Gadget drivers talk to hardware-specific code indirectly, through ops vectors. That insulates the gadget driver from hardware details, and packages the hardware endpoints through generic i/o queues. The "usb_gadget" and "usb_ep" interfaces provide that insulation from the hardware.
Except for the driver data, all fields in this structure are read-only to the gadget driver. That driver data is part of the "driver model" infrastructure in 2.6 (and later) kernels, and for earlier systems is grouped in a similar structure that's not known to the rest of the kernel.
Values of the three OTG device feature flags are updated before the
setup() call corresponding to USB_REQ_SET_CONFIGURATION, and before
driver suspend() calls. They are valid only when is_otg, and when the
device is acting as a B-Peripheral (so is_a_peripheral is false).
usb_ep_align() #
size_t returns len aligned to ep's maxpacketsize.
Parameters
struct usb_ep *ep: the endpoint whose maxpacketsize is used to align lensize_t len: buffer size's length to align to ep's maxpacketsize
Description
This helper is used to align buffer's size to an ep's maxpacketsize.
usb_ep_align_maybe() #
size_t returns len aligned to ep's maxpacketsize if gadget requires quirk_ep_out_aligned_size, otherwise returns len.
Parameters
struct usb_gadget *g: controller to check for quirkstruct usb_ep *ep: the endpoint whose maxpacketsize is used to align lensize_t len: buffer size's length to align to ep's maxpacketsize
Description
This helper is used in case it's required for any reason to check and maybe align buffer's size to an ep's maxpacketsize.
gadget_is_altset_supported() #
int return true iff the hardware supports altsettings
Parameters
struct usb_gadget *g: controller to check for quirk
gadget_is_stall_supported() #
int return true iff the hardware supports stalling
Parameters
struct usb_gadget *g: controller to check for quirk
gadget_is_zlp_supported() #
int return true iff the hardware supports zlp
Parameters
struct usb_gadget *g: controller to check for quirk
gadget_avoids_skb_reserve() #
int return true iff the hardware would like to avoid skb_reserve to improve performance.
Parameters
struct usb_gadget *g: controller to check for quirk
gadget_is_dualspeed() #
int return true iff the hardware handles high speed
Parameters
struct usb_gadget *g: controller that might support both high and full speeds
gadget_is_superspeed() #
int return true if the hardware handles superspeed
Parameters
struct usb_gadget *g: controller that might support superspeed
gadget_is_superspeed_plus() #
int return true if the hardware handles superspeed plus
Parameters
struct usb_gadget *g: controller that might support superspeed plus
gadget_is_otg() #
int return true iff the hardware is OTG-ready
Parameters
struct usb_gadget *g: controller that might have a Mini-AB connector
Description
This is a runtime test, since kernels with a USB-OTG stack sometimes run on boards which only have a Mini-B (or Mini-A) connector.
struct usb_gadget_driver #
driver for usb gadget devices
Definition
;
Members
function: String describing the gadget's functionmax_speed: Highest speed the driver handles.bind: the driver's bind callbackunbind: Invoked when the driver is unbound from a gadget, usually from rmmod (after a disconnect is reported). Called in a context that permits sleeping.setup: Invoked for ep0 control requests that aren't handled by the hardware level driver. Most calls must be handled by the gadget driver, including descriptor and configuration management. The 16 bit members of the setup data are in USB byte order. Called in_interrupt; this may not sleep. Driver queues a response to ep0, or returns negative to stall.disconnect: Invoked after all transfers have been stopped, when the host is disconnected. May be called in_interrupt; this may not sleep. Some devices can't detect disconnect, so this might not be called except as part of controller shutdown.suspend: Invoked on USB suspend. May be called in_interrupt.resume: Invoked on USB resume. May be called in_interrupt.reset: Invoked on USB bus reset. It is mandatory for all gadget drivers and should be called in_interrupt.driver: Driver model state for this driver.udc_name: A name of UDC this driver should be bound to. If udc_name is NULL, this driver will be bound to any available UDC.match_existing_only: If udc is not found, return an error and fail the driver registrationis_bound: Allow a driver to be bound to only one gadget
Description
Devices are disabled till a gadget driver successfully bind()s, which
means the driver will handle setup() requests needed to enumerate (and
meet "chapter 9" requirements) then do some useful work.
If gadget->is_otg is true, the gadget driver must provide an OTG
descriptor during enumeration, or else fail the bind() call. In such
cases, no USB traffic may flow until both bind() returns without
having called usb_gadget_disconnect(), and the USB host stack has
initialized.
Drivers use hardware-specific knowledge to configure the usb hardware.
endpoint addressing is only one of several hardware characteristics that
are in descriptors the ep0 implementation returns from setup() calls.
Except for ep0 implementation, most driver code shouldn't need change to run on top of different usb controllers. It'll use endpoints set up by that ep0 implementation.
The usb controller driver handles a few standard usb requests. Those include set_address, and feature flags for devices, interfaces, and endpoints (the get_status, set_feature, and clear_feature requests).
Accordingly, the driver's setup() callback must always implement all
get_descriptor requests, returning at least a device descriptor and
a configuration descriptor. Drivers must make sure the endpoint
descriptors match any hardware constraints. Some hardware also constrains
other descriptors. (The pxa250 allows only configurations 1, 2, or 3).
The driver's setup() callback must also implement set_configuration,
and should also implement set_interface, get_configuration, and
get_interface. Setting a configuration (or interface) is where
endpoints should be activated or (config 0) shut down.
The gadget driver's setup() callback does not have to queue a response to
ep0 within the setup() call, the driver can do it after setup() returns.
The UDC driver must wait until such a response is queued before proceeding
with the data/status stages of the control transfer.
NOTE
Currently, a number of UDC drivers rely on USB_GADGET_DELAYED_STATUS
being returned from the setup() callback, which is a bug. See the comment
next to USB_GADGET_DELAYED_STATUS for details.
(Note that only the default control endpoint is supported. Neither hosts nor devices generally support control traffic except to ep0.)
Most devices will ignore USB suspend/resume operations, and so will not provide those callbacks. However, some may need to change modes when the host is not longer directing those activities. For example, local controls (buttons, dials, etc) may need to be re-enabled since the (remote) host can't do that any longer; or an error state might be cleared, to make the device behave identically whether or not power is maintained.
usb_gadget_register_driver_owner() #
int register a gadget driver
Parameters
struct usb_gadget_driver *driver: the driver being registeredstruct module *owner: the driver moduleconst char *mod_name: the driver module's build name
Context
can sleep
Description
Call this in your gadget driver's module initialization function, to tell the underlying UDC controller driver about your driver. The bind() function will be called to bind it to a gadget before this registration call returns. It's expected that the bind() function will be in init sections.
Use the macro defined below instead of calling this directly.
usb_gadget_unregister_driver() #
int unregister a gadget driver
Parameters
struct usb_gadget_driver *driver: the driver being unregistered
Context
can sleep
Description
Call this in your gadget driver's module cleanup function,
to tell the underlying usb controller that your driver is
going away. If the controller is connected to a USB host,
it will first disconnect(). The driver is also requested
to unbind() and clean up any device state, before this procedure
finally returns. It's expected that the unbind() functions
will be in exit sections, so may not be linked in some kernels.
struct usb_string #
wraps a C string and its USB id
Definition
;
Members
id: the (nonzero) ID for this strings: the string, in UTF-8 encoding
Description
If you're using usb_gadget_get_string(), use this to wrap a string
together with its ID.
struct usb_gadget_strings #
a set of USB strings in a given language
Definition
;
Members
language: identifies the strings' language (0x0409 for en-us)strings: array of strings with their ids
Description
If you're using usb_gadget_get_string(), use this to wrap all the
strings for a given language.
usb_free_descriptors() #
void free descriptors returned by usb_copy_descriptors()
Parameters
struct usb_descriptor_header **v: vector of descriptors
Optional Utilities #
The core API is sufficient for writing a USB Gadget Driver, but some optional utilities are provided to simplify common tasks. These utilities include endpoint autoconfiguration.
usb_gadget_get_string() #
int fill out a string descriptor
Parameters
const struct usb_gadget_strings *table: of c strings encoded using UTF-8int id: string id, from low byte of wValue in get string descriptoru8 *buf: at least 256 bytes, must be 16-bit aligned
Description
Finds the UTF-8 string matching the ID, and converts it into a string descriptor in utf16-le. Returns length of descriptor (always even) or negative errno
If your driver needs stings in multiple languages, you'll probably "switch (wIndex) { ... }" in your ep0 string descriptor logic, using this routine after choosing which set of UTF-8 strings to use. Note that US-ASCII is a strict subset of UTF-8; any string bytes with the eighth bit set will be multibyte UTF-8 characters, not ISO-8859/1 characters (which are also widely used in C strings).
usb_validate_langid() #
bool validate usb language identifiers
Parameters
u16 langid: usb language identifier
Description
Returns true for valid language identifier, otherwise false.
usb_descriptor_fillbuf() #
int fill buffer with descriptors
Parameters
void *buf: Buffer to be filledunsigned buflen: Size of bufconst struct usb_descriptor_header **src: Array of descriptor pointers, terminated by null pointer.
Description
Copies descriptors into the buffer, returning the length or a negative error code if they can't all be copied. Useful when assembling descriptors for an associated set of interfaces used as part of configuring a composite device; or in other cases where sets of descriptors need to be marshaled.
usb_copy_descriptors() #
struct usb_descriptor_header ** copy a vector of USB descriptors
Parameters
struct usb_descriptor_header **src: null-terminated vector to copy
Context
initialization code, which may sleep
Description
This makes a copy of a vector of USB descriptors. Its primary use is to support usb_function objects which can have multiple copies, each needing different descriptors. Functions may have static tables of descriptors, which are used as templates and customized with identifiers (for interfaces, strings, endpoints, and more) as needed by a given function instance.
Composite Device Framework #
The core API is sufficient for writing drivers for composite USB devices (with more than one function in a given configuration), and also multi-configuration devices (also more than one function, but not necessarily sharing a given configuration). There is however an optional framework which makes it easier to reuse and combine functions.
Devices using this framework provide a struct usb_composite_driver, which in turn provides one or more struct usb_configuration instances. Each such configuration includes at least one struct usb_function, which packages a user visible role such as "network link" or "mass storage device". Management functions may also exist, such as "Device Firmware Upgrade".
struct usb_os_desc_ext_prop #
describes one "Extended Property"
Definition
;
Members
entry: used to keep a list of extended propertiestype: Extended Property typename_len: Extended Property unicode name length, including terminating '\0'name: Extended Property namedata_len: Length of Extended Property blob (for unicode store double len)data: Extended Property blobitem: Represents this Extended Property in configfs
struct usb_os_desc #
describes OS descriptors associated with one interface
Definition
;
Members
ext_compat_id: 16 bytes of "Compatible ID" and "Subcompatible ID"ext_prop: Extended Properties listext_prop_len: Total length of Extended Properties blobsext_prop_count: Number of Extended Propertiesopts_mutex: Optional mutex protecting config data of a usb_function_instancegroup: Represents OS descriptors associated with an interface in configfsowner: Module associated with this OS descriptor
struct usb_os_desc_table #
describes OS descriptors associated with one interface of a usb_function
Definition
;
Members
if_id: Interface idos_desc: "Extended Compatibility ID" and "Extended Properties" of the interface
Description
Each interface can have at most one "Extended Compatibility ID" and a number of "Extended Properties".
struct usb_function #
describes one function of a configuration
Definition
;
Members
name: For diagnostics, identifies the function.strings: tables of strings, keyed by identifiers assigned duringbind()and by language IDs provided in control requestsfs_descriptors: Table of full (or low) speed descriptors, using interface and string identifiers assigned during bind(). If this pointer is null, the function will not be available at full speed (or at low speed).hs_descriptors: Table of high speed descriptors, using interface and string identifiers assigned during bind(). If this pointer is null, the function will not be available at high speed.ss_descriptors: Table of super speed descriptors, using interface and string identifiers assigned during bind(). If this pointer is null after initiation, the function will not be available at super speed.ssp_descriptors: Table of super speed plus descriptors, using interface and string identifiers assigned during bind(). If this pointer is null after initiation, the function will not be available at super speed plus.config: assigned when usb_add_function() is called; this is the configuration with which this function is associated.os_desc_table: Table of (interface id, os descriptors) pairs. The function can expose more than one interface. If an interface is a member of an IAD, only the first interface of IAD has its entry in the table.os_desc_n: Number of entries in os_desc_tablebind: Before the gadget can register, all of its functionsbind()to the available resources including string and interface identifiers used in interface or class descriptors; endpoints; I/O buffers; and so on.unbind: Reverses bind; called as a side effect of unregistering the driver which added this function.free_func: free the struct usb_function.mod: (internal) points to the module that created this structure.set_alt: (REQUIRED) Reconfigures altsettings; function drivers may initialize usb_ep.driver data at this time (when it is used). Note that setting an interface to its current altsetting resets interface state, and that all interfaces have a disabled state.get_alt: Returns the active altsetting. If this is not provided, then only altsetting zero is supported.disable: (REQUIRED) Indicates the function should be disabled. Reasons include host resetting or reconfiguring the gadget, and disconnection.setup: Used for interface-specific control requests.req_match: Tests if a given class request can be handled by this function.suspend: Notifies functions when the host stops sending USB traffic.resume: Notifies functions when the host restarts USB traffic.get_status: Returns function status as a reply toGetStatus()request when the recipient is Interface.func_suspend: callback to be called when SetFeature(FUNCTION_SUSPEND) is reseivedfunc_suspended: Indicates whether the function is in function suspend state.func_wakeup_armed: Indicates whether the function is armed by the host for wakeup signaling.
Description
A single USB function uses one or more interfaces, and should in most cases support operation at both full and high speeds. Each function is associated by usb_add_function() with a one configuration; that function causes bind() to be called so resources can be allocated as part of setting up a gadget driver. Those resources include endpoints, which should be allocated using usb_ep_autoconfig().
To support dual speed operation, a function driver provides descriptors for both high and full speed operation. Except in rare cases that don't involve bulk endpoints, each speed needs different endpoint descriptors.
Function drivers choose their own strategies for managing instance data. The simplest strategy just declares it "static', which means the function can only be activated once. If the function needs to be exposed in more than one configuration at a given speed, it needs to support multiple usb_function structures (one for each configuration).
A more complex strategy might encapsulate a usb_function structure inside a driver-specific instance structure to allows multiple activations. An example of multiple activations might be a CDC ACM function that supports two or more distinct instances within the same configuration, providing several independent logical data links to a USB host.
struct usb_configuration #
represents one gadget configuration
Definition
;
Members
label: For diagnostics, describes the configuration.strings: Tables of strings, keyed by identifiers assigned during bind() and by language IDs provided in control requests.descriptors: Table of descriptors preceding all function descriptors. Examples include OTG and vendor-specific descriptors.unbind: Reverses bind; called as a side effect of unregistering the driver which added this configuration.setup: Used to delegate control requests that aren't handled by standard device infrastructure or directed at a specific interface.bConfigurationValue: Copied into configuration descriptor.iConfiguration: Copied into configuration descriptor.bmAttributes: Copied into configuration descriptor.MaxPower: Power consumption in mA. Used to compute bMaxPower in the configuration descriptor after considering the bus speed.cdev: assigned by usb_add_config() before calling bind(); this is the device associated with this configuration.
Description
Configurations are building blocks for gadget drivers structured around function drivers. Simple USB gadgets require only one function and one configuration, and handle dual-speed hardware by always providing the same functionality. Slightly more complex gadgets may have more than one single-function configuration at a given speed; or have configurations that only work at one speed.
Composite devices are, by definition, ones with configurations which include more than one function.
The lifecycle of a usb_configuration includes allocation, initialization of the fields described above, and calling usb_add_config() to set up internal data and bind it to a specific device. The configuration's bind() method is then used to initialize all the functions and then call usb_add_function() for them.
Those functions would normally be independent of each other, but that's
not mandatory. CDC WMC devices are an example where functions often
depend on other functions, with some functions subsidiary to others.
Such interdependency may be managed in any way, so long as all of the
descriptors complete by the time the composite driver returns from
its bind() routine.
struct usb_composite_driver #
groups configurations into a gadget
Definition
;
Members
name: For diagnostics, identifies the driver.dev: Template descriptor for the device, including default device identifiers.strings: tables of strings, keyed by identifiers assigned during bind and language IDs provided in control requests. Note: The first entries are predefined. The first entry that may be used is USB_GADGET_FIRST_AVAIL_IDXmax_speed: Highest speed the driver supports.needs_serial: set to 1 if the gadget needs userspace to provide a serial number. If one is not provided, warning will be printed.bind: (REQUIRED) Used to allocate resources that are shared across the whole device, such as string IDs, and add its configurations using usb_add_config(). This may fail by returning a negative errno value; it should return zero on successful initialization.unbind: Reverses bind; called as a side effect of unregistering this driver.disconnect: optional driver disconnect methodsuspend: Notifies when the host stops sending USB traffic, after function notificationsresume: Notifies configuration when the host restarts USB traffic, before function notificationsgadget_driver: Gadget driver controlling this driver
Description
Devices default to reporting self powered operation. Devices which rely on bus powered operation should report this in their bind method.
Before returning from bind, various fields in the template descriptor may be overridden. These include the idVendor/idProduct/bcdDevice values normally to bind the appropriate host side driver, and the three strings (iManufacturer, iProduct, iSerialNumber) normally used to provide user meaningful device identifiers. (The strings will not be defined unless they are defined in dev and strings.) The correct ep0 maxpacket size is also reported, as defined by the underlying controller driver.
module_usb_composite_driver() #
Helper macro for registering a USB gadget composite driver
Parameters
__usb_composite_driver: usb_composite_driver struct
Description
Helper macro for USB gadget composite drivers which do not do anything
special in module init/exit. This eliminates a lot of boilerplate. Each
module may only use this macro once, and calling it replaces module_init()
and module_exit()
struct usb_composite_dev #
represents one composite usb gadget
Definition
;
Members
gadget: read-only, abstracts the gadget's usb peripheral controllerreq: used for control responses; buffer is pre-allocatedos_desc_req: used for OS descriptors responses; buffer is pre-allocatedconfig: the currently active configurationqw_sign: qwSignature part of the OS stringb_vendor_code: bMS_VendorCode part of the OS stringos_desc_config: the configuration to be used with OS descriptorsuse_os_string: false by default, interested gadgets set itbcd_webusb_version: 0x0100 by default, WebUSB specification versionb_webusb_vendor_code: 0x0 by default, vendor code for WebUSBlanding_page: empty by default, landing page to announce in WebUSBuse_webusb: false by default, interested gadgets set itsetup_pending: true when setup request is queued but not completedos_desc_pending: true when os_desc request is queued but not completed
Description
One of these devices is allocated and initialized before the
associated device driver's bind() is called.
config_ep_by_speed_and_alt() #
int configures the given endpoint according to gadget speed.
Parameters
struct usb_gadget *g: pointer to the gadgetstruct usb_function *f: usb functionstruct usb_ep *_ep: the endpoint to configureu8 alt: alternate setting number
Return
error code, 0 on success
Description
This function chooses the right descriptors for a given endpoint according to gadget speed and saves it in the endpoint desc field. If the endpoint already has a descriptor assigned to it - overwrites it with currently corresponding descriptor. The endpoint maxpacket field is updated according to the chosen descriptor.
Note
the supplied function should hold all the descriptors for supported speeds
config_ep_by_speed() #
int configures the given endpoint according to gadget speed.
Parameters
struct usb_gadget *g: pointer to the gadgetstruct usb_function *f: usb functionstruct usb_ep *_ep: the endpoint to configure
Return
error code, 0 on success
Description
This function chooses the right descriptors for a given endpoint according to gadget speed and saves it in the endpoint desc field. If the endpoint already has a descriptor assigned to it - overwrites it with currently corresponding descriptor. The endpoint maxpacket field is updated according to the chosen descriptor.
Note
the supplied function should hold all the descriptors for supported speeds
usb_add_function() #
int add a function to a configuration
Parameters
struct usb_configuration *config: the configurationstruct usb_function *function: the function being added
Context
single threaded during gadget setup
Description
After initialization, each configuration must have one or more functions added to it. Adding a function involves calling its bind() method to allocate resources such as interface and string identifiers and endpoints.
This function returns the value of the function's bind(), which is
zero for success else a negative errno value.
usb_function_deactivate() #
int prevent function and gadget enumeration
Parameters
struct usb_function *function: the function that isn't yet ready to respond
Description
Blocks response of the gadget driver to host enumeration by preventing the data line pullup from being activated. This is normally called during bind() processing to change from the initial "ready to respond" state, or when a required resource becomes available.
For example, drivers that serve as a passthrough to a userspace daemon can block enumeration unless that daemon (such as an OBEX, MTP, or print server) is ready to handle host requests.
Not all systems support software control of their USB peripheral data pullups.
Returns zero on success, else negative errno.
usb_function_activate() #
int allow function and gadget enumeration
Parameters
struct usb_function *function: function on whichusb_function_activate()was called
Description
Reverses effect of usb_function_deactivate(). If no more functions
are delaying their activation, the gadget driver will respond to
host enumeration procedures.
Returns zero on success, else negative errno.
usb_interface_id() #
int allocate an unused interface ID
Parameters
struct usb_configuration *config: configuration associated with the interfacestruct usb_function *function: function handling the interface
Context
single threaded during gadget setup
Description
usb_interface_id() is called from usb_function.bind() callbacks to
allocate new interface IDs. The function driver will then store that
ID in interface, association, CDC union, and other descriptors. It
will also handle any control requests targeted at that interface,
particularly changing its altsetting via set_alt(). There may
also be class-specific or vendor-specific requests to handle.
All interface identifier should be allocated using this routine, to ensure that for example different functions don't wrongly assign different meanings to the same identifier. Note that since interface identifiers are configuration-specific, functions used in more than one configuration (or more than once in a given configuration) need multiple versions of the relevant descriptors.
Returns the interface ID which was allocated; or -ENODEV if no more interface IDs can be allocated.
usb_func_wakeup() #
int sends function wake notification to the host.
Parameters
struct usb_function *func: function that sends the remote wakeup notification.
Description
Applicable to devices operating at enhanced superspeed when usb functions are put in function suspend state and armed for function remote wakeup. On completion, function wake notification is sent. If the device is in low power state it tries to bring the device to active state before sending the wake notification. Since it is a synchronous call, caller must take care of not calling it in interrupt context. For devices operating at lower speeds returns negative errno.
Returns zero on success, else negative errno.
usb_add_config() #
int add a configuration to a device.
Parameters
struct usb_composite_dev *cdev: wraps the USB gadgetstruct usb_configuration *config: the configuration, with bConfigurationValue assignedint (*bind)(struct usb_configuration *): the configuration's bind function
Context
single threaded during gadget setup
Description
One of the main tasks of a composite bind() routine is to add each of the configurations it supports, using this routine.
This function returns the value of the configuration's bind(), which is zero for success else a negative errno value. Binding configurations assigns global resources including string IDs, and per-configuration resources such as interface IDs and endpoints.
usb_string_id() #
int allocate an unused string ID
Parameters
struct usb_composite_dev *cdev: the device whose string descriptor IDs are being allocated
Context
single threaded during gadget setup
Description
usb_string_id() is called from bind() callbacks to allocate
string IDs. Drivers for functions, configurations, or gadgets will
then store that ID in the appropriate descriptors and string table.
All string identifier should be allocated using this, usb_string_ids_tab() or usb_string_ids_n() routine, to ensure that for example different functions don't wrongly assign different meanings to the same identifier.
usb_string_ids_tab() #
int allocate unused string IDs in batch
Parameters
struct usb_composite_dev *cdev: the device whose string descriptor IDs are being allocatedstruct usb_string *str: an array of usb_string objects to assign numbers to
Context
single threaded during gadget setup
Description
usb_string_ids() is called from bind() callbacks to allocate
string IDs. Drivers for functions, configurations, or gadgets will
then copy IDs from the string table to the appropriate descriptors
and string table for other languages.
All string identifier should be allocated using this, usb_string_id() or usb_string_ids_n() routine, to ensure that for example different functions don't wrongly assign different meanings to the same identifier.
usb_gstrings_attach() #
struct usb_string * attach gadget strings to a cdev and assign ids
Parameters
struct usb_composite_dev *cdev: the device whose string descriptor IDs are being allocated and attached.struct usb_gadget_strings **sp: an array of usb_gadget_strings to attach.unsigned n_strings: number of entries in each usb_strings array (sp[]->strings)
Description
This function will create a deep copy of usb_gadget_strings and usb_string and attach it to the cdev. The actual string (usb_string.s) will not be copied but only a referenced will be made. The struct usb_gadget_strings array may contain multiple languages and should be NULL terminated. The ->language pointer of each struct usb_gadget_strings has to contain the same amount of entries. For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the first usb_string entry of es-ES contains the translation of the first usb_string entry of en-US. Therefore both entries become the same id assign.
usb_string_ids_n() #
int allocate unused string IDs in batch
Parameters
struct usb_composite_dev *c: the device whose string descriptor IDs are being allocatedunsigned n: number of string IDs to allocate
Context
single threaded during gadget setup
Description
Returns the first requested ID. This ID and next n-1 IDs are now valid IDs. At least provided that n is non-zero because if it is, returns last requested ID which is now very useful information.
usb_string_ids_n() is called from bind() callbacks to allocate
string IDs. Drivers for functions, configurations, or gadgets will
then store that ID in the appropriate descriptors and string table.
All string identifier should be allocated using this, usb_string_id() or usb_string_ids_n() routine, to ensure that for example different functions don't wrongly assign different meanings to the same identifier.
usb_composite_probe() #
int register a composite driver
Parameters
struct usb_composite_driver *driver: the driver to register
Context
single threaded during gadget setup
Description
This function is used to register drivers using the composite driver framework. The return value is zero, or a negative errno value. Those values normally come from the driver's bind method, which does all the work of setting up the driver to match the hardware.
On successful return, the gadget is ready to respond to requests from
the host, unless one of its components invokes usb_gadget_disconnect()
while it was binding. That would usually be done in order to wait for
some userspace participation.
usb_composite_unregister() #
void unregister a composite driver
Parameters
struct usb_composite_driver *driver: the driver to unregister
Description
This function is used to unregister drivers using the composite driver framework.
usb_composite_setup_continue() #
void Continue with the control transfer
Parameters
struct usb_composite_dev *cdev: the composite device who's control transfer was kept waiting
Description
This function must be called by the USB function driver to continue
with the control transfer's data/status stage in case it had requested to
delay the data/status stages. A USB function's setup handler (e.g. set_alt())
can request the composite framework to delay the setup request's data/status
stages by returning USB_GADGET_DELAYED_STATUS.
Composite Device Functions #
At this writing, a few of the current gadget drivers have been converted to this framework. Near-term plans include converting all of them, except for gadgetfs.
Peripheral Controller Drivers #
The first hardware supporting this API was the NetChip 2280 controller, which supports USB 2.0 high speed and is based on PCI. This is the net2280 driver module. The driver supports Linux kernel versions 2.4 and 2.6; contact NetChip Technologies for development boards and product information.
Other hardware working in the gadget framework includes: Intel's PXA 25x and IXP42x series processors (pxa2xx_udc), Toshiba TC86c001 "Goku-S" (goku_udc), Renesas SH7705/7727 (sh_udc), MediaQ 11xx (mq11xx_udc), Hynix HMS30C7202 (h7202_udc), National 9303/4 (n9604_udc), Texas Instruments OMAP (omap_udc), Sharp LH7A40x (lh7a40x_udc), and more. Most of those are full speed controllers.
At this writing, there are people at work on drivers in this framework for several other USB device controllers, with plans to make many of them be widely available.
A partial USB simulator, the dummy_hcd driver, is available. It can act like a net2280, a pxa25x, or an sa11x0 in terms of available endpoints and device speeds; and it simulates control, bulk, and to some extent interrupt transfers. That lets you develop some parts of a gadget driver on a normal PC, without any special hardware, and perhaps with the assistance of tools such as GDB running with User Mode Linux. At least one person has expressed interest in adapting that approach, hooking it up to a simulator for a microcontroller. Such simulators can help debug subsystems where the runtime hardware is unfriendly to software development, or is not yet available.
Support for other controllers is expected to be developed and contributed over time, as this driver framework evolves.
Gadget Drivers #
In addition to Gadget Zero (used primarily for testing and development with drivers for usb controller hardware), other gadget drivers exist.
There's an ethernet gadget driver, which implements one of the most useful Communications Device Class (CDC) models. One of the standards for cable modem interoperability even specifies the use of this ethernet model as one of two mandatory options. Gadgets using this code look to a USB host as if they're an Ethernet adapter. It provides access to a network where the gadget's CPU is one host, which could easily be bridging, routing, or firewalling access to other networks. Since some hardware can't fully implement the CDC Ethernet requirements, this driver also implements a "good parts only" subset of CDC Ethernet. (That subset doesn't advertise itself as CDC Ethernet, to avoid creating problems.)
Support for Microsoft's RNDIS protocol has been contributed by Pengutronix and Auerswald GmbH. This is like CDC Ethernet, but it runs on more slightly USB hardware (but less than the CDC subset). However, its main claim to fame is being able to connect directly to recent versions of Windows, using drivers that Microsoft bundles and supports, making it much simpler to network with Windows.
There is also support for user mode gadget drivers, using gadgetfs. This provides a User Mode API that presents each endpoint as a single file descriptor. I/O is done using normal read() and read() calls. Familiar tools like GDB and pthreads can be used to develop and debug user mode drivers, so that once a robust controller driver is available many applications for it won't require new kernel mode software. Linux 2.6 Async I/O (AIO) support is available, so that user mode software can stream data with only slightly more overhead than a kernel driver.
There's a USB Mass Storage class driver, which provides a different solution for interoperability with systems such as MS-Windows and MacOS. That Mass Storage driver uses a file or block device as backing store for a drive, like the loop driver. The USB host uses the BBB, CB, or CBI versions of the mass storage class specification, using transparent SCSI commands to access the data from the backing store.
There's a "serial line" driver, useful for TTY style operation over USB. The latest version of that driver supports CDC ACM style operation, like a USB modem, and so on most hardware it can interoperate easily with MS-Windows. One interesting use of that driver is in boot firmware (like a BIOS), which can sometimes use that model with very small systems without real serial lines.
Support for other kinds of gadget is expected to be developed and contributed over time, as this driver framework evolves.
USB On-The-GO (OTG) #
USB OTG support on Linux 2.6 was initially developed by Texas Instruments for OMAP 16xx and 17xx series processors. Other OTG systems should work in similar ways, but the hardware level details could be very different.
Systems need specialized hardware support to implement OTG, notably including a special Mini-AB jack and associated transceiver to support Dual-Role operation: they can act either as a host, using the standard Linux-USB host side driver stack, or as a peripheral, using this gadget framework. To do that, the system software relies on small additions to those programming interfaces, and on a new internal component (here called an "OTG Controller") affecting which driver stack connects to the OTG port. In each role, the system can reuse the existing pool of hardware-neutral drivers, layered on top of the controller driver interfaces (usb_bus or usb_gadget). Such drivers need at most minor changes, and most of the calls added to support OTG can also benefit non-OTG products.
-
Gadget drivers test the
is_otgflag, and use it to determine whether or not to include an OTG descriptor in each of their configurations. -
Gadget drivers may need changes to support the two new OTG protocols, exposed in new gadget attributes such as
b_hnp_enableflag. HNP support should be reported through a user interface (two LEDs could suffice), and is triggered in some cases when the host suspends the peripheral. SRP support can be user-initiated just like remote wakeup, probably by pressing the same button. -
On the host side, USB device drivers need to be taught to trigger HNP at appropriate moments, using
usb_suspend_device(). That also conserves battery power, which is useful even for non-OTG configurations. -
Also on the host side, a driver must support the OTG "Targeted Peripheral List". That's just a whitelist, used to reject peripherals not supported with a given Linux OTG host. This whitelist is product-specific; each product must modify
otg_whitelist.hto match its interoperability specification.Non-OTG Linux hosts, like PCs and workstations, normally have some solution for adding drivers, so that peripherals that aren't recognized can eventually be supported. That approach is unreasonable for consumer products that may never have their firmware upgraded, and where it's usually unrealistic to expect traditional PC/workstation/server kinds of support model to work. For example, it's often impractical to change device firmware once the product has been distributed, so driver bugs can't normally be fixed if they're found after shipment.
Additional changes are needed below those hardware-neutral usb_bus and usb_gadget driver interfaces; those aren't discussed here in any detail. Those affect the hardware-specific code for each USB Host or Peripheral controller, and how the HCD initializes (since OTG can be active only on a single port). They also involve what may be called an OTG Controller Driver, managing the OTG transceiver and the OTG state machine logic as well as much of the root hub behavior for the OTG port. The OTG controller driver needs to activate and deactivate USB controllers depending on the relevant device role. Some related changes were needed inside usbcore, so that it can identify OTG-capable devices and respond appropriately to HNP or SRP protocols.
USB hotplugging
Peios Kernel / Hardware and drivers / Driver development / USB
Linux Hotplugging #
In hotpluggable buses like USB (and Cardbus PCI), end-users plug devices into the bus with power on. In most cases, users expect the devices to become immediately usable. That means the system must do many things, including:
Find a driver that can handle the device. That may involve loading a kernel module; newer drivers can use module-init-tools to publish their device (and class) support to user utilities.
Bind a driver to that device. Bus frameworks do that using a device driver's probe() routine.
Tell other subsystems to configure the new device. Print queues may need to be enabled, networks brought up, disk partitions mounted, and so on. In some cases these will be driver-specific actions.
This involves a mix of kernel mode and user mode actions. Making devices be immediately usable means that any user mode actions can't wait for an administrator to do them: the kernel must trigger them, either passively (triggering some monitoring daemon to invoke a helper program) or actively (calling such a user mode helper program directly).
Those triggered actions must support a system's administrative policies; such programs are called "policy agents" here. Typically they involve shell scripts that dispatch to more familiar administration tools.
Because some of those actions rely on information about drivers (metadata) that is currently available only when the drivers are dynamically linked, you get the best hotplugging when you configure a highly modular system.
Kernel Hotplug Helper (/sbin/hotplug) #
There is a kernel parameter: /proc/sys/kernel/hotplug, which normally holds the pathname /sbin/hotplug. That parameter names a program which the kernel may invoke at various times.
The /sbin/hotplug program can be invoked by any subsystem as part of its reaction to a configuration change, from a thread in that subsystem. Only one parameter is required: the name of a subsystem being notified of some kernel event. That name is used as the first key for further event dispatch; any other argument and environment parameters are specified by the subsystem making that invocation.
Hotplug software and other resources is available at:
Mailing list information is also available at that site.
USB Policy Agent #
The USB subsystem currently invokes /sbin/hotplug when USB devices are added or removed from system. The invocation is done by the kernel hub workqueue [hub_wq], or else as part of root hub initialization (done by init, modprobe, kapmd, etc). Its single command line parameter is the string "usb", and it passes these environment variables:
|
ACTION |
|
|
PRODUCT |
USB vendor, product, and version codes (hex) |
|
TYPE |
device class codes (decimal) |
|
INTERFACE |
interface 0 class codes (decimal) |
If "usbdevfs" is configured, DEVICE and DEVFS are also passed. DEVICE is the pathname of the device, and is useful for devices with multiple and/or alternate interfaces that complicate driver selection. By design, USB hotplugging is independent of usbdevfs: you can do most essential parts of USB device setup without using that filesystem, and without running a user mode daemon to detect changes in system configuration.
Currently available policy agent implementations can load drivers for modules, and can invoke driver-specific setup scripts. The newest ones leverage USB module-init-tools support. Later agents might unload drivers.
USB Modutils Support #
Current versions of module-init-tools will create a modules.usbmap file which contains the entries from each driver's MODULE_DEVICE_TABLE. Such files can be used by various user mode policy agents to make sure all the right driver modules get loaded, either at boot time or later.
See linux/usb.h for full information about such table entries; or look at existing drivers. Each table entry describes one or more criteria to be used when matching a driver to a device or class of devices. The specific criteria are identified by bits set in "match_flags", paired with field values. You can construct the criteria directly, or with macros such as these, and use driver_info to store more information:
USB_DEVICE (vendorId, productId)
... matching devices with specified vendor and product ids
USB_DEVICE_VER (vendorId, productId, lo, hi)
... like USB_DEVICE with lo <= productversion <= hi
USB_INTERFACE_INFO (class, subclass, protocol)
... matching specified interface class info
USB_DEVICE_INFO (class, subclass, protocol)
... matching specified device class info
A short example, for a driver that supports several specific USB devices and their quirks, might have a MODULE_DEVICE_TABLE like this:
static const struct usb_device_id mydriver_id_table[] = {
{ USB_DEVICE (0x9999, 0xaaaa), driver_info: QUIRK_X },
{ USB_DEVICE (0xbbbb, 0x8888), driver_info: QUIRK_Y|QUIRK_Z },
...
{ } /* end with an all-zeroes entry */
};
MODULE_DEVICE_TABLE(usb, mydriver_id_table);
Most USB device drivers should pass these tables to the USB subsystem as well as to the module management subsystem. Not all, though: some driver frameworks connect using interfaces layered over USB, and so they won't need such a struct usb_driver.
Drivers that connect directly to the USB subsystem should be declared something like this:
static struct usb_driver mydriver = {
.name = "mydriver",
.id_table = mydriver_id_table,
.probe = my_probe,
.disconnect = my_disconnect,
/*
if using the usb chardev framework:
.minor = MY_USB_MINOR_START,
.fops = my_file_ops,
if exposing any operations through usbdevfs:
.ioctl = my_ioctl,
*/
};
When the USB subsystem knows about a driver's device ID table, it's used when choosing drivers to probe(). The thread doing new device processing checks drivers' device ID entries from the MODULE_DEVICE_TABLE against interface and device descriptors for the device. It will only call probe() if there is a match, and the third argument to probe() will be the entry that matched.
If you don't provide an id_table for your driver, then your driver may get probed for each new device; the third parameter to probe() will be NULL.
USB device persistence during system suspend
Peios Kernel / Hardware and drivers / Driver development / USB
Author: Alan Stern <stern@rowland.harvard.edu>
Date: September 2, 2006 (Updated February 25, 2008)
What is the problem? #
According to the USB specification, when a USB bus is suspended the bus must continue to supply suspend current (around 1-5 mA). This is so that devices can maintain their internal state and hubs can detect connect-change events (devices being plugged in or unplugged). The technical term is "power session".
If a USB device's power session is interrupted then the system is required to behave as though the device has been unplugged. It's a conservative approach; in the absence of suspend current the computer has no way to know what has actually happened. Perhaps the same device is still attached or perhaps it was removed and a different device plugged into the port. The system must assume the worst.
By default, Linux behaves according to the spec. If a USB host controller loses power during a system suspend, then when the system wakes up all the devices attached to that controller are treated as though they had disconnected. This is always safe and it is the "officially correct" thing to do.
For many sorts of devices this behavior doesn't matter in the least. If the kernel wants to believe that your USB keyboard was unplugged while the system was asleep and a new keyboard was plugged in when the system woke up, who cares? It'll still work the same when you type on it.
Unfortunately problems _can_ arise, particularly with mass-storage devices. The effect is exactly the same as if the device really had been unplugged while the system was suspended. If you had a mounted filesystem on the device, you're out of luck -- everything in that filesystem is now inaccessible. This is especially annoying if your root filesystem was located on the device, since your system will instantly crash.
Loss of power isn't the only mechanism to worry about. Anything that interrupts a power session will have the same effect. For example, even though suspend current may have been maintained while the system was asleep, on many systems during the initial stages of wakeup the firmware (i.e., the BIOS) resets the motherboard's USB host controllers. Result: all the power sessions are destroyed and again it's as though you had unplugged all the USB devices. Yes, it's entirely the BIOS's fault, but that doesn't do _you_ any good unless you can convince the BIOS supplier to fix the problem (lots of luck!).
On many systems the USB host controllers will get reset after a suspend-to-RAM. On almost all systems, no suspend current is available during hibernation (also known as swsusp or suspend-to-disk). You can check the kernel log after resuming to see if either of these has happened; look for lines saying "root hub lost power or was reset".
In practice, people are forced to unmount any filesystems on a USB device before suspending. If the root filesystem is on a USB device, the system can't be suspended at all. (All right, it _can_ be suspended -- but it will crash as soon as it wakes up, which isn't much better.)
What is the solution? #
The kernel includes a feature called USB-persist. It tries to work around these issues by allowing the core USB device data structures to persist across a power-session disruption.
It works like this. If the kernel sees that a USB host controller is not in the expected state during resume (i.e., if the controller was reset or otherwise had lost power) then it applies a persistence check to each of the USB devices below that controller for which the "persist" attribute is set. It doesn't try to resume the device; that can't work once the power session is gone. Instead it issues a USB port reset and then re-enumerates the device. (This is exactly the same thing that happens whenever a USB device is reset.) If the re-enumeration shows that the device now attached to that port has the same descriptors as before, including the Vendor and Product IDs, then the kernel continues to use the same device structure. In effect, the kernel treats the device as though it had merely been reset instead of unplugged.
The same thing happens if the host controller is in the expected state but a USB device was unplugged and then replugged, or if a USB device fails to carry out a normal resume.
If no device is now attached to the port, or if the descriptors are different from what the kernel remembers, then the treatment is what you would expect. The kernel destroys the old device structure and behaves as though the old device had been unplugged and a new device plugged in.
The end result is that the USB device remains available and usable. Filesystem mounts and memory mappings are unaffected, and the world is now a good and happy place.
Note that the "USB-persist" feature will be applied only to those devices for which it is enabled. You can enable the feature by doing (as root):
echo 1 >/sys/bus/usb/devices/.../power/persist
where the "..." should be filled in the with the device's ID. Disable the feature by writing 0 instead of 1. For hubs the feature is automatically and permanently enabled and the power/persist file doesn't even exist, so you only have to worry about setting it for devices where it really matters.
Is this the best solution? #
Perhaps not. Arguably, keeping track of mounted filesystems and memory mappings across device disconnects should be handled by a centralized Logical Volume Manager. Such a solution would allow you to plug in a USB flash device, create a persistent volume associated with it, unplug the flash device, plug it back in later, and still have the same persistent volume associated with the device. As such it would be more far-reaching than USB-persist.
On the other hand, writing a persistent volume manager would be a big job and using it would require significant input from the user. This solution is much quicker and easier -- and it exists now, a giant point in its favor!
Furthermore, the USB-persist feature applies to _all_ USB devices, not just mass-storage devices. It might turn out to be equally useful for other device types, such as network interfaces.
WARNING: USB-persist can be dangerous!! #
When recovering an interrupted power session the kernel does its best to make sure the USB device hasn't been changed; that is, the same device is still plugged into the port as before. But the checks aren't guaranteed to be 100% accurate.
If you replace one USB device with another of the same type (same manufacturer, same IDs, and so on) there's an excellent chance the kernel won't detect the change. The serial number string and other descriptors are compared with the kernel's stored values, but this might not help since manufacturers frequently omit serial numbers entirely in their devices.
Furthermore it's quite possible to leave a USB device exactly the same while changing its media. If you replace the flash memory card in a USB card reader while the system is asleep, the kernel will have no way to know you did it. The kernel will assume that nothing has happened and will continue to use the partition tables, inodes, and memory mappings for the old card.
If the kernel gets fooled in this way, it's almost certain to cause data corruption and to crash your system. You'll have no one to blame but yourself.
For those devices with avoid_reset_quirk attribute being set, persist maybe fail because they may morph after reset.
YOU HAVE BEEN WARNED! USE AT YOUR OWN RISK!
That having been said, most of the time there shouldn't be any trouble at all. The USB-persist feature can be extremely useful. Make the most of it.
Power Management for USB
Peios Kernel / Hardware and drivers / Driver development / USB
Author: Alan Stern <stern@rowland.harvard.edu>
Date: Last-updated: February 2014
What is Power Management? #
Power Management (PM) is the practice of saving energy by suspending parts of a computer system when they aren't being used. While a component is suspended it is in a nonfunctional low-power state; it might even be turned off completely. A suspended component can be resumed (returned to a functional full-power state) when the kernel needs to use it. (There also are forms of PM in which components are placed in a less functional but still usable state instead of being suspended; an example would be reducing the CPU's clock rate. This document will not discuss those other forms.)
When the parts being suspended include the CPU and most of the rest of the system, we speak of it as a "system suspend". When a particular device is turned off while the system as a whole remains running, we call it a "dynamic suspend" (also known as a "runtime suspend" or "selective suspend"). This document concentrates mostly on how dynamic PM is implemented in the USB subsystem, although system PM is covered to some extent (see Documentation/power/*.rst for more information about system PM).
System PM support is present only if the kernel was built with CONFIG_SUSPEND or CONFIG_HIBERNATION enabled. Dynamic PM support
for USB is present whenever the kernel was built with CONFIG_PM enabled.
[Historically, dynamic PM support for USB was present only if the kernel had been built with CONFIG_USB_SUSPEND enabled (which depended on CONFIG_PM_RUNTIME). Starting with the 3.10 kernel release, dynamic PM support for USB was present whenever the kernel was built with CONFIG_PM_RUNTIME enabled. The CONFIG_USB_SUSPEND option had been eliminated.]
What is Remote Wakeup? #
When a device has been suspended, it generally doesn't resume until the computer tells it to. Likewise, if the entire computer has been suspended, it generally doesn't resume until the user tells it to, say by pressing a power button or opening the cover.
However some devices have the capability of resuming by themselves, or asking the kernel to resume them, or even telling the entire computer to resume. This capability goes by several names such as "Wake On LAN"; we will refer to it generically as "remote wakeup". When a device is enabled for remote wakeup and it is suspended, it may resume itself (or send a request to be resumed) in response to some external event. Examples include a suspended keyboard resuming when a key is pressed, or a suspended USB hub resuming when a device is plugged in.
When is a USB device idle? #
A device is idle whenever the kernel thinks it's not busy doing anything important and thus is a candidate for being suspended. The exact definition depends on the device's driver; drivers are allowed to declare that a device isn't idle even when there's no actual communication taking place. (For example, a hub isn't considered idle unless all the devices plugged into that hub are already suspended.) In addition, a device isn't considered idle so long as a program keeps its usbfs file open, whether or not any I/O is going on.
If a USB device has no driver, its usbfs file isn't open, and it isn't being accessed through sysfs, then it definitely is idle.
Forms of dynamic PM #
Dynamic suspends occur when the kernel decides to suspend an idle device. This is called autosuspend for short. In general, a device won't be autosuspended unless it has been idle for some minimum period of time, the so-called idle-delay time.
Of course, nothing the kernel does on its own initiative should prevent the computer or its devices from working properly. If a device has been autosuspended and a program tries to use it, the kernel will automatically resume the device (autoresume). For the same reason, an autosuspended device will usually have remote wakeup enabled, if the device supports remote wakeup.
It is worth mentioning that many USB drivers don't support autosuspend. In fact, at the time of this writing (Linux 2.6.23) the only drivers which do support it are the hub driver, kaweth, asix, usblp, usblcd, and usb-skeleton (which doesn't count). If a non-supporting driver is bound to a device, the device won't be autosuspended. In effect, the kernel pretends the device is never idle.
We can categorize power management events in two broad classes: external and internal. External events are those triggered by some agent outside the USB stack: system suspend/resume (triggered by userspace), manual dynamic resume (also triggered by userspace), and remote wakeup (triggered by the device). Internal events are those triggered within the USB stack: autosuspend and autoresume. Note that all dynamic suspend events are internal; external agents are not allowed to issue dynamic suspends.
The user interface for dynamic PM #
The user interface for controlling dynamic PM is located in the power/ subdirectory of each USB device's sysfs directory, that is, in /sys/bus/usb/devices/.../power/ where "..." is the device's ID. The relevant attribute files are: wakeup, control, and autosuspend_delay_ms. (There may also be a file named level; this file was deprecated as of the 2.6.35 kernel and replaced by the control file. In 2.6.38 the autosuspend file will be deprecated and replaced by the autosuspend_delay_ms file. The only difference is that the newer file expresses the delay in milliseconds whereas the older file uses seconds. Confusingly, both files are present in 2.6.37 but only autosuspend works.)
power/wakeupThis file is empty if the device does not support remote wakeup. Otherwise the file contains either the word
enabledor the worddisabled, and you can write those words to the file. The setting determines whether or not remote wakeup will be enabled when the device is next suspended. (If the setting is changed while the device is suspended, the change won't take effect until the following suspend.)
power/controlThis file contains one of two words:
onorauto. You can write those words to the file to change the device's setting.
onmeans that the device should be resumed and autosuspend is not allowed. (Of course, system suspends are still allowed.)
autois the normal state in which the kernel is allowed to autosuspend and autoresume the device.(In kernels up to 2.6.32, you could also specify
suspend, meaning that the device should remain suspended and autoresume was not allowed. This setting is no longer supported.)
power/autosuspend_delay_msThis file contains an integer value, which is the number of milliseconds the device should remain idle before the kernel will autosuspend it (the idle-delay time). The default is 2000. 0 means to autosuspend as soon as the device becomes idle, and negative values mean never to autosuspend. You can write a number to the file to change the autosuspend idle-delay time.
Writing -1 to power/autosuspend_delay_ms and writing on to power/control do essentially the same thing -- they both prevent the device from being autosuspended. Yes, this is a redundancy in the API.
(In 2.6.21 writing 0 to power/autosuspend would prevent the device from being autosuspended; the behavior was changed in 2.6.22. The power/autosuspend attribute did not exist prior to 2.6.21, and the power/level attribute did not exist prior to 2.6.22. power/control was added in 2.6.34, and power/autosuspend_delay_ms was added in 2.6.37 but did not become functional until 2.6.38.)
Changing the default idle-delay time #
The default autosuspend idle-delay time (in seconds) is controlled by a module parameter in usbcore. You can specify the value when usbcore is loaded. For example, to set it to 5 seconds instead of 2 you would do:
modprobe usbcore autosuspend=5
Equivalently, you could add to a configuration file in /etc/modprobe.d a line saying:
options usbcore autosuspend=5
Some distributions load the usbcore module very early during the boot process, by means of a program or script running from an initramfs image. To alter the parameter value you would have to rebuild that image.
If usbcore is compiled into the kernel rather than built as a loadable module, you can add:
usbcore.autosuspend=5
to the kernel's boot command line.
Finally, the parameter value can be changed while the system is running. If you do:
echo 5 >/sys/module/usbcore/parameters/autosuspend
then each new USB device will have its autosuspend idle-delay initialized to 5. (The idle-delay values for already existing devices will not be affected.)
Setting the initial default idle-delay to -1 will prevent any autosuspend of any USB device. This has the benefit of allowing you then to enable autosuspend for selected devices.
Warnings #
The USB specification states that all USB devices must support power management. Nevertheless, the sad fact is that many devices do not support it very well. You can suspend them all right, but when you try to resume them they disconnect themselves from the USB bus or they stop working entirely. This seems to be especially prevalent among printers and scanners, but plenty of other types of device have the same deficiency.
For this reason, by default the kernel disables autosuspend (the power/control attribute is initialized to on) for all devices other than hubs. Hubs, at least, appear to be reasonably well-behaved in this regard.
(In 2.6.21 and 2.6.22 this wasn't the case. Autosuspend was enabled by default for almost all USB devices. A number of people experienced problems as a result.)
This means that non-hub devices won't be autosuspended unless the user or a program explicitly enables it. As of this writing there aren't any widespread programs which will do this; we hope that in the near future device managers such as HAL will take on this added responsibility. In the meantime you can always carry out the necessary operations by hand or add them to a udev script. You can also change the idle-delay time; 2 seconds is not the best choice for every device.
If a driver knows that its device has proper suspend/resume support, it can enable autosuspend all by itself. For example, the video driver for a laptop's webcam might do this (in recent kernels they do), since these devices are rarely used and so should normally be autosuspended.
Sometimes it turns out that even when a device does work okay with autosuspend there are still problems. For example, the usbhid driver, which manages keyboards and mice, has autosuspend support. Tests with a number of keyboards show that typing on a suspended keyboard, while causing the keyboard to do a remote wakeup all right, will nonetheless frequently result in lost keystrokes. Tests with mice show that some of them will issue a remote-wakeup request in response to button presses but not to motion, and some in response to neither.
The kernel will not prevent you from enabling autosuspend on devices that can't handle it. It is even possible in theory to damage a device by suspending it at the wrong time. (Highly unlikely, but possible.) Take care.
The driver interface for Power Management #
The requirements for a USB driver to support external power management are pretty modest; the driver need only define:
.suspend
.resume
.reset_resume
methods in its usb_driver structure, and the reset_resume method is optional. The methods' jobs are quite simple:
The
suspendmethod is called to warn the driver that the device is going to be suspended. If the driver returns a negative error code, the suspend will be aborted. Normally the driver will return 0, in which case it must cancel all outstanding URBs (usb_kill_urb()) and not submit any more.The
resumemethod is called to tell the driver that the device has been resumed and the driver can return to normal operation. URBs may once more be submitted.The
reset_resumemethod is called to tell the driver that the device has been resumed and it also has been reset. The driver should redo any necessary device initialization, since the device has probably lost most or all of its state (although the interfaces will be in the same altsettings as before the suspend).
If the device is disconnected or powered down while it is suspended, the disconnect method will be called instead of the resume or reset_resume method. This is also quite likely to happen when waking up from hibernation, as many systems do not maintain suspend current to the USB host controllers during hibernation. (It's possible to work around the hibernation-forces-disconnect problem by using the USB Persist facility.)
The reset_resume method is used by the USB Persist facility (see USB device persistence during system suspend) and it can also be used under certain circumstances when CONFIG_USB_PERSIST is not enabled. Currently, if a device is reset during a resume and the driver does not have a reset_resume method, the driver won't receive any notification about the resume. Later kernels will call the driver's disconnect method; 2.6.23 doesn't do this.
USB drivers are bound to interfaces, so their suspend and resume methods get called when the interfaces are suspended or resumed. In principle one might want to suspend some interfaces on a device (i.e., force the drivers for those interface to stop all activity) without suspending the other interfaces. The USB core doesn't allow this; all interfaces are suspended when the device itself is suspended and all interfaces are resumed when the device is resumed. It isn't possible to suspend or resume some but not all of a device's interfaces. The closest you can come is to unbind the interfaces' drivers.
The driver interface for autosuspend and autoresume #
To support autosuspend and autoresume, a driver should implement all three of the methods listed above. In addition, a driver indicates that it supports autosuspend by setting the .supports_autosuspend flag in its usb_driver structure. It is then responsible for informing the USB core whenever one of its interfaces becomes busy or idle. The driver does so by calling these six functions:
int usb_autopm_get_interface(struct usb_interface *intf);
void usb_autopm_put_interface(struct usb_interface *intf);
int usb_autopm_get_interface_async(struct usb_interface *intf);
void usb_autopm_put_interface_async(struct usb_interface *intf);
void usb_autopm_get_interface_no_resume(struct usb_interface *intf);
void usb_autopm_put_interface_no_suspend(struct usb_interface *intf);
The functions work by maintaining a usage counter in the usb_interface's embedded device structure. When the counter is > 0 then the interface is deemed to be busy, and the kernel will not autosuspend the interface's device. When the usage counter is = 0 then the interface is considered to be idle, and the kernel may autosuspend the device.
Drivers must be careful to balance their overall changes to the usage counter. Unbalanced "get"s will remain in effect when a driver is unbound from its interface, preventing the device from going into runtime suspend should the interface be bound to a driver again. On the other hand, drivers are allowed to achieve this balance by calling the usb_autopm_* functions even after their disconnect routine has returned -- say from within a work-queue routine -- provided they retain an active reference to the interface (via usb_get_intf and usb_put_intf).
Drivers using the async routines are responsible for their own synchronization and mutual exclusion.
usb_autopm_get_interface()increments the usage counter and does an autoresume if the device is suspended. If the autoresume fails, the counter is decremented back.
usb_autopm_put_interface()decrements the usage counter and attempts an autosuspend if the new value is = 0.
usb_autopm_get_interface_async()andusb_autopm_put_interface_async()do almost the same things as their non-async counterparts. The big difference is that they use a workqueue to do the resume or suspend part of their jobs. As a result they can be called in an atomic context, such as an URB's completion handler, but when they return the device will generally not yet be in the desired state.
usb_autopm_get_interface_no_resume()andusb_autopm_put_interface_no_suspend()merely increment or decrement the usage counter; they do not attempt to carry out an autoresume or an autosuspend. Hence they can be called in an atomic context.
The simplest usage pattern is that a driver calls usb_autopm_get_interface() in its open routine and usb_autopm_put_interface() in its close or release routine. But other patterns are possible.
The autosuspend attempts mentioned above will often fail for one reason or another. For example, the power/control attribute might be set to on, or another interface in the same device might not be idle. This is perfectly normal. If the reason for failure was that the device hasn't been idle for long enough, a timer is scheduled to carry out the operation automatically when the autosuspend idle-delay has expired.
Autoresume attempts also can fail, although failure would mean that the device is no longer present or operating properly. Unlike autosuspend, there's no idle-delay for an autoresume.
Other parts of the driver interface #
Drivers can enable autosuspend for their devices by calling:
usb_enable_autosuspend(struct usb_device *udev);
in their probe() routine, if they know that the device is capable of suspending and resuming correctly. This is exactly equivalent to writing auto to the device's power/control attribute. Likewise, drivers can disable autosuspend by calling:
usb_disable_autosuspend(struct usb_device *udev);
This is exactly the same as writing on to the power/control attribute.
Sometimes a driver needs to make sure that remote wakeup is enabled during autosuspend. For example, there's not much point autosuspending a keyboard if the user can't cause the keyboard to do a remote wakeup by typing on it. If the driver sets intf->needs_remote_wakeup to 1, the kernel won't autosuspend the device if remote wakeup isn't available. (If the device is already autosuspended, though, setting this flag won't cause the kernel to autoresume it. Normally a driver would set this flag in its probe method, at which time the device is guaranteed not to be autosuspended.)
If a driver does its I/O asynchronously in interrupt context, it should call usb_autopm_get_interface_async() before starting output and usb_autopm_put_interface_async() when the output queue drains. When it receives an input event, it should call:
usb_mark_last_busy(struct usb_device *udev);
in the event handler. This tells the PM core that the device was just busy and therefore the next autosuspend idle-delay expiration should be pushed back. Many of the usb_autopm_* routines also make this call, so drivers need to worry only when interrupt-driven input arrives.
Asynchronous operation is always subject to races. For example, a driver may call the usb_autopm_get_interface_async() routine at a time when the core has just finished deciding the device has been idle for long enough but not yet gotten around to calling the driver's suspend method. The suspend method must be responsible for synchronizing with the I/O request routine and the URB completion handler; it should cause autosuspends to fail with -EBUSY if the driver needs to use the device.
External suspend calls should never be allowed to fail in this way, only autosuspend calls. The driver can tell them apart by applying the PMSG_IS_AUTO() macro to the message argument to the suspend method; it will return True for internal PM events (autosuspend) and False for external PM events.
Mutual exclusion #
For external events -- but not necessarily for autosuspend or autoresume -- the device semaphore (udev->dev.sem) will be held when a suspend or resume method is called. This implies that external suspend/resume events are mutually exclusive with calls to probe, disconnect, pre_reset, and post_reset; the USB core guarantees that this is true of autosuspend/autoresume events as well.
If a driver wants to block all suspend/resume calls during some critical section, the best way is to lock the device and call usb_autopm_get_interface() (and do the reverse at the end of the critical section). Holding the device semaphore will block all external PM calls, and the usb_autopm_get_interface() will prevent any internal PM calls, even if it fails. (Exercise: Why?)
Interaction between dynamic PM and system PM #
Dynamic power management and system power management can interact in a couple of ways.
Firstly, a device may already be autosuspended when a system suspend occurs. Since system suspends are supposed to be as transparent as possible, the device should remain suspended following the system resume. But this theory may not work out well in practice; over time the kernel's behavior in this regard has changed. As of 2.6.37 the policy is to resume all devices during a system resume and let them handle their own runtime suspends afterward.
Secondly, a dynamic power-management event may occur as a system suspend is underway. The window for this is short, since system suspends don't take long (a few seconds usually), but it can happen. For example, a suspended device may send a remote-wakeup signal while the system is suspending. The remote wakeup may succeed, which would cause the system suspend to abort. If the remote wakeup doesn't succeed, it may still remain active and thus cause the system to resume as soon as the system suspend is complete. Or the remote wakeup may fail and get lost. Which outcome occurs depends on timing and on the hardware and firmware design.
xHCI hardware link PM #
xHCI host controller provides hardware link power management to usb2.0 (xHCI 1.0 feature) and usb3.0 devices which support link PM. By enabling hardware LPM, the host can automatically put the device into lower power state(L1 for usb2.0 devices, or U1/U2 for usb3.0 devices), which state device can enter and resume very quickly.
The user interface for controlling hardware LPM is located in the power/ subdirectory of each USB device's sysfs directory, that is, in /sys/bus/usb/devices/.../power/ where "..." is the device's ID. The relevant attribute files are usb2_hardware_lpm and usb3_hardware_lpm.
power/usb2_hardware_lpmWhen a USB2 device which support LPM is plugged to a xHCI host root hub which support software LPM, the host will run a software LPM test for it; if the device enters L1 state and resume successfully and the host supports USB2 hardware LPM, this file will show up and driver will enable hardware LPM for the device. You can write y/Y/1 or n/N/0 to the file to enable/disable USB2 hardware LPM manually. This is for test purpose mainly.
power/usb3_hardware_lpm_u1power/usb3_hardware_lpm_u2When a USB 3.0 lpm-capable device is plugged in to a xHCI host which supports link PM, it will check if U1 and U2 exit latencies have been set in the BOS descriptor; if the check is passed and the host supports USB3 hardware LPM, USB3 hardware LPM will be enabled for the device and these files will be created. The files hold a string value (enable or disable) indicating whether or not USB3 hardware LPM U1 or U2 is enabled for the device.
USB Port Power Control #
In addition to suspending endpoint devices and enabling hardware controlled link power management, the USB subsystem also has the capability to disable power to ports under some conditions. Power is controlled through Set/ClearPortFeature(PORT_POWER) requests to a hub. In the case of a root or platform-internal hub the host controller driver translates PORT_POWER requests into platform firmware (ACPI) method calls to set the port power state. For more background see the Linux Plumbers Conference 2012 slides 1 and video 2:
Upon receiving a ClearPortFeature(PORT_POWER) request a USB port is logically off, and may trigger the actual loss of VBUS to the port 3. VBUS may be maintained in the case where a hub gangs multiple ports into a shared power well causing power to remain until all ports in the gang are turned off. VBUS may also be maintained by hub ports configured for a charging application. In any event a logically off port will lose connection with its device, not respond to hotplug events, and not respond to remote wakeup events.
As far as the effect on the device itself it is similar to what a device goes through during system suspend, i.e. the power session is lost. Any USB device or driver that misbehaves with system suspend will be similarly affected by a port power cycle event. For this reason the implementation shares the same device recovery path (and honors the same quirks) as the system resume path for the hub.
[1] http://dl.dropbox.com/u/96820575/sarah-sharp-lpt-port-power-off2-mini.pdf
[2] http://linuxplumbers.ubicast.tv/videos/usb-port-power-off-kerneluserspace-api/
[3] USB 3.1 Section 10.12
wakeup note: if a device is configured to send wakeup events the port power control implementation will block poweroff attempts on that port.
User Interface for Port Power Control #
The port power control mechanism uses the PM runtime system. Poweroff is requested by clearing the power/pm_qos_no_power_off flag of the port device (defaults to 1). If the port is disconnected it will immediately receive a ClearPortFeature(PORT_POWER) request. Otherwise, it will honor the pm runtime rules and require the attached child device and all descendants to be suspended. This mechanism is dependent on the hub advertising port power switching in its hub descriptor (wHubCharacteristics logical power switching mode field).
Note, some interface devices/drivers do not support autosuspend. Userspace may need to unbind the interface drivers before the usb_device will suspend. An unbound interface device is suspended by default. When unbinding, be careful to unbind interface drivers, not the driver of the parent usb device. Also, leave hub interface drivers bound. If the driver for the usb device (not interface) is unbound the kernel is no longer able to resume the device. If a hub interface driver is unbound, control of its child ports is lost and all attached child-devices will disconnect. A good rule of thumb is that if the 'driver/module' link for a device points to /sys/module/usbcore then unbinding it will interfere with port power control.
Example of the relevant files for port power control. Note, in this example these files are relative to a usb hub device (prefix):
prefix=/sys/devices/pci0000:00/0000:00:14.0/usb3/3-1
attached child device +
hub port device + |
hub interface device + | |
v v v
$prefix/3-1:1.0/3-1-port1/device
$prefix/3-1:1.0/3-1-port1/power/pm_qos_no_power_off
$prefix/3-1:1.0/3-1-port1/device/power/control
$prefix/3-1:1.0/3-1-port1/device/3-1.1:<intf0>/driver/unbind
$prefix/3-1:1.0/3-1-port1/device/3-1.1:<intf1>/driver/unbind
...
$prefix/3-1:1.0/3-1-port1/device/3-1.1:<intfN>/driver/unbind
In addition to these files some ports may have a 'peer' link to a port on another hub. The expectation is that all superspeed ports have a hi-speed peer:
$prefix/3-1:1.0/3-1-port1/peer -> ../../../../usb2/2-1/2-1:1.0/2-1-port1
../../../../usb2/2-1/2-1:1.0/2-1-port1/peer -> ../../../../usb3/3-1/3-1:1.0/3-1-port1
Distinct from 'companion ports', or 'ehci/xhci shared switchover ports' peer ports are simply the hi-speed and superspeed interface pins that are combined into a single usb3 connector. Peer ports share the same ancestor XHCI device.
While a superspeed port is powered off a device may downgrade its connection and attempt to connect to the hi-speed pins. The implementation takes steps to prevent this:
-
Port suspend is sequenced to guarantee that hi-speed ports are powered-off before their superspeed peer is permitted to power-off. The implication is that the setting
pm_qos_no_power_offto zero on a superspeed port may not cause the port to power-off until its highspeed peer has gone to its runtime suspend state. Userspace must take care to order the suspensions if it wants to guarantee that a superspeed port will power-off. -
Port resume is sequenced to force a superspeed port to power-on prior to its highspeed peer.
-
Port resume always triggers an attached child device to resume. After a power session is lost the device may have been removed, or need reset. Resuming the child device when the parent port regains power resolves those states and clamps the maximum port power cycle frequency at the rate the child device can suspend (autosuspend-delay) and resume (reset-resume latency).
Sysfs files relevant for port power control:
<hubdev-portX>/power/pm_qos_no_power_off:This writable flag controls the state of an idle port. Once all children and descendants have suspended the port may suspend/poweroff provided that pm_qos_no_power_off is '0'. If pm_qos_no_power_off is '1' the port will remain active/powered regardless of the stats of descendants. Defaults to 1.
<hubdev-portX>/power/runtime_status:This file reflects whether the port is 'active' (power is on) or 'suspended' (logically off). There is no indication to userspace whether VBUS is still supplied.
<hubdev-portX>/connect_type:An advisory read-only flag to userspace indicating the location and connection type of the port. It returns one of four values 'hotplug', 'hardwired', 'not used', and 'unknown'. All values, besides unknown, are set by platform firmware.
hotplugindicates an externally connectable/visible port on the platform. Typically userspace would choose to keep such a port powered to handle new device connection events.
hardwiredrefers to a port that is not visible but connectable. Examples are internal ports for USB bluetooth that can be disconnected via an external switch or a port with a hardwired USB camera. It is expected to be safe to allow these ports to suspend provided pm_qos_no_power_off is coordinated with any switch that gates connections. Userspace must arrange for the device to be connected prior to the port powering off, or to activate the port prior to enabling connection via a switch.
not usedrefers to an internal port that is expected to never have a device connected to it. These may be empty internal ports, or ports that are not physically exposed on a platform. Considered safe to be powered-off at all times.
unknownmeans platform firmware does not provide information for this port. Most commonly refers to external hub ports which should be considered 'hotplug' for policy decisions.Once a child device is attached additional constraints are applied before the port is allowed to poweroff.
<child>/power/control:Must be
auto, and the port will not power down until<child>/power/runtime_statusreflects the 'suspended' state. Default value is controlled by child device driver.
<child>/power/persist:This defaults to
1for most devices and indicates if kernel can persist the device's configuration across a power session loss (suspend / port-power event). When this value is0(quirky devices), port poweroff is disabled.
<child>/driver/unbind:Wakeup capable devices will block port poweroff. At this time the only mechanism to clear the usb-internal wakeup-capability for an interface device is to unbind its driver.
Summary of poweroff pre-requisite settings relative to a port device:
echo 0 > power/pm_qos_no_power_off
echo 0 > peer/power/pm_qos_no_power_off # if it exists
echo auto > power/control # this is the default value
echo auto > <child>/power/control
echo 1 > <child>/power/persist # this is the default value
Suggested Userspace Port Power Policy #
As noted above userspace needs to be careful and deliberate about what ports are enabled for poweroff.
The default configuration is that all ports start with power/pm_qos_no_power_off set to 1 causing ports to always remain active.
Given confidence in the platform firmware's description of the ports (ACPI _PLD record for a port populates 'connect_type') userspace can clear pm_qos_no_power_off for all 'not used' ports. The same can be done for 'hardwired' ports provided poweroff is coordinated with any connection switch for the port.
A more aggressive userspace policy is to enable USB port power off for all ports (set <hubdev-portX>/power/pm_qos_no_power_off to 0) when some external factor indicates the user has stopped interacting with the system. For example, a distro may want to enable power off all USB ports when the screen blanks, and re-power them when the screen becomes active. Smart phones and tablets may want to power off USB ports when the user pushes the power button.
USB Type-C connector class
Peios Kernel / Hardware and drivers / Driver development / USB
Introduction #
The typec class is meant for describing the USB Type-C ports in a system to the user space in unified fashion. The class is designed to provide nothing else except the user space interface implementation in hope that it can be utilized on as many platforms as possible.
The platforms are expected to register every USB Type-C port they have with the class. In a normal case the registration will be done by a USB Type-C or PD PHY driver, but it may be a driver for firmware interface such as UCSI, driver for USB PD controller or even driver for Thunderbolt3 controller. This document considers the component registering the USB Type-C ports with the class as "port driver".
On top of showing the capabilities, the class also offer user space control over the roles and alternate modes of ports, partners and cable plugs when the port driver is capable of supporting those features.
The class provides an API for the port drivers described in this document. The attributes are described in Documentation/ABI/testing/sysfs-class-typec.
User space interface #
Every port will be presented as its own device under /sys/class/typec/. The first port will be named "port0", the second "port1" and so on.
When connected, the partner will be presented also as its own device under /sys/class/typec/. The parent of the partner device will always be the port it is attached to. The partner attached to port "port0" will be named "port0-partner". Full path to the device would be /sys/class/typec/port0/port0-partner/.
The cable and the two plugs on it may also be optionally presented as their own devices under /sys/class/typec/. The cable attached to the port "port0" port will be named port0-cable and the plug on the SOP Prime end (see USB Power Delivery Specification ch. 2.4) will be named "port0-plug0" and on the SOP Double Prime end "port0-plug1". The parent of a cable will always be the port, and the parent of the cable plugs will always be the cable.
If the port, partner or cable plug supports Alternate Modes, every supported Alternate Mode SVID will have their own device describing them. Note that the Alternate Mode devices will not be attached to the typec class. The parent of an alternate mode will be the device that supports it, so for example an alternate mode of port0-partner will be presented under /sys/class/typec/port0-partner/. Every mode that is supported will have its own group under the Alternate Mode device named "mode<index>", for example /sys/class/typec/port0/<alternate mode>/mode1/. The requests for entering/exiting a mode can be done with "active" attribute file in that group.
Driver API #
Registering the ports #
The port drivers will describe every Type-C port they control with struct typec_capability data structure, and register them with the following API:
typec_register_port() #
struct typec_port * Register a USB Type-C Port
Parameters
struct device *parent: Parent deviceconst struct typec_capability *cap: Description of the port
Description
Registers a device for USB Type-C Port described in cap.
Returns handle to the port on success or ERR_PTR on failure.
typec_unregister_port() #
void Unregister a USB Type-C Port
Parameters
struct typec_port *port: The port to be unregistered
Description
Unregister device created with typec_register_port().
When registering the ports, the prefer_role member in struct typec_capability deserves special notice. If the port that is being registered does not have initial role preference, which means the port does not execute Try.SNK or Try.SRC by default, the member must have value TYPEC_NO_PREFERRED_ROLE. Otherwise if the port executes Try.SNK by default, the member must have value TYPEC_DEVICE, and with Try.SRC the value must be TYPEC_HOST.
Registering Partners #
After successful connection of a partner, the port driver needs to register the partner with the class. Details about the partner need to be described in struct typec_partner_desc. The class copies the details of the partner during registration. The class offers the following API for registering/unregistering partners.
typec_register_partner() #
struct typec_partner * Register a USB Type-C Partner
Parameters
struct typec_port *port: The USB Type-C Port the partner is connected tostruct typec_partner_desc *desc: Description of the partner
Description
Registers a device for USB Type-C Partner described in desc.
Returns handle to the partner on success or ERR_PTR on failure.
typec_unregister_partner() #
void Unregister a USB Type-C Partner
Parameters
struct typec_partner *partner: The partner to be unregistered
Description
Unregister device created with typec_register_partner().
The class will provide a handle to struct typec_partner if the registration was successful, or NULL.
If the partner is USB Power Delivery capable, and the port driver is able to show the result of Discover Identity command, the partner descriptor structure should include handle to struct usb_pd_identity instance. The class will then create a sysfs directory for the identity under the partner device. The result of Discover Identity command can then be reported with the following API:
typec_partner_set_identity() #
int Report result from Discover Identity command
Parameters
struct typec_partner *partner: The partner updated identity values
Description
This routine is used to report that the result of Discover Identity USB power delivery command has become available.
Registering Cables #
After successful connection of a cable that supports USB Power Delivery Structured VDM "Discover Identity", the port driver needs to register the cable and one or two plugs, depending if there is CC Double Prime controller present in the cable or not. So a cable capable of SOP Prime communication, but not SOP Double Prime communication, should only have one plug registered. For more information about SOP communication, please read chapter about it from the latest USB Power Delivery specification.
The plugs are represented as their own devices. The cable is registered first, followed by registration of the cable plugs. The cable will be the parent device for the plugs. Details about the cable need to be described in struct typec_cable_desc and about a plug in struct typec_plug_desc. The class copies the details during registration. The class offers the following API for registering/unregistering cables and their plugs:
typec_register_plug() #
struct typec_plug * Register a USB Type-C Cable Plug
Parameters
struct typec_cable *cable: USB Type-C Cable with the plugstruct typec_plug_desc *desc: Description of the cable plug
Description
Registers a device for USB Type-C Cable Plug described in desc. A USB Type-C Cable Plug represents a plug with electronics in it that can response to USB Power Delivery SOP Prime or SOP Double Prime packages.
Returns handle to the cable plug on success or ERR_PTR on failure.
typec_unregister_plug() #
void Unregister a USB Type-C Cable Plug
Parameters
struct typec_plug *plug: The cable plug to be unregistered
Description
Unregister device created with typec_register_plug().
typec_register_cable() #
struct typec_cable * Register a USB Type-C Cable
Parameters
struct typec_port *port: The USB Type-C Port the cable is connected tostruct typec_cable_desc *desc: Description of the cable
Description
Registers a device for USB Type-C Cable described in desc. The cable will be parent for the optional cable plug devises.
Returns handle to the cable on success or ERR_PTR on failure.
typec_unregister_cable() #
void Unregister a USB Type-C Cable
Parameters
struct typec_cable *cable: The cable to be unregistered
Description
Unregister device created with typec_register_cable().
The class will provide a handle to struct typec_cable and struct typec_plug if the registration is successful, or NULL if it isn't.
If the cable is USB Power Delivery capable, and the port driver is able to show the result of Discover Identity command, the cable descriptor structure should include handle to struct usb_pd_identity instance. The class will then create a sysfs directory for the identity under the cable device. The result of Discover Identity command can then be reported with the following API:
typec_cable_set_identity() #
int Report result from Discover Identity command
Parameters
struct typec_cable *cable: The cable updated identity values
Description
This routine is used to report that the result of Discover Identity USB power delivery command has become available.
Notifications #
When the partner has executed a role change, or when the default roles change during connection of a partner or cable, the port driver must use the following APIs to report it to the class:
typec_set_data_role() #
void Report data role change
Parameters
struct typec_port *port: The USB Type-C Port where the role was changedenum typec_data_role role: The new data role
Description
This routine is used by the port drivers to report data role changes.
typec_set_pwr_role() #
void Report power role change
Parameters
struct typec_port *port: The USB Type-C Port where the role was changedenum typec_role role: The new data role
Description
This routine is used by the port drivers to report power role changes.
typec_set_vconn_role() #
void Report VCONN source change
Parameters
struct typec_port *port: The USB Type-C Port which VCONN role changedenum typec_role role: Source when port is sourcing VCONN, or Sink when it's not
Description
This routine is used by the port drivers to report if the VCONN source is changes.
typec_set_pwr_opmode() #
void Report changed power operation mode
Parameters
struct typec_port *port: The USB Type-C Port where the mode was changedenum typec_pwr_opmode opmode: New power operation mode
Description
This routine is used by the port drivers to report changed power operation mode in port. The modes are USB (default), 1.5A, 3.0A as defined in USB Type-C specification, and "USB Power Delivery" when the power levels are negotiated with methods defined in USB Power Delivery specification.
Alternate Modes #
USB Type-C ports, partners and cable plugs may support Alternate Modes. Each Alternate Mode will have identifier called SVID, which is either a Standard ID given by USB-IF or vendor ID, and each supported SVID can have 1 - 6 modes. The class provides struct typec_mode_desc for describing individual mode of a SVID, and struct typec_altmode_desc which is a container for all the supported modes.
Ports that support Alternate Modes need to register each SVID they support with the following API:
typec_port_register_altmode() #
struct typec_altmode * Register USB Type-C Port Alternate Mode
Parameters
struct typec_port *port: USB Type-C Port that supports the alternate modeconst struct typec_altmode_desc *desc: Description of the alternate mode
Description
This routine is used to register an alternate mode that port is capable of supporting.
Returns handle to the alternate mode on success or ERR_PTR on failure.
If a partner or cable plug provides a list of SVIDs as response to USB Power Delivery Structured VDM Discover SVIDs message, each SVID needs to be registered.
API for the partners:
typec_partner_register_altmode() #
struct typec_altmode * Register USB Type-C Partner Alternate Mode
Parameters
struct typec_partner *partner: USB Type-C Partner that supports the alternate modeconst struct typec_altmode_desc *desc: Description of the alternate mode
Description
This routine is used to register each alternate mode individually that partner has listed in response to Discover SVIDs command. The modes for a SVID listed in response to Discover Modes command need to be listed in an array in desc.
Returns handle to the alternate mode on success or ERR_PTR on failure.
API for the Cable Plugs:
typec_plug_register_altmode() #
struct typec_altmode * Register USB Type-C Cable Plug Alternate Mode
Parameters
struct typec_plug *plug: USB Type-C Cable Plug that supports the alternate modeconst struct typec_altmode_desc *desc: Description of the alternate mode
Description
This routine is used to register each alternate mode individually that plug has listed in response to Discover SVIDs command. The modes for a SVID that the plug lists in response to Discover Modes command need to be listed in an array in desc.
Returns handle to the alternate mode on success or ERR_PTR on failure.
So ports, partners and cable plugs will register the alternate modes with their own functions, but the registration will always return a handle to struct typec_altmode on success, or NULL. The unregistration will happen with the same function:
typec_unregister_altmode() #
void Unregister Alternate Mode
Parameters
struct typec_altmode *adev: The alternate mode to be unregistered
Description
Unregister device created with typec_partner_register_altmode(),
typec_plug_register_altmode() or typec_port_register_altmode().
If a partner or cable plug enters or exits a mode, the port driver needs to notify the class with the following API:
typec_altmode_update_active() #
void Report Enter/Exit mode
Parameters
struct typec_altmode *adev: Handle to the alternate modebool active: True when the mode has been entered
Description
If a partner or cable plug executes Enter/Exit Mode command successfully, the drivers use this routine to report the updated state of the mode.
Multiplexer/DeMultiplexer Switches #
USB Type-C connectors may have one or more mux/demux switches behind them. Since the plugs can be inserted right-side-up or upside-down, a switch is needed to route the correct data pairs from the connector to the USB controllers. If Alternate or Accessory Modes are supported, another switch is needed that can route the pins on the connector to some other component besides USB. USB Type-C Connector Class supplies an API for registering those switches.
typec_switch_register() #
struct typec_switch_dev * Register USB Type-C orientation switch
Parameters
struct device *parent: Parent deviceconst struct typec_switch_desc *desc: Orientation switch description
Description
This function registers a switch that can be used for routing the correct data pairs depending on the cable plug orientation from the USB Type-C connector to the USB controllers. USB Type-C plugs can be inserted right-side-up or upside-down.
typec_switch_unregister() #
void Unregister USB Type-C orientation switch
Parameters
struct typec_switch_dev *sw_dev: USB Type-C orientation switch
Description
Unregister switch that was registered with typec_switch_register().
typec_mux_register() #
struct typec_mux_dev * Register Multiplexer routing USB Type-C pins
Parameters
struct device *parent: Parent deviceconst struct typec_mux_desc *desc: Multiplexer description
Description
USB Type-C connectors can be used for alternate modes of operation besides USB when Accessory/Alternate Modes are supported. With some of those modes, the pins on the connector need to be reconfigured. This function registers multiplexer switches routing the pins on the connector.
typec_mux_unregister() #
void Unregister Multiplexer Switch
Parameters
struct typec_mux_dev *mux_dev: USB Type-C Connector Multiplexer/DeMultiplexer
Description
Unregister mux that was registered with typec_mux_register().
In most cases the same physical mux will handle both the orientation and mode. However, as the port drivers will be responsible for the orientation, and the alternate mode drivers for the mode, the two are always separated into their own logical components: "mux" for the mode and "switch" for the orientation.
When a port is registered, USB Type-C Connector Class requests both the mux and the switch for the port. The drivers can then use the following API for controlling them:
typec_set_orientation() #
int Set USB Type-C cable plug orientation
Parameters
struct typec_port *port: USB Type-C Portenum typec_orientation orientation: USB Type-C cable plug orientation
Description
Set cable plug orientation for port.
typec_set_mode() #
int Set mode of operation for USB Type-C connector
Parameters
struct typec_port *port: USB Type-C connectorint mode: Accessory Mode, USB Operation or Safe State
Description
Configure port for Accessory Mode mode. This function will configure the muxes needed for mode.
If the connector is dual-role capable, there may also be a switch for the data role. USB Type-C Connector Class does not supply separate API for them. The port drivers can use USB Role Class API with those.
Illustration of the muxes behind a connector that supports an alternate mode:
------------------------
| Connector |
------------------------
| |
------------------------
\ Orientation /
--------------------
|
--------------------
/ Mode \
------------------------
/ \
------------------------ --------------------
| Alt Mode | / USB Role \
------------------------ ------------------------
/ \
------------------------ ------------------------
| USB Host | | USB Device |
------------------------ ------------------------
API for USB Type-C Alternate Mode drivers
Peios Kernel / Hardware and drivers / Driver development / USB
Introduction #
Alternate modes require communication with the partner using Vendor Defined Messages (VDM) as defined in USB Type-C and USB Power Delivery Specifications. The communication is SVID (Standard or Vendor ID) specific, i.e. specific for every alternate mode, so every alternate mode will need a custom driver.
USB Type-C bus allows binding a driver to the discovered partner alternate modes by using the SVID and the mode number.
USB Type-C Connector Class provides a device for every alternate mode a port supports, and separate device for every alternate mode the partner supports. The drivers for the alternate modes are bound to the partner alternate mode devices, and the port alternate mode devices must be handled by the port drivers.
When a new partner alternate mode device is registered, it is linked to the alternate mode device of the port that the partner is attached to, that has matching SVID and mode. Communication between the port driver and alternate mode driver will happen using the same API.
The port alternate mode devices are used as a proxy between the partner and the alternate mode drivers, so the port drivers are only expected to pass the SVID specific commands from the alternate mode drivers to the partner, and from the partners to the alternate mode drivers. No direct SVID specific communication is needed from the port drivers, but the port drivers need to provide the operation callbacks for the port alternate mode devices, just like the alternate mode drivers need to provide them for the partner alternate mode devices.
Usage: #
General #
By default, the alternate mode drivers are responsible for entering the mode. It is also possible to leave the decision about entering the mode to the user space (See Documentation/ABI/testing/sysfs-class-typec). Port drivers should not enter any modes on their own.
->vdm is the most important callback in the operation callbacks vector. It will be used to deliver all the SVID specific commands from the partner to the alternate mode driver, and vice versa in case of port drivers. The drivers send the SVID specific commands to each other using typec_altmode_vdm().
If the communication with the partner using the SVID specific commands results in need to reconfigure the pins on the connector, the alternate mode driver needs to notify the bus using typec_altmode_notify(). The driver passes the negotiated SVID specific pin configuration value to the function as parameter. The bus driver will then configure the mux behind the connector using that value as the state value for the mux.
NOTE: The SVID specific pin configuration values must always start from TYPEC_STATE_MODAL. USB Type-C specification defines two default states for the connector: TYPEC_STATE_USB and TYPEC_STATE_SAFE. These values are reserved by the bus as the first possible values for the state. When the alternate mode is entered, the bus will put the connector into TYPEC_STATE_SAFE before sending Enter or Exit Mode command as defined in USB Type-C Specification, and also put the connector back to TYPEC_STATE_USB after the mode has been exited.
An example of working definitions for SVID specific pin configurations would look like this:
enum {
ALTMODEX_CONF_A = TYPEC_STATE_MODAL,
ALTMODEX_CONF_B,
...
};
Helper macro TYPEC_MODAL_STATE() can also be used:
#define ALTMODEX_CONF_A = TYPEC_MODAL_STATE(0);
#define ALTMODEX_CONF_B = TYPEC_MODAL_STATE(1);
Cable plug alternate modes #
The alternate mode drivers are not bound to cable plug alternate mode devices, only to the partner alternate mode devices. If the alternate mode supports, or requires, a cable that responds to SOP Prime, and optionally SOP Double Prime messages, the driver for that alternate mode must request handle to the cable plug alternate modes using typec_altmode_get_plug(), and take over their control.
Driver API #
Alternate mode structs #
struct typec_altmode_ops #
Alternate mode specific operations vector
Definition
;
Members
enter: Operations to be executed with Enter Mode Commandexit: Operations to be executed with Exit Mode Commandattention: Callback for Attention Commandvdm: Callback for SVID specific commandsnotify: Communication channel for platform and the alternate modeactivate: User callback for Enter/Exit Mode
struct typec_altmode_driver #
USB Type-C alternate mode device driver
Definition
;
Members
id_table: Null terminated array of SVIDsprobe: Callback for device bindingremove: Callback for device unbindingdriver: Device driver model driver
Description
These drivers will be bind to the partner alternate mode devices. They will handle all SVID specific communication.
Alternate mode driver registering/unregistering #
typec_altmode_register_driver() #
registers a USB Type-C alternate mode device driver
Parameters
drv: pointer to struct typec_altmode_driver
Description
These drivers will be bind to the partner alternate mode devices. They will handle all SVID specific communication.
typec_altmode_unregister_driver() #
void unregisters a USB Type-C alternate mode device driver
Parameters
struct typec_altmode_driver *drv: pointer to struct typec_altmode_driver
Description
These drivers will be bind to the partner alternate mode devices. They will handle all SVID specific communication.
Alternate mode driver operations #
typec_altmode_notify() #
int Communication between the OS and alternate mode driver
Parameters
struct typec_altmode *adev: Handle to the alternate modeunsigned long conf: Alternate mode specific configuration valuevoid *data: Alternate mode specific data
Description
The primary purpose for this function is to allow the alternate mode drivers to tell which pin configuration has been negotiated with the partner. That information will then be used for example to configure the muxes. Communication to the other direction is also possible, and low level device drivers can also send notifications to the alternate mode drivers. The actual communication will be specific for every SVID.
typec_altmode_enter() #
int Enter Mode
Parameters
struct typec_altmode *adev: The alternate modeu32 *vdo: VDO for the Enter Mode command
Description
The alternate mode drivers use this function to enter mode. The port drivers use this to inform the alternate mode drivers that the partner has initiated Enter Mode command. If the alternate mode does not require VDO, vdo must be NULL.
typec_altmode_exit() #
int Exit Mode
Parameters
struct typec_altmode *adev: The alternate mode
Description
The partner of adev has initiated Exit Mode command.
typec_altmode_attention() #
int Attention command
Parameters
struct typec_altmode *adev: The alternate modeu32 vdo: VDO for the Attention command
Description
Notifies the partner of adev about Attention command.
typec_altmode_vdm() #
int Send Vendor Defined Messages (VDM) to the partner
Parameters
struct typec_altmode *adev: Alternate mode handleconst u32 header: VDM Headerconst u32 *vdo: Array of Vendor Defined Data Objectsint count: Number of Data Objects
Description
The alternate mode drivers use this function for SVID specific communication with the partner. The port drivers use it to deliver the Structured VDMs received from the partners to the alternate mode drivers.
API for the port drivers #
typec_match_altmode() #
struct typec_altmode * Match SVID and mode to an array of alternate modes
Parameters
struct typec_altmode **altmodes: Array of alternate modessize_t n: Number of elements in the array, or -1 for NULL terminated arraysu16 svid: Standard or Vendor ID to match withu8 mode: Mode to match with
Description
Return pointer to an alternate mode with SVID matching svid, or NULL when no match is found.
Cable Plug operations #
typec_altmode_get_plug() #
struct typec_altmode * Find cable plug alternate mode
Parameters
struct typec_altmode *adev: Handle to partner alternate modeenum typec_plug_index index: Cable plug index
Description
Increment reference count for cable plug alternate mode device. Returns handle to the cable plug alternate mode, or NULL if none is found.
typec_altmode_put_plug() #
void Decrement cable plug alternate mode reference count
Parameters
struct typec_altmode *plug: Handle to the cable plug alternate mode
The Linux-USB Host Side API
Peios Kernel / Hardware and drivers / Driver development / USB
Peios: Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0,
setcapand Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See Peios kernel behaviour for the mapping and exceptions.
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) buses 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 buses.
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.
usb_ep_type_string() #
const char * 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 byusb_endpoint_type(), the string 'unknown' will be returned.
usb_otg_state_string() #
const char * returns human readable name of OTG state.
Parameters
enum usb_otg_state state: the OTG state to return the human readable name of. If it's not any of the states defined in usb_otg_state enum, 'UNDEFINED' will be returned.
usb_speed_string() #
const char * 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.
usb_get_maximum_speed() #
enum usb_device_speed 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.
usb_get_maximum_ssp_rate() #
enum usb_ssp_rate 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.
usb_state_string() #
const char * 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.
usb_get_role_switch_default_mode() #
enum usb_dr_mode 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.
usb_decode_interval() #
unsigned int Decode bInterval into the time expressed in 1us unit
Parameters
const struct usb_endpoint_descriptor *epd: The descriptor of the endpointenum 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.
of_usb_get_dr_mode_by_phy() #
enum usb_dr_mode 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_nodeint 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.
of_usb_host_tpl_support() #
bool 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
of_usb_update_otg_caps() #
int to update usb otg capabilities according to the passed properties in DT.
Parameters
struct device_node *np: Pointer to the given device_nodestruct usb_otg_caps *otg_caps: Pointer to the target usb_otg_caps to be set
Description
The function updates the otg capabilities
usb_of_get_companion_dev() #
struct device * 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.
struct usb_host_endpoint #
host-side endpoint descriptor and queue
Definition
;
Members
desc: descriptor for this endpoint, wMaxPacketSize in native byteorderss_ep_comp: SuperSpeed companion descriptor for this endpointssp_isoc_ep_comp: SuperSpeedPlus isoc companion descriptor for this endpointeusb2_isoc_ep_comp: eUSB2 isoc companion descriptor for this endpointurb_list: urbs queued to this endpoint; maintained by usbcorehcpriv: for use by HCD; typically holds hardware dma queue head (QH) with one or more transfer descriptors (TDs) per urb; must be preserved by core while BW is allocated for the endpointep_dev: ep_device for sysfs infoextra: descriptors following this endpoint in the configurationextralen: how many bytes of "extra" are validenabled: URBs may be submitted to this endpointstreams: number of USB-3 streams allocated on the endpoint
Description
USB requests are always queued to a given endpoint, identified by a descriptor within an active interface in a given USB configuration.
struct usb_interface #
what usb device drivers talk to
Definition
;
Members
altsetting: array of interface structures, one for each alternate setting that may be selected. Each one includes a set of endpoint configurations. They will be in no particular order.cur_altsetting: the current altsetting.num_altsetting: number of altsettings defined.intf_assoc: interface association descriptorminor: the minor number assigned to this interface, if this interface is bound to a driver that uses the USB major number. If this interface does not use the USB major, this field should be unused. The driver should set this value in theprobe()function of the driver, after it has been assigned a minor number from the USB core by callingusb_register_dev().condition: binding state of the interface: not bound, binding (inprobe()), bound to a driver, or unbinding (indisconnect())sysfs_files_created: sysfs attributes existep_devs_created: endpoint child pseudo-devices existunregistering: flag set when the interface is being unregisteredneeds_remote_wakeup: flag set when the driver requires remote-wakeup capability during autosuspend.needs_altsetting0: flag set when a set-interface request for altsetting 0 has been deferred.needs_binding: flag set when the driver should be re-probed or unbound following a reset or suspend operation it doesn't support.resetting_device: USB core reset the device, so use alt setting 0 as current; needs bandwidth alloc after reset.authorized: This allows to (de)authorize individual interfaces instead a whole device in contrast to the device authorization.wireless_status: if the USB device uses a receiver/emitter combo, whether the emitter is connected.wireless_status_work: Used for scheduling wireless status changes from atomic context.dev: driver model's view of this deviceusb_dev: if an interface is bound to the USB major, this will point to the sysfs representation for that device.reset_ws: Used for scheduling resets from atomic context.
Description
USB device drivers attach to interfaces on a physical device. Each interface encapsulates a single high level function, such as feeding an audio stream to a speaker or reporting a change in a volume control. Many USB devices only have one interface. The protocol used to talk to an interface's endpoints can be defined in a usb "class" specification, or by a product's vendor. The (default) control endpoint is part of every interface, but is never listed among the interface's descriptors.
The driver that is bound to the interface can use standard driver model
calls such as dev_get_drvdata() on the dev member of this structure.
Each interface may have alternate settings. The initial configuration
of a device sets altsetting 0, but the device driver can change
that setting using usb_set_interface(). Alternate settings are often
used to control the use of periodic endpoints, such as by having
different endpoints use different amounts of reserved USB bandwidth.
All standards-conformant USB devices that use isochronous endpoints
will use them in non-default settings.
The USB specification says that alternate setting numbers must run from
0 to one less than the total number of alternate settings. But some
devices manage to mess this up, and the structures aren't necessarily
stored in numerical order anyhow. Use usb_altnum_to_altsetting() to
look up an alternate setting in the altsetting array based on its number.
usb_set_intfdata() #
void associate driver-specific data with an interface
Parameters
struct usb_interface *intf: USB interfacevoid *data: driver data
Description
Drivers can use this function in their probe() callbacks to associate
driver-specific data with an interface.
Note that there is generally no need to clear the driver-data pointer even if some drivers do so for historical or implementation-specific reasons.
struct usb_interface_cache #
long-term representation of a device interface
Definition
;
Members
num_altsetting: number of altsettings defined.ref: reference counter.altsetting: variable-length array of interface structures, one for each alternate setting that may be selected. Each one includes a set of endpoint configurations. They will be in no particular order.
Description
These structures persist for the lifetime of a usb_device, unlike struct usb_interface (which persists only as long as its configuration is installed). The altsetting arrays can be accessed through these structures at any time, permitting comparison of configurations and providing support for the /sys/kernel/debug/usb/devices pseudo-file.
struct usb_host_config #
representation of a device's configuration
Definition
;
Members
desc: the device's configuration descriptor.string: pointer to the cached version of the iConfiguration string, if present for this configuration.intf_assoc: list of any interface association descriptors in this configinterface: array of pointers to usb_interface structures, one for each interface in the configuration. The number of interfaces is stored in desc.bNumInterfaces. These pointers are valid only while the configuration is active.intf_cache: array of pointers to usb_interface_cache structures, one for each interface in the configuration. These structures exist for the entire life of the device.extra: pointer to buffer containing all extra descriptors associated with this configuration (those preceding the first interface descriptor).extralen: length of the extra descriptors buffer.
Description
USB devices may have multiple configurations, but only one can be active at any time. Each encapsulates a different operational environment; for example, a dual-speed device would have separate configurations for full-speed and high-speed operation. The number of configurations available is stored in the device descriptor as bNumConfigurations.
A configuration can contain multiple interfaces. Each corresponds to
a different function of the USB device, and all are available whenever
the configuration is active. The USB standard says that interfaces
are supposed to be numbered from 0 to desc.bNumInterfaces-1, but a lot
of devices get this wrong. In addition, the interface array is not
guaranteed to be sorted in numerical order. Use usb_ifnum_to_if() to
look up an interface entry based on its number.
Device drivers should not attempt to activate configurations. The choice
of which configuration to install is a policy decision based on such
considerations as available power, functionality provided, and the user's
desires (expressed through userspace tools). However, drivers can call
usb_reset_configuration() to reinitialize the current configuration and
all its interfaces.
struct usb_device #
kernel's representation of a USB device
Definition
;
Members
devnum: device number; address on a USB busdevpath: device ID string for use in messages (e.g., /port/...)route: tree topology hex string for use with xHCIstate: device state: configured, not attached, etc.speed: device speed: high/full/low (or error)rx_lanes: number of rx lanes in use, USB 3.2 adds dual-lane supporttx_lanes: number of tx lanes in use, USB 3.2 adds dual-lane supportssp_rate: SuperSpeed Plus phy signaling rate and lane counttt: Transaction Translator info; used with low/full speed dev, highspeed hubttport: device port on that tt hubtoggle: one bit for each endpoint, with ([0] = IN, [1] = OUT) endpointsparent: our hub, unless we're the rootbus: bus we're part ofep0: endpoint 0 data (default control pipe)dev: generic device interfacedescriptor: USB device descriptorbos: USB device BOS descriptor setconfig: all of the device's configsactconfig: the active configurationep_in: array of IN endpointsep_out: array of OUT endpointsrawdescriptors: raw descriptors for each configbus_mA: Current available from the busportnum: parent port number (origin 1)level: number of USB hub ancestorsdevaddr: device address, XHCI: assigned by HW, others: same as devnumcan_submit: URBs may be submittedpersist_enabled: USB_PERSIST enabled for this devicereset_in_progress: the device is being resethave_langid: whether string_langid is validauthorized: policy has said we can use it; (user space) policy determines if we authorize this device to be used or not. By default, wired USB devices are authorized. WUSB devices are not, until we authorize them from user space. FIXME -- complete docauthenticated: Crypto authentication passedlpm_capable: device supports LPMlpm_devinit_allow: Allow USB3 device initiated LPM, exit latency is in rangeusb2_hw_lpm_capable: device can perform USB2 hardware LPMusb2_hw_lpm_besl_capable: device can perform USB2 hardware BESL LPMusb2_hw_lpm_enabled: USB2 hardware LPM is enabledusb2_hw_lpm_allowed: Userspace allows USB 2.0 LPM to be enabledusb3_lpm_u1_enabled: USB3 hardware U1 LPM enabledusb3_lpm_u2_enabled: USB3 hardware U2 LPM enabledstring_langid: language ID for stringsproduct: iProduct string, if present (static)manufacturer: iManufacturer string, if present (static)serial: iSerialNumber string, if present (static)filelist: usbfs files that are open to this devicemaxchild: number of ports if hubquirks: quirks of the whole deviceurbnum: number of URBs submitted for the whole deviceactive_duration: total time device is not suspendedconnect_time: time device was first connecteddo_remote_wakeup: remote wakeup should be enabledreset_resume: needs reset instead of resumeport_is_suspended: the upstream port is suspended (L2 or U3)offload_pm_locked: prevents offload_usage changes during PM transitions.offload_usage: number of offload activities happening on this usb device.offload_lock: protects offload_usage and offload_pm_lockedtunnel_mode: Connection native or tunneled over USB4usb4_link: device link to the USB4 host interfaceslot_id: Slot ID assigned by xHCIl1_params: best effor service latency for USB2 L1 LPM state, and L1 timeout.u1_params: exit latencies for USB3 U1 LPM state, and hub-initiated timeout.u2_params: exit latencies for USB3 U2 LPM state, and hub-initiated timeout.lpm_disable_count: Ref count used byusb_disable_lpm()andusb_enable_lpm()to keep track of the number of functions that require USB 3.0 Link Power Management to be disabled for this usb_device. This count should only be manipulated by those functions, with the bandwidth_mutex is held.hub_delay: cached value consisting of: parent->hub_delay + wHubDelay + tTPTransmissionDelay (40ns) Will be used as wValue for SetIsochDelay requests.use_generic_driver: ask driver core to reprobe using the generic driver.
Notes
Usbcore drivers should not set usbdev->state directly. Instead use
usb_set_device_state().
usb_hub_for_each_child() #
iterate over all child devices on the hub
Parameters
hdev: USB device belonging to the usb hubport1: portnum associated with child devicechild: child device pointer
usb_interface_claimed() #
int returns true iff an interface is claimed
Parameters
struct usb_interface *iface: the interface being checked
Return
true (nonzero) iff the interface is claimed, else false
(zero).
Note
Callers must own the driver model's usb bus readlock. So driver
probe() entries don't need extra locking, but other call contexts
may need to explicitly claim that lock.
usb_make_path() #
int returns stable device path in the usb tree
Parameters
struct usb_device *dev: the device whose path is being constructedchar *buf: where to put the stringsize_t size: how big is "buf"?
Return
Length of the string (> 0) or negative if size was too small.
Note
This identifier is intended to be "stable", reflecting physical paths in hardware such as physical bus addresses for host controllers or ports on USB hubs. That makes it stay the same until systems are physically reconfigured, by re-cabling a tree of USB devices or by moving USB host controllers. Adding and removing devices, including virtual root hubs in host controller driver modules, does not change these path identifiers; neither does rebooting or re-enumerating. These are more useful identifiers than changeable ("unstable") ones like bus numbers or device addresses.
With a partial exception for devices connected to USB 2.0 root hubs, these identifiers are also predictable. So long as the device tree isn't changed, plugging any USB device into a given hub port always gives it the same path. Because of the use of "companion" controllers, devices connected to ports on USB 2.0 root hubs (EHCI host controllers) will get one path ID if they are high speed, and a different one if they are full or low speed.
USB_DEVICE() #
macro used to describe a specific usb device
Parameters
vend: the 16 bit USB Vendor IDprod: the 16 bit USB Product ID
Description
This macro is used to create a struct usb_device_id that matches a specific device.
USB_DEVICE_VER() #
describe a specific usb device with a version range
Parameters
vend: the 16 bit USB Vendor IDprod: the 16 bit USB Product IDlo: the bcdDevice_lo valuehi: the bcdDevice_hi value
Description
This macro is used to create a struct usb_device_id that matches a specific device, with a version range.
USB_DEVICE_INTERFACE_CLASS() #
describe a usb device with a specific interface class
Parameters
vend: the 16 bit USB Vendor IDprod: the 16 bit USB Product IDcl: bInterfaceClass value
Description
This macro is used to create a struct usb_device_id that matches a specific interface class of devices.
USB_DEVICE_INTERFACE_PROTOCOL() #
describe a usb device with a specific interface protocol
Parameters
vend: the 16 bit USB Vendor IDprod: the 16 bit USB Product IDpr: bInterfaceProtocol value
Description
This macro is used to create a struct usb_device_id that matches a specific interface protocol of devices.
USB_DEVICE_INTERFACE_NUMBER() #
describe a usb device with a specific interface number
Parameters
vend: the 16 bit USB Vendor IDprod: the 16 bit USB Product IDnum: bInterfaceNumber value
Description
This macro is used to create a struct usb_device_id that matches a specific interface number of devices.
USB_DEVICE_INFO() #
macro used to describe a class of usb devices
Parameters
cl: bDeviceClass valuesc: bDeviceSubClass valuepr: bDeviceProtocol value
Description
This macro is used to create a struct usb_device_id that matches a specific class of devices.
USB_INTERFACE_INFO() #
macro used to describe a class of usb interfaces
Parameters
cl: bInterfaceClass valuesc: bInterfaceSubClass valuepr: bInterfaceProtocol value
Description
This macro is used to create a struct usb_device_id that matches a specific class of interfaces.
USB_DEVICE_AND_INTERFACE_INFO() #
describe a specific usb device with a class of usb interfaces
Parameters
vend: the 16 bit USB Vendor IDprod: the 16 bit USB Product IDcl: bInterfaceClass valuesc: bInterfaceSubClass valuepr: bInterfaceProtocol value
Description
This macro is used to create a struct usb_device_id that matches a specific device with a specific class of interfaces.
This is especially useful when explicitly matching devices that have vendor specific bDeviceClass values, but standards-compliant interfaces.
USB_VENDOR_AND_INTERFACE_INFO() #
describe a specific usb vendor with a class of usb interfaces
Parameters
vend: the 16 bit USB Vendor IDcl: bInterfaceClass valuesc: bInterfaceSubClass valuepr: bInterfaceProtocol value
Description
This macro is used to create a struct usb_device_id that matches a specific vendor with a specific class of interfaces.
This is especially useful when explicitly matching devices that have vendor specific bDeviceClass values, but standards-compliant interfaces.
struct usb_driver #
identifies USB interface driver to usbcore
Definition
;
Members
name: The driver name should be unique among USB drivers, and should normally be the same as the module name.probe: Called to see if the driver is willing to manage a particular interface on a device. If it is, probe returns zero and usesusb_set_intfdata()to associate driver-specific data with the interface. It may also useusb_set_interface()to specify the appropriate altsetting. If unwilling to manage the interface, return -ENODEV, if genuine IO errors occurred, an appropriate negative errno value.disconnect: Called when the interface is no longer accessible, usually because its device has been (or is being) disconnected or the driver module is being unloaded.unlocked_ioctl: Used for drivers that want to talk to userspace through the "usbfs" filesystem. This lets devices provide ways to expose information to user space regardless of where they do (or don't) show up otherwise in the filesystem.suspend: Called when the device is going to be suspended by the system either from system sleep or runtime suspend context. The return value will be ignored in system sleep context, so do NOT try to continue using the device if suspend fails in this case. Instead, let the resume or reset-resume routine recover from the failure.resume: Called when the device is being resumed by the system.reset_resume: Called when the suspended device has been reset instead of being resumed.pre_reset: Called byusb_reset_device()when the device is about to be reset. This routine must not return until the driver has no active URBs for the device, and no more URBs may be submitted until the post_reset method is called.post_reset: Called byusb_reset_device()after the device has been resetshutdown: Called at shut-down time to quiesce the device.id_table: USB drivers use ID table to support hotplugging. Export this with MODULE_DEVICE_TABLE(usb,...). This must be set or your driver's probe function will never get called.dev_groups: Attributes attached to the device that will be created once it is bound to the driver.dynids: used internally to hold the list of dynamically added device ids for this driver.driver: The driver-model core driver structure.no_dynamic_id: if set to 1, the USB core will not allow dynamic ids to be added to this driver by preventing the sysfs file from being created.supports_autosuspend: if set to 0, the USB core will not allow autosuspend for interfaces bound to this driver.disable_hub_initiated_lpm: if set to 1, the USB core will not allow hubs to initiate lower power link state transitions when an idle timeout occurs. Device-initiated USB 3.0 link PM will still be allowed.soft_unbind: if set to 1, the USB core will not kill URBs and disable endpoints before calling the driver's disconnect method.
Description
USB interface drivers must provide a name, probe() and disconnect()
methods, and an id_table. Other driver fields are optional.
The id_table is used in hotplugging. It holds a set of descriptors, and specialized data may be associated with each entry. That table is used by both user and kernel mode hotplugging support.
The probe() and disconnect() methods are called in a context where
they can sleep, but they should avoid abusing the privilege. Most
work to connect to a device should be done when the device is opened,
and undone at the last close. The disconnect code needs to address
concurrency issues with respect to open() and close() methods, as
well as forcing all pending I/O requests to complete (by unlinking
them as necessary, and blocking until the unlinks complete).
struct usb_device_driver #
identifies USB device driver to usbcore
Definition
;
Members
name: The driver name should be unique among USB drivers, and should normally be the same as the module name.match: If set, used for better device/driver matching.probe: Called to see if the driver is willing to manage a particular device. If it is, probe returns zero and usesdev_set_drvdata()to associate driver-specific data with the device. If unwilling to manage the device, return a negative errno value.disconnect: Called when the device is no longer accessible, usually because it has been (or is being) disconnected or the driver's module is being unloaded.suspend: Called when the device is going to be suspended by the system.resume: Called when the device is being resumed by the system.choose_configuration: If non-NULL, called instead of the defaultusb_choose_configuration(). If this returns an error then we'll go on to call the normalusb_choose_configuration().dev_groups: Attributes attached to the device that will be created once it is bound to the driver.driver: The driver-model core driver structure.id_table: used with match() to select better matching driver atprobe()time.supports_autosuspend: if set to 0, the USB core will not allow autosuspend for devices bound to this driver.generic_subclass: if set to 1, the generic USB driver's probe, disconnect, resume and suspend functions will be called in addition to the driver's own, so this part of the setup does not need to be replicated.
Description
USB device drivers must provide a name, other driver fields are optional.
struct usb_class_driver #
identifies a USB driver that wants to use the USB major number
Definition
;
Members
name: the usb class device name for this driver. Will show up in sysfs.devnode: Callback to provide a naming hint for a possible device node to create.fops: pointer to the struct file_operations of this driver.minor_base: the start of the minor range for this driver.
Description
This structure is used for the usb_register_dev() and
usb_deregister_dev() functions, to consolidate a number of the
parameters used for them.
module_usb_driver() #
Helper macro for registering a USB driver
Parameters
__usb_driver: usb_driver struct
Description
Helper macro for USB drivers which do not do anything special in module
init/exit. This eliminates a lot of boilerplate. Each module may only
use this macro once, and calling it replaces module_init() and module_exit()
struct urb #
USB Request Block
Definition
;
Members
urb_list: For use by current owner of the URB.anchor_list: membership in the list of an anchoranchor: to anchor URBs to a common mooringdev: Identifies the USB device to perform the request.ep: Points to the endpoint's data structure. Will eventually replace pipe.pipe: Holds endpoint number, direction, type, and more. Create these values with the eight macros available; usb_{snd,rcv}TYPEpipe(dev,endpoint), where the TYPE is "ctrl" (control), "bulk", "int" (interrupt), or "iso" (isochronous). For exampleusb_sndbulkpipe()orusb_rcvintpipe(). Endpoint numbers range from zero to fifteen. Note that "in" endpoint two is a different endpoint (and pipe) from "out" endpoint two. The current configuration controls the existence, type, and maximum packet size of any given endpoint.stream_id: the endpoint's stream ID for bulk streamsstatus: This is read in non-iso completion functions to get the status of the particular request. ISO requests only use it to tell whether the URB was unlinked; detailed status for each frame is in the fields of the iso_frame-desc.transfer_flags: A variety of flags may be used to affect how URB submission, unlinking, or operation are handled. Different kinds of URB can use different flags.transfer_buffer: This identifies the buffer to (or from) which the I/O request will be performed unless URB_NO_TRANSFER_DMA_MAP is set (however, do not leave garbage in transfer_buffer even then). This buffer must be suitable for DMA; allocate it withkmalloc()or equivalent. For transfers to "in" endpoints, contents of this buffer will be modified. This buffer is used for the data stage of control transfers.transfer_dma: When transfer_flags includes URB_NO_TRANSFER_DMA_MAP, the device driver is saying that it provided this DMA address, which the host controller driver should use in preference to the transfer_buffer.sg: scatter gather buffer list, the buffer size of each element in the list (except the last) must be divisible by the endpoint's max packet size if no_sg_constraint isn't set in 'struct usb_bus'sgt: used to hold a scatter gather table returned byusb_alloc_noncoherent(), which describes the allocated non-coherent and possibly non-contiguous memory and is guaranteed to have 1 single DMA mapped segment. The allocated memory needs to be freed byusb_free_noncoherent().num_mapped_sgs: (internal) number of mapped sg entriesnum_sgs: number of entries in the sg listtransfer_buffer_length: How big is transfer_buffer. The transfer may be broken up into chunks according to the current maximum packet size for the endpoint, which is a function of the configuration and is encoded in the pipe. When the length is zero, neither transfer_buffer nor transfer_dma is used.actual_length: This is read in non-iso completion functions, and it tells how many bytes (out of transfer_buffer_length) were transferred. It will normally be the same as requested, unless either an error was reported or a short read was performed. The URB_SHORT_NOT_OK transfer flag may be used to make such short reads be reported as errors.setup_packet: Only used for control transfers, this points to eight bytes of setup data. Control transfers always start by sending this data to the device. Then transfer_buffer is read or written, if needed.setup_dma: DMA pointer for the setup packet. The caller must not use this field; setup_packet must point to a valid buffer.start_frame: Returns the initial frame for isochronous transfers.number_of_packets: Lists the number of ISO transfer buffers.interval: Specifies the polling interval for interrupt or isochronous transfers. The units are frames (milliseconds) for full and low speed devices, and microframes (1/8 millisecond) for highspeed and SuperSpeed devices.error_count: Returns the number of ISO transfers that reported errors.context: For use in completion functions. This normally points to request-specific driver context.complete: Completion handler. This URB is passed as the parameter to the completion function. The completion function may then do what it likes with the URB, including resubmitting or freeing it.iso_frame_desc: Used to provide arrays of ISO transfer buffers and to collect the transfer status for each buffer.
Description
This structure identifies USB transfer requests. URBs must be allocated by
calling usb_alloc_urb() and freed with a call to usb_free_urb().
Initialization may be done using various usb_fill_*_urb() functions. URBs
are submitted using usb_submit_urb(), and pending requests may be canceled
using usb_unlink_urb() or usb_kill_urb().
Data Transfer Buffers:
Normally drivers provide I/O buffers allocated with kmalloc() or otherwise
taken from the general page pool. That is provided by transfer_buffer
(control requests also use setup_packet), and host controller drivers
perform a dma mapping (and unmapping) for each buffer transferred. Those
mapping operations can be expensive on some platforms (perhaps using a dma
bounce buffer or talking to an IOMMU),
although they're cheap on commodity x86 and ppc hardware.
Alternatively, drivers may pass the URB_NO_TRANSFER_DMA_MAP transfer flag,
which tells the host controller driver that no such mapping is needed for
the transfer_buffer since
the device driver is DMA-aware. For example, a device driver might
allocate a DMA buffer with usb_alloc_coherent() or call usb_buffer_map().
When this transfer flag is provided, host controller drivers will
attempt to use the dma address found in the transfer_dma
field rather than determining a dma address themselves.
Note that transfer_buffer must still be set if the controller
does not support DMA (as indicated by hcd_uses_dma()) and when talking
to root hub. If you have to transfer between highmem zone and the device
on such controller, create a bounce buffer or bail out with an error.
If transfer_buffer cannot be set (is in highmem) and the controller is DMA
capable, assign NULL to it, so that usbmon knows not to use the value.
The setup_packet must always be set, so it cannot be located in highmem.
Initialization:
All URBs submitted must initialize the dev, pipe, transfer_flags (may be zero), and complete fields. All URBs must also initialize transfer_buffer and transfer_buffer_length. They may provide the URB_SHORT_NOT_OK transfer flag, indicating that short reads are to be treated as errors; that flag is invalid for write requests.
Bulk URBs may use the URB_ZERO_PACKET transfer flag, indicating that bulk OUT transfers should always terminate with a short packet, even if it means adding an extra zero length packet.
Control URBs must provide a valid pointer in the setup_packet field. Unlike the transfer_buffer, the setup_packet may not be mapped for DMA beforehand.
Interrupt URBs must provide an interval, saying how often (in milliseconds or, for highspeed devices, 125 microsecond units) to poll for transfers. After the URB has been submitted, the interval field reflects how the transfer was actually scheduled. The polling interval may be more frequent than requested. For example, some controllers have a maximum interval of 32 milliseconds, while others support intervals of up to 1024 milliseconds. Isochronous URBs also have transfer intervals. (Note that for isochronous endpoints, as well as high speed interrupt endpoints, the encoding of the transfer interval in the endpoint descriptor is logarithmic. Device drivers must convert that value to linear units themselves.)
If an isochronous endpoint queue isn't already running, the host controller will schedule a new URB to start as soon as bandwidth utilization allows. If the queue is running then a new URB will be scheduled to start in the first transfer slot following the end of the preceding URB, if that slot has not already expired. If the slot has expired (which can happen when IRQ delivery is delayed for a long time), the scheduling behavior depends on the URB_ISO_ASAP flag. If the flag is clear then the URB will be scheduled to start in the expired slot, implying that some of its packets will not be transferred; if the flag is set then the URB will be scheduled in the first unexpired slot, breaking the queue's synchronization. Upon URB completion, the start_frame field will be set to the (micro)frame number in which the transfer was scheduled. Ranges for frame counter values are HC-specific and can go from as low as 256 to as high as 65536 frames.
Isochronous URBs have a different data transfer model, in part because the quality of service is only "best effort". Callers provide specially allocated URBs, with number_of_packets worth of iso_frame_desc structures at the end. Each such packet is an individual ISO transfer. Isochronous URBs are normally queued, submitted by drivers to arrange that transfers are at least double buffered, and then explicitly resubmitted in completion handlers, so that data (such as audio or video) streams at as constant a rate as the host controller scheduler can support.
Completion Callbacks:
The completion callback is made in_interrupt(), and one of the first
things that a completion handler should do is check the status field.
The status field is provided for all URBs. It is used to report
unlinked URBs, and status for all non-ISO transfers. It should not
be examined before the URB is returned to the completion handler.
The context field is normally used to link URBs back to the relevant driver or request state.
When the completion callback is invoked for non-isochronous URBs, the actual_length field tells how many bytes were transferred. This field is updated even when the URB terminated with an error or was unlinked.
ISO transfer status is reported in the status and actual_length fields of the iso_frame_desc array, and the number of errors is reported in error_count. Completion callbacks for ISO transfers will normally (re)submit URBs to ensure a constant transfer rate.
Note that even fields marked "public" should not be touched by the driver
when the urb is owned by the hcd, that is, since the call to
usb_submit_urb() till the entry into the completion routine.
usb_fill_control_urb() #
void initializes a control urb
Parameters
struct urb *urb: pointer to the urb to initialize.struct usb_device *dev: pointer to the struct usb_device for this urb.unsigned int pipe: the endpoint pipeunsigned char *setup_packet: pointer to the setup_packet buffer. The buffer must be suitable for DMA.void *transfer_buffer: pointer to the transfer buffer. The buffer must be suitable for DMA.int buffer_length: length of the transfer bufferusb_complete_t complete_fn: pointer to the usb_complete_t functionvoid *context: what to set the urb context to.
Description
Initializes a control urb with the proper information needed to submit it to a device.
The transfer buffer and the setup_packet buffer will most likely be filled
or read via DMA. The simplest way to get a buffer that can be DMAed to is
allocating it via kmalloc() or equivalent, even for very small buffers.
If the buffers are embedded in a bigger structure, there is a risk that
the buffer itself, the previous fields and/or the next fields are corrupted
due to cache incoherencies; or slowed down if they are evicted from the
cache. For more information, check struct urb.
usb_fill_bulk_urb() #
void macro to help initialize a bulk urb
Parameters
struct urb *urb: pointer to the urb to initialize.struct usb_device *dev: pointer to the struct usb_device for this urb.unsigned int pipe: the endpoint pipevoid *transfer_buffer: pointer to the transfer buffer. The buffer must be suitable for DMA.int buffer_length: length of the transfer bufferusb_complete_t complete_fn: pointer to the usb_complete_t functionvoid *context: what to set the urb context to.
Description
Initializes a bulk urb with the proper information needed to submit it to a device.
Refer to usb_fill_control_urb() for a description of the requirements for
transfer_buffer.
usb_fill_int_urb() #
void macro to help initialize a interrupt urb
Parameters
struct urb *urb: pointer to the urb to initialize.struct usb_device *dev: pointer to the struct usb_device for this urb.unsigned int pipe: the endpoint pipevoid *transfer_buffer: pointer to the transfer buffer. The buffer must be suitable for DMA.int buffer_length: length of the transfer bufferusb_complete_t complete_fn: pointer to the usb_complete_t functionvoid *context: what to set the urb context to.int interval: what to set the urb interval to, encoded like the endpoint descriptor's bInterval value.
Description
Initializes a interrupt urb with the proper information needed to submit it to a device.
Refer to usb_fill_control_urb() for a description of the requirements for
transfer_buffer.
Note that High Speed and SuperSpeed(+) interrupt endpoints use a logarithmic encoding of the endpoint interval, and express polling intervals in microframes (eight per millisecond) rather than in frames (one per millisecond).
usb_urb_dir_in() #
int check if an URB describes an IN transfer
Parameters
struct urb *urb: URB to be checked
Return
1 if urb describes an IN transfer (device-to-host), otherwise 0.
usb_urb_dir_out() #
int check if an URB describes an OUT transfer
Parameters
struct urb *urb: URB to be checked
Return
1 if urb describes an OUT transfer (host-to-device), otherwise 0.
struct usb_sg_request #
support for scatter/gather I/O
Definition
;
Members
status: zero indicates success, else negative errnobytes: counts bytes transferred.
Description
These requests are initialized using usb_sg_init(), and then are used
as request handles passed to usb_sg_wait() or usb_sg_cancel(). Most
members of the request object aren't for driver access.
The status and bytecount values are valid only after usb_sg_wait()
returns. If the status is zero, then the bytecount matches the total
from the request.
After an error completion, drivers may need to clear a halt condition on the endpoint.
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.
usb_init_urb() #
void 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.
usb_alloc_urb() #
struct urb * creates a new urb for a USB driver to use
Parameters
int iso_packets: number of iso packets for this urbgfp_t mem_flags: the type of memory to allocate, seekmalloc()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.
usb_free_urb() #
void 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.
usb_get_urb() #
struct 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.
usb_anchor_urb() #
void anchors an URB while it is processed
Parameters
struct urb *urb: pointer to the urb to anchorstruct 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
usb_unanchor_urb() #
void 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
usb_pipe_type_check() #
int sanity check of a specific pipe for a usb device
Parameters
struct usb_device *dev: struct usb_device to be checkedunsigned 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.
usb_urb_ep_type_check() #
int 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.
usb_submit_urb() #
int issue an asynchronous transfer request for an endpoint
Parameters
struct urb *urb: pointer to the urb describing the requestgfp_t mem_flags: the type of memory to allocate, seekmalloc()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
(a) you are inside a completion handler, an interrupt, bottom half, tasklet or timer, or (b) you are holding a spinlock or rwlock (does not apply to semaphores), or (c) 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
(1) start_xmit, timeout, and receive methods of network drivers must use GFP_ATOMIC (they are called with a spinlock held); (2) queuecommand methods of scsi drivers must use GFP_ATOMIC (also called with a spinlock held); (3) If you use a kernel thread with a network driver you must use GFP_NOIO, unless (b) or (c) apply; (4) 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; (5) USB probe and disconnect can use GFP_KERNEL unless (b) or (c) apply; and (6) 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.
usb_unlink_urb() #
int 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(), 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.
usb_kill_urb() #
void 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.
usb_poison_urb() #
void 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.
usb_block_urb() #
void 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.
usb_kill_anchored_urbs() #
void 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.
usb_poison_anchored_urbs() #
void 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.
usb_unpoison_anchored_urbs() #
void 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
usb_anchor_suspend_wakeups() #
void 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.
usb_anchor_resume_wakeups() #
void 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.
usb_wait_anchor_empty_timeout() #
int wait for an anchor to be unused
Parameters
struct usb_anchor *anchor: the anchor you want to become unusedunsigned 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.
usb_get_from_anchor() #
struct urb * 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.
usb_scuttle_anchored_urbs() #
void 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
usb_anchor_empty() #
int 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.
usb_control_msg() #
int 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 tounsigned 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 valuevoid *data: pointer to the data to send__u16 size: length in bytes of the data to sendint timeout: time in msecs to wait for the message to complete before timing out
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.
usb_control_msg_send() #
int 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 valueconst void *driver_data: pointer to the data to send__u16 size: length in bytes of the data to sendint timeout: time in msecs to wait for the message to complete before timing outgfp_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.
usb_control_msg_recv() #
int 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 valuevoid *driver_data: pointer to the data to be filled in by the message__u16 size: length in bytes of the data to be receivedint timeout: time in msecs to wait for the message to complete before timing outgfp_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.
usb_interrupt_msg() #
int 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 tounsigned int pipe: endpoint "pipe" to send the message tovoid *data: pointer to the data to sendint len: length in bytes of the data to sendint *actual_length: pointer to a location to put the actual length transferred in bytesint timeout: time in msecs to wait for the message to complete before timing out
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.
usb_bulk_msg() #
int 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 tounsigned int pipe: endpoint "pipe" to send the message tovoid *data: pointer to the data to sendint len: length in bytes of the data to sendint *actual_length: pointer to a location to put the actual length transferred in bytesint timeout: time in msecs to wait for the message to complete before timing out
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.
usb_bulk_msg_killable() #
int Builds a bulk urb, sends it off and waits for completion in a killable state
Parameters
struct usb_device *usb_dev: pointer to the usb device to send the message tounsigned int pipe: endpoint "pipe" to send the message tovoid *data: pointer to the data to sendint len: length in bytes of the data to sendint *actual_length: pointer to a location to put the actual length transferred in bytesint timeout: time in msecs to wait for the message to complete before timing out (if <= 0, the wait is as long as possible)
Context
task context, might sleep.
Description
This function is just like usb_blk_msg(), except that it waits in a
killable state and there is no limit on the timeout length.
Return
If successful, 0. Otherwise a negative error number. The number of actual bytes transferred will be stored in the actual_length parameter.
usb_sg_init() #
int initializes scatterlist-based bulk/interrupt I/O request
Parameters
struct usb_sg_request *io: request block being initialized. untilusb_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 dataunsigned pipe: endpoint "pipe" used to transfer the dataunsigned period: polling rate for interrupt endpoints, in frames or (for high speed endpoints) microframes; ignored for bulkstruct scatterlist *sg: scatterlist entriesint nents: how many entries in the scatterlistsize_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.
usb_sg_wait() #
void synchronously execute scatter/gather request
Parameters
struct usb_sg_request *io: request block handle, as initialized withusb_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.
-
(1) success, where io->status is zero. The number of io->bytes
transferred is as requested.
-
(2) 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.
-
(3) 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.
usb_sg_cancel() #
void stop scatter/gather i/o issued by usb_sg_wait()
Parameters
struct usb_sg_request *io: request block, initialized withusb_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.
usb_get_descriptor() #
int issues a generic GET_DESCRIPTOR request
Parameters
struct usb_device *dev: the device whose descriptor is being retrievedunsigned char type: the descriptor type (USB_DT_*)unsigned char index: the number of the descriptorvoid *buf: where to put the descriptorint 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.
usb_string() #
int returns UTF-8 version of a string descriptor
Parameters
struct usb_device *dev: the device whose string descriptor is being retrievedint index: the number of the descriptorchar *buf: where to put the stringsize_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).
usb_cache_string() #
char * read a string descriptor and cache it for later use
Parameters
struct usb_device *udev: the device whose string descriptor is being readint index: the descriptor index
Return
A pointer to a kmalloc'ed buffer containing the descriptor string,
or NULL if the index is 0 or the string could not be read.
usb_get_status() #
int issues a GET_STATUS call
Parameters
struct usb_device *dev: the device whose status is being checkedint recip: USB_RECIP_*; for device, interface, or endpointint type: USB_STATUS_TYPE_*; for standard or PTM status typesint target: zero (for device), else interface or endpoint numbervoid *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.
usb_clear_halt() #
int tells device to clear endpoint halt/stall condition
Parameters
struct usb_device *dev: device whose endpoint is haltedint 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.
If a thread in your driver uses this call, make sure your disconnect()
method can wait for it to complete.
Return
Zero on success, or else the status code returned by the
underlying usb_control_msg() call.
usb_reset_endpoint() #
void Reset an endpoint's state.
Parameters
struct usb_device *dev: the device whose endpoint is to be resetunsigned 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.
usb_set_interface() #
int Makes a particular alternate setting be current
Parameters
struct usb_device *dev: the device whose interface is being updatedint interface: the interface being updatedint 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). If a thread in your driver uses this call,
make sure your disconnect() method can wait for it to complete.
Return
Zero on success, or else the status code returned by the
underlying usb_control_msg() call.
usb_reset_configuration() #
int 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.
usb_set_wireless_status() #
int sets the wireless_status struct member
Parameters
struct usb_interface *iface: the interface to modifyenum usb_wireless_status status: the new wireless status
Description
Set the wireless_status struct member to the new value, and emit sysfs changes as necessary.
Return
0 on success, -EALREADY if already set.
usb_driver_set_configuration() #
int Provide a way for drivers to change device configurations
Parameters
struct usb_device *udev: the device whose configuration is being updatedint 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.
cdc_parse_cdc_header() #
int parse the extra headers present in CDC devices
Parameters
struct usb_cdc_parsed_header *hdr: the place to put the results of the parsingstruct usb_interface *intf: the interface for which parsing is requestedu8 *buffer: pointer to the extra headers to be parsedint 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
usb_register_dev() #
int register a USB device, and ask for a minor number
Parameters
struct usb_interface *intf: pointer to the usb_interface that is being registeredstruct 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.
usb_deregister_dev() #
void deregister a USB device's dynamic minor.
Parameters
struct usb_interface *intf: pointer to the usb_interface that is being deregisteredstruct 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.
usb_driver_claim_interface() #
int bind a driver to an interface
Parameters
struct usb_driver *driver: the driver to be boundstruct usb_interface *iface: the interface to which it will be bound; must be in the usb device's active configurationvoid *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.
usb_driver_release_interface() #
void unbind a driver from an interface
Parameters
struct usb_driver *driver: the driver to be unboundstruct 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.
usb_match_id() #
const struct usb_device_id * find first usb_device_id matching device or interface
Parameters
struct usb_interface *interface: the interface of interestconst 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.
usb_register_device_driver() #
int register a USB device (not interface) driver
Parameters
struct usb_device_driver *new_udriver: USB operations for the device driverstruct 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.
usb_deregister_device_driver() #
void 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.
usb_register_driver() #
int register a USB interface driver
Parameters
struct usb_driver *new_driver: USB operations for the interface driverstruct 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.
usb_deregister() #
void 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.
usb_enable_autosuspend() #
void 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.
usb_disable_autosuspend() #
void 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.
usb_autopm_put_interface() #
void 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.
usb_autopm_put_interface_async() #
void 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.
usb_autopm_put_interface_no_suspend() #
void 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.
usb_autopm_get_interface() #
int 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.
usb_autopm_get_interface_async() #
int 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.
usb_autopm_get_interface_no_resume() #
void 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.
usb_find_common_endpoints() #
int - look up common endpoint descriptors
Parameters
struct usb_host_interface *alt: alternate setting to searchstruct usb_endpoint_descriptor **bulk_in: pointer to descriptor pointer, or NULLstruct usb_endpoint_descriptor **bulk_out: pointer to descriptor pointer, or NULLstruct usb_endpoint_descriptor **int_in: pointer to descriptor pointer, or NULLstruct 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.
usb_find_common_endpoints_reverse() #
int - look up common endpoint descriptors
Parameters
struct usb_host_interface *alt: alternate setting to searchstruct usb_endpoint_descriptor **bulk_in: pointer to descriptor pointer, or NULLstruct usb_endpoint_descriptor **bulk_out: pointer to descriptor pointer, or NULLstruct usb_endpoint_descriptor **int_in: pointer to descriptor pointer, or NULLstruct 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.
usb_check_bulk_endpoints() #
bool 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 searchedconst 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.
usb_check_int_endpoints() #
bool 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 searchedconst 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.
usb_find_alt_setting() #
struct usb_host_interface * 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 inunsigned 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.
usb_ifnum_to_if() #
struct usb_interface * get the interface object with a given interface number
Parameters
const struct usb_device *dev: the device whose current configuration is consideredunsigned 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.
usb_altnum_to_altsetting() #
struct usb_host_interface * get the altsetting structure with a given alternate setting number.
Parameters
const struct usb_interface *intf: the interface containing the altsetting in questionunsigned 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.
usb_find_interface() #
struct usb_interface * find usb_interface pointer for driver and device
Parameters
struct usb_driver *drv: the driver whose current configuration is consideredint 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.
usb_for_each_dev() #
int iterate over all USB devices in the system
Parameters
void *data: data pointer that will be handed to the callback functionint (*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.
usb_alloc_dev() #
struct usb_device * usb device constructor (usbcore-internal)
Parameters
struct usb_device *parent: hub to which device is connected; null to allocate a root hubstruct usb_bus *bus: bus used to access the deviceunsigned 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.
usb_get_dev() #
struct usb_device * 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.
usb_put_dev() #
void 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.
usb_get_intf() #
struct usb_interface * 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.
usb_put_intf() #
void 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.
usb_intf_get_dma_device() #
struct device * 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.
usb_lock_device_for_reset() #
int cautiously acquire the lock for a usb device structure
Parameters
struct usb_device *udev: device that's being lockedconst 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.
usb_get_current_frame_number() #
int 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.
usb_alloc_coherent() #
void * allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
Parameters
struct usb_device *dev: device the buffer will be used withsize_t size: requested buffer sizegfp_t mem_flags: affect whether allocation may blockdma_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.
When the buffer is no longer used, free it with usb_free_coherent().
usb_free_coherent() #
void free memory allocated with usb_alloc_coherent()
Parameters
struct usb_device *dev: device the buffer was used withsize_t size: requested buffer sizevoid *addr: CPU address of bufferdma_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.
usb_alloc_noncoherent() #
void * allocate dma-noncoherent buffer for URB_NO_xxx_DMA_MAP
Parameters
struct usb_device *dev: device the buffer will be used withsize_t size: requested buffer sizegfp_t mem_flags: affect whether allocation may blockdma_addr_t *dma: used to return DMA address of bufferenum dma_data_direction dir: DMA transfer directionstruct sg_table **table: used to return sg_table of allocated memory
Description
To explicit manage the memory ownership for the kernel vs the device by USB core, the user needs save sg_table to urb->sgt. Then USB core will do DMA sync for CPU and device properly.
When the buffer is no longer used, free it with usb_free_noncoherent().
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).
usb_free_noncoherent() #
void free memory allocated with usb_alloc_noncoherent()
Parameters
struct usb_device *dev: device the buffer was used withsize_t size: requested buffer sizevoid *addr: CPU address of bufferenum dma_data_direction dir: DMA transfer directionstruct sg_table *table: describe the allocated and DMA mapped memory,
Description
This reclaims an I/O buffer, letting it be reused. The memory must have
been allocated using usb_alloc_noncoherent(), and the parameters must match
those provided in that allocation request.
usb_endpoint_max_periodic_payload() #
u32 Get maximum payload bytes per service interval
Parameters
struct usb_device *udev: The USB deviceconst struct usb_host_endpoint *ep: The endpoint
Return
the maximum number of bytes isochronous or interrupt endpoint ep can transfer during a service interval, or 0 for other endpoints.
usb_endpoint_is_hs_isoc_double() #
bool Tell whether an endpoint uses USB 2 Isochronous Double IN Bandwidth
Parameters
struct usb_device *udev: The USB deviceconst struct usb_host_endpoint *ep: The endpoint
Return
true if an endpoint ep conforms to USB 2 Isochronous Double IN Bandwidth ECN, false otherwise.
usb_hub_clear_tt_buffer() #
int 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.
usb_set_device_state() #
void change a device's current state (usbcore, hcds)
Parameters
struct usb_device *udev: pointer to device whose state should be changedenum 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.
usb_root_hub_lost_power() #
void 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.
usb_reset_device() #
int 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).
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().
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.
usb_queue_reset_device() #
void 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(), callusb_reset_device()directly -- but watch out for nested unbinding issues!
usb_hub_find_child() #
struct usb_device * 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 hubint 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 <usb_bus> is a rather thin layer that became available in the 2.2 kernels, while struct usb_hcd <usb_hcd> is a more featureful layer that lets HCDs share common code, to shrink driver size and significantly reduce hcd-specific behaviors.
usb_calc_bus_time() #
long 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 hostint isoc: true for isochronous transactions, false for interrupt onesint 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.
usb_hcd_link_urb_to_ep() #
int add an URB to its endpoint queue
Parameters
struct usb_hcd *hcd: host controller to which urb was submittedstruct 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.
usb_hcd_check_unlink_urb() #
int check whether an URB may be unlinked
Parameters
struct usb_hcd *hcd: host controller to which urb was submittedstruct urb *urb: URB being checked for unlinkabilityint 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.
-
-EIDRM: urb was not submitted or has already completed.
The completion function may not have been called yet.
-EBUSY: urb has already been unlinked.
Return
0 for no error, otherwise a negative error code (in which case
the dequeue() method must fail). The possible error codes are:
usb_hcd_unlink_urb_from_ep() #
void remove an URB from its endpoint queue
Parameters
struct usb_hcd *hcd: host controller to which urb was submittedstruct 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.
usb_hcd_giveback_urb() #
void return URB from HCD to device driver
Parameters
struct usb_hcd *hcd: host controller returning the URBstruct 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 either in a work queue (BH) context or in the caller's context, depending on whether the HCD_BH flag is set in the hcd structure, except that URBs submitted to the root hub always complete in BH 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.
usb_alloc_streams() #
int 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.
usb_free_streams() #
int 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.
usb_hcd_resume_root_hub() #
void 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).
usb_bus_start_enum() #
int 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.
usb_hcd_irq() #
irqreturn_t hook IRQs to HCD framework (bus glue)
Parameters
int irq: the IRQ being raisedvoid *__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.
usb_hc_died() #
void 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.
usb_create_shared_hcd() #
struct usb_hcd * create and initialize an HCD structure
Parameters
const struct hc_driver *driver: HC driver that will use this hcdstruct device *dev: device for this HC, stored in hcd->self.controllerconst char *bus_name: value to store in hcd->self.bus_namestruct 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.
usb_create_hcd() #
struct usb_hcd * create and initialize an HCD structure
Parameters
const struct hc_driver *driver: HC driver that will use this hcdstruct device *dev: device for this HC, stored in hcd->self.controllerconst 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.
usb_add_hcd() #
int finish generic HCD structure initialization and register
Parameters
struct usb_hcd *hcd: the usb_hcd structure to initializeunsigned int irqnum: Interrupt line to allocateunsigned 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.
usb_remove_hcd() #
void 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.
usb_hcd_pci_probe() #
int initialize PCI-based HCDs
Parameters
struct pci_dev *dev: USB Host Controller being probedconst 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.
usb_hcd_pci_remove() #
void 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().
usb_hcd_pci_shutdown() #
void shutdown host controller
Parameters
struct pci_dev *dev: USB Host Controller being shutdown
hcd_buffer_create() #
int 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.
hcd_buffer_destroy() #
void 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/
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_RAWIOcapability, 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.
The inherited Unix mode settings on BBB/DDD files are not a Peios access grant. A userspace driver needs native authorization to open and operate on the device, including the relevant handle and ioctl rights. chmod or a devmode=0666 mount option alone does not delegate that authority. See Peios kernel behaviour.
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_GET_SPEED
Returns the speed of the device. The speed is returned as a numerical value in accordance with enum usb_device_speed
File modification time is not updated by this request.
-
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.
-
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.
-
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
epvalue 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
-EPIPEstatus 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.
-
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.
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)
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:
USB3 debug port
Peios Kernel / Hardware and drivers / Driver development / USB
Author: Lu Baolu <baolu.lu@linux.intel.com>
Date: March 2017
GENERAL #
This is a HOWTO for using the USB3 debug port on x86 systems.
Before using any kernel debugging functionality based on USB3 debug port, you need to:
1) check whether any USB3 debug port is available in
your system;
2) check which port is used for debugging purposes;
3) have a USB 3.0 super-speed A-to-A debugging cable.
INTRODUCTION #
The xHCI debug capability (DbC) is an optional but standalone functionality provided by the xHCI host controller. The xHCI specification describes DbC in the section 7.6.
When DbC is initialized and enabled, it will present a debug device through the debug port (normally the first USB3 super-speed port). The debug device is fully compliant with the USB framework and provides the equivalent of a very high performance full-duplex serial link between the debug target (the system under debugging) and a debug host.
EARLY PRINTK #
DbC has been designed to log early printk messages. One use for this feature is kernel debugging. For example, when your machine crashes very early before the regular console code is initialized. Other uses include simpler, lockless logging instead of a full- blown printk console driver and klogd.
On the debug target system, you need to customize a debugging kernel with CONFIG_EARLY_PRINTK_USB_XDBC enabled. And, add below kernel boot parameter:
"earlyprintk=xdbc"
If there are multiple xHCI controllers in your system, you can append a host controller index to this kernel parameter. This index starts from 0.
Current design doesn't support DbC runtime suspend/resume. As the result, you'd better disable runtime power management for USB subsystem by adding below kernel boot parameter:
"usbcore.autosuspend=-1"
Before starting the debug target, you should connect the debug port to a USB port (root port or port of any external hub) on the debug host. The cable used to connect these two ports should be a USB 3.0 super-speed A-to-A debugging cable.
During early boot of the debug target, DbC will be detected and initialized. After initialization, the debug host should be able to enumerate the debug device in debug target. The debug host will then bind the debug device with the usb_debug driver module and create the /dev/ttyUSB device.
If the debug device enumeration goes smoothly, you should be able to see below kernel messages on the debug host:
# tail -f /var/log/kern.log
[ 1815.983374] usb 4-3: new SuperSpeed USB device number 4 using xhci_hcd
[ 1815.999595] usb 4-3: LPM exit latency is zeroed, disabling LPM.
[ 1815.999899] usb 4-3: New USB device found, idVendor=1d6b, idProduct=0004
[ 1815.999902] usb 4-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 1815.999903] usb 4-3: Product: Remote GDB
[ 1815.999904] usb 4-3: Manufacturer: Linux
[ 1815.999905] usb 4-3: SerialNumber: 0001
[ 1816.000240] usb_debug 4-3:1.0: xhci_dbc converter detected
[ 1816.000360] usb 4-3: xhci_dbc converter now attached to ttyUSB0
You can use any communication program, for example minicom, to read and view the messages. Below simple bash scripts can help you to check the sanity of the setup.
=====
#!/bin/bash
while ; do
while [ ; do
done
done
=====
Serial TTY #
The DbC support has been added to the xHCI driver. You can get a debug device provided by the DbC at runtime.
In order to use this, you need to make sure your kernel has been configured to support USB_XHCI_DBGCAP. A sysfs attribute under the xHCI device node is used to enable or disable DbC. By default, DbC is disabled:
root@target:/sys/bus/pci/devices/0000:00:14.0# cat dbc
disabled
Enable DbC with the following command:
root@target:/sys/bus/pci/devices/0000:00:14.0# echo enable > dbc
You can check the DbC state at anytime:
root@target:/sys/bus/pci/devices/0000:00:14.0# cat dbc
enabled
Connect the debug target to the debug host with a USB 3.0 super- speed A-to-A debugging cable. You can see /dev/ttyDBC0 created on the debug target. You will see below kernel message lines:
root@target: tail -f /var/log/kern.log
[ 182.730103] xhci_hcd 0000:00:14.0: DbC connected
[ 191.169420] xhci_hcd 0000:00:14.0: DbC configured
[ 191.169597] xhci_hcd 0000:00:14.0: DbC now attached to /dev/ttyDBC0
Accordingly, the DbC state has been brought up to:
root@target:/sys/bus/pci/devices/0000:00:14.0# cat dbc
configured
On the debug host, you will see the debug device has been enumerated. You will see below kernel message lines:
root@host: tail -f /var/log/kern.log
[ 79.454780] usb 2-2.1: new SuperSpeed USB device number 3 using xhci_hcd
[ 79.475003] usb 2-2.1: LPM exit latency is zeroed, disabling LPM.
[ 79.475389] usb 2-2.1: New USB device found, idVendor=1d6b, idProduct=0010
[ 79.475390] usb 2-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 79.475391] usb 2-2.1: Product: Linux USB Debug Target
[ 79.475392] usb 2-2.1: Manufacturer: Linux Foundation
[ 79.475393] usb 2-2.1: SerialNumber: 0001
The debug device works now. You can use any communication or debugging program to talk between the host and the target.
Writing a MUSB Glue Layer
Peios Kernel / Hardware and drivers / Driver development / USB
Author: Apelete Seketeli
Introduction #
The Linux MUSB subsystem is part of the larger Linux USB subsystem. It provides support for embedded USB Device Controllers (UDC) that do not use Universal Host Controller Interface (UHCI) or Open Host Controller Interface (OHCI).
Instead, these embedded UDC rely on the USB On-the-Go (OTG) specification which they implement at least partially. The silicon reference design used in most cases is the Multipoint USB Highspeed Dual-Role Controller (MUSB HDRC) found in the Mentor Graphics Inventra™ design.
As a self-taught exercise I have written an MUSB glue layer for the Ingenic JZ4740 SoC, modelled after the many MUSB glue layers in the kernel source tree. This layer can be found at drivers/usb/musb/jz4740.c. In this documentation I will walk through the basics of the jz4740.c glue layer, explaining the different pieces and what needs to be done in order to write your own device glue layer.
Linux MUSB Basics #
To get started on the topic, please read USB On-the-Go Basics (see Resources) which provides an introduction of USB OTG operation at the hardware level. A couple of wiki pages by Texas Instruments and Analog Devices also provide an overview of the Linux kernel MUSB configuration, albeit focused on some specific devices provided by these companies. Finally, getting acquainted with the USB specification at USB home page may come in handy, with practical instance provided through the Writing USB Device Drivers documentation (again, see Resources).
Linux USB stack is a layered architecture in which the MUSB controller hardware sits at the lowest. The MUSB controller driver abstract the MUSB controller hardware to the Linux USB stack:
------------------------
| | <------- drivers/usb/gadget
| Linux USB Core Stack | <------- drivers/usb/host
| | <------- drivers/usb/core
------------------------
⬍
--------------------------
| | <------ drivers/usb/musb/musb_gadget.c
| MUSB Controller driver | <------ drivers/usb/musb/musb_host.c
| | <------ drivers/usb/musb/musb_core.c
--------------------------
⬍
---------------------------------
| MUSB Platform Specific Driver |
| | <-- drivers/usb/musb/jz4740.c
| aka "Glue Layer" |
---------------------------------
⬍
---------------------------------
| MUSB Controller Hardware |
---------------------------------
As outlined above, the glue layer is actually the platform specific code sitting in between the controller driver and the controller hardware.
Just like a Linux USB driver needs to register itself with the Linux USB subsystem, the MUSB glue layer needs first to register itself with the MUSB controller driver. This will allow the controller driver to know about which device the glue layer supports and which functions to call when a supported device is detected or released; remember we are talking about an embedded controller chip here, so no insertion or removal at run-time.
All of this information is passed to the MUSB controller driver through a platform_driver structure defined in the glue layer as:
static struct platform_driver jz4740_driver = {
.probe = jz4740_probe,
.remove = jz4740_remove,
.driver = {
.name = "musb-jz4740",
},
};
The probe and remove function pointers are called when a matching device is detected and, respectively, released. The name string describes the device supported by this glue layer. In the current case it matches a platform_device structure declared in arch/mips/jz4740/platform.c. Note that we are not using device tree bindings here.
In order to register itself to the controller driver, the glue layer goes through a few steps, basically allocating the controller hardware resources and initialising a couple of circuits. To do so, it needs to keep track of the information used throughout these steps. This is done by defining a private jz4740_glue structure:
struct jz4740_glue {
struct device *dev;
struct platform_device *musb;
struct clk *clk;
};
The dev and musb members are both device structure variables. The first one holds generic information about the device, since it's the basic device structure, and the latter holds information more closely related to the subsystem the device is registered to. The clk variable keeps information related to the device clock operation.
Let's go through the steps of the probe function that leads the glue layer to register itself to the controller driver.
static int
The first few lines of the probe function allocate and assign the glue, musb and clk variables. The GFP_KERNEL flag (line 8) allows the allocation process to sleep and wait for memory, thus being usable in a locking situation. The PLATFORM_DEVID_AUTO flag (line 12) allows automatic allocation and management of device IDs in order to avoid device namespace collisions with explicit IDs. With devm_clk_get() (line 18) the glue layer allocates the clock -- the devm_ prefix indicates that clk_get() is managed: it automatically frees the allocated clock resource data when the device is released -- and enable it.
Then comes the registration steps:
static int
The first step is to pass the device data privately held by the glue layer on to the controller driver through platform_set_drvdata() (line 7). Next is passing on the device resources information, also privately held at that point, through platform_device_add_resources() (line 9).
Finally comes passing on the platform specific data to the controller driver (line 16). Platform data will be discussed in Device Platform Data, but here we are looking at the platform_ops function pointer (line 5) in musb_hdrc_platform_data structure (line 3). This function pointer allows the MUSB controller driver to know which function to call for device operation:
static const struct musb_platform_ops jz4740_musb_ops = {
.init = jz4740_musb_init,
.exit = jz4740_musb_exit,
};
Here we have the minimal case where only init and exit functions are called by the controller driver when needed. Fact is the JZ4740 MUSB controller is a basic controller, lacking some features found in other controllers, otherwise we may also have pointers to a few other functions like a power management function or a function to switch between OTG and non-OTG modes, for instance.
At that point of the registration process, the controller driver actually calls the init function:
static int
The goal of jz4740_musb_init() is to get hold of the transceiver driver data of the MUSB controller hardware and pass it on to the MUSB controller driver, as usual. The transceiver is the circuitry inside the controller hardware responsible for sending/receiving the USB data. Since it is an implementation of the physical layer of the OSI model, the transceiver is also referred to as PHY.
Getting hold of the MUSB PHY driver data is done with usb_get_phy() which returns a pointer to the structure containing the driver instance data. The next couple of instructions (line 12 and 14) are used as a quirk and to setup IRQ handling respectively. Quirks and IRQ handling will be discussed later in Device Quirks and Handling IRQs
static int jz4740_musb_exit(struct musb *musb)
{
usb_put_phy(musb->xceiv);
return 0;
}
Acting as the counterpart of init, the exit function releases the MUSB PHY driver when the controller hardware itself is about to be released.
Again, note that init and exit are fairly simple in this case due to the basic set of features of the JZ4740 controller hardware. When writing an musb glue layer for a more complex controller hardware, you might need to take care of more processing in those two functions.
Returning from the init function, the MUSB controller driver jumps back into the probe function:
static int jz4740_probe(struct platform_device *pdev)
{
ret = platform_device_add(musb);
if (ret) {
dev_err(&pdev->dev, "failed to register musb device\n");
goto err_clk_disable;
}
return 0;
err_clk_disable:
clk_disable_unprepare(clk);
err_platform_device_put:
platform_device_put(musb);
return ret;
}
This is the last part of the device registration process where the glue layer adds the controller hardware device to Linux kernel device hierarchy: at this stage, all known information about the device is passed on to the Linux USB core stack:
static int
Acting as the counterpart of probe, the remove function unregister the MUSB controller hardware (line 5) and disable the clock (line 6), allowing it to be gated.
Handling IRQs #
Additionally to the MUSB controller hardware basic setup and registration, the glue layer is also responsible for handling the IRQs:
static irqreturn_t
Here the glue layer mostly has to read the relevant hardware registers and pass their values on to the controller driver which will handle the actual event that triggered the IRQ.
The interrupt handler critical section is protected by the spin_lock_irqsave() and counterpart spin_unlock_irqrestore() functions (line 7 and 24 respectively), which prevent the interrupt handler code to be run by two different threads at the same time.
Then the relevant interrupt registers are read (line 9 to 11):
-
MUSB_INTRUSB: indicates which USB interrupts are currently active, -
MUSB_INTRTX: indicates which of the interrupts for TX endpoints are currently active, -
MUSB_INTRRX: indicates which of the interrupts for TX endpoints are currently active.
Note that musb_readb() is used to read 8-bit registers at most, while musb_readw() allows us to read at most 16-bit registers. There are other functions that can be used depending on the size of your device registers. See musb_io.h for more information.
Instruction on line 18 is another quirk specific to the JZ4740 USB device controller, which will be discussed later in Device Quirks.
The glue layer still needs to register the IRQ handler though. Remember the instruction on line 14 of the init function:
static int jz4740_musb_init(struct musb *musb)
{
musb->isr = jz4740_musb_interrupt;
return 0;
}
This instruction sets a pointer to the glue layer IRQ handler function, in order for the controller hardware to call the handler back when an IRQ comes from the controller hardware. The interrupt handler is now implemented and registered.
Device Platform Data #
In order to write an MUSB glue layer, you need to have some data describing the hardware capabilities of your controller hardware, which is called the platform data.
Platform data is specific to your hardware, though it may cover a broad range of devices, and is generally found somewhere in the arch/ directory, depending on your device architecture.
For instance, platform data for the JZ4740 SoC is found in arch/mips/jz4740/platform.c. In the platform.c file each device of the JZ4740 SoC is described through a set of structures.
Here is the part of arch/mips/jz4740/platform.c that covers the USB Device Controller (UDC):
/* USB Device Controller */ struct platform_device jz4740_udc_xceiv_device = ; static struct resource jz4740_udc_resources = ; struct platform_device jz4740_udc_device = ;
The jz4740_udc_xceiv_device platform device structure (line 2) describes the UDC transceiver with a name and id number.
At the time of this writing, note that usb_phy_gen_xceiv is the specific name to be used for all transceivers that are either built-in with reference USB IP or autonomous and doesn't require any PHY programming. You will need to set CONFIG_NOP_USB_XCEIV=y in the kernel configuration to make use of the corresponding transceiver driver. The id field could be set to -1 (equivalent to PLATFORM_DEVID_NONE), -2 (equivalent to PLATFORM_DEVID_AUTO) or start with 0 for the first device of this kind if we want a specific id number.
The jz4740_udc_resources resource structure (line 7) defines the UDC registers base addresses.
The first array (line 9 to 11) defines the UDC registers base memory addresses: start points to the first register memory address, end points to the last register memory address and the flags member defines the type of resource we are dealing with. So IORESOURCE_MEM is used to define the registers memory addresses. The second array (line 14 to 17) defines the UDC IRQ registers addresses. Since there is only one IRQ register available for the JZ4740 UDC, start and end point at the same address. The IORESOURCE_IRQ flag tells that we are dealing with IRQ resources, and the name mc is in fact hard-coded in the MUSB core in order for the controller driver to retrieve this IRQ resource by querying it by its name.
Finally, the jz4740_udc_device platform device structure (line 21) describes the UDC itself.
The musb-jz4740 name (line 22) defines the MUSB driver that is used for this device; remember this is in fact the name that we used in the jz4740_driver platform driver structure in Linux MUSB Basics. The id field (line 23) is set to -1 (equivalent to PLATFORM_DEVID_NONE) since we do not need an id for the device: the MUSB controller driver was already set to allocate an automatic id in Linux MUSB Basics. In the dev field we care for DMA related information here. The dma_mask field (line 25) defines the width of the DMA mask that is going to be used, and coherent_dma_mask (line 26) has the same purpose but for the alloc_coherent DMA mappings: in both cases we are using a 32 bits mask. Then the resource field (line 29) is simply a pointer to the resource structure defined before, while the num_resources field (line 28) keeps track of the number of arrays defined in the resource structure (in this case there were two resource arrays defined before).
With this quick overview of the UDC platform data at the arch/ level now done, let's get back to the MUSB glue layer specific platform data in drivers/usb/musb/jz4740.c:
static struct musb_hdrc_config jz4740_musb_config = ; static struct musb_hdrc_platform_data jz4740_musb_platform_data = ;
First the glue layer configures some aspects of the controller driver operation related to the controller hardware specifics. This is done through the jz4740_musb_config musb_hdrc_config structure.
Defining the OTG capability of the controller hardware, the multipoint member (line 3) is set to 0 (equivalent to false) since the JZ4740 UDC is not OTG compatible. Then num_eps (line 5) defines the number of USB endpoints of the controller hardware, including endpoint 0: here we have 3 endpoints + endpoint 0. Next is ram_bits (line 7) which is the width of the RAM address bus for the MUSB controller hardware. This information is needed when the controller driver cannot automatically configure endpoints by reading the relevant controller hardware registers. This issue will be discussed when we get to device quirks in Device Quirks. Last two fields (line 8 and 9) are also about device quirks: fifo_cfg points to the USB endpoints configuration table and fifo_cfg_size keeps track of the size of the number of entries in that configuration table. More on that later in Device Quirks.
Then this configuration is embedded inside jz4740_musb_platform_data musb_hdrc_platform_data structure (line 11): config is a pointer to the configuration structure itself, and mode tells the controller driver if the controller hardware may be used as MUSB_HOST only, MUSB_PERIPHERAL only or MUSB_OTG which is a dual mode.
Remember that jz4740_musb_platform_data is then used to convey platform data information as we have seen in the probe function in Linux MUSB Basics.
Device Quirks #
Completing the platform data specific to your device, you may also need to write some code in the glue layer to work around some device specific limitations. These quirks may be due to some hardware bugs, or simply be the result of an incomplete implementation of the USB On-the-Go specification.
The JZ4740 UDC exhibits such quirks, some of which we will discuss here for the sake of insight even though these might not be found in the controller hardware you are working on.
Let's get back to the init function first:
static int
Instruction on line 12 helps the MUSB controller driver to work around the fact that the controller hardware is missing registers that are used for USB endpoints configuration.
Without these registers, the controller driver is unable to read the endpoints configuration from the hardware, so we use line 12 instruction to bypass reading the configuration from silicon, and rely on a hard-coded table that describes the endpoints configuration instead:
static const struct musb_fifo_cfg jz4740_musb_fifo_cfg[] = {
{ .hw_ep_num = 1, .style = FIFO_TX, .maxpacket = 512, },
{ .hw_ep_num = 1, .style = FIFO_RX, .maxpacket = 512, },
{ .hw_ep_num = 2, .style = FIFO_TX, .maxpacket = 64, },
};
Looking at the configuration table above, we see that each endpoints is described by three fields: hw_ep_num is the endpoint number, style is its direction (either FIFO_TX for the controller driver to send packets in the controller hardware, or FIFO_RX to receive packets from hardware), and maxpacket defines the maximum size of each data packet that can be transmitted over that endpoint. Reading from the table, the controller driver knows that endpoint 1 can be used to send and receive USB data packets of 512 bytes at once (this is in fact a bulk in/out endpoint), and endpoint 2 can be used to send data packets of 64 bytes at once (this is in fact an interrupt endpoint).
Note that there is no information about endpoint 0 here: that one is implemented by default in every silicon design, with a predefined configuration according to the USB specification. For more examples of endpoint configuration tables, see musb_core.c.
Let's now get back to the interrupt handler function:
static irqreturn_t
Instruction on line 18 above is a way for the controller driver to work around the fact that some interrupt bits used for USB host mode operation are missing in the MUSB_INTRUSB register, thus left in an undefined hardware state, since this MUSB controller hardware is used in peripheral mode only. As a consequence, the glue layer masks these missing bits out to avoid parasite interrupts by doing a logical AND operation between the value read from MUSB_INTRUSB and the bits that are actually implemented in the register.
These are only a couple of the quirks found in the JZ4740 USB device controller. Some others were directly addressed in the MUSB core since the fixes were generic enough to provide a better handling of the issues for others controller hardware eventually.
Conclusion #
Writing a Linux MUSB glue layer should be a more accessible task, as this documentation tries to show the ins and outs of this exercise.
The JZ4740 USB device controller being fairly simple, I hope its glue layer serves as a good example for the curious mind. Used with the current MUSB glue layers, this documentation should provide enough guidance to get started; should anything gets out of hand, the linux-usb mailing list archive is another helpful resource to browse through.
Acknowledgements #
Many thanks to Lars-Peter Clausen and Maarten ter Huurne for answering my questions while I was writing the JZ4740 glue layer and for helping me out getting the code in good shape.
I would also like to thank the Qi-Hardware community at large for its cheerful guidance and support.
Resources #
USB Home Page: https://www.usb.org
linux-usb Mailing List Archives: https://lore.kernel.org/linux-usb
USB On-the-Go Basics: https://www.maximintegrated.com/app-notes/index.mvp/id/1822
Texas Instruments USB Configuration Wiki Page: https://web.archive.org/web/20201215135015/http://processors.wiki.ti.com/index.php/Usbgeneralpage
Writing USB Device Drivers
Peios Kernel / Hardware and drivers / Driver development / USB
Author: Greg Kroah-Hartman
Introduction #
The Linux USB subsystem has grown from supporting only two different types of devices in the 2.2.7 kernel (mice and keyboards), to over 20 different types of devices in the 2.4 kernel. Linux currently supports almost all USB class devices (standard types of devices like keyboards, mice, modems, printers and speakers) and an ever-growing number of vendor-specific devices (such as USB to serial converters, digital cameras, Ethernet devices and MP3 players). For a full list of the different USB devices currently supported, see Resources.
The remaining kinds of USB devices that do not have support on Linux are almost all vendor-specific devices. Each vendor decides to implement a custom protocol to talk to their device, so a custom driver usually needs to be created. Some vendors are open with their USB protocols and help with the creation of Linux drivers, while others do not publish them, and developers are forced to reverse-engineer. See Resources for some links to handy reverse-engineering tools.
Because each different protocol causes a new driver to be created, I have written a generic USB driver skeleton, modelled after the pci-skeleton.c file in the kernel source tree upon which many PCI network drivers have been based. This USB skeleton can be found at drivers/usb/usb-skeleton.c in the kernel source tree. In this article I will walk through the basics of the skeleton driver, explaining the different pieces and what needs to be done to customize it to your specific device.
Linux USB Basics #
If you are going to write a Linux USB driver, please become familiar with the USB protocol specification. It can be found, along with many other useful documents, at the USB home page (see Resources). An excellent introduction to the Linux USB subsystem can be found at the USB Working Devices List (see Resources). It explains how the Linux USB subsystem is structured and introduces the reader to the concept of USB urbs (USB Request Blocks), which are essential to USB drivers.
The first thing a Linux USB driver needs to do is register itself with the Linux USB subsystem, giving it some information about which devices the driver supports and which functions to call when a device supported by the driver is inserted or removed from the system. All of this information is passed to the USB subsystem in the usb_driver structure. The skeleton driver declares a usb_driver as:
static struct usb_driver skel_driver = {
.name = "skeleton",
.probe = skel_probe,
.disconnect = skel_disconnect,
.suspend = skel_suspend,
.resume = skel_resume,
.pre_reset = skel_pre_reset,
.post_reset = skel_post_reset,
.id_table = skel_table,
.supports_autosuspend = 1,
};
The variable name is a string that describes the driver. It is used in informational messages printed to the system log. The probe and disconnect function pointers are called when a device that matches the information provided in the id_table variable is either seen or removed.
The fops and minor variables are optional. Most USB drivers hook into another kernel subsystem, such as the SCSI, network or TTY subsystem. These types of drivers register themselves with the other kernel subsystem, and any user-space interactions are provided through that interface. But for drivers that do not have a matching kernel subsystem, such as MP3 players or scanners, a method of interacting with user space is needed. The USB subsystem provides a way to register a minor device number and a set of file_operations function pointers that enable this user-space interaction. The skeleton driver needs this kind of interface, so it provides a minor starting number and a pointer to its file_operations functions.
The USB driver is then registered with a call to usb_register(), usually in the driver's init function, as shown here:
static int __init usb_skel_init(void)
{
int result;
/* register this driver with the USB subsystem */
result = usb_register(&skel_driver);
if (result < 0) {
pr_err("usb_register failed for the %s driver. Error number %d\n",
skel_driver.name, result);
return -1;
}
return 0;
}
module_init(usb_skel_init);
When the driver is unloaded from the system, it needs to deregister itself with the USB subsystem. This is done with usb_deregister() function:
static void __exit usb_skel_exit(void)
{
/* deregister this driver with the USB subsystem */
usb_deregister(&skel_driver);
}
module_exit(usb_skel_exit);
To enable the linux-hotplug system to load the driver automatically when the device is plugged in, you need to create a MODULE_DEVICE_TABLE. The following code tells the hotplug scripts that this module supports a single device with a specific vendor and product ID:
/* table of devices that work with this driver */
static struct usb_device_id skel_table [] = {
{ USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, skel_table);
There are other macros that can be used in describing a struct usb_device_id for drivers that support a whole class of USB drivers. See usb.h for more information on this.
Device operation #
When a device is plugged into the USB bus that matches the device ID pattern that your driver registered with the USB core, the probe function is called. The usb_device structure, interface number and the interface ID are passed to the function:
static int skel_probe(struct usb_interface *interface,
const struct usb_device_id *id)
The driver now needs to verify that this device is actually one that it can accept. If so, it returns 0. If not, or if any error occurs during initialization, an errorcode (such as -ENOMEM or -ENODEV) is returned from the probe function.
In the skeleton driver, we determine what end points are marked as bulk-in and bulk-out. We create buffers to hold the data that will be sent and received from the device, and a USB urb to write data to the device is initialized.
Conversely, when the device is removed from the USB bus, the disconnect function is called with the device pointer. The driver needs to clean any private data that has been allocated at this time and to shut down any pending urbs that are in the USB system.
Now that the device is plugged into the system and the driver is bound to the device, any of the functions in the file_operations structure that were passed to the USB subsystem will be called from a user program trying to talk to the device. The first function called will be open, as the program tries to open the device for I/O. We increment our private usage count and save a pointer to our internal structure in the file structure. This is done so that future calls to file operations will enable the driver to determine which device the user is addressing. All of this is done with the following code:
/* increment our usage count for the device */
kref_get(&dev->kref);
/* save our object in the file's private structure */
file->private_data = dev;
After the open function is called, the read and write functions are called to receive and send data to the device. In the skel_write function, we receive a pointer to some data that the user wants to send to the device and the size of the data. The function determines how much data it can send to the device based on the size of the write urb it has created (this size depends on the size of the bulk out end point that the device has). Then it copies the data from user space to kernel space, points the urb to the data and submits the urb to the USB subsystem. This can be seen in the following code:
/* we can only write as much as 1 urb will hold */
size_t writesize = min_t(size_t, count, MAX_TRANSFER);
/* copy the data from user space into our urb */
copy_from_user(buf, user_buffer, writesize);
/* set up our urb */
usb_fill_bulk_urb(urb,
dev->udev,
usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
buf,
writesize,
skel_write_bulk_callback,
dev);
/* send the data out the bulk port */
retval = usb_submit_urb(urb, GFP_KERNEL);
if (retval) {
dev_err(&dev->interface->dev,
"%s - failed submitting write urb, error %d\n",
__func__, retval);
}
When the write urb is filled up with the proper information using the usb_fill_bulk_urb() function, we point the urb's completion callback to call our own skel_write_bulk_callback function. This function is called when the urb is finished by the USB subsystem. The callback function is called in interrupt context, so caution must be taken not to do very much processing at that time. Our implementation of skel_write_bulk_callback merely reports if the urb was completed successfully or not and then returns.
The read function works a bit differently from the write function in that we do not use an urb to transfer data from the device to the driver. Instead we call the usb_bulk_msg() function, which can be used to send or receive data from a device without having to create urbs and handle urb completion callback functions. We call the usb_bulk_msg() function, giving it a buffer into which to place any data received from the device and a timeout value. If the timeout period expires without receiving any data from the device, the function will fail and return an error message. This can be shown with the following code:
/* do an immediate bulk read to get data from the device */
retval = usb_bulk_msg (skel->dev,
usb_rcvbulkpipe (skel->dev,
skel->bulk_in_endpointAddr),
skel->bulk_in_buffer,
skel->bulk_in_size,
&count, 5000);
/* if the read was successful, copy the data to user space */
if (!retval) {
if (copy_to_user (buffer, skel->bulk_in_buffer, count))
retval = -EFAULT;
else
retval = count;
}
The usb_bulk_msg() function can be very useful for doing single reads or writes to a device; however, if you need to read or write constantly to a device, it is recommended to set up your own urbs and submit them to the USB subsystem.
When the user program releases the file handle that it has been using to talk to the device, the release function in the driver is called. In this function we decrement our private usage count and wait for possible pending writes:
/* decrement our usage count for the device */
--skel->open_count;
One of the more difficult problems that USB drivers must be able to handle smoothly is the fact that the USB device may be removed from the system at any point in time, even if a program is currently talking to it. It needs to be able to shut down any current reads and writes and notify the user-space programs that the device is no longer there. The following code (function skel_delete) is an example of how to do this:
static inline void skel_delete (struct usb_skel *dev)
{
kfree (dev->bulk_in_buffer);
if (dev->bulk_out_buffer != NULL)
usb_free_coherent (dev->udev, dev->bulk_out_size,
dev->bulk_out_buffer,
dev->write_urb->transfer_dma);
usb_free_urb (dev->write_urb);
kfree (dev);
}
If a program currently has an open handle to the device, we reset the flag device_present. For every read, write, release and other functions that expect a device to be present, the driver first checks this flag to see if the device is still present. If not, it releases that the device has disappeared, and a -ENODEV error is returned to the user-space program. When the release function is eventually called, it determines if there is no device and if not, it does the cleanup that the skel_disconnect function normally does if there are no open files on the device (see Listing 5).
Isochronous Data #
This usb-skeleton driver does not have any examples of interrupt or isochronous data being sent to or from the device. Interrupt data is sent almost exactly as bulk data is, with a few minor exceptions. Isochronous data works differently with continuous streams of data being sent to or from the device. The audio and video camera drivers are very good examples of drivers that handle isochronous data and will be useful if you also need to do this.
Conclusion #
Writing Linux USB device drivers is not a difficult task as the usb-skeleton driver shows. This driver, combined with the other current USB drivers, should provide enough examples to help a beginning author create a working driver in a minimal amount of time. The linux-usb-devel mailing list archives also contain a lot of helpful information.
Resources #
The Linux USB Project: http://www.linux-usb.org/
Linux Hotplug Project: http://linux-hotplug.sourceforge.net/
linux-usb Mailing List Archives: https://lore.kernel.org/linux-usb/
Programming Guide for Linux USB Device Drivers: https://lmu.web.psi.ch/docu/manuals/software_manuals/linux_sl/usb_linux_programming_guide.pdf
USB Home Page: https://www.usb.org