Back to home page

OSCL-LXR

 
 

    


0001 .. _usb-hostside-api:
0002 
0003 ===========================
0004 The Linux-USB Host Side API
0005 ===========================
0006 
0007 Introduction to USB on Linux
0008 ============================
0009 
0010 A Universal Serial Bus (USB) is used to connect a host, such as a PC or
0011 workstation, to a number of peripheral devices. USB uses a tree
0012 structure, with the host as the root (the system's master), hubs as
0013 interior nodes, and peripherals as leaves (and slaves). Modern PCs
0014 support several such trees of USB devices, usually
0015 a few USB 3.0 (5 GBit/s) or USB 3.1 (10 GBit/s) and some legacy
0016 USB 2.0 (480 MBit/s) busses just in case.
0017 
0018 That master/slave asymmetry was designed-in for a number of reasons, one
0019 being ease of use. It is not physically possible to mistake upstream and
0020 downstream or it does not matter with a type C plug (or they are built into the
0021 peripheral). Also, the host software doesn't need to deal with
0022 distributed auto-configuration since the pre-designated master node
0023 manages all that.
0024 
0025 Kernel developers added USB support to Linux early in the 2.2 kernel
0026 series and have been developing it further since then. Besides support
0027 for each new generation of USB, various host controllers gained support,
0028 new drivers for peripherals have been added and advanced features for latency
0029 measurement and improved power management introduced.
0030 
0031 Linux can run inside USB devices as well as on the hosts that control
0032 the devices. But USB device drivers running inside those peripherals
0033 don't do the same things as the ones running inside hosts, so they've
0034 been given a different name: *gadget drivers*. This document does not
0035 cover gadget drivers.
0036 
0037 USB Host-Side API Model
0038 =======================
0039 
0040 Host-side drivers for USB devices talk to the "usbcore" APIs. There are
0041 two. One is intended for *general-purpose* drivers (exposed through
0042 driver frameworks), and the other is for drivers that are *part of the
0043 core*. Such core drivers include the *hub* driver (which manages trees
0044 of USB devices) and several different kinds of *host controller
0045 drivers*, which control individual busses.
0046 
0047 The device model seen by USB drivers is relatively complex.
0048 
0049 -  USB supports four kinds of data transfers (control, bulk, interrupt,
0050    and isochronous). Two of them (control and bulk) use bandwidth as
0051    it's available, while the other two (interrupt and isochronous) are
0052    scheduled to provide guaranteed bandwidth.
0053 
0054 -  The device description model includes one or more "configurations"
0055    per device, only one of which is active at a time. Devices are supposed
0056    to be capable of operating at lower than their top
0057    speeds and may provide a BOS descriptor showing the lowest speed they
0058    remain fully operational at.
0059 
0060 -  From USB 3.0 on configurations have one or more "functions", which
0061    provide a common functionality and are grouped together for purposes
0062    of power management.
0063 
0064 -  Configurations or functions have one or more "interfaces", each of which may have
0065    "alternate settings". Interfaces may be standardized by USB "Class"
0066    specifications, or may be specific to a vendor or device.
0067 
0068    USB device drivers actually bind to interfaces, not devices. Think of
0069    them as "interface drivers", though you may not see many devices
0070    where the distinction is important. *Most USB devices are simple,
0071    with only one function, one configuration, one interface, and one alternate
0072    setting.*
0073 
0074 -  Interfaces have one or more "endpoints", each of which supports one
0075    type and direction of data transfer such as "bulk out" or "interrupt
0076    in". The entire configuration may have up to sixteen endpoints in
0077    each direction, allocated as needed among all the interfaces.
0078 
0079 -  Data transfer on USB is packetized; each endpoint has a maximum
0080    packet size. Drivers must often be aware of conventions such as
0081    flagging the end of bulk transfers using "short" (including zero
0082    length) packets.
0083 
0084 -  The Linux USB API supports synchronous calls for control and bulk
0085    messages. It also supports asynchronous calls for all kinds of data
0086    transfer, using request structures called "URBs" (USB Request
0087    Blocks).
0088 
0089 Accordingly, the USB Core API exposed to device drivers covers quite a
0090 lot of territory. You'll probably need to consult the USB 3.0
0091 specification, available online from www.usb.org at no cost, as well as
0092 class or device specifications.
0093 
0094 The only host-side drivers that actually touch hardware (reading/writing
0095 registers, handling IRQs, and so on) are the HCDs. In theory, all HCDs
0096 provide the same functionality through the same API. In practice, that's
0097 becoming more true, but there are still differences
0098 that crop up especially with fault handling on the less common controllers.
0099 Different controllers don't
0100 necessarily report the same aspects of failures, and recovery from
0101 faults (including software-induced ones like unlinking an URB) isn't yet
0102 fully consistent. Device driver authors should make a point of doing
0103 disconnect testing (while the device is active) with each different host
0104 controller driver, to make sure drivers don't have bugs of their own as
0105 well as to make sure they aren't relying on some HCD-specific behavior.
0106 
0107 .. _usb_chapter9:
0108 
0109 USB-Standard Types
0110 ==================
0111 
0112 In ``include/uapi/linux/usb/ch9.h`` you will find the USB data types defined
0113 in chapter 9 of the USB specification. These data types are used throughout
0114 USB, and in APIs including this host side API, gadget APIs, usb character
0115 devices and debugfs interfaces. That file is itself included by
0116 ``include/linux/usb/ch9.h``, which also contains declarations of a few
0117 utility routines for manipulating these data types; the implementations
0118 are in ``drivers/usb/common/common.c``.
0119 
0120 .. kernel-doc:: drivers/usb/common/common.c
0121    :export:
0122 
0123 In addition, some functions useful for creating debugging output are
0124 defined in ``drivers/usb/common/debug.c``.
0125 
0126 .. _usb_header:
0127 
0128 Host-Side Data Types and Macros
0129 ===============================
0130 
0131 The host side API exposes several layers to drivers, some of which are
0132 more necessary than others. These support lifecycle models for host side
0133 drivers and devices, and support passing buffers through usbcore to some
0134 HCD that performs the I/O for the device driver.
0135 
0136 .. kernel-doc:: include/linux/usb.h
0137    :internal:
0138 
0139 USB Core APIs
0140 =============
0141 
0142 There are two basic I/O models in the USB API. The most elemental one is
0143 asynchronous: drivers submit requests in the form of an URB, and the
0144 URB's completion callback handles the next step. All USB transfer types
0145 support that model, although there are special cases for control URBs
0146 (which always have setup and status stages, but may not have a data
0147 stage) and isochronous URBs (which allow large packets and include
0148 per-packet fault reports). Built on top of that is synchronous API
0149 support, where a driver calls a routine that allocates one or more URBs,
0150 submits them, and waits until they complete. There are synchronous
0151 wrappers for single-buffer control and bulk transfers (which are awkward
0152 to use in some driver disconnect scenarios), and for scatterlist based
0153 streaming i/o (bulk or interrupt).
0154 
0155 USB drivers need to provide buffers that can be used for DMA, although
0156 they don't necessarily need to provide the DMA mapping themselves. There
0157 are APIs to use used when allocating DMA buffers, which can prevent use
0158 of bounce buffers on some systems. In some cases, drivers may be able to
0159 rely on 64bit DMA to eliminate another kind of bounce buffer.
0160 
0161 .. kernel-doc:: drivers/usb/core/urb.c
0162    :export:
0163 
0164 .. kernel-doc:: drivers/usb/core/message.c
0165    :export:
0166 
0167 .. kernel-doc:: drivers/usb/core/file.c
0168    :export:
0169 
0170 .. kernel-doc:: drivers/usb/core/driver.c
0171    :export:
0172 
0173 .. kernel-doc:: drivers/usb/core/usb.c
0174    :export:
0175 
0176 .. kernel-doc:: drivers/usb/core/hub.c
0177    :export:
0178 
0179 Host Controller APIs
0180 ====================
0181 
0182 These APIs are only for use by host controller drivers, most of which
0183 implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI
0184 was one of the first interfaces, designed by Intel and also used by VIA;
0185 it doesn't do much in hardware. OHCI was designed later, to have the
0186 hardware do more work (bigger transfers, tracking protocol state, and so
0187 on). EHCI was designed with USB 2.0; its design has features that
0188 resemble OHCI (hardware does much more work) as well as UHCI (some parts
0189 of ISO support, TD list processing). XHCI was designed with USB 3.0. It
0190 continues to shift support for functionality into hardware.
0191 
0192 There are host controllers other than the "big three", although most PCI
0193 based controllers (and a few non-PCI based ones) use one of those
0194 interfaces. Not all host controllers use DMA; some use PIO, and there is
0195 also a simulator and a virtual host controller to pipe USB over the network.
0196 
0197 The same basic APIs are available to drivers for all those controllers.
0198 For historical reasons they are in two layers: :c:type:`struct
0199 usb_bus <usb_bus>` is a rather thin layer that became available
0200 in the 2.2 kernels, while :c:type:`struct usb_hcd <usb_hcd>`
0201 is a more featureful layer
0202 that lets HCDs share common code, to shrink driver size and
0203 significantly reduce hcd-specific behaviors.
0204 
0205 .. kernel-doc:: drivers/usb/core/hcd.c
0206    :export:
0207 
0208 .. kernel-doc:: drivers/usb/core/hcd-pci.c
0209    :export:
0210 
0211 .. kernel-doc:: drivers/usb/core/buffer.c
0212    :internal:
0213 
0214 The USB character device nodes
0215 ==============================
0216 
0217 This chapter presents the Linux character device nodes. You may prefer
0218 to avoid writing new kernel code for your USB driver. User mode device
0219 drivers are usually packaged as applications or libraries, and may use
0220 character devices through some programming library that wraps it.
0221 Such libraries include:
0222 
0223  - `libusb <http://libusb.sourceforge.net>`__ for C/C++, and
0224  - `jUSB <http://jUSB.sourceforge.net>`__ for Java.
0225 
0226 Some old information about it can be seen at the "USB Device Filesystem"
0227 section of the USB Guide. The latest copy of the USB Guide can be found
0228 at http://www.linux-usb.org/
0229 
0230 .. note::
0231 
0232   - They were used to be implemented via *usbfs*, but this is not part of
0233     the sysfs debug interface.
0234 
0235    - This particular documentation is incomplete, especially with respect
0236      to the asynchronous mode. As of kernel 2.5.66 the code and this
0237      (new) documentation need to be cross-reviewed.
0238 
0239 What files are in "devtmpfs"?
0240 -----------------------------
0241 
0242 Conventionally mounted at ``/dev/bus/usb/``, usbfs features include:
0243 
0244 -  ``/dev/bus/usb/BBB/DDD`` ... magic files exposing the each device's
0245    configuration descriptors, and supporting a series of ioctls for
0246    making device requests, including I/O to devices. (Purely for access
0247    by programs.)
0248 
0249 Each bus is given a number (``BBB``) based on when it was enumerated; within
0250 each bus, each device is given a similar number (``DDD``). Those ``BBB/DDD``
0251 paths are not "stable" identifiers; expect them to change even if you
0252 always leave the devices plugged in to the same hub port. *Don't even
0253 think of saving these in application configuration files.* Stable
0254 identifiers are available, for user mode applications that want to use
0255 them. HID and networking devices expose these stable IDs, so that for
0256 example you can be sure that you told the right UPS to power down its
0257 second server. Pleast note that it doesn't (yet) expose those IDs.
0258 
0259 /dev/bus/usb/BBB/DDD
0260 --------------------
0261 
0262 Use these files in one of these basic ways:
0263 
0264 - *They can be read,* producing first the device descriptor (18 bytes) and
0265   then the descriptors for the current configuration. See the USB 2.0 spec
0266   for details about those binary data formats. You'll need to convert most
0267   multibyte values from little endian format to your native host byte
0268   order, although a few of the fields in the device descriptor (both of
0269   the BCD-encoded fields, and the vendor and product IDs) will be
0270   byteswapped for you. Note that configuration descriptors include
0271   descriptors for interfaces, altsettings, endpoints, and maybe additional
0272   class descriptors.
0273 
0274 - *Perform USB operations* using *ioctl()* requests to make endpoint I/O
0275   requests (synchronously or asynchronously) or manage the device. These
0276   requests need the ``CAP_SYS_RAWIO`` capability, as well as filesystem
0277   access permissions. Only one ioctl request can be made on one of these
0278   device files at a time. This means that if you are synchronously reading
0279   an endpoint from one thread, you won't be able to write to a different
0280   endpoint from another thread until the read completes. This works for
0281   *half duplex* protocols, but otherwise you'd use asynchronous i/o
0282   requests.
0283 
0284 Each connected USB device has one file.  The ``BBB`` indicates the bus
0285 number.  The ``DDD`` indicates the device address on that bus.  Both
0286 of these numbers are assigned sequentially, and can be reused, so
0287 you can't rely on them for stable access to devices.  For example,
0288 it's relatively common for devices to re-enumerate while they are
0289 still connected (perhaps someone jostled their power supply, hub,
0290 or USB cable), so a device might be ``002/027`` when you first connect
0291 it and ``002/048`` sometime later.
0292 
0293 These files can be read as binary data.  The binary data consists
0294 of first the device descriptor, then the descriptors for each
0295 configuration of the device.  Multi-byte fields in the device descriptor
0296 are converted to host endianness by the kernel.  The configuration
0297 descriptors are in bus endian format! The configuration descriptor
0298 are wTotalLength bytes apart. If a device returns less configuration
0299 descriptor data than indicated by wTotalLength there will be a hole in
0300 the file for the missing bytes.  This information is also shown
0301 in text form by the ``/sys/kernel/debug/usb/devices`` file, described later.
0302 
0303 These files may also be used to write user-level drivers for the USB
0304 devices.  You would open the ``/dev/bus/usb/BBB/DDD`` file read/write,
0305 read its descriptors to make sure it's the device you expect, and then
0306 bind to an interface (or perhaps several) using an ioctl call.  You
0307 would issue more ioctls to the device to communicate to it using
0308 control, bulk, or other kinds of USB transfers.  The IOCTLs are
0309 listed in the ``<linux/usbdevice_fs.h>`` file, and at this writing the
0310 source code (``linux/drivers/usb/core/devio.c``) is the primary reference
0311 for how to access devices through those files.
0312 
0313 Note that since by default these ``BBB/DDD`` files are writable only by
0314 root, only root can write such user mode drivers.  You can selectively
0315 grant read/write permissions to other users by using ``chmod``.  Also,
0316 usbfs mount options such as ``devmode=0666`` may be helpful.
0317 
0318 
0319 Life Cycle of User Mode Drivers
0320 -------------------------------
0321 
0322 Such a driver first needs to find a device file for a device it knows
0323 how to handle. Maybe it was told about it because a ``/sbin/hotplug``
0324 event handling agent chose that driver to handle the new device. Or
0325 maybe it's an application that scans all the ``/dev/bus/usb`` device files,
0326 and ignores most devices. In either case, it should :c:func:`read()`
0327 all the descriptors from the device file, and check them against what it
0328 knows how to handle. It might just reject everything except a particular
0329 vendor and product ID, or need a more complex policy.
0330 
0331 Never assume there will only be one such device on the system at a time!
0332 If your code can't handle more than one device at a time, at least
0333 detect when there's more than one, and have your users choose which
0334 device to use.
0335 
0336 Once your user mode driver knows what device to use, it interacts with
0337 it in either of two styles. The simple style is to make only control
0338 requests; some devices don't need more complex interactions than those.
0339 (An example might be software using vendor-specific control requests for
0340 some initialization or configuration tasks, with a kernel driver for the
0341 rest.)
0342 
0343 More likely, you need a more complex style driver: one using non-control
0344 endpoints, reading or writing data and claiming exclusive use of an
0345 interface. *Bulk* transfers are easiest to use, but only their sibling
0346 *interrupt* transfers work with low speed devices. Both interrupt and
0347 *isochronous* transfers offer service guarantees because their bandwidth
0348 is reserved. Such "periodic" transfers are awkward to use through usbfs,
0349 unless you're using the asynchronous calls. However, interrupt transfers
0350 can also be used in a synchronous "one shot" style.
0351 
0352 Your user-mode driver should never need to worry about cleaning up
0353 request state when the device is disconnected, although it should close
0354 its open file descriptors as soon as it starts seeing the ENODEV errors.
0355 
0356 The ioctl() Requests
0357 --------------------
0358 
0359 To use these ioctls, you need to include the following headers in your
0360 userspace program::
0361 
0362     #include <linux/usb.h>
0363     #include <linux/usbdevice_fs.h>
0364     #include <asm/byteorder.h>
0365 
0366 The standard USB device model requests, from "Chapter 9" of the USB 2.0
0367 specification, are automatically included from the ``<linux/usb/ch9.h>``
0368 header.
0369 
0370 Unless noted otherwise, the ioctl requests described here will update
0371 the modification time on the usbfs file to which they are applied
0372 (unless they fail). A return of zero indicates success; otherwise, a
0373 standard USB error code is returned (These are documented in
0374 :ref:`usb-error-codes`).
0375 
0376 Each of these files multiplexes access to several I/O streams, one per
0377 endpoint. Each device has one control endpoint (endpoint zero) which
0378 supports a limited RPC style RPC access. Devices are configured by
0379 hub_wq (in the kernel) setting a device-wide *configuration* that
0380 affects things like power consumption and basic functionality. The
0381 endpoints are part of USB *interfaces*, which may have *altsettings*
0382 affecting things like which endpoints are available. Many devices only
0383 have a single configuration and interface, so drivers for them will
0384 ignore configurations and altsettings.
0385 
0386 Management/Status Requests
0387 ~~~~~~~~~~~~~~~~~~~~~~~~~~
0388 
0389 A number of usbfs requests don't deal very directly with device I/O.
0390 They mostly relate to device management and status. These are all
0391 synchronous requests.
0392 
0393 USBDEVFS_CLAIMINTERFACE
0394     This is used to force usbfs to claim a specific interface, which has
0395     not previously been claimed by usbfs or any other kernel driver. The
0396     ioctl parameter is an integer holding the number of the interface
0397     (bInterfaceNumber from descriptor).
0398 
0399     Note that if your driver doesn't claim an interface before trying to
0400     use one of its endpoints, and no other driver has bound to it, then
0401     the interface is automatically claimed by usbfs.
0402 
0403     This claim will be released by a RELEASEINTERFACE ioctl, or by
0404     closing the file descriptor. File modification time is not updated
0405     by this request.
0406 
0407 USBDEVFS_CONNECTINFO
0408     Says whether the device is lowspeed. The ioctl parameter points to a
0409     structure like this::
0410 
0411         struct usbdevfs_connectinfo {
0412                 unsigned int   devnum;
0413                 unsigned char  slow;
0414         };
0415 
0416     File modification time is not updated by this request.
0417 
0418     *You can't tell whether a "not slow" device is connected at high
0419     speed (480 MBit/sec) or just full speed (12 MBit/sec).* You should
0420     know the devnum value already, it's the DDD value of the device file
0421     name.
0422 
0423 USBDEVFS_GETDRIVER
0424     Returns the name of the kernel driver bound to a given interface (a
0425     string). Parameter is a pointer to this structure, which is
0426     modified::
0427 
0428         struct usbdevfs_getdriver {
0429                 unsigned int  interface;
0430                 char          driver[USBDEVFS_MAXDRIVERNAME + 1];
0431         };
0432 
0433     File modification time is not updated by this request.
0434 
0435 USBDEVFS_IOCTL
0436     Passes a request from userspace through to a kernel driver that has
0437     an ioctl entry in the *struct usb_driver* it registered::
0438 
0439         struct usbdevfs_ioctl {
0440                 int     ifno;
0441                 int     ioctl_code;
0442                 void    *data;
0443         };
0444 
0445         /* user mode call looks like this.
0446          * 'request' becomes the driver->ioctl() 'code' parameter.
0447          * the size of 'param' is encoded in 'request', and that data
0448          * is copied to or from the driver->ioctl() 'buf' parameter.
0449          */
0450         static int
0451         usbdev_ioctl (int fd, int ifno, unsigned request, void *param)
0452         {
0453                 struct usbdevfs_ioctl   wrapper;
0454 
0455                 wrapper.ifno = ifno;
0456                 wrapper.ioctl_code = request;
0457                 wrapper.data = param;
0458 
0459                 return ioctl (fd, USBDEVFS_IOCTL, &wrapper);
0460         }
0461 
0462     File modification time is not updated by this request.
0463 
0464     This request lets kernel drivers talk to user mode code through
0465     filesystem operations even when they don't create a character or
0466     block special device. It's also been used to do things like ask
0467     devices what device special file should be used. Two pre-defined
0468     ioctls are used to disconnect and reconnect kernel drivers, so that
0469     user mode code can completely manage binding and configuration of
0470     devices.
0471 
0472 USBDEVFS_RELEASEINTERFACE
0473     This is used to release the claim usbfs made on interface, either
0474     implicitly or because of a USBDEVFS_CLAIMINTERFACE call, before the
0475     file descriptor is closed. The ioctl parameter is an integer holding
0476     the number of the interface (bInterfaceNumber from descriptor); File
0477     modification time is not updated by this request.
0478 
0479     .. warning::
0480 
0481         *No security check is made to ensure that the task which made
0482         the claim is the one which is releasing it. This means that user
0483         mode driver may interfere other ones.*
0484 
0485 USBDEVFS_RESETEP
0486     Resets the data toggle value for an endpoint (bulk or interrupt) to
0487     DATA0. The ioctl parameter is an integer endpoint number (1 to 15,
0488     as identified in the endpoint descriptor), with USB_DIR_IN added
0489     if the device's endpoint sends data to the host.
0490 
0491     .. Warning::
0492 
0493         *Avoid using this request. It should probably be removed.* Using
0494         it typically means the device and driver will lose toggle
0495         synchronization. If you really lost synchronization, you likely
0496         need to completely handshake with the device, using a request
0497         like CLEAR_HALT or SET_INTERFACE.
0498 
0499 USBDEVFS_DROP_PRIVILEGES
0500     This is used to relinquish the ability to do certain operations
0501     which are considered to be privileged on a usbfs file descriptor.
0502     This includes claiming arbitrary interfaces, resetting a device on
0503     which there are currently claimed interfaces from other users, and
0504     issuing USBDEVFS_IOCTL calls. The ioctl parameter is a 32 bit mask
0505     of interfaces the user is allowed to claim on this file descriptor.
0506     You may issue this ioctl more than one time to narrow said mask.
0507 
0508 Synchronous I/O Support
0509 ~~~~~~~~~~~~~~~~~~~~~~~
0510 
0511 Synchronous requests involve the kernel blocking until the user mode
0512 request completes, either by finishing successfully or by reporting an
0513 error. In most cases this is the simplest way to use usbfs, although as
0514 noted above it does prevent performing I/O to more than one endpoint at
0515 a time.
0516 
0517 USBDEVFS_BULK
0518     Issues a bulk read or write request to the device. The ioctl
0519     parameter is a pointer to this structure::
0520 
0521         struct usbdevfs_bulktransfer {
0522                 unsigned int  ep;
0523                 unsigned int  len;
0524                 unsigned int  timeout; /* in milliseconds */
0525                 void          *data;
0526         };
0527 
0528     The ``ep`` value identifies a bulk endpoint number (1 to 15, as
0529     identified in an endpoint descriptor), masked with USB_DIR_IN when
0530     referring to an endpoint which sends data to the host from the
0531     device. The length of the data buffer is identified by ``len``; Recent
0532     kernels support requests up to about 128KBytes. *FIXME say how read
0533     length is returned, and how short reads are handled.*.
0534 
0535 USBDEVFS_CLEAR_HALT
0536     Clears endpoint halt (stall) and resets the endpoint toggle. This is
0537     only meaningful for bulk or interrupt endpoints. The ioctl parameter
0538     is an integer endpoint number (1 to 15, as identified in an endpoint
0539     descriptor), masked with USB_DIR_IN when referring to an endpoint
0540     which sends data to the host from the device.
0541 
0542     Use this on bulk or interrupt endpoints which have stalled,
0543     returning ``-EPIPE`` status to a data transfer request. Do not issue
0544     the control request directly, since that could invalidate the host's
0545     record of the data toggle.
0546 
0547 USBDEVFS_CONTROL
0548     Issues a control request to the device. The ioctl parameter points
0549     to a structure like this::
0550 
0551         struct usbdevfs_ctrltransfer {
0552                 __u8   bRequestType;
0553                 __u8   bRequest;
0554                 __u16  wValue;
0555                 __u16  wIndex;
0556                 __u16  wLength;
0557                 __u32  timeout;  /* in milliseconds */
0558                 void   *data;
0559         };
0560 
0561     The first eight bytes of this structure are the contents of the
0562     SETUP packet to be sent to the device; see the USB 2.0 specification
0563     for details. The bRequestType value is composed by combining a
0564     ``USB_TYPE_*`` value, a ``USB_DIR_*`` value, and a ``USB_RECIP_*``
0565     value (from ``linux/usb.h``). If wLength is nonzero, it describes
0566     the length of the data buffer, which is either written to the device
0567     (USB_DIR_OUT) or read from the device (USB_DIR_IN).
0568 
0569     At this writing, you can't transfer more than 4 KBytes of data to or
0570     from a device; usbfs has a limit, and some host controller drivers
0571     have a limit. (That's not usually a problem.) *Also* there's no way
0572     to say it's not OK to get a short read back from the device.
0573 
0574 USBDEVFS_RESET
0575     Does a USB level device reset. The ioctl parameter is ignored. After
0576     the reset, this rebinds all device interfaces. File modification
0577     time is not updated by this request.
0578 
0579 .. warning::
0580 
0581         *Avoid using this call* until some usbcore bugs get fixed, since
0582         it does not fully synchronize device, interface, and driver (not
0583         just usbfs) state.
0584 
0585 USBDEVFS_SETINTERFACE
0586     Sets the alternate setting for an interface. The ioctl parameter is
0587     a pointer to a structure like this::
0588 
0589         struct usbdevfs_setinterface {
0590                 unsigned int  interface;
0591                 unsigned int  altsetting;
0592         };
0593 
0594     File modification time is not updated by this request.
0595 
0596     Those struct members are from some interface descriptor applying to
0597     the current configuration. The interface number is the
0598     bInterfaceNumber value, and the altsetting number is the
0599     bAlternateSetting value. (This resets each endpoint in the
0600     interface.)
0601 
0602 USBDEVFS_SETCONFIGURATION
0603     Issues the :c:func:`usb_set_configuration()` call for the
0604     device. The parameter is an integer holding the number of a
0605     configuration (bConfigurationValue from descriptor). File
0606     modification time is not updated by this request.
0607 
0608 .. warning::
0609 
0610         *Avoid using this call* until some usbcore bugs get fixed, since
0611         it does not fully synchronize device, interface, and driver (not
0612         just usbfs) state.
0613 
0614 Asynchronous I/O Support
0615 ~~~~~~~~~~~~~~~~~~~~~~~~
0616 
0617 As mentioned above, there are situations where it may be important to
0618 initiate concurrent operations from user mode code. This is particularly
0619 important for periodic transfers (interrupt and isochronous), but it can
0620 be used for other kinds of USB requests too. In such cases, the
0621 asynchronous requests described here are essential. Rather than
0622 submitting one request and having the kernel block until it completes,
0623 the blocking is separate.
0624 
0625 These requests are packaged into a structure that resembles the URB used
0626 by kernel device drivers. (No POSIX Async I/O support here, sorry.) It
0627 identifies the endpoint type (``USBDEVFS_URB_TYPE_*``), endpoint
0628 (number, masked with USB_DIR_IN as appropriate), buffer and length,
0629 and a user "context" value serving to uniquely identify each request.
0630 (It's usually a pointer to per-request data.) Flags can modify requests
0631 (not as many as supported for kernel drivers).
0632 
0633 Each request can specify a realtime signal number (between SIGRTMIN and
0634 SIGRTMAX, inclusive) to request a signal be sent when the request
0635 completes.
0636 
0637 When usbfs returns these urbs, the status value is updated, and the
0638 buffer may have been modified. Except for isochronous transfers, the
0639 actual_length is updated to say how many bytes were transferred; if the
0640 USBDEVFS_URB_DISABLE_SPD flag is set ("short packets are not OK"), if
0641 fewer bytes were read than were requested then you get an error report::
0642 
0643     struct usbdevfs_iso_packet_desc {
0644             unsigned int                     length;
0645             unsigned int                     actual_length;
0646             unsigned int                     status;
0647     };
0648 
0649     struct usbdevfs_urb {
0650             unsigned char                    type;
0651             unsigned char                    endpoint;
0652             int                              status;
0653             unsigned int                     flags;
0654             void                             *buffer;
0655             int                              buffer_length;
0656             int                              actual_length;
0657             int                              start_frame;
0658             int                              number_of_packets;
0659             int                              error_count;
0660             unsigned int                     signr;
0661             void                             *usercontext;
0662             struct usbdevfs_iso_packet_desc  iso_frame_desc[];
0663     };
0664 
0665 For these asynchronous requests, the file modification time reflects
0666 when the request was initiated. This contrasts with their use with the
0667 synchronous requests, where it reflects when requests complete.
0668 
0669 USBDEVFS_DISCARDURB
0670     *TBS* File modification time is not updated by this request.
0671 
0672 USBDEVFS_DISCSIGNAL
0673     *TBS* File modification time is not updated by this request.
0674 
0675 USBDEVFS_REAPURB
0676     *TBS* File modification time is not updated by this request.
0677 
0678 USBDEVFS_REAPURBNDELAY
0679     *TBS* File modification time is not updated by this request.
0680 
0681 USBDEVFS_SUBMITURB
0682     *TBS*
0683 
0684 The USB devices
0685 ===============
0686 
0687 The USB devices are now exported via debugfs:
0688 
0689 -  ``/sys/kernel/debug/usb/devices`` ... a text file showing each of the USB
0690    devices on known to the kernel, and their configuration descriptors.
0691    You can also poll() this to learn about new devices.
0692 
0693 /sys/kernel/debug/usb/devices
0694 -----------------------------
0695 
0696 This file is handy for status viewing tools in user mode, which can scan
0697 the text format and ignore most of it. More detailed device status
0698 (including class and vendor status) is available from device-specific
0699 files. For information about the current format of this file, see below.
0700 
0701 This file, in combination with the poll() system call, can also be used
0702 to detect when devices are added or removed::
0703 
0704     int fd;
0705     struct pollfd pfd;
0706 
0707     fd = open("/sys/kernel/debug/usb/devices", O_RDONLY);
0708     pfd = { fd, POLLIN, 0 };
0709     for (;;) {
0710         /* The first time through, this call will return immediately. */
0711         poll(&pfd, 1, -1);
0712 
0713         /* To see what's changed, compare the file's previous and current
0714            contents or scan the filesystem.  (Scanning is more precise.) */
0715     }
0716 
0717 Note that this behavior is intended to be used for informational and
0718 debug purposes. It would be more appropriate to use programs such as
0719 udev or HAL to initialize a device or start a user-mode helper program,
0720 for instance.
0721 
0722 In this file, each device's output has multiple lines of ASCII output.
0723 
0724 I made it ASCII instead of binary on purpose, so that someone
0725 can obtain some useful data from it without the use of an
0726 auxiliary program.  However, with an auxiliary program, the numbers
0727 in the first 4 columns of each ``T:`` line (topology info:
0728 Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.
0729 
0730 Each line is tagged with a one-character ID for that line::
0731 
0732         T = Topology (etc.)
0733         B = Bandwidth (applies only to USB host controllers, which are
0734         virtualized as root hubs)
0735         D = Device descriptor info.
0736         P = Product ID info. (from Device descriptor, but they won't fit
0737         together on one line)
0738         S = String descriptors.
0739         C = Configuration descriptor info. (* = active configuration)
0740         I = Interface descriptor info.
0741         E = Endpoint descriptor info.
0742 
0743 /sys/kernel/debug/usb/devices output format
0744 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0745 
0746 Legend::
0747   d = decimal number (may have leading spaces or 0's)
0748   x = hexadecimal number (may have leading spaces or 0's)
0749   s = string
0750 
0751 
0752 
0753 Topology info
0754 ^^^^^^^^^^^^^
0755 
0756 ::
0757 
0758         T:  Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=dddd MxCh=dd
0759         |   |      |      |       |       |      |        |        |__MaxChildren
0760         |   |      |      |       |       |      |        |__Device Speed in Mbps
0761         |   |      |      |       |       |      |__DeviceNumber
0762         |   |      |      |       |       |__Count of devices at this level
0763         |   |      |      |       |__Connector/Port on Parent for this device
0764         |   |      |      |__Parent DeviceNumber
0765         |   |      |__Level in topology for this bus
0766         |   |__Bus number
0767         |__Topology info tag
0768 
0769 Speed may be:
0770 
0771         ======= ======================================================
0772         1.5     Mbit/s for low speed USB
0773         12      Mbit/s for full speed USB
0774         480     Mbit/s for high speed USB (added for USB 2.0);
0775                 also used for Wireless USB, which has no fixed speed
0776         5000    Mbit/s for SuperSpeed USB (added for USB 3.0)
0777         ======= ======================================================
0778 
0779 For reasons lost in the mists of time, the Port number is always
0780 too low by 1.  For example, a device plugged into port 4 will
0781 show up with ``Port=03``.
0782 
0783 Bandwidth info
0784 ^^^^^^^^^^^^^^
0785 
0786 ::
0787 
0788         B:  Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
0789         |   |                       |         |__Number of isochronous requests
0790         |   |                       |__Number of interrupt requests
0791         |   |__Total Bandwidth allocated to this bus
0792         |__Bandwidth info tag
0793 
0794 Bandwidth allocation is an approximation of how much of one frame
0795 (millisecond) is in use.  It reflects only periodic transfers, which
0796 are the only transfers that reserve bandwidth.  Control and bulk
0797 transfers use all other bandwidth, including reserved bandwidth that
0798 is not used for transfers (such as for short packets).
0799 
0800 The percentage is how much of the "reserved" bandwidth is scheduled by
0801 those transfers.  For a low or full speed bus (loosely, "USB 1.1"),
0802 90% of the bus bandwidth is reserved.  For a high speed bus (loosely,
0803 "USB 2.0") 80% is reserved.
0804 
0805 
0806 Device descriptor info & Product ID info
0807 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0808 
0809 ::
0810 
0811         D:  Ver=x.xx Cls=xx(s) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
0812         P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx
0813 
0814 where::
0815 
0816         D:  Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
0817         |   |        |             |      |       |       |__NumberConfigurations
0818         |   |        |             |      |       |__MaxPacketSize of Default Endpoint
0819         |   |        |             |      |__DeviceProtocol
0820         |   |        |             |__DeviceSubClass
0821         |   |        |__DeviceClass
0822         |   |__Device USB version
0823         |__Device info tag #1
0824 
0825 where::
0826 
0827         P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx
0828         |   |           |           |__Product revision number
0829         |   |           |__Product ID code
0830         |   |__Vendor ID code
0831         |__Device info tag #2
0832 
0833 
0834 String descriptor info
0835 ^^^^^^^^^^^^^^^^^^^^^^
0836 ::
0837 
0838         S:  Manufacturer=ssss
0839         |   |__Manufacturer of this device as read from the device.
0840         |      For USB host controller drivers (virtual root hubs) this may
0841         |      be omitted, or (for newer drivers) will identify the kernel
0842         |      version and the driver which provides this hub emulation.
0843         |__String info tag
0844 
0845         S:  Product=ssss
0846         |   |__Product description of this device as read from the device.
0847         |      For older USB host controller drivers (virtual root hubs) this
0848         |      indicates the driver; for newer ones, it's a product (and vendor)
0849         |      description that often comes from the kernel's PCI ID database.
0850         |__String info tag
0851 
0852         S:  SerialNumber=ssss
0853         |   |__Serial Number of this device as read from the device.
0854         |      For USB host controller drivers (virtual root hubs) this is
0855         |      some unique ID, normally a bus ID (address or slot name) that
0856         |      can't be shared with any other device.
0857         |__String info tag
0858 
0859 
0860 
0861 Configuration descriptor info
0862 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0863 ::
0864 
0865         C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
0866         | | |       |       |      |__MaxPower in mA
0867         | | |       |       |__Attributes
0868         | | |       |__ConfiguratioNumber
0869         | | |__NumberOfInterfaces
0870         | |__ "*" indicates the active configuration (others are " ")
0871         |__Config info tag
0872 
0873 USB devices may have multiple configurations, each of which act
0874 rather differently.  For example, a bus-powered configuration
0875 might be much less capable than one that is self-powered.  Only
0876 one device configuration can be active at a time; most devices
0877 have only one configuration.
0878 
0879 Each configuration consists of one or more interfaces.  Each
0880 interface serves a distinct "function", which is typically bound
0881 to a different USB device driver.  One common example is a USB
0882 speaker with an audio interface for playback, and a HID interface
0883 for use with software volume control.
0884 
0885 Interface descriptor info (can be multiple per Config)
0886 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0887 ::
0888 
0889         I:* If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
0890         | | |      |      |       |             |      |       |__Driver name
0891         | | |      |      |       |             |      |          or "(none)"
0892         | | |      |      |       |             |      |__InterfaceProtocol
0893         | | |      |      |       |             |__InterfaceSubClass
0894         | | |      |      |       |__InterfaceClass
0895         | | |      |      |__NumberOfEndpoints
0896         | | |      |__AlternateSettingNumber
0897         | | |__InterfaceNumber
0898         | |__ "*" indicates the active altsetting (others are " ")
0899         |__Interface info tag
0900 
0901 A given interface may have one or more "alternate" settings.
0902 For example, default settings may not use more than a small
0903 amount of periodic bandwidth.  To use significant fractions
0904 of bus bandwidth, drivers must select a non-default altsetting.
0905 
0906 Only one setting for an interface may be active at a time, and
0907 only one driver may bind to an interface at a time.  Most devices
0908 have only one alternate setting per interface.
0909 
0910 
0911 Endpoint descriptor info (can be multiple per Interface)
0912 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0913 
0914 ::
0915 
0916         E:  Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddss
0917         |   |        |            |         |__Interval (max) between transfers
0918         |   |        |            |__EndpointMaxPacketSize
0919         |   |        |__Attributes(EndpointType)
0920         |   |__EndpointAddress(I=In,O=Out)
0921         |__Endpoint info tag
0922 
0923 The interval is nonzero for all periodic (interrupt or isochronous)
0924 endpoints.  For high speed endpoints the transfer interval may be
0925 measured in microseconds rather than milliseconds.
0926 
0927 For high speed periodic endpoints, the ``EndpointMaxPacketSize`` reflects
0928 the per-microframe data transfer size.  For "high bandwidth"
0929 endpoints, that can reflect two or three packets (for up to
0930 3KBytes every 125 usec) per endpoint.
0931 
0932 With the Linux-USB stack, periodic bandwidth reservations use the
0933 transfer intervals and sizes provided by URBs, which can be less
0934 than those found in endpoint descriptor.
0935 
0936 Usage examples
0937 ~~~~~~~~~~~~~~
0938 
0939 If a user or script is interested only in Topology info, for
0940 example, use something like ``grep ^T: /sys/kernel/debug/usb/devices``
0941 for only the Topology lines.  A command like
0942 ``grep -i ^[tdp]: /sys/kernel/debug/usb/devices`` can be used to list
0943 only the lines that begin with the characters in square brackets,
0944 where the valid characters are TDPCIE.  With a slightly more able
0945 script, it can display any selected lines (for example, only T, D,
0946 and P lines) and change their output format.  (The ``procusb``
0947 Perl script is the beginning of this idea.  It will list only
0948 selected lines [selected from TBDPSCIE] or "All" lines from
0949 ``/sys/kernel/debug/usb/devices``.)
0950 
0951 The Topology lines can be used to generate a graphic/pictorial
0952 of the USB devices on a system's root hub.  (See more below
0953 on how to do this.)
0954 
0955 The Interface lines can be used to determine what driver is
0956 being used for each device, and which altsetting it activated.
0957 
0958 The Configuration lines could be used to list maximum power
0959 (in milliamps) that a system's USB devices are using.
0960 For example, ``grep ^C: /sys/kernel/debug/usb/devices``.
0961 
0962 
0963 Here's an example, from a system which has a UHCI root hub,
0964 an external hub connected to the root hub, and a mouse and
0965 a serial converter connected to the external hub.
0966 
0967 ::
0968 
0969         T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 2
0970         B:  Alloc= 28/900 us ( 3%), #Int=  2, #Iso=  0
0971         D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
0972         P:  Vendor=0000 ProdID=0000 Rev= 0.00
0973         S:  Product=USB UHCI Root Hub
0974         S:  SerialNumber=dce0
0975         C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr=  0mA
0976         I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
0977         E:  Ad=81(I) Atr=03(Int.) MxPS=   8 Ivl=255ms
0978 
0979         T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 4
0980         D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
0981         P:  Vendor=0451 ProdID=1446 Rev= 1.00
0982         C:* #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=100mA
0983         I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
0984         E:  Ad=81(I) Atr=03(Int.) MxPS=   1 Ivl=255ms
0985 
0986         T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 0
0987         D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
0988         P:  Vendor=04b4 ProdID=0001 Rev= 0.00
0989         C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
0990         I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse
0991         E:  Ad=81(I) Atr=03(Int.) MxPS=   3 Ivl= 10ms
0992 
0993         T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
0994         D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
0995         P:  Vendor=0565 ProdID=0001 Rev= 1.08
0996         S:  Manufacturer=Peracom Networks, Inc.
0997         S:  Product=Peracom USB to Serial Converter
0998         C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=100mA
0999         I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
1000         E:  Ad=81(I) Atr=02(Bulk) MxPS=  64 Ivl= 16ms
1001         E:  Ad=01(O) Atr=02(Bulk) MxPS=  16 Ivl= 16ms
1002         E:  Ad=82(I) Atr=03(Int.) MxPS=   8 Ivl=  8ms
1003 
1004 
1005 Selecting only the ``T:`` and ``I:`` lines from this (for example, by using
1006 ``procusb ti``), we have
1007 
1008 ::
1009 
1010         T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 2
1011         T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 4
1012         I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
1013         T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 0
1014         I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse
1015         T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
1016         I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
1017 
1018 
1019 Physically this looks like (or could be converted to)::
1020 
1021                       +------------------+
1022                       |  PC/root_hub (12)|   Dev# = 1
1023                       +------------------+   (nn) is Mbps.
1024     Level 0           |  CN.0   |  CN.1  |   [CN = connector/port #]
1025                       +------------------+
1026                           /
1027                          /
1028             +-----------------------+
1029   Level 1   | Dev#2: 4-port hub (12)|
1030             +-----------------------+
1031             |CN.0 |CN.1 |CN.2 |CN.3 |
1032             +-----------------------+
1033                 \           \____________________
1034                  \_____                          \
1035                        \                          \
1036                +--------------------+      +--------------------+
1037   Level 2      | Dev# 3: mouse (1.5)|      | Dev# 4: serial (12)|
1038                +--------------------+      +--------------------+
1039 
1040 
1041 
1042 Or, in a more tree-like structure (ports [Connectors] without
1043 connections could be omitted)::
1044 
1045         PC:  Dev# 1, root hub, 2 ports, 12 Mbps
1046         |_ CN.0:  Dev# 2, hub, 4 ports, 12 Mbps
1047              |_ CN.0:  Dev #3, mouse, 1.5 Mbps
1048              |_ CN.1:
1049              |_ CN.2:  Dev #4, serial, 12 Mbps
1050              |_ CN.3:
1051         |_ CN.1: