요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
========================
USB Gadget API for Linux
========================
:Author: David Brownell
:Date: 20 August 2004
Introduction
============
This document presents a Linux-USB "Gadget" kernel mode API, for use
within peripherals and other USB devices that embed Linux. It provides
an overview of the API structure, and shows how that fits into a system
development project. This is the first such API released on Linux to
address a number of important problems, including:
- Supports USB 2.0, for high speed devices which can stream data at
several dozen megabytes per second.
- Handles devices with dozens of endpoints just as well as ones with
just two fixed-function ones. Gadget drivers can be written so
they're easy to port to new hardware.
- Flexible enough to expose more complex USB device capabilities such
as multiple configurations, multiple interfaces, composite devices,
and alternate interface settings.
- USB "On-The-Go" (OTG) support, in conjunction with updates to the
Linux-USB host side.
- Sharing data structures and API models with the Linux-USB host side
API. This helps the OTG support, and looks forward to more-symmetric
frameworks (where the same I/O model is used by both host and device
side drivers).
- Minimalist, so it's easier to support new device controller hardware.
I/O processing doesn't imply large demands for memory or CPU
resources.
Most Linux developers will not be able to use this API, since they have
USB ``host`` hardware in a PC, workstation, or server. Linux users with
embedded systems are more likely to have USB peripheral hardware. To
distinguish drivers running inside such hardware from the more familiar
Linux "USB device drivers", which are host side proxies for the real USB
devices, a different term is used: the drivers inside the peripherals
are "USB gadget drivers". In USB protocol interactions, the device
driver is the master (or "client driver") and the gadget driver is the
slave (or "function driver").
The gadget API resembles the host side Linux-USB API in that both use
queues of request objects to package I/O buffers, and those requests may
be submitted or canceled. They share common definitions for the standard
USB *Chapter 9* messages, structures, and constants. Also, both APIs
bind and unbind drivers to devices. The APIs differ in detail, since the
host side's current URB framework exposes a number of implementation
details and assumptions that are inappropriate for a gadget API. While
the model for control transfers and configuration management is
necessarily different (one side is a hardware-neutral master, the other
is a hardware-aware slave), the endpoint I/0 API used here should also
be usable for an overhead-reduced host side API.
Structure of Gadget Drivers
===========================
A system running inside a USB peripheral normally has at least three
layers inside the kernel to handle USB protocol processing, and may have
additional layers in user space code. The ``gadget`` API is used by the
middle layer to interact with the lowest level (which directly handles
hardware).
In Linux, from the bottom up, these layers are:
*USB Controller Driver*
This is the lowest software level. It is the only layer that talks
to hardware, through registers, fifos, dma, irqs, and the like. The
``<linux/usb/gadget.h>`` API abstracts the peripheral controller
endpoint hardware. That hardware is exposed through endpoint
objects, which accept streams of IN/OUT buffers, and through
callbacks that interact with gadget drivers. Since normal USB
devices only have one upstream port, they only have one of these
drivers. The controller driver can support any number of different
gadget drivers, but only one of them can be used at a time.
Examples of such controller hardware include the PCI-based NetChip
2280 USB 2.0 high speed controller, the SA-11x0 or PXA-25x UDC
(found within many PDAs), and a variety of other products.
*Gadget Driver*
The lower boundary of this driver implements hardware-neutral USB
functions, using calls to the controller driver. Because such
hardware varies widely in capabilities and restrictions, and is used
in embedded environments where space is at a premium, the gadget
driver is often configured at compile time to work with endpoints
supported by one particular controller. Gadget drivers may be
portable to several different controllers, using conditional
compilation. (Recent kernels substantially simplify the work
involved in supporting new hardware, by *autoconfiguring* endpoints
automatically for many bulk-oriented drivers.) Gadget driver
responsibilities include:
- handling setup requests (ep0 protocol responses) possibly
including class-specific functionality
- returning configuration and string descriptors
- (re)setting configurations and interface altsettings, including
enabling and configuring endpoints
- handling life cycle events, such as managing bindings to
hardware, USB suspend/resume, remote wakeup, and disconnection
from the USB host.
- managing IN and OUT transfers on all currently enabled endpoints
Such drivers may be modules of proprietary code, although that
approach is discouraged in the Linux community.
*Upper Level*
Most gadget drivers have an upper boundary that connects to some
Linux driver or framework in Linux. Through that boundary flows the
data which the gadget driver produces and/or consumes through
protocol transfers over USB. Examples include:
- user mode code, using generic (gadgetfs) or application specific
files in ``/dev``
- networking subsystem (for network gadgets, like the CDC Ethernet
Model gadget driver)
- data capture drivers, perhaps video4Linux or a scanner driver; or
test and measurement hardware.
- input subsystem (for HID gadgets)
- sound subsystem (for audio gadgets)
- file system (for PTP gadgets)
- block i/o subsystem (for usb-storage gadgets)
- ... and more
*Additional Layers*
Other layers may exist. These could include kernel layers, such as
network protocol stacks, as well as user mode applications building
on standard POSIX system call APIs such as ``open()``, ``close()``,
``read()`` 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.
Kernel Mode Gadget API
======================
Gadget drivers declare themselves through a struct
:c:type:`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.
Driver Life Cycle
-----------------
Gadget drivers make endpoint I/O requests to hardware without needing to
know many details of the hardware, but driver setup/configuration code
needs to handle some differences. Use the API like this:
1. Register a driver for the particular device side usb controller
hardware, such as the net2280 on PCI (USB 2.0), sa11x0 or pxa25x as
found in Linux PDAs, and so on. At this point the device is logically
in the USB ch9 initial state (``attached``), drawing no power and not
usable (since it does not yet support enumeration). Any host should
not see the device, since it's not activated the data line pullup
used by the host to detect a device, even if VBUS power is available.
2. Register a gadget driver that implements some higher level device
function. That will then bind() to a :c:type:`usb_gadget`, which activates
the data line pullup sometime after detecting VBUS.
3. The hardware driver can now start enumerating. The steps it handles
are to accept USB ``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.
4. The gadget driver's ``setup()`` call returns usb descriptors, based both
on what the bus interface hardware provides and on the functionality
being implemented. That can involve alternate settings or
configurations, unless the hardware prevents such operation. For OTG
devices, each configuration descriptor includes an OTG descriptor.
5. The gadget driver handles the last step of enumeration, when the USB
host issues a ``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.
6. Do real work and perform data transfers, possibly involving changes
to interface settings or switching to new configurations, until the
device is disconnect()ed from the host. Queue any number of transfer
requests to each endpoint. It may be suspended and resumed several
times before being disconnected. On disconnect, the drivers go back
to step 3 (above).
7. When the gadget driver module is being unloaded, the driver unbind()
callback is issued. That lets the controller driver be unloaded.
Drivers will normally be arranged so that just loading the gadget driver
module (or statically linking it into a Linux kernel) allows the
peripheral device to be enumerated, but some drivers will defer
enumeration until some higher level component (like a user mode daemon)
enables it. Note that at this lowest level there are no policies about
how ep0 configuration logic is implemented, except that it should obey
USB specifications. Such issues are in the domain of gadget drivers,
including knowing about implementation constraints imposed by some USB
controllers or understanding that composite devices might happen to be
built by integrating reusable components.
Note that the lifecycle above can be slightly different for OTG devices.
Other than providing an additional OTG descriptor in each configuration,
only the HNP-related differences are particularly visible to driver
code. They involve reporting requirements during the ``SET_CONFIGURATION``
request, and the option to invoke HNP during some suspend callbacks.
Also, SRP changes the semantics of ``usb_gadget_wakeup`` slightly.
USB 2.0 Chapter 9 Types and Constants
-------------------------------------
Gadget drivers rely on common USB structures and constants defined in
the :ref:`linux/usb/ch9.h <usb_chapter9>` header file, which is standard in
Linux 2.6+ kernels. These are the same types and constants used by host side
drivers (and usbcore).
Core Objects and Methods
------------------------
These are declared in ``<linux/usb/gadget.h>``, and are used by gadget
drivers to interact with USB peripheral controller drivers.
.. kernel-doc:: include/linux/usb/gadget.h
:internal:
Optional Utilities
------------------
The core API is sufficient for writing a USB Gadget Driver, but some
optional utilities are provided to simplify common tasks. These
utilities include endpoint autoconfiguration.
.. kernel-doc:: drivers/usb/gadget/usbstring.c
:export:
.. kernel-doc:: drivers/usb/gadget/config.c
:export:
Composite Device Framework
--------------------------
The core API is sufficient for writing drivers for composite USB devices
(with more than one function in a given configuration), and also
multi-configuration devices (also more than one function, but not
necessarily sharing a given configuration). There is however an optional
framework which makes it easier to reuse and combine functions.
Devices using this framework provide a struct usb_composite_driver,
which in turn provides one or more struct usb_configuration
instances. Each such configuration includes at least one struct
:c:type:`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".
.. kernel-doc:: include/linux/usb/composite.h
:internal:
.. kernel-doc:: drivers/usb/gadget/composite.c
:export:
Composite Device Functions
--------------------------
At this writing, a few of the current gadget drivers have been converted
to this framework. Near-term plans include converting all of them,
except for ``gadgetfs``.
Peripheral Controller Drivers
=============================
The first hardware supporting this API was the NetChip 2280 controller,
which supports USB 2.0 high speed and is based on PCI. This is the
``net2280`` driver module. The driver supports Linux kernel versions 2.4
and 2.6; contact NetChip Technologies for development boards and product
information.
Other hardware working in the ``gadget`` framework includes: Intel's PXA
25x and IXP42x series processors (``pxa2xx_udc``), Toshiba TC86c001
"Goku-S" (``goku_udc``), Renesas SH7705/7727 (``sh_udc``), MediaQ 11xx
(``mq11xx_udc``), Hynix HMS30C7202 (``h7202_udc``), National 9303/4
(``n9604_udc``), Texas Instruments OMAP (``omap_udc``), Sharp LH7A40x
(``lh7a40x_udc``), and more. Most of those are full speed controllers.
At this writing, there are people at work on drivers in this framework
for several other USB device controllers, with plans to make many of
them be widely available.
A partial USB simulator, the ``dummy_hcd`` driver, is available. It can
act like a net2280, a pxa25x, or an sa11x0 in terms of available
endpoints and device speeds; and it simulates control, bulk, and to some
extent interrupt transfers. That lets you develop some parts of a gadget
driver on a normal PC, without any special hardware, and perhaps with
the assistance of tools such as GDB running with User Mode Linux. At
least one person has expressed interest in adapting that approach,
hooking it up to a simulator for a microcontroller. Such simulators can
help debug subsystems where the runtime hardware is unfriendly to
software development, or is not yet available.
Support for other controllers is expected to be developed and
contributed over time, as this driver framework evolves.
Gadget Drivers
==============
In addition to *Gadget Zero* (used primarily for testing and development
with drivers for usb controller hardware), other gadget drivers exist.
There's an ``ethernet`` gadget driver, which implements one of the most
useful *Communications Device Class* (CDC) models. One of the standards
for cable modem interoperability even specifies the use of this ethernet
model as one of two mandatory options. Gadgets using this code look to a
USB host as if they're an Ethernet adapter. It provides access to a
network where the gadget's CPU is one host, which could easily be
bridging, routing, or firewalling access to other networks. Since some
hardware can't fully implement the CDC Ethernet requirements, this
driver also implements a "good parts only" subset of CDC Ethernet. (That
subset doesn't advertise itself as CDC Ethernet, to avoid creating
problems.)
Support for Microsoft's ``RNDIS`` protocol has been contributed by
Pengutronix and Auerswald GmbH. This is like CDC Ethernet, but it runs
on more slightly USB hardware (but less than the CDC subset). However,
its main claim to fame is being able to connect directly to recent
versions of Windows, using drivers that Microsoft bundles and supports,
making it much simpler to network with Windows.
There is also support for user mode gadget drivers, using ``gadgetfs``.
This provides a *User Mode API* that presents each endpoint as a single
file descriptor. I/O is done using normal ``read()`` and ``read()`` calls.
Familiar tools like GDB and pthreads can be used to develop and debug
user mode drivers, so that once a robust controller driver is available
many applications for it won't require new kernel mode software. Linux
2.6 *Async I/O (AIO)* support is available, so that user mode software
can stream data with only slightly more overhead than a kernel driver.
There's a USB Mass Storage class driver, which provides a different
solution for interoperability with systems such as MS-Windows and MacOS.
That *Mass Storage* driver uses a file or block device as backing store
for a drive, like the ``loop`` driver. The USB host uses the BBB, CB, or
CBI versions of the mass storage class specification, using transparent
SCSI commands to access the data from the backing store.
There's a "serial line" driver, useful for TTY style operation over USB.
The latest version of that driver supports CDC ACM style operation, like
a USB modem, and so on most hardware it can interoperate easily with
MS-Windows. One interesting use of that driver is in boot firmware (like
a BIOS), which can sometimes use that model with very small systems
without real serial lines.
Support for other kinds of gadget is expected to be developed and
contributed over time, as this driver framework evolves.
USB On-The-GO (OTG)
===================
USB OTG support on Linux 2.6 was initially developed by Texas
Instruments for `OMAP <http://www.omap.com>`__ 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 (:c:type:`usb_bus` or :c:type:`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 :c:type:`usb_bus`
and :c:type:`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.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
Linux USB Gadget API 소개
1-61이 문서는 Linux를 내장한 peripheral과 USB device 내부에서 사용하는 Linux-USB kernel mode `Gadget` API를 소개합니다. API 구조가 시스템 개발 프로젝트에 어떻게 들어맞는지 설명하며, Linux에서 이 문제 영역을 다룬 최초의 API입니다.
이 API는 USB 2.0 high speed, 두 개의 고정 endpoint부터 수십 개의 endpoint까지의 hardware, 여러 configuration·interface·alternate setting을 포함한 composite device, OTG를 지원합니다. Host 측 Linux-USB API와 data structure·I/O model을 공유하면서도 새 device controller hardware를 적은 memory·CPU 부담으로 지원하도록 작게 설계되었습니다.
PC·workstation·server의 USB host hardware를 다루는 개발자보다 embedded system에서 USB peripheral hardware를 쓰는 개발자가 이 API를 주로 사용합니다. Host에서 실제 USB device를 대리하는 `USB device driver`와 구별하기 위해 peripheral 내부 driver를 `USB gadget driver`라고 부릅니다. Protocol 관계에서 device driver는 master 또는 client driver이고 gadget driver는 slave 또는 function driver입니다.
Host API와 gadget API는 I/O buffer를 request object queue로 묶어 submit·cancel하고 USB Chapter 9 message·structure·constant를 공유하며 driver bind·unbind를 지원합니다. 그러나 host의 URB framework가 노출하는 구현 세부와 가정은 gadget API에 맞지 않으므로 control transfer와 configuration management의 세부 model은 다릅니다.
========================
USB Gadget API for Linux
========================
:Author: David Brownell
:Date: 20 August 2004
Introduction
============
This document presents a Linux-USB "Gadget" kernel mode API, for use
within peripherals and other USB devices that embed Linux. It provides
an overview of the API structure, and shows how that fits into a system
development project. This is the first such API released on Linux to
address a number of important problems, including:
- Supports USB 2.0, for high speed devices which can stream data at
several dozen megabytes per second.
- Handles devices with dozens of endpoints just as well as ones with
just two fixed-function ones. Gadget drivers can be written so
they're easy to port to new hardware.
- Flexible enough to expose more complex USB device capabilities such
as multiple configurations, multiple interfaces, composite devices,
and alternate interface settings.
- USB "On-The-Go" (OTG) support, in conjunction with updates to the
Linux-USB host side.
- Sharing data structures and API models with the Linux-USB host side
API. This helps the OTG support, and looks forward to more-symmetric
frameworks (where the same I/O model is used by both host and device
side drivers).
- Minimalist, so it's easier to support new device controller hardware.
I/O processing doesn't imply large demands for memory or CPU
resources.
Most Linux developers will not be able to use this API, since they have
USB ``host`` hardware in a PC, workstation, or server. Linux users with
embedded systems are more likely to have USB peripheral hardware. To
distinguish drivers running inside such hardware from the more familiar
Linux "USB device drivers", which are host side proxies for the real USB
devices, a different term is used: the drivers inside the peripherals
are "USB gadget drivers". In USB protocol interactions, the device
driver is the master (or "client driver") and the gadget driver is the
slave (or "function driver").
The gadget API resembles the host side Linux-USB API in that both use
queues of request objects to package I/O buffers, and those requests may
be submitted or canceled. They share common definitions for the standard
USB *Chapter 9* messages, structures, and constants. Also, both APIs
bind and unbind drivers to devices. The APIs differ in detail, since the
host side's current URB framework exposes a number of implementation
details and assumptions that are inappropriate for a gadget API. While
the model for control transfers and configuration management is
necessarily different (one side is a hardware-neutral master, the other
is a hardware-aware slave), the endpoint I/0 API used here should also
be usable for an overhead-reduced host side API.
Controller와 Gadget driver 계층
62-117USB peripheral 내부의 Linux system은 보통 kernel에서 최소 세 계층으로 USB protocol을 처리하며 user space 계층을 더 둘 수 있습니다. `gadget` API는 middle layer가 hardware를 직접 다루는 lowest layer와 통신할 때 사용합니다.
*USB Controller Driver*는 register, FIFO, DMA, IRQ 등 hardware와 직접 통신하는 유일한 계층입니다. `<linux/usb/gadget.h>`는 peripheral controller endpoint hardware를 추상화하며, endpoint object는 IN·OUT buffer stream을 받고 callback으로 gadget driver와 상호작용합니다. 일반 device는 upstream port가 하나라 controller driver도 하나이며, 여러 gadget driver를 지원할 수 있어도 한 번에 하나만 사용합니다.
Controller 예로 PCI 기반 NetChip 2280 USB 2.0 high speed controller와 SA-11x0·PXA-25x UDC 등이 있습니다.
*Gadget Driver*의 아래 경계는 controller driver 호출을 사용해 hardware-neutral USB function을 구현합니다. Hardware capability와 제약이 다양하고 embedded 환경에서는 공간이 중요하므로 특정 controller의 endpoint에 맞춰 compile-time 구성하는 경우가 많지만, conditional compilation으로 여러 controller에 이식할 수 있습니다. 최근 kernel은 bulk 중심 driver의 endpoint를 자동 구성하여 새 hardware 지원을 단순화합니다.
Gadget driver는 setup request와 ep0 protocol response 처리, configuration·string descriptor 반환, configuration·interface altsetting 설정과 endpoint enable, bind·suspend·resume·remote wakeup·disconnect lifecycle 관리, enable된 모든 endpoint의 IN·OUT 전송 관리를 맡습니다.
USB protocol data가 hardware와 상위 subsystem 사이를 이동하는 기본 구조입니다.
Structure of Gadget Drivers
===========================
A system running inside a USB peripheral normally has at least three
layers inside the kernel to handle USB protocol processing, and may have
additional layers in user space code. The ``gadget`` API is used by the
middle layer to interact with the lowest level (which directly handles
hardware).
In Linux, from the bottom up, these layers are:
*USB Controller Driver*
This is the lowest software level. It is the only layer that talks
to hardware, through registers, fifos, dma, irqs, and the like. The
``<linux/usb/gadget.h>`` API abstracts the peripheral controller
endpoint hardware. That hardware is exposed through endpoint
objects, which accept streams of IN/OUT buffers, and through
callbacks that interact with gadget drivers. Since normal USB
devices only have one upstream port, they only have one of these
drivers. The controller driver can support any number of different
gadget drivers, but only one of them can be used at a time.
Examples of such controller hardware include the PCI-based NetChip
2280 USB 2.0 high speed controller, the SA-11x0 or PXA-25x UDC
(found within many PDAs), and a variety of other products.
*Gadget Driver*
The lower boundary of this driver implements hardware-neutral USB
functions, using calls to the controller driver. Because such
hardware varies widely in capabilities and restrictions, and is used
in embedded environments where space is at a premium, the gadget
driver is often configured at compile time to work with endpoints
supported by one particular controller. Gadget drivers may be
portable to several different controllers, using conditional
compilation. (Recent kernels substantially simplify the work
involved in supporting new hardware, by *autoconfiguring* endpoints
automatically for many bulk-oriented drivers.) Gadget driver
responsibilities include:
- handling setup requests (ep0 protocol responses) possibly
including class-specific functionality
- returning configuration and string descriptors
- (re)setting configurations and interface altsettings, including
enabling and configuring endpoints
- handling life cycle events, such as managing bindings to
hardware, USB suspend/resume, remote wakeup, and disconnection
from the USB host.
- managing IN and OUT transfers on all currently enabled endpoints
Such drivers may be modules of proprietary code, although that
approach is discouraged in the Linux community.
상위 계층, OTG stack, 재사용 component
118-173대부분 gadget driver의 위쪽 경계는 Linux의 다른 driver 또는 framework와 연결되며 USB protocol transfer로 생산·소비하는 data가 이 경계를 통과합니다.
상위 계층에는 `gadgetfs` 또는 `/dev`의 application 전용 file을 쓰는 user mode code, CDC Ethernet 같은 network subsystem, video4Linux·scanner·시험 계측 같은 data capture driver, HID용 input subsystem, audio용 sound subsystem, PTP용 filesystem, usb-storage용 block I/O subsystem 등이 있습니다.
그 위에는 network protocol stack 같은 kernel layer와 `open()`, `close()`, `read()`, `write()` 및 POSIX Async I/O를 쓰는 user application이 추가될 수 있습니다. 이런 user mode code가 반드시 GPL 적용을 받는 것은 아닙니다.
OTG system은 `usbcore`, HCD, Targeted Peripheral List의 USB Device Driver를 포함한 표준 host stack도 필요합니다. OTG Controller Driver는 gadget·device driver 개발자에게 간접적으로 보이며 HNP와 SRP를 구현하도록 host·device controller를 조정합니다. HNP는 suspend 중 host와 peripheral 역할을 바꾸고 SRP는 battery 친화적인 device wakeup protocol로 볼 수 있습니다.
재사용 utility는 descriptor vector에서 configuration descriptor를 만들고 hardware endpoint를 자동 선택·초기화합니다. HID, networking, storage, audio 같은 USB-IF protocol 구현과 KDB·KGDB remote debugging hook도 hardware 독립적으로 재사용할 수 있으며, 이런 function driver를 결합해 composite device를 구성하는 방향으로 발전합니다.
*Upper Level*
Most gadget drivers have an upper boundary that connects to some
Linux driver or framework in Linux. Through that boundary flows the
data which the gadget driver produces and/or consumes through
protocol transfers over USB. Examples include:
- user mode code, using generic (gadgetfs) or application specific
files in ``/dev``
- networking subsystem (for network gadgets, like the CDC Ethernet
Model gadget driver)
- data capture drivers, perhaps video4Linux or a scanner driver; or
test and measurement hardware.
- input subsystem (for HID gadgets)
- sound subsystem (for audio gadgets)
- file system (for PTP gadgets)
- block i/o subsystem (for usb-storage gadgets)
- ... and more
*Additional Layers*
Other layers may exist. These could include kernel layers, such as
network protocol stacks, as well as user mode applications building
on standard POSIX system call APIs such as ``open()``, ``close()``,
``read()`` 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.
Kernel Mode Gadget API 핵심 객체
174-234Gadget driver는 `struct usb_gadget_driver`로 자신을 선언하고 `struct usb_gadget`의 enumeration 대부분을 담당합니다. `set_configuration`에 응답할 때 gadget이 제공하는 하나 이상의 `struct usb_ep`를 enable하고 하나 이상의 `struct usb_request` buffer를 submit해 data를 전송합니다. 이 네 data type과 operation을 이해하면 API의 핵심을 이해한 것입니다.
Chapter 9 type 외의 주요 type과 function은 이 문서에 설명되지만 endpoint autoconfiguration 같은 관련 정보가 빠질 수 있습니다. 완전한 이해를 위해 header와 `Gadget Zero` 같은 example source를 함께 읽어야 합니다.
기본 driver capability 일부는 kernel version에 의존합니다. Linux 2.6 이상에는 이전 kernel에 대응물이 없는 driver model framework가 있어 해당 gadget API 부분은 완전히 portable하지 않으며, driver model state는 kerneldoc tool이 다루지 않습니다.
Core API는 널리 제공되는 hardware feature만 노출합니다. Temporary memory buffer 없이 수행하는 device-to-device DMA 같은 기능은 hardware-specific API로 추가해야 합니다.
Hardware마다 transfer type, addressing, packet size, buffering, endpoint availability 제약이 다릅니다. API는 conditional compilation을 허용하지만 강제하지 않고 endpoint naming convention을 통한 제한적 runtime capability detection과 autoconfiguration을 제공합니다. Driver init code는 endpoint list를 scan해 요구 조건에 맞는 endpoint를 찾을 수 있습니다.
이 API는 USB message가 여러 packet으로 나뉘고 packet boundary가 driver에 보이는 특성을 그대로 노출합니다. Controller driver는 한 바이트 write 두 개를 임의로 두 바이트 IN packet 하나로 합치지 않지만, short packet과 packet boundary가 중요하지 않은 protocol을 구현하는 gadget driver는 이를 합칠 수 있습니다.
Kernel Mode Gadget API
======================
Gadget drivers declare themselves through a struct
:c:type:`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 driver 수명주기
235-302Gadget driver의 endpoint I/O는 hardware 세부를 거의 몰라도 되지만 setup과 configuration code는 controller 차이를 처리해야 합니다.
1단계에서 device-side USB controller driver를 등록합니다. Device는 논리적으로 Chapter 9의 초기 `attached` 상태이며 power를 소비하지 않고 enumeration도 지원하지 않습니다. VBUS가 있어도 host가 device를 감지하는 data-line pullup을 활성화하지 않았으므로 host에 보이면 안 됩니다.
2단계에서 상위 device function을 구현하는 gadget driver를 등록합니다. Driver가 `usb_gadget`에 `bind()`되고 VBUS를 감지한 뒤 적절한 시점에 pullup을 활성화합니다. 3단계에서 hardware driver가 `power`와 `set_address` request를 받아 enumeration을 시작하고 나머지는 gadget driver가 처리합니다.
4단계의 `setup()`은 bus hardware와 구현 function에 맞는 USB descriptor를 반환합니다. Hardware가 허용하면 alternate setting과 여러 configuration을 사용할 수 있고 OTG configuration에는 OTG descriptor가 포함됩니다.
5단계에서 host의 `set_configuration`에 응답해 해당 configuration의 endpoint를 descriptor에 맞게 enable하고 interface를 default setting으로 둡니다. `usb_gadget_vbus_draw()`로 configuration이 허용하는 추가 VBUS power를 요청할 수 있으며 OTG에서는 HNP capability를 user interface로 보고할 수 있습니다.
6단계에서 실제 data transfer를 수행하며 interface setting·configuration을 바꾸고 endpoint마다 여러 request를 queue할 수 있습니다. Suspend·resume이 여러 번 일어난 뒤 disconnect되면 3단계로 돌아갑니다. 7단계에서 module unload 시 `unbind()` callback을 호출해 controller driver도 unload할 수 있게 합니다.
보통 gadget driver module을 load하거나 kernel에 정적으로 link하면 enumeration이 가능하지만 user daemon 같은 상위 component가 enable할 때까지 미룰 수도 있습니다. Ep0 policy는 USB specification을 지키는 것 외에는 gadget driver 영역이며 controller 제약과 reusable component로 만든 composite device도 여기서 처리합니다.
OTG lifecycle은 configuration마다 OTG descriptor를 제공하고 `SET_CONFIGURATION` 중 HNP 요구를 보고하며 일부 suspend callback에서 HNP를 시작할 수 있다는 점이 다릅니다. SRP는 `usb_gadget_wakeup()` 의미를 약간 바꿉니다.
Controller 등록부터 module 해제까지의 상태 전이입니다.
Driver Life Cycle
-----------------
Gadget drivers make endpoint I/O requests to hardware without needing to
know many details of the hardware, but driver setup/configuration code
needs to handle some differences. Use the API like this:
1. Register a driver for the particular device side usb controller
hardware, such as the net2280 on PCI (USB 2.0), sa11x0 or pxa25x as
found in Linux PDAs, and so on. At this point the device is logically
in the USB ch9 initial state (``attached``), drawing no power and not
usable (since it does not yet support enumeration). Any host should
not see the device, since it's not activated the data line pullup
used by the host to detect a device, even if VBUS power is available.
2. Register a gadget driver that implements some higher level device
function. That will then bind() to a :c:type:`usb_gadget`, which activates
the data line pullup sometime after detecting VBUS.
3. The hardware driver can now start enumerating. The steps it handles
are to accept USB ``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.
4. The gadget driver's ``setup()`` call returns usb descriptors, based both
on what the bus interface hardware provides and on the functionality
being implemented. That can involve alternate settings or
configurations, unless the hardware prevents such operation. For OTG
devices, each configuration descriptor includes an OTG descriptor.
5. The gadget driver handles the last step of enumeration, when the USB
host issues a ``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.
6. Do real work and perform data transfers, possibly involving changes
to interface settings or switching to new configurations, until the
device is disconnect()ed from the host. Queue any number of transfer
requests to each endpoint. It may be suspended and resumed several
times before being disconnected. On disconnect, the drivers go back
to step 3 (above).
7. When the gadget driver module is being unloaded, the driver unbind()
callback is issued. That lets the controller driver be unloaded.
Drivers will normally be arranged so that just loading the gadget driver
module (or statically linking it into a Linux kernel) allows the
peripheral device to be enumerated, but some drivers will defer
enumeration until some higher level component (like a user mode daemon)
enables it. Note that at this lowest level there are no policies about
how ep0 configuration logic is implemented, except that it should obey
USB specifications. Such issues are in the domain of gadget drivers,
including knowing about implementation constraints imposed by some USB
controllers or understanding that composite devices might happen to be
built by integrating reusable components.
Note that the lifecycle above can be slightly different for OTG devices.
Other than providing an additional OTG descriptor in each configuration,
only the HNP-related differences are particularly visible to driver
code. They involve reporting requirements during the ``SET_CONFIGURATION``
request, and the option to invoke HNP during some suspend callbacks.
Also, SRP changes the semantics of ``usb_gadget_wakeup`` slightly.
Chapter 9, utility, composite framework
303-361Gadget driver는 `linux/usb/ch9.h`에 정의된 공통 USB structure와 constant를 사용합니다. Linux 2.6 이상에서 표준이며 host-side driver와 usbcore도 같은 type과 constant를 사용합니다.
Controller driver와 상호작용하는 core object·method는 `<linux/usb/gadget.h>`에 선언되고 `include/linux/usb/gadget.h`의 kernel-doc `:internal:` 항목으로 문서화됩니다.
Core API만으로 USB Gadget Driver를 작성할 수 있지만 endpoint autoconfiguration 등 공통 작업을 단순화하는 optional utility가 있습니다. `drivers/usb/gadget/usbstring.c`와 `drivers/usb/gadget/config.c`의 exported API가 이에 해당합니다.
Composite USB device와 multi-configuration device도 core API로 구현할 수 있지만 optional composite framework를 쓰면 function을 재사용하고 결합하기 쉽습니다.
Framework 사용 device는 `struct usb_composite_driver`를 제공하고 이 driver는 하나 이상의 `struct usb_configuration`을 제공합니다. 각 configuration은 `network link`나 `mass storage device` 같은 user-visible role을 묶는 `struct usb_function`을 최소 하나 포함하며 Device Firmware Upgrade 같은 management function도 둘 수 있습니다.
Composite core는 `include/linux/usb/composite.h`의 internal API와 `drivers/usb/gadget/composite.c`의 exported API로 문서화됩니다. 작성 당시 일부 gadget driver만 framework로 전환됐으며 `gadgetfs`를 제외한 나머지도 전환할 계획이었습니다.
Reusable USB function을 configuration과 driver로 조합하는 구조입니다.
USB 2.0 Chapter 9 Types and Constants
-------------------------------------
Gadget drivers rely on common USB structures and constants defined in
the :ref:`linux/usb/ch9.h <usb_chapter9>` header file, which is standard in
Linux 2.6+ kernels. These are the same types and constants used by host side
drivers (and usbcore).
Core Objects and Methods
------------------------
These are declared in ``<linux/usb/gadget.h>``, and are used by gadget
drivers to interact with USB peripheral controller drivers.
.. kernel-doc:: include/linux/usb/gadget.h
:internal:
Optional Utilities
------------------
The core API is sufficient for writing a USB Gadget Driver, but some
optional utilities are provided to simplify common tasks. These
utilities include endpoint autoconfiguration.
.. kernel-doc:: drivers/usb/gadget/usbstring.c
:export:
.. kernel-doc:: drivers/usb/gadget/config.c
:export:
Composite Device Framework
--------------------------
The core API is sufficient for writing drivers for composite USB devices
(with more than one function in a given configuration), and also
multi-configuration devices (also more than one function, but not
necessarily sharing a given configuration). There is however an optional
framework which makes it easier to reuse and combine functions.
Devices using this framework provide a struct usb_composite_driver,
which in turn provides one or more struct usb_configuration
instances. Each such configuration includes at least one struct
:c:type:`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".
.. kernel-doc:: include/linux/usb/composite.h
:internal:
.. kernel-doc:: drivers/usb/gadget/composite.c
:export:
Composite Device Functions
--------------------------
At this writing, a few of the current gadget drivers have been converted
to this framework. Near-term plans include converting all of them,
except for ``gadgetfs``.
Peripheral Controller Driver
362-395이 API를 처음 지원한 hardware는 PCI 기반 USB 2.0 high speed NetChip 2280 controller이며 `net2280` driver module이 Linux 2.4와 2.6을 지원했습니다.
다른 controller에는 Intel PXA25x·IXP42x의 `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`, TI OMAP의 `omap_udc`, Sharp LH7A40x의 `lh7a40x_udc` 등이 있으며 대부분 full speed controller입니다.
`dummy_hcd`는 부분 USB simulator입니다. 사용 가능한 endpoint와 device speed 관점에서 net2280, pxa25x, sa11x0처럼 동작하며 control·bulk와 일부 interrupt transfer를 흉내 냅니다.
따라서 특수 hardware 없이 일반 PC에서 gadget driver 일부를 개발하고 User Mode Linux의 GDB 같은 도구로 debug할 수 있습니다. Runtime hardware가 개발에 불편하거나 아직 준비되지 않았을 때 microcontroller simulator와 연결하는 방식도 subsystem debug에 도움이 됩니다.
Peripheral Controller Drivers
=============================
The first hardware supporting this API was the NetChip 2280 controller,
which supports USB 2.0 high speed and is based on PCI. This is the
``net2280`` driver module. The driver supports Linux kernel versions 2.4
and 2.6; contact NetChip Technologies for development boards and product
information.
Other hardware working in the ``gadget`` framework includes: Intel's PXA
25x and IXP42x series processors (``pxa2xx_udc``), Toshiba TC86c001
"Goku-S" (``goku_udc``), Renesas SH7705/7727 (``sh_udc``), MediaQ 11xx
(``mq11xx_udc``), Hynix HMS30C7202 (``h7202_udc``), National 9303/4
(``n9604_udc``), Texas Instruments OMAP (``omap_udc``), Sharp LH7A40x
(``lh7a40x_udc``), and more. Most of those are full speed controllers.
At this writing, there are people at work on drivers in this framework
for several other USB device controllers, with plans to make many of
them be widely available.
A partial USB simulator, the ``dummy_hcd`` driver, is available. It can
act like a net2280, a pxa25x, or an sa11x0 in terms of available
endpoints and device speeds; and it simulates control, bulk, and to some
extent interrupt transfers. That lets you develop some parts of a gadget
driver on a normal PC, without any special hardware, and perhaps with
the assistance of tools such as GDB running with User Mode Linux. At
least one person has expressed interest in adapting that approach,
hooking it up to a simulator for a microcontroller. Such simulators can
help debug subsystems where the runtime hardware is unfriendly to
software development, or is not yet available.
Support for other controllers is expected to be developed and
contributed over time, as this driver framework evolves.
Gadget function driver 사례
396-446*Gadget Zero*는 주로 USB controller hardware driver의 시험과 개발에 사용되며 그 밖에도 여러 gadget driver가 있습니다.
`ethernet` gadget driver는 CDC의 유용한 Ethernet model을 구현해 host에서 USB Ethernet adapter처럼 보입니다. Gadget CPU가 network host가 되어 bridge·route·firewall을 수행할 수 있습니다. CDC Ethernet 요구를 완전히 구현하지 못하는 hardware를 위해 CDC라고 광고하지 않는 부분집합도 제공합니다.
Pengutronix와 Auerswald GmbH가 기여한 Microsoft `RNDIS`는 CDC Ethernet과 비슷하며 더 제한된 USB hardware에서 동작합니다. Windows에 bundled된 Microsoft driver로 직접 연결할 수 있어 Windows networking을 단순화합니다.
`gadgetfs`는 endpoint마다 하나의 file descriptor를 제공하는 User Mode API입니다. 원문은 I/O에 일반 `read()`와 `read()` 호출을 사용한다고 적고 있으며, GDB·pthreads와 Linux 2.6 AIO로 user-mode driver를 개발·debug하고 kernel driver에 가까운 낮은 overhead로 stream할 수 있습니다.
USB Mass Storage gadget은 file 또는 block device를 `loop` driver처럼 backing store로 사용합니다. Host는 mass storage specification의 BBB, CB, CBI 방식과 transparent SCSI command로 data에 접근합니다.
Serial line gadget은 USB 위에서 TTY 방식으로 동작하며 CDC ACM model을 지원해 USB modem처럼 Windows와 상호운용할 수 있습니다. 실제 serial line이 없는 작은 system의 BIOS 같은 boot firmware에서도 유용합니다.
Gadget Drivers
==============
In addition to *Gadget Zero* (used primarily for testing and development
with drivers for usb controller hardware), other gadget drivers exist.
There's an ``ethernet`` gadget driver, which implements one of the most
useful *Communications Device Class* (CDC) models. One of the standards
for cable modem interoperability even specifies the use of this ethernet
model as one of two mandatory options. Gadgets using this code look to a
USB host as if they're an Ethernet adapter. It provides access to a
network where the gadget's CPU is one host, which could easily be
bridging, routing, or firewalling access to other networks. Since some
hardware can't fully implement the CDC Ethernet requirements, this
driver also implements a "good parts only" subset of CDC Ethernet. (That
subset doesn't advertise itself as CDC Ethernet, to avoid creating
problems.)
Support for Microsoft's ``RNDIS`` protocol has been contributed by
Pengutronix and Auerswald GmbH. This is like CDC Ethernet, but it runs
on more slightly USB hardware (but less than the CDC subset). However,
its main claim to fame is being able to connect directly to recent
versions of Windows, using drivers that Microsoft bundles and supports,
making it much simpler to network with Windows.
There is also support for user mode gadget drivers, using ``gadgetfs``.
This provides a *User Mode API* that presents each endpoint as a single
file descriptor. I/O is done using normal ``read()`` and ``read()`` calls.
Familiar tools like GDB and pthreads can be used to develop and debug
user mode drivers, so that once a robust controller driver is available
many applications for it won't require new kernel mode software. Linux
2.6 *Async I/O (AIO)* support is available, so that user mode software
can stream data with only slightly more overhead than a kernel driver.
There's a USB Mass Storage class driver, which provides a different
solution for interoperability with systems such as MS-Windows and MacOS.
That *Mass Storage* driver uses a file or block device as backing store
for a drive, like the ``loop`` driver. The USB host uses the BBB, CB, or
CBI versions of the mass storage class specification, using transparent
SCSI commands to access the data from the backing store.
There's a "serial line" driver, useful for TTY style operation over USB.
The latest version of that driver supports CDC ACM style operation, like
a USB modem, and so on most hardware it can interoperate easily with
MS-Windows. One interesting use of that driver is in boot firmware (like
a BIOS), which can sometimes use that model with very small systems
without real serial lines.
Support for other kinds of gadget is expected to be developed and
contributed over time, as this driver framework evolves.
USB On-The-Go
447-510Linux 2.6의 USB OTG 지원은 Texas Instruments가 OMAP 16xx·17xx processor용으로 처음 개발했습니다. 다른 OTG system도 비슷하게 동작하지만 hardware 세부는 크게 다를 수 있습니다.
OTG에는 *Mini-AB* jack과 transceiver 등 Dual-Role 전용 hardware가 필요합니다. System은 표준 host stack의 host 또는 `gadget` framework의 peripheral로 동작하며, OTG Controller가 어떤 stack을 OTG port에 연결할지 조정합니다. 각 역할은 `usb_bus` 또는 `usb_gadget` controller interface 위의 기존 hardware-neutral driver를 재사용합니다.
Gadget driver는 `is_otg` flag로 각 configuration에 OTG descriptor를 넣을지 결정합니다. `b_hnp_enable` 같은 attribute로 HNP를 지원하고 이를 LED 등 user interface에 보고해야 합니다. HNP는 host가 peripheral을 suspend할 때 시작될 수 있고 SRP는 remote wakeup처럼 사용자가 시작할 수 있습니다.
Host 측 USB device driver는 `usb_suspend_device()`로 적절한 시점에 HNP를 시작해야 합니다. 이는 non-OTG configuration에서도 battery power 절약에 도움이 됩니다.
Host driver는 OTG Targeted Peripheral List도 지원해야 합니다. 이는 해당 Linux OTG host가 지원하지 않는 peripheral을 거부하는 product-specific whitelist이며, 각 product는 interoperability specification에 맞춰 `otg_whitelist.h`를 수정해야 합니다.
Firmware update가 어려운 consumer product에서는 PC처럼 나중에 driver를 추가하는 지원 model이 현실적이지 않습니다. 출하 뒤 발견된 driver bug를 고치기 어려우므로 whitelist가 중요합니다.
Hardware-neutral `usb_bus`·`usb_gadget` 아래에서도 변경이 필요합니다. OTG Controller Driver는 transceiver, OTG state machine, OTG port의 root hub 동작을 관리하고 device role에 따라 USB controller를 활성·비활성화합니다. Usbcore도 OTG-capable device를 식별하고 HNP·SRP에 응답하도록 변경됩니다.
하나의 OTG port에서 host와 peripheral stack을 선택하는 흐름입니다.
USB On-The-GO (OTG)
===================
USB OTG support on Linux 2.6 was initially developed by Texas
Instruments for `OMAP <http://www.omap.com>`__ 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 (:c:type:`usb_bus` or :c:type:`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 :c:type:`usb_bus`
and :c:type:`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.
요약·해설
gadget.rst:1-510Gadget API는 Linux가 USB peripheral로 동작할 때 controller hardware와 reusable USB function 사이를 연결합니다. Endpoint request queue, Chapter 9 enumeration, composite function 조합, HNP·SRP 역할 전환을 공통 객체와 callback으로 관리합니다.