Merge tag 'gpio-fixes-for-v5.13-rc3' of git://git.kernel.org/pub/scm/linux/kernel...
[linux-2.6-microblaze.git] / Documentation / driver-api / usb / usb.rst
1 .. _usb-hostside-api:
2
3 ===========================
4 The Linux-USB Host Side API
5 ===========================
6
7 Introduction to USB on Linux
8 ============================
9
10 A Universal Serial Bus (USB) is used to connect a host, such as a PC or
11 workstation, to a number of peripheral devices. USB uses a tree
12 structure, with the host as the root (the system's master), hubs as
13 interior nodes, and peripherals as leaves (and slaves). Modern PCs
14 support several such trees of USB devices, usually
15 a few USB 3.0 (5 GBit/s) or USB 3.1 (10 GBit/s) and some legacy
16 USB 2.0 (480 MBit/s) busses just in case.
17
18 That master/slave asymmetry was designed-in for a number of reasons, one
19 being ease of use. It is not physically possible to mistake upstream and
20 downstream or it does not matter with a type C plug (or they are built into the
21 peripheral). Also, the host software doesn't need to deal with
22 distributed auto-configuration since the pre-designated master node
23 manages all that.
24
25 Kernel developers added USB support to Linux early in the 2.2 kernel
26 series and have been developing it further since then. Besides support
27 for each new generation of USB, various host controllers gained support,
28 new drivers for peripherals have been added and advanced features for latency
29 measurement and improved power management introduced.
30
31 Linux can run inside USB devices as well as on the hosts that control
32 the devices. But USB device drivers running inside those peripherals
33 don't do the same things as the ones running inside hosts, so they've
34 been given a different name: *gadget drivers*. This document does not
35 cover gadget drivers.
36
37 USB Host-Side API Model
38 =======================
39
40 Host-side drivers for USB devices talk to the "usbcore" APIs. There are
41 two. One is intended for *general-purpose* drivers (exposed through
42 driver frameworks), and the other is for drivers that are *part of the
43 core*. Such core drivers include the *hub* driver (which manages trees
44 of USB devices) and several different kinds of *host controller
45 drivers*, which control individual busses.
46
47 The 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
89 Accordingly, the USB Core API exposed to device drivers covers quite a
90 lot of territory. You'll probably need to consult the USB 3.0
91 specification, available online from www.usb.org at no cost, as well as
92 class or device specifications.
93
94 The only host-side drivers that actually touch hardware (reading/writing
95 registers, handling IRQs, and so on) are the HCDs. In theory, all HCDs
96 provide the same functionality through the same API. In practice, that's
97 becoming more true, but there are still differences
98 that crop up especially with fault handling on the less common controllers.
99 Different controllers don't
100 necessarily report the same aspects of failures, and recovery from
101 faults (including software-induced ones like unlinking an URB) isn't yet
102 fully consistent. Device driver authors should make a point of doing
103 disconnect testing (while the device is active) with each different host
104 controller driver, to make sure drivers don't have bugs of their own as
105 well as to make sure they aren't relying on some HCD-specific behavior.
106
107 .. _usb_chapter9:
108
109 USB-Standard Types
110 ==================
111
112 In ``include/uapi/linux/usb/ch9.h`` you will find the USB data types defined
113 in chapter 9 of the USB specification. These data types are used throughout
114 USB, and in APIs including this host side API, gadget APIs, usb character
115 devices and debugfs interfaces. That file is itself included by
116 ``include/linux/usb/ch9.h``, which also contains declarations of a few
117 utility routines for manipulating these data types; the implementations
118 are in ``drivers/usb/common/common.c``.
119
120 .. kernel-doc:: drivers/usb/common/common.c
121    :export:
122
123 In addition, some functions useful for creating debugging output are
124 defined in ``drivers/usb/common/debug.c``.
125
126 Host-Side Data Types and Macros
127 ===============================
128
129 The host side API exposes several layers to drivers, some of which are
130 more necessary than others. These support lifecycle models for host side
131 drivers and devices, and support passing buffers through usbcore to some
132 HCD that performs the I/O for the device driver.
133
134 .. kernel-doc:: include/linux/usb.h
135    :internal:
136
137 USB Core APIs
138 =============
139
140 There are two basic I/O models in the USB API. The most elemental one is
141 asynchronous: drivers submit requests in the form of an URB, and the
142 URB's completion callback handles the next step. All USB transfer types
143 support that model, although there are special cases for control URBs
144 (which always have setup and status stages, but may not have a data
145 stage) and isochronous URBs (which allow large packets and include
146 per-packet fault reports). Built on top of that is synchronous API
147 support, where a driver calls a routine that allocates one or more URBs,
148 submits them, and waits until they complete. There are synchronous
149 wrappers for single-buffer control and bulk transfers (which are awkward
150 to use in some driver disconnect scenarios), and for scatterlist based
151 streaming i/o (bulk or interrupt).
152
153 USB drivers need to provide buffers that can be used for DMA, although
154 they don't necessarily need to provide the DMA mapping themselves. There
155 are APIs to use used when allocating DMA buffers, which can prevent use
156 of bounce buffers on some systems. In some cases, drivers may be able to
157 rely 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
177 Host Controller APIs
178 ====================
179
180 These APIs are only for use by host controller drivers, most of which
181 implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI
182 was one of the first interfaces, designed by Intel and also used by VIA;
183 it doesn't do much in hardware. OHCI was designed later, to have the
184 hardware do more work (bigger transfers, tracking protocol state, and so
185 on). EHCI was designed with USB 2.0; its design has features that
186 resemble OHCI (hardware does much more work) as well as UHCI (some parts
187 of ISO support, TD list processing). XHCI was designed with USB 3.0. It
188 continues to shift support for functionality into hardware.
189
190 There are host controllers other than the "big three", although most PCI
191 based controllers (and a few non-PCI based ones) use one of those
192 interfaces. Not all host controllers use DMA; some use PIO, and there is
193 also a simulator and a virtual host controller to pipe USB over the network.
194
195 The same basic APIs are available to drivers for all those controllers.
196 For historical reasons they are in two layers: :c:type:`struct
197 usb_bus <usb_bus>` is a rather thin layer that became available
198 in the 2.2 kernels, while :c:type:`struct usb_hcd <usb_hcd>`
199 is a more featureful layer
200 that lets HCDs share common code, to shrink driver size and
201 significantly 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
212 The USB character device nodes
213 ==============================
214
215 This chapter presents the Linux character device nodes. You may prefer
216 to avoid writing new kernel code for your USB driver. User mode device
217 drivers are usually packaged as applications or libraries, and may use
218 character devices through some programming library that wraps it.
219 Such libraries include:
220
221  - `libusb <http://libusb.sourceforge.net>`__ for C/C++, and
222  - `jUSB <http://jUSB.sourceforge.net>`__ for Java.
223
224 Some old information about it can be seen at the "USB Device Filesystem"
225 section of the USB Guide. The latest copy of the USB Guide can be found
226 at 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
237 What files are in "devtmpfs"?
238 -----------------------------
239
240 Conventionally 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
247 Each bus is given a number (``BBB``) based on when it was enumerated; within
248 each bus, each device is given a similar number (``DDD``). Those ``BBB/DDD``
249 paths are not "stable" identifiers; expect them to change even if you
250 always leave the devices plugged in to the same hub port. *Don't even
251 think of saving these in application configuration files.* Stable
252 identifiers are available, for user mode applications that want to use
253 them. HID and networking devices expose these stable IDs, so that for
254 example you can be sure that you told the right UPS to power down its
255 second server. Pleast note that it doesn't (yet) expose those IDs.
256
257 /dev/bus/usb/BBB/DDD
258 --------------------
259
260 Use 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
282 Each connected USB device has one file.  The ``BBB`` indicates the bus
283 number.  The ``DDD`` indicates the device address on that bus.  Both
284 of these numbers are assigned sequentially, and can be reused, so
285 you can't rely on them for stable access to devices.  For example,
286 it's relatively common for devices to re-enumerate while they are
287 still connected (perhaps someone jostled their power supply, hub,
288 or USB cable), so a device might be ``002/027`` when you first connect
289 it and ``002/048`` sometime later.
290
291 These files can be read as binary data.  The binary data consists
292 of first the device descriptor, then the descriptors for each
293 configuration of the device.  Multi-byte fields in the device descriptor
294 are converted to host endianness by the kernel.  The configuration
295 descriptors are in bus endian format! The configuration descriptor
296 are wTotalLength bytes apart. If a device returns less configuration
297 descriptor data than indicated by wTotalLength there will be a hole in
298 the file for the missing bytes.  This information is also shown
299 in text form by the ``/sys/kernel/debug/usb/devices`` file, described later.
300
301 These files may also be used to write user-level drivers for the USB
302 devices.  You would open the ``/dev/bus/usb/BBB/DDD`` file read/write,
303 read its descriptors to make sure it's the device you expect, and then
304 bind to an interface (or perhaps several) using an ioctl call.  You
305 would issue more ioctls to the device to communicate to it using
306 control, bulk, or other kinds of USB transfers.  The IOCTLs are
307 listed in the ``<linux/usbdevice_fs.h>`` file, and at this writing the
308 source code (``linux/drivers/usb/core/devio.c``) is the primary reference
309 for how to access devices through those files.
310
311 Note that since by default these ``BBB/DDD`` files are writable only by
312 root, only root can write such user mode drivers.  You can selectively
313 grant read/write permissions to other users by using ``chmod``.  Also,
314 usbfs mount options such as ``devmode=0666`` may be helpful.
315
316
317 Life Cycle of User Mode Drivers
318 -------------------------------
319
320 Such a driver first needs to find a device file for a device it knows
321 how to handle. Maybe it was told about it because a ``/sbin/hotplug``
322 event handling agent chose that driver to handle the new device. Or
323 maybe it's an application that scans all the ``/dev/bus/usb`` device files,
324 and ignores most devices. In either case, it should :c:func:`read()`
325 all the descriptors from the device file, and check them against what it
326 knows how to handle. It might just reject everything except a particular
327 vendor and product ID, or need a more complex policy.
328
329 Never assume there will only be one such device on the system at a time!
330 If your code can't handle more than one device at a time, at least
331 detect when there's more than one, and have your users choose which
332 device to use.
333
334 Once your user mode driver knows what device to use, it interacts with
335 it in either of two styles. The simple style is to make only control
336 requests; some devices don't need more complex interactions than those.
337 (An example might be software using vendor-specific control requests for
338 some initialization or configuration tasks, with a kernel driver for the
339 rest.)
340
341 More likely, you need a more complex style driver: one using non-control
342 endpoints, reading or writing data and claiming exclusive use of an
343 interface. *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
346 is reserved. Such "periodic" transfers are awkward to use through usbfs,
347 unless you're using the asynchronous calls. However, interrupt transfers
348 can also be used in a synchronous "one shot" style.
349
350 Your user-mode driver should never need to worry about cleaning up
351 request state when the device is disconnected, although it should close
352 its open file descriptors as soon as it starts seeing the ENODEV errors.
353
354 The ioctl() Requests
355 --------------------
356
357 To use these ioctls, you need to include the following headers in your
358 userspace program::
359
360     #include <linux/usb.h>
361     #include <linux/usbdevice_fs.h>
362     #include <asm/byteorder.h>
363
364 The standard USB device model requests, from "Chapter 9" of the USB 2.0
365 specification, are automatically included from the ``<linux/usb/ch9.h>``
366 header.
367
368 Unless noted otherwise, the ioctl requests described here will update
369 the modification time on the usbfs file to which they are applied
370 (unless they fail). A return of zero indicates success; otherwise, a
371 standard USB error code is returned (These are documented in
372 :ref:`usb-error-codes`).
373
374 Each of these files multiplexes access to several I/O streams, one per
375 endpoint. Each device has one control endpoint (endpoint zero) which
376 supports a limited RPC style RPC access. Devices are configured by
377 hub_wq (in the kernel) setting a device-wide *configuration* that
378 affects things like power consumption and basic functionality. The
379 endpoints are part of USB *interfaces*, which may have *altsettings*
380 affecting things like which endpoints are available. Many devices only
381 have a single configuration and interface, so drivers for them will
382 ignore configurations and altsettings.
383
384 Management/Status Requests
385 ~~~~~~~~~~~~~~~~~~~~~~~~~~
386
387 A number of usbfs requests don't deal very directly with device I/O.
388 They mostly relate to device management and status. These are all
389 synchronous requests.
390
391 USBDEVFS_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
405 USBDEVFS_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
421 USBDEVFS_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
433 USBDEVFS_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
470 USBDEVFS_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
483 USBDEVFS_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
497 USBDEVFS_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
506 Synchronous I/O Support
507 ~~~~~~~~~~~~~~~~~~~~~~~
508
509 Synchronous requests involve the kernel blocking until the user mode
510 request completes, either by finishing successfully or by reporting an
511 error. In most cases this is the simplest way to use usbfs, although as
512 noted above it does prevent performing I/O to more than one endpoint at
513 a time.
514
515 USBDEVFS_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
533 USBDEVFS_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
545 USBDEVFS_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
572 USBDEVFS_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
583 USBDEVFS_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
600 USBDEVFS_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
612 Asynchronous I/O Support
613 ~~~~~~~~~~~~~~~~~~~~~~~~
614
615 As mentioned above, there are situations where it may be important to
616 initiate concurrent operations from user mode code. This is particularly
617 important for periodic transfers (interrupt and isochronous), but it can
618 be used for other kinds of USB requests too. In such cases, the
619 asynchronous requests described here are essential. Rather than
620 submitting one request and having the kernel block until it completes,
621 the blocking is separate.
622
623 These requests are packaged into a structure that resembles the URB used
624 by kernel device drivers. (No POSIX Async I/O support here, sorry.) It
625 identifies the endpoint type (``USBDEVFS_URB_TYPE_*``), endpoint
626 (number, masked with USB_DIR_IN as appropriate), buffer and length,
627 and 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
631 Each request can specify a realtime signal number (between SIGRTMIN and
632 SIGRTMAX, inclusive) to request a signal be sent when the request
633 completes.
634
635 When usbfs returns these urbs, the status value is updated, and the
636 buffer may have been modified. Except for isochronous transfers, the
637 actual_length is updated to say how many bytes were transferred; if the
638 USBDEVFS_URB_DISABLE_SPD flag is set ("short packets are not OK"), if
639 fewer 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
663 For these asynchronous requests, the file modification time reflects
664 when the request was initiated. This contrasts with their use with the
665 synchronous requests, where it reflects when requests complete.
666
667 USBDEVFS_DISCARDURB
668     *TBS* File modification time is not updated by this request.
669
670 USBDEVFS_DISCSIGNAL
671     *TBS* File modification time is not updated by this request.
672
673 USBDEVFS_REAPURB
674     *TBS* File modification time is not updated by this request.
675
676 USBDEVFS_REAPURBNDELAY
677     *TBS* File modification time is not updated by this request.
678
679 USBDEVFS_SUBMITURB
680     *TBS*
681
682 The USB devices
683 ===============
684
685 The 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
694 This file is handy for status viewing tools in user mode, which can scan
695 the text format and ignore most of it. More detailed device status
696 (including class and vendor status) is available from device-specific
697 files. For information about the current format of this file, see below.
698
699 This file, in combination with the poll() system call, can also be used
700 to 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
715 Note that this behavior is intended to be used for informational and
716 debug purposes. It would be more appropriate to use programs such as
717 udev or HAL to initialize a device or start a user-mode helper program,
718 for instance.
719
720 In this file, each device's output has multiple lines of ASCII output.
721
722 I made it ASCII instead of binary on purpose, so that someone
723 can obtain some useful data from it without the use of an
724 auxiliary program.  However, with an auxiliary program, the numbers
725 in the first 4 columns of each ``T:`` line (topology info:
726 Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.
727
728 Each 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
744 Legend::
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
751 Topology 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
767 Speed 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
777 For reasons lost in the mists of time, the Port number is always
778 too low by 1.  For example, a device plugged into port 4 will
779 show up with ``Port=03``.
780
781 Bandwidth 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
792 Bandwidth allocation is an approximation of how much of one frame
793 (millisecond) is in use.  It reflects only periodic transfers, which
794 are the only transfers that reserve bandwidth.  Control and bulk
795 transfers use all other bandwidth, including reserved bandwidth that
796 is not used for transfers (such as for short packets).
797
798 The percentage is how much of the "reserved" bandwidth is scheduled by
799 those transfers.  For a low or full speed bus (loosely, "USB 1.1"),
800 90% of the bus bandwidth is reserved.  For a high speed bus (loosely,
801 "USB 2.0") 80% is reserved.
802
803
804 Device 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
812 where::
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
823 where::
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
832 String 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
859 Configuration 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
871 USB devices may have multiple configurations, each of which act
872 rather differently.  For example, a bus-powered configuration
873 might be much less capable than one that is self-powered.  Only
874 one device configuration can be active at a time; most devices
875 have only one configuration.
876
877 Each configuration consists of one or more interfaces.  Each
878 interface serves a distinct "function", which is typically bound
879 to a different USB device driver.  One common example is a USB
880 speaker with an audio interface for playback, and a HID interface
881 for use with software volume control.
882
883 Interface 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
899 A given interface may have one or more "alternate" settings.
900 For example, default settings may not use more than a small
901 amount of periodic bandwidth.  To use significant fractions
902 of bus bandwidth, drivers must select a non-default altsetting.
903
904 Only one setting for an interface may be active at a time, and
905 only one driver may bind to an interface at a time.  Most devices
906 have only one alternate setting per interface.
907
908
909 Endpoint 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
921 The interval is nonzero for all periodic (interrupt or isochronous)
922 endpoints.  For high speed endpoints the transfer interval may be
923 measured in microseconds rather than milliseconds.
924
925 For high speed periodic endpoints, the ``EndpointMaxPacketSize`` reflects
926 the per-microframe data transfer size.  For "high bandwidth"
927 endpoints, that can reflect two or three packets (for up to
928 3KBytes every 125 usec) per endpoint.
929
930 With the Linux-USB stack, periodic bandwidth reservations use the
931 transfer intervals and sizes provided by URBs, which can be less
932 than those found in endpoint descriptor.
933
934 Usage examples
935 ~~~~~~~~~~~~~~
936
937 If a user or script is interested only in Topology info, for
938 example, use something like ``grep ^T: /sys/kernel/debug/usb/devices``
939 for only the Topology lines.  A command like
940 ``grep -i ^[tdp]: /sys/kernel/debug/usb/devices`` can be used to list
941 only the lines that begin with the characters in square brackets,
942 where the valid characters are TDPCIE.  With a slightly more able
943 script, it can display any selected lines (for example, only T, D,
944 and P lines) and change their output format.  (The ``procusb``
945 Perl script is the beginning of this idea.  It will list only
946 selected lines [selected from TBDPSCIE] or "All" lines from
947 ``/sys/kernel/debug/usb/devices``.)
948
949 The Topology lines can be used to generate a graphic/pictorial
950 of the USB devices on a system's root hub.  (See more below
951 on how to do this.)
952
953 The Interface lines can be used to determine what driver is
954 being used for each device, and which altsetting it activated.
955
956 The Configuration lines could be used to list maximum power
957 (in milliamps) that a system's USB devices are using.
958 For example, ``grep ^C: /sys/kernel/debug/usb/devices``.
959
960
961 Here's an example, from a system which has a UHCI root hub,
962 an external hub connected to the root hub, and a mouse and
963 a 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
1003 Selecting 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
1017 Physically 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
1040 Or, in a more tree-like structure (ports [Connectors] without
1041 connections 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: