summaryrefslogtreecommitdiffstats
path: root/Documentation/driver-api/usb/usb.rst
blob: dba0f876b36f4dc1f52c412f82896972b36d208a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
.. _usb-hostside-api:

===========================
The Linux-USB Host Side API
===========================

Introduction to USB on Linux
============================

A Universal Serial Bus (USB) is used to connect a host, such as a PC or
workstation, to a number of peripheral devices. USB uses a tree
structure, with the host as the root (the system's master), hubs as
interior nodes, and peripherals as leaves (and slaves). Modern PCs
support several such trees of USB devices, usually
a few USB 3.0 (5 GBit/s) or USB 3.1 (10 GBit/s) and some legacy
USB 2.0 (480 MBit/s) busses just in case.

That master/slave asymmetry was designed-in for a number of reasons, one
being ease of use. It is not physically possible to mistake upstream and
downstream or it does not matter with a type C plug (or they are built into the
peripheral). Also, the host software doesn't need to deal with
distributed auto-configuration since the pre-designated master node
manages all that.

Kernel developers added USB support to Linux early in the 2.2 kernel
series and have been developing it further since then. Besides support
for each new generation of USB, various host controllers gained support,
new drivers for peripherals have been added and advanced features for latency
measurement and improved power management introduced.

Linux can run inside USB devices as well as on the hosts that control
the devices. But USB device drivers running inside those peripherals
don't do the same things as the ones running inside hosts, so they've
been given a different name: *gadget drivers*. This document does not
cover gadget drivers.

USB Host-Side API Model
=======================

Host-side drivers for USB devices talk to the "usbcore" APIs. There are
two. One is intended for *general-purpose* drivers (exposed through
driver frameworks), and the other is for drivers that are *part of the
core*. Such core drivers include the *hub* driver (which manages trees
of USB devices) and several different kinds of *host controller
drivers*, which control individual busses.

The device model seen by USB drivers is relatively complex.

-  USB supports four kinds of data transfers (control, bulk, interrupt,
   and isochronous). Two of them (control and bulk) use bandwidth as
   it's available, while the other two (interrupt and isochronous) are
   scheduled to provide guaranteed bandwidth.

-  The device description model includes one or more "configurations"
   per device, only one of which is active at a time. Devices are supposed
   to be capable of operating at lower than their top
   speeds and may provide a BOS descriptor showing the lowest speed they
   remain fully operational at.

-  From USB 3.0 on configurations have one or more "functions", which
   provide a common functionality and are grouped together for purposes
   of power management.

-  Configurations or functions have one or more "interfaces", each of which may have
   "alternate settings". Interfaces may be standardized by USB "Class"
   specifications, or may be specific to a vendor or device.

   USB device drivers actually bind to interfaces, not devices. Think of
   them as "interface drivers", though you may not see many devices
   where the distinction is important. *Most USB devices are simple,
   with only one function, one configuration, one interface, and one alternate
   setting.*

-  Interfaces have one or more "endpoints", each of which supports one
   type and direction of data transfer such as "bulk out" or "interrupt
   in". The entire configuration may have up to sixteen endpoints in
   each direction, allocated as needed among all the interfaces.

-  Data transfer on USB is packetized; each endpoint has a maximum
   packet size. Drivers must often be aware of conventions such as
   flagging the end of bulk transfers using "short" (including zero
   length) packets.

-  The Linux USB API supports synchronous calls for control and bulk
   messages. It also supports asynchronous calls for all kinds of data
   transfer, using request structures called "URBs" (USB Request
   Blocks).

Accordingly, the USB Core API exposed to device drivers covers quite a
lot of territory. You'll probably need to consult the USB 3.0
specification, available online from www.usb.org at no cost, as well as
class or device specifications.

The only host-side drivers that actually touch hardware (reading/writing
registers, handling IRQs, and so on) are the HCDs. In theory, all HCDs
provide the same functionality through the same API. In practice, that's
becoming more true, but there are still differences
that crop up especially with fault handling on the less common controllers.
Different controllers don't
necessarily report the same aspects of failures, and recovery from
faults (including software-induced ones like unlinking an URB) isn't yet
fully consistent. Device driver authors should make a point of doing
disconnect testing (while the device is active) with each different host
controller driver, to make sure drivers don't have bugs of their own as
well as to make sure they aren't relying on some HCD-specific behavior.

.. _usb_chapter9:

USB-Standard Types
==================

In ``<linux/usb/ch9.h>`` you will find the USB data types defined in
chapter 9 of the USB specification. These data types are used throughout
USB, and in APIs including this host side API, gadget APIs, usb character
devices and debugfs interfaces.

.. kernel-doc:: include/linux/usb/ch9.h
   :internal:

.. _usb_header:

Host-Side Data Types and Macros
===============================

The host side API exposes several layers to drivers, some of which are
more necessary than others. These support lifecycle models for host side
drivers and devices, and support passing buffers through usbcore to some
HCD that performs the I/O for the device driver.

.. kernel-doc:: include/linux/usb.h
   :internal:

USB Core APIs
=============

There are two basic I/O models in the USB API. The most elemental one is
asynchronous: drivers submit requests in the form of an URB, and the
URB's completion callback handles the next step. All USB transfer types
support that model, although there are special cases for control URBs
(which always have setup and status stages, but may not have a data
stage) and isochronous URBs (which allow large packets and include
per-packet fault reports). Built on top of that is synchronous API
support, where a driver calls a routine that allocates one or more URBs,
submits them, and waits until they complete. There are synchronous
wrappers for single-buffer control and bulk transfers (which are awkward
to use in some driver disconnect scenarios), and for scatterlist based
streaming i/o (bulk or interrupt).

USB drivers need to provide buffers that can be used for DMA, although
they don't necessarily need to provide the DMA mapping themselves. There
are APIs to use used when allocating DMA buffers, which can prevent use
of bounce buffers on some systems. In some cases, drivers may be able to
rely on 64bit DMA to eliminate another kind of bounce buffer.

.. kernel-doc:: drivers/usb/core/urb.c
   :export:

.. kernel-doc:: drivers/usb/core/message.c
   :export:

.. kernel-doc:: drivers/usb/core/file.c
   :export:

.. kernel-doc:: drivers/usb/core/driver.c
   :export:

.. kernel-doc:: drivers/usb/core/usb.c
   :export:

.. kernel-doc:: drivers/usb/core/hub.c
   :export:

Host Controller APIs
====================

These APIs are only for use by host controller drivers, most of which
implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI
was one of the first interfaces, designed by Intel and also used by VIA;
it doesn't do much in hardware. OHCI was designed later, to have the
hardware do more work (bigger transfers, tracking protocol state, and so
on). EHCI was designed with USB 2.0; its design has features that
resemble OHCI (hardware does much more work) as well as UHCI (some parts
of ISO support, TD list processing). XHCI was designed with USB 3.0. It
continues to shift support for functionality into hardware.

There are host controllers other than the "big three", although most PCI
based controllers (and a few non-PCI based ones) use one of those
interfaces. Not all host controllers use DMA; some use PIO, and there is
also a simulator and a virtual host controller to pipe USB over the network.

The same basic APIs are available to drivers for all those controllers.
For historical reasons they are in two layers: :c:type:`struct
usb_bus <usb_bus>` is a rather thin layer that became available
in the 2.2 kernels, while :c:type:`struct usb_hcd <usb_hcd>`
is a more featureful layer
that lets HCDs share common code, to shrink driver size and
significantly reduce hcd-specific behaviors.

.. kernel-doc:: drivers/usb/core/hcd.c
   :export:

.. kernel-doc:: drivers/usb/core/hcd-pci.c
   :export:

.. kernel-doc:: drivers/usb/core/buffer.c
   :internal:

The USB character device nodes
==============================

This chapter presents the Linux character device nodes. You may prefer
to avoid writing new kernel code for your USB driver. User mode device
drivers are usually packaged as applications or libraries, and may use
character devices through some programming library that wraps it.
Such libraries include:

 - `libusb <http://libusb.sourceforge.net>`__ for C/C++, and
 - `jUSB <http://jUSB.sourceforge.net>`__ for Java.

Some old information about it can be seen at the "USB Device Filesystem"
section of the USB Guide. The latest copy of the USB Guide can be found
at http://www.linux-usb.org/

.. note::

  - They were used to be implemented via *usbfs*, but this is not part of
    the sysfs debug interface.

   - This particular documentation is incomplete, especially with respect
     to the asynchronous mode. As of kernel 2.5.66 the code and this
     (new) documentation need to be cross-reviewed.

What files are in "devtmpfs"?
-----------------------------

Conventionally mounted at ``/dev/bus/usb/``, usbfs features include:

-  ``/dev/bus/usb/BBB/DDD`` ... magic files exposing the each device's
   configuration descriptors, and supporting a series of ioctls for
   making device requests, including I/O to devices. (Purely for access
   by programs.)

Each bus is given a number (``BBB``) based on when it was enumerated; within
each bus, each device is given a similar number (``DDD``). Those ``BBB/DDD``
paths are not "stable" identifiers; expect them to change even if you
always leave the devices plugged in to the same hub port. *Don't even
think of saving these in application configuration files.* Stable
identifiers are available, for user mode applications that want to use
them. HID and networking devices expose these stable IDs, so that for
example you can be sure that you told the right UPS to power down its
second server. Pleast note that it doesn't (yet) expose those IDs.

/dev/bus/usb/BBB/DDD
--------------------

Use these files in one of these basic ways:

- *They can be read,* producing first the device descriptor (18 bytes) and
  then the descriptors for the current configuration. See the USB 2.0 spec
  for details about those binary data formats. You'll need to convert most
  multibyte values from little endian format to your native host byte
  order, although a few of the fields in the device descriptor (both of
  the BCD-encoded fields, and the vendor and product IDs) will be
  byteswapped for you. Note that configuration descriptors include
  descriptors for interfaces, altsettings, endpoints, and maybe additional
  class descriptors.

- *Perform USB operations* using *ioctl()* requests to make endpoint I/O
  requests (synchronously or asynchronously) or manage the device. These
  requests need the ``CAP_SYS_RAWIO`` capability, as well as filesystem
  access permissions. Only one ioctl request can be made on one of these
  device files at a time. This means that if you are synchronously reading
  an endpoint from one thread, you won't be able to write to a different
  endpoint from another thread until the read completes. This works for
  *half duplex* protocols, but otherwise you'd use asynchronous i/o
  requests.

Each connected USB device has one file.  The ``BBB`` indicates the bus
number.  The ``DDD`` indicates the device address on that bus.  Both
of these numbers are assigned sequentially, and can be reused, so
you can't rely on them for stable access to devices.  For example,
it's relatively common for devices to re-enumerate while they are
still connected (perhaps someone jostled their power supply, hub,
or USB cable), so a device might be ``002/027`` when you first connect
it and ``002/048`` sometime later.

These files can be read as binary data.  The binary data consists
of first the device descriptor, then the descriptors for each
configuration of the device.  Multi-byte fields in the device descriptor
are converted to host endianness by the kernel.  The configuration
descriptors are in bus endian format! The configuration descriptor
are wTotalLength bytes apart. If a device returns less configuration
descriptor data than indicated by wTotalLength there will be a hole in
the file for the missing bytes.  This information is also shown
in text form by the ``/sys/kernel/debug/usb/devices`` file, described later.

These files may also be used to write user-level drivers for the USB
devices.  You would open the ``/dev/bus/usb/BBB/DDD`` file read/write,
read its descriptors to make sure it's the device you expect, and then
bind to an interface (or perhaps several) using an ioctl call.  You
would issue more ioctls to the device to communicate to it using
control, bulk, or other kinds of USB transfers.  The IOCTLs are
listed in the ``<linux/usbdevice_fs.h>`` file, and at this writing the
source code (``linux/drivers/usb/core/devio.c``) is the primary reference
for how to access devices through those files.

Note that since by default these ``BBB/DDD`` files are writable only by
root, only root can write such user mode drivers.  You can selectively
grant read/write permissions to other users by using ``chmod``.  Also,
usbfs mount options such as ``devmode=0666`` may be helpful.


Life Cycle of User Mode Drivers
-------------------------------

Such a driver first needs to find a device file for a device it knows
how to handle. Maybe it was told about it because a ``/sbin/hotplug``
event handling agent chose that driver to handle the new device. Or
maybe it's an application that scans all the ``/dev/bus/usb`` device files,
and ignores most devices. In either case, it should :c:func:`read()`
all the descriptors from the device file, and check them against what it
knows how to handle. It might just reject everything except a particular
vendor and product ID, or need a more complex policy.

Never assume there will only be one such device on the system at a time!
If your code can't handle more than one device at a time, at least
detect when there's more than one, and have your users choose which
device to use.

Once your user mode driver knows what device to use, it interacts with
it in either of two styles. The simple style is to make only control
requests; some devices don't need more complex interactions than those.
(An example might be software using vendor-specific control requests for
some initialization or configuration tasks, with a kernel driver for the
rest.)

More likely, you need a more complex style driver: one using non-control
endpoints, reading or writing data and claiming exclusive use of an
interface. *Bulk* transfers are easiest to use, but only their sibling
*interrupt* transfers work with low speed devices. Both interrupt and
*isochronous* transfers offer service guarantees because their bandwidth
is reserved. Such "periodic" transfers are awkward to use through usbfs,
unless you're using the asynchronous calls. However, interrupt transfers
can also be used in a synchronous "one shot" style.

Your user-mode driver should never need to worry about cleaning up
request state when the device is disconnected, although it should close
its open file descriptors as soon as it starts seeing the ENODEV errors.

The ioctl() Requests
--------------------

To use these ioctls, you need to include the following headers in your
userspace program::

    #include <linux/usb.h>
    #include <linux/usbdevice_fs.h>
    #include <asm/byteorder.h>

The standard USB device model requests, from "Chapter 9" of the USB 2.0
specification, are automatically included from the ``<linux/usb/ch9.h>``
header.

Unless noted otherwise, the ioctl requests described here will update
the modification time on the usbfs file to which they are applied
(unless they fail). A return of zero indicates success; otherwise, a
standard USB error code is returned (These are documented in
:ref:`usb-error-codes`).

Each of these files multiplexes access to several I/O streams, one per
endpoint. Each device has one control endpoint (endpoint zero) which
supports a limited RPC style RPC access. Devices are configured by
hub_wq (in the kernel) setting a device-wide *configuration* that
affects things like power consumption and basic functionality. The
endpoints are part of USB *interfaces*, which may have *altsettings*
affecting things like which endpoints are available. Many devices only
have a single configu