요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. _usb-hostside-api:
===========================
The Linux-USB Host Side API
===========================
Introduction to USB on Linux
============================
A Universal Serial Bus (USB) is used to connect a host, such as a PC or
workstation, to a number of peripheral devices. USB uses a tree
structure, with the host as the root (the system's master), hubs as
interior nodes, and peripherals as leaves (and slaves). Modern PCs
support several such trees of USB devices, usually
a few USB 3.0 (5 GBit/s) or USB 3.1 (10 GBit/s) and some legacy
USB 2.0 (480 MBit/s) buses just in case.
That master/slave asymmetry was designed-in for a number of reasons, one
being ease of use. It is not physically possible to mistake upstream and
downstream or it does not matter with a type C plug (or they are built into the
peripheral). Also, the host software doesn't need to deal with
distributed auto-configuration since the pre-designated master node
manages all that.
Kernel developers added USB support to Linux early in the 2.2 kernel
series and have been developing it further since then. Besides support
for each new generation of USB, various host controllers gained support,
new drivers for peripherals have been added and advanced features for latency
measurement and improved power management introduced.
Linux can run inside USB devices as well as on the hosts that control
the devices. But USB device drivers running inside those peripherals
don't do the same things as the ones running inside hosts, so they've
been given a different name: *gadget drivers*. This document does not
cover gadget drivers.
USB Host-Side API Model
=======================
Host-side drivers for USB devices talk to the "usbcore" APIs. There are
two. One is intended for *general-purpose* drivers (exposed through
driver frameworks), and the other is for drivers that are *part of the
core*. Such core drivers include the *hub* driver (which manages trees
of USB devices) and several different kinds of *host controller
drivers*, which control individual buses.
The device model seen by USB drivers is relatively complex.
- USB supports four kinds of data transfers (control, bulk, interrupt,
and isochronous). Two of them (control and bulk) use bandwidth as
it's available, while the other two (interrupt and isochronous) are
scheduled to provide guaranteed bandwidth.
- The device description model includes one or more "configurations"
per device, only one of which is active at a time. Devices are supposed
to be capable of operating at lower than their top
speeds and may provide a BOS descriptor showing the lowest speed they
remain fully operational at.
- From USB 3.0 on configurations have one or more "functions", which
provide a common functionality and are grouped together for purposes
of power management.
- Configurations or functions have one or more "interfaces", each of which may have
"alternate settings". Interfaces may be standardized by USB "Class"
specifications, or may be specific to a vendor or device.
USB device drivers actually bind to interfaces, not devices. Think of
them as "interface drivers", though you may not see many devices
where the distinction is important. *Most USB devices are simple,
with only one function, one configuration, one interface, and one alternate
setting.*
- Interfaces have one or more "endpoints", each of which supports one
type and direction of data transfer such as "bulk out" or "interrupt
in". The entire configuration may have up to sixteen endpoints in
each direction, allocated as needed among all the interfaces.
- Data transfer on USB is packetized; each endpoint has a maximum
packet size. Drivers must often be aware of conventions such as
flagging the end of bulk transfers using "short" (including zero
length) packets.
- The Linux USB API supports synchronous calls for control and bulk
messages. It also supports asynchronous calls for all kinds of data
transfer, using request structures called "URBs" (USB Request
Blocks).
Accordingly, the USB Core API exposed to device drivers covers quite a
lot of territory. You'll probably need to consult the USB 3.0
specification, available online from www.usb.org at no cost, as well as
class or device specifications.
The only host-side drivers that actually touch hardware (reading/writing
registers, handling IRQs, and so on) are the HCDs. In theory, all HCDs
provide the same functionality through the same API. In practice, that's
becoming more true, but there are still differences
that crop up especially with fault handling on the less common controllers.
Different controllers don't
necessarily report the same aspects of failures, and recovery from
faults (including software-induced ones like unlinking an URB) isn't yet
fully consistent. Device driver authors should make a point of doing
disconnect testing (while the device is active) with each different host
controller driver, to make sure drivers don't have bugs of their own as
well as to make sure they aren't relying on some HCD-specific behavior.
.. _usb_chapter9:
USB-Standard Types
==================
In ``include/uapi/linux/usb/ch9.h`` you will find the USB data types defined
in chapter 9 of the USB specification. These data types are used throughout
USB, and in APIs including this host side API, gadget APIs, usb character
devices and debugfs interfaces. That file is itself included by
``include/linux/usb/ch9.h``, which also contains declarations of a few
utility routines for manipulating these data types; the implementations
are in ``drivers/usb/common/common.c``.
.. kernel-doc:: drivers/usb/common/common.c
:export:
In addition, some functions useful for creating debugging output are
defined in ``drivers/usb/common/debug.c``.
.. _usb_header:
Host-Side Data Types and Macros
===============================
The host side API exposes several layers to drivers, some of which are
more necessary than others. These support lifecycle models for host side
drivers and devices, and support passing buffers through usbcore to some
HCD that performs the I/O for the device driver.
.. kernel-doc:: include/linux/usb.h
:internal:
USB Core APIs
=============
There are two basic I/O models in the USB API. The most elemental one is
asynchronous: drivers submit requests in the form of an URB, and the
URB's completion callback handles the next step. All USB transfer types
support that model, although there are special cases for control URBs
(which always have setup and status stages, but may not have a data
stage) and isochronous URBs (which allow large packets and include
per-packet fault reports). Built on top of that is synchronous API
support, where a driver calls a routine that allocates one or more URBs,
submits them, and waits until they complete. There are synchronous
wrappers for single-buffer control and bulk transfers (which are awkward
to use in some driver disconnect scenarios), and for scatterlist based
streaming i/o (bulk or interrupt).
USB drivers need to provide buffers that can be used for DMA, although
they don't necessarily need to provide the DMA mapping themselves. There
are APIs to use used when allocating DMA buffers, which can prevent use
of bounce buffers on some systems. In some cases, drivers may be able to
rely on 64bit DMA to eliminate another kind of bounce buffer.
.. kernel-doc:: drivers/usb/core/urb.c
:export:
.. c:namespace:: usb_core
.. kernel-doc:: drivers/usb/core/message.c
:export:
.. kernel-doc:: drivers/usb/core/file.c
:export:
.. kernel-doc:: drivers/usb/core/driver.c
:export:
.. kernel-doc:: drivers/usb/core/usb.c
:export:
.. kernel-doc:: drivers/usb/core/hub.c
:export:
Host Controller APIs
====================
These APIs are only for use by host controller drivers, most of which
implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI
was one of the first interfaces, designed by Intel and also used by VIA;
it doesn't do much in hardware. OHCI was designed later, to have the
hardware do more work (bigger transfers, tracking protocol state, and so
on). EHCI was designed with USB 2.0; its design has features that
resemble OHCI (hardware does much more work) as well as UHCI (some parts
of ISO support, TD list processing). XHCI was designed with USB 3.0. It
continues to shift support for functionality into hardware.
There are host controllers other than the "big three", although most PCI
based controllers (and a few non-PCI based ones) use one of those
interfaces. Not all host controllers use DMA; some use PIO, and there is
also a simulator and a virtual host controller to pipe USB over the network.
The same basic APIs are available to drivers for all those controllers.
For historical reasons they are in two layers: :c:type:`struct
usb_bus <usb_bus>` is a rather thin layer that became available
in the 2.2 kernels, while :c:type:`struct usb_hcd <usb_hcd>`
is a more featureful layer
that lets HCDs share common code, to shrink driver size and
significantly reduce hcd-specific behaviors.
.. kernel-doc:: drivers/usb/core/hcd.c
:export:
.. kernel-doc:: drivers/usb/core/hcd-pci.c
:export:
.. kernel-doc:: drivers/usb/core/buffer.c
:internal:
The USB character device nodes
==============================
This chapter presents the Linux character device nodes. You may prefer
to avoid writing new kernel code for your USB driver. User mode device
drivers are usually packaged as applications or libraries, and may use
character devices through some programming library that wraps it.
Such libraries include:
- `libusb <http://libusb.sourceforge.net>`__ for C/C++, and
- `jUSB <http://jUSB.sourceforge.net>`__ for Java.
Some old information about it can be seen at the "USB Device Filesystem"
section of the USB Guide. The latest copy of the USB Guide can be found
at http://www.linux-usb.org/
.. note::
- They were used to be implemented via *usbfs*, but this is not part of
the sysfs debug interface.
- This particular documentation is incomplete, especially with respect
to the asynchronous mode. As of kernel 2.5.66 the code and this
(new) documentation need to be cross-reviewed.
What files are in "devtmpfs"?
-----------------------------
Conventionally mounted at ``/dev/bus/usb/``, usbfs features include:
- ``/dev/bus/usb/BBB/DDD`` ... magic files exposing the each device's
configuration descriptors, and supporting a series of ioctls for
making device requests, including I/O to devices. (Purely for access
by programs.)
Each bus is given a number (``BBB``) based on when it was enumerated; within
each bus, each device is given a similar number (``DDD``). Those ``BBB/DDD``
paths are not "stable" identifiers; expect them to change even if you
always leave the devices plugged in to the same hub port. *Don't even
think of saving these in application configuration files.* Stable
identifiers are available, for user mode applications that want to use
them. HID and networking devices expose these stable IDs, so that for
example you can be sure that you told the right UPS to power down its
second server. Pleast note that it doesn't (yet) expose those IDs.
/dev/bus/usb/BBB/DDD
--------------------
Use these files in one of these basic ways:
- *They can be read,* producing first the device descriptor (18 bytes) and
then the descriptors for the current configuration. See the USB 2.0 spec
for details about those binary data formats. You'll need to convert most
multibyte values from little endian format to your native host byte
order, although a few of the fields in the device descriptor (both of
the BCD-encoded fields, and the vendor and product IDs) will be
byteswapped for you. Note that configuration descriptors include
descriptors for interfaces, altsettings, endpoints, and maybe additional
class descriptors.
- *Perform USB operations* using *ioctl()* requests to make endpoint I/O
requests (synchronously or asynchronously) or manage the device. These
requests need the ``CAP_SYS_RAWIO`` capability, as well as filesystem
access permissions. Only one ioctl request can be made on one of these
device files at a time. This means that if you are synchronously reading
an endpoint from one thread, you won't be able to write to a different
endpoint from another thread until the read completes. This works for
*half duplex* protocols, but otherwise you'd use asynchronous i/o
requests.
Each connected USB device has one file. The ``BBB`` indicates the bus
number. The ``DDD`` indicates the device address on that bus. Both
of these numbers are assigned sequentially, and can be reused, so
you can't rely on them for stable access to devices. For example,
it's relatively common for devices to re-enumerate while they are
still connected (perhaps someone jostled their power supply, hub,
or USB cable), so a device might be ``002/027`` when you first connect
it and ``002/048`` sometime later.
These files can be read as binary data. The binary data consists
of first the device descriptor, then the descriptors for each
configuration of the device. Multi-byte fields in the device descriptor
are converted to host endianness by the kernel. The configuration
descriptors are in bus endian format! The configuration descriptor
are wTotalLength bytes apart. If a device returns less configuration
descriptor data than indicated by wTotalLength there will be a hole in
the file for the missing bytes. This information is also shown
in text form by the ``/sys/kernel/debug/usb/devices`` file, described later.
These files may also be used to write user-level drivers for the USB
devices. You would open the ``/dev/bus/usb/BBB/DDD`` file read/write,
read its descriptors to make sure it's the device you expect, and then
bind to an interface (or perhaps several) using an ioctl call. You
would issue more ioctls to the device to communicate to it using
control, bulk, or other kinds of USB transfers. The IOCTLs are
listed in the ``<linux/usbdevice_fs.h>`` file, and at this writing the
source code (``linux/drivers/usb/core/devio.c``) is the primary reference
for how to access devices through those files.
Note that since by default these ``BBB/DDD`` files are writable only by
root, only root can write such user mode drivers. You can selectively
grant read/write permissions to other users by using ``chmod``. Also,
usbfs mount options such as ``devmode=0666`` may be helpful.
Life Cycle of User Mode Drivers
-------------------------------
Such a driver first needs to find a device file for a device it knows
how to handle. Maybe it was told about it because a ``/sbin/hotplug``
event handling agent chose that driver to handle the new device. Or
maybe it's an application that scans all the ``/dev/bus/usb`` device files,
and ignores most devices. In either case, it should :c:func:`read()`
all the descriptors from the device file, and check them against what it
knows how to handle. It might just reject everything except a particular
vendor and product ID, or need a more complex policy.
Never assume there will only be one such device on the system at a time!
If your code can't handle more than one device at a time, at least
detect when there's more than one, and have your users choose which
device to use.
Once your user mode driver knows what device to use, it interacts with
it in either of two styles. The simple style is to make only control
requests; some devices don't need more complex interactions than those.
(An example might be software using vendor-specific control requests for
some initialization or configuration tasks, with a kernel driver for the
rest.)
More likely, you need a more complex style driver: one using non-control
endpoints, reading or writing data and claiming exclusive use of an
interface. *Bulk* transfers are easiest to use, but only their sibling
*interrupt* transfers work with low speed devices. Both interrupt and
*isochronous* transfers offer service guarantees because their bandwidth
is reserved. Such "periodic" transfers are awkward to use through usbfs,
unless you're using the asynchronous calls. However, interrupt transfers
can also be used in a synchronous "one shot" style.
Your user-mode driver should never need to worry about cleaning up
request state when the device is disconnected, although it should close
its open file descriptors as soon as it starts seeing the ENODEV errors.
The ioctl() Requests
--------------------
To use these ioctls, you need to include the following headers in your
userspace program::
#include <linux/usb.h>
#include <linux/usbdevice_fs.h>
#include <asm/byteorder.h>
The standard USB device model requests, from "Chapter 9" of the USB 2.0
specification, are automatically included from the ``<linux/usb/ch9.h>``
header.
Unless noted otherwise, the ioctl requests described here will update
the modification time on the usbfs file to which they are applied
(unless they fail). A return of zero indicates success; otherwise, a
standard USB error code is returned (These are documented in
:ref:`usb-error-codes`).
Each of these files multiplexes access to several I/O streams, one per
endpoint. Each device has one control endpoint (endpoint zero) which
supports a limited RPC style RPC access. Devices are configured by
hub_wq (in the kernel) setting a device-wide *configuration* that
affects things like power consumption and basic functionality. The
endpoints are part of USB *interfaces*, which may have *altsettings*
affecting things like which endpoints are available. Many devices only
have a single configuration and interface, so drivers for them will
ignore configurations and altsettings.
Management/Status Requests
~~~~~~~~~~~~~~~~~~~~~~~~~~
A number of usbfs requests don't deal very directly with device I/O.
They mostly relate to device management and status. These are all
synchronous requests.
USBDEVFS_CLAIMINTERFACE
This is used to force usbfs to claim a specific interface, which has
not previously been claimed by usbfs or any other kernel driver. The
ioctl parameter is an integer holding the number of the interface
(bInterfaceNumber from descriptor).
Note that if your driver doesn't claim an interface before trying to
use one of its endpoints, and no other driver has bound to it, then
the interface is automatically claimed by usbfs.
This claim will be released by a RELEASEINTERFACE ioctl, or by
closing the file descriptor. File modification time is not updated
by this request.
USBDEVFS_CONNECTINFO
Says whether the device is lowspeed. The ioctl parameter points to a
structure like this::
struct usbdevfs_connectinfo {
unsigned int devnum;
unsigned char slow;
};
File modification time is not updated by this request.
*You can't tell whether a "not slow" device is connected at high
speed (480 MBit/sec) or just full speed (12 MBit/sec).* You should
know the devnum value already, it's the DDD value of the device file
name.
USBDEVFS_GET_SPEED
Returns the speed of the device. The speed is returned as a
numerical value in accordance with enum usb_device_speed
File modification time is not updated by this request.
USBDEVFS_GETDRIVER
Returns the name of the kernel driver bound to a given interface (a
string). Parameter is a pointer to this structure, which is
modified::
struct usbdevfs_getdriver {
unsigned int interface;
char driver[USBDEVFS_MAXDRIVERNAME + 1];
};
File modification time is not updated by this request.
USBDEVFS_IOCTL
Passes a request from userspace through to a kernel driver that has
an ioctl entry in the *struct usb_driver* it registered::
struct usbdevfs_ioctl {
int ifno;
int ioctl_code;
void *data;
};
/* user mode call looks like this.
* 'request' becomes the driver->ioctl() 'code' parameter.
* the size of 'param' is encoded in 'request', and that data
* is copied to or from the driver->ioctl() 'buf' parameter.
*/
static int
usbdev_ioctl (int fd, int ifno, unsigned request, void *param)
{
struct usbdevfs_ioctl wrapper;
wrapper.ifno = ifno;
wrapper.ioctl_code = request;
wrapper.data = param;
return ioctl (fd, USBDEVFS_IOCTL, &wrapper);
}
File modification time is not updated by this request.
This request lets kernel drivers talk to user mode code through
filesystem operations even when they don't create a character or
block special device. It's also been used to do things like ask
devices what device special file should be used. Two pre-defined
ioctls are used to disconnect and reconnect kernel drivers, so that
user mode code can completely manage binding and configuration of
devices.
USBDEVFS_RELEASEINTERFACE
This is used to release the claim usbfs made on interface, either
implicitly or because of a USBDEVFS_CLAIMINTERFACE call, before the
file descriptor is closed. The ioctl parameter is an integer holding
the number of the interface (bInterfaceNumber from descriptor); File
modification time is not updated by this request.
.. warning::
*No security check is made to ensure that the task which made
the claim is the one which is releasing it. This means that user
mode driver may interfere other ones.*
USBDEVFS_RESETEP
Resets the data toggle value for an endpoint (bulk or interrupt) to
DATA0. The ioctl parameter is an integer endpoint number (1 to 15,
as identified in the endpoint descriptor), with USB_DIR_IN added
if the device's endpoint sends data to the host.
.. Warning::
*Avoid using this request. It should probably be removed.* Using
it typically means the device and driver will lose toggle
synchronization. If you really lost synchronization, you likely
need to completely handshake with the device, using a request
like CLEAR_HALT or SET_INTERFACE.
USBDEVFS_DROP_PRIVILEGES
This is used to relinquish the ability to do certain operations
which are considered to be privileged on a usbfs file descriptor.
This includes claiming arbitrary interfaces, resetting a device on
which there are currently claimed interfaces from other users, and
issuing USBDEVFS_IOCTL calls. The ioctl parameter is a 32 bit mask
of interfaces the user is allowed to claim on this file descriptor.
You may issue this ioctl more than one time to narrow said mask.
Synchronous I/O Support
~~~~~~~~~~~~~~~~~~~~~~~
Synchronous requests involve the kernel blocking until the user mode
request completes, either by finishing successfully or by reporting an
error. In most cases this is the simplest way to use usbfs, although as
noted above it does prevent performing I/O to more than one endpoint at
a time.
USBDEVFS_BULK
Issues a bulk read or write request to the device. The ioctl
parameter is a pointer to this structure::
struct usbdevfs_bulktransfer {
unsigned int ep;
unsigned int len;
unsigned int timeout; /* in milliseconds */
void *data;
};
The ``ep`` value identifies a bulk endpoint number (1 to 15, as
identified in an endpoint descriptor), masked with USB_DIR_IN when
referring to an endpoint which sends data to the host from the
device. The length of the data buffer is identified by ``len``; Recent
kernels support requests up to about 128KBytes. *FIXME say how read
length is returned, and how short reads are handled.*.
USBDEVFS_CLEAR_HALT
Clears endpoint halt (stall) and resets the endpoint toggle. This is
only meaningful for bulk or interrupt endpoints. The ioctl parameter
is an integer endpoint number (1 to 15, as identified in an endpoint
descriptor), masked with USB_DIR_IN when referring to an endpoint
which sends data to the host from the device.
Use this on bulk or interrupt endpoints which have stalled,
returning ``-EPIPE`` status to a data transfer request. Do not issue
the control request directly, since that could invalidate the host's
record of the data toggle.
USBDEVFS_CONTROL
Issues a control request to the device. The ioctl parameter points
to a structure like this::
struct usbdevfs_ctrltransfer {
__u8 bRequestType;
__u8 bRequest;
__u16 wValue;
__u16 wIndex;
__u16 wLength;
__u32 timeout; /* in milliseconds */
void *data;
};
The first eight bytes of this structure are the contents of the
SETUP packet to be sent to the device; see the USB 2.0 specification
for details. The bRequestType value is composed by combining a
``USB_TYPE_*`` value, a ``USB_DIR_*`` value, and a ``USB_RECIP_*``
value (from ``linux/usb.h``). If wLength is nonzero, it describes
the length of the data buffer, which is either written to the device
(USB_DIR_OUT) or read from the device (USB_DIR_IN).
At this writing, you can't transfer more than 4 KBytes of data to or
from a device; usbfs has a limit, and some host controller drivers
have a limit. (That's not usually a problem.) *Also* there's no way
to say it's not OK to get a short read back from the device.
USBDEVFS_RESET
Does a USB level device reset. The ioctl parameter is ignored. After
the reset, this rebinds all device interfaces. File modification
time is not updated by this request.
.. warning::
*Avoid using this call* until some usbcore bugs get fixed, since
it does not fully synchronize device, interface, and driver (not
just usbfs) state.
USBDEVFS_SETINTERFACE
Sets the alternate setting for an interface. The ioctl parameter is
a pointer to a structure like this::
struct usbdevfs_setinterface {
unsigned int interface;
unsigned int altsetting;
};
File modification time is not updated by this request.
Those struct members are from some interface descriptor applying to
the current configuration. The interface number is the
bInterfaceNumber value, and the altsetting number is the
bAlternateSetting value. (This resets each endpoint in the
interface.)
USBDEVFS_SETCONFIGURATION
Issues the :c:func:`usb_set_configuration()` call for the
device. The parameter is an integer holding the number of a
configuration (bConfigurationValue from descriptor). File
modification time is not updated by this request.
.. warning::
*Avoid using this call* until some usbcore bugs get fixed, since
it does not fully synchronize device, interface, and driver (not
just usbfs) state.
Asynchronous I/O Support
~~~~~~~~~~~~~~~~~~~~~~~~
As mentioned above, there are situations where it may be important to
initiate concurrent operations from user mode code. This is particularly
important for periodic transfers (interrupt and isochronous), but it can
be used for other kinds of USB requests too. In such cases, the
asynchronous requests described here are essential. Rather than
submitting one request and having the kernel block until it completes,
the blocking is separate.
These requests are packaged into a structure that resembles the URB used
by kernel device drivers. (No POSIX Async I/O support here, sorry.) It
identifies the endpoint type (``USBDEVFS_URB_TYPE_*``), endpoint
(number, masked with USB_DIR_IN as appropriate), buffer and length,
and a user "context" value serving to uniquely identify each request.
(It's usually a pointer to per-request data.) Flags can modify requests
(not as many as supported for kernel drivers).
Each request can specify a realtime signal number (between SIGRTMIN and
SIGRTMAX, inclusive) to request a signal be sent when the request
completes.
When usbfs returns these urbs, the status value is updated, and the
buffer may have been modified. Except for isochronous transfers, the
actual_length is updated to say how many bytes were transferred; if the
USBDEVFS_URB_DISABLE_SPD flag is set ("short packets are not OK"), if
fewer bytes were read than were requested then you get an error report::
struct usbdevfs_iso_packet_desc {
unsigned int length;
unsigned int actual_length;
unsigned int status;
};
struct usbdevfs_urb {
unsigned char type;
unsigned char endpoint;
int status;
unsigned int flags;
void *buffer;
int buffer_length;
int actual_length;
int start_frame;
int number_of_packets;
int error_count;
unsigned int signr;
void *usercontext;
struct usbdevfs_iso_packet_desc iso_frame_desc[];
};
For these asynchronous requests, the file modification time reflects
when the request was initiated. This contrasts with their use with the
synchronous requests, where it reflects when requests complete.
USBDEVFS_DISCARDURB
*TBS* File modification time is not updated by this request.
USBDEVFS_DISCSIGNAL
*TBS* File modification time is not updated by this request.
USBDEVFS_REAPURB
*TBS* File modification time is not updated by this request.
USBDEVFS_REAPURBNDELAY
*TBS* File modification time is not updated by this request.
USBDEVFS_SUBMITURB
*TBS*
The USB devices
===============
The USB devices are now exported via debugfs:
- ``/sys/kernel/debug/usb/devices`` ... a text file showing each of the USB
devices on known to the kernel, and their configuration descriptors.
You can also poll() this to learn about new devices.
/sys/kernel/debug/usb/devices
-----------------------------
This file is handy for status viewing tools in user mode, which can scan
the text format and ignore most of it. More detailed device status
(including class and vendor status) is available from device-specific
files. For information about the current format of this file, see below.
This file, in combination with the poll() system call, can also be used
to detect when devices are added or removed::
int fd;
struct pollfd pfd;
fd = open("/sys/kernel/debug/usb/devices", O_RDONLY);
pfd = { fd, POLLIN, 0 };
for (;;) {
/* The first time through, this call will return immediately. */
poll(&pfd, 1, -1);
/* To see what's changed, compare the file's previous and current
contents or scan the filesystem. (Scanning is more precise.) */
}
Note that this behavior is intended to be used for informational and
debug purposes. It would be more appropriate to use programs such as
udev or HAL to initialize a device or start a user-mode helper program,
for instance.
In this file, each device's output has multiple lines of ASCII output.
I made it ASCII instead of binary on purpose, so that someone
can obtain some useful data from it without the use of an
auxiliary program. However, with an auxiliary program, the numbers
in the first 4 columns of each ``T:`` line (topology info:
Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.
Each line is tagged with a one-character ID for that line::
T = Topology (etc.)
B = Bandwidth (applies only to USB host controllers, which are
virtualized as root hubs)
D = Device descriptor info.
P = Product ID info. (from Device descriptor, but they won't fit
together on one line)
S = String descriptors.
C = Configuration descriptor info. (* = active configuration)
I = Interface descriptor info.
E = Endpoint descriptor info.
/sys/kernel/debug/usb/devices output format
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Legend::
d = decimal number (may have leading spaces or 0's)
x = hexadecimal number (may have leading spaces or 0's)
s = string
Topology info
^^^^^^^^^^^^^
::
T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=dddd MxCh=dd
| | | | | | | | |__MaxChildren
| | | | | | | |__Device Speed in Mbps
| | | | | | |__DeviceNumber
| | | | | |__Count of devices at this level
| | | | |__Connector/Port on Parent for this device
| | | |__Parent DeviceNumber
| | |__Level in topology for this bus
| |__Bus number
|__Topology info tag
Speed may be:
======= ======================================================
1.5 Mbit/s for low speed USB
12 Mbit/s for full speed USB
480 Mbit/s for high speed USB (added for USB 2.0)
5000 Mbit/s for SuperSpeed USB (added for USB 3.0)
======= ======================================================
For reasons lost in the mists of time, the Port number is always
too low by 1. For example, a device plugged into port 4 will
show up with ``Port=03``.
Bandwidth info
^^^^^^^^^^^^^^
::
B: Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
| | | |__Number of isochronous requests
| | |__Number of interrupt requests
| |__Total Bandwidth allocated to this bus
|__Bandwidth info tag
Bandwidth allocation is an approximation of how much of one frame
(millisecond) is in use. It reflects only periodic transfers, which
are the only transfers that reserve bandwidth. Control and bulk
transfers use all other bandwidth, including reserved bandwidth that
is not used for transfers (such as for short packets).
The percentage is how much of the "reserved" bandwidth is scheduled by
those transfers. For a low or full speed bus (loosely, "USB 1.1"),
90% of the bus bandwidth is reserved. For a high speed bus (loosely,
"USB 2.0") 80% is reserved.
Device descriptor info & Product ID info
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
D: Ver=x.xx Cls=xx(s) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
where::
D: Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
| | | | | | |__NumberConfigurations
| | | | | |__MaxPacketSize of Default Endpoint
| | | | |__DeviceProtocol
| | | |__DeviceSubClass
| | |__DeviceClass
| |__Device USB version
|__Device info tag #1
where::
P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
| | | |__Product revision number
| | |__Product ID code
| |__Vendor ID code
|__Device info tag #2
String descriptor info
^^^^^^^^^^^^^^^^^^^^^^
::
S: Manufacturer=ssss
| |__Manufacturer of this device as read from the device.
| For USB host controller drivers (virtual root hubs) this may
| be omitted, or (for newer drivers) will identify the kernel
| version and the driver which provides this hub emulation.
|__String info tag
S: Product=ssss
| |__Product description of this device as read from the device.
| For older USB host controller drivers (virtual root hubs) this
| indicates the driver; for newer ones, it's a product (and vendor)
| description that often comes from the kernel's PCI ID database.
|__String info tag
S: SerialNumber=ssss
| |__Serial Number of this device as read from the device.
| For USB host controller drivers (virtual root hubs) this is
| some unique ID, normally a bus ID (address or slot name) that
| can't be shared with any other device.
|__String info tag
Configuration descriptor info
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
| | | | | |__MaxPower in mA
| | | | |__Attributes
| | | |__ConfiguratioNumber
| | |__NumberOfInterfaces
| |__ "*" indicates the active configuration (others are " ")
|__Config info tag
USB devices may have multiple configurations, each of which act
rather differently. For example, a bus-powered configuration
might be much less capable than one that is self-powered. Only
one device configuration can be active at a time; most devices
have only one configuration.
Each configuration consists of one or more interfaces. Each
interface serves a distinct "function", which is typically bound
to a different USB device driver. One common example is a USB
speaker with an audio interface for playback, and a HID interface
for use with software volume control.
Interface descriptor info (can be multiple per Config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
I:* If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
| | | | | | | | |__Driver name
| | | | | | | | or "(none)"
| | | | | | | |__InterfaceProtocol
| | | | | | |__InterfaceSubClass
| | | | | |__InterfaceClass
| | | | |__NumberOfEndpoints
| | | |__AlternateSettingNumber
| | |__InterfaceNumber
| |__ "*" indicates the active altsetting (others are " ")
|__Interface info tag
A given interface may have one or more "alternate" settings.
For example, default settings may not use more than a small
amount of periodic bandwidth. To use significant fractions
of bus bandwidth, drivers must select a non-default altsetting.
Only one setting for an interface may be active at a time, and
only one driver may bind to an interface at a time. Most devices
have only one alternate setting per interface.
Endpoint descriptor info (can be multiple per Interface)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddss
| | | | |__Interval (max) between transfers
| | | |__EndpointMaxPacketSize
| | |__Attributes(EndpointType)
| |__EndpointAddress(I=In,O=Out)
|__Endpoint info tag
The interval is nonzero for all periodic (interrupt or isochronous)
endpoints. For high speed endpoints the transfer interval may be
measured in microseconds rather than milliseconds.
For high speed periodic endpoints, the ``EndpointMaxPacketSize`` reflects
the per-microframe data transfer size. For "high bandwidth"
endpoints, that can reflect two or three packets (for up to
3KBytes every 125 usec) per endpoint.
With the Linux-USB stack, periodic bandwidth reservations use the
transfer intervals and sizes provided by URBs, which can be less
than those found in endpoint descriptor.
Usage examples
~~~~~~~~~~~~~~
If a user or script is interested only in Topology info, for
example, use something like ``grep ^T: /sys/kernel/debug/usb/devices``
for only the Topology lines. A command like
``grep -i ^[tdp]: /sys/kernel/debug/usb/devices`` can be used to list
only the lines that begin with the characters in square brackets,
where the valid characters are TDPCIE. With a slightly more able
script, it can display any selected lines (for example, only T, D,
and P lines) and change their output format. (The ``procusb``
Perl script is the beginning of this idea. It will list only
selected lines [selected from TBDPSCIE] or "All" lines from
``/sys/kernel/debug/usb/devices``.)
The Topology lines can be used to generate a graphic/pictorial
of the USB devices on a system's root hub. (See more below
on how to do this.)
The Interface lines can be used to determine what driver is
being used for each device, and which altsetting it activated.
The Configuration lines could be used to list maximum power
(in milliamps) that a system's USB devices are using.
For example, ``grep ^C: /sys/kernel/debug/usb/devices``.
Here's an example, from a system which has a UHCI root hub,
an external hub connected to the root hub, and a mouse and
a serial converter connected to the external hub.
::
T: Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#= 1 Spd=12 MxCh= 2
B: Alloc= 28/900 us ( 3%), #Int= 2, #Iso= 0
D: Ver= 1.00 Cls=09(hub ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=0000 ProdID=0000 Rev= 0.00
S: Product=USB UHCI Root Hub
S: SerialNumber=dce0
C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr= 0mA
I: If#= 0 Alt= 0 #EPs= 1 Cls=09(hub ) Sub=00 Prot=00 Driver=hub
E: Ad=81(I) Atr=03(Int.) MxPS= 8 Ivl=255ms
T: Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#= 2 Spd=12 MxCh= 4
D: Ver= 1.00 Cls=09(hub ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=0451 ProdID=1446 Rev= 1.00
C:* #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=100mA
I: If#= 0 Alt= 0 #EPs= 1 Cls=09(hub ) Sub=00 Prot=00 Driver=hub
E: Ad=81(I) Atr=03(Int.) MxPS= 1 Ivl=255ms
T: Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#= 3 Spd=1.5 MxCh= 0
D: Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=04b4 ProdID=0001 Rev= 0.00
C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
I: If#= 0 Alt= 0 #EPs= 1 Cls=03(HID ) Sub=01 Prot=02 Driver=mouse
E: Ad=81(I) Atr=03(Int.) MxPS= 3 Ivl= 10ms
T: Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#= 4 Spd=12 MxCh= 0
D: Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=0565 ProdID=0001 Rev= 1.08
S: Manufacturer=Peracom Networks, Inc.
S: Product=Peracom USB to Serial Converter
C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=100mA
I: If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
E: Ad=81(I) Atr=02(Bulk) MxPS= 64 Ivl= 16ms
E: Ad=01(O) Atr=02(Bulk) MxPS= 16 Ivl= 16ms
E: Ad=82(I) Atr=03(Int.) MxPS= 8 Ivl= 8ms
Selecting only the ``T:`` and ``I:`` lines from this (for example, by using
``procusb ti``), we have
::
T: Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#= 1 Spd=12 MxCh= 2
T: Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#= 2 Spd=12 MxCh= 4
I: If#= 0 Alt= 0 #EPs= 1 Cls=09(hub ) Sub=00 Prot=00 Driver=hub
T: Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#= 3 Spd=1.5 MxCh= 0
I: If#= 0 Alt= 0 #EPs= 1 Cls=03(HID ) Sub=01 Prot=02 Driver=mouse
T: Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#= 4 Spd=12 MxCh= 0
I: If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
Physically this looks like (or could be converted to)::
+------------------+
| PC/root_hub (12)| Dev# = 1
+------------------+ (nn) is Mbps.
Level 0 | CN.0 | CN.1 | [CN = connector/port #]
+------------------+
/
/
+-----------------------+
Level 1 | Dev#2: 4-port hub (12)|
+-----------------------+
|CN.0 |CN.1 |CN.2 |CN.3 |
+-----------------------+
\ \____________________
\_____ \
\ \
+--------------------+ +--------------------+
Level 2 | Dev# 3: mouse (1.5)| | Dev# 4: serial (12)|
+--------------------+ +--------------------+
Or, in a more tree-like structure (ports [Connectors] without
connections could be omitted)::
PC: Dev# 1, root hub, 2 ports, 12 Mbps
|_ CN.0: Dev# 2, hub, 4 ports, 12 Mbps
|_ CN.0: Dev #3, mouse, 1.5 Mbps
|_ CN.1:
|_ CN.2: Dev #4, serial, 12 Mbps
|_ CN.3:
|_ CN.1:
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
Linux USB host-side API 소개
1-36USB는 PC나 workstation 같은 host에 여러 peripheral device를 연결합니다. Topology는 host가 root이자 system master, hub가 interior node, peripheral이 leaf이자 slave인 tree 구조입니다.
현대 PC는 보통 여러 USB tree를 제공하며 USB 3.0은 5 Gbit/s, USB 3.1은 10 Gbit/s, legacy USB 2.0은 480 Mbit/s bus를 사용합니다.
Master·slave 비대칭은 사용 편의성을 위해 설계되었습니다. Upstream과 downstream connector를 물리적으로 혼동하기 어렵고 Type-C plug에서는 방향이 중요하지 않으며, 미리 정해진 master가 auto-configuration을 관리하므로 host software가 distributed configuration을 처리할 필요도 없습니다.
Linux USB 지원은 2.2 kernel 초기에 추가된 뒤 USB 세대, host controller, peripheral driver 지원과 latency 측정·power management 기능이 계속 확장되었습니다.
Linux는 USB host뿐 아니라 USB device 내부에서도 실행될 수 있습니다. Peripheral 내부 driver는 host-side driver와 역할이 달라 `gadget driver`라고 부르며 이 문서의 범위에는 포함되지 않습니다.
Host가 bus를 통제하고 hub를 거쳐 peripheral leaf를 관리합니다.
.. _usb-hostside-api:
===========================
The Linux-USB Host Side API
===========================
Introduction to USB on Linux
============================
A Universal Serial Bus (USB) is used to connect a host, such as a PC or
workstation, to a number of peripheral devices. USB uses a tree
structure, with the host as the root (the system's master), hubs as
interior nodes, and peripherals as leaves (and slaves). Modern PCs
support several such trees of USB devices, usually
a few USB 3.0 (5 GBit/s) or USB 3.1 (10 GBit/s) and some legacy
USB 2.0 (480 MBit/s) buses just in case.
That master/slave asymmetry was designed-in for a number of reasons, one
being ease of use. It is not physically possible to mistake upstream and
downstream or it does not matter with a type C plug (or they are built into the
peripheral). Also, the host software doesn't need to deal with
distributed auto-configuration since the pre-designated master node
manages all that.
Kernel developers added USB support to Linux early in the 2.2 kernel
series and have been developing it further since then. Besides support
for each new generation of USB, various host controllers gained support,
new drivers for peripherals have been added and advanced features for latency
measurement and improved power management introduced.
Linux can run inside USB devices as well as on the hosts that control
the devices. But USB device drivers running inside those peripherals
don't do the same things as the ones running inside hosts, so they've
been given a different name: *gadget drivers*. This document does not
cover gadget drivers.
Usbcore, interface driver와 transfer model
37-108Host-side USB device driver는 `usbcore` API와 통신합니다. 하나는 driver framework를 통해 노출되는 general-purpose driver용이고, 다른 하나는 USB tree를 관리하는 hub driver나 개별 bus를 제어하는 host controller driver처럼 core 일부인 driver용입니다.
USB transfer는 control, bulk, interrupt, isochronous 네 종류입니다. Control과 bulk는 남는 bandwidth를 사용하고 interrupt와 isochronous는 bandwidth를 예약해 service를 보장합니다.
Device는 하나 이상의 configuration을 가지며 한 번에 하나만 active입니다. 최고 속도보다 낮은 속도에서도 동작해야 하고, 완전한 기능을 유지하는 최저 속도를 BOS descriptor로 알릴 수 있습니다. USB 3.0 이후 configuration에는 power management 단위로 묶이는 하나 이상의 function이 있습니다.
Configuration 또는 function에는 interface가 있고 interface는 alternate setting을 가질 수 있습니다. Interface는 USB Class specification이나 vendor·device별 규격으로 정의됩니다. USB device driver는 device가 아니라 interface에 bind됩니다. 다만 대부분의 단순 device는 function·configuration·interface·alternate setting이 각각 하나뿐입니다.
Interface는 transfer type과 direction을 정의하는 endpoint를 하나 이상 가집니다. Configuration 전체에서 각 direction마다 최대 16 endpoint를 interface들에 배분할 수 있습니다.
USB data는 packet 단위이며 endpoint마다 maximum packet size가 있습니다. Bulk transfer 끝은 short packet 또는 zero-length packet으로 표시할 수 있어 driver가 convention을 알아야 합니다.
Linux USB API는 control·bulk message용 synchronous call과 모든 transfer type에 사용하는 URB 기반 asynchronous call을 제공합니다. Driver 개발에는 USB 3.0 specification과 해당 class·device specification을 함께 참고해야 합니다.
실제 register I/O와 IRQ를 다루는 host-side driver는 HCD뿐입니다. HCD API는 공통이지만 덜 일반적인 controller의 fault reporting과 URB unlink 같은 recovery에는 차이가 남아 있으므로 device driver는 active disconnect를 여러 HCD에서 시험해 HCD-specific behavior에 의존하지 않는지 확인해야 합니다.
USB Host-Side API Model
=======================
Host-side drivers for USB devices talk to the "usbcore" APIs. There are
two. One is intended for *general-purpose* drivers (exposed through
driver frameworks), and the other is for drivers that are *part of the
core*. Such core drivers include the *hub* driver (which manages trees
of USB devices) and several different kinds of *host controller
drivers*, which control individual buses.
The device model seen by USB drivers is relatively complex.
- USB supports four kinds of data transfers (control, bulk, interrupt,
and isochronous). Two of them (control and bulk) use bandwidth as
it's available, while the other two (interrupt and isochronous) are
scheduled to provide guaranteed bandwidth.
- The device description model includes one or more "configurations"
per device, only one of which is active at a time. Devices are supposed
to be capable of operating at lower than their top
speeds and may provide a BOS descriptor showing the lowest speed they
remain fully operational at.
- From USB 3.0 on configurations have one or more "functions", which
provide a common functionality and are grouped together for purposes
of power management.
- Configurations or functions have one or more "interfaces", each of which may have
"alternate settings". Interfaces may be standardized by USB "Class"
specifications, or may be specific to a vendor or device.
USB device drivers actually bind to interfaces, not devices. Think of
them as "interface drivers", though you may not see many devices
where the distinction is important. *Most USB devices are simple,
with only one function, one configuration, one interface, and one alternate
setting.*
- Interfaces have one or more "endpoints", each of which supports one
type and direction of data transfer such as "bulk out" or "interrupt
in". The entire configuration may have up to sixteen endpoints in
each direction, allocated as needed among all the interfaces.
- Data transfer on USB is packetized; each endpoint has a maximum
packet size. Drivers must often be aware of conventions such as
flagging the end of bulk transfers using "short" (including zero
length) packets.
- The Linux USB API supports synchronous calls for control and bulk
messages. It also supports asynchronous calls for all kinds of data
transfer, using request structures called "URBs" (USB Request
Blocks).
Accordingly, the USB Core API exposed to device drivers covers quite a
lot of territory. You'll probably need to consult the USB 3.0
specification, available online from www.usb.org at no cost, as well as
class or device specifications.
The only host-side drivers that actually touch hardware (reading/writing
registers, handling IRQs, and so on) are the HCDs. In theory, all HCDs
provide the same functionality through the same API. In practice, that's
becoming more true, but there are still differences
that crop up especially with fault handling on the less common controllers.
Different controllers don't
necessarily report the same aspects of failures, and recovery from
faults (including software-induced ones like unlinking an URB) isn't yet
fully consistent. Device driver authors should make a point of doing
disconnect testing (while the device is active) with each different host
controller driver, to make sure drivers don't have bugs of their own as
well as to make sure they aren't relying on some HCD-specific behavior.
.. _usb_chapter9:
USB Chapter 9 type과 host data macro
109-138`include/uapi/linux/usb/ch9.h`에는 USB specification Chapter 9의 표준 data type이 정의되어 있습니다. 이 type은 host-side API, gadget API, USB character device와 debugfs interface 전반에서 사용됩니다.
UAPI header는 `include/linux/usb/ch9.h`에서 include되며 kernel header에는 이 data type을 조작하는 utility routine 선언도 있습니다. 구현은 `drivers/usb/common/common.c`에 있고 debugging output helper는 `drivers/usb/common/debug.c`에 정의됩니다.
Host-side API는 driver·device lifecycle과 buffer를 usbcore에서 실제 I/O를 수행하는 HCD까지 전달하는 여러 layer의 data type과 macro를 노출합니다. 내부 정의는 `include/linux/usb.h` kernel-doc에 정리되어 있습니다.
USB-Standard Types
==================
In ``include/uapi/linux/usb/ch9.h`` you will find the USB data types defined
in chapter 9 of the USB specification. These data types are used throughout
USB, and in APIs including this host side API, gadget APIs, usb character
devices and debugfs interfaces. That file is itself included by
``include/linux/usb/ch9.h``, which also contains declarations of a few
utility routines for manipulating these data types; the implementations
are in ``drivers/usb/common/common.c``.
.. kernel-doc:: drivers/usb/common/common.c
:export:
In addition, some functions useful for creating debugging output are
defined in ``drivers/usb/common/debug.c``.
.. _usb_header:
Host-Side Data Types and Macros
===============================
The host side API exposes several layers to drivers, some of which are
more necessary than others. These support lifecycle models for host side
drivers and devices, and support passing buffers through usbcore to some
HCD that performs the I/O for the device driver.
.. kernel-doc:: include/linux/usb.h
:internal:
Asynchronous URB와 synchronous wrapper
139-179USB API의 가장 기본적인 I/O model은 asynchronous URB입니다. Driver가 request를 submit하고 URB completion callback이 다음 단계를 처리합니다. 모든 transfer type이 이 model을 지원합니다.
Control URB는 항상 setup과 status stage가 있고 data stage는 없을 수 있습니다. Isochronous URB는 큰 packet을 허용하며 packet별 fault report를 포함하는 특수 규칙이 있습니다.
Synchronous API는 하나 이상의 URB를 allocate·submit한 뒤 completion까지 기다리는 wrapper입니다. Single-buffer control·bulk wrapper는 일부 disconnect scenario에서 쓰기 까다롭고, scatterlist streaming I/O wrapper는 bulk 또는 interrupt에 사용됩니다.
USB driver는 DMA 가능한 buffer를 제공해야 하지만 mapping까지 직접 할 필요는 없습니다. DMA buffer allocation API를 쓰면 일부 system의 bounce buffer를 피할 수 있고, 64-bit DMA 지원으로 다른 형태의 bounce buffer도 줄일 수 있습니다.
Exported core API 구현은 `drivers/usb/core/urb.c`, `message.c`, `file.c`, `driver.c`, `usb.c`, `hub.c`에 분산되어 있으며 `message.c`는 `usb_core` C namespace로 문서화됩니다.
USB Core APIs
=============
There are two basic I/O models in the USB API. The most elemental one is
asynchronous: drivers submit requests in the form of an URB, and the
URB's completion callback handles the next step. All USB transfer types
support that model, although there are special cases for control URBs
(which always have setup and status stages, but may not have a data
stage) and isochronous URBs (which allow large packets and include
per-packet fault reports). Built on top of that is synchronous API
support, where a driver calls a routine that allocates one or more URBs,
submits them, and waits until they complete. There are synchronous
wrappers for single-buffer control and bulk transfers (which are awkward
to use in some driver disconnect scenarios), and for scatterlist based
streaming i/o (bulk or interrupt).
USB drivers need to provide buffers that can be used for DMA, although
they don't necessarily need to provide the DMA mapping themselves. There
are APIs to use used when allocating DMA buffers, which can prevent use
of bounce buffers on some systems. In some cases, drivers may be able to
rely on 64bit DMA to eliminate another kind of bounce buffer.
.. kernel-doc:: drivers/usb/core/urb.c
:export:
.. c:namespace:: usb_core
.. kernel-doc:: drivers/usb/core/message.c
:export:
.. kernel-doc:: drivers/usb/core/file.c
:export:
.. kernel-doc:: drivers/usb/core/driver.c
:export:
.. kernel-doc:: drivers/usb/core/usb.c
:export:
.. kernel-doc:: drivers/usb/core/hub.c
:export:
Host Controller Driver API layer
180-214Host Controller API는 주로 XHCI, EHCI, OHCI, UHCI 같은 표준 register interface를 구현하는 HCD 전용입니다.
UHCI는 Intel이 설계하고 VIA도 사용한 초기 interface로 hardware가 담당하는 일이 적습니다. OHCI는 더 큰 transfer와 protocol state 추적을 hardware에 맡겼고, USB 2.0용 EHCI는 OHCI식 hardware offload와 UHCI식 ISO·TD list 특성을 함께 가집니다. USB 3.0용 XHCI는 더 많은 기능을 hardware로 옮겼습니다.
표준 controller 외에도 PIO 기반 controller, simulator, USB를 network로 전달하는 virtual host controller가 있습니다. 모든 controller driver에는 같은 기본 API가 제공됩니다.
역사적으로 API는 두 layer입니다. 2.2 kernel부터 있던 `struct usb_bus`는 얇은 layer이고, `struct usb_hcd`는 HCD끼리 common code를 공유해 driver 크기와 HCD-specific behavior를 줄이는 풍부한 layer입니다.
구현과 export는 `drivers/usb/core/hcd.c`, PCI helper는 `hcd-pci.c`, internal buffer support는 `buffer.c`에 있습니다.
Host Controller APIs
====================
These APIs are only for use by host controller drivers, most of which
implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI
was one of the first interfaces, designed by Intel and also used by VIA;
it doesn't do much in hardware. OHCI was designed later, to have the
hardware do more work (bigger transfers, tracking protocol state, and so
on). EHCI was designed with USB 2.0; its design has features that
resemble OHCI (hardware does much more work) as well as UHCI (some parts
of ISO support, TD list processing). XHCI was designed with USB 3.0. It
continues to shift support for functionality into hardware.
There are host controllers other than the "big three", although most PCI
based controllers (and a few non-PCI based ones) use one of those
interfaces. Not all host controllers use DMA; some use PIO, and there is
also a simulator and a virtual host controller to pipe USB over the network.
The same basic APIs are available to drivers for all those controllers.
For historical reasons they are in two layers: :c:type:`struct
usb_bus <usb_bus>` is a rather thin layer that became available
in the 2.2 kernels, while :c:type:`struct usb_hcd <usb_hcd>`
is a more featureful layer
that lets HCDs share common code, to shrink driver size and
significantly reduce hcd-specific behaviors.
.. kernel-doc:: drivers/usb/core/hcd.c
:export:
.. kernel-doc:: drivers/usb/core/hcd-pci.c
:export:
.. kernel-doc:: drivers/usb/core/buffer.c
:internal:
USB character device와 devtmpfs node
215-259USB driver를 위해 새 kernel code를 쓰지 않고 userspace application이나 library로 구현할 수 있습니다. Character device를 감싸는 대표 library는 C/C++용 `libusb`와 Java용 `jUSB`이며, 오래된 배경 자료는 `http://www.linux-usb.org/`의 USB Guide에 있습니다.
이 interface는 과거 `usbfs`로 구현됐지만 sysfs debug interface의 일부는 아닙니다. 특히 asynchronous mode 설명은 불완전하며 kernel 2.5.66 당시 code와 문서의 교차 검토가 필요하다고 명시되어 있습니다.
관례적으로 `/dev/bus/usb/` 아래에 있는 `/dev/bus/usb/BBB/DDD` file은 device configuration descriptor를 노출하고 device request와 endpoint I/O를 위한 ioctl을 지원합니다. Program access 전용 magic file입니다.
`BBB`는 bus enumeration 순서, `DDD`는 bus 안의 device 순서에서 받은 번호입니다. 같은 hub port에 계속 꽂혀 있어도 바뀔 수 있는 불안정 identifier이므로 application configuration에 저장해서는 안 됩니다.
HID와 networking device는 올바른 UPS 같은 특정 장치를 고를 수 있는 stable ID를 별도로 노출하지만 이 device-file interface 자체는 아직 그 ID를 제공하지 않습니다.
The USB character device nodes
==============================
This chapter presents the Linux character device nodes. You may prefer
to avoid writing new kernel code for your USB driver. User mode device
drivers are usually packaged as applications or libraries, and may use
character devices through some programming library that wraps it.
Such libraries include:
- `libusb <http://libusb.sourceforge.net>`__ for C/C++, and
- `jUSB <http://jUSB.sourceforge.net>`__ for Java.
Some old information about it can be seen at the "USB Device Filesystem"
section of the USB Guide. The latest copy of the USB Guide can be found
at http://www.linux-usb.org/
.. note::
- They were used to be implemented via *usbfs*, but this is not part of
the sysfs debug interface.
- This particular documentation is incomplete, especially with respect
to the asynchronous mode. As of kernel 2.5.66 the code and this
(new) documentation need to be cross-reviewed.
What files are in "devtmpfs"?
-----------------------------
Conventionally mounted at ``/dev/bus/usb/``, usbfs features include:
- ``/dev/bus/usb/BBB/DDD`` ... magic files exposing the each device's
configuration descriptors, and supporting a series of ioctls for
making device requests, including I/O to devices. (Purely for access
by programs.)
Each bus is given a number (``BBB``) based on when it was enumerated; within
each bus, each device is given a similar number (``DDD``). Those ``BBB/DDD``
paths are not "stable" identifiers; expect them to change even if you
always leave the devices plugged in to the same hub port. *Don't even
think of saving these in application configuration files.* Stable
identifiers are available, for user mode applications that want to use
them. HID and networking devices expose these stable IDs, so that for
example you can be sure that you told the right UPS to power down its
second server. Pleast note that it doesn't (yet) expose those IDs.
`/dev/bus/usb/BBB/DDD` binary와 접근 규칙
260-319Device file을 read하면 먼저 18-byte device descriptor가 나오고 이어서 configuration descriptor가 나옵니다. Multi-byte 값은 대체로 little endian에서 host byte order로 바꿔야 하지만 device descriptor의 BCD field, vendor ID, product ID는 kernel이 byte-swap합니다.
Configuration descriptor에는 interface, alternate setting, endpoint와 추가 class descriptor가 포함될 수 있습니다. 뒤 설명에 따르면 file에는 device descriptor 다음 각 configuration descriptor가 이어지고, device descriptor multi-byte field는 host endian이지만 configuration descriptor는 bus endian입니다.
Configuration block은 `wTotalLength` byte 간격입니다. Device가 표시된 길이보다 적은 descriptor data를 반환하면 누락 byte만큼 file에 hole이 생깁니다. 같은 정보는 `/sys/kernel/debug/usb/devices`에서 text로도 볼 수 있습니다.
`ioctl()`로 synchronous·asynchronous endpoint I/O와 device 관리 request를 수행할 수 있습니다. `CAP_SYS_RAWIO` capability와 filesystem permission이 모두 필요하고 한 device file에는 한 번에 ioctl 하나만 실행할 수 있어 synchronous read 중 다른 thread의 endpoint write가 막힙니다. Half-duplex가 아니라면 asynchronous I/O를 사용해야 합니다.
Bus·device 번호는 순차 할당되고 재사용됩니다. Connected 상태에서도 power·hub·cable 접촉으로 re-enumerate되어 예를 들어 `002/027`이 나중에 `002/048`이 될 수 있으므로 stable access key로 사용할 수 없습니다.
User-level driver는 file을 read/write로 열고 descriptor로 예상 device인지 확인한 뒤 ioctl로 interface 하나 이상을 claim하고 control·bulk 등 transfer를 수행합니다. ioctl 정의는 `<linux/usbdevice_fs.h>`, 주 reference 구현은 `linux/drivers/usb/core/devio.c`입니다.
기본적으로 `BBB/DDD`는 root만 write할 수 있습니다. 필요한 user에게 `chmod`로 선택 권한을 주거나 usbfs mount option `devmode=0666` 등을 사용할 수 있습니다.
불안정 path를 discovery 시점에 찾고 descriptor 검증 후 interface를 claim합니다.
/dev/bus/usb/BBB/DDD
--------------------
Use these files in one of these basic ways:
- *They can be read,* producing first the device descriptor (18 bytes) and
then the descriptors for the current configuration. See the USB 2.0 spec
for details about those binary data formats. You'll need to convert most
multibyte values from little endian format to your native host byte
order, although a few of the fields in the device descriptor (both of
the BCD-encoded fields, and the vendor and product IDs) will be
byteswapped for you. Note that configuration descriptors include
descriptors for interfaces, altsettings, endpoints, and maybe additional
class descriptors.
- *Perform USB operations* using *ioctl()* requests to make endpoint I/O
requests (synchronously or asynchronously) or manage the device. These
requests need the ``CAP_SYS_RAWIO`` capability, as well as filesystem
access permissions. Only one ioctl request can be made on one of these
device files at a time. This means that if you are synchronously reading
an endpoint from one thread, you won't be able to write to a different
endpoint from another thread until the read completes. This works for
*half duplex* protocols, but otherwise you'd use asynchronous i/o
requests.
Each connected USB device has one file. The ``BBB`` indicates the bus
number. The ``DDD`` indicates the device address on that bus. Both
of these numbers are assigned sequentially, and can be reused, so
you can't rely on them for stable access to devices. For example,
it's relatively common for devices to re-enumerate while they are
still connected (perhaps someone jostled their power supply, hub,
or USB cable), so a device might be ``002/027`` when you first connect
it and ``002/048`` sometime later.
These files can be read as binary data. The binary data consists
of first the device descriptor, then the descriptors for each
configuration of the device. Multi-byte fields in the device descriptor
are converted to host endianness by the kernel. The configuration
descriptors are in bus endian format! The configuration descriptor
are wTotalLength bytes apart. If a device returns less configuration
descriptor data than indicated by wTotalLength there will be a hole in
the file for the missing bytes. This information is also shown
in text form by the ``/sys/kernel/debug/usb/devices`` file, described later.
These files may also be used to write user-level drivers for the USB
devices. You would open the ``/dev/bus/usb/BBB/DDD`` file read/write,
read its descriptors to make sure it's the device you expect, and then
bind to an interface (or perhaps several) using an ioctl call. You
would issue more ioctls to the device to communicate to it using
control, bulk, or other kinds of USB transfers. The IOCTLs are
listed in the ``<linux/usbdevice_fs.h>`` file, and at this writing the
source code (``linux/drivers/usb/core/devio.c``) is the primary reference
for how to access devices through those files.
Note that since by default these ``BBB/DDD`` files are writable only by
root, only root can write such user mode drivers. You can selectively
grant read/write permissions to other users by using ``chmod``. Also,
usbfs mount options such as ``devmode=0666`` may be helpful.
User-mode driver lifecycle
320-356User-mode driver는 먼저 처리 가능한 device file을 찾아야 합니다. `/sbin/hotplug` event agent가 알려 줄 수도 있고 `/dev/bus/usb` 전체를 scan해 대부분을 무시할 수도 있습니다.
어느 방식이든 device file의 descriptor를 모두 `read()`하고 지원 policy와 대조해야 합니다. Vendor·product ID 한 쌍만 허용할 수도 있고 더 복잡한 policy가 필요할 수도 있습니다.
System에 같은 device가 하나만 있다고 가정해서는 안 됩니다. Code가 동시에 하나만 처리한다면 여러 개를 감지하고 user가 사용할 device를 고르게 해야 합니다.
단순 driver는 control request만 사용할 수 있습니다. 예를 들어 vendor-specific control request로 초기화·설정만 하고 나머지는 kernel driver가 맡습니다.
복잡한 driver는 non-control endpoint로 data를 읽고 쓰며 interface를 exclusive하게 claim합니다. Bulk가 가장 쉽지만 low-speed device에서는 interrupt만 사용할 수 있습니다. Interrupt와 isochronous는 bandwidth를 예약하는 periodic transfer이며 usbfs에서는 asynchronous call 없이 사용하기 까다롭지만 interrupt는 synchronous one-shot도 가능합니다.
Disconnect 시 request state cleanup은 kernel이 처리합니다. User-mode driver는 `ENODEV`를 보기 시작하면 open file descriptor를 가능한 빨리 닫아야 합니다.
Discovery부터 disconnect 정리까지의 기본 흐름입니다.
Life Cycle of User Mode Drivers
-------------------------------
Such a driver first needs to find a device file for a device it knows
how to handle. Maybe it was told about it because a ``/sbin/hotplug``
event handling agent chose that driver to handle the new device. Or
maybe it's an application that scans all the ``/dev/bus/usb`` device files,
and ignores most devices. In either case, it should :c:func:`read()`
all the descriptors from the device file, and check them against what it
knows how to handle. It might just reject everything except a particular
vendor and product ID, or need a more complex policy.
Never assume there will only be one such device on the system at a time!
If your code can't handle more than one device at a time, at least
detect when there's more than one, and have your users choose which
device to use.
Once your user mode driver knows what device to use, it interacts with
it in either of two styles. The simple style is to make only control
requests; some devices don't need more complex interactions than those.
(An example might be software using vendor-specific control requests for
some initialization or configuration tasks, with a kernel driver for the
rest.)
More likely, you need a more complex style driver: one using non-control
endpoints, reading or writing data and claiming exclusive use of an
interface. *Bulk* transfers are easiest to use, but only their sibling
*interrupt* transfers work with low speed devices. Both interrupt and
*isochronous* transfers offer service guarantees because their bandwidth
is reserved. Such "periodic" transfers are awkward to use through usbfs,
unless you're using the asynchronous calls. However, interrupt transfers
can also be used in a synchronous "one shot" style.
Your user-mode driver should never need to worry about cleaning up
request state when the device is disconnected, although it should close
its open file descriptors as soon as it starts seeing the ENODEV errors.
Usbfs ioctl 공통 규칙
357-386Userspace program은 ioctl 사용을 위해 `<linux/usb.h>`, `<linux/usbdevice_fs.h>`, `<asm/byteorder.h>`를 include해야 합니다. USB 2.0 Chapter 9 standard request는 `<linux/usb/ch9.h>`를 통해 자동 포함됩니다.
별도 설명이 없으면 ioctl request가 성공할 때 적용한 usbfs file의 modification time을 갱신합니다. 반환값 `0`은 성공이고 그 밖에는 `usb-error-codes`에 설명된 standard USB error code입니다.
Device file 하나는 endpoint마다 하나씩인 여러 I/O stream을 multiplex합니다. 모든 device는 제한된 RPC-style access를 지원하는 control endpoint 0을 가집니다.
Kernel `hub_wq`는 power consumption과 기본 기능에 영향을 주는 device-wide configuration을 설정합니다. Endpoint는 interface에 속하고 interface의 alternate setting에 따라 available endpoint가 달라질 수 있습니다. 단순 device는 configuration과 interface가 하나라 driver가 이 구분을 무시하기도 합니다.
The ioctl() Requests
--------------------
To use these ioctls, you need to include the following headers in your
userspace program::
#include <linux/usb.h>
#include <linux/usbdevice_fs.h>
#include <asm/byteorder.h>
The standard USB device model requests, from "Chapter 9" of the USB 2.0
specification, are automatically included from the ``<linux/usb/ch9.h>``
header.
Unless noted otherwise, the ioctl requests described here will update
the modification time on the usbfs file to which they are applied
(unless they fail). A return of zero indicates success; otherwise, a
standard USB error code is returned (These are documented in
:ref:`usb-error-codes`).
Each of these files multiplexes access to several I/O streams, one per
endpoint. Each device has one control endpoint (endpoint zero) which
supports a limited RPC style RPC access. Devices are configured by
hub_wq (in the kernel) setting a device-wide *configuration* that
affects things like power consumption and basic functionality. The
endpoints are part of USB *interfaces*, which may have *altsettings*
affecting things like which endpoints are available. Many devices only
have a single configuration and interface, so drivers for them will
ignore configurations and altsettings.
Management와 status ioctl
387-514Management·status request는 device I/O 자체보다 interface ownership, speed, driver binding, endpoint state를 다루며 모두 synchronous입니다.
`USBDEVFS_CLAIMINTERFACE`는 아직 usbfs나 kernel driver가 claim하지 않은 `bInterfaceNumber`를 강제로 claim합니다. Endpoint 사용 전에 명시적으로 claim하지 않아도 다른 driver가 bind하지 않았다면 usbfs가 자동 claim합니다. Claim은 `USBDEVFS_RELEASEINTERFACE` 또는 file close로 해제되며 이 두 request는 mtime을 갱신하지 않습니다.
`USBDEVFS_CONNECTINFO`는 `usbdevfs_connectinfo`에 device number와 low-speed 여부를 반환하지만 `slow=0`만으로 full speed와 480 Mbit/s high speed를 구분할 수 없습니다. `USBDEVFS_GET_SPEED`는 `enum usb_device_speed`에 맞는 숫자로 정확한 speed를 반환합니다.
`USBDEVFS_GETDRIVER`는 `usbdevfs_getdriver`를 통해 지정 interface에 bind된 kernel driver name을 반환합니다.
`USBDEVFS_IOCTL`은 `usbdevfs_ioctl` wrapper로 userspace request를 등록된 `struct usb_driver`의 ioctl entry에 전달합니다. Special character·block device를 만들지 않는 kernel driver와 filesystem operation으로 통신할 수 있고, 미리 정의된 ioctl은 kernel driver disconnect·reconnect를 통해 userspace가 binding과 configuration을 관리하게 합니다.
`USBDEVFS_RELEASEINTERFACE`에는 claim한 task와 release하는 task가 같은지 확인하는 security check가 없어 한 user-mode driver가 다른 driver를 방해할 수 있습니다.
`USBDEVFS_RESETEP`는 bulk·interrupt endpoint의 data toggle을 DATA0으로 reset합니다. Host와 device의 toggle synchronization을 잃기 쉬우므로 사용을 피하고 실제 sync loss에는 `CLEAR_HALT` 또는 `SET_INTERFACE` 같은 완전한 handshake를 써야 합니다.
`USBDEVFS_DROP_PRIVILEGES`는 arbitrary interface claim, 다른 user가 claim한 interface가 있는 device reset, `USBDEVFS_IOCTL` 실행 권한을 포기합니다. Parameter는 이 file descriptor가 claim할 수 있는 interface의 32-bit mask이며 여러 번 호출해 mask를 더 좁힐 수 있습니다.
Management/Status Requests
~~~~~~~~~~~~~~~~~~~~~~~~~~
A number of usbfs requests don't deal very directly with device I/O.
They mostly relate to device management and status. These are all
synchronous requests.
USBDEVFS_CLAIMINTERFACE
This is used to force usbfs to claim a specific interface, which has
not previously been claimed by usbfs or any other kernel driver. The
ioctl parameter is an integer holding the number of the interface
(bInterfaceNumber from descriptor).
Note that if your driver doesn't claim an interface before trying to
use one of its endpoints, and no other driver has bound to it, then
the interface is automatically claimed by usbfs.
This claim will be released by a RELEASEINTERFACE ioctl, or by
closing the file descriptor. File modification time is not updated
by this request.
USBDEVFS_CONNECTINFO
Says whether the device is lowspeed. The ioctl parameter points to a
structure like this::
struct usbdevfs_connectinfo {
unsigned int devnum;
unsigned char slow;
};
File modification time is not updated by this request.
*You can't tell whether a "not slow" device is connected at high
speed (480 MBit/sec) or just full speed (12 MBit/sec).* You should
know the devnum value already, it's the DDD value of the device file
name.
USBDEVFS_GET_SPEED
Returns the speed of the device. The speed is returned as a
numerical value in accordance with enum usb_device_speed
File modification time is not updated by this request.
USBDEVFS_GETDRIVER
Returns the name of the kernel driver bound to a given interface (a
string). Parameter is a pointer to this structure, which is
modified::
struct usbdevfs_getdriver {
unsigned int interface;
char driver[USBDEVFS_MAXDRIVERNAME + 1];
};
File modification time is not updated by this request.
USBDEVFS_IOCTL
Passes a request from userspace through to a kernel driver that has
an ioctl entry in the *struct usb_driver* it registered::
struct usbdevfs_ioctl {
int ifno;
int ioctl_code;
void *data;
};
/* user mode call looks like this.
* 'request' becomes the driver->ioctl() 'code' parameter.
* the size of 'param' is encoded in 'request', and that data
* is copied to or from the driver->ioctl() 'buf' parameter.
*/
static int
usbdev_ioctl (int fd, int ifno, unsigned request, void *param)
{
struct usbdevfs_ioctl wrapper;
wrapper.ifno = ifno;
wrapper.ioctl_code = request;
wrapper.data = param;
return ioctl (fd, USBDEVFS_IOCTL, &wrapper);
}
File modification time is not updated by this request.
This request lets kernel drivers talk to user mode code through
filesystem operations even when they don't create a character or
block special device. It's also been used to do things like ask
devices what device special file should be used. Two pre-defined
ioctls are used to disconnect and reconnect kernel drivers, so that
user mode code can completely manage binding and configuration of
devices.
USBDEVFS_RELEASEINTERFACE
This is used to release the claim usbfs made on interface, either
implicitly or because of a USBDEVFS_CLAIMINTERFACE call, before the
file descriptor is closed. The ioctl parameter is an integer holding
the number of the interface (bInterfaceNumber from descriptor); File
modification time is not updated by this request.
.. warning::
*No security check is made to ensure that the task which made
the claim is the one which is releasing it. This means that user
mode driver may interfere other ones.*
USBDEVFS_RESETEP
Resets the data toggle value for an endpoint (bulk or interrupt) to
DATA0. The ioctl parameter is an integer endpoint number (1 to 15,
as identified in the endpoint descriptor), with USB_DIR_IN added
if the device's endpoint sends data to the host.
.. Warning::
*Avoid using this request. It should probably be removed.* Using
it typically means the device and driver will lose toggle
synchronization. If you really lost synchronization, you likely
need to completely handshake with the device, using a request
like CLEAR_HALT or SET_INTERFACE.
USBDEVFS_DROP_PRIVILEGES
This is used to relinquish the ability to do certain operations
which are considered to be privileged on a usbfs file descriptor.
This includes claiming arbitrary interfaces, resetting a device on
which there are currently claimed interfaces from other users, and
issuing USBDEVFS_IOCTL calls. The ioctl parameter is a 32 bit mask
of interfaces the user is allowed to claim on this file descriptor.
You may issue this ioctl more than one time to narrow said mask.
Synchronous usbfs I/O
515-620Synchronous request는 성공 또는 error로 끝날 때까지 kernel이 calling user-mode task를 block합니다. 가장 단순한 usbfs 사용법이지만 device file 하나에서 동시에 endpoint 하나만 I/O할 수 있습니다.
`USBDEVFS_BULK`는 `usbdevfs_bulktransfer`의 endpoint, length, millisecond timeout, data pointer로 bulk read·write를 수행합니다. Endpoint는 1~15이고 device-to-host이면 `USB_DIR_IN`을 OR합니다. 당시 최신 kernel은 약 128 KByte까지 지원하며 short read와 실제 read length 설명은 원문에도 FIXME로 남아 있습니다.
`USBDEVFS_CLEAR_HALT`는 stalled bulk·interrupt endpoint의 halt와 data toggle을 clear합니다. `-EPIPE`를 반환한 endpoint에서 사용하며 control request를 직접 보내면 host의 toggle record가 깨질 수 있으므로 ioctl을 사용해야 합니다.
`USBDEVFS_CONTROL`은 `usbdevfs_ctrltransfer`로 control request를 보냅니다. 처음 8 byte가 SETUP packet이고 `bRequestType`은 `USB_TYPE_*`, `USB_DIR_*`, `USB_RECIP_*`를 조합합니다. `wLength`가 0이 아니면 OUT write 또는 IN read buffer 길이입니다.
Control data는 usbfs와 일부 HCD 제약으로 당시 4 KByte를 넘길 수 없고 short read를 허용하지 않는다고 지정할 방법도 없습니다.
`USBDEVFS_RESET`은 device-level reset 후 모든 interface를 rebind합니다. `USBDEVFS_SETINTERFACE`는 `bInterfaceNumber`와 `bAlternateSetting`으로 altsetting을 설정하며 해당 interface endpoint를 reset합니다.
`USBDEVFS_SETCONFIGURATION`은 descriptor의 `bConfigurationValue`로 `usb_set_configuration()`을 호출합니다. RESET과 SETCONFIGURATION은 device·interface·driver state를 완전히 synchronize하지 못하는 usbcore bug가 있어 사용을 피하라는 경고가 있습니다.
Synchronous I/O Support
~~~~~~~~~~~~~~~~~~~~~~~
Synchronous requests involve the kernel blocking until the user mode
request completes, either by finishing successfully or by reporting an
error. In most cases this is the simplest way to use usbfs, although as
noted above it does prevent performing I/O to more than one endpoint at
a time.
USBDEVFS_BULK
Issues a bulk read or write request to the device. The ioctl
parameter is a pointer to this structure::
struct usbdevfs_bulktransfer {
unsigned int ep;
unsigned int len;
unsigned int timeout; /* in milliseconds */
void *data;
};
The ``ep`` value identifies a bulk endpoint number (1 to 15, as
identified in an endpoint descriptor), masked with USB_DIR_IN when
referring to an endpoint which sends data to the host from the
device. The length of the data buffer is identified by ``len``; Recent
kernels support requests up to about 128KBytes. *FIXME say how read
length is returned, and how short reads are handled.*.
USBDEVFS_CLEAR_HALT
Clears endpoint halt (stall) and resets the endpoint toggle. This is
only meaningful for bulk or interrupt endpoints. The ioctl parameter
is an integer endpoint number (1 to 15, as identified in an endpoint
descriptor), masked with USB_DIR_IN when referring to an endpoint
which sends data to the host from the device.
Use this on bulk or interrupt endpoints which have stalled,
returning ``-EPIPE`` status to a data transfer request. Do not issue
the control request directly, since that could invalidate the host's
record of the data toggle.
USBDEVFS_CONTROL
Issues a control request to the device. The ioctl parameter points
to a structure like this::
struct usbdevfs_ctrltransfer {
__u8 bRequestType;
__u8 bRequest;
__u16 wValue;
__u16 wIndex;
__u16 wLength;
__u32 timeout; /* in milliseconds */
void *data;
};
The first eight bytes of this structure are the contents of the
SETUP packet to be sent to the device; see the USB 2.0 specification
for details. The bRequestType value is composed by combining a
``USB_TYPE_*`` value, a ``USB_DIR_*`` value, and a ``USB_RECIP_*``
value (from ``linux/usb.h``). If wLength is nonzero, it describes
the length of the data buffer, which is either written to the device
(USB_DIR_OUT) or read from the device (USB_DIR_IN).
At this writing, you can't transfer more than 4 KBytes of data to or
from a device; usbfs has a limit, and some host controller drivers
have a limit. (That's not usually a problem.) *Also* there's no way
to say it's not OK to get a short read back from the device.
USBDEVFS_RESET
Does a USB level device reset. The ioctl parameter is ignored. After
the reset, this rebinds all device interfaces. File modification
time is not updated by this request.
.. warning::
*Avoid using this call* until some usbcore bugs get fixed, since
it does not fully synchronize device, interface, and driver (not
just usbfs) state.
USBDEVFS_SETINTERFACE
Sets the alternate setting for an interface. The ioctl parameter is
a pointer to a structure like this::
struct usbdevfs_setinterface {
unsigned int interface;
unsigned int altsetting;
};
File modification time is not updated by this request.
Those struct members are from some interface descriptor applying to
the current configuration. The interface number is the
bInterfaceNumber value, and the altsetting number is the
bAlternateSetting value. (This resets each endpoint in the
interface.)
USBDEVFS_SETCONFIGURATION
Issues the :c:func:`usb_set_configuration()` call for the
device. The parameter is an integer holding the number of a
configuration (bConfigurationValue from descriptor). File
modification time is not updated by this request.
.. warning::
*Avoid using this call* until some usbcore bugs get fixed, since
it does not fully synchronize device, interface, and driver (not
just usbfs) state.
Asynchronous usbfs URB
621-690Userspace에서 여러 operation을 동시에 시작해야 할 때 asynchronous request가 필수입니다. 특히 interrupt·isochronous 같은 periodic transfer에 중요하지만 다른 USB request에도 사용할 수 있습니다. Submit과 completion 대기를 분리해 kernel이 request마다 block하지 않게 합니다.
Request는 kernel driver의 URB와 비슷한 `struct usbdevfs_urb`로 표현되지만 POSIX Async I/O는 아닙니다. `USBDEVFS_URB_TYPE_*` endpoint type, direction을 포함한 endpoint number, buffer와 length, request를 식별하는 userspace `usercontext`를 가집니다.
Request별로 `SIGRTMIN`부터 `SIGRTMAX` 사이 realtime signal number를 지정해 completion 시 signal을 받을 수 있습니다. Flag는 kernel URB보다 적은 범위에서 동작을 바꿉니다.
Usbfs가 URB를 반환할 때 `status`와 buffer가 갱신됩니다. ISO를 제외하면 `actual_length`가 실제 byte 수를 나타냅니다. `USBDEVFS_URB_DISABLE_SPD`를 설정하면 short packet을 허용하지 않아 요청보다 적게 읽을 때 error가 됩니다.
ISO request는 packet마다 `usbdevfs_iso_packet_desc`의 requested length, actual length, status를 가집니다. `usbdevfs_urb`에는 type, endpoint, status, flags, buffer, buffer length, actual length, start frame, packet count, error count, signal, context와 flexible ISO descriptor array가 포함됩니다.
Asynchronous request의 file mtime은 request를 시작한 시점이고 synchronous request는 완료 시점입니다. `USBDEVFS_DISCARDURB`, `USBDEVFS_DISCSIGNAL`, `USBDEVFS_REAPURB`, `USBDEVFS_REAPURBNDELAY`, `USBDEVFS_SUBMITURB`의 세부 설명은 원문에 TBS로 남아 있습니다.
Asynchronous I/O Support
~~~~~~~~~~~~~~~~~~~~~~~~
As mentioned above, there are situations where it may be important to
initiate concurrent operations from user mode code. This is particularly
important for periodic transfers (interrupt and isochronous), but it can
be used for other kinds of USB requests too. In such cases, the
asynchronous requests described here are essential. Rather than
submitting one request and having the kernel block until it completes,
the blocking is separate.
These requests are packaged into a structure that resembles the URB used
by kernel device drivers. (No POSIX Async I/O support here, sorry.) It
identifies the endpoint type (``USBDEVFS_URB_TYPE_*``), endpoint
(number, masked with USB_DIR_IN as appropriate), buffer and length,
and a user "context" value serving to uniquely identify each request.
(It's usually a pointer to per-request data.) Flags can modify requests
(not as many as supported for kernel drivers).
Each request can specify a realtime signal number (between SIGRTMIN and
SIGRTMAX, inclusive) to request a signal be sent when the request
completes.
When usbfs returns these urbs, the status value is updated, and the
buffer may have been modified. Except for isochronous transfers, the
actual_length is updated to say how many bytes were transferred; if the
USBDEVFS_URB_DISABLE_SPD flag is set ("short packets are not OK"), if
fewer bytes were read than were requested then you get an error report::
struct usbdevfs_iso_packet_desc {
unsigned int length;
unsigned int actual_length;
unsigned int status;
};
struct usbdevfs_urb {
unsigned char type;
unsigned char endpoint;
int status;
unsigned int flags;
void *buffer;
int buffer_length;
int actual_length;
int start_frame;
int number_of_packets;
int error_count;
unsigned int signr;
void *usercontext;
struct usbdevfs_iso_packet_desc iso_frame_desc[];
};
For these asynchronous requests, the file modification time reflects
when the request was initiated. This contrasts with their use with the
synchronous requests, where it reflects when requests complete.
USBDEVFS_DISCARDURB
*TBS* File modification time is not updated by this request.
USBDEVFS_DISCSIGNAL
*TBS* File modification time is not updated by this request.
USBDEVFS_REAPURB
*TBS* File modification time is not updated by this request.
USBDEVFS_REAPURBNDELAY
*TBS* File modification time is not updated by this request.
USBDEVFS_SUBMITURB
*TBS*
`/sys/kernel/debug/usb/devices` 개요
691-749Kernel에 알려진 USB device와 configuration descriptor는 debugfs의 `/sys/kernel/debug/usb/devices` text file로 노출됩니다. `poll()`로 새 device 변화를 감지할 수도 있습니다.
Userspace status viewer는 text format을 scan하고 필요 없는 line을 무시할 수 있습니다. Class·vendor-specific 상세 status는 device별 file에서 확인합니다.
File descriptor를 열고 `poll()`하면 첫 호출은 즉시 반환하며, 이후 이전·현재 content를 비교하거나 filesystem을 scan해 변화를 확인합니다. 더 정확한 방법은 filesystem scan입니다.
이 behavior는 정보와 debug 목적입니다. Device 초기화나 user-mode helper 시작에는 udev나 HAL 같은 program을 사용하는 편이 더 적절합니다.
각 device는 여러 ASCII line으로 출력됩니다. `T:` line의 첫 네 topology column인 Lev, Prnt, Port, Cnt로 USB topology diagram을 만들 수 있습니다.
Line tag는 `T` topology, `B` root hub bandwidth, `D` device descriptor, `P` product ID, `S` string descriptor, `C` configuration, `I` interface, `E` endpoint입니다. Active configuration과 altsetting은 `*`로 표시됩니다.
The USB devices
===============
The USB devices are now exported via debugfs:
- ``/sys/kernel/debug/usb/devices`` ... a text file showing each of the USB
devices on known to the kernel, and their configuration descriptors.
You can also poll() this to learn about new devices.
/sys/kernel/debug/usb/devices
-----------------------------
This file is handy for status viewing tools in user mode, which can scan
the text format and ignore most of it. More detailed device status
(including class and vendor status) is available from device-specific
files. For information about the current format of this file, see below.
This file, in combination with the poll() system call, can also be used
to detect when devices are added or removed::
int fd;
struct pollfd pfd;
fd = open("/sys/kernel/debug/usb/devices", O_RDONLY);
pfd = { fd, POLLIN, 0 };
for (;;) {
/* The first time through, this call will return immediately. */
poll(&pfd, 1, -1);
/* To see what's changed, compare the file's previous and current
contents or scan the filesystem. (Scanning is more precise.) */
}
Note that this behavior is intended to be used for informational and
debug purposes. It would be more appropriate to use programs such as
udev or HAL to initialize a device or start a user-mode helper program,
for instance.
In this file, each device's output has multiple lines of ASCII output.
I made it ASCII instead of binary on purpose, so that someone
can obtain some useful data from it without the use of an
auxiliary program. However, with an auxiliary program, the numbers
in the first 4 columns of each ``T:`` line (topology info:
Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.
Each line is tagged with a one-character ID for that line::
T = Topology (etc.)
B = Bandwidth (applies only to USB host controllers, which are
virtualized as root hubs)
D = Device descriptor info.
P = Product ID info. (from Device descriptor, but they won't fit
together on one line)
S = String descriptors.
C = Configuration descriptor info. (* = active configuration)
I = Interface descriptor info.
E = Endpoint descriptor info.
Topology `T:` line format
750-788Output legend에서 `d`는 decimal, `x`는 hexadecimal, `s`는 string이며 숫자에는 leading space나 zero가 있을 수 있습니다.
`T:` line의 `Bus`는 bus number, `Lev`는 bus topology level, `Prnt`는 parent device number, `Port`는 parent의 connector·port, `Cnt`는 같은 level의 device count, `Dev#`는 device number, `Spd`는 Mbit/s speed, `MxCh`는 maximum children입니다.
Speed `1.5`는 low speed, `12`는 full speed, `480`은 USB 2.0 high speed, `5000`은 USB 3.0 SuperSpeed를 뜻합니다.
역사적 이유로 출력되는 `Port` number는 실제보다 항상 1 작습니다. 실제 port 4에 꽂은 device는 `Port=03`으로 표시됩니다.
/sys/kernel/debug/usb/devices output format
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Legend::
d = decimal number (may have leading spaces or 0's)
x = hexadecimal number (may have leading spaces or 0's)
s = string
Topology info
^^^^^^^^^^^^^
::
T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=dddd MxCh=dd
| | | | | | | | |__MaxChildren
| | | | | | | |__Device Speed in Mbps
| | | | | | |__DeviceNumber
| | | | | |__Count of devices at this level
| | | | |__Connector/Port on Parent for this device
| | | |__Parent DeviceNumber
| | |__Level in topology for this bus
| |__Bus number
|__Topology info tag
Speed may be:
======= ======================================================
1.5 Mbit/s for low speed USB
12 Mbit/s for full speed USB
480 Mbit/s for high speed USB (added for USB 2.0)
5000 Mbit/s for SuperSpeed USB (added for USB 3.0)
======= ======================================================
For reasons lost in the mists of time, the Port number is always
too low by 1. For example, a device plugged into port 4 will
show up with ``Port=03``.
Bandwidth `B:` line format
789-811`B:` line은 `Alloc=used/reserved us (percentage)`, interrupt request 수 `#Int`, isochronous request 수 `#Iso`를 표시합니다.
Bandwidth allocation은 1 frame, 즉 1 millisecond 중 사용 중인 시간의 근사치입니다. Bandwidth를 예약하는 periodic interrupt·isochronous transfer만 반영합니다.
Control과 bulk transfer는 예약되지 않은 bandwidth와 short packet 등으로 예약됐지만 사용되지 않는 bandwidth를 모두 활용합니다.
Percentage는 periodic transfer가 reserved bandwidth 중 schedule한 비율입니다. Low·full speed bus에서는 전체의 90%, high speed bus에서는 80%가 reserved bandwidth입니다.
Bandwidth info
^^^^^^^^^^^^^^
::
B: Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
| | | |__Number of isochronous requests
| | |__Number of interrupt requests
| |__Total Bandwidth allocated to this bus
|__Bandwidth info tag
Bandwidth allocation is an approximation of how much of one frame
(millisecond) is in use. It reflects only periodic transfers, which
are the only transfers that reserve bandwidth. Control and bulk
transfers use all other bandwidth, including reserved bandwidth that
is not used for transfers (such as for short packets).
The percentage is how much of the "reserved" bandwidth is scheduled by
those transfers. For a low or full speed bus (loosely, "USB 1.1"),
90% of the bus bandwidth is reserved. For a high speed bus (loosely,
"USB 2.0") 80% is reserved.
Device `D:`와 Product `P:` line
812-839`D:` line은 device USB version `Ver`, device class와 text `Cls`, subclass `Sub`, protocol `Prot`, default endpoint maximum packet size `MxPS`, configuration 수 `#Cfgs`를 표시합니다.
`P:` line은 vendor ID `Vendor`, product ID `ProdID`, product revision `Rev`를 hexadecimal·BCD-style text로 표시합니다.
Device descriptor info & Product ID info
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
D: Ver=x.xx Cls=xx(s) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
where::
D: Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
| | | | | | |__NumberConfigurations
| | | | | |__MaxPacketSize of Default Endpoint
| | | | |__DeviceProtocol
| | | |__DeviceSubClass
| | |__DeviceClass
| |__Device USB version
|__Device info tag #1
where::
P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
| | | |__Product revision number
| | |__Product ID code
| |__Vendor ID code
|__Device info tag #2
String descriptor `S:` line
840-866`S: Manufacturer`는 device에서 읽은 manufacturer string입니다. Virtual root hub에서는 생략될 수 있고 newer HCD는 kernel version과 hub emulation driver를 표시할 수 있습니다.
`S: Product`는 device product description입니다. Older virtual root hub에서는 driver name, newer implementation에서는 kernel PCI ID database에서 온 product·vendor description을 표시하는 경우가 많습니다.
`S: SerialNumber`는 device serial number입니다. Virtual root hub에서는 다른 device와 공유할 수 없는 bus ID, address 또는 slot name 같은 unique identifier를 사용합니다.
String descriptor info
^^^^^^^^^^^^^^^^^^^^^^
::
S: Manufacturer=ssss
| |__Manufacturer of this device as read from the device.
| For USB host controller drivers (virtual root hubs) this may
| be omitted, or (for newer drivers) will identify the kernel
| version and the driver which provides this hub emulation.
|__String info tag
S: Product=ssss
| |__Product description of this device as read from the device.
| For older USB host controller drivers (virtual root hubs) this
| indicates the driver; for newer ones, it's a product (and vendor)
| description that often comes from the kernel's PCI ID database.
|__String info tag
S: SerialNumber=ssss
| |__Serial Number of this device as read from the device.
| For USB host controller drivers (virtual root hubs) this is
| some unique ID, normally a bus ID (address or slot name) that
| can't be shared with any other device.
|__String info tag
Configuration `C:` line
867-890`C:` line에서 `*`는 active configuration을 뜻합니다. `#Ifs`는 interface 수, `Cfg#`는 configuration number, `Atr`는 attribute, `MPwr`는 milliampere 단위 maximum power입니다.
USB device는 동작이 크게 다른 여러 configuration을 가질 수 있습니다. 예를 들어 bus-powered configuration은 self-powered configuration보다 기능이 적을 수 있습니다. 한 번에 configuration 하나만 active이며 대부분 device는 하나만 가집니다.
각 configuration에는 interface가 하나 이상 있고 각 interface는 독립 function을 제공하며 보통 서로 다른 USB driver에 bind됩니다. 예를 들어 USB speaker는 playback용 audio interface와 software volume control용 HID interface를 함께 가질 수 있습니다.
Configuration descriptor info
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
| | | | | |__MaxPower in mA
| | | | |__Attributes
| | | |__ConfiguratioNumber
| | |__NumberOfInterfaces
| |__ "*" indicates the active configuration (others are " ")
|__Config info tag
USB devices may have multiple configurations, each of which act
rather differently. For example, a bus-powered configuration
might be much less capable than one that is self-powered. Only
one device configuration can be active at a time; most devices
have only one configuration.
Each configuration consists of one or more interfaces. Each
interface serves a distinct "function", which is typically bound
to a different USB device driver. One common example is a USB
speaker with an audio interface for playback, and a HID interface
for use with software volume control.
Interface `I:` line
891-916`I:` line에서 `*`는 active alternate setting입니다. `If#`는 interface number, `Alt`는 alternate setting number, `#EPs`는 endpoint 수, `Cls`·`Sub`·`Prot`는 interface class·subclass·protocol, `Driver`는 bind된 driver name 또는 `(none)`입니다.
Interface에는 alternate setting이 하나 이상 있을 수 있습니다. Default setting은 적은 periodic bandwidth만 쓰고, bus bandwidth의 큰 비율을 사용하려면 driver가 non-default altsetting을 선택하는 방식이 일반적입니다.
한 interface에서는 한 번에 setting 하나만 active이고 driver 하나만 bind할 수 있습니다. 대부분 device는 interface마다 alternate setting 하나만 가집니다.
Interface descriptor info (can be multiple per Config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
I:* If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
| | | | | | | | |__Driver name
| | | | | | | | or "(none)"
| | | | | | | |__InterfaceProtocol
| | | | | | |__InterfaceSubClass
| | | | | |__InterfaceClass
| | | | |__NumberOfEndpoints
| | | |__AlternateSettingNumber
| | |__InterfaceNumber
| |__ "*" indicates the active altsetting (others are " ")
|__Interface info tag
A given interface may have one or more "alternate" settings.
For example, default settings may not use more than a small
amount of periodic bandwidth. To use significant fractions
of bus bandwidth, drivers must select a non-default altsetting.
Only one setting for an interface may be active at a time, and
only one driver may bind to an interface at a time. Most devices
have only one alternate setting per interface.
Endpoint `E:` line
917-941`E:` line의 `Ad`는 endpoint address와 IN·OUT direction, `Atr`는 endpoint type attribute, `MxPS`는 maximum packet size, `Ivl`은 transfer 사이 maximum interval입니다.
Interrupt·isochronous periodic endpoint에서는 interval이 항상 0이 아닙니다. High-speed endpoint의 interval은 millisecond가 아니라 microsecond로 표현될 수 있습니다.
High-speed periodic endpoint의 `EndpointMaxPacketSize`는 microframe당 data size입니다. High-bandwidth endpoint에서는 두세 packet을 합쳐 endpoint마다 최대 3 KByte를 125 microsecond마다 전송할 수 있습니다.
Linux USB stack의 periodic bandwidth reservation은 endpoint descriptor 값이 아니라 URB가 제공한 transfer interval과 size를 사용하며, URB 값은 descriptor보다 작을 수 있습니다.
Endpoint descriptor info (can be multiple per Interface)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddss
| | | | |__Interval (max) between transfers
| | | |__EndpointMaxPacketSize
| | |__Attributes(EndpointType)
| |__EndpointAddress(I=In,O=Out)
|__Endpoint info tag
The interval is nonzero for all periodic (interrupt or isochronous)
endpoints. For high speed endpoints the transfer interval may be
measured in microseconds rather than milliseconds.
For high speed periodic endpoints, the ``EndpointMaxPacketSize`` reflects
the per-microframe data transfer size. For "high bandwidth"
endpoints, that can reflect two or three packets (for up to
3KBytes every 125 usec) per endpoint.
With the Linux-USB stack, periodic bandwidth reservations use the
transfer intervals and sizes provided by URBs, which can be less
than those found in endpoint descriptor.
Debugfs filtering과 실제 device 예제
942-1024Topology line만 필요하면 `grep ^T: /sys/kernel/debug/usb/devices`, T·D·P 같은 선택 tag만 필요하면 `grep -i ^[tdp]: ...`를 사용할 수 있습니다. Valid tag는 `TDPCIE`이며 `procusb` Perl script는 `TBDPSCIE`에서 고른 line 또는 전체 line을 출력하는 초기 예입니다.
Topology line으로 root hub 아래 USB device의 graphic topology를 만들 수 있습니다. Interface line은 device별 driver와 active altsetting, Configuration line은 전체 USB device의 maximum power 합계를 분석하는 데 쓸 수 있습니다. Power line만 보려면 `grep ^C:`를 사용합니다.
예제 system에는 UHCI root hub, root hub에 연결된 external four-port hub, external hub에 연결된 mouse와 serial converter가 있습니다.
Dev#1 root hub는 12 Mbit/s, port 2개, periodic bandwidth 28/900 microsecond(3%), interrupt request 2개입니다. Dev#2는 12 Mbit/s four-port hub입니다.
Dev#3은 1.5 Mbit/s HID mouse로 interrupt IN endpoint 하나를 사용합니다. Dev#4는 12 Mbit/s USB-to-serial converter로 bulk IN·OUT endpoint와 interrupt IN endpoint를 사용합니다.
`T:`와 `I:` line만 고르면 각 topology node 다음에 해당 interface driver가 나타나 hub·mouse·serial binding을 간결하게 확인할 수 있습니다.
Usage examples
~~~~~~~~~~~~~~
If a user or script is interested only in Topology info, for
example, use something like ``grep ^T: /sys/kernel/debug/usb/devices``
for only the Topology lines. A command like
``grep -i ^[tdp]: /sys/kernel/debug/usb/devices`` can be used to list
only the lines that begin with the characters in square brackets,
where the valid characters are TDPCIE. With a slightly more able
script, it can display any selected lines (for example, only T, D,
and P lines) and change their output format. (The ``procusb``
Perl script is the beginning of this idea. It will list only
selected lines [selected from TBDPSCIE] or "All" lines from
``/sys/kernel/debug/usb/devices``.)
The Topology lines can be used to generate a graphic/pictorial
of the USB devices on a system's root hub. (See more below
on how to do this.)
The Interface lines can be used to determine what driver is
being used for each device, and which altsetting it activated.
The Configuration lines could be used to list maximum power
(in milliamps) that a system's USB devices are using.
For example, ``grep ^C: /sys/kernel/debug/usb/devices``.
Here's an example, from a system which has a UHCI root hub,
an external hub connected to the root hub, and a mouse and
a serial converter connected to the external hub.
::
T: Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#= 1 Spd=12 MxCh= 2
B: Alloc= 28/900 us ( 3%), #Int= 2, #Iso= 0
D: Ver= 1.00 Cls=09(hub ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=0000 ProdID=0000 Rev= 0.00
S: Product=USB UHCI Root Hub
S: SerialNumber=dce0
C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr= 0mA
I: If#= 0 Alt= 0 #EPs= 1 Cls=09(hub ) Sub=00 Prot=00 Driver=hub
E: Ad=81(I) Atr=03(Int.) MxPS= 8 Ivl=255ms
T: Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#= 2 Spd=12 MxCh= 4
D: Ver= 1.00 Cls=09(hub ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=0451 ProdID=1446 Rev= 1.00
C:* #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=100mA
I: If#= 0 Alt= 0 #EPs= 1 Cls=09(hub ) Sub=00 Prot=00 Driver=hub
E: Ad=81(I) Atr=03(Int.) MxPS= 1 Ivl=255ms
T: Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#= 3 Spd=1.5 MxCh= 0
D: Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=04b4 ProdID=0001 Rev= 0.00
C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
I: If#= 0 Alt= 0 #EPs= 1 Cls=03(HID ) Sub=01 Prot=02 Driver=mouse
E: Ad=81(I) Atr=03(Int.) MxPS= 3 Ivl= 10ms
T: Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#= 4 Spd=12 MxCh= 0
D: Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
P: Vendor=0565 ProdID=0001 Rev= 1.08
S: Manufacturer=Peracom Networks, Inc.
S: Product=Peracom USB to Serial Converter
C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=100mA
I: If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
E: Ad=81(I) Atr=02(Bulk) MxPS= 64 Ivl= 16ms
E: Ad=01(O) Atr=02(Bulk) MxPS= 16 Ivl= 16ms
E: Ad=82(I) Atr=03(Int.) MxPS= 8 Ivl= 8ms
Selecting only the ``T:`` and ``I:`` lines from this (for example, by using
``procusb ti``), we have
::
T: Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#= 1 Spd=12 MxCh= 2
T: Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#= 2 Spd=12 MxCh= 4
I: If#= 0 Alt= 0 #EPs= 1 Cls=09(hub ) Sub=00 Prot=00 Driver=hub
T: Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#= 3 Spd=1.5 MxCh= 0
I: If#= 0 Alt= 0 #EPs= 1 Cls=03(HID ) Sub=01 Prot=02 Driver=mouse
T: Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#= 4 Spd=12 MxCh= 0
I: If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
예제 ASCII topology 재구성
1025-1057원문 graphic은 level 0의 PC root hub Dev#1에서 connector 0으로 level 1의 four-port hub Dev#2가 연결되고, 그 hub의 connector 0과 2에 level 2 mouse Dev#3과 serial converter Dev#4가 연결된 구조입니다.
Root hub의 connector 1과 external hub의 connector 1·3은 비어 있습니다. Graphic의 괄호 숫자는 Mbit/s이고 `CN`은 connector 또는 port number를 뜻합니다.
같은 topology를 tree text로 쓰면 PC Dev#1 아래 CN.0에 Dev#2 hub가 있고, Dev#2 CN.0에는 mouse, CN.2에는 serial device가 있습니다. 연결 없는 port는 생략할 수도 있습니다.
원문의 두 ASCII 그림을 동일한 parent·port·speed 관계로 재구성했습니다.
Physically this looks like (or could be converted to)::
+------------------+
| PC/root_hub (12)| Dev# = 1
+------------------+ (nn) is Mbps.
Level 0 | CN.0 | CN.1 | [CN = connector/port #]
+------------------+
/
/
+-----------------------+
Level 1 | Dev#2: 4-port hub (12)|
+-----------------------+
|CN.0 |CN.1 |CN.2 |CN.3 |
+-----------------------+
\ \____________________
\_____ \
\ \
+--------------------+ +--------------------+
Level 2 | Dev# 3: mouse (1.5)| | Dev# 4: serial (12)|
+--------------------+ +--------------------+
Or, in a more tree-like structure (ports [Connectors] without
connections could be omitted)::
PC: Dev# 1, root hub, 2 ports, 12 Mbps
|_ CN.0: Dev# 2, hub, 4 ports, 12 Mbps
|_ CN.0: Dev #3, mouse, 1.5 Mbps
|_ CN.1:
|_ CN.2: Dev #4, serial, 12 Mbps
|_ CN.3:
|_ CN.1:
요약·해설
usb.rst:1-1057Linux USB 호스트 측 API는 인터페이스 드라이버와 HCD 사이의 usbcore 모델, URB·동기 I/O, 사용자 공간 usbfs ioctl, debugfs 토폴로지를 한 문서에 연결합니다. 장치 경로는 불안정하므로 descriptor와 stable identity를 확인하고 endpoint·altsetting·bandwidth·disconnect 규칙을 지켜야 합니다.