code:
===============================================================
Synopsys DesignWare Core SuperSpeed USB 3.0 Controller
===============================================================

:Author: Felipe Balbi <felipe.balbi@linux.intel.com>
:Date: April 2017

Introduction
============

The *Synopsys DesignWare Core SuperSpeed USB 3.0 Controller*
(hereinafter referred to as *DWC3*) is a USB SuperSpeed compliant
controller which can be configured in one of 4 ways:

	1. Peripheral-only configuration
	2. Host-only configuration
	3. Dual-Role configuration
	4. Hub configuration

Linux currently supports several versions of this controller. In all
likelyhood, the version in your SoC is already supported. At the time
of this writing, known tested versions range from 2.02a to 3.10a. As a
rule of thumb, anything above 2.02a should work reliably well.

Currently, we have many known users for this driver. In alphabetical
order:

	1. Cavium
	2. Intel Corporation
	3. Qualcomm
	4. Rockchip
	5. ST
	6. Samsung
	7. Texas Instruments
	8. Xilinx

Summary of Features
======================

For details about features supported by your version of DWC3, consult
your IP team and/or *Synopsys DesignWare Core SuperSpeed USB 3.0
Controller Databook*. Following is a list of features supported by the
driver at the time of this writing:

	1. Up to 16 bidirectional endpoints (including the control
	   pipe - ep0)
	2. Flexible endpoint configuration
	3. Simultaneous IN and OUT transfer support
	4. Scatter-list support
	5. Up to 256 TRBs [#trb]_ per endpoint
	6. Support for all transfer types (*Control*, *Bulk*,
	   *Interrupt*, and *Isochronous*)
	7. SuperSpeed Bulk Streams
	8. Link Power Management
	9. Trace Events for debugging
	10. DebugFS [#debugfs]_ interface

These features have all been exercised with many of the **in-tree**
gadget drivers. We have verified both *ConfigFS* [#configfs]_ and
legacy gadget drivers.

Driver Design
==============

The DWC3 driver sits on the *drivers/usb/dwc3/* directory. All files
related to this driver are in this one directory. This makes it easy
for new-comers to read the code and understand how it behaves.

Because of DWC3's configuration flexibility, the driver is a little
complex in some places but it should be rather straightforward to
understand.

The biggest part of the driver refers to the Gadget API.

Known Limitations
===================

Like any other HW, DWC3 has its own set of limitations. To avoid
constant questions about such problems, we decided to document them
here and have a single location to where we could point users.

OUT Transfer Size Requirements
---------------------------------

According to Synopsys Databook, all OUT transfer TRBs [#trb]_ must
have their *size* field set to a value which is integer divisible by
the endpoint's *wMaxPacketSize*. This means that *e.g.* in order to
receive a Mass Storage *CBW* [#cbw]_, req->length must either be set
to a value that's divisible by *wMaxPacketSize* (1024 on SuperSpeed,
512 on HighSpeed, etc), or DWC3 driver must add a Chained TRB pointing
to a throw-away buffer for the remaining length. Without this, OUT
transfers will **NOT** start.

Note that as of this writing, this won't be a problem because DWC3 is
fully capable of appending a chained TRB for the remaining length and
completely hide this detail from the gadget driver. It's still worth
mentioning because this seems to be the largest source of queries
about DWC3 and *non-working transfers*.

TRB Ring Size Limitation
-------------------------

We, currently, have a hard limit of 256 TRBs [#trb]_ per endpoint,
with the last TRB being a Link TRB [#link_trb]_ pointing back to the
first. This limit is arbitrary but it has the benefit of adding up to
exactly 4096 bytes, or 1 Page.

DWC3 driver will try its best to cope with more than 255 requests and,
for the most part, it should work normally. However this is not
something that has been exercised very frequently. If you experience
any problems, see section **Reporting Bugs** below.

Reporting Bugs
================

Whenever you encounter a problem with DWC3, first and foremost you
should make sure that:

	1. You're running latest tag from `Linus' tree`_
	2. You can reproduce the error without any out-of-tree changes
	   to DWC3
	3. You have checked that it's not a fault on the host machine

After all these are verified, then here's how to capture enough
information so we can be of any help to you.

Required Information
---------------------

DWC3 relies exclusively on Trace Events for debugging. Everything is
exposed there, with some extra bits being exposed to DebugFS
[#debugfs]_.

In order to capture DWC3's Trace Events you should run the following
commands **before** plugging the USB cable to a host machine:

.. code-block:: sh

		 # mkdir -p /d
		 # mkdir -p /t
		 # mount -t debugfs none /d
		 # mount -t tracefs none /t
		 # echo 81920 > /t/buffer_size_kb
		 # echo 1 > /t/events/dwc3/enable

After this is done, you can connect your USB cable and reproduce the
problem. As soon as the fault is reproduced, make a copy of files
``trace`` and ``regdump``, like so:

.. code-block:: sh

		# cp /t/trace /root/trace.txt
		# cat /d/*dwc3*/regdump > /root/regdump.txt

Make sure to compress ``trace.txt`` and ``regdump.txt`` in a tarball
and email it to `me`_ with `linux-usb`_ in Cc. If you want to be extra
sure that I'll help you, write your subject line in the following
format:

	**[BUG REPORT] usb: dwc3: Bug while doing XYZ**

On the email body, make sure to detail what you doing, which gadget
driver you were using, how to reproduce the problem, what SoC you're
using, which OS (and its version) was running on the Host machine.

With all this information, we should be able to understand what's
going on and be helpful to you.

Debugging
===========

First and foremost a disclaimer::

  DISCLAIMER: The information available on DebugFS and/or TraceFS can
  change at any time at any Major Linux Kernel Release. If writing
  scripts, do **NOT** assume information to be available in the
  current format.

With that out of the way, let's carry on.

If you're willing to debug your own problem, you deserve a round of
applause :-)

Anyway, there isn't much to say here other than Trace Events will be
really helpful in figuring out issues with DWC3. Also, access to
Synopsys Databook will be **really** valuable in this case.

A USB Sniffer can be helpful at times but it's not entirely required,
there's a lot that can be understood without looking at the wire.

Feel free to email `me`_ and Cc `linux-usb`_ if you need any help.

``DebugFS``
-------------

``DebugFS`` is very good for gathering snapshots of what's going on
with DWC3 and/or any endpoint.

On DWC3's ``DebugFS`` directory, you will find the following files and
directories:

``ep[0..15]{in,out}/``
``link_state``
``regdump``
``testmode``

``link_state``
``````````````

When read, ``link_state`` will print out one of ``U0``, ``U1``,
``U2``, ``U3``, ``SS.Disabled``, ``RX.Detect``, ``SS.Inactive``,
``Polling``, ``Recovery``, ``Hot Reset``, ``Compliance``,
``Loopback``, ``Reset``, ``Resume`` or ``UNKNOWN link state``.

This file can also be written to in order to force link to one of the
states above.

``regdump``
`````````````

File name is self-explanatory. When read, ``regdump`` will print out a
register dump of DWC3. Note that this file can be grepped to find the
information you want.

``testmode``
``````````````

When read, ``testmode`` will print out a name of one of the specified
USB 2.0 Testmodes (``test_j``, ``test_k``, ``test_se0_nak``,
``test_packet``, ``test_force_enable``) or the string ``no test`` in
case no tests are currently being executed.

In order to start any of these test modes, the same strings can be
written to the file and DWC3 will enter the requested test mode.

``ep[0..15]{in,out}``
``````````````````````

For each endpoint we expose one directory following the naming
convention ``ep$num$dir`` *(ep0in, ep0out, ep1in, ...)*. Inside each
of these directories you will find the following files:

``descriptor_fetch_queue``
``event_queue``
``rx_fifo_queue``
``rx_info_queue``
``rx_request_queue``
``transfer_type``
``trb_ring``
``tx_fifo_queue``
``tx_request_queue``

With access to Synopsys Databook, you can decode the information on
them.

``transfer_type``
~~~~~~~~~~~~~~~~~~

When read, ``transfer_type`` will print out one of ``control``,
``bulk``, ``interrupt`` or ``isochronous`` depending on what the
endpoint descriptor says. If the endpoint hasn't been enabled yet, it
will print ``--``.

``trb_ring``
~~~~~~~~~~~~~

When read, ``trb_ring`` will print out details about all TRBs on the
ring. It will also tell you where our enqueue and dequeue pointers are
located in the ring:

.. code-block:: sh

		buffer_addr,size,type,ioc,isp_imi,csp,chn,lst,hwo
		000000002c754000,481,normal,1,0,1,0,0,0
		000000002c75c000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c754000,481,normal,1,0,1,0,0,0
		000000002c75c000,481,normal,1,0,1,0,0,0
		000000002c784000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c784000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c754000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c784000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c784000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c754000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c75c000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c754000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c754000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c754000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c75c000,481,normal,1,0,1,0,0,0
		000000002c780000,481,normal,1,0,1,0,0,0
		000000002c784000,481,normal,1,0,1,0,0,0
		000000002c788000,481,normal,1,0,1,0,0,0
		000000002c78c000,481,normal,1,0,1,0,0,0
		000000002c790000,481,normal,1,0,1,0,0,0
		000000002c754000,481,normal,1,0,1,0,0,0
		000000002c758000,481,normal,1,0,1,0,0,0
		000000002c75c000,512,normal,1,0,1,0,0,1        D
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0       E
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		0000000000000000,0,UNKNOWN,0,0,0,0,0,0
		00000000381ab000,0,link,0,0,0,0,0,1

Trace Events
-------------

DWC3 also provides several trace events which help us gathering
information about the behavior of the driver during runtime.

In order to use these events, you must enable ``CONFIG_FTRACE`` in
your kernel config.

For details about how enable DWC3 events, see section **Reporting
Bugs**.

The following subsections will give details about each Event Class and
each Event defined by DWC3.

MMIO
```````

It is sometimes useful to look at every MMIO access when looking for
bugs. Because of that, DWC3 offers two Trace Events (one for
dwc3_readl() and one for dwc3_writel()). ``TP_printk`` follows::

  TP_printk("addr %p value %08x", __entry->base + __entry->offset,
  		__entry->value)

Interrupt Events
````````````````

Every IRQ event can be logged and decoded into a human readable
string. Because every event will be different, we don't give an
example other than the ``TP_printk`` format used::

  TP_printk("event (%08x): %s", __entry->event,
  		dwc3_decode_event(__entry->event, __entry->ep0state))

Control Request
`````````````````

Every USB Control Request can be logged to the trace buffer. The
output format is::

  TP_printk("%s", dwc3_decode_ctrl(__entry->bRequestType,
  				__entry->bRequest, __entry->wValue,
  				__entry->wIndex, __entry->wLength)
  )

Note that Standard Control Requests will be decoded into
human-readable strings with their respective arguments. Class and
Vendor requests will be printed out a sequence of 8 bytes in hex
format.

Lifetime of a ``struct usb_request``
```````````````````````````````````````

The entire lifetime of a ``struct usb_request`` can be tracked on the
trace buffer. We have one event for each of allocation, free,
queueing, dequeueing, and giveback. Output format is::

  TP_printk("%s: req %p length %u/%u %s%s%s ==> %d",
  	__get_str(name), __entry->req, __entry->actual, __entry->length,
  	__entry->zero ? "Z" : "z",
  	__entry->short_not_ok ? "S" : "s",
  	__entry->no_interrupt ? "i" : "I",
  	__entry->status
  )

Generic Commands
````````````````````

We can log and decode every Generic Command with its completion
code. Format is::

  TP_printk("cmd '%s' [%x] param %08x --> status: %s",
  	dwc3_gadget_generic_cmd_string(__entry->cmd),
  	__entry->cmd, __entry->param,
  	dwc3_gadget_generic_cmd_status_string(__entry->status)
  )

Endpoint Commands
````````````````````

Endpoints commands can also be logged together with completion
code. Format is::

  TP_printk("%s: cmd '%s' [%d] params %08x %08x %08x --> status: %s",
  	__get_str(name), dwc3_gadget_ep_cmd_string(__entry->cmd),
  	__entry->cmd, __entry->param0,
  	__entry->param1, __entry->param2,
  	dwc3_ep_cmd_status_string(__entry->cmd_status)
  )

Lifetime of a ``TRB``
``````````````````````

A ``TRB`` Lifetime is simple. We are either preparing a ``TRB`` or
completing it. With these two events, we can see how a ``TRB`` changes
over time. Format is::

  TP_printk("%s: %d/%d trb %p buf %08x%08x size %s%d ctrl %08x (%c%c%c%c:%c%c:%s)",
  	__get_str(name), __entry->queued, __entry->allocated,
  	__entry->trb, __entry->bph, __entry->bpl,
  	({char *s;
  	int pcm = ((__entry->size >> 24) & 3) + 1;
  	switch (__entry->type) {
  	case USB_ENDPOINT_XFER_INT:
  	case USB_ENDPOINT_XFER_ISOC:
  		switch (pcm) {
  		case 1:
  			s = "1x ";
  			break;
  		case 2:
  			s = "2x ";
  			break;
  		case 3:
  			s = "3x ";
  			break;
  		}
  	default:
  		s = "";
  	} s; }),
  	DWC3_TRB_SIZE_LENGTH(__entry->size), __entry->ctrl,
  	__entry->ctrl & DWC3_TRB_CTRL_HWO ? 'H' : 'h',
  	__entry->ctrl & DWC3_TRB_CTRL_LST ? 'L' : 'l',
  	__entry->ctrl & DWC3_TRB_CTRL_CHN ? 'C' : 'c',
  	__entry->ctrl & DWC3_TRB_CTRL_CSP ? 'S' : 's',
  	__entry->ctrl & DWC3_TRB_CTRL_ISP_IMI ? 'S' : 's',
  	__entry->ctrl & DWC3_TRB_CTRL_IOC ? 'C' : 'c',
      dwc3_trb_type_string(DWC3_TRBCTL_TYPE(__entry->ctrl))
  )

Lifetime of an Endpoint
```````````````````````

And endpoint's lifetime is summarized with enable and disable
operations, both of which can be traced. Format is::

  TP_printk("%s: mps %d/%d streams %d burst %d ring %d/%d flags %c:%c%c%c%c%c:%c:%c",
  	__get_str(name), __entry->maxpacket,
  	__entry->maxpacket_limit, __entry->max_streams,
  	__entry->maxburst, __entry->trb_enqueue,
  	__entry->trb_dequeue,
  	__entry->flags & DWC3_EP_ENABLED ? 'E' : 'e',
  	__entry->flags & DWC3_EP_STALL ? 'S' : 's',
  	__entry->flags & DWC3_EP_WEDGE ? 'W' : 'w',
  	__entry->flags & DWC3_EP_TRANSFER_STARTED ? 'B' : 'b',
  	__entry->flags & DWC3_EP_PENDING_REQUEST ? 'P' : 'p',
  	__entry->flags & DWC3_EP_END_TRANSFER_PENDING ? 'E' : 'e',
  	__entry->direction ? '<' : '>'
  )

Structures, Methods and Definitions
====================================

.. kernel-doc:: drivers/usb/dwc3/core.h
   :doc: main data structures
   :internal:

.. kernel-doc:: drivers/usb/dwc3/gadget.h
   :doc: gadget-only helpers
   :internal:

.. kernel-doc:: drivers/usb/dwc3/gadget.c
   :doc: gadget-side implementation
   :internal:

.. kernel-doc:: drivers/usb/dwc3/core.c
   :doc: core driver (probe, PM, etc)
   :internal:

.. [#trb] Transfer Request Block
.. [#link_trb] Transfer Request Block pointing to another Transfer
	       Request Block.
.. [#debugfs] The Debug File System
.. [#configfs] The Config File System
.. [#cbw] Command Block Wrapper
.. _Linus' tree: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/
.. _me: felipe.balbi@linux.intel.com
.. _linux-usb: linux-usb@vger.kernel.org


code:
.. _usb-error-codes:

USB Error codes
~~~~~~~~~~~~~~~

:Revised: 2004-Oct-21

This is the documentation of (hopefully) all possible error codes (and
their interpretation) that can be returned from usbcore.

Some of them are returned by the Host Controller Drivers (HCDs), which
device drivers only see through usbcore.  As a rule, all the HCDs should
behave the same except for transfer speed dependent behaviors and the
way certain faults are reported.

Error codes returned by :c:func:`usb_submit_urb`
================================================

Non-USB-specific:

=============== ===============================================
0		URB submission went fine

``-ENOMEM``	no memory for allocation of internal structures
=============== ===============================================

USB-specific:

=======================	=======================================================
``-EBUSY``		The URB is already active.

``-ENODEV``		specified USB-device or bus doesn't exist

``-ENOENT``		specified interface or endpoint does not exist or
			is not enabled

``-ENXIO``		host controller driver does not support queuing of
			this type of urb.  (treat as a host controller bug.)

``-EINVAL``		a) Invalid transfer type specified (or not supported)
			b) Invalid or unsupported periodic transfer interval
			c) ISO: attempted to change transfer interval
			d) ISO: ``number_of_packets`` is < 0
			e) various other cases

``-EXDEV``		ISO: ``URB_ISO_ASAP`` wasn't specified and all the
			frames the URB would be scheduled in have already
			expired.

``-EFBIG``		Host controller driver can't schedule that many ISO
			frames.

``-EPIPE``		The pipe type specified in the URB doesn't match the
			endpoint's actual type.

``-EMSGSIZE``		(a) endpoint maxpacket size is zero; it is not usable
			    in the current interface altsetting.
			(b) ISO packet is larger than the endpoint maxpacket.
			(c) requested data transfer length is invalid: negative
			    or too large for the host controller.

``-EBADR``		The wLength value in a control URB's setup packet does
			not match the URB's transfer_buffer_length.

``-ENOSPC``		This request would overcommit the usb bandwidth reserved
			for periodic transfers (interrupt, isochronous).

``-ESHUTDOWN``		The device or host controller has been disabled due to
			some problem that could not be worked around.

``-EPERM``		Submission failed because ``urb->reject`` was set.

``-EHOSTUNREACH``	URB was rejected because the device is suspended.

``-ENOEXEC``		A control URB doesn't contain a Setup packet.
=======================	=======================================================

Error codes returned by ``in urb->status`` or in ``iso_frame_desc[n].status`` (for ISO)
=======================================================================================

USB device drivers may only test urb status values in completion handlers.
This is because otherwise there would be a race between HCDs updating
these values on one CPU, and device drivers testing them on another CPU.

A transfer's actual_length may be positive even when an error has been
reported.  That's because transfers often involve several packets, so that
one or more packets could finish before an error stops further endpoint I/O.

For isochronous URBs, the urb status value is non-zero only if the URB is
unlinked, the device is removed, the host controller is disabled, or the total
transferred length is less than the requested length and the
``URB_SHORT_NOT_OK`` flag is set.  Completion handlers for isochronous URBs
should only see ``urb->status`` set to zero, ``-ENOENT``, ``-ECONNRESET``,
``-ESHUTDOWN``, or ``-EREMOTEIO``. Individual frame descriptor status fields
may report more status codes.

===============================	===============================================
0				Transfer completed successfully

``-ENOENT``			URB was synchronously unlinked by
				:c:func:`usb_unlink_urb`

``-EINPROGRESS``		URB still pending, no results yet
				(That is, if drivers see this it's a bug.)

``-EPROTO`` [#f1]_, [#f2]_	a) bitstuff error
				b) no response packet received within the
				   prescribed bus turn-around time
				c) unknown USB error

``-EILSEQ`` [#f1]_, [#f2]_	a) CRC mismatch
				b) no response packet received within the
				   prescribed bus turn-around time
				c) unknown USB error

				Note that often the controller hardware does
				not distinguish among cases a), b), and c), so
				a driver cannot tell whether there was a
				protocol error, a failure to respond (often
				caused by device disconnect), or some other
				fault.

``-ETIME`` [#f2]_		No response packet received within the
				prescribed bus turn-around time.  This error
				may instead be reported as
				``-EPROTO`` or ``-EILSEQ``.

``-ETIMEDOUT``			Synchronous USB message functions use this code
				to indicate timeout expired before the transfer
				completed, and no other error was reported
				by HC.

``-EPIPE`` [#f2]_		Endpoint stalled.  For non-control endpoints,
				reset this status with
				:c:func:`usb_clear_halt`.

``-ECOMM``			During an IN transfer, the host controller
				received data from an endpoint faster than it
				could be written to system memory

``-ENOSR``			During an OUT transfer, the host controller
				could not retrieve data from system memory fast
				enough to keep up with the USB data rate

``-EOVERFLOW`` [#f1]_		The amount of data returned by the endpoint was
				greater than either the max packet size of the
				endpoint or the remaining buffer size.
				"Babble".

``-EREMOTEIO``			The data read from the endpoint did not fill
				the specified buffer, and ``URB_SHORT_NOT_OK``
				was set in ``urb->transfer_flags``.

``-ENODEV``			Device was removed.  Often preceded by a burst
				of other errors, since the hub driver doesn't
				detect device removal events immediately.

``-EXDEV``			ISO transfer only partially completed
				(only set in ``iso_frame_desc[n].status``,
				not ``urb->status``)

``-EINVAL``			ISO madness, if this happens: Log off and
				go home

``-ECONNRESET``			URB was asynchronously unlinked by
				:c:func:`usb_unlink_urb`

``-ESHUTDOWN``			The device or host controller has been
				disabled due to some problem that could not
				be worked around, such as a physical
				disconnect.
===============================	===============================================

.. [#f1]

   Error codes like ``-EPROTO``, ``-EILSEQ`` and ``-EOVERFLOW`` normally
   indicate hardware problems such as bad devices (including firmware)
   or cables.

.. [#f2]

   This is also one of several codes that different kinds of host
   controller use to indicate a transfer has failed because of device
   disconnect.  In the interval before the hub driver starts disconnect
   processing, devices may receive such fault reports for every request.

Error codes returned by usbcore-functions
=========================================

.. note:: expect also other submit and transfer status codes

:c:func:`usb_register`:

======================= ===================================
``-EINVAL``		error during registering new driver
======================= ===================================

``usb_get_*/usb_set_*()``,
:c:func:`usb_control_msg`,
:c:func:`usb_bulk_msg()`:

======================= ==============================================
``-ETIMEDOUT``		Timeout expired before the transfer completed.
======================= ==============================================

repo_name: angery/linux


code:
========================
USB Gadget API for Linux
========================

:Author: David Brownell
:Date:   20 August 2004

Introduction
============

This document presents a Linux-USB "Gadget" kernel mode API, for use
within peripherals and other USB devices that embed Linux. It provides
an overview of the API structure, and shows how that fits into a system
development project. This is the first such API released on Linux to
address a number of important problems, including:

-  Supports USB 2.0, for high speed devices which can stream data at
   several dozen megabytes per second.

-  Handles devices with dozens of endpoints just as well as ones with
   just two fixed-function ones. Gadget drivers can be written so
   they're easy to port to new hardware.

-  Flexible enough to expose more complex USB device capabilities such
   as multiple configurations, multiple interfaces, composite devices,
   and alternate interface settings.

-  USB "On-The-Go" (OTG) support, in conjunction with updates to the
   Linux-USB host side.

-  Sharing data structures and API models with the Linux-USB host side
   API. This helps the OTG support, and looks forward to more-symmetric
   frameworks (where the same I/O model is used by both host and device
   side drivers).

-  Minimalist, so it's easier to support new device controller hardware.
   I/O processing doesn't imply large demands for memory or CPU
   resources.

Most Linux developers will not be able to use this API, since they have
USB ``host`` hardware in a PC, workstation, or server. Linux users with
embedded systems are more likely to have USB peripheral hardware. To
distinguish drivers running inside such hardware from the more familiar
Linux "USB device drivers", which are host side proxies for the real USB
devices, a different term is used: the drivers inside the peripherals
are "USB gadget drivers". In USB protocol interactions, the device
driver is the master (or "client driver") and the gadget driver is the
slave (or "function driver").

The gadget API resembles the host side Linux-USB API in that both use
queues of request objects to package I/O buffers, and those requests may
be submitted or canceled. They share common definitions for the standard
USB *Chapter 9* messages, structures, and constants. Also, both APIs
bind and unbind drivers to devices. The APIs differ in detail, since the
host side's current URB framework exposes a number of implementation
details and assumptions that are inappropriate for a gadget API. While
the model for control transfers and configuration management is
necessarily different (one side is a hardware-neutral master, the other
is a hardware-aware slave), the endpoint I/0 API used here should also
be usable for an overhead-reduced host side API.

Structure of Gadget Drivers
===========================

A system running inside a USB peripheral normally has at least three
layers inside the kernel to handle USB protocol processing, and may have
additional layers in user space code. The ``gadget`` API is used by the
middle layer to interact with the lowest level (which directly handles
hardware).

In Linux, from the bottom up, these layers are:

*USB Controller Driver*
    This is the lowest software level. It is the only layer that talks
    to hardware, through registers, fifos, dma, irqs, and the like. The
    ``<linux/usb/gadget.h>`` API abstracts the peripheral controller
    endpoint hardware. That hardware is exposed through endpoint
    objects, which accept streams of IN/OUT buffers, and through
    callbacks that interact with gadget drivers. Since normal USB
    devices only have one upstream port, they only have one of these
    drivers. The controller driver can support any number of different
    gadget drivers, but only one of them can be used at a time.

    Examples of such controller hardware include the PCI-based NetChip
    2280 USB 2.0 high speed controller, the SA-11x0 or PXA-25x UDC
    (found within many PDAs), and a variety of other products.

*Gadget Driver*
    The lower boundary of this driver implements hardware-neutral USB
    functions, using calls to the controller driver. Because such
    hardware varies widely in capabilities and restrictions, and is used
    in embedded environments where space is at a premium, the gadget
    driver is often configured at compile time to work with endpoints
    supported by one particular controller. Gadget drivers may be
    portable to several different controllers, using conditional
    compilation. (Recent kernels substantially simplify the work
    involved in supporting new hardware, by *autoconfiguring* endpoints
    automatically for many bulk-oriented drivers.) Gadget driver
    responsibilities include:

    -  handling setup requests (ep0 protocol responses) possibly
       including class-specific functionality

    -  returning configuration and string descriptors

    -  (re)setting configurations and interface altsettings, including
       enabling and configuring endpoints

    -  handling life cycle events, such as managing bindings to
       hardware, USB suspend/resume, remote wakeup, and disconnection
       from the USB host.

    -  managing IN and OUT transfers on all currently enabled endpoints

    Such drivers may be modules of proprietary code, although that
    approach is discouraged in the Linux community.

*Upper Level*
    Most gadget drivers have an upper boundary that connects to some
    Linux driver or framework in Linux. Through that boundary flows the
    data which the gadget driver produces and/or consumes through
    protocol transfers over USB. Examples include:

    -  user mode code, using generic (gadgetfs) or application specific
       files in ``/dev``

    -  networking subsystem (for network gadgets, like the CDC Ethernet
       Model gadget driver)

    -  data capture drivers, perhaps video4Linux or a scanner driver; or
       test and measurement hardware.

    -  input subsystem (for HID gadgets)

    -  sound subsystem (for audio gadgets)

    -  file system (for PTP gadgets)

    -  block i/o subsystem (for usb-storage gadgets)

    -  ... and more

*Additional Layers*
    Other layers may exist. These could include kernel layers, such as
    network protocol stacks, as well as user mode applications building
    on standard POSIX system call APIs such as ``open()``, ``close()``,
    ``read()`` and ``write()``. On newer systems, POSIX Async I/O calls may
    be an option. Such user mode code will not necessarily be subject to
    the GNU General Public License (GPL).

OTG-capable systems will also need to include a standard Linux-USB host
side stack, with ``usbcore``, one or more *Host Controller Drivers*
(HCDs), *USB Device Drivers* to support the OTG "Targeted Peripheral
List", and so forth. There will also be an *OTG Controller Driver*,
which is visible to gadget and device driver developers only indirectly.
That helps the host and device side USB controllers implement the two
new OTG protocols (HNP and SRP). Roles switch (host to peripheral, or
vice versa) using HNP during USB suspend processing, and SRP can be
viewed as a more battery-friendly kind of device wakeup protocol.

Over time, reusable utilities are evolving to help make some gadget
driver tasks simpler. For example, building configuration descriptors
from vectors of descriptors for the configurations interfaces and
endpoints is now automated, and many drivers now use autoconfiguration
to choose hardware endpoints and initialize their descriptors. A
potential example of particular interest is code implementing standard
USB-IF protocols for HID, networking, storage, or audio classes. Some
developers are interested in KDB or KGDB hooks, to let target hardware
be remotely debugged. Most such USB protocol code doesn't need to be
hardware-specific, any more than network protocols like X11, HTTP, or
NFS are. Such gadget-side interface drivers should eventually be
combined, to implement composite devices.

Kernel Mode Gadget API
======================

Gadget drivers declare themselves through a struct
:c:type:`usb_gadget_driver`, which is responsible for most parts of enumeration
for a struct usb_gadget. The response to a set_configuration usually
involves enabling one or more of the struct usb_ep objects exposed by
the gadget, and submitting one or more struct usb_request buffers to
transfer data. Understand those four data types, and their operations,
and you will understand how this API works.

.. Note::

    Other than the "Chapter 9" data types, most of the significant data
    types and functions are described here.

    However, some relevant information is likely omitted from what you
    are reading. One example of such information is endpoint
    autoconfiguration. You'll have to read the header file, and use
    example source code (such as that for "Gadget Zero"), to fully
    understand the API.

    The part of the API implementing some basic driver capabilities is
    specific to the version of the Linux kernel that's in use. The 2.6
    and upper kernel versions include a *driver model* framework that has
    no analogue on earlier kernels; so those parts of the gadget API are
    not fully portable. (They are implemented on 2.4 kernels, but in a
    different way.) The driver model state is another part of this API that is
    ignored by the kerneldoc tools.

The core API does not expose every possible hardware feature, only the
most widely available ones. There are significant hardware features,
such as device-to-device DMA (without temporary storage in a memory
buffer) that would be added using hardware-specific APIs.

This API allows drivers to use conditional compilation to handle
endpoint capabilities of different hardware, but doesn't require that.
Hardware tends to have arbitrary restrictions, relating to transfer
types, addressing, packet sizes, buffering, and availability. As a rule,
such differences only matter for "endpoint zero" logic that handles
device configuration and management. The API supports limited run-time
detection of capabilities, through naming conventions for endpoints.
Many drivers will be able to at least partially autoconfigure
themselves. In particular, driver init sections will often have endpoint
autoconfiguration logic that scans the hardware's list of endpoints to
find ones matching the driver requirements (relying on those
conventions), to eliminate some of the most common reasons for
conditional compilation.

Like the Linux-USB host side API, this API exposes the "chunky" nature
of USB messages: I/O requests are in terms of one or more "packets", and
packet boundaries are visible to drivers. Compared to RS-232 serial
protocols, USB resembles synchronous protocols like HDLC (N bytes per
frame, multipoint addressing, host as the primary station and devices as
secondary stations) more than asynchronous ones (tty style: 8 data bits
per frame, no parity, one stop bit). So for example the controller
drivers won't buffer two single byte writes into a single two-byte USB
IN packet, although gadget drivers may do so when they implement
protocols where packet boundaries (and "short packets") are not
significant.

Driver Life Cycle
-----------------

Gadget drivers make endpoint I/O requests to hardware without needing to
know many details of the hardware, but driver setup/configuration code
needs to handle some differences. Use the API like this:

1. Register a driver for the particular device side usb controller
   hardware, such as the net2280 on PCI (USB 2.0), sa11x0 or pxa25x as
   found in Linux PDAs, and so on. At this point the device is logically
   in the USB ch9 initial state (``attached``), drawing no power and not
   usable (since it does not yet support enumeration). Any host should
   not see the device, since it's not activated the data line pullup
   used by the host to detect a device, even if VBUS power is available.

2. Register a gadget driver that implements some higher level device
   function. That will then bind() to a :c:type:`usb_gadget`, which activates
   the data line pullup sometime after detecting VBUS.

3. The hardware driver can now start enumerating. The steps it handles
   are to accept USB ``power`` and ``set_address`` requests. Other steps are
   handled by the gadget driver. If the gadget driver module is unloaded
   before the host starts to enumerate, steps before step 7 are skipped.

4. The gadget driver's ``setup()`` call returns usb descriptors, based both
   on what the bus interface hardware provides and on the functionality
   being implemented. That can involve alternate settings or
   configurations, unless the hardware prevents such operation. For OTG
   devices, each configuration descriptor includes an OTG descriptor.

5. The gadget driver handles the last step of enumeration, when the USB
   host issues a ``set_configuration`` call. It enables all endpoints used
   in that configuration, with all interfaces in their default settings.
   That involves using a list of the hardware's endpoints, enabling each
   endpoint according to its descriptor. It may also involve using
   ``usb_gadget_vbus_draw`` to let more power be drawn from VBUS, as
   allowed by that configuration. For OTG devices, setting a
   configuration may also involve reporting HNP capabilities through a
   user interface.

6. Do real work and perform data transfers, possibly involving changes
   to interface settings or switching to new configurations, until the
   device is disconnect()ed from the host. Queue any number of transfer
   requests to each endpoint. It may be suspended and resumed several
   times before being disconnected. On disconnect, the drivers go back
   to step 3 (above).

7. When the gadget driver module is being unloaded, the driver unbind()
   callback is issued. That lets the controller driver be unloaded.

Drivers will normally be arranged so that just loading the gadget driver
module (or statically linking it into a Linux kernel) allows the
peripheral device to be enumerated, but some drivers will defer
enumeration until some higher level component (like a user mode daemon)
enables it. Note that at this lowest level there are no policies about
how ep0 configuration logic is implemented, except that it should obey
USB specifications. Such issues are in the domain of gadget drivers,
including knowing about implementation constraints imposed by some USB
controllers or understanding that composite devices might happen to be
built by integrating reusable components.

Note that the lifecycle above can be slightly different for OTG devices.
Other than providing an additional OTG descriptor in each configuration,
only the HNP-related differences are particularly visible to driver
code. They involve reporting requirements during the ``SET_CONFIGURATION``
request, and the option to invoke HNP during some suspend callbacks.
Also, SRP changes the semantics of ``usb_gadget_wakeup`` slightly.

USB 2.0 Chapter 9 Types and Constants
-------------------------------------

Gadget drivers rely on common USB structures and constants defined in
the :ref:`linux/usb/ch9.h <usb_chapter9>` header file, which is standard in
Linux 2.6+ kernels. These are the same types and constants used by host side
drivers (and usbcore).

Core Objects and Methods
------------------------

These are declared in ``<linux/usb/gadget.h>``, and are used by gadget
drivers to interact with USB peripheral controller drivers.

.. kernel-doc:: include/linux/usb/gadget.h
   :internal:

Optional Utilities
------------------

The core API is sufficient for writing a USB Gadget Driver, but some
optional utilities are provided to simplify common tasks. These
utilities include endpoint autoconfiguration.

.. kernel-doc:: drivers/usb/gadget/usbstring.c
   :export:

.. kernel-doc:: drivers/usb/gadget/config.c
   :export:

Composite Device Framework
--------------------------

The core API is sufficient for writing drivers for composite USB devices
(with more than one function in a given configuration), and also
multi-configuration devices (also more than one function, but not
necessarily sharing a given configuration). There is however an optional
framework which makes it easier to reuse and combine functions.

Devices using this framework provide a struct usb_composite_driver,
which in turn provides one or more struct usb_configuration
instances. Each such configuration includes at least one struct
:c:type:`usb_function`, which packages a user visible role such as "network
link" or "mass storage device". Management functions may also exist,
such as "Device Firmware Upgrade".

.. kernel-doc:: include/linux/usb/composite.h
   :internal:

.. kernel-doc:: drivers/usb/gadget/composite.c
   :export:

Composite Device Functions
--------------------------

At this writing, a few of the current gadget drivers have been converted
to this framework. Near-term plans include converting all of them,
except for ``gadgetfs``.

Peripheral Controller Drivers
=============================

The first hardware supporting this API was the NetChip 2280 controller,
which supports USB 2.0 high speed and is based on PCI. This is the
``net2280`` driver module. The driver supports Linux kernel versions 2.4
and 2.6; contact NetChip Technologies for development boards and product
information.

Other hardware working in the ``gadget`` framework includes: Intel's PXA
25x and IXP42x series processors (``pxa2xx_udc``), Toshiba TC86c001
"Goku-S" (``goku_udc``), Renesas SH7705/7727 (``sh_udc``), MediaQ 11xx
(``mq11xx_udc``), Hynix HMS30C7202 (``h7202_udc``), National 9303/4
(``n9604_udc``), Texas Instruments OMAP (``omap_udc``), Sharp LH7A40x
(``lh7a40x_udc``), and more. Most of those are full speed controllers.

At this writing, there are people at work on drivers in this framework
for several other USB device controllers, with plans to make many of
them be widely available.

A partial USB simulator, the ``dummy_hcd`` driver, is available. It can
act like a net2280, a pxa25x, or an sa11x0 in terms of available
endpoints and device speeds; and it simulates control, bulk, and to some
extent interrupt transfers. That lets you develop some parts of a gadget
driver on a normal PC, without any special hardware, and perhaps with
the assistance of tools such as GDB running with User Mode Linux. At
least one person has expressed interest in adapting that approach,
hooking it up to a simulator for a microcontroller. Such simulators can
help debug subsystems where the runtime hardware is unfriendly to
software development, or is not yet available.

Support for other controllers is expected to be developed and
contributed over time, as this driver framework evolves.

Gadget Drivers
==============

In addition to *Gadget Zero* (used primarily for testing and development
with drivers for usb controller hardware), other gadget drivers exist.

There's an ``ethernet`` gadget driver, which implements one of the most
useful *Communications Device Class* (CDC) models. One of the standards
for cable modem interoperability even specifies the use of this ethernet
model as one of two mandatory options. Gadgets using this code look to a
USB host as if they're an Ethernet adapter. It provides access to a
network where the gadget's CPU is one host, which could easily be
bridging, routing, or firewalling access to other networks. Since some
hardware can't fully implement the CDC Ethernet requirements, this
driver also implements a "good parts only" subset of CDC Ethernet. (That
subset doesn't advertise itself as CDC Ethernet, to avoid creating
problems.)

Support for Microsoft's ``RNDIS`` protocol has been contributed by
Pengutronix and Auerswald GmbH. This is like CDC Ethernet, but it runs
on more slightly USB hardware (but less than the CDC subset). However,
its main claim to fame is being able to connect directly to recent
versions of Windows, using drivers that Microsoft bundles and supports,
making it much simpler to network with Windows.

There is also support for user mode gadget drivers, using ``gadgetfs``.
This provides a *User Mode API* that presents each endpoint as a single
file descriptor. I/O is done using normal ``read()`` and ``read()`` calls.
Familiar tools like GDB and pthreads can be used to develop and debug
user mode drivers, so that once a robust controller driver is available
many applications for it won't require new kernel mode software. Linux
2.6 *Async I/O (AIO)* support is available, so that user mode software
can stream data with only slightly more overhead than a kernel driver.

There's a USB Mass Storage class driver, which provides a different
solution for interoperability with systems such as MS-Windows and MacOS.
That *Mass Storage* driver uses a file or block device as backing store
for a drive, like the ``loop`` driver. The USB host uses the BBB, CB, or
CBI versions of the mass storage class specification, using transparent
SCSI commands to access the data from the backing store.

There's a "serial line" driver, useful for TTY style operation over USB.
The latest version of that driver supports CDC ACM style operation, like
a USB modem, and so on most hardware it can interoperate easily with
MS-Windows. One interesting use of that driver is in boot firmware (like
a BIOS), which can sometimes use that model with very small systems
without real serial lines.

Support for other kinds of gadget is expected to be developed and
contributed over time, as this driver framework evolves.

USB On-The-GO (OTG)
===================

USB OTG support on Linux 2.6 was initially developed by Texas
Instruments for `OMAP <http://www.omap.com>`__ 16xx and 17xx series
processors. Other OTG systems should work in similar ways, but the
hardware level details could be very different.

Systems need specialized hardware support to implement OTG, notably
including a special *Mini-AB* jack and associated transceiver to support
*Dual-Role* operation: they can act either as a host, using the standard
Linux-USB host side driver stack, or as a peripheral, using this
``gadget`` framework. To do that, the system software relies on small
additions to those programming interfaces, and on a new internal
component (here called an "OTG Controller") affecting which driver stack
connects to the OTG port. In each role, the system can re-use the
existing pool of hardware-neutral drivers, layered on top of the
controller driver interfaces (:c:type:`usb_bus` or :c:type:`usb_gadget`).
Such drivers need at most minor changes, and most of the calls added to
support OTG can also benefit non-OTG products.

-  Gadget drivers test the ``is_otg`` flag, and use it to determine
   whether or not to include an OTG descriptor in each of their
   configurations.

-  Gadget drivers may need changes to support the two new OTG protocols,
   exposed in new gadget attributes such as ``b_hnp_enable`` flag. HNP
   support should be reported through a user interface (two LEDs could
   suffice), and is triggered in some cases when the host suspends the
   peripheral. SRP support can be user-initiated just like remote
   wakeup, probably by pressing the same button.

-  On the host side, USB device drivers need to be taught to trigger HNP
   at appropriate moments, using ``usb_suspend_device()``. That also
   conserves battery power, which is useful even for non-OTG
   configurations.

-  Also on the host side, a driver must support the OTG "Targeted
   Peripheral List". That's just a whitelist, used to reject peripherals
   not supported with a given Linux OTG host. *This whitelist is
   product-specific; each product must modify* ``otg_whitelist.h`` *to
   match its interoperability specification.*

   Non-OTG Linux hosts, like PCs and workstations, normally have some
   solution for adding drivers, so that peripherals that aren't
   recognized can eventually be supported. That approach is unreasonable
   for consumer products that may never have their firmware upgraded,
   and where it's usually unrealistic to expect traditional
   PC/workstation/server kinds of support model to work. For example,
   it's often impractical to change device firmware once the product has
   been distributed, so driver bugs can't normally be fixed if they're
   found after shipment.

Additional changes are needed below those hardware-neutral :c:type:`usb_bus`
and :c:type:`usb_gadget` driver interfaces; those aren't discussed here in any
detail. Those affect the hardware-specific code for each USB Host or
Peripheral controller, and how the HCD initializes (since OTG can be
active only on a single port). They also involve what may be called an
*OTG Controller Driver*, managing the OTG transceiver and the OTG state
machine logic as well as much of the root hub behavior for the OTG port.
The OTG controller driver needs to activate and deactivate USB
controllers depending on the relevant device role. Some related changes
were needed inside usbcore, so that it can identify OTG-capable devices
and respond appropriately to HNP or SRP protocols.


code:
USB hotplugging
~~~~~~~~~~~~~~~

Linux Hotplugging
=================

In hotpluggable busses like USB (and Cardbus PCI), end-users plug devices
into the bus with power on.  In most cases, users expect the devices to become
immediately usable.  That means the system must do many things, including:

    - Find a driver that can handle the device.  That may involve
      loading a kernel module; newer drivers can use module-init-tools
      to publish their device (and class) support to user utilities.

    - Bind a driver to that device.  Bus frameworks do that using a
      device driver's probe() routine.

    - Tell other subsystems to configure the new device.  Print
      queues may need to be enabled, networks brought up, disk
      partitions mounted, and so on.  In some cases these will
      be driver-specific actions.

This involves a mix of kernel mode and user mode actions.  Making devices
be immediately usable means that any user mode actions can't wait for an
administrator to do them:  the kernel must trigger them, either passively
(triggering some monitoring daemon to invoke a helper program) or
actively (calling such a user mode helper program directly).

Those triggered actions must support a system's administrative policies;
such programs are called "policy agents" here.  Typically they involve
shell scripts that dispatch to more familiar administration tools.

Because some of those actions rely on information about drivers (metadata)
that is currently available only when the drivers are dynamically linked,
you get the best hotplugging when you configure a highly modular system.

Kernel Hotplug Helper (``/sbin/hotplug``)
=========================================

There is a kernel parameter: ``/proc/sys/kernel/hotplug``, which normally
holds the pathname ``/sbin/hotplug``.  That parameter names a program
which the kernel may invoke at various times.

The /sbin/hotplug program can be invoked by any subsystem as part of its
reaction to a configuration change, from a thread in that subsystem.
Only one parameter is required: the name of a subsystem being notified of
some kernel event.  That name is used as the first key for further event
dispatch; any other argument and environment parameters are specified by
the subsystem making that invocation.

Hotplug software and other resources is available at:

	http://linux-hotplug.sourceforge.net

Mailing list information is also available at that site.

USB Policy Agent
================

The USB subsystem currently invokes ``/sbin/hotplug`` when USB devices
are added or removed from system.  The invocation is done by the kernel
hub workqueue [hub_wq], or else as part of root hub initialization
(done by init, modprobe, kapmd, etc).  Its single command line parameter
is the string "usb", and it passes these environment variables:

========== ============================================
ACTION     ``add``, ``remove``
PRODUCT    USB vendor, product, and version codes (hex)
TYPE       device class codes (decimal)
INTERFACE  interface 0 class codes (decimal)
========== ============================================

If "usbdevfs" is configured, DEVICE and DEVFS are also passed.  DEVICE is
the pathname of the device, and is useful for devices with multiple and/or
alternate interfaces that complicate driver selection.  By design, USB
hotplugging is independent of ``usbdevfs``:  you can do most essential parts
of USB device setup without using that filesystem, and without running a
user mode daemon to detect changes in system configuration.

Currently available policy agent implementations can load drivers for
modules, and can invoke driver-specific setup scripts.  The newest ones
leverage USB module-init-tools support.  Later agents might unload drivers.

USB Modutils Support
====================

Current versions of module-init-tools will create a ``modules.usbmap`` file
which contains the entries from each driver's ``MODULE_DEVICE_TABLE``.  Such
files can be used by various user mode policy agents to make sure all the
right driver modules get loaded, either at boot time or later.

See ``linux/usb.h`` for full information about such table entries; or look
at existing drivers.  Each table entry describes one or more criteria to
be used when matching a driver to a device or class of devices.  The
specific criteria are identified by bits set in "match_flags", paired
with field values.  You can construct the criteria directly, or with
macros such as these, and use driver_info to store more information::

    USB_DEVICE (vendorId, productId)
	... matching devices with specified vendor and product ids
    USB_DEVICE_VER (vendorId, productId, lo, hi)
	... like USB_DEVICE with lo <= productversion <= hi
    USB_INTERFACE_INFO (class, subclass, protocol)
	... matching specified interface class info
    USB_DEVICE_INFO (class, subclass, protocol)
	... matching specified device class info

A short example, for a driver that supports several specific USB devices
and their quirks, might have a MODULE_DEVICE_TABLE like this::

    static const struct usb_device_id mydriver_id_table[] = {
	{ USB_DEVICE (0x9999, 0xaaaa), driver_info: QUIRK_X },
	{ USB_DEVICE (0xbbbb, 0x8888), driver_info: QUIRK_Y|QUIRK_Z },
	...
	{ } /* end with an all-zeroes entry */
    };
    MODULE_DEVICE_TABLE(usb, mydriver_id_table);

Most USB device drivers should pass these tables to the USB subsystem as
well as to the module management subsystem.  Not all, though: some driver
frameworks connect using interfaces layered over USB, and so they won't
need such a struct usb_driver.

Drivers that connect directly to the USB subsystem should be declared
something like this::

    static struct usb_driver mydriver = {
	.name		= "mydriver",
	.id_table	= mydriver_id_table,
	.probe		= my_probe,
	.disconnect	= my_disconnect,

	/*
	if using the usb chardev framework:
	    .minor		= MY_USB_MINOR_START,
	    .fops		= my_file_ops,
	if exposing any operations through usbdevfs:
	    .ioctl		= my_ioctl,
	*/
    };

When the USB subsystem knows about a driver's device ID table, it's used when
choosing drivers to probe().  The thread doing new device processing checks
drivers' device ID entries from the ``MODULE_DEVICE_TABLE`` against interface
and device descriptors for the device.  It will only call ``probe()`` if there
is a match, and the third argument to ``probe()`` will be the entry that
matched.

If you don't provide an ``id_table`` for your driver, then your driver may get
probed for each new device; the third parameter to ``probe()`` will be
``NULL``.


code:
=============
Linux USB API
=============

.. toctree::

   usb
   gadget
   anchors
   bulk-streams
   callbacks
   dma
   URB
   power-management
   hotplug
   persist
   error-codes
   writing_usb_driver
   dwc3
   writing_musb_glue_layer
   typec
   typec_bus
   usb3-debug-port

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`


code:
.. _usb-persist:

USB device persistence during system suspend
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Author: Alan Stern <stern@rowland.harvard.edu>
:Date: September 2, 2006 (Updated February 25, 2008)

What is the problem?
====================

According to the USB specification, when a USB bus is suspended the
bus must continue to supply suspend current (around 1-5 mA).  This
is so that devices can maintain their internal state and hubs can
detect connect-change events (devices being plugged in or unplugged).
The technical term is "power session".

If a USB device's power session is interrupted then the system is
required to behave as though the device has been unplugged.  It's a
conservative approach; in the absence of suspend current the computer
has no way to know what has actually happened.  Perhaps the same
device is still attached or perhaps it was removed and a different
device plugged into the port.  The system must assume the worst.

By default, Linux behaves according to the spec.  If a USB host
controller loses power during a system suspend, then when the system
wakes up all the devices attached to that controller are treated as
though they had disconnected.  This is always safe and it is the
"officially correct" thing to do.

For many sorts of devices this behavior doesn't matter in the least.
If the kernel wants to believe that your USB keyboard was unplugged
while the system was asleep and a new keyboard was plugged in when the
system woke up, who cares?  It'll still work the same when you type on
it.

Unfortunately problems _can_ arise, particularly with mass-storage
devices.  The effect is exactly the same as if the device really had
been unplugged while the system was suspended.  If you had a mounted
filesystem on the device, you're out of luck -- everything in that
filesystem is now inaccessible.  This is especially annoying if your
root filesystem was located on the device, since your system will
instantly crash.

Loss of power isn't the only mechanism to worry about.  Anything that
interrupts a power session will have the same effect.  For example,
even though suspend current may have been maintained while the system
was asleep, on many systems during the initial stages of wakeup the
firmware (i.e., the BIOS) resets the motherboard's USB host
controllers.  Result: all the power sessions are destroyed and again
it's as though you had unplugged all the USB devices.  Yes, it's
entirely the BIOS's fault, but that doesn't do _you_ any good unless
you can convince the BIOS supplier to fix the problem (lots of luck!).

On many systems the USB host controllers will get reset after a
suspend-to-RAM.  On almost all systems, no suspend current is
available during hibernation (also known as swsusp or suspend-to-disk).
You can check the kernel log after resuming to see if either of these
has happened; look for lines saying "root hub lost power or was reset".

In practice, people are forced to unmount any filesystems on a USB
device before suspending.  If the root filesystem is on a USB device,
the system can't be suspended at all.  (All right, it _can_ be
suspended -- but it will crash as soon as it wakes up, which isn't
much better.)

What is the solution?
=====================

The kernel includes a feature called USB-persist.  It tries to work
around these issues by allowing the core USB device data structures to
persist across a power-session disruption.

It works like this.  If the kernel sees that a USB host controller is
not in the expected state during resume (i.e., if the controller was
reset or otherwise had lost power) then it applies a persistence check
to each of the USB devices below that controller for which the
"persist" attribute is set.  It doesn't try to resume the device; that
can't work once the power session is gone.  Instead it issues a USB
port reset and then re-enumerates the device.  (This is exactly the
same thing that happens whenever a USB device is reset.)  If the
re-enumeration shows that the device now attached to that port has the
same descriptors as before, including the Vendor and Product IDs, then
the kernel continues to use the same device structure.  In effect, the
kernel treats the device as though it had merely been reset instead of
unplugged.

The same thing happens if the host controller is in the expected state
but a USB device was unplugged and then replugged, or if a USB device
fails to carry out a normal resume.

If no device is now attached to the port, or if the descriptors are
different from what the kernel remembers, then the treatment is what
you would expect.  The kernel destroys the old device structure and
behaves as though the old device had been unplugged and a new device
plugged in.

The end result is that the USB device remains available and usable.
Filesystem mounts and memory mappings are unaffected, and the world is
now a good and happy place.

Note that the "USB-persist" feature will be applied only to those
devices for which it is enabled.  You can enable the feature by doing
(as root)::

	echo 1 >/sys/bus/usb/devices/.../power/persist

where the "..." should be filled in the with the device's ID.  Disable
the feature by writing 0 instead of 1.  For hubs the feature is
automatically and permanently enabled and the power/persist file
doesn't even exist, so you only have to worry about setting it for
devices where it really matters.

Is this the best solution?
==========================

Perhaps not.  Arguably, keeping track of mounted filesystems and
memory mappings across device disconnects should be handled by a
centralized Logical Volume Manager.  Such a solution would allow you
to plug in a USB flash device, create a persistent volume associated
with it, unplug the flash device, plug it back in later, and still
have the same persistent volume associated with the device.  As such
it would be more far-reaching than USB-persist.

On the other hand, writing a persistent volume manager would be a big
job and using it would require significant input from the user.  This
solution is much quicker and easier -- and it exists now, a giant
point in its favor!

Furthermore, the USB-persist feature applies to _all_ USB devices, not
just mass-storage devices.  It might turn out to be equally useful for
other device types, such as network interfaces.

WARNING: USB-persist can be dangerous!!
=======================================

When recovering an interrupted power session the kernel does its best
to make sure the USB device hasn't been changed; that is, the same
device is still plugged into the port as before.  But the checks
aren't guaranteed to be 100% accurate.

If you replace one USB device with another of the same type (same
manufacturer, same IDs, and so on) there's an excellent chance the
kernel won't detect the change.  The serial number string and other
descriptors are compared with the kernel's stored values, but this
might not help since manufacturers frequently omit serial numbers
entirely in their devices.

Furthermore it's quite possible to leave a USB device exactly the same
while changing its media.  If you replace the flash memory card in a
USB card reader while the system is asleep, the kernel will have no
way to know you did it.  The kernel will assume that nothing has
happened and will continue to use the partition tables, inodes, and
memory mappings for the old card.

If the kernel gets fooled in this way, it's almost certain to cause
data corruption and to crash your system.  You'll have no one to blame
but yourself.

For those devices with avoid_reset_quirk attribute being set, persist
maybe fail because they may morph after reset.

YOU HAVE BEEN WARNED!  USE AT YOUR OWN RISK!

That having been said, most of the time there shouldn't be any trouble
at all.  The USB-persist feature can be extremely useful.  Make the
most of it.