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