Documentation/driver-api/usb/gadget.rst GitHub 원문 ↗

Linux 6.18.37 · Driver API

USB Gadget API for Linux

Linux USB peripheral의 Gadget API 계층, 핵심 객체, driver lifecycle, composite framework, controller·function driver와 OTG 동작을 설명하는 한국어 전문 번역입니다.

Source pathDocumentation/driver-api/usb/gadget.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

gadget.rst:1-510

Gadget API는 Linux가 USB peripheral로 동작할 때 controller hardware와 reusable USB function 사이를 연결합니다. Endpoint request queue, Chapter 9 enumeration, composite function 조합, HNP·SRP 역할 전환을 공통 객체와 callback으로 관리합니다.

문서 구성
원문 줄핵심 내용
1-61API 목표와 host 측 비교
62-117controller·gadget driver 계층
118-173상위 subsystem과 재사용 component
174-234네 핵심 API 객체
235-3027단계 lifecycle
303-361Chapter 9·utility·composite framework
362-395peripheral controller driver
396-446gadget function driver
447-510OTG hardware·HNP·SRP

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 ========================
2 USB Gadget API for Linux
3 ========================
4
5 :Author: David Brownell
6 :Date: 20 August 2004
7
8 Introduction
9 ============
10
11 This document presents a Linux-USB "Gadget" kernel mode API, for use
12 within peripherals and other USB devices that embed Linux. It provides
13 an overview of the API structure, and shows how that fits into a system
14 development project. This is the first such API released on Linux to
15 address a number of important problems, including:
16
17 - Supports USB 2.0, for high speed devices which can stream data at
18 several dozen megabytes per second.
19
20 - Handles devices with dozens of endpoints just as well as ones with
21 just two fixed-function ones. Gadget drivers can be written so
22 they're easy to port to new hardware.
23
24 - Flexible enough to expose more complex USB device capabilities such
25 as multiple configurations, multiple interfaces, composite devices,
26 and alternate interface settings.
27
28 - USB "On-The-Go" (OTG) support, in conjunction with updates to the
29 Linux-USB host side.
30
31 - Sharing data structures and API models with the Linux-USB host side
32 API. This helps the OTG support, and looks forward to more-symmetric
33 frameworks (where the same I/O model is used by both host and device
34 side drivers).
35
36 - Minimalist, so it's easier to support new device controller hardware.
37 I/O processing doesn't imply large demands for memory or CPU
38 resources.
39
40 Most Linux developers will not be able to use this API, since they have
41 USB ``host`` hardware in a PC, workstation, or server. Linux users with
42 embedded systems are more likely to have USB peripheral hardware. To
43 distinguish drivers running inside such hardware from the more familiar
44 Linux "USB device drivers", which are host side proxies for the real USB
45 devices, a different term is used: the drivers inside the peripherals
46 are "USB gadget drivers". In USB protocol interactions, the device
47 driver is the master (or "client driver") and the gadget driver is the
48 slave (or "function driver").
49
50 The gadget API resembles the host side Linux-USB API in that both use
51 queues of request objects to package I/O buffers, and those requests may
52 be submitted or canceled. They share common definitions for the standard
53 USB *Chapter 9* messages, structures, and constants. Also, both APIs
54 bind and unbind drivers to devices. The APIs differ in detail, since the
55 host side's current URB framework exposes a number of implementation
56 details and assumptions that are inappropriate for a gadget API. While
57 the model for control transfers and configuration management is
58 necessarily different (one side is a hardware-neutral master, the other
59 is a hardware-aware slave), the endpoint I/0 API used here should also
60 be usable for an overhead-reduced host side API.
61
62 Structure of Gadget Drivers
63 ===========================
64
65 A system running inside a USB peripheral normally has at least three
66 layers inside the kernel to handle USB protocol processing, and may have
67 additional layers in user space code. The ``gadget`` API is used by the
68 middle layer to interact with the lowest level (which directly handles
69 hardware).
70
71 In Linux, from the bottom up, these layers are:
72
73 *USB Controller Driver*
74 This is the lowest software level. It is the only layer that talks
75 to hardware, through registers, fifos, dma, irqs, and the like. The
76 ``<linux/usb/gadget.h>`` API abstracts the peripheral controller
77 endpoint hardware. That hardware is exposed through endpoint
78 objects, which accept streams of IN/OUT buffers, and through
79 callbacks that interact with gadget drivers. Since normal USB
80 devices only have one upstream port, they only have one of these
81 drivers. The controller driver can support any number of different
82 gadget drivers, but only one of them can be used at a time.
83
84 Examples of such controller hardware include the PCI-based NetChip
85 2280 USB 2.0 high speed controller, the SA-11x0 or PXA-25x UDC
86 (found within many PDAs), and a variety of other products.
87
88 *Gadget Driver*
89 The lower boundary of this driver implements hardware-neutral USB
90 functions, using calls to the controller driver. Because such
91 hardware varies widely in capabilities and restrictions, and is used
92 in embedded environments where space is at a premium, the gadget
93 driver is often configured at compile time to work with endpoints
94 supported by one particular controller. Gadget drivers may be
95 portable to several different controllers, using conditional
96 compilation. (Recent kernels substantially simplify the work
97 involved in supporting new hardware, by *autoconfiguring* endpoints
98 automatically for many bulk-oriented drivers.) Gadget driver
99 responsibilities include:
100
101 - handling setup requests (ep0 protocol responses) possibly
102 including class-specific functionality
103
104 - returning configuration and string descriptors
105
106 - (re)setting configurations and interface altsettings, including
107 enabling and configuring endpoints
108
109 - handling life cycle events, such as managing bindings to
110 hardware, USB suspend/resume, remote wakeup, and disconnection
111 from the USB host.
112
113 - managing IN and OUT transfers on all currently enabled endpoints
114
115 Such drivers may be modules of proprietary code, although that
116 approach is discouraged in the Linux community.
117
118 *Upper Level*
119 Most gadget drivers have an upper boundary that connects to some
120 Linux driver or framework in Linux. Through that boundary flows the
121 data which the gadget driver produces and/or consumes through
122 protocol transfers over USB. Examples include:
123
124 - user mode code, using generic (gadgetfs) or application specific
125 files in ``/dev``
126
127 - networking subsystem (for network gadgets, like the CDC Ethernet
128 Model gadget driver)
129
130 - data capture drivers, perhaps video4Linux or a scanner driver; or
131 test and measurement hardware.
132
133 - input subsystem (for HID gadgets)
134
135 - sound subsystem (for audio gadgets)
136
137 - file system (for PTP gadgets)
138
139 - block i/o subsystem (for usb-storage gadgets)
140
141 - ... and more
142
143 *Additional Layers*
144 Other layers may exist. These could include kernel layers, such as
145 network protocol stacks, as well as user mode applications building
146 on standard POSIX system call APIs such as ``open()``, ``close()``,
147 ``read()`` and ``write()``. On newer systems, POSIX Async I/O calls may
148 be an option. Such user mode code will not necessarily be subject to
149 the GNU General Public License (GPL).
150
151 OTG-capable systems will also need to include a standard Linux-USB host
152 side stack, with ``usbcore``, one or more *Host Controller Drivers*
153 (HCDs), *USB Device Drivers* to support the OTG "Targeted Peripheral
154 List", and so forth. There will also be an *OTG Controller Driver*,
155 which is visible to gadget and device driver developers only indirectly.
156 That helps the host and device side USB controllers implement the two
157 new OTG protocols (HNP and SRP). Roles switch (host to peripheral, or
158 vice versa) using HNP during USB suspend processing, and SRP can be
159 viewed as a more battery-friendly kind of device wakeup protocol.
160
161 Over time, reusable utilities are evolving to help make some gadget
162 driver tasks simpler. For example, building configuration descriptors
163 from vectors of descriptors for the configurations interfaces and
164 endpoints is now automated, and many drivers now use autoconfiguration
165 to choose hardware endpoints and initialize their descriptors. A
166 potential example of particular interest is code implementing standard
167 USB-IF protocols for HID, networking, storage, or audio classes. Some
168 developers are interested in KDB or KGDB hooks, to let target hardware
169 be remotely debugged. Most such USB protocol code doesn't need to be
170 hardware-specific, any more than network protocols like X11, HTTP, or
171 NFS are. Such gadget-side interface drivers should eventually be
172 combined, to implement composite devices.
173
174 Kernel Mode Gadget API
175 ======================
176
177 Gadget drivers declare themselves through a struct
178 :c:type:`usb_gadget_driver`, which is responsible for most parts of enumeration
179 for a struct usb_gadget. The response to a set_configuration usually
180 involves enabling one or more of the struct usb_ep objects exposed by
181 the gadget, and submitting one or more struct usb_request buffers to
182 transfer data. Understand those four data types, and their operations,
183 and you will understand how this API works.
184
185 .. Note::
186
187 Other than the "Chapter 9" data types, most of the significant data
188 types and functions are described here.
189
190 However, some relevant information is likely omitted from what you
191 are reading. One example of such information is endpoint
192 autoconfiguration. You'll have to read the header file, and use
193 example source code (such as that for "Gadget Zero"), to fully
194 understand the API.
195
196 The part of the API implementing some basic driver capabilities is
197 specific to the version of the Linux kernel that's in use. The 2.6
198 and upper kernel versions include a *driver model* framework that has
199 no analogue on earlier kernels; so those parts of the gadget API are
200 not fully portable. (They are implemented on 2.4 kernels, but in a
201 different way.) The driver model state is another part of this API that is
202 ignored by the kerneldoc tools.
203
204 The core API does not expose every possible hardware feature, only the
205 most widely available ones. There are significant hardware features,
206 such as device-to-device DMA (without temporary storage in a memory
207 buffer) that would be added using hardware-specific APIs.
208
209 This API allows drivers to use conditional compilation to handle
210 endpoint capabilities of different hardware, but doesn't require that.
211 Hardware tends to have arbitrary restrictions, relating to transfer
212 types, addressing, packet sizes, buffering, and availability. As a rule,
213 such differences only matter for "endpoint zero" logic that handles
214 device configuration and management. The API supports limited run-time
215 detection of capabilities, through naming conventions for endpoints.
216 Many drivers will be able to at least partially autoconfigure
217 themselves. In particular, driver init sections will often have endpoint
218 autoconfiguration logic that scans the hardware's list of endpoints to
219 find ones matching the driver requirements (relying on those
220 conventions), to eliminate some of the most common reasons for
221 conditional compilation.
222
223 Like the Linux-USB host side API, this API exposes the "chunky" nature
224 of USB messages: I/O requests are in terms of one or more "packets", and
225 packet boundaries are visible to drivers. Compared to RS-232 serial
226 protocols, USB resembles synchronous protocols like HDLC (N bytes per
227 frame, multipoint addressing, host as the primary station and devices as
228 secondary stations) more than asynchronous ones (tty style: 8 data bits
229 per frame, no parity, one stop bit). So for example the controller
230 drivers won't buffer two single byte writes into a single two-byte USB
231 IN packet, although gadget drivers may do so when they implement
232 protocols where packet boundaries (and "short packets") are not
233 significant.
234
235 Driver Life Cycle
236 -----------------
237
238 Gadget drivers make endpoint I/O requests to hardware without needing to
239 know many details of the hardware, but driver setup/configuration code
240 needs to handle some differences. Use the API like this:
241
242 1. Register a driver for the particular device side usb controller
243 hardware, such as the net2280 on PCI (USB 2.0), sa11x0 or pxa25x as
244 found in Linux PDAs, and so on. At this point the device is logically
245 in the USB ch9 initial state (``attached``), drawing no power and not
246 usable (since it does not yet support enumeration). Any host should
247 not see the device, since it's not activated the data line pullup
248 used by the host to detect a device, even if VBUS power is available.
249
250 2. Register a gadget driver that implements some higher level device
251 function. That will then bind() to a :c:type:`usb_gadget`, which activates
252 the data line pullup sometime after detecting VBUS.
253
254 3. The hardware driver can now start enumerating. The steps it handles
255 are to accept USB ``power`` and ``set_address`` requests. Other steps are
256 handled by the gadget driver. If the gadget driver module is unloaded
257 before the host starts to enumerate, steps before step 7 are skipped.
258
259 4. The gadget driver's ``setup()`` call returns usb descriptors, based both
260 on what the bus interface hardware provides and on the functionality
261 being implemented. That can involve alternate settings or
262 configurations, unless the hardware prevents such operation. For OTG
263 devices, each configuration descriptor includes an OTG descriptor.
264
265 5. The gadget driver handles the last step of enumeration, when the USB
266 host issues a ``set_configuration`` call. It enables all endpoints used
267 in that configuration, with all interfaces in their default settings.
268 That involves using a list of the hardware's endpoints, enabling each
269 endpoint according to its descriptor. It may also involve using
270 ``usb_gadget_vbus_draw`` to let more power be drawn from VBUS, as
271 allowed by that configuration. For OTG devices, setting a
272 configuration may also involve reporting HNP capabilities through a
273 user interface.
274
275 6. Do real work and perform data transfers, possibly involving changes
276 to interface settings or switching to new configurations, until the
277 device is disconnect()ed from the host. Queue any number of transfer
278 requests to each endpoint. It may be suspended and resumed several
279 times before being disconnected. On disconnect, the drivers go back
280 to step 3 (above).
281
282 7. When the gadget driver module is being unloaded, the driver unbind()
283 callback is issued. That lets the controller driver be unloaded.
284
285 Drivers will normally be arranged so that just loading the gadget driver
286 module (or statically linking it into a Linux kernel) allows the
287 peripheral device to be enumerated, but some drivers will defer
288 enumeration until some higher level component (like a user mode daemon)
289 enables it. Note that at this lowest level there are no policies about
290 how ep0 configuration logic is implemented, except that it should obey
291 USB specifications. Such issues are in the domain of gadget drivers,
292 including knowing about implementation constraints imposed by some USB
293 controllers or understanding that composite devices might happen to be
294 built by integrating reusable components.
295
296 Note that the lifecycle above can be slightly different for OTG devices.
297 Other than providing an additional OTG descriptor in each configuration,
298 only the HNP-related differences are particularly visible to driver
299 code. They involve reporting requirements during the ``SET_CONFIGURATION``
300 request, and the option to invoke HNP during some suspend callbacks.
301 Also, SRP changes the semantics of ``usb_gadget_wakeup`` slightly.
302
303 USB 2.0 Chapter 9 Types and Constants
304 -------------------------------------
305
306 Gadget drivers rely on common USB structures and constants defined in
307 the :ref:`linux/usb/ch9.h <usb_chapter9>` header file, which is standard in
308 Linux 2.6+ kernels. These are the same types and constants used by host side
309 drivers (and usbcore).
310
311 Core Objects and Methods
312 ------------------------
313
314 These are declared in ``<linux/usb/gadget.h>``, and are used by gadget
315 drivers to interact with USB peripheral controller drivers.
316
317 .. kernel-doc:: include/linux/usb/gadget.h
318 :internal:
319
320 Optional Utilities
321 ------------------
322
323 The core API is sufficient for writing a USB Gadget Driver, but some
324 optional utilities are provided to simplify common tasks. These
325 utilities include endpoint autoconfiguration.
326
327 .. kernel-doc:: drivers/usb/gadget/usbstring.c
328 :export:
329
330 .. kernel-doc:: drivers/usb/gadget/config.c
331 :export:
332
333 Composite Device Framework
334 --------------------------
335
336 The core API is sufficient for writing drivers for composite USB devices
337 (with more than one function in a given configuration), and also
338 multi-configuration devices (also more than one function, but not
339 necessarily sharing a given configuration). There is however an optional
340 framework which makes it easier to reuse and combine functions.
341
342 Devices using this framework provide a struct usb_composite_driver,
343 which in turn provides one or more struct usb_configuration
344 instances. Each such configuration includes at least one struct
345 :c:type:`usb_function`, which packages a user visible role such as "network
346 link" or "mass storage device". Management functions may also exist,
347 such as "Device Firmware Upgrade".
348
349 .. kernel-doc:: include/linux/usb/composite.h
350 :internal:
351
352 .. kernel-doc:: drivers/usb/gadget/composite.c
353 :export:
354
355 Composite Device Functions
356 --------------------------
357
358 At this writing, a few of the current gadget drivers have been converted
359 to this framework. Near-term plans include converting all of them,
360 except for ``gadgetfs``.
361
362 Peripheral Controller Drivers
363 =============================
364
365 The first hardware supporting this API was the NetChip 2280 controller,
366 which supports USB 2.0 high speed and is based on PCI. This is the
367 ``net2280`` driver module. The driver supports Linux kernel versions 2.4
368 and 2.6; contact NetChip Technologies for development boards and product
369 information.
370
371 Other hardware working in the ``gadget`` framework includes: Intel's PXA
372 25x and IXP42x series processors (``pxa2xx_udc``), Toshiba TC86c001
373 "Goku-S" (``goku_udc``), Renesas SH7705/7727 (``sh_udc``), MediaQ 11xx
374 (``mq11xx_udc``), Hynix HMS30C7202 (``h7202_udc``), National 9303/4
375 (``n9604_udc``), Texas Instruments OMAP (``omap_udc``), Sharp LH7A40x
376 (``lh7a40x_udc``), and more. Most of those are full speed controllers.
377
378 At this writing, there are people at work on drivers in this framework
379 for several other USB device controllers, with plans to make many of
380 them be widely available.
381
382 A partial USB simulator, the ``dummy_hcd`` driver, is available. It can
383 act like a net2280, a pxa25x, or an sa11x0 in terms of available
384 endpoints and device speeds; and it simulates control, bulk, and to some
385 extent interrupt transfers. That lets you develop some parts of a gadget
386 driver on a normal PC, without any special hardware, and perhaps with
387 the assistance of tools such as GDB running with User Mode Linux. At
388 least one person has expressed interest in adapting that approach,
389 hooking it up to a simulator for a microcontroller. Such simulators can
390 help debug subsystems where the runtime hardware is unfriendly to
391 software development, or is not yet available.
392
393 Support for other controllers is expected to be developed and
394 contributed over time, as this driver framework evolves.
395
396 Gadget Drivers
397 ==============
398
399 In addition to *Gadget Zero* (used primarily for testing and development
400 with drivers for usb controller hardware), other gadget drivers exist.
401
402 There's an ``ethernet`` gadget driver, which implements one of the most
403 useful *Communications Device Class* (CDC) models. One of the standards
404 for cable modem interoperability even specifies the use of this ethernet
405 model as one of two mandatory options. Gadgets using this code look to a
406 USB host as if they're an Ethernet adapter. It provides access to a
407 network where the gadget's CPU is one host, which could easily be
408 bridging, routing, or firewalling access to other networks. Since some
409 hardware can't fully implement the CDC Ethernet requirements, this
410 driver also implements a "good parts only" subset of CDC Ethernet. (That
411 subset doesn't advertise itself as CDC Ethernet, to avoid creating
412 problems.)
413
414 Support for Microsoft's ``RNDIS`` protocol has been contributed by
415 Pengutronix and Auerswald GmbH. This is like CDC Ethernet, but it runs
416 on more slightly USB hardware (but less than the CDC subset). However,
417 its main claim to fame is being able to connect directly to recent
418 versions of Windows, using drivers that Microsoft bundles and supports,
419 making it much simpler to network with Windows.
420
421 There is also support for user mode gadget drivers, using ``gadgetfs``.
422 This provides a *User Mode API* that presents each endpoint as a single
423 file descriptor. I/O is done using normal ``read()`` and ``read()`` calls.
424 Familiar tools like GDB and pthreads can be used to develop and debug
425 user mode drivers, so that once a robust controller driver is available
426 many applications for it won't require new kernel mode software. Linux
427 2.6 *Async I/O (AIO)* support is available, so that user mode software
428 can stream data with only slightly more overhead than a kernel driver.
429
430 There's a USB Mass Storage class driver, which provides a different
431 solution for interoperability with systems such as MS-Windows and MacOS.
432 That *Mass Storage* driver uses a file or block device as backing store
433 for a drive, like the ``loop`` driver. The USB host uses the BBB, CB, or
434 CBI versions of the mass storage class specification, using transparent
435 SCSI commands to access the data from the backing store.
436
437 There's a "serial line" driver, useful for TTY style operation over USB.
438 The latest version of that driver supports CDC ACM style operation, like
439 a USB modem, and so on most hardware it can interoperate easily with
440 MS-Windows. One interesting use of that driver is in boot firmware (like
441 a BIOS), which can sometimes use that model with very small systems
442 without real serial lines.
443
444 Support for other kinds of gadget is expected to be developed and
445 contributed over time, as this driver framework evolves.
446
447 USB On-The-GO (OTG)
448 ===================
449
450 USB OTG support on Linux 2.6 was initially developed by Texas
451 Instruments for `OMAP <http://www.omap.com>`__ 16xx and 17xx series
452 processors. Other OTG systems should work in similar ways, but the
453 hardware level details could be very different.
454
455 Systems need specialized hardware support to implement OTG, notably
456 including a special *Mini-AB* jack and associated transceiver to support
457 *Dual-Role* operation: they can act either as a host, using the standard
458 Linux-USB host side driver stack, or as a peripheral, using this
459 ``gadget`` framework. To do that, the system software relies on small
460 additions to those programming interfaces, and on a new internal
461 component (here called an "OTG Controller") affecting which driver stack
462 connects to the OTG port. In each role, the system can re-use the
463 existing pool of hardware-neutral drivers, layered on top of the
464 controller driver interfaces (:c:type:`usb_bus` or :c:type:`usb_gadget`).
465 Such drivers need at most minor changes, and most of the calls added to
466 support OTG can also benefit non-OTG products.
467
468 - Gadget drivers test the ``is_otg`` flag, and use it to determine
469 whether or not to include an OTG descriptor in each of their
470 configurations.
471
472 - Gadget drivers may need changes to support the two new OTG protocols,
473 exposed in new gadget attributes such as ``b_hnp_enable`` flag. HNP
474 support should be reported through a user interface (two LEDs could
475 suffice), and is triggered in some cases when the host suspends the
476 peripheral. SRP support can be user-initiated just like remote
477 wakeup, probably by pressing the same button.
478
479 - On the host side, USB device drivers need to be taught to trigger HNP
480 at appropriate moments, using ``usb_suspend_device()``. That also
481 conserves battery power, which is useful even for non-OTG
482 configurations.
483
484 - Also on the host side, a driver must support the OTG "Targeted
485 Peripheral List". That's just a whitelist, used to reject peripherals
486 not supported with a given Linux OTG host. *This whitelist is
487 product-specific; each product must modify* ``otg_whitelist.h`` *to
488 match its interoperability specification.*
489
490 Non-OTG Linux hosts, like PCs and workstations, normally have some
491 solution for adding drivers, so that peripherals that aren't
492 recognized can eventually be supported. That approach is unreasonable
493 for consumer products that may never have their firmware upgraded,
494 and where it's usually unrealistic to expect traditional
495 PC/workstation/server kinds of support model to work. For example,
496 it's often impractical to change device firmware once the product has
497 been distributed, so driver bugs can't normally be fixed if they're
498 found after shipment.
499
500 Additional changes are needed below those hardware-neutral :c:type:`usb_bus`
501 and :c:type:`usb_gadget` driver interfaces; those aren't discussed here in any
502 detail. Those affect the hardware-specific code for each USB Host or
503 Peripheral controller, and how the HCD initializes (since OTG can be
504 active only on a single port). They also involve what may be called an
505 *OTG Controller Driver*, managing the OTG transceiver and the OTG state
506 machine logic as well as much of the root hub behavior for the OTG port.
507 The OTG controller driver needs to activate and deactivate USB
508 controllers depending on the relevant device role. Some related changes
509 were needed inside usbcore, so that it can identify OTG-capable devices
510 and respond appropriately to HNP or SRP protocols.
511

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은 다릅니다.

