1.. _usb-hostside-api:
2
3===========================
4The Linux-USB Host Side API
5===========================
6
7Introduction to USB on Linux
8============================
9
10A Universal Serial Bus (USB) is used to connect a host, such as a PC or
11workstation, to a number of peripheral devices. USB uses a tree
12structure, with the host as the root (the system's master), hubs as
13interior nodes, and peripherals as leaves (and slaves). Modern PCs
14support several such trees of USB devices, usually
15a few USB 3.0 (5 GBit/s) or USB 3.1 (10 GBit/s) and some legacy
16USB 2.0 (480 MBit/s) busses just in case.
17
18That master/slave asymmetry was designed-in for a number of reasons, one
19being ease of use. It is not physically possible to mistake upstream and
20downstream or it does not matter with a type C plug (or they are built into the
21peripheral). Also, the host software doesn't need to deal with
22distributed auto-configuration since the pre-designated master node
23manages all that.
24
25Kernel developers added USB support to Linux early in the 2.2 kernel
26series and have been developing it further since then. Besides support
27for each new generation of USB, various host controllers gained support,
28new drivers for peripherals have been added and advanced features for latency
29measurement and improved power management introduced.
30
31Linux can run inside USB devices as well as on the hosts that control
32the devices. But USB device drivers running inside those peripherals
33don't do the same things as the ones running inside hosts, so they've
34been given a different name: *gadget drivers*. This document does not
35cover gadget drivers.
36
37USB Host-Side API Model
38=======================
39
40Host-side drivers for USB devices talk to the "usbcore" APIs. There are
41two. One is intended for *general-purpose* drivers (exposed through
42driver frameworks), and the other is for drivers that are *part of the
43core*. Such core drivers include the *hub* driver (which manages trees
44of USB devices) and several different kinds of *host controller
45drivers*, 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 as
51   it's available, while the other two (interrupt and isochronous) are
52   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 supposed
56   to be capable of operating at lower than their top
57   speeds and may provide a BOS descriptor showing the lowest speed they
58   remain fully operational at.
59
60-  From USB 3.0 on configurations have one or more "functions", which
61   provide a common functionality and are grouped together for purposes
62   of power management.
63
64-  Configurations or functions have one or more "interfaces", each of which may have
65   "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 of
69   them as "interface drivers", though you may not see many devices
70   where the distinction is important. *Most USB devices are simple,
71   with only one function, one configuration, one interface, and one alternate
72   setting.*
73
74-  Interfaces have one or more "endpoints", each of which supports one
75   type and direction of data transfer such as "bulk out" or "interrupt
76   in". The entire configuration may have up to sixteen endpoints in
77   each direction, allocated as needed among all the interfaces.
78
79-  Data transfer on USB is packetized; each endpoint has a maximum
80   packet size. Drivers must often be aware of conventions such as
81   flagging the end of bulk transfers using "short" (including zero
82   length) packets.
83
84-  The Linux USB API supports synchronous calls for control and bulk
85   messages. It also supports asynchronous calls for all kinds of data
86   transfer, using request structures called "URBs" (USB Request
87   Blocks).
88
89Accordingly, the USB Core API exposed to device drivers covers quite a
90lot of territory. You'll probably need to consult the USB 3.0
91specification, available online from www.usb.org at no cost, as well as
92class or device specifications.
93
94The only host-side drivers that actually touch hardware (reading/writing
95registers, handling IRQs, and so on) are the HCDs. In theory, all HCDs
96provide the same functionality through the same API. In practice, that's
97becoming more true, but there are still differences
98that crop up especially with fault handling on the less common controllers.
99Different controllers don't
100necessarily report the same aspects of failures, and recovery from
101faults (including software-induced ones like unlinking an URB) isn't yet
102fully consistent. Device driver authors should make a point of doing
103disconnect testing (while the device is active) with each different host
104controller driver, to make sure drivers don't have bugs of their own as
105well as to make sure they aren't relying on some HCD-specific behavior.
106
107.. _usb_chapter9:
108
109USB-Standard Types
110==================
111
112In ``include/uapi/linux/usb/ch9.h`` you will find the USB data types defined
113in chapter 9 of the USB specification. These data types are used throughout
114USB, and in APIs including this host side API, gadget APIs, usb character
115devices and debugfs interfaces. That file is itself included by
116``include/linux/usb/ch9.h``, which also contains declarations of a few
117utility routines for manipulating these data types; the implementations
118are in ``drivers/usb/common/common.c``.
119
120.. kernel-doc:: drivers/usb/common/common.c
121   :export:
122
123In addition, some functions useful for creating debugging output are
124defined in ``drivers/usb/common/debug.c``.
125
126Host-Side Data Types and Macros
127===============================
128
129The host side API exposes several layers to drivers, some of which are
130more necessary than others. These support lifecycle models for host side
131drivers and devices, and support passing buffers through usbcore to some
132HCD that performs the I/O for the device driver.
133
134.. kernel-doc:: include/linux/usb.h
135   :internal:
136
137USB Core APIs
138=============
139
140There are two basic I/O models in the USB API. The most elemental one is
141asynchronous: drivers submit requests in the form of an URB, and the
142URB's completion callback handles the next step. All USB transfer types
143support that model, although there are special cases for control URBs
144(which always have setup and status stages, but may not have a data
145stage) and isochronous URBs (which allow large packets and include
146per-packet fault reports). Built on top of that is synchronous API
147support, where a driver calls a routine that allocates one or more URBs,
148submits them, and waits until they complete. There are synchronous
149wrappers for single-buffer control and bulk transfers (which are awkward
150to use in some driver disconnect scenarios), and for scatterlist based
151streaming i/o (bulk or interrupt).
152
153USB drivers need to provide buffers that can be used for DMA, although
154they don't necessarily need to provide the DMA mapping themselves. There
155are APIs to use used when allocating DMA buffers, which can prevent use
156of bounce buffers on some systems. In some cases, drivers may be able to
157rely on 64bit DMA to eliminate another kind of bounce buffer.
158
159.. kernel-doc:: drivers/usb/core/urb.c
160   :export:
161
162.. kernel-doc:: drivers/usb/core/message.c
163   :export:
164
165.. kernel-doc:: drivers/usb/core/file.c
166   :export:
167
168.. kernel-doc:: drivers/usb/core/driver.c
169   :export:
170
171.. kernel-doc:: drivers/usb/core/usb.c
172   :export:
173
174.. kernel-doc:: drivers/usb/core/hub.c
175   :export:
176
177Host Controller APIs
178====================
179
180These APIs are only for use by host controller drivers, most of which
181implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI
182was one of the first interfaces, designed by Intel and also used by VIA;
183it doesn't do much in hardware. OHCI was designed later, to have the
184hardware do more work (bigger transfers, tracking protocol state, and so
185on). EHCI was designed with USB 2.0; its design has features that
186resemble OHCI (hardware does much more work) as well as UHCI (some parts
187of ISO support, TD list processing). XHCI was designed with USB 3.0. It
188continues to shift support for functionality into hardware.
189
190There are host controllers other than the "big three", although most PCI
191based controllers (and a few non-PCI based ones) use one of those
192interfaces. Not all host controllers use DMA; some use PIO, and there is
193also a simulator and a virtual host controller to pipe USB over the network.
194
195The same basic APIs are available to drivers for all those controllers.
196For historical reasons they are in two layers: :c:type:`struct
197usb_bus <usb_bus>` is a rather thin layer that became available
198in the 2.2 kernels, while :c:type:`struct usb_hcd <usb_hcd>`
199is a more featureful layer
200that lets HCDs share common code, to shrink driver size and
201significantly reduce hcd-specific behaviors.
202
203.. kernel-doc:: drivers/usb/core/hcd.c
204   :export:
205
206.. kernel-doc:: drivers/usb/core/hcd-pci.c
207   :export:
208
209.. kernel-doc:: drivers/usb/core/buffer.c
210   :internal:
211
212The USB character device nodes
213==============================
214
215This chapter presents the Linux character device nodes. You may prefer
216to avoid writing new kernel code for your USB driver. User mode device
217drivers are usually packaged as applications or libraries, and may use
218character devices through some programming library that wraps it.
219Such libraries include:
220
221 - `libusb <http://libusb.sourceforge.net>`__ for C/C++, and
222 - `jUSB <http://jUSB.sourceforge.net>`__ for Java.
223
224Some old information about it can be seen at the "USB Device Filesystem"
225section of the USB Guide. The latest copy of the USB Guide can be found
226at http://www.linux-usb.org/
227
228.. note::
229
230  - They were used to be implemented via *usbfs*, but this is not part of
231    the sysfs debug interface.
232
233   - This particular documentation is incomplete, especially with respect
234     to the asynchronous mode. As of kernel 2.5.66 the code and this
235     (new) documentation need to be cross-reviewed.
236
237What files are in "devtmpfs"?
238-----------------------------
239
240Conventionally mounted at ``/dev/bus/usb/``, usbfs features include:
241
242-  ``/dev/bus/usb/BBB/DDD`` ... magic files exposing the each device's
243   configuration descriptors, and supporting a series of ioctls for
244   making device requests, including I/O to devices. (Purely for access
245   by programs.)
246
247Each bus is given a number (``BBB``) based on when it was enumerated; within
248each bus, each device is given a similar number (``DDD``). Those ``BBB/DDD``
249paths are not "stable" identifiers; expect them to change even if you
250always leave the devices plugged in to the same hub port. *Don't even
251think of saving these in application configuration files.* Stable
252identifiers are available, for user mode applications that want to use
253them. HID and networking devices expose these stable IDs, so that for
254example you can be sure that you told the right UPS to power down its
255second server. Pleast note that it doesn't (yet) expose those IDs.
256
257/dev/bus/usb/BBB/DDD
258--------------------
259
260Use these files in one of these basic ways:
261
262- *They can be read,* producing first the device descriptor (18 bytes) and
263  then the descriptors for the current configuration. See the USB 2.0 spec
264  for details about those binary data formats. You'll need to convert most
265  multibyte values from little endian format to your native host byte
266  order, although a few of the fields in the device descriptor (both of
267  the BCD-encoded fields, and the vendor and product IDs) will be
268  byteswapped for you. Note that configuration descriptors include
269  descriptors for interfaces, altsettings, endpoints, and maybe additional
270  class descriptors.
271
272- *Perform USB operations* using *ioctl()* requests to make endpoint I/O
273  requests (synchronously or asynchronously) or manage the device. These
274  requests need the ``CAP_SYS_RAWIO`` capability, as well as filesystem
275  access permissions. Only one ioctl request can be made on one of these
276  device files at a time. This means that if you are synchronously reading
277  an endpoint from one thread, you won't be able to write to a different
278  endpoint from another thread until the read completes. This works for
279  *half duplex* protocols, but otherwise you'd use asynchronous i/o
280  requests.
281
282Each connected USB device has one file.  The ``BBB`` indicates the bus
283number.  The ``DDD`` indicates the device address on that bus.  Both
284of these numbers are assigned sequentially, and can be reused, so
285you can't rely on them for stable access to devices.  For example,
286it's relatively common for devices to re-enumerate while they are
287still connected (perhaps someone jostled their power supply, hub,
288or USB cable), so a device might be ``002/027`` when you first connect
289it and ``002/048`` sometime later.
290
291These files can be read as binary data.  The binary data consists
292of first the device descriptor, then the descriptors for each
293configuration of the device.  Multi-byte fields in the device descriptor
294are converted to host endianness by the kernel.  The configuration
295descriptors are in bus endian format! The configuration descriptor
296are wTotalLength bytes apart. If a device returns less configuration
297descriptor data than indicated by wTotalLength there will be a hole in
298the file for the missing bytes.  This information is also shown
299in text form by the ``/sys/kernel/debug/usb/devices`` file, described later.
300
301These files may also be used to write user-level drivers for the USB
302devices.  You would open the ``/dev/bus/usb/BBB/DDD`` file read/write,
303read its descriptors to make sure it's the device you expect, and then
304bind to an interface (or perhaps several) using an ioctl call.  You
305would issue more ioctls to the device to communicate to it using
306control, bulk, or other kinds of USB transfers.  The IOCTLs are
307listed in the ``<linux/usbdevice_fs.h>`` file, and at this writing the
308source code (``linux/drivers/usb/core/devio.c``) is the primary reference
309for how to access devices through those files.
310
311Note that since by default these ``BBB/DDD`` files are writable only by
312root, only root can write such user mode drivers.  You can selectively
313grant read/write permissions to other users by using ``chmod``.  Also,
314usbfs mount options such as ``devmode=0666`` may be helpful.
315
316
317Life Cycle of User Mode Drivers
318-------------------------------
319
320Such a driver first needs to find a device file for a device it knows
321how to handle. Maybe it was told about it because a ``/sbin/hotplug``
322event handling agent chose that driver to handle the new device. Or
323maybe it's an application that scans all the ``/dev/bus/usb`` device files,
324and ignores most devices. In either case, it should :c:func:`read()`
325all the descriptors from the device file, and check them against what it
326knows how to handle. It might just reject everything except a particular
327vendor and product ID, or need a more complex policy.
328
329Never assume there will only be one such device on the system at a time!
330If your code can't handle more than one device at a time, at least
331detect when there's more than one, and have your users choose which
332device to use.
333
334Once your user mode driver knows what device to use, it interacts with
335it in either of two styles. The simple style is to make only control
336requests; some devices don't need more complex interactions than those.
337(An example might be software using vendor-specific control requests for
338some initialization or configuration tasks, with a kernel driver for the
339rest.)
340
341More likely, you need a more complex style driver: one using non-control
342endpoints, reading or writing data and claiming exclusive use of an
343interface. *Bulk* transfers are easiest to use, but only their sibling
344*interrupt* transfers work with low speed devices. Both interrupt and
345*isochronous* transfers offer service guarantees because their bandwidth
346is reserved. Such "periodic" transfers are awkward to use through usbfs,
347unless you're using the asynchronous calls. However, interrupt transfers
348can also be used in a synchronous "one shot" style.
349
350Your user-mode driver should never need to worry about cleaning up
351request state when the device is disconnected, although it should close
352its open file descriptors as soon as it starts seeing the ENODEV errors.
353
354The ioctl() Requests
355--------------------
356
357To use these ioctls, you need to include the following headers in your
358userspace program::
359
360    #include <linux/usb.h>
361    #include <linux/usbdevice_fs.h>
362    #include <asm/byteorder.h>
363
364The standard USB device model requests, from "Chapter 9" of the USB 2.0
365specification, are automatically included from the ``<linux/usb/ch9.h>``
366header.
367
368Unless noted otherwise, the ioctl requests described here will update
369the modification time on the usbfs file to which they are applied
370(unless they fail). A return of zero indicates success; otherwise, a
371standard USB error code is returned (These are documented in
372:ref:`usb-error-codes`).
373
374Each of these files multiplexes access to several I/O streams, one per
375endpoint. Each device has one control endpoint (endpoint zero) which
376supports a limited RPC style RPC access. Devices are configured by
377hub_wq (in the kernel) setting a device-wide *configuration* that
378affects things like power consumption and basic functionality. The
379endpoints are part of USB *interfaces*, which may have *altsettings*
380affecting things like which endpoints are available. Many devices only
381have a single configuration and interface, so drivers for them will
382ignore configurations and altsettings.
383
384Management/Status Requests
385~~~~~~~~~~~~~~~~~~~~~~~~~~
386
387A number of usbfs requests don't deal very directly with device I/O.
388They mostly relate to device management and status. These are all
389synchronous requests.
390
391USBDEVFS_CLAIMINTERFACE
392    This is used to force usbfs to claim a specific interface, which has
393    not previously been claimed by usbfs or any other kernel driver. The
394    ioctl parameter is an integer holding the number of the interface
395    (bInterfaceNumber from descriptor).
396
397    Note that if your driver doesn't claim an interface before trying to
398    use one of its endpoints, and no other driver has bound to it, then
399    the interface is automatically claimed by usbfs.
400
401    This claim will be released by a RELEASEINTERFACE ioctl, or by
402    closing the file descriptor. File modification time is not updated
403    by this request.
404
405USBDEVFS_CONNECTINFO
406    Says whether the device is lowspeed. The ioctl parameter points to a
407    structure like this::
408
409	struct usbdevfs_connectinfo {
410		unsigned int   devnum;
411		unsigned char  slow;
412	};
413
414    File modification time is not updated by this request.
415
416    *You can't tell whether a "not slow" device is connected at high
417    speed (480 MBit/sec) or just full speed (12 MBit/sec).* You should
418    know the devnum value already, it's the DDD value of the device file
419    name.
420
421USBDEVFS_GETDRIVER
422    Returns the name of the kernel driver bound to a given interface (a
423    string). Parameter is a pointer to this structure, which is
424    modified::
425
426	struct usbdevfs_getdriver {
427		unsigned int  interface;
428		char          driver[USBDEVFS_MAXDRIVERNAME + 1];
429	};
430
431    File modification time is not updated by this request.
432
433USBDEVFS_IOCTL
434    Passes a request from userspace through to a kernel driver that has
435    an ioctl entry in the *struct usb_driver* it registered::
436
437	struct usbdevfs_ioctl {
438		int     ifno;
439		int     ioctl_code;
440		void    *data;
441	};
442
443	/* user mode call looks like this.
444	 * 'request' becomes the driver->ioctl() 'code' parameter.
445	 * the size of 'param' is encoded in 'request', and that data
446	 * is copied to or from the driver->ioctl() 'buf' parameter.
447	 */
448	static int
449	usbdev_ioctl (int fd, int ifno, unsigned request, void *param)
450	{
451		struct usbdevfs_ioctl   wrapper;
452
453		wrapper.ifno = ifno;
454		wrapper.ioctl_code = request;
455		wrapper.data = param;
456
457		return ioctl (fd, USBDEVFS_IOCTL, &wrapper);
458	}
459
460    File modification time is not updated by this request.
461
462    This request lets kernel drivers talk to user mode code through
463    filesystem operations even when they don't create a character or
464    block special device. It's also been used to do things like ask
465    devices what device special file should be used. Two pre-defined
466    ioctls are used to disconnect and reconnect kernel drivers, so that
467    user mode code can completely manage binding and configuration of
468    devices.
469
470USBDEVFS_RELEASEINTERFACE
471    This is used to release the claim usbfs made on interface, either
472    implicitly or because of a USBDEVFS_CLAIMINTERFACE call, before the
473    file descriptor is closed. The ioctl parameter is an integer holding
474    the number of the interface (bInterfaceNumber from descriptor); File
475    modification time is not updated by this request.
476
477    .. warning::
478
479	*No security check is made to ensure that the task which made
480	the claim is the one which is releasing it. This means that user
481	mode driver may interfere other ones.*
482
483USBDEVFS_RESETEP
484    Resets the data toggle value for an endpoint (bulk or interrupt) to
485    DATA0. The ioctl parameter is an integer endpoint number (1 to 15,
486    as identified in the endpoint descriptor), with USB_DIR_IN added
487    if the device's endpoint sends data to the host.
488
489    .. Warning::
490
491	*Avoid using this request. It should probably be removed.* Using
492	it typically means the device and driver will lose toggle
493	synchronization. If you really lost synchronization, you likely
494	need to completely handshake with the device, using a request
495	like CLEAR_HALT or SET_INTERFACE.
496
497USBDEVFS_DROP_PRIVILEGES
498    This is used to relinquish the ability to do certain operations
499    which are considered to be privileged on a usbfs file descriptor.
500    This includes claiming arbitrary interfaces, resetting a device on
501    which there are currently claimed interfaces from other users, and
502    issuing USBDEVFS_IOCTL calls. The ioctl parameter is a 32 bit mask
503    of interfaces the user is allowed to claim on this file descriptor.
504    You may issue this ioctl more than one time to narrow said mask.
505
506Synchronous I/O Support
507~~~~~~~~~~~~~~~~~~~~~~~
508
509Synchronous requests involve the kernel blocking until the user mode
510request completes, either by finishing successfully or by reporting an
511error. In most cases this is the simplest way to use usbfs, although as
512noted above it does prevent performing I/O to more than one endpoint at
513a time.
514
515USBDEVFS_BULK
516    Issues a bulk read or write request to the device. The ioctl
517    parameter is a pointer to this structure::
518
519	struct usbdevfs_bulktransfer {
520		unsigned int  ep;
521		unsigned int  len;
522		unsigned int  timeout; /* in milliseconds */
523		void          *data;
524	};
525
526    The ``ep`` value identifies a bulk endpoint number (1 to 15, as
527    identified in an endpoint descriptor), masked with USB_DIR_IN when
528    referring to an endpoint which sends data to the host from the
529    device. The length of the data buffer is identified by ``len``; Recent
530    kernels support requests up to about 128KBytes. *FIXME say how read
531    length is returned, and how short reads are handled.*.
532
533USBDEVFS_CLEAR_HALT
534    Clears endpoint halt (stall) and resets the endpoint toggle. This is
535    only meaningful for bulk or interrupt endpoints. The ioctl parameter
536    is an integer endpoint number (1 to 15, as identified in an endpoint
537    descriptor), masked with USB_DIR_IN when referring to an endpoint
538    which sends data to the host from the device.
539
540    Use this on bulk or interrupt endpoints which have stalled,
541    returning ``-EPIPE`` status to a data transfer request. Do not issue
542    the control request directly, since that could invalidate the host's
543    record of the data toggle.
544
545USBDEVFS_CONTROL
546    Issues a control request to the device. The ioctl parameter points
547    to a structure like this::
548
549	struct usbdevfs_ctrltransfer {
550		__u8   bRequestType;
551		__u8   bRequest;
552		__u16  wValue;
553		__u16  wIndex;
554		__u16  wLength;
555		__u32  timeout;  /* in milliseconds */
556		void   *data;
557	};
558
559    The first eight bytes of this structure are the contents of the
560    SETUP packet to be sent to the device; see the USB 2.0 specification
561    for details. The bRequestType value is composed by combining a
562    ``USB_TYPE_*`` value, a ``USB_DIR_*`` value, and a ``USB_RECIP_*``
563    value (from ``linux/usb.h``). If wLength is nonzero, it describes
564    the length of the data buffer, which is either written to the device
565    (USB_DIR_OUT) or read from the device (USB_DIR_IN).
566
567    At this writing, you can't transfer more than 4 KBytes of data to or
568    from a device; usbfs has a limit, and some host controller drivers
569    have a limit. (That's not usually a problem.) *Also* there's no way
570    to say it's not OK to get a short read back from the device.
571
572USBDEVFS_RESET
573    Does a USB level device reset. The ioctl parameter is ignored. After
574    the reset, this rebinds all device interfaces. File modification
575    time is not updated by this request.
576
577.. warning::
578
579	*Avoid using this call* until some usbcore bugs get fixed, since
580	it does not fully synchronize device, interface, and driver (not
581	just usbfs) state.
582
583USBDEVFS_SETINTERFACE
584    Sets the alternate setting for an interface. The ioctl parameter is
585    a pointer to a structure like this::
586
587	struct usbdevfs_setinterface {
588		unsigned int  interface;
589		unsigned int  altsetting;
590	};
591
592    File modification time is not updated by this request.
593
594    Those struct members are from some interface descriptor applying to
595    the current configuration. The interface number is the
596    bInterfaceNumber value, and the altsetting number is the
597    bAlternateSetting value. (This resets each endpoint in the
598    interface.)
599
600USBDEVFS_SETCONFIGURATION
601    Issues the :c:func:`usb_set_configuration()` call for the
602    device. The parameter is an integer holding the number of a
603    configuration (bConfigurationValue from descriptor). File
604    modification time is not updated by this request.
605
606.. warning::
607
608	*Avoid using this call* until some usbcore bugs get fixed, since
609	it does not fully synchronize device, interface, and driver (not
610	just usbfs) state.
611
612Asynchronous I/O Support
613~~~~~~~~~~~~~~~~~~~~~~~~
614
615As mentioned above, there are situations where it may be important to
616initiate concurrent operations from user mode code. This is particularly
617important for periodic transfers (interrupt and isochronous), but it can
618be used for other kinds of USB requests too. In such cases, the
619asynchronous requests described here are essential. Rather than
620submitting one request and having the kernel block until it completes,
621the blocking is separate.
622
623These requests are packaged into a structure that resembles the URB used
624by kernel device drivers. (No POSIX Async I/O support here, sorry.) It
625identifies the endpoint type (``USBDEVFS_URB_TYPE_*``), endpoint
626(number, masked with USB_DIR_IN as appropriate), buffer and length,
627and a user "context" value serving to uniquely identify each request.
628(It's usually a pointer to per-request data.) Flags can modify requests
629(not as many as supported for kernel drivers).
630
631Each request can specify a realtime signal number (between SIGRTMIN and
632SIGRTMAX, inclusive) to request a signal be sent when the request
633completes.
634
635When usbfs returns these urbs, the status value is updated, and the
636buffer may have been modified. Except for isochronous transfers, the
637actual_length is updated to say how many bytes were transferred; if the
638USBDEVFS_URB_DISABLE_SPD flag is set ("short packets are not OK"), if
639fewer bytes were read than were requested then you get an error report::
640
641    struct usbdevfs_iso_packet_desc {
642	    unsigned int                     length;
643	    unsigned int                     actual_length;
644	    unsigned int                     status;
645    };
646
647    struct usbdevfs_urb {
648	    unsigned char                    type;
649	    unsigned char                    endpoint;
650	    int                              status;
651	    unsigned int                     flags;
652	    void                             *buffer;
653	    int                              buffer_length;
654	    int                              actual_length;
655	    int                              start_frame;
656	    int                              number_of_packets;
657	    int                              error_count;
658	    unsigned int                     signr;
659	    void                             *usercontext;
660	    struct usbdevfs_iso_packet_desc  iso_frame_desc[];
661    };
662
663For these asynchronous requests, the file modification time reflects
664when the request was initiated. This contrasts with their use with the
665synchronous requests, where it reflects when requests complete.
666
667USBDEVFS_DISCARDURB
668    *TBS* File modification time is not updated by this request.
669
670USBDEVFS_DISCSIGNAL
671    *TBS* File modification time is not updated by this request.
672
673USBDEVFS_REAPURB
674    *TBS* File modification time is not updated by this request.
675
676USBDEVFS_REAPURBNDELAY
677    *TBS* File modification time is not updated by this request.
678
679USBDEVFS_SUBMITURB
680    *TBS*
681
682The USB devices
683===============
684
685The USB devices are now exported via debugfs:
686
687-  ``/sys/kernel/debug/usb/devices`` ... a text file showing each of the USB
688   devices on known to the kernel, and their configuration descriptors.
689   You can also poll() this to learn about new devices.
690
691/sys/kernel/debug/usb/devices
692-----------------------------
693
694This file is handy for status viewing tools in user mode, which can scan
695the text format and ignore most of it. More detailed device status
696(including class and vendor status) is available from device-specific
697files. For information about the current format of this file, see below.
698
699This file, in combination with the poll() system call, can also be used
700to detect when devices are added or removed::
701
702    int fd;
703    struct pollfd pfd;
704
705    fd = open("/sys/kernel/debug/usb/devices", O_RDONLY);
706    pfd = { fd, POLLIN, 0 };
707    for (;;) {
708	/* The first time through, this call will return immediately. */
709	poll(&pfd, 1, -1);
710
711	/* To see what's changed, compare the file's previous and current
712	   contents or scan the filesystem.  (Scanning is more precise.) */
713    }
714
715Note that this behavior is intended to be used for informational and
716debug purposes. It would be more appropriate to use programs such as
717udev or HAL to initialize a device or start a user-mode helper program,
718for instance.
719
720In this file, each device's output has multiple lines of ASCII output.
721
722I made it ASCII instead of binary on purpose, so that someone
723can obtain some useful data from it without the use of an
724auxiliary program.  However, with an auxiliary program, the numbers
725in the first 4 columns of each ``T:`` line (topology info:
726Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.
727
728Each line is tagged with a one-character ID for that line::
729
730	T = Topology (etc.)
731	B = Bandwidth (applies only to USB host controllers, which are
732	virtualized as root hubs)
733	D = Device descriptor info.
734	P = Product ID info. (from Device descriptor, but they won't fit
735	together on one line)
736	S = String descriptors.
737	C = Configuration descriptor info. (* = active configuration)
738	I = Interface descriptor info.
739	E = Endpoint descriptor info.
740
741/sys/kernel/debug/usb/devices output format
742~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
743
744Legend::
745  d = decimal number (may have leading spaces or 0's)
746  x = hexadecimal number (may have leading spaces or 0's)
747  s = string
748
749
750
751Topology info
752^^^^^^^^^^^^^
753
754::
755
756	T:  Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=dddd MxCh=dd
757	|   |      |      |       |       |      |        |        |__MaxChildren
758	|   |      |      |       |       |      |        |__Device Speed in Mbps
759	|   |      |      |       |       |      |__DeviceNumber
760	|   |      |      |       |       |__Count of devices at this level
761	|   |      |      |       |__Connector/Port on Parent for this device
762	|   |      |      |__Parent DeviceNumber
763	|   |      |__Level in topology for this bus
764	|   |__Bus number
765	|__Topology info tag
766
767Speed may be:
768
769	======= ======================================================
770	1.5	Mbit/s for low speed USB
771	12	Mbit/s for full speed USB
772	480	Mbit/s for high speed USB (added for USB 2.0);
773		also used for Wireless USB, which has no fixed speed
774	5000	Mbit/s for SuperSpeed USB (added for USB 3.0)
775	======= ======================================================
776
777For reasons lost in the mists of time, the Port number is always
778too low by 1.  For example, a device plugged into port 4 will
779show up with ``Port=03``.
780
781Bandwidth info
782^^^^^^^^^^^^^^
783
784::
785
786	B:  Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
787	|   |                       |         |__Number of isochronous requests
788	|   |                       |__Number of interrupt requests
789	|   |__Total Bandwidth allocated to this bus
790	|__Bandwidth info tag
791
792Bandwidth allocation is an approximation of how much of one frame
793(millisecond) is in use.  It reflects only periodic transfers, which
794are the only transfers that reserve bandwidth.  Control and bulk
795transfers use all other bandwidth, including reserved bandwidth that
796is not used for transfers (such as for short packets).
797
798The percentage is how much of the "reserved" bandwidth is scheduled by
799those transfers.  For a low or full speed bus (loosely, "USB 1.1"),
80090% of the bus bandwidth is reserved.  For a high speed bus (loosely,
801"USB 2.0") 80% is reserved.
802
803
804Device descriptor info & Product ID info
805^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
806
807::
808
809	D:  Ver=x.xx Cls=xx(s) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
810	P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx
811
812where::
813
814	D:  Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
815	|   |        |             |      |       |       |__NumberConfigurations
816	|   |        |             |      |       |__MaxPacketSize of Default Endpoint
817	|   |        |             |      |__DeviceProtocol
818	|   |        |             |__DeviceSubClass
819	|   |        |__DeviceClass
820	|   |__Device USB version
821	|__Device info tag #1
822
823where::
824
825	P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx
826	|   |           |           |__Product revision number
827	|   |           |__Product ID code
828	|   |__Vendor ID code
829	|__Device info tag #2
830
831
832String descriptor info
833^^^^^^^^^^^^^^^^^^^^^^
834::
835
836	S:  Manufacturer=ssss
837	|   |__Manufacturer of this device as read from the device.
838	|      For USB host controller drivers (virtual root hubs) this may
839	|      be omitted, or (for newer drivers) will identify the kernel
840	|      version and the driver which provides this hub emulation.
841	|__String info tag
842
843	S:  Product=ssss
844	|   |__Product description of this device as read from the device.
845	|      For older USB host controller drivers (virtual root hubs) this
846	|      indicates the driver; for newer ones, it's a product (and vendor)
847	|      description that often comes from the kernel's PCI ID database.
848	|__String info tag
849
850	S:  SerialNumber=ssss
851	|   |__Serial Number of this device as read from the device.
852	|      For USB host controller drivers (virtual root hubs) this is
853	|      some unique ID, normally a bus ID (address or slot name) that
854	|      can't be shared with any other device.
855	|__String info tag
856
857
858
859Configuration descriptor info
860^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
861::
862
863	C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
864	| | |       |       |      |__MaxPower in mA
865	| | |       |       |__Attributes
866	| | |       |__ConfiguratioNumber
867	| | |__NumberOfInterfaces
868	| |__ "*" indicates the active configuration (others are " ")
869	|__Config info tag
870
871USB devices may have multiple configurations, each of which act
872rather differently.  For example, a bus-powered configuration
873might be much less capable than one that is self-powered.  Only
874one device configuration can be active at a time; most devices
875have only one configuration.
876
877Each configuration consists of one or more interfaces.  Each
878interface serves a distinct "function", which is typically bound
879to a different USB device driver.  One common example is a USB
880speaker with an audio interface for playback, and a HID interface
881for use with software volume control.
882
883Interface descriptor info (can be multiple per Config)
884^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
885::
886
887	I:* If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
888	| | |      |      |       |             |      |       |__Driver name
889	| | |      |      |       |             |      |          or "(none)"
890	| | |      |      |       |             |      |__InterfaceProtocol
891	| | |      |      |       |             |__InterfaceSubClass
892	| | |      |      |       |__InterfaceClass
893	| | |      |      |__NumberOfEndpoints
894	| | |      |__AlternateSettingNumber
895	| | |__InterfaceNumber
896	| |__ "*" indicates the active altsetting (others are " ")
897	|__Interface info tag
898
899A given interface may have one or more "alternate" settings.
900For example, default settings may not use more than a small
901amount of periodic bandwidth.  To use significant fractions
902of bus bandwidth, drivers must select a non-default altsetting.
903
904Only one setting for an interface may be active at a time, and
905only one driver may bind to an interface at a time.  Most devices
906have only one alternate setting per interface.
907
908
909Endpoint descriptor info (can be multiple per Interface)
910^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
911
912::
913
914	E:  Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddss
915	|   |        |            |         |__Interval (max) between transfers
916	|   |        |            |__EndpointMaxPacketSize
917	|   |        |__Attributes(EndpointType)
918	|   |__EndpointAddress(I=In,O=Out)
919	|__Endpoint info tag
920
921The interval is nonzero for all periodic (interrupt or isochronous)
922endpoints.  For high speed endpoints the transfer interval may be
923measured in microseconds rather than milliseconds.
924
925For high speed periodic endpoints, the ``EndpointMaxPacketSize`` reflects
926the per-microframe data transfer size.  For "high bandwidth"
927endpoints, that can reflect two or three packets (for up to
9283KBytes every 125 usec) per endpoint.
929
930With the Linux-USB stack, periodic bandwidth reservations use the
931transfer intervals and sizes provided by URBs, which can be less
932than those found in endpoint descriptor.
933
934Usage examples
935~~~~~~~~~~~~~~
936
937If a user or script is interested only in Topology info, for
938example, use something like ``grep ^T: /sys/kernel/debug/usb/devices``
939for only the Topology lines.  A command like
940``grep -i ^[tdp]: /sys/kernel/debug/usb/devices`` can be used to list
941only the lines that begin with the characters in square brackets,
942where the valid characters are TDPCIE.  With a slightly more able
943script, it can display any selected lines (for example, only T, D,
944and P lines) and change their output format.  (The ``procusb``
945Perl script is the beginning of this idea.  It will list only
946selected lines [selected from TBDPSCIE] or "All" lines from
947``/sys/kernel/debug/usb/devices``.)
948
949The Topology lines can be used to generate a graphic/pictorial
950of the USB devices on a system's root hub.  (See more below
951on how to do this.)
952
953The Interface lines can be used to determine what driver is
954being used for each device, and which altsetting it activated.
955
956The Configuration lines could be used to list maximum power
957(in milliamps) that a system's USB devices are using.
958For example, ``grep ^C: /sys/kernel/debug/usb/devices``.
959
960
961Here's an example, from a system which has a UHCI root hub,
962an external hub connected to the root hub, and a mouse and
963a serial converter connected to the external hub.
964
965::
966
967	T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 2
968	B:  Alloc= 28/900 us ( 3%), #Int=  2, #Iso=  0
969	D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
970	P:  Vendor=0000 ProdID=0000 Rev= 0.00
971	S:  Product=USB UHCI Root Hub
972	S:  SerialNumber=dce0
973	C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr=  0mA
974	I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
975	E:  Ad=81(I) Atr=03(Int.) MxPS=   8 Ivl=255ms
976
977	T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 4
978	D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
979	P:  Vendor=0451 ProdID=1446 Rev= 1.00
980	C:* #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=100mA
981	I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
982	E:  Ad=81(I) Atr=03(Int.) MxPS=   1 Ivl=255ms
983
984	T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 0
985	D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
986	P:  Vendor=04b4 ProdID=0001 Rev= 0.00
987	C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
988	I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse
989	E:  Ad=81(I) Atr=03(Int.) MxPS=   3 Ivl= 10ms
990
991	T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
992	D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
993	P:  Vendor=0565 ProdID=0001 Rev= 1.08
994	S:  Manufacturer=Peracom Networks, Inc.
995	S:  Product=Peracom USB to Serial Converter
996	C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=100mA
997	I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
998	E:  Ad=81(I) Atr=02(Bulk) MxPS=  64 Ivl= 16ms
999	E:  Ad=01(O) Atr=02(Bulk) MxPS=  16 Ivl= 16ms
1000	E:  Ad=82(I) Atr=03(Int.) MxPS=   8 Ivl=  8ms
1001
1002
1003Selecting only the ``T:`` and ``I:`` lines from this (for example, by using
1004``procusb ti``), we have
1005
1006::
1007
1008	T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 2
1009	T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 4
1010	I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
1011	T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 0
1012	I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse
1013	T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
1014	I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
1015
1016
1017Physically this looks like (or could be converted to)::
1018
1019                      +------------------+
1020                      |  PC/root_hub (12)|   Dev# = 1
1021                      +------------------+   (nn) is Mbps.
1022    Level 0           |  CN.0   |  CN.1  |   [CN = connector/port #]
1023                      +------------------+
1024                          /
1025                         /
1026            +-----------------------+
1027  Level 1   | Dev#2: 4-port hub (12)|
1028            +-----------------------+
1029            |CN.0 |CN.1 |CN.2 |CN.3 |
1030            +-----------------------+
1031                \           \____________________
1032                 \_____                          \
1033                       \                          \
1034               +--------------------+      +--------------------+
1035  Level 2      | Dev# 3: mouse (1.5)|      | Dev# 4: serial (12)|
1036               +--------------------+      +--------------------+
1037
1038
1039
1040Or, in a more tree-like structure (ports [Connectors] without
1041connections could be omitted)::
1042
1043	PC:  Dev# 1, root hub, 2 ports, 12 Mbps
1044	|_ CN.0:  Dev# 2, hub, 4 ports, 12 Mbps
1045	     |_ CN.0:  Dev #3, mouse, 1.5 Mbps
1046	     |_ CN.1:
1047	     |_ CN.2:  Dev #4, serial, 12 Mbps
1048	     |_ CN.3:
1049	|_ CN.1:
1050