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