标签:limit cas scan iso pull led ted devices method
Author: | David Brownell |
---|---|
Date: | 20 August 2004 |
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:
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.
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:
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.
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:
Such drivers may be modules of proprietary code, although that approach is discouraged in the Linux community.
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:
/dev
open()
, close()
, read()
and write()
. 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.
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.
Note
Other than the “Chapter 9” data types, most of the significant data types and functions are described here.
However, some relevant information is likely omitted from what you are reading. One example of such information is endpoint autoconfiguration. You’ll have to read the header file, and use example source code (such as that for “Gadget Zero”), to fully understand the API.
The part of the API implementing some basic driver capabilities is specific to the version of the Linux kernel that’s in use. The 2.6 and upper kernel versions include a driver model framework that has no analogue on earlier kernels; so those parts of the gadget API are not fully portable. (They are implemented on 2.4 kernels, but in a different way.) The driver model state is another part of this API that is ignored by the kerneldoc tools.
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.
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:
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.usb_gadget
, which activates the data line pullup sometime after detecting VBUS.power
and set_address
requests. 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.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.set_configuration
call. 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 using usb_gadget_vbus_draw
to 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.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.
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).
These are declared in <linux/usb/gadget.h>
, and are used by gadget drivers to interact with USB peripheral controller drivers.
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 no_interrupt:1;
unsigned zero:1;
unsigned short_not_ok:1;
void (* complete) (struct usb_ep *ep,struct usb_request *req);
void * context;
struct list_head list;
int status;
unsigned actual;
};
Members
buf
length
dma
sg
num_sgs
num_mapped_sgs
stream_id
no_interrupt
zero
short_not_ok
complete
context
list
status
actual
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.
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
type_iso
type_bulk
type_int
dir_in
dir_out
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;
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
name
ops
ep_list
caps
maxpacket
maxpacket_limit
max_streams
mult
maxburst
address
desc
comp_desc
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.
usb_gadget
represents a usb slave 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_device_state state;
const char * name;
struct device dev;
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_avoids_skb_reserve:1;
unsigned is_selfpowered:1;
unsigned deactivated:1;
unsigned connected:1;
unsigned lpm_capable:1;
};
Members
work
sysfs_notify()
udc
ops
ep0
setup()
requestsep_list
speed
max_speed
state
name
dev
out_epnum
in_epnum
mA
otg_caps
sg_supported
is_otg
is_a_peripheral
b_hnp_enable
a_hnp_support
a_alt_hnp_support
hnp_polling_support
host_request_flag
quirk_ep_out_aligned_size
quirk_avoids_skb_reserve
skb_reserve()
in u_ether.c to improve performance.is_selfpowered
deactivated
connected
lpm_capable
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
(struct usb_ep * ep, size_t len)returns len aligned to ep’s maxpacketsize.
Parameters
struct usb_ep * ep
size_t len
Description
This helper is used to align buffer’s size to an ep’s maxpacketsize.
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
struct usb_ep * ep
size_t len
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
(struct usb_gadget * g)return true iff the hardware supports altsettings
Parameters
struct usb_gadget * g
gadget_is_stall_supported
(struct usb_gadget * g)return true iff the hardware supports stalling
Parameters
struct usb_gadget * g
gadget_is_zlp_supported
(struct usb_gadget * g)return true iff the hardware supports zlp
Parameters
struct usb_gadget * g
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
gadget_is_dualspeed
(struct usb_gadget * g)return true iff the hardware handles high speed
Parameters
struct usb_gadget * g
gadget_is_superspeed
(struct usb_gadget * g)return true if the hardware handles superspeed
Parameters
struct usb_gadget * g
gadget_is_superspeed_plus
(struct usb_gadget * g)return true if the hardware handles superspeed plus
Parameters
struct usb_gadget * g
gadget_is_otg
(struct usb_gadget * g)return true iff the hardware is OTG-ready
Parameters
struct usb_gadget * g
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.
usb_gadget_driver
driver for usb ‘slave’ 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;
struct list_head pending;
unsigned match_existing_only:1;
};
Members
function
max_speed
bind
unbind
setup
disconnect
suspend
resume
reset
driver
udc_name
pending
match_existing_only
Description
Devices are disabled till a gadget driver successfully bind()`s, which means the driver will handle :c:func:`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.
(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_probe_driver
(struct usb_gadget_driver * driver)probe a gadget driver
Parameters
struct usb_gadget_driver * driver
Context
can sleep
Description
Call this in your gadget driver’s module initialization function, to tell the underlying usb 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.
usb_gadget_unregister_driver
(struct usb_gadget_driver * driver)unregister a gadget driver
Parameters
struct usb_gadget_driver * driver
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 in in exit sections, so may not be linked in some kernels.
usb_string
wraps a C string and its USB id
Definition
struct usb_string {
u8 id;
const char * s;
};
Members
id
s
Description
If you’re using usb_gadget_get_string()
, use this to wrap a string together with its ID.
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
strings
Description
If you’re using usb_gadget_get_string()
, use this to wrap all the strings for a given language.
usb_free_descriptors
(struct usb_descriptor_header ** v)free descriptors returned by usb_copy_descriptors()
Parameters
struct usb_descriptor_header ** v
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
(struct usb_gadget_strings * table, int id, u8 * buf)fill out a string descriptor
Parameters
struct usb_gadget_strings * table
int id
u8 * buf
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_descriptor_fillbuf
(void * buf, unsigned buflen, const struct usb_descriptor_header ** src)fill buffer with descriptors
Parameters
void * buf
unsigned buflen
const struct usb_descriptor_header ** src
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_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
void * buf
unsigned length
const struct usb_descriptor_header ** desc
Description
This copies descriptors into the response buffer, building a descriptor for that configuration. It returns the buffer length or a negative status code. The config.wTotalLength field is set to match the length of the result, but other descriptor fields (including power usage and interface count) must be set by the caller.
Gadget drivers could use this when constructing a config descriptor in response to USB_REQ_GET_DESCRIPTOR. They will need to patch the resulting bDescriptorType value if USB_DT_OTHER_SPEED_CONFIG is needed.
usb_copy_descriptors
(struct usb_descriptor_header ** src)copy a vector of USB descriptors
Parameters
struct usb_descriptor_header ** src
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.
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”.
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
type
name_len
name
data_len
data
item
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
ext_prop
ext_prop_len
ext_prop_count
opts_mutex
group
owner
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
os_desc
Description
Each interface can have at most one “Extended Compatibility ID” and a number of “Extended Properties”.
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);
};
Members
name
strings
bind()
and by language IDs provided in control requestsfs_descriptors
hs_descriptors
ss_descriptors
ssp_descriptors
config
os_desc_table
os_desc_n
bind
bind()
to the available resources including string and interface identifiers used in interface or class descriptors; endpoints; I/O buffers; and so on.unbind
free_func
mod
set_alt
get_alt
disable
setup
req_match
suspend
resume
get_status
GetStatus()
request when the recipient is Interface.func_suspend
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.
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
strings
descriptors
unbind
setup
bConfigurationValue
iConfiguration
bmAttributes
MaxPower
cdev
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.
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
dev
strings
max_speed
needs_serial
bind
unbind
disconnect
suspend
resume
gadget_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
(__usb_composite_driver)Helper macro for registering a USB gadget composite driver
Parameters
__usb_composite_driver
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()
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;
u8 b_vendor_code;
struct usb_configuration * os_desc_config;
unsigned int use_os_string:1;
unsigned int setup_pending:1;
unsigned int os_desc_pending:1;
};
Members
gadget
req
os_desc_req
config
qw_sign
b_vendor_code
os_desc_config
use_os_string
setup_pending
os_desc_pending
Description
One of these devices is allocated and initialized before the associated device driver’s bind()
is called.
OPEN ISSUE: it appears that some WUSB devices will need to be built by combining a normal (wired) gadget with a wireless one. This revision of the gadget framework should probably try to make sure doing that won’t hurt too much.
One notion for how to handle Wireless USB devices involves:
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
struct usb_function * f
struct usb_ep * _ep
Return
error code, 0 on success
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
(struct usb_configuration * config, struct usb_function * function)add a function to a configuration
Parameters
struct usb_configuration * config
struct usb_function * function
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
(struct usb_function * function)prevent function and gadget enumeration
Parameters
struct usb_function * function
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
(struct usb_function * function)allow function and gadget enumeration
Parameters
struct usb_function * function
usb_function_activate()
was calledDescription
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
(struct usb_configuration * config, struct usb_function * function)allocate an unused interface ID
Parameters
struct usb_configuration * config
struct usb_function * function
Context
single threaded during gadget setup
Description
usb_interface_id()
is called from usb_function.:c:func: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_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
struct usb_configuration * config
int (*)(struct usb_configuration *) bind
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
(struct usb_composite_dev * cdev)allocate an unused string ID
Parameters
struct usb_composite_dev * cdev
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
(struct usb_composite_dev * cdev, struct usb_string * str)allocate unused string IDs in batch
Parameters
struct usb_composite_dev * cdev
struct usb_string * str
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_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
struct usb_gadget_strings ** sp
unsigned n_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
(struct usb_composite_dev * c, unsigned n)allocate unused string IDs in batch
Parameters
struct usb_composite_dev * c
unsigned n
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
(struct usb_composite_driver * driver)register a composite driver
Parameters
struct usb_composite_driver * driver
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
(struct usb_composite_driver * driver)unregister a composite driver
Parameters
struct usb_composite_driver * driver
Description
This function is used to unregister drivers using the composite driver framework.
usb_composite_setup_continue
(struct usb_composite_dev * cdev)Continue with the control transfer
Parameters
struct usb_composite_dev * cdev
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.
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
.
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.
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 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 re-use 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_otg
flag, 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_enable
flag. 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.h
to 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.
标签:limit cas scan iso pull led ted devices method
原文地址:https://www.cnblogs.com/xspdef/p/10731398.html