- Author
David Brownell
- Date
20 August 2004
Introduction¶
This document presents a Linux-USB “Gadget” kernel mode API, for usewithin peripherals and other USB devices that embed Linux. It providesan overview of the API structure, and shows how that fits into a systemdevelopment project. This is the first such API released on Linux toaddress a number of important problems, including:
Supports USB 2.0, for high speed devices which can stream data atseveral dozen megabytes per second.
Handles devices with dozens of endpoints just as well as ones withjust two fixed-function ones. Gadget drivers can be written sothey’re easy to port to new hardware.
Flexible enough to expose more complex USB device capabilities suchas multiple configurations, multiple interfaces, composite devices,and alternate interface settings.
USB “On-The-Go” (OTG) support, in conjunction with updates to theLinux-USB host side.
Sharing data structures and API models with the Linux-USB host sideAPI. This helps the OTG support, and looks forward to more-symmetricframeworks (where the same I/O model is used by both host and deviceside drivers).
Minimalist, so it’s easier to support new device controller hardware.I/O processing doesn’t imply large demands for memory or CPUresources.
Most Linux developers will not be able to use this API, since they haveUSB host
hardware in a PC, workstation, or server. Linux users withembedded systems are more likely to have USB peripheral hardware. Todistinguish drivers running inside such hardware from the more familiarLinux “USB device drivers”, which are host side proxies for the real USBdevices, a different term is used: the drivers inside the peripheralsare “USB gadget drivers”. In USB protocol interactions, the devicedriver is the master (or “client driver”) and the gadget driver is theslave (or “function driver”).
The gadget API resembles the host side Linux-USB API in that both usequeues of request objects to package I/O buffers, and those requests maybe submitted or canceled. They share common definitions for the standardUSB Chapter 9 messages, structures, and constants. Also, both APIsbind and unbind drivers to devices. The APIs differ in detail, since thehost side’s current URB framework exposes a number of implementationdetails and assumptions that are inappropriate for a gadget API. Whilethe model for control transfers and configuration management isnecessarily different (one side is a hardware-neutral master, the otheris a hardware-aware slave), the endpoint I/0 API used here should alsobe usable for an overhead-reduced host side API.
Structure of Gadget Drivers¶
A system running inside a USB peripheral normally has at least threelayers inside the kernel to handle USB protocol processing, and may haveadditional layers in user space code. The gadget
API is used by themiddle layer to interact with the lowest level (which directly handleshardware).
In Linux, from the bottom up, these layers are:
- USB Controller Driver
This is the lowest software level. It is the only layer that talksto hardware, through registers, fifos, dma, irqs, and the like. The
<linux/usb/gadget.h>
API abstracts the peripheral controllerendpoint hardware. That hardware is exposed through endpointobjects, which accept streams of IN/OUT buffers, and throughcallbacks that interact with gadget drivers. Since normal USBdevices only have one upstream port, they only have one of thesedrivers. The controller driver can support any number of differentgadget drivers, but only one of them can be used at a time.Examples of such controller hardware include the PCI-based NetChip2280 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 USBfunctions, using calls to the controller driver. Because suchhardware varies widely in capabilities and restrictions, and is usedin embedded environments where space is at a premium, the gadgetdriver is often configured at compile time to work with endpointssupported by one particular controller. Gadget drivers may beportable to several different controllers, using conditionalcompilation. (Recent kernels substantially simplify the workinvolved in supporting new hardware, by autoconfiguring endpointsautomatically for many bulk-oriented drivers.) Gadget driverresponsibilities include:
handling setup requests (ep0 protocol responses) possiblyincluding class-specific functionality
returning configuration and string descriptors
(re)setting configurations and interface altsettings, includingenabling and configuring endpoints
handling life cycle events, such as managing bindings tohardware, USB suspend/resume, remote wakeup, and disconnectionfrom the USB host.
managing IN and OUT transfers on all currently enabled endpoints
Such drivers may be modules of proprietary code, although thatapproach is discouraged in the Linux community.
- Upper Level
Most gadget drivers have an upper boundary that connects to someLinux driver or framework in Linux. Through that boundary flows thedata which the gadget driver produces and/or consumes throughprotocol transfers over USB. Examples include:
user mode code, using generic (gadgetfs) or application specificfiles in
/dev
networking subsystem (for network gadgets, like the CDC EthernetModel gadget driver)
data capture drivers, perhaps video4Linux or a scanner driver; ortest 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 asnetwork protocol stacks, as well as user mode applications buildingon standard POSIX system call APIs such as
open()
,close()
,read()
andwrite()
. On newer systems, POSIX Async I/O calls maybe an option. Such user mode code will not necessarily be subject tothe GNU General Public License (GPL).
OTG-capable systems will also need to include a standard Linux-USB hostside stack, with usbcore
, one or more Host Controller Drivers(HCDs), USB Device Drivers to support the OTG “Targeted PeripheralList”, 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 twonew OTG protocols (HNP and SRP). Roles switch (host to peripheral, orvice versa) using HNP during USB suspend processing, and SRP can beviewed as a more battery-friendly kind of device wakeup protocol.
Over time, reusable utilities are evolving to help make some gadgetdriver tasks simpler. For example, building configuration descriptorsfrom vectors of descriptors for the configurations interfaces andendpoints is now automated, and many drivers now use autoconfigurationto choose hardware endpoints and initialize their descriptors. Apotential example of particular interest is code implementing standardUSB-IF protocols for HID, networking, storage, or audio classes. Somedevelopers are interested in KDB or KGDB hooks, to let target hardwarebe remotely debugged. Most such USB protocol code doesn’t need to behardware-specific, any more than network protocols like X11, HTTP, orNFS are. Such gadget-side interface drivers should eventually becombined, to implement composite devices.
Kernel Mode Gadget API¶
Gadget drivers declare themselves through a structusb_gadget_driver, which is responsible for most parts of enumerationfor a struct usb_gadget. The response to a set_configuration usuallyinvolves enabling one or more of the struct usb_ep objects exposed bythe gadget, and submitting one or more struct usb_request buffers totransfer data. Understand those four data types, and their operations,and you will understand how this API works.
Note
Other than the “Chapter 9” data types, most of the significant datatypes and functions are described here.
However, some relevant information is likely omitted from what youare reading. One example of such information is endpointautoconfiguration. You’ll have to read the header file, and useexample source code (such as that for “Gadget Zero”), to fullyunderstand the API.
The part of the API implementing some basic driver capabilities isspecific to the version of the Linux kernel that’s in use. The 2.6and upper kernel versions include a driver model framework that hasno analogue on earlier kernels; so those parts of the gadget API arenot fully portable. (They are implemented on 2.4 kernels, but in adifferent way.) The driver model state is another part of this API that isignored by the kerneldoc tools.
The core API does not expose every possible hardware feature, only themost widely available ones. There are significant hardware features,such as device-to-device DMA (without temporary storage in a memorybuffer) that would be added using hardware-specific APIs.
This API allows drivers to use conditional compilation to handleendpoint capabilities of different hardware, but doesn’t require that.Hardware tends to have arbitrary restrictions, relating to transfertypes, addressing, packet sizes, buffering, and availability. As a rule,such differences only matter for “endpoint zero” logic that handlesdevice configuration and management. The API supports limited run-timedetection of capabilities, through naming conventions for endpoints.Many drivers will be able to at least partially autoconfigurethemselves. In particular, driver init sections will often have endpointautoconfiguration logic that scans the hardware’s list of endpoints tofind ones matching the driver requirements (relying on thoseconventions), to eliminate some of the most common reasons forconditional compilation.
Like the Linux-USB host side API, this API exposes the “chunky” natureof USB messages: I/O requests are in terms of one or more “packets”, andpacket boundaries are visible to drivers. Compared to RS-232 serialprotocols, USB resembles synchronous protocols like HDLC (N bytes perframe, multipoint addressing, host as the primary station and devices assecondary stations) more than asynchronous ones (tty style: 8 data bitsper frame, no parity, one stop bit). So for example the controllerdrivers won’t buffer two single byte writes into a single two-byte USBIN packet, although gadget drivers may do so when they implementprotocols where packet boundaries (and “short packets”) are notsignificant.
Driver Life Cycle¶
Gadget drivers make endpoint I/O requests to hardware without needing toknow many details of the hardware, but driver setup/configuration codeneeds to handle some differences. Use the API like this:
Register a driver for the particular device side usb controllerhardware, such as the net2280 on PCI (USB 2.0), sa11x0 or pxa25x asfound in Linux PDAs, and so on. At this point the device is logicallyin the USB ch9 initial state (
attached
), drawing no power and notusable (since it does not yet support enumeration). Any host shouldnot see the device, since it’s not activated the data line pullupused by the host to detect a device, even if VBUS power is available.Register a gadget driver that implements some higher level devicefunction. That will then bind() to a usb_gadget, which activatesthe data line pullup sometime after detecting VBUS.
The hardware driver can now start enumerating. The steps it handlesare to accept USB
power
andset_address
requests. Other steps arehandled by the gadget driver. If the gadget driver module is unloadedbefore the host starts to enumerate, steps before step 7 are skipped.The gadget driver’s
setup()
call returns usb descriptors, based bothon what the bus interface hardware provides and on the functionalitybeing implemented. That can involve alternate settings orconfigurations, unless the hardware prevents such operation. For OTGdevices, each configuration descriptor includes an OTG descriptor.The gadget driver handles the last step of enumeration, when the USBhost issues a
set_configuration
call. It enables all endpoints usedin that configuration, with all interfaces in their default settings.That involves using a list of the hardware’s endpoints, enabling eachendpoint according to its descriptor. It may also involve usingusb_gadget_vbus_draw
to let more power be drawn from VBUS, asallowed by that configuration. For OTG devices, setting aconfiguration may also involve reporting HNP capabilities through auser interface.Do real work and perform data transfers, possibly involving changesto interface settings or switching to new configurations, until thedevice is disconnect()ed from the host. Queue any number of transferrequests to each endpoint. It may be suspended and resumed severaltimes before being disconnected. On disconnect, the drivers go backto 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 drivermodule (or statically linking it into a Linux kernel) allows theperipheral device to be enumerated, but some drivers will deferenumeration until some higher level component (like a user mode daemon)enables it. Note that at this lowest level there are no policies abouthow ep0 configuration logic is implemented, except that it should obeyUSB specifications. Such issues are in the domain of gadget drivers,including knowing about implementation constraints imposed by some USBcontrollers or understanding that composite devices might happen to bebuilt 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 drivercode. 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 inthe linux/usb/ch9.h header file, which is standard inLinux 2.6+ kernels. These are the same types and constants used by host sidedrivers (and usbcore).
Core Objects and Methods¶
These are declared in <linux/usb/gadget.h>
, and are used by gadgetdrivers to interact with USB peripheral controller drivers.
- struct usb_request¶
describes one i/o request
Definition:
struct usb_request { void *buf; unsigned length; dma_addr_t dma; struct scatterlist *sg; unsigned num_sgs; unsigned num_mapped_sgs; unsigned stream_id:16; unsigned is_last:1; unsigned no_interrupt:1; unsigned zero:1; unsigned short_not_ok:1; unsigned dma_mapped:1; unsigned sg_was_mapped:1; void (*complete)(struct usb_ep *ep, struct usb_request *req); void *context; struct list_head list; unsigned frame_number; int status; unsigned actual;};
Members
buf
Buffer used for data. Always provide this; some controllersonly use PIO, or don’t use DMA for some endpoints.
length
Length of that data
dma
DMA address corresponding to ‘buf’. If you don’t set thisfield, and the usb controller needs one, it is responsiblefor mapping and unmapping the buffer.
sg
a scatterlist for SG-capable controllers.
num_sgs
number of SG entries
num_mapped_sgs
number of SG entries mapped to DMA (internal)
stream_id
The stream id, when USB3.0 bulk streams are being used
is_last
Indicates if this is the last request of a stream_id beforeswitching 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 handleddirectly 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 betreated 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 request
complete
Function called when request completes, so this request andits buffer may be re-used. The function will always be called withinterrupts 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 byteswill usually still be in flight (often in a hardware fifo).Errors (for reads or writes) stop the queue from advancinguntil the completion function returns, so that any transfersinvalidated by the error may first be dequeued.
context
For use by the completion callback
list
For use by the gadget driver.
frame_number
Reports the interval number in (micro)frame in which theisochronous transfer was transmitted or received.
status
Reports completion code, zero or a negative errno.Normally, faults block the transfer queue from advancing untilthe 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 (OUTtransfers) this may be less than the requested length. If theshort_not_ok flag is set, short reads are treated as errorseven when status otherwise indicates successful completion.Note that for writes (IN transfers) some data bytes may stillreside in a device-side FIFO when the request is reported ascomplete.
Description
These are allocated/freed through the endpoint they’re used with. Thehardware’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 lengthpacket is written (the “zero” flag), whether a short read should betreated 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 interrupttransfers. interrupt-only endpoints can be much less functional.
NOTE
this is analogous to ‘struct urb’ on the host side, except thatit’s thinner and promotes more pre-allocation.
- struct usb_ep_caps¶
endpoint capabilities description
Definition:
struct usb_ep_caps { unsigned type_control:1; unsigned type_iso:1; unsigned type_bulk:1; unsigned type_int:1; unsigned dir_in:1; unsigned dir_out:1;};
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:
struct usb_ep { void *driver_data; const char *name; const struct usb_ep_ops *ops; struct list_head ep_list; struct usb_ep_caps caps; bool claimed; bool enabled; unsigned maxpacket:16; unsigned maxpacket_limit:16; unsigned max_streams:16; unsigned mult:2; unsigned maxburst:5; u8 address; const struct usb_endpoint_descriptor *desc; const struct usb_ss_ep_comp_descriptor *comp_desc;};
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.
ep_list
the gadget’s ep_list holds all of its endpoints
caps
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.
maxpacket
The maximum packet size used on this endpoint. The initialvalue can sometimes be reduced (hardware allowing), according tothe endpoint descriptor used to configure the endpoint.
maxpacket_limit
The maximum packet size value which can be handled by thisendpoint. It’s set once by UDC driver when endpoint is initialized, andshould not be changed. Should not be confused with maxpacket.
max_streams
The maximum number of streams supportedby this EP (0 - 16, actual number is 2^n)
mult
multiplier, ‘mult’ value for SS Isoc EPs
maxburst
the maximum number of bursts supported by this EP (for usb3)
address
used to identify the endpoint when finding descriptor thatmatches connection speed
desc
endpoint descriptor. This pointer is set before the endpoint isenabled and remains valid until the endpoint is disabled.
comp_desc
In case of SuperSpeed support, this is the endpoint companiondescriptor that is used to configure the endpoint
Description
the bus controller driver lists all the general purpose endpoints ingadget->ep_list. the control endpoint (gadget->ep0) is not in that list,and is accessed only in response to a driver setup() callback.
- struct usb_gadget¶
represents a usb device
Definition:
struct usb_gadget { struct work_struct work; struct usb_udc *udc; const struct usb_gadget_ops *ops; struct usb_ep *ep0; struct list_head ep_list; enum usb_device_speed speed; enum usb_device_speed max_speed; enum usb_ssp_rate ssp_rate; enum usb_ssp_rate max_ssp_rate; enum usb_device_state state; const char *name; struct device dev; unsigned isoch_delay; unsigned out_epnum; unsigned in_epnum; unsigned mA; struct usb_otg_caps *otg_caps; unsigned sg_supported:1; unsigned is_otg:1; unsigned is_a_peripheral:1; unsigned b_hnp_enable:1; unsigned a_hnp_support:1; unsigned a_alt_hnp_support:1; unsigned hnp_polling_support:1; unsigned host_request_flag:1; unsigned quirk_ep_out_aligned_size:1; unsigned quirk_altset_not_supp:1; unsigned quirk_stall_not_supp:1; unsigned quirk_zlp_not_supp:1; unsigned quirk_avoids_skb_reserve:1; unsigned is_selfpowered:1; unsigned deactivated:1; unsigned connected:1; unsigned lpm_capable:1; unsigned wakeup_capable:1; unsigned wakeup_armed:1; int irq; int id_number;};
Members
work
(internal use) Workqueue to be used for sysfs_notify()
udc
struct usb_udc pointer for this gadget
ops
Function pointers used to access hardware-specific operations.
ep0
Endpoint zero, used when reading or writing responses todriver setup() requests
ep_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 thisand 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 UDCcan handle. The UDC must support this and all slower speeds and lowernumber of lanes.
state
the state we are now (attached, suspended, configured, etc)
name
Identifies the controller hardware type. Used in diagnosticsand sometimes configuration.
dev
Driver model state for this abstract device.
isoch_delay
value from Set Isoch Delay request. Only valid on SS/SSP
out_epnum
last used out ep number
in_epnum
last used in ep number
mA
last set mA value
otg_caps
OTG capabilities of this gadget.
sg_supported
true if we can handle scatter-gather
is_otg
True if the USB device port uses a Mini-AB jack, so that thegadget driver must provide a USB OTG descriptor.
is_a_peripheral
False unless is_otg, the “A” end of a USB cableis in the Mini-AB jack, and HNP has been used to switch rolesso that the “A” device currently acts as A-Peripheral, not A-Host.
b_hnp_enable
OTG device feature flag, indicating that the A-Hostenabled HNP support.
a_hnp_support
OTG device feature flag, indicating that the A-Hostsupports HNP at this port.
a_alt_hnp_support
OTG device feature flag, indicating that the A-Hostonly supports HNP on a different root port.
hnp_polling_support
OTG device feature flag, indicating if the OTG devicein peripheral mode can support HNP polling.
host_request_flag
OTG device feature flag, indicating if A-Peripheralor B-Peripheral wants to take host role.
quirk_ep_out_aligned_size
epout requires buffer size to be aligned toMaxPacketSize.
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 avoid skb_reserve() inu_ether.c to improve performance.
is_selfpowered
if the gadget is self-powered.
deactivated
True if gadget is deactivated - in deactivated state it cannotbe connected.
connected
True if gadget is connected.
lpm_capable
If the gadget max_speed is FULL or HIGH, this flagindicates 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 devicefunctions, handling all usb configurations and interfaces. Gadgetdrivers talk to hardware-specific code indirectly, through ops vectors.That insulates the gadget driver from hardware details, and packagesthe 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 areread-only to the gadget driver. That driver data is part of the“driver model” infrastructure in 2.6 (and later) kernels, and forearlier systems is grouped in a similar structure that’s not knownto the rest of the kernel.
Values of the three OTG device feature flags are updated before thesetup() call corresponding to USB_REQ_SET_CONFIGURATION, and beforedriver suspend() calls. They are valid only when is_otg, and when thedevice is acting as a B-Peripheral (so is_a_peripheral is false).
- size_t usb_ep_align(struct usb_ep *ep, size_t len)¶
returns len aligned to ep’s maxpacketsize.
Parameters
struct usb_ep *ep
the endpoint whose maxpacketsize is used to align len
size_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.
- size_t usb_ep_align_maybe(struct usb_gadget *g, struct usb_ep *ep, size_t len)¶
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 quirk
struct usb_ep *ep
the endpoint whose maxpacketsize is used to align len
size_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 maybealign buffer’s size to an ep’s maxpacketsize.
- int gadget_is_altset_supported(struct usb_gadget *g)¶
return true iff the hardware supports altsettings
Parameters
struct usb_gadget *g
controller to check for quirk
- int gadget_is_stall_supported(struct usb_gadget *g)¶
return true iff the hardware supports stalling
Parameters
struct usb_gadget *g
controller to check for quirk
- int gadget_is_zlp_supported(struct usb_gadget *g)¶
return true iff the hardware supports zlp
Parameters
struct usb_gadget *g
controller to check for quirk
- int gadget_avoids_skb_reserve(struct usb_gadget *g)¶
return true iff the hardware would like to avoid skb_reserve to improve performance.
Parameters
struct usb_gadget *g
controller to check for quirk
- int gadget_is_dualspeed(struct usb_gadget *g)¶
return true iff the hardware handles high speed
Parameters
struct usb_gadget *g
controller that might support both high and full speeds
- int gadget_is_superspeed(struct usb_gadget *g)¶
return true if the hardware handles superspeed
Parameters
struct usb_gadget *g
controller that might support superspeed
- int gadget_is_superspeed_plus(struct usb_gadget *g)¶
return true if the hardware handles superspeed plus
Parameters
struct usb_gadget *g
controller that might support superspeed plus
- int gadget_is_otg(struct usb_gadget *g)¶
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 sometimesrun on boards which only have a Mini-B (or Mini-A) connector.
- struct usb_gadget_driver¶
driver for usb gadget devices
Definition:
struct usb_gadget_driver { char *function; enum usb_device_speed max_speed; int (*bind)(struct usb_gadget *gadget, struct usb_gadget_driver *driver); void (*unbind)(struct usb_gadget *); int (*setup)(struct usb_gadget *, const struct usb_ctrlrequest *); void (*disconnect)(struct usb_gadget *); void (*suspend)(struct usb_gadget *); void (*resume)(struct usb_gadget *); void (*reset)(struct usb_gadget *); struct device_driver driver; char *udc_name; unsigned match_existing_only:1; bool is_bound:1;};
Members
function
String describing the gadget’s function
max_speed
Highest speed the driver handles.
bind
the driver’s bind callback
unbind
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 bythe hardware level driver. Most calls must be handled bythe gadget driver, including descriptor and configurationmanagement. The 16 bit members of the setup data are inUSB byte order. Called in_interrupt; this may not sleep. Driverqueues 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; thismay not sleep. Some devices can’t detect disconnect, so this mightnot 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 driversand 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 failthe driver registration
is_bound
Allow a driver to be bound to only one gadget
Description
Devices are disabled till a gadget driver successfully bind()s, whichmeans the driver will handle setup() requests needed to enumerate (andmeet “chapter 9” requirements) then do some useful work.
If gadget->is_otg is true, the gadget driver must provide an OTGdescriptor during enumeration, or else fail the bind() call. In suchcases, no USB traffic may flow until both bind() returns withouthaving called usb_gadget_disconnect(), and the USB host stack hasinitialized.
Drivers use hardware-specific knowledge to configure the usb hardware.endpoint addressing is only one of several hardware characteristics thatare in descriptors the ep0 implementation returns from setup() calls.
Except for ep0 implementation, most driver code shouldn’t need change torun on top of different usb controllers. It’ll use endpoints set up bythat ep0 implementation.
The usb controller driver handles a few standard usb requests. Thoseinclude set_address, and feature flags for devices, interfaces, andendpoints (the get_status, set_feature, and clear_feature requests).
Accordingly, the driver’s setup() callback must always implement allget_descriptor requests, returning at least a device descriptor anda configuration descriptor. Drivers must make sure the endpointdescriptors match any hardware constraints. Some hardware also constrainsother 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, andget_interface. Setting a configuration (or interface) is whereendpoints should be activated or (config 0) shut down.
The gadget driver’s setup() callback does not have to queue a response toep0 within the setup() call, the driver can do it after setup() returns.The UDC driver must wait until such a response is queued before proceedingwith the data/status stages of the control transfer.
(Note that only the default control endpoint is supported. Neitherhosts nor devices generally support control traffic except to ep0.)
Most devices will ignore USB suspend/resume operations, and so willnot provide those callbacks. However, some may need to change modeswhen the host is not longer directing those activities. For example,local controls (buttons, dials, etc) may need to be re-enabled sincethe (remote) host can’t do that any longer; or an error state mightbe cleared, to make the device behave identically whether or notpower is maintained.
NOTE
Currently, a number of UDC drivers rely on USB_GADGET_DELAYED_STATUSbeing returned from the setup() callback, which is a bug. See the commentnext to USB_GADGET_DELAYED_STATUS for details.
- int usb_gadget_register_driver_owner(struct usb_gadget_driver *driver, struct module *owner, const char *mod_name)¶
register a gadget driver
Parameters
struct usb_gadget_driver *driver
the driver being registered
struct module *owner
the driver module
const 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 thisregistration call returns. It’s expected that the bind() function willbe in init sections.
Use the macro defined below instead of calling this directly.
- int usb_gadget_unregister_driver(struct usb_gadget_driver *driver)¶
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 isgoing away. If the controller is connected to a USB host,it will first disconnect(). The driver is also requestedto unbind() and clean up any device state, before this procedurefinally returns. It’s expected that the unbind() functionswill be in exit sections, so may not be linked in some kernels.
- struct usb_string¶
wraps a C string and its USB id
Definition:
struct usb_string { u8 id; const char *s;};
Members
id
the (nonzero) ID for this string
s
the string, in UTF-8 encoding
Description
If you’re using usb_gadget_get_string(), use this to wrap a stringtogether with its ID.
- struct usb_gadget_strings¶
a set of USB strings in a given language
Definition:
struct usb_gadget_strings { u16 language; struct usb_string *strings;};
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 thestrings for a given language.
- void usb_free_descriptors(struct usb_descriptor_header **v)¶
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 someoptional utilities are provided to simplify common tasks. Theseutilities include endpoint autoconfiguration.
- int usb_gadget_get_string(const struct usb_gadget_strings *table, int id, u8 *buf)¶
fill out a string descriptor
Parameters
const struct usb_gadget_strings *table
of c strings encoded using UTF-8
int id
string id, from low byte of wValue in get string descriptor
u8 *buf
at least 256 bytes, must be 16-bit aligned
Description
Finds the UTF-8 string matching the ID, and converts it into astring 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 withthe eighth bit set will be multibyte UTF-8 characters, not ISO-8859/1characters (which are also widely used in C strings).
- bool usb_validate_langid(u16 langid)¶
validate usb language identifiers
Parameters
u16 langid
usb language identifier
Description
Returns true for valid language identifier, otherwise false.
- int usb_descriptor_fillbuf(void *buf, unsigned buflen, const struct usb_descriptor_header **src)¶
fill buffer with descriptors
Parameters
void *buf
Buffer to be filled
unsigned buflen
Size of buf
const struct usb_descriptor_header **src
Array of descriptor pointers, terminated by null pointer.
Description
Copies descriptors into the buffer, returning the length or anegative error code if they can’t all be copied. Useful whenassembling descriptors for an associated set of interfaces usedas part of configuring a composite device; or in other cases wheresets of descriptors need to be marshaled.
- int usb_gadget_config_buf(const struct usb_config_descriptor *config, void *buf, unsigned length, const struct usb_descriptor_header **desc)¶
builts a complete configuration descriptor
Parameters
const struct usb_config_descriptor *config
Header for the descriptor, including characteristics suchas power requirements and number of interfaces.
void *buf
Buffer for the resulting configuration descriptor.
unsigned length
Length of buffer. If this is not big enough to hold theentire configuration descriptor, an error code will be returned.
const struct usb_descriptor_header **desc
Null-terminated vector of pointers to the descriptors (interface,endpoint, etc) defining all functions in this device configuration.
Description
This copies descriptors into the response buffer, building a descriptorfor that configuration. It returns the buffer length or a negativestatus code. The config.wTotalLength field is set to match the lengthof the result, but other descriptor fields (including power usage andinterface count) must be set by the caller.
Gadget drivers could use this when constructing a config descriptorin response to USB_REQ_GET_DESCRIPTOR. They will need to patch theresulting bDescriptorType value if USB_DT_OTHER_SPEED_CONFIG is needed.
- struct usb_descriptor_header **usb_copy_descriptors(struct usb_descriptor_header **src)¶
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 useis to support usb_function objects which can have multiple copies,each needing different descriptors. Functions may have statictables of descriptors, which are used as templates and customizedwith 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 alsomulti-configuration devices (also more than one function, but notnecessarily sharing a given configuration). There is however an optionalframework 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_configurationinstances. Each such configuration includes at least one structusb_function, which packages a user visible role such as “networklink” 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:
struct usb_os_desc_ext_prop { struct list_head entry; u8 type; int name_len; char *name; int data_len; char *data; struct config_item item;};
Members
entry
used to keep a list of extended properties
type
Extended Property type
name_len
Extended Property unicode name length, including terminating ‘0’
name
Extended Property name
data_len
Length of Extended Property blob (for unicode store double len)
data
Extended Property blob
item
Represents this Extended Property in configfs
- struct usb_os_desc¶
describes OS descriptors associated with one interface
Definition:
struct usb_os_desc { char *ext_compat_id; struct list_head ext_prop; int ext_prop_len; int ext_prop_count; struct mutex *opts_mutex; struct config_group group; struct module *owner;};
Members
ext_compat_id
16 bytes of “Compatible ID” and “Subcompatible ID”
ext_prop
Extended Properties list
ext_prop_len
Total length of Extended Properties blobs
ext_prop_count
Number of Extended Properties
opts_mutex
Optional mutex protecting config data of a usb_function_instance
group
Represents OS descriptors associated with an interface in configfs
owner
Module associated with this OS descriptor
- struct usb_os_desc_table¶
describes OS descriptors associated with one interface of a usb_function
Definition:
struct usb_os_desc_table { int if_id; struct usb_os_desc *os_desc;};
Members
if_id
Interface id
os_desc
“Extended Compatibility ID” and “Extended Properties” of theinterface
Description
Each interface can have at most one “Extended Compatibility ID” and anumber of “Extended Properties”.
- struct usb_function¶
describes one function of a configuration
Definition:
struct usb_function { const char *name; struct usb_gadget_strings **strings; struct usb_descriptor_header **fs_descriptors; struct usb_descriptor_header **hs_descriptors; struct usb_descriptor_header **ss_descriptors; struct usb_descriptor_header **ssp_descriptors; struct usb_configuration *config; struct usb_os_desc_table *os_desc_table; unsigned os_desc_n; int (*bind)(struct usb_configuration *, struct usb_function *); void (*unbind)(struct usb_configuration *, struct usb_function *); void (*free_func)(struct usb_function *f); struct module *mod; int (*set_alt)(struct usb_function *, unsigned interface, unsigned alt); int (*get_alt)(struct usb_function *, unsigned interface); void (*disable)(struct usb_function *); int (*setup)(struct usb_function *, const struct usb_ctrlrequest *); bool (*req_match)(struct usb_function *,const struct usb_ctrlrequest *, bool config0); void (*suspend)(struct usb_function *); void (*resume)(struct usb_function *); int (*get_status)(struct usb_function *); int (*func_suspend)(struct usb_function *, u8 suspend_opt); bool func_suspended; bool func_wakeup_armed;};
Members
name
For diagnostics, identifies the function.
strings
tables of strings, keyed by identifiers assigned during bind()and by language IDs provided in control requests
fs_descriptors
Table of full (or low) speed descriptors, using interface andstring 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 andstring 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 andstring identifiers assigned during bind(). If thispointer is null after initiation, the function will notbe available at super speed.
ssp_descriptors
Table of super speed plus descriptors, usinginterface and string identifiers assigned during bind(). Ifthis pointer is null after initiation, the function will notbe available at super speed plus.
config
assigned when usb_add_function() is called; this is theconfiguration with which this function is associated.
os_desc_table
Table of (interface id, os descriptors) pairs. The functioncan expose more than one interface. If an interface is a member ofan IAD, only the first interface of IAD has its entry in the table.
os_desc_n
Number of entries in os_desc_table
bind
Before the gadget can register, all of its functions bind() to theavailable resources including string and interface identifiers usedin interface or class descriptors; endpoints; I/O buffers; and so on.
unbind
Reverses bind; called as a side effect of unregistering thedriver 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 mayinitialize usb_ep.driver data at this time (when it is used).Note that setting an interface to its current altsetting resetsinterface 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. Reasonsinclude 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 whenSetFeature(FUNCTION_SUSPEND) is reseived
func_suspended
Indicates whether the function is in function suspend state.
func_wakeup_armed
Indicates whether the function is armed by the host forwakeup signaling.
Description
A single USB function uses one or more interfaces, and should in mostcases support operation at both full and high speeds. Each function isassociated by usb_add_function() with a one configuration; that functioncauses bind() to be called so resources can be allocated as part ofsetting up a gadget driver. Those resources include endpoints, whichshould be allocated using usb_ep_autoconfig().
To support dual speed operation, a function driver provides descriptorsfor both high and full speed operation. Except in rare cases that don’tinvolve 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 functioncan only be activated once. If the function needs to be exposed in morethan one configuration at a given speed, it needs to support multipleusb_function structures (one for each configuration).
A more complex strategy might encapsulate a usb_function structure insidea driver-specific instance structure to allows multiple activations. Anexample of multiple activations might be a CDC ACM function that supportstwo or more distinct instances within the same configuration, providingseveral independent logical data links to a USB host.
- struct usb_configuration¶
represents one gadget configuration
Definition:
struct usb_configuration { const char *label; struct usb_gadget_strings **strings; const struct usb_descriptor_header **descriptors; void (*unbind)(struct usb_configuration *); int (*setup)(struct usb_configuration *, const struct usb_ctrlrequest *); u8 bConfigurationValue; u8 iConfiguration; u8 bmAttributes; u16 MaxPower; struct usb_composite_dev *cdev;};
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 thedriver which added this configuration.
setup
Used to delegate control requests that aren’t handled by standarddevice 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 theconfiguration descriptor after considering the bus speed.
cdev
assigned by usb_add_config() before calling bind(); this isthe device associated with this configuration.
Description
Configurations are building blocks for gadget drivers structured aroundfunction drivers. Simple USB gadgets require only one function and oneconfiguration, and handle dual-speed hardware by always providing the samefunctionality. Slightly more complex gadgets may have more than onesingle-function configuration at a given speed; or have configurationsthat only work at one speed.
Composite devices are, by definition, ones with configurations whichinclude more than one function.
The lifecycle of a usb_configuration includes allocation, initializationof the fields described above, and calling usb_add_config() to set upinternal data and bind it to a specific device. The configuration’sbind() method is then used to initialize all the functions and thencall usb_add_function() for them.
Those functions would normally be independent of each other, but that’snot mandatory. CDC WMC devices are an example where functions oftendepend on other functions, with some functions subsidiary to others.Such interdependency may be managed in any way, so long as all of thedescriptors complete by the time the composite driver returns fromits bind() routine.
- struct usb_composite_driver¶
groups configurations into a gadget
Definition:
struct usb_composite_driver { const char *name; const struct usb_device_descriptor *dev; struct usb_gadget_strings **strings; enum usb_device_speed max_speed; unsigned needs_serial:1; int (*bind)(struct usb_composite_dev *cdev); int (*unbind)(struct usb_composite_dev *); void (*disconnect)(struct usb_composite_dev *); void (*suspend)(struct usb_composite_dev *); void (*resume)(struct usb_composite_dev *); struct usb_gadget_driver gadget_driver;};
Members
name
For diagnostics, identifies the driver.
dev
Template descriptor for the device, including default deviceidentifiers.
strings
tables of strings, keyed by identifiers assigned during bindand language IDs provided in control requests. Note: The first entriesare predefined. The first entry that may be used isUSB_GADGET_FIRST_AVAIL_IDX
max_speed
Highest speed the driver supports.
needs_serial
set to 1 if the gadget needs userspace to providea serial number. If one is not provided, warning will be printed.
bind
(REQUIRED) Used to allocate resources that are shared across thewhole device, such as string IDs, and add its configurations usingusb_add_config(). This may fail by returning a negative errnovalue; it should return zero on successful initialization.
unbind
Reverses bind; called as a side effect of unregisteringthis driver.
disconnect
optional driver disconnect method
suspend
Notifies when the host stops sending USB traffic,after function notifications
resume
Notifies configuration when the host restarts USB traffic,before function notifications
gadget_driver
Gadget driver controlling this driver
Description
Devices default to reporting self powered operation. Devices which relyon bus powered operation should report this in their bind method.
Before returning from bind, various fields in the template descriptormay be overridden. These include the idVendor/idProduct/bcdDevice valuesnormally to bind the appropriate host side driver, and the three strings(iManufacturer, iProduct, iSerialNumber) normally used to provide usermeaningful device identifiers. (The strings will not be defined unlessthey are defined in dev and strings.) The correct ep0 maxpacket sizeis also reported, as defined by the underlying controller driver.
- module_usb_composite_driver¶
module_usb_composite_driver (__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 anythingspecial in module init/exit. This eliminates a lot of boilerplate. Eachmodule 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:
struct usb_composite_dev { struct usb_gadget *gadget; struct usb_request *req; struct usb_request *os_desc_req; struct usb_configuration *config; u8 qw_sign[OS_STRING_QW_SIGN_LEN]; u8 b_vendor_code; struct usb_configuration *os_desc_config; unsigned int use_os_string:1; u16 bcd_webusb_version; u8 b_webusb_vendor_code; char landing_page[WEBUSB_URL_RAW_MAX_LENGTH]; unsigned int use_webusb:1; unsigned int setup_pending:1; unsigned int os_desc_pending:1;};
Members
gadget
read-only, abstracts the gadget’s usb peripheral controller
req
used for control responses; buffer is pre-allocated
os_desc_req
used for OS descriptors responses; buffer is pre-allocated
config
the currently active configuration
qw_sign
qwSignature part of the OS string
b_vendor_code
bMS_VendorCode part of the OS string
os_desc_config
the configuration to be used with OS descriptors
use_os_string
false by default, interested gadgets set it
bcd_webusb_version
0x0100 by default, WebUSB specification version
b_webusb_vendor_code
0x0 by default, vendor code for WebUSB
landing_page
empty by default, landing page to announce in WebUSB
use_webusb
false by default, interested gadgets set it
setup_pending
true when setup request is queued but not completed
os_desc_pending
true when os_desc request is queued but not completed
Description
One of these devices is allocated and initialized before theassociated device driver’s bind() is called.
- int config_ep_by_speed_and_alt(struct usb_gadget *g, struct usb_function *f, struct usb_ep *_ep, u8 alt)¶
configures the given endpoint according to gadget speed.
Parameters
struct usb_gadget *g
pointer to the gadget
struct usb_function *f
usb function
struct usb_ep *_ep
the endpoint to configure
u8 alt
alternate setting number
Return
error code, 0 on success
Description
This function chooses the right descriptors for a givenendpoint according to gadget speed and saves it in theendpoint desc field. If the endpoint already has a descriptorassigned to it - overwrites it with currently correspondingdescriptor. The endpoint maxpacket field is updated accordingto the chosen descriptor.
Note
the supplied function should hold all the descriptorsfor supported speeds
- int config_ep_by_speed(struct usb_gadget *g, struct usb_function *f, struct usb_ep *_ep)¶
configures the given endpoint according to gadget speed.
Parameters
struct usb_gadget *g
pointer to the gadget
struct usb_function *f
usb function
struct usb_ep *_ep
the endpoint to configure
Return
error code, 0 on success
Description
This function chooses the right descriptors for a givenendpoint according to gadget speed and saves it in theendpoint desc field. If the endpoint already has a descriptorassigned to it - overwrites it with currently correspondingdescriptor. The endpoint maxpacket field is updated accordingto the chosen descriptor.
Note
the supplied function should hold all the descriptorsfor supported speeds
- int usb_add_function(struct usb_configuration *config, struct usb_function *function)¶
add a function to a configuration
Parameters
struct usb_configuration *config
the configuration
struct usb_function *function
the function being added
Context
single threaded during gadget setup
Description
After initialization, each configuration must have one or morefunctions added to it. Adding a function involves calling its bind()method to allocate resources such as interface and string identifiersand endpoints.
This function returns the value of the function’s bind(), which iszero for success else a negative errno value.
- int usb_function_deactivate(struct usb_function *function)¶
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 bypreventing the data line pullup from being activated. This isnormally called during bind() processing to change from theinitial “ready to respond” state, or when a required resourcebecomes available.
For example, drivers that serve as a passthrough to a userspacedaemon 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 peripheraldata pullups.
Returns zero on success, else negative errno.
- int usb_function_activate(struct usb_function *function)¶
allow function and gadget enumeration
Parameters
struct usb_function *function
function on which usb_function_activate() was called
Description
Reverses effect of usb_function_deactivate(). If no more functionsare delaying their activation, the gadget driver will respond tohost enumeration procedures.
Returns zero on success, else negative errno.
- int usb_interface_id(struct usb_configuration *config, struct usb_function *function)¶
allocate an unused interface ID
Parameters
struct usb_configuration *config
configuration associated with the interface
struct usb_function *function
function handling the interface
Context
single threaded during gadget setup
Description
usb_interface_id() is called from usb_function.bind() callbacks toallocate new interface IDs. The function driver will then store thatID in interface, association, CDC union, and other descriptors. Itwill also handle any control requests targeted at that interface,particularly changing its altsetting via set_alt(). There mayalso be class-specific or vendor-specific requests to handle.
All interface identifier should be allocated using this routine, toensure that for example different functions don’t wrongly assigndifferent meanings to the same identifier. Note that since interfaceidentifiers are configuration-specific, functions used in more thanone configuration (or more than once in a given configuration) needmultiple versions of the relevant descriptors.
Returns the interface ID which was allocated; or -ENODEV if nomore interface IDs can be allocated.
- int usb_func_wakeup(struct usb_function *func)¶
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 usbfunctions are put in function suspend state and armed for functionremote wakeup. On completion, function wake notification is sent. Ifthe device is in low power state it tries to bring the device to activestate before sending the wake notification. Since it is a synchronouscall, 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.
- int usb_add_config(struct usb_composite_dev *cdev, struct usb_configuration *config, int (*bind)(struct usb_configuration*))¶
add a configuration to a device.
Parameters
struct usb_composite_dev *cdev
wraps the USB gadget
struct usb_configuration *config
the configuration, with bConfigurationValue assigned
int (*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 toadd each of the configurations it supports, using this routine.
This function returns the value of the configuration’s bind(), whichis zero for success else a negative errno value. Binding configurationsassigns global resources including string IDs, and per-configurationresources such as interface IDs and endpoints.
- int usb_string_id(struct usb_composite_dev *cdev)¶
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 allocatestring IDs. Drivers for functions, configurations, or gadgets willthen 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 ensurethat for example different functions don’t wrongly assign differentmeanings to the same identifier.
- int usb_string_ids_tab(struct usb_composite_dev *cdev, struct usb_string *str)¶
allocate unused string IDs in batch
Parameters
struct usb_composite_dev *cdev
the device whose string descriptor IDs are being allocated
struct 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 allocatestring IDs. Drivers for functions, configurations, or gadgets willthen copy IDs from the string table to the appropriate descriptorsand 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 forexample different functions don’t wrongly assign different meaningsto the same identifier.
- struct usb_string *usb_gstrings_attach(struct usb_composite_dev *cdev, struct usb_gadget_strings **sp, unsigned n_strings)¶
attach gadget strings to a cdev and assign ids
Parameters
struct usb_composite_dev *cdev
the device whose string descriptor IDs are being allocatedand 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_stringand attach it to the cdev. The actual string (usb_string.s) will not becopied but only a referenced will be made. The struct usb_gadget_stringsarray may contain multiple languages and should be NULL terminated.The ->language pointer of each struct usb_gadget_strings has to contain thesame amount of entries.For instance: sp[0] is en-US, sp[1] is es-ES. It is expected that the firstusb_string entry of es-ES contains the translation of the first usb_stringentry of en-US. Therefore both entries become the same id assign.
- int usb_string_ids_n(struct usb_composite_dev *c, unsigned n)¶
allocate unused string IDs in batch
Parameters
struct usb_composite_dev *c
the device whose string descriptor IDs are being allocated
unsigned 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 nowvalid IDs. At least provided that n is non-zero because if itis, returns last requested ID which is now very useful information.
usb_string_ids_n() is called from bind() callbacks to allocatestring IDs. Drivers for functions, configurations, or gadgets willthen 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 forexample different functions don’t wrongly assign different meaningsto the same identifier.
- int usb_composite_probe(struct usb_composite_driver *driver)¶
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 driverframework. The return value is zero, or a negative errno value.Those values normally come from the driver’s bind method, which doesall the work of setting up the driver to match the hardware.
On successful return, the gadget is ready to respond to requests fromthe host, unless one of its components invokes usb_gadget_disconnect()while it was binding. That would usually be done in order to wait forsome userspace participation.
- void usb_composite_unregister(struct usb_composite_driver *driver)¶
unregister a composite driver
Parameters
struct usb_composite_driver *driver
the driver to unregister
Description
This function is used to unregister drivers using the compositedriver framework.
- void usb_composite_setup_continue(struct usb_composite_dev *cdev)¶
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 continuewith the control transfer’s data/status stage in case it had requested todelay 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/statusstages by returning USB_GADGET_DELAYED_STATUS.
Composite Device Functions¶
At this writing, a few of the current gadget drivers have been convertedto 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 thenet2280
driver module. The driver supports Linux kernel versions 2.4and 2.6; contact NetChip Technologies for development boards and productinformation.
Other hardware working in the gadget
framework includes: Intel’s PXA25x 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 frameworkfor several other USB device controllers, with plans to make many ofthem be widely available.
A partial USB simulator, the dummy_hcd
driver, is available. It canact like a net2280, a pxa25x, or an sa11x0 in terms of availableendpoints and device speeds; and it simulates control, bulk, and to someextent interrupt transfers. That lets you develop some parts of a gadgetdriver on a normal PC, without any special hardware, and perhaps withthe assistance of tools such as GDB running with User Mode Linux. Atleast one person has expressed interest in adapting that approach,hooking it up to a simulator for a microcontroller. Such simulators canhelp debug subsystems where the runtime hardware is unfriendly tosoftware development, or is not yet available.
Support for other controllers is expected to be developed andcontributed over time, as this driver framework evolves.
Gadget Drivers¶
In addition to Gadget Zero (used primarily for testing and developmentwith drivers for usb controller hardware), other gadget drivers exist.
There’s an ethernet
gadget driver, which implements one of the mostuseful Communications Device Class (CDC) models. One of the standardsfor cable modem interoperability even specifies the use of this ethernetmodel as one of two mandatory options. Gadgets using this code look to aUSB host as if they’re an Ethernet adapter. It provides access to anetwork where the gadget’s CPU is one host, which could easily bebridging, routing, or firewalling access to other networks. Since somehardware can’t fully implement the CDC Ethernet requirements, thisdriver also implements a “good parts only” subset of CDC Ethernet. (Thatsubset doesn’t advertise itself as CDC Ethernet, to avoid creatingproblems.)
Support for Microsoft’s RNDIS
protocol has been contributed byPengutronix and Auerswald GmbH. This is like CDC Ethernet, but it runson more slightly USB hardware (but less than the CDC subset). However,its main claim to fame is being able to connect directly to recentversions 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 singlefile descriptor. I/O is done using normal read()
and read()
calls.Familiar tools like GDB and pthreads can be used to develop and debuguser mode drivers, so that once a robust controller driver is availablemany applications for it won’t require new kernel mode software. Linux2.6 Async I/O (AIO) support is available, so that user mode softwarecan stream data with only slightly more overhead than a kernel driver.
There’s a USB Mass Storage class driver, which provides a differentsolution for interoperability with systems such as MS-Windows and MacOS.That Mass Storage driver uses a file or block device as backing storefor a drive, like the loop
driver. The USB host uses the BBB, CB, orCBI versions of the mass storage class specification, using transparentSCSI 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, likea USB modem, and so on most hardware it can interoperate easily withMS-Windows. One interesting use of that driver is in boot firmware (likea BIOS), which can sometimes use that model with very small systemswithout real serial lines.
Support for other kinds of gadget is expected to be developed andcontributed over time, as this driver framework evolves.
USB On-The-GO (OTG)¶
USB OTG support on Linux 2.6 was initially developed by TexasInstruments for OMAP 16xx and 17xx seriesprocessors. Other OTG systems should work in similar ways, but thehardware level details could be very different.
Systems need specialized hardware support to implement OTG, notablyincluding a special Mini-AB jack and associated transceiver to supportDual-Role operation: they can act either as a host, using the standardLinux-USB host side driver stack, or as a peripheral, using thisgadget
framework. To do that, the system software relies on smalladditions to those programming interfaces, and on a new internalcomponent (here called an “OTG Controller”) affecting which driver stackconnects to the OTG port. In each role, the system can re-use theexisting pool of hardware-neutral drivers, layered on top of thecontroller driver interfaces (usb_bus
or usb_gadget).Such drivers need at most minor changes, and most of the calls added tosupport OTG can also benefit non-OTG products.
Gadget drivers test the
is_otg
flag, and use it to determinewhether or not to include an OTG descriptor in each of theirconfigurations.Gadget drivers may need changes to support the two new OTG protocols,exposed in new gadget attributes such as
b_hnp_enable
flag. HNPsupport should be reported through a user interface (two LEDs couldsuffice), and is triggered in some cases when the host suspends theperipheral. SRP support can be user-initiated just like remotewakeup, probably by pressing the same button.On the host side, USB device drivers need to be taught to trigger HNPat appropriate moments, using
usb_suspend_device()
. That alsoconserves battery power, which is useful even for non-OTGconfigurations.Also on the host side, a driver must support the OTG “TargetedPeripheral List”. That’s just a whitelist, used to reject peripheralsnot supported with a given Linux OTG host. This whitelist isproduct-specific; each product must modify
otg_whitelist.h
tomatch its interoperability specification.Non-OTG Linux hosts, like PCs and workstations, normally have somesolution for adding drivers, so that peripherals that aren’trecognized can eventually be supported. That approach is unreasonablefor consumer products that may never have their firmware upgraded,and where it’s usually unrealistic to expect traditionalPC/workstation/server kinds of support model to work. For example,it’s often impractical to change device firmware once the product hasbeen distributed, so driver bugs can’t normally be fixed if they’refound after shipment.
Additional changes are needed below those hardware-neutral usb_bus
and usb_gadget driver interfaces; those aren’t discussed here in anydetail. Those affect the hardware-specific code for each USB Host orPeripheral controller, and how the HCD initializes (since OTG can beactive only on a single port). They also involve what may be called anOTG Controller Driver, managing the OTG transceiver and the OTG statemachine logic as well as much of the root hub behavior for the OTG port.The OTG controller driver needs to activate and deactivate USBcontrollers depending on the relevant device role. Some related changeswere needed inside usbcore, so that it can identify OTG-capable devicesand respond appropriately to HNP or SRP protocols.