Gadget API 설계 목표
목표내용
속도와 규모USB 2.0 high speed, 수십 endpoint와 단순 두 endpoint 모두 지원
복합 기능multiple configuration·interface·alternate setting·composite device
OTGhost 측 갱신과 함께 On-The-Go 지원
공유 modelhost와 Chapter 9 정의 및 request queue 개념 공유
경량성새 controller 지원과 I/O에 큰 memory·CPU 요구를 만들지 않음

========================
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-117

USB 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 전송 관리를 맡습니다.

Gadget kernel 계층
상위 subsystem·user spacenetwork, input, sound, filesystem, block I/O, application
Gadget DriverUSB function·descriptor·configuration·endpoint transfer
`<linux/usb/gadget.h>`hardware-neutral endpoint·request API
USB Controller Driverregister·FIFO·DMA·IRQ와 직접 통신
USB peripheral hardwareupstream port와 endpoint

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를 구성하는 방향으로 발전합니다.

Gadget 상위 연결점
연결 대상대표 역할
User mode`gadgetfs`, `/dev`, POSIX I/O·AIO
NetworkCDC Ethernet과 protocol stack
Media·measurementvideo4Linux, scanner, capture hardware
Input·soundHID gadget, audio gadget
Filesystem·blockPTP, usb-storage
OTG host stack`usbcore`, HCD, Targeted Peripheral List, HNP·SRP

*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-234

Gadget 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는 이를 합칠 수 있습니다.

Gadget API 네 핵심 객체
객체책임
`struct usb_gadget_driver`function driver 선언과 enumeration 처리
`struct usb_gadget`device-side controller와 전체 gadget 표현
`struct usb_ep`hardware endpoint를 추상화하고 enable·queue 수행
`struct usb_request`I/O buffer, 길이, completion을 담는 전송 request

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-302

Gadget 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()` 의미를 약간 바꿉니다.

Gadget driver 7단계 lifecycle
1. Controller 등록Chapter 9 `attached`, pullup 비활성
2. Gadget 등록`bind()` 후 VBUS 감지와 pullup 활성
3. Enumeration 시작hardware가 `power`·`set_address` 처리
4. `setup()`descriptor와 OTG descriptor 반환
5. `set_configuration`endpoint enable, VBUS power·HNP 설정
6. Data I/Orequest queue, suspend·resume, disconnect 시 3단계
7. Module unload`unbind()` 호출

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-361

Gadget 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`를 제외한 나머지도 전환할 계획이었습니다.

Composite gadget 구성
`struct usb_function`network, storage, DFU 같은 단일 역할
`struct usb_configuration`하나 이상의 function과 interface·endpoint 묶음
`struct usb_composite_driver`하나 이상의 configuration 제공
Composite gadget devicehost에 복합 또는 다중 configuration device로 노출

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에 도움이 됩니다.

