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