brintos

brintos / linux-shallow public Read only

0
0
Text · 42.2 KiB · 89f9c37 Raw
1057 lines · plain
1.. _usb-hostside-api:2 3===========================4The Linux-USB Host Side API5===========================6 7Introduction to USB on Linux8============================9 10A Universal Serial Bus (USB) is used to connect a host, such as a PC or11workstation, to a number of peripheral devices. USB uses a tree12structure, with the host as the root (the system's master), hubs as13interior nodes, and peripherals as leaves (and slaves). Modern PCs14support several such trees of USB devices, usually15a few USB 3.0 (5 GBit/s) or USB 3.1 (10 GBit/s) and some legacy16USB 2.0 (480 MBit/s) busses just in case.17 18That master/slave asymmetry was designed-in for a number of reasons, one19being ease of use. It is not physically possible to mistake upstream and20downstream or it does not matter with a type C plug (or they are built into the21peripheral). Also, the host software doesn't need to deal with22distributed auto-configuration since the pre-designated master node23manages all that.24 25Kernel developers added USB support to Linux early in the 2.2 kernel26series and have been developing it further since then. Besides support27for each new generation of USB, various host controllers gained support,28new drivers for peripherals have been added and advanced features for latency29measurement and improved power management introduced.30 31Linux can run inside USB devices as well as on the hosts that control32the devices. But USB device drivers running inside those peripherals33don't do the same things as the ones running inside hosts, so they've34been given a different name: *gadget drivers*. This document does not35cover gadget drivers.36 37USB Host-Side API Model38=======================39 40Host-side drivers for USB devices talk to the "usbcore" APIs. There are41two. One is intended for *general-purpose* drivers (exposed through42driver frameworks), and the other is for drivers that are *part of the43core*. Such core drivers include the *hub* driver (which manages trees44of USB devices) and several different kinds of *host controller45drivers*, which control individual busses.46 47The device model seen by USB drivers is relatively complex.48 49-  USB supports four kinds of data transfers (control, bulk, interrupt,50   and isochronous). Two of them (control and bulk) use bandwidth as51   it's available, while the other two (interrupt and isochronous) are52   scheduled to provide guaranteed bandwidth.53 54-  The device description model includes one or more "configurations"55   per device, only one of which is active at a time. Devices are supposed56   to be capable of operating at lower than their top57   speeds and may provide a BOS descriptor showing the lowest speed they58   remain fully operational at.59 60-  From USB 3.0 on configurations have one or more "functions", which61   provide a common functionality and are grouped together for purposes62   of power management.63 64-  Configurations or functions have one or more "interfaces", each of which may have65   "alternate settings". Interfaces may be standardized by USB "Class"66   specifications, or may be specific to a vendor or device.67 68   USB device drivers actually bind to interfaces, not devices. Think of69   them as "interface drivers", though you may not see many devices70   where the distinction is important. *Most USB devices are simple,71   with only one function, one configuration, one interface, and one alternate72   setting.*73 74-  Interfaces have one or more "endpoints", each of which supports one75   type and direction of data transfer such as "bulk out" or "interrupt76   in". The entire configuration may have up to sixteen endpoints in77   each direction, allocated as needed among all the interfaces.78 79-  Data transfer on USB is packetized; each endpoint has a maximum80   packet size. Drivers must often be aware of conventions such as81   flagging the end of bulk transfers using "short" (including zero82   length) packets.83 84-  The Linux USB API supports synchronous calls for control and bulk85   messages. It also supports asynchronous calls for all kinds of data86   transfer, using request structures called "URBs" (USB Request87   Blocks).88 89Accordingly, the USB Core API exposed to device drivers covers quite a90lot of territory. You'll probably need to consult the USB 3.091specification, available online from www.usb.org at no cost, as well as92class or device specifications.93 94The only host-side drivers that actually touch hardware (reading/writing95registers, handling IRQs, and so on) are the HCDs. In theory, all HCDs96provide the same functionality through the same API. In practice, that's97becoming more true, but there are still differences98that crop up especially with fault handling on the less common controllers.99Different controllers don't100necessarily report the same aspects of failures, and recovery from101faults (including software-induced ones like unlinking an URB) isn't yet102fully consistent. Device driver authors should make a point of doing103disconnect testing (while the device is active) with each different host104controller driver, to make sure drivers don't have bugs of their own as105well as to make sure they aren't relying on some HCD-specific behavior.106 107.. _usb_chapter9:108 109USB-Standard Types110==================111 112In ``include/uapi/linux/usb/ch9.h`` you will find the USB data types defined113in chapter 9 of the USB specification. These data types are used throughout114USB, and in APIs including this host side API, gadget APIs, usb character115devices and debugfs interfaces. That file is itself included by116``include/linux/usb/ch9.h``, which also contains declarations of a few117utility routines for manipulating these data types; the implementations118are in ``drivers/usb/common/common.c``.119 120.. kernel-doc:: drivers/usb/common/common.c121   :export:122 123In addition, some functions useful for creating debugging output are124defined in ``drivers/usb/common/debug.c``.125 126.. _usb_header:127 128Host-Side Data Types and Macros129===============================130 131The host side API exposes several layers to drivers, some of which are132more necessary than others. These support lifecycle models for host side133drivers and devices, and support passing buffers through usbcore to some134HCD that performs the I/O for the device driver.135 136.. kernel-doc:: include/linux/usb.h137   :internal:138 139USB Core APIs140=============141 142There are two basic I/O models in the USB API. The most elemental one is143asynchronous: drivers submit requests in the form of an URB, and the144URB's completion callback handles the next step. All USB transfer types145support that model, although there are special cases for control URBs146(which always have setup and status stages, but may not have a data147stage) and isochronous URBs (which allow large packets and include148per-packet fault reports). Built on top of that is synchronous API149support, where a driver calls a routine that allocates one or more URBs,150submits them, and waits until they complete. There are synchronous151wrappers for single-buffer control and bulk transfers (which are awkward152to use in some driver disconnect scenarios), and for scatterlist based153streaming i/o (bulk or interrupt).154 155USB drivers need to provide buffers that can be used for DMA, although156they don't necessarily need to provide the DMA mapping themselves. There157are APIs to use used when allocating DMA buffers, which can prevent use158of bounce buffers on some systems. In some cases, drivers may be able to159rely on 64bit DMA to eliminate another kind of bounce buffer.160 161.. kernel-doc:: drivers/usb/core/urb.c162   :export:163 164.. kernel-doc:: drivers/usb/core/message.c165   :export:166 167.. kernel-doc:: drivers/usb/core/file.c168   :export:169 170.. kernel-doc:: drivers/usb/core/driver.c171   :export:172 173.. kernel-doc:: drivers/usb/core/usb.c174   :export:175 176.. kernel-doc:: drivers/usb/core/hub.c177   :export:178 179Host Controller APIs180====================181 182These APIs are only for use by host controller drivers, most of which183implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI184was one of the first interfaces, designed by Intel and also used by VIA;185it doesn't do much in hardware. OHCI was designed later, to have the186hardware do more work (bigger transfers, tracking protocol state, and so187on). EHCI was designed with USB 2.0; its design has features that188resemble OHCI (hardware does much more work) as well as UHCI (some parts189of ISO support, TD list processing). XHCI was designed with USB 3.0. It190continues to shift support for functionality into hardware.191 192There are host controllers other than the "big three", although most PCI193based controllers (and a few non-PCI based ones) use one of those194interfaces. Not all host controllers use DMA; some use PIO, and there is195also a simulator and a virtual host controller to pipe USB over the network.196 197The same basic APIs are available to drivers for all those controllers.198For historical reasons they are in two layers: :c:type:`struct199usb_bus <usb_bus>` is a rather thin layer that became available200in the 2.2 kernels, while :c:type:`struct usb_hcd <usb_hcd>`201is a more featureful layer202that lets HCDs share common code, to shrink driver size and203significantly reduce hcd-specific behaviors.204 205.. kernel-doc:: drivers/usb/core/hcd.c206   :export:207 208.. kernel-doc:: drivers/usb/core/hcd-pci.c209   :export:210 211.. kernel-doc:: drivers/usb/core/buffer.c212   :internal:213 214The USB character device nodes215==============================216 217This chapter presents the Linux character device nodes. You may prefer218to avoid writing new kernel code for your USB driver. User mode device219drivers are usually packaged as applications or libraries, and may use220character devices through some programming library that wraps it.221Such libraries include:222 223 - `libusb <http://libusb.sourceforge.net>`__ for C/C++, and224 - `jUSB <http://jUSB.sourceforge.net>`__ for Java.225 226Some old information about it can be seen at the "USB Device Filesystem"227section of the USB Guide. The latest copy of the USB Guide can be found228at http://www.linux-usb.org/229 230.. note::231 232  - They were used to be implemented via *usbfs*, but this is not part of233    the sysfs debug interface.234 235   - This particular documentation is incomplete, especially with respect236     to the asynchronous mode. As of kernel 2.5.66 the code and this237     (new) documentation need to be cross-reviewed.238 239What files are in "devtmpfs"?240-----------------------------241 242Conventionally mounted at ``/dev/bus/usb/``, usbfs features include:243 244-  ``/dev/bus/usb/BBB/DDD`` ... magic files exposing the each device's245   configuration descriptors, and supporting a series of ioctls for246   making device requests, including I/O to devices. (Purely for access247   by programs.)248 249Each bus is given a number (``BBB``) based on when it was enumerated; within250each bus, each device is given a similar number (``DDD``). Those ``BBB/DDD``251paths are not "stable" identifiers; expect them to change even if you252always leave the devices plugged in to the same hub port. *Don't even253think of saving these in application configuration files.* Stable254identifiers are available, for user mode applications that want to use255them. HID and networking devices expose these stable IDs, so that for256example you can be sure that you told the right UPS to power down its257second server. Pleast note that it doesn't (yet) expose those IDs.258 259/dev/bus/usb/BBB/DDD260--------------------261 262Use these files in one of these basic ways:263 264- *They can be read,* producing first the device descriptor (18 bytes) and265  then the descriptors for the current configuration. See the USB 2.0 spec266  for details about those binary data formats. You'll need to convert most267  multibyte values from little endian format to your native host byte268  order, although a few of the fields in the device descriptor (both of269  the BCD-encoded fields, and the vendor and product IDs) will be270  byteswapped for you. Note that configuration descriptors include271  descriptors for interfaces, altsettings, endpoints, and maybe additional272  class descriptors.273 274- *Perform USB operations* using *ioctl()* requests to make endpoint I/O275  requests (synchronously or asynchronously) or manage the device. These276  requests need the ``CAP_SYS_RAWIO`` capability, as well as filesystem277  access permissions. Only one ioctl request can be made on one of these278  device files at a time. This means that if you are synchronously reading279  an endpoint from one thread, you won't be able to write to a different280  endpoint from another thread until the read completes. This works for281  *half duplex* protocols, but otherwise you'd use asynchronous i/o282  requests.283 284Each connected USB device has one file.  The ``BBB`` indicates the bus285number.  The ``DDD`` indicates the device address on that bus.  Both286of these numbers are assigned sequentially, and can be reused, so287you can't rely on them for stable access to devices.  For example,288it's relatively common for devices to re-enumerate while they are289still connected (perhaps someone jostled their power supply, hub,290or USB cable), so a device might be ``002/027`` when you first connect291it and ``002/048`` sometime later.292 293These files can be read as binary data.  The binary data consists294of first the device descriptor, then the descriptors for each295configuration of the device.  Multi-byte fields in the device descriptor296are converted to host endianness by the kernel.  The configuration297descriptors are in bus endian format! The configuration descriptor298are wTotalLength bytes apart. If a device returns less configuration299descriptor data than indicated by wTotalLength there will be a hole in300the file for the missing bytes.  This information is also shown301in text form by the ``/sys/kernel/debug/usb/devices`` file, described later.302 303These files may also be used to write user-level drivers for the USB304devices.  You would open the ``/dev/bus/usb/BBB/DDD`` file read/write,305read its descriptors to make sure it's the device you expect, and then306bind to an interface (or perhaps several) using an ioctl call.  You307would issue more ioctls to the device to communicate to it using308control, bulk, or other kinds of USB transfers.  The IOCTLs are309listed in the ``<linux/usbdevice_fs.h>`` file, and at this writing the310source code (``linux/drivers/usb/core/devio.c``) is the primary reference311for how to access devices through those files.312 313Note that since by default these ``BBB/DDD`` files are writable only by314root, only root can write such user mode drivers.  You can selectively315grant read/write permissions to other users by using ``chmod``.  Also,316usbfs mount options such as ``devmode=0666`` may be helpful.317 318 319Life Cycle of User Mode Drivers320-------------------------------321 322Such a driver first needs to find a device file for a device it knows323how to handle. Maybe it was told about it because a ``/sbin/hotplug``324event handling agent chose that driver to handle the new device. Or325maybe it's an application that scans all the ``/dev/bus/usb`` device files,326and ignores most devices. In either case, it should :c:func:`read()`327all the descriptors from the device file, and check them against what it328knows how to handle. It might just reject everything except a particular329vendor and product ID, or need a more complex policy.330 331Never assume there will only be one such device on the system at a time!332If your code can't handle more than one device at a time, at least333detect when there's more than one, and have your users choose which334device to use.335 336Once your user mode driver knows what device to use, it interacts with337it in either of two styles. The simple style is to make only control338requests; some devices don't need more complex interactions than those.339(An example might be software using vendor-specific control requests for340some initialization or configuration tasks, with a kernel driver for the341rest.)342 343More likely, you need a more complex style driver: one using non-control344endpoints, reading or writing data and claiming exclusive use of an345interface. *Bulk* transfers are easiest to use, but only their sibling346*interrupt* transfers work with low speed devices. Both interrupt and347*isochronous* transfers offer service guarantees because their bandwidth348is reserved. Such "periodic" transfers are awkward to use through usbfs,349unless you're using the asynchronous calls. However, interrupt transfers350can also be used in a synchronous "one shot" style.351 352Your user-mode driver should never need to worry about cleaning up353request state when the device is disconnected, although it should close354its open file descriptors as soon as it starts seeing the ENODEV errors.355 356The ioctl() Requests357--------------------358 359To use these ioctls, you need to include the following headers in your360userspace program::361 362    #include <linux/usb.h>363    #include <linux/usbdevice_fs.h>364    #include <asm/byteorder.h>365 366The standard USB device model requests, from "Chapter 9" of the USB 2.0367specification, are automatically included from the ``<linux/usb/ch9.h>``368header.369 370Unless noted otherwise, the ioctl requests described here will update371the modification time on the usbfs file to which they are applied372(unless they fail). A return of zero indicates success; otherwise, a373standard USB error code is returned (These are documented in374:ref:`usb-error-codes`).375 376Each of these files multiplexes access to several I/O streams, one per377endpoint. Each device has one control endpoint (endpoint zero) which378supports a limited RPC style RPC access. Devices are configured by379hub_wq (in the kernel) setting a device-wide *configuration* that380affects things like power consumption and basic functionality. The381endpoints are part of USB *interfaces*, which may have *altsettings*382affecting things like which endpoints are available. Many devices only383have a single configuration and interface, so drivers for them will384ignore configurations and altsettings.385 386Management/Status Requests387~~~~~~~~~~~~~~~~~~~~~~~~~~388 389A number of usbfs requests don't deal very directly with device I/O.390They mostly relate to device management and status. These are all391synchronous requests.392 393USBDEVFS_CLAIMINTERFACE394    This is used to force usbfs to claim a specific interface, which has395    not previously been claimed by usbfs or any other kernel driver. The396    ioctl parameter is an integer holding the number of the interface397    (bInterfaceNumber from descriptor).398 399    Note that if your driver doesn't claim an interface before trying to400    use one of its endpoints, and no other driver has bound to it, then401    the interface is automatically claimed by usbfs.402 403    This claim will be released by a RELEASEINTERFACE ioctl, or by404    closing the file descriptor. File modification time is not updated405    by this request.406 407USBDEVFS_CONNECTINFO408    Says whether the device is lowspeed. The ioctl parameter points to a409    structure like this::410 411	struct usbdevfs_connectinfo {412		unsigned int   devnum;413		unsigned char  slow;414	};415 416    File modification time is not updated by this request.417 418    *You can't tell whether a "not slow" device is connected at high419    speed (480 MBit/sec) or just full speed (12 MBit/sec).* You should420    know the devnum value already, it's the DDD value of the device file421    name.422 423USBDEVFS_GET_SPEED424    Returns the speed of the device. The speed is returned as a425    numerical value in accordance with enum usb_device_speed426 427    File modification time is not updated by this request.428 429USBDEVFS_GETDRIVER430    Returns the name of the kernel driver bound to a given interface (a431    string). Parameter is a pointer to this structure, which is432    modified::433 434	struct usbdevfs_getdriver {435		unsigned int  interface;436		char          driver[USBDEVFS_MAXDRIVERNAME + 1];437	};438 439    File modification time is not updated by this request.440 441USBDEVFS_IOCTL442    Passes a request from userspace through to a kernel driver that has443    an ioctl entry in the *struct usb_driver* it registered::444 445	struct usbdevfs_ioctl {446		int     ifno;447		int     ioctl_code;448		void    *data;449	};450 451	/* user mode call looks like this.452	 * 'request' becomes the driver->ioctl() 'code' parameter.453	 * the size of 'param' is encoded in 'request', and that data454	 * is copied to or from the driver->ioctl() 'buf' parameter.455	 */456	static int457	usbdev_ioctl (int fd, int ifno, unsigned request, void *param)458	{459		struct usbdevfs_ioctl   wrapper;460 461		wrapper.ifno = ifno;462		wrapper.ioctl_code = request;463		wrapper.data = param;464 465		return ioctl (fd, USBDEVFS_IOCTL, &wrapper);466	}467 468    File modification time is not updated by this request.469 470    This request lets kernel drivers talk to user mode code through471    filesystem operations even when they don't create a character or472    block special device. It's also been used to do things like ask473    devices what device special file should be used. Two pre-defined474    ioctls are used to disconnect and reconnect kernel drivers, so that475    user mode code can completely manage binding and configuration of476    devices.477 478USBDEVFS_RELEASEINTERFACE479    This is used to release the claim usbfs made on interface, either480    implicitly or because of a USBDEVFS_CLAIMINTERFACE call, before the481    file descriptor is closed. The ioctl parameter is an integer holding482    the number of the interface (bInterfaceNumber from descriptor); File483    modification time is not updated by this request.484 485    .. warning::486 487	*No security check is made to ensure that the task which made488	the claim is the one which is releasing it. This means that user489	mode driver may interfere other ones.*490 491USBDEVFS_RESETEP492    Resets the data toggle value for an endpoint (bulk or interrupt) to493    DATA0. The ioctl parameter is an integer endpoint number (1 to 15,494    as identified in the endpoint descriptor), with USB_DIR_IN added495    if the device's endpoint sends data to the host.496 497    .. Warning::498 499	*Avoid using this request. It should probably be removed.* Using500	it typically means the device and driver will lose toggle501	synchronization. If you really lost synchronization, you likely502	need to completely handshake with the device, using a request503	like CLEAR_HALT or SET_INTERFACE.504 505USBDEVFS_DROP_PRIVILEGES506    This is used to relinquish the ability to do certain operations507    which are considered to be privileged on a usbfs file descriptor.508    This includes claiming arbitrary interfaces, resetting a device on509    which there are currently claimed interfaces from other users, and510    issuing USBDEVFS_IOCTL calls. The ioctl parameter is a 32 bit mask511    of interfaces the user is allowed to claim on this file descriptor.512    You may issue this ioctl more than one time to narrow said mask.513 514Synchronous I/O Support515~~~~~~~~~~~~~~~~~~~~~~~516 517Synchronous requests involve the kernel blocking until the user mode518request completes, either by finishing successfully or by reporting an519error. In most cases this is the simplest way to use usbfs, although as520noted above it does prevent performing I/O to more than one endpoint at521a time.522 523USBDEVFS_BULK524    Issues a bulk read or write request to the device. The ioctl525    parameter is a pointer to this structure::526 527	struct usbdevfs_bulktransfer {528		unsigned int  ep;529		unsigned int  len;530		unsigned int  timeout; /* in milliseconds */531		void          *data;532	};533 534    The ``ep`` value identifies a bulk endpoint number (1 to 15, as535    identified in an endpoint descriptor), masked with USB_DIR_IN when536    referring to an endpoint which sends data to the host from the537    device. The length of the data buffer is identified by ``len``; Recent538    kernels support requests up to about 128KBytes. *FIXME say how read539    length is returned, and how short reads are handled.*.540 541USBDEVFS_CLEAR_HALT542    Clears endpoint halt (stall) and resets the endpoint toggle. This is543    only meaningful for bulk or interrupt endpoints. The ioctl parameter544    is an integer endpoint number (1 to 15, as identified in an endpoint545    descriptor), masked with USB_DIR_IN when referring to an endpoint546    which sends data to the host from the device.547 548    Use this on bulk or interrupt endpoints which have stalled,549    returning ``-EPIPE`` status to a data transfer request. Do not issue550    the control request directly, since that could invalidate the host's551    record of the data toggle.552 553USBDEVFS_CONTROL554    Issues a control request to the device. The ioctl parameter points555    to a structure like this::556 557	struct usbdevfs_ctrltransfer {558		__u8   bRequestType;559		__u8   bRequest;560		__u16  wValue;561		__u16  wIndex;562		__u16  wLength;563		__u32  timeout;  /* in milliseconds */564		void   *data;565	};566 567    The first eight bytes of this structure are the contents of the568    SETUP packet to be sent to the device; see the USB 2.0 specification569    for details. The bRequestType value is composed by combining a570    ``USB_TYPE_*`` value, a ``USB_DIR_*`` value, and a ``USB_RECIP_*``571    value (from ``linux/usb.h``). If wLength is nonzero, it describes572    the length of the data buffer, which is either written to the device573    (USB_DIR_OUT) or read from the device (USB_DIR_IN).574 575    At this writing, you can't transfer more than 4 KBytes of data to or576    from a device; usbfs has a limit, and some host controller drivers577    have a limit. (That's not usually a problem.) *Also* there's no way578    to say it's not OK to get a short read back from the device.579 580USBDEVFS_RESET581    Does a USB level device reset. The ioctl parameter is ignored. After582    the reset, this rebinds all device interfaces. File modification583    time is not updated by this request.584 585.. warning::586 587	*Avoid using this call* until some usbcore bugs get fixed, since588	it does not fully synchronize device, interface, and driver (not589	just usbfs) state.590 591USBDEVFS_SETINTERFACE592    Sets the alternate setting for an interface. The ioctl parameter is593    a pointer to a structure like this::594 595	struct usbdevfs_setinterface {596		unsigned int  interface;597		unsigned int  altsetting;598	};599 600    File modification time is not updated by this request.601 602    Those struct members are from some interface descriptor applying to603    the current configuration. The interface number is the604    bInterfaceNumber value, and the altsetting number is the605    bAlternateSetting value. (This resets each endpoint in the606    interface.)607 608USBDEVFS_SETCONFIGURATION609    Issues the :c:func:`usb_set_configuration()` call for the610    device. The parameter is an integer holding the number of a611    configuration (bConfigurationValue from descriptor). File612    modification time is not updated by this request.613 614.. warning::615 616	*Avoid using this call* until some usbcore bugs get fixed, since617	it does not fully synchronize device, interface, and driver (not618	just usbfs) state.619 620Asynchronous I/O Support621~~~~~~~~~~~~~~~~~~~~~~~~622 623As mentioned above, there are situations where it may be important to624initiate concurrent operations from user mode code. This is particularly625important for periodic transfers (interrupt and isochronous), but it can626be used for other kinds of USB requests too. In such cases, the627asynchronous requests described here are essential. Rather than628submitting one request and having the kernel block until it completes,629the blocking is separate.630 631These requests are packaged into a structure that resembles the URB used632by kernel device drivers. (No POSIX Async I/O support here, sorry.) It633identifies the endpoint type (``USBDEVFS_URB_TYPE_*``), endpoint634(number, masked with USB_DIR_IN as appropriate), buffer and length,635and a user "context" value serving to uniquely identify each request.636(It's usually a pointer to per-request data.) Flags can modify requests637(not as many as supported for kernel drivers).638 639Each request can specify a realtime signal number (between SIGRTMIN and640SIGRTMAX, inclusive) to request a signal be sent when the request641completes.642 643When usbfs returns these urbs, the status value is updated, and the644buffer may have been modified. Except for isochronous transfers, the645actual_length is updated to say how many bytes were transferred; if the646USBDEVFS_URB_DISABLE_SPD flag is set ("short packets are not OK"), if647fewer bytes were read than were requested then you get an error report::648 649    struct usbdevfs_iso_packet_desc {650	    unsigned int                     length;651	    unsigned int                     actual_length;652	    unsigned int                     status;653    };654 655    struct usbdevfs_urb {656	    unsigned char                    type;657	    unsigned char                    endpoint;658	    int                              status;659	    unsigned int                     flags;660	    void                             *buffer;661	    int                              buffer_length;662	    int                              actual_length;663	    int                              start_frame;664	    int                              number_of_packets;665	    int                              error_count;666	    unsigned int                     signr;667	    void                             *usercontext;668	    struct usbdevfs_iso_packet_desc  iso_frame_desc[];669    };670 671For these asynchronous requests, the file modification time reflects672when the request was initiated. This contrasts with their use with the673synchronous requests, where it reflects when requests complete.674 675USBDEVFS_DISCARDURB676    *TBS* File modification time is not updated by this request.677 678USBDEVFS_DISCSIGNAL679    *TBS* File modification time is not updated by this request.680 681USBDEVFS_REAPURB682    *TBS* File modification time is not updated by this request.683 684USBDEVFS_REAPURBNDELAY685    *TBS* File modification time is not updated by this request.686 687USBDEVFS_SUBMITURB688    *TBS*689 690The USB devices691===============692 693The USB devices are now exported via debugfs:694 695-  ``/sys/kernel/debug/usb/devices`` ... a text file showing each of the USB696   devices on known to the kernel, and their configuration descriptors.697   You can also poll() this to learn about new devices.698 699/sys/kernel/debug/usb/devices700-----------------------------701 702This file is handy for status viewing tools in user mode, which can scan703the text format and ignore most of it. More detailed device status704(including class and vendor status) is available from device-specific705files. For information about the current format of this file, see below.706 707This file, in combination with the poll() system call, can also be used708to detect when devices are added or removed::709 710    int fd;711    struct pollfd pfd;712 713    fd = open("/sys/kernel/debug/usb/devices", O_RDONLY);714    pfd = { fd, POLLIN, 0 };715    for (;;) {716	/* The first time through, this call will return immediately. */717	poll(&pfd, 1, -1);718 719	/* To see what's changed, compare the file's previous and current720	   contents or scan the filesystem.  (Scanning is more precise.) */721    }722 723Note that this behavior is intended to be used for informational and724debug purposes. It would be more appropriate to use programs such as725udev or HAL to initialize a device or start a user-mode helper program,726for instance.727 728In this file, each device's output has multiple lines of ASCII output.729 730I made it ASCII instead of binary on purpose, so that someone731can obtain some useful data from it without the use of an732auxiliary program.  However, with an auxiliary program, the numbers733in the first 4 columns of each ``T:`` line (topology info:734Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.735 736Each line is tagged with a one-character ID for that line::737 738	T = Topology (etc.)739	B = Bandwidth (applies only to USB host controllers, which are740	virtualized as root hubs)741	D = Device descriptor info.742	P = Product ID info. (from Device descriptor, but they won't fit743	together on one line)744	S = String descriptors.745	C = Configuration descriptor info. (* = active configuration)746	I = Interface descriptor info.747	E = Endpoint descriptor info.748 749/sys/kernel/debug/usb/devices output format750~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~751 752Legend::753  d = decimal number (may have leading spaces or 0's)754  x = hexadecimal number (may have leading spaces or 0's)755  s = string756 757 758 759Topology info760^^^^^^^^^^^^^761 762::763 764	T:  Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=dddd MxCh=dd765	|   |      |      |       |       |      |        |        |__MaxChildren766	|   |      |      |       |       |      |        |__Device Speed in Mbps767	|   |      |      |       |       |      |__DeviceNumber768	|   |      |      |       |       |__Count of devices at this level769	|   |      |      |       |__Connector/Port on Parent for this device770	|   |      |      |__Parent DeviceNumber771	|   |      |__Level in topology for this bus772	|   |__Bus number773	|__Topology info tag774 775Speed may be:776 777	======= ======================================================778	1.5	Mbit/s for low speed USB779	12	Mbit/s for full speed USB780	480	Mbit/s for high speed USB (added for USB 2.0)781	5000	Mbit/s for SuperSpeed USB (added for USB 3.0)782	======= ======================================================783 784For reasons lost in the mists of time, the Port number is always785too low by 1.  For example, a device plugged into port 4 will786show up with ``Port=03``.787 788Bandwidth info789^^^^^^^^^^^^^^790 791::792 793	B:  Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd794	|   |                       |         |__Number of isochronous requests795	|   |                       |__Number of interrupt requests796	|   |__Total Bandwidth allocated to this bus797	|__Bandwidth info tag798 799Bandwidth allocation is an approximation of how much of one frame800(millisecond) is in use.  It reflects only periodic transfers, which801are the only transfers that reserve bandwidth.  Control and bulk802transfers use all other bandwidth, including reserved bandwidth that803is not used for transfers (such as for short packets).804 805The percentage is how much of the "reserved" bandwidth is scheduled by806those transfers.  For a low or full speed bus (loosely, "USB 1.1"),80790% of the bus bandwidth is reserved.  For a high speed bus (loosely,808"USB 2.0") 80% is reserved.809 810 811Device descriptor info & Product ID info812^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^813 814::815 816	D:  Ver=x.xx Cls=xx(s) Sub=xx Prot=xx MxPS=dd #Cfgs=dd817	P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx818 819where::820 821	D:  Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd822	|   |        |             |      |       |       |__NumberConfigurations823	|   |        |             |      |       |__MaxPacketSize of Default Endpoint824	|   |        |             |      |__DeviceProtocol825	|   |        |             |__DeviceSubClass826	|   |        |__DeviceClass827	|   |__Device USB version828	|__Device info tag #1829 830where::831 832	P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx833	|   |           |           |__Product revision number834	|   |           |__Product ID code835	|   |__Vendor ID code836	|__Device info tag #2837 838 839String descriptor info840^^^^^^^^^^^^^^^^^^^^^^841::842 843	S:  Manufacturer=ssss844	|   |__Manufacturer of this device as read from the device.845	|      For USB host controller drivers (virtual root hubs) this may846	|      be omitted, or (for newer drivers) will identify the kernel847	|      version and the driver which provides this hub emulation.848	|__String info tag849 850	S:  Product=ssss851	|   |__Product description of this device as read from the device.852	|      For older USB host controller drivers (virtual root hubs) this853	|      indicates the driver; for newer ones, it's a product (and vendor)854	|      description that often comes from the kernel's PCI ID database.855	|__String info tag856 857	S:  SerialNumber=ssss858	|   |__Serial Number of this device as read from the device.859	|      For USB host controller drivers (virtual root hubs) this is860	|      some unique ID, normally a bus ID (address or slot name) that861	|      can't be shared with any other device.862	|__String info tag863 864 865 866Configuration descriptor info867^^^^^^^^^^^^^^^^^^^^^^^^^^^^^868::869 870	C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA871	| | |       |       |      |__MaxPower in mA872	| | |       |       |__Attributes873	| | |       |__ConfiguratioNumber874	| | |__NumberOfInterfaces875	| |__ "*" indicates the active configuration (others are " ")876	|__Config info tag877 878USB devices may have multiple configurations, each of which act879rather differently.  For example, a bus-powered configuration880might be much less capable than one that is self-powered.  Only881one device configuration can be active at a time; most devices882have only one configuration.883 884Each configuration consists of one or more interfaces.  Each885interface serves a distinct "function", which is typically bound886to a different USB device driver.  One common example is a USB887speaker with an audio interface for playback, and a HID interface888for use with software volume control.889 890Interface descriptor info (can be multiple per Config)891^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^892::893 894	I:* If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss895	| | |      |      |       |             |      |       |__Driver name896	| | |      |      |       |             |      |          or "(none)"897	| | |      |      |       |             |      |__InterfaceProtocol898	| | |      |      |       |             |__InterfaceSubClass899	| | |      |      |       |__InterfaceClass900	| | |      |      |__NumberOfEndpoints901	| | |      |__AlternateSettingNumber902	| | |__InterfaceNumber903	| |__ "*" indicates the active altsetting (others are " ")904	|__Interface info tag905 906A given interface may have one or more "alternate" settings.907For example, default settings may not use more than a small908amount of periodic bandwidth.  To use significant fractions909of bus bandwidth, drivers must select a non-default altsetting.910 911Only one setting for an interface may be active at a time, and912only one driver may bind to an interface at a time.  Most devices913have only one alternate setting per interface.914 915 916Endpoint descriptor info (can be multiple per Interface)917^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^918 919::920 921	E:  Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddss922	|   |        |            |         |__Interval (max) between transfers923	|   |        |            |__EndpointMaxPacketSize924	|   |        |__Attributes(EndpointType)925	|   |__EndpointAddress(I=In,O=Out)926	|__Endpoint info tag927 928The interval is nonzero for all periodic (interrupt or isochronous)929endpoints.  For high speed endpoints the transfer interval may be930measured in microseconds rather than milliseconds.931 932For high speed periodic endpoints, the ``EndpointMaxPacketSize`` reflects933the per-microframe data transfer size.  For "high bandwidth"934endpoints, that can reflect two or three packets (for up to9353KBytes every 125 usec) per endpoint.936 937With the Linux-USB stack, periodic bandwidth reservations use the938transfer intervals and sizes provided by URBs, which can be less939than those found in endpoint descriptor.940 941Usage examples942~~~~~~~~~~~~~~943 944If a user or script is interested only in Topology info, for945example, use something like ``grep ^T: /sys/kernel/debug/usb/devices``946for only the Topology lines.  A command like947``grep -i ^[tdp]: /sys/kernel/debug/usb/devices`` can be used to list948only the lines that begin with the characters in square brackets,949where the valid characters are TDPCIE.  With a slightly more able950script, it can display any selected lines (for example, only T, D,951and P lines) and change their output format.  (The ``procusb``952Perl script is the beginning of this idea.  It will list only953selected lines [selected from TBDPSCIE] or "All" lines from954``/sys/kernel/debug/usb/devices``.)955 956The Topology lines can be used to generate a graphic/pictorial957of the USB devices on a system's root hub.  (See more below958on how to do this.)959 960The Interface lines can be used to determine what driver is961being used for each device, and which altsetting it activated.962 963The Configuration lines could be used to list maximum power964(in milliamps) that a system's USB devices are using.965For example, ``grep ^C: /sys/kernel/debug/usb/devices``.966 967 968Here's an example, from a system which has a UHCI root hub,969an external hub connected to the root hub, and a mouse and970a serial converter connected to the external hub.971 972::973 974	T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 2975	B:  Alloc= 28/900 us ( 3%), #Int=  2, #Iso=  0976	D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1977	P:  Vendor=0000 ProdID=0000 Rev= 0.00978	S:  Product=USB UHCI Root Hub979	S:  SerialNumber=dce0980	C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr=  0mA981	I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub982	E:  Ad=81(I) Atr=03(Int.) MxPS=   8 Ivl=255ms983 984	T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 4985	D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1986	P:  Vendor=0451 ProdID=1446 Rev= 1.00987	C:* #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=100mA988	I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub989	E:  Ad=81(I) Atr=03(Int.) MxPS=   1 Ivl=255ms990 991	T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 0992	D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1993	P:  Vendor=04b4 ProdID=0001 Rev= 0.00994	C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA995	I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse996	E:  Ad=81(I) Atr=03(Int.) MxPS=   3 Ivl= 10ms997 998	T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0999	D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  11000	P:  Vendor=0565 ProdID=0001 Rev= 1.081001	S:  Manufacturer=Peracom Networks, Inc.1002	S:  Product=Peracom USB to Serial Converter1003	C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=100mA1004	I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial1005	E:  Ad=81(I) Atr=02(Bulk) MxPS=  64 Ivl= 16ms1006	E:  Ad=01(O) Atr=02(Bulk) MxPS=  16 Ivl= 16ms1007	E:  Ad=82(I) Atr=03(Int.) MxPS=   8 Ivl=  8ms1008 1009 1010Selecting only the ``T:`` and ``I:`` lines from this (for example, by using1011``procusb ti``), we have1012 1013::1014 1015	T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 21016	T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 41017	I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub1018	T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 01019	I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse1020	T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 01021	I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial1022 1023 1024Physically this looks like (or could be converted to)::1025 1026                      +------------------+1027                      |  PC/root_hub (12)|   Dev# = 11028                      +------------------+   (nn) is Mbps.1029    Level 0           |  CN.0   |  CN.1  |   [CN = connector/port #]1030                      +------------------+1031                          /1032                         /1033            +-----------------------+1034  Level 1   | Dev#2: 4-port hub (12)|1035            +-----------------------+1036            |CN.0 |CN.1 |CN.2 |CN.3 |1037            +-----------------------+1038                \           \____________________1039                 \_____                          \1040                       \                          \1041               +--------------------+      +--------------------+1042  Level 2      | Dev# 3: mouse (1.5)|      | Dev# 4: serial (12)|1043               +--------------------+      +--------------------+1044 1045 1046 1047Or, in a more tree-like structure (ports [Connectors] without1048connections could be omitted)::1049 1050	PC:  Dev# 1, root hub, 2 ports, 12 Mbps1051	|_ CN.0:  Dev# 2, hub, 4 ports, 12 Mbps1052	     |_ CN.0:  Dev #3, mouse, 1.5 Mbps1053	     |_ CN.1:1054	     |_ CN.2:  Dev #4, serial, 12 Mbps1055	     |_ CN.3:1056	|_ CN.1:1057