gadget.rst 25 KB

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