Gadget controller driver 예
DriverHardware·용도
`net2280`PCI NetChip 2280, USB 2.0 high speed
`pxa2xx_udc`Intel PXA25x·IXP42x
`goku_udc`Toshiba TC86c001 Goku-S
`sh_udc`Renesas SH7705/7727
`omap_udc`Texas Instruments OMAP
`dummy_hcd`PC에서 endpoint·speed·transfer를 흉내 내는 simulator

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 driver
Driver·protocolHost에 보이는 기능
Gadget Zerocontroller 시험과 개발
CDC EthernetUSB Ethernet adapter, bridge·routing·firewall
`RNDIS`Windows bundled driver와 network 연결
`gadgetfs`endpoint별 file descriptor를 쓰는 user-mode gadget
Mass Storagefile·block backing store와 SCSI 접근
CDC ACM serialUSB modem·TTY style serial line

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-510

Linux 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 역할 전환 구조
Mini-AB·transceiverDual-Role hardware와 cable 상태 감지
OTG Controller Driverstate machine과 root hub, controller 활성화 관리
Host role`usb_bus`, HCD, Targeted Peripheral List, `usb_suspend_device()`
Peripheral role`usb_gadget`, `is_otg`, OTG descriptor, `b_hnp_enable`
ProtocolHNP로 역할 전환, SRP로 session 요청·wakeup

하나의 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.