Documentation/driver-api/usb/usb.rst GitHub 원문 ↗

Linux 6.18.37 · Driver API

The Linux-USB Host Side API

Linux USB 호스트 측 드라이버 모델, usbcore·HCD API, usbfs 문자 장치 ioctl과 debugfs 장치 토폴로지 형식을 설명하는 한국어 전문 번역입니다.

Source pathDocumentation/driver-api/usb/usb.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

usb.rst:1-1057

Linux USB 호스트 측 API는 인터페이스 드라이버와 HCD 사이의 usbcore 모델, URB·동기 I/O, 사용자 공간 usbfs ioctl, debugfs 토폴로지를 한 문서에 연결합니다. 장치 경로는 불안정하므로 descriptor와 stable identity를 확인하고 endpoint·altsetting·bandwidth·disconnect 규칙을 지켜야 합니다.

문서 구성
원문 줄핵심 내용
1-36USB 호스트 트리와 범위
37-108usbcore 드라이버 모델
109-138Chapter 9 형식·매크로
139-179USB core I/O API
180-214Host Controller API
215-259문자 노드·devtmpfs
260-319BBB/DDD 장치 파일
320-356사용자 드라이버 수명주기
357-386ioctl 공통 규칙
387-514관리·상태 ioctl
515-620동기 I/O
621-690비동기 I/O
691-749debugfs devices·tag
750-788토폴로지 형식
789-811대역폭 형식
812-839장치·제품 형식
840-866문자열 형식
867-890구성 형식
891-916인터페이스 형식
917-941엔드포인트 형식
942-1024사용 예·샘플 출력
1025-1057토폴로지 도식

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
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) buses 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 buses.
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 .. _usb_header:
127
128 Host-Side Data Types and Macros
129 ===============================
130
131 The host side API exposes several layers to drivers, some of which are
132 more necessary than others. These support lifecycle models for host side
133 drivers and devices, and support passing buffers through usbcore to some
134 HCD that performs the I/O for the device driver.
135
136 .. kernel-doc:: include/linux/usb.h
137 :internal:
138
139 USB Core APIs
140 =============
141
142 There are two basic I/O models in the USB API. The most elemental one is
143 asynchronous: drivers submit requests in the form of an URB, and the
144 URB's completion callback handles the next step. All USB transfer types
145 support that model, although there are special cases for control URBs
146 (which always have setup and status stages, but may not have a data
147 stage) and isochronous URBs (which allow large packets and include
148 per-packet fault reports). Built on top of that is synchronous API
149 support, where a driver calls a routine that allocates one or more URBs,
150 submits them, and waits until they complete. There are synchronous
151 wrappers for single-buffer control and bulk transfers (which are awkward
152 to use in some driver disconnect scenarios), and for scatterlist based
153 streaming i/o (bulk or interrupt).
154
155 USB drivers need to provide buffers that can be used for DMA, although
156 they don't necessarily need to provide the DMA mapping themselves. There
157 are APIs to use used when allocating DMA buffers, which can prevent use
158 of bounce buffers on some systems. In some cases, drivers may be able to
159 rely 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
180 Host Controller APIs
181 ====================
182
183 These APIs are only for use by host controller drivers, most of which
184 implement standard register interfaces such as XHCI, EHCI, OHCI, or UHCI. UHCI
185 was one of the first interfaces, designed by Intel and also used by VIA;
186 it doesn't do much in hardware. OHCI was designed later, to have the
187 hardware do more work (bigger transfers, tracking protocol state, and so
188 on). EHCI was designed with USB 2.0; its design has features that
189 resemble OHCI (hardware does much more work) as well as UHCI (some parts
190 of ISO support, TD list processing). XHCI was designed with USB 3.0. It
191 continues to shift support for functionality into hardware.
192
193 There are host controllers other than the "big three", although most PCI
194 based controllers (and a few non-PCI based ones) use one of those
195 interfaces. Not all host controllers use DMA; some use PIO, and there is
196 also a simulator and a virtual host controller to pipe USB over the network.
197
198 The same basic APIs are available to drivers for all those controllers.
199 For historical reasons they are in two layers: :c:type:`struct
200 usb_bus <usb_bus>` is a rather thin layer that became available
201 in the 2.2 kernels, while :c:type:`struct usb_hcd <usb_hcd>`
202 is a more featureful layer
203 that lets HCDs share common code, to shrink driver size and
204 significantly 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
215 The USB character device nodes
216 ==============================
217
218 This chapter presents the Linux character device nodes. You may prefer
219 to avoid writing new kernel code for your USB driver. User mode device
220 drivers are usually packaged as applications or libraries, and may use
221 character devices through some programming library that wraps it.
222 Such libraries include:
223
224 - `libusb <http://libusb.sourceforge.net>`__ for C/C++, and
225 - `jUSB <http://jUSB.sourceforge.net>`__ for Java.
226
227 Some old information about it can be seen at the "USB Device Filesystem"
228 section of the USB Guide. The latest copy of the USB Guide can be found
229 at 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
240 What files are in "devtmpfs"?
241 -----------------------------
242
243 Conventionally 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
250 Each bus is given a number (``BBB``) based on when it was enumerated; within
251 each bus, each device is given a similar number (``DDD``). Those ``BBB/DDD``
252 paths are not "stable" identifiers; expect them to change even if you
253 always leave the devices plugged in to the same hub port. *Don't even
254 think of saving these in application configuration files.* Stable
255 identifiers are available, for user mode applications that want to use
256 them. HID and networking devices expose these stable IDs, so that for
257 example you can be sure that you told the right UPS to power down its
258 second server. Pleast note that it doesn't (yet) expose those IDs.
259
260 /dev/bus/usb/BBB/DDD
261 --------------------
262
263 Use 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
285 Each connected USB device has one file. The ``BBB`` indicates the bus
286 number. The ``DDD`` indicates the device address on that bus. Both
287 of these numbers are assigned sequentially, and can be reused, so
288 you can't rely on them for stable access to devices. For example,
289 it's relatively common for devices to re-enumerate while they are
290 still connected (perhaps someone jostled their power supply, hub,
291 or USB cable), so a device might be ``002/027`` when you first connect
292 it and ``002/048`` sometime later.
293
294 These files can be read as binary data. The binary data consists
295 of first the device descriptor, then the descriptors for each
296 configuration of the device. Multi-byte fields in the device descriptor
297 are converted to host endianness by the kernel. The configuration
298 descriptors are in bus endian format! The configuration descriptor
299 are wTotalLength bytes apart. If a device returns less configuration
300 descriptor data than indicated by wTotalLength there will be a hole in
301 the file for the missing bytes. This information is also shown
302 in text form by the ``/sys/kernel/debug/usb/devices`` file, described later.
303
304 These files may also be used to write user-level drivers for the USB
305 devices. You would open the ``/dev/bus/usb/BBB/DDD`` file read/write,
306 read its descriptors to make sure it's the device you expect, and then
307 bind to an interface (or perhaps several) using an ioctl call. You
308 would issue more ioctls to the device to communicate to it using
309 control, bulk, or other kinds of USB transfers. The IOCTLs are
310 listed in the ``<linux/usbdevice_fs.h>`` file, and at this writing the
311 source code (``linux/drivers/usb/core/devio.c``) is the primary reference
312 for how to access devices through those files.
313
314 Note that since by default these ``BBB/DDD`` files are writable only by
315 root, only root can write such user mode drivers. You can selectively
316 grant read/write permissions to other users by using ``chmod``. Also,
317 usbfs mount options such as ``devmode=0666`` may be helpful.
318
319
320 Life Cycle of User Mode Drivers
321 -------------------------------
322
323 Such a driver first needs to find a device file for a device it knows
324 how to handle. Maybe it was told about it because a ``/sbin/hotplug``
325 event handling agent chose that driver to handle the new device. Or
326 maybe it's an application that scans all the ``/dev/bus/usb`` device files,
327 and ignores most devices. In either case, it should :c:func:`read()`
328 all the descriptors from the device file, and check them against what it
329 knows how to handle. It might just reject everything except a particular
330 vendor and product ID, or need a more complex policy.
331
332 Never assume there will only be one such device on the system at a time!
333 If your code can't handle more than one device at a time, at least
334 detect when there's more than one, and have your users choose which
335 device to use.
336
337 Once your user mode driver knows what device to use, it interacts with
338 it in either of two styles. The simple style is to make only control
339 requests; some devices don't need more complex interactions than those.
340 (An example might be software using vendor-specific control requests for
341 some initialization or configuration tasks, with a kernel driver for the
342 rest.)
343
344 More likely, you need a more complex style driver: one using non-control
345 endpoints, reading or writing data and claiming exclusive use of an
346 interface. *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
349 is reserved. Such "periodic" transfers are awkward to use through usbfs,
350 unless you're using the asynchronous calls. However, interrupt transfers
351 can also be used in a synchronous "one shot" style.
352
353 Your user-mode driver should never need to worry about cleaning up
354 request state when the device is disconnected, although it should close
355 its open file descriptors as soon as it starts seeing the ENODEV errors.
356
357 The ioctl() Requests
358 --------------------
359
360 To use these ioctls, you need to include the following headers in your
361 userspace program::
362
363 #include <linux/usb.h>
364 #include <linux/usbdevice_fs.h>
365 #include <asm/byteorder.h>
366
367 The standard USB device model requests, from "Chapter 9" of the USB 2.0
368 specification, are automatically included from the ``<linux/usb/ch9.h>``
369 header.
370
371 Unless noted otherwise, the ioctl requests described here will update
372 the modification time on the usbfs file to which they are applied
373 (unless they fail). A return of zero indicates success; otherwise, a
374 standard USB error code is returned (These are documented in
375 :ref:`usb-error-codes`).
376
377 Each of these files multiplexes access to several I/O streams, one per
378 endpoint. Each device has one control endpoint (endpoint zero) which
379 supports a limited RPC style RPC access. Devices are configured by
380 hub_wq (in the kernel) setting a device-wide *configuration* that
381 affects things like power consumption and basic functionality. The
382 endpoints are part of USB *interfaces*, which may have *altsettings*
383 affecting things like which endpoints are available. Many devices only
384 have a single configuration and interface, so drivers for them will
385 ignore configurations and altsettings.
386
387 Management/Status Requests
388 ~~~~~~~~~~~~~~~~~~~~~~~~~~
389
390 A number of usbfs requests don't deal very directly with device I/O.
391 They mostly relate to device management and status. These are all
392 synchronous requests.
393
394 USBDEVFS_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
408 USBDEVFS_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
424 USBDEVFS_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
430 USBDEVFS_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
442 USBDEVFS_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
479 USBDEVFS_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
492 USBDEVFS_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
506 USBDEVFS_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
515 Synchronous I/O Support
516 ~~~~~~~~~~~~~~~~~~~~~~~
517
518 Synchronous requests involve the kernel blocking until the user mode
519 request completes, either by finishing successfully or by reporting an
520 error. In most cases this is the simplest way to use usbfs, although as
521 noted above it does prevent performing I/O to more than one endpoint at
522 a time.
523
524 USBDEVFS_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
542 USBDEVFS_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
554 USBDEVFS_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
581 USBDEVFS_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
592 USBDEVFS_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
609 USBDEVFS_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
621 Asynchronous I/O Support
622 ~~~~~~~~~~~~~~~~~~~~~~~~
623
624 As mentioned above, there are situations where it may be important to
625 initiate concurrent operations from user mode code. This is particularly
626 important for periodic transfers (interrupt and isochronous), but it can
627 be used for other kinds of USB requests too. In such cases, the
628 asynchronous requests described here are essential. Rather than
629 submitting one request and having the kernel block until it completes,
630 the blocking is separate.
631
632 These requests are packaged into a structure that resembles the URB used
633 by kernel device drivers. (No POSIX Async I/O support here, sorry.) It
634 identifies the endpoint type (``USBDEVFS_URB_TYPE_*``), endpoint
635 (number, masked with USB_DIR_IN as appropriate), buffer and length,
636 and 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
640 Each request can specify a realtime signal number (between SIGRTMIN and
641 SIGRTMAX, inclusive) to request a signal be sent when the request
642 completes.
643
644 When usbfs returns these urbs, the status value is updated, and the
645 buffer may have been modified. Except for isochronous transfers, the
646 actual_length is updated to say how many bytes were transferred; if the
647 USBDEVFS_URB_DISABLE_SPD flag is set ("short packets are not OK"), if
648 fewer 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
672 For these asynchronous requests, the file modification time reflects
673 when the request was initiated. This contrasts with their use with the
674 synchronous requests, where it reflects when requests complete.
675
676 USBDEVFS_DISCARDURB
677 *TBS* File modification time is not updated by this request.
678
679 USBDEVFS_DISCSIGNAL
680 *TBS* File modification time is not updated by this request.
681
682 USBDEVFS_REAPURB
683 *TBS* File modification time is not updated by this request.
684
685 USBDEVFS_REAPURBNDELAY
686 *TBS* File modification time is not updated by this request.
687
688 USBDEVFS_SUBMITURB
689 *TBS*
690
691 The USB devices
692 ===============
693
694 The 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
703 This file is handy for status viewing tools in user mode, which can scan
704 the text format and ignore most of it. More detailed device status
705 (including class and vendor status) is available from device-specific
706 files. For information about the current format of this file, see below.
707
708 This file, in combination with the poll() system call, can also be used
709 to 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
724 Note that this behavior is intended to be used for informational and
725 debug purposes. It would be more appropriate to use programs such as
726 udev or HAL to initialize a device or start a user-mode helper program,
727 for instance.
728
729 In this file, each device's output has multiple lines of ASCII output.
730
731 I made it ASCII instead of binary on purpose, so that someone
732 can obtain some useful data from it without the use of an
733 auxiliary program. However, with an auxiliary program, the numbers
734 in the first 4 columns of each ``T:`` line (topology info:
735 Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.
736
737 Each 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
753 Legend::
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
760 Topology 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
776 Speed 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
785 For reasons lost in the mists of time, the Port number is always
786 too low by 1. For example, a device plugged into port 4 will
787 show up with ``Port=03``.
788
789 Bandwidth 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
800 Bandwidth allocation is an approximation of how much of one frame
801 (millisecond) is in use. It reflects only periodic transfers, which
802 are the only transfers that reserve bandwidth. Control and bulk
803 transfers use all other bandwidth, including reserved bandwidth that
804 is not used for transfers (such as for short packets).
805
806 The percentage is how much of the "reserved" bandwidth is scheduled by
807 those transfers. For a low or full speed bus (loosely, "USB 1.1"),
808 90% of the bus bandwidth is reserved. For a high speed bus (loosely,
809 "USB 2.0") 80% is reserved.
810
811
812 Device 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
820 where::
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
831 where::
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
840 String 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
867 Configuration 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
879 USB devices may have multiple configurations, each of which act
880 rather differently. For example, a bus-powered configuration
881 might be much less capable than one that is self-powered. Only
882 one device configuration can be active at a time; most devices
883 have only one configuration.
884
885 Each configuration consists of one or more interfaces. Each
886 interface serves a distinct "function", which is typically bound
887 to a different USB device driver. One common example is a USB
888 speaker with an audio interface for playback, and a HID interface
889 for use with software volume control.
890
891 Interface 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
907 A given interface may have one or more "alternate" settings.
908 For example, default settings may not use more than a small
909 amount of periodic bandwidth. To use significant fractions
910 of bus bandwidth, drivers must select a non-default altsetting.
911
912 Only one setting for an interface may be active at a time, and
913 only one driver may bind to an interface at a time. Most devices
914 have only one alternate setting per interface.
915
916
917 Endpoint 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
929 The interval is nonzero for all periodic (interrupt or isochronous)
930 endpoints. For high speed endpoints the transfer interval may be
931 measured in microseconds rather than milliseconds.
932
933 For high speed periodic endpoints, the ``EndpointMaxPacketSize`` reflects
934 the per-microframe data transfer size. For "high bandwidth"
935 endpoints, that can reflect two or three packets (for up to
936 3KBytes every 125 usec) per endpoint.
937
938 With the Linux-USB stack, periodic bandwidth reservations use the
939 transfer intervals and sizes provided by URBs, which can be less
940 than those found in endpoint descriptor.
941
942 Usage examples
943 ~~~~~~~~~~~~~~
944
945 If a user or script is interested only in Topology info, for
946 example, use something like ``grep ^T: /sys/kernel/debug/usb/devices``
947 for only the Topology lines. A command like
948 ``grep -i ^[tdp]: /sys/kernel/debug/usb/devices`` can be used to list
949 only the lines that begin with the characters in square brackets,
950 where the valid characters are TDPCIE. With a slightly more able
951 script, it can display any selected lines (for example, only T, D,
952 and P lines) and change their output format. (The ``procusb``
953 Perl script is the beginning of this idea. It will list only
954 selected lines [selected from TBDPSCIE] or "All" lines from
955 ``/sys/kernel/debug/usb/devices``.)
956
957 The Topology lines can be used to generate a graphic/pictorial
958 of the USB devices on a system's root hub. (See more below
959 on how to do this.)
960
961 The Interface lines can be used to determine what driver is
962 being used for each device, and which altsetting it activated.
963
964 The Configuration lines could be used to list maximum power
965 (in milliamps) that a system's USB devices are using.
966 For example, ``grep ^C: /sys/kernel/debug/usb/devices``.
967
968
969 Here's an example, from a system which has a UHCI root hub,
970 an external hub connected to the root hub, and a mouse and
971 a 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
1011 Selecting only the ``T:`` and ``I:`` lines from this (for example, by using
1012 ``procusb ti``), we have
1014 ::
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
1025 Physically this looks like (or could be converted to)::
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 +--------------------+ +--------------------+
1048 Or, in a more tree-like structure (ports [Connectors] without
1049 connections could be omitted)::
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:

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Linux USB host-side API 소개

1-36

USB는 PC나 workstation 같은 host에 여러 peripheral device를 연결합니다. Topology는 host가 root이자 system master, hub가 interior node, peripheral이 leaf이자 slave인 tree 구조입니다.

현대 PC는 보통 여러 USB tree를 제공하며 USB 3.0은 5 Gbit/s, USB 3.1은 10 Gbit/s, legacy USB 2.0은 480 Mbit/s bus를 사용합니다.

Master·slave 비대칭은 사용 편의성을 위해 설계되었습니다. Upstream과 downstream connector를 물리적으로 혼동하기 어렵고 Type-C plug에서는 방향이 중요하지 않으며, 미리 정해진 master가 auto-configuration을 관리하므로 host software가 distributed configuration을 처리할 필요도 없습니다.

Linux USB 지원은 2.2 kernel 초기에 추가된 뒤 USB 세대, host controller, peripheral driver 지원과 latency 측정·power management 기능이 계속 확장되었습니다.

Linux는 USB host뿐 아니라 USB device 내부에서도 실행될 수 있습니다. Peripheral 내부 driver는 host-side driver와 역할이 달라 `gadget driver`라고 부르며 이 문서의 범위에는 포함되지 않습니다.

USB host tree
Host·rootSystem master와 host controller
USB bus treeUSB 3.1·3.0·2.0 bus
Hub interior nodePort 확장과 child 관리
Peripheral leafDevice·slave endpoint 제공
Linux gadget sidePeripheral 내부 driver, 별도 API

Host가 bus를 통제하고 hub를 거쳐 peripheral leaf를 관리합니다.

.. _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) buses 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.

Usbcore, interface driver와 transfer model

37-108

Host-side USB device driver는 `usbcore` API와 통신합니다. 하나는 driver framework를 통해 노출되는 general-purpose driver용이고, 다른 하나는 USB tree를 관리하는 hub driver나 개별 bus를 제어하는 host controller driver처럼 core 일부인 driver용입니다.

USB transfer는 control, bulk, interrupt, isochronous 네 종류입니다. Control과 bulk는 남는 bandwidth를 사용하고 interrupt와 isochronous는 bandwidth를 예약해 service를 보장합니다.

Device는 하나 이상의 configuration을 가지며 한 번에 하나만 active입니다. 최고 속도보다 낮은 속도에서도 동작해야 하고, 완전한 기능을 유지하는 최저 속도를 BOS descriptor로 알릴 수 있습니다. USB 3.0 이후 configuration에는 power management 단위로 묶이는 하나 이상의 function이 있습니다.

Configuration 또는 function에는 interface가 있고 interface는 alternate setting을 가질 수 있습니다. Interface는 USB Class specification이나 vendor·device별 규격으로 정의됩니다. USB device driver는 device가 아니라 interface에 bind됩니다. 다만 대부분의 단순 device는 function·configuration·interface·alternate setting이 각각 하나뿐입니다.

Interface는 transfer type과 direction을 정의하는 endpoint를 하나 이상 가집니다. Configuration 전체에서 각 direction마다 최대 16 endpoint를 interface들에 배분할 수 있습니다.

USB data는 packet 단위이며 endpoint마다 maximum packet size가 있습니다. Bulk transfer 끝은 short packet 또는 zero-length packet으로 표시할 수 있어 driver가 convention을 알아야 합니다.

Linux USB API는 control·bulk message용 synchronous call과 모든 transfer type에 사용하는 URB 기반 asynchronous call을 제공합니다. Driver 개발에는 USB 3.0 specification과 해당 class·device specification을 함께 참고해야 합니다.

실제 register I/O와 IRQ를 다루는 host-side driver는 HCD뿐입니다. HCD API는 공통이지만 덜 일반적인 controller의 fault reporting과 URB unlink 같은 recovery에는 차이가 남아 있으므로 device driver는 active disconnect를 여러 HCD에서 시험해 HCD-specific behavior에 의존하지 않는지 확인해야 합니다.

USB host-side object와 transfer
계층·종류핵심 규칙
Configuration여러 개 가능, 한 번에 하나 active
FunctionUSB 3.0+, power management 단위
InterfaceDriver bind 단위, alternate setting 보유
EndpointType·direction·maximum packet size
Control·BulkAvailable bandwidth 사용
Interrupt·IsochronousPeriodic bandwidth 예약
Synchronous APIControl·bulk wrapper
Asynchronous API모든 transfer type의 URB
HCDHardware register·IRQ 담당, controller별 fault 차이 시험

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 buses.

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 Chapter 9 type과 host data macro

109-138

`include/uapi/linux/usb/ch9.h`에는 USB specification Chapter 9의 표준 data type이 정의되어 있습니다. 이 type은 host-side API, gadget API, USB character device와 debugfs interface 전반에서 사용됩니다.

UAPI header는 `include/linux/usb/ch9.h`에서 include되며 kernel header에는 이 data type을 조작하는 utility routine 선언도 있습니다. 구현은 `drivers/usb/common/common.c`에 있고 debugging output helper는 `drivers/usb/common/debug.c`에 정의됩니다.

Host-side API는 driver·device lifecycle과 buffer를 usbcore에서 실제 I/O를 수행하는 HCD까지 전달하는 여러 layer의 data type과 macro를 노출합니다. 내부 정의는 `include/linux/usb.h` kernel-doc에 정리되어 있습니다.

USB 표준 type source
Source path역할
`include/uapi/linux/usb/ch9.h`USB Chapter 9 UAPI data type
`include/linux/usb/ch9.h`Kernel include와 utility 선언
`drivers/usb/common/common.c`표준 type utility 구현
`drivers/usb/common/debug.c`Debug output helper
`include/linux/usb.h`Host-side lifecycle·buffer type와 macro

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

In ``include/uapi/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. That file is itself included by
``include/linux/usb/ch9.h``, which also contains declarations of a few
utility routines for manipulating these data types; the implementations
are in ``drivers/usb/common/common.c``.

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

In addition, some functions useful for creating debugging output are
defined in ``drivers/usb/common/debug.c``.

.. _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:

Asynchronous URB와 synchronous wrapper

139-179

USB API의 가장 기본적인 I/O model은 asynchronous URB입니다. Driver가 request를 submit하고 URB completion callback이 다음 단계를 처리합니다. 모든 transfer type이 이 model을 지원합니다.

Control URB는 항상 setup과 status stage가 있고 data stage는 없을 수 있습니다. Isochronous URB는 큰 packet을 허용하며 packet별 fault report를 포함하는 특수 규칙이 있습니다.

Synchronous API는 하나 이상의 URB를 allocate·submit한 뒤 completion까지 기다리는 wrapper입니다. Single-buffer control·bulk wrapper는 일부 disconnect scenario에서 쓰기 까다롭고, scatterlist streaming I/O wrapper는 bulk 또는 interrupt에 사용됩니다.

USB driver는 DMA 가능한 buffer를 제공해야 하지만 mapping까지 직접 할 필요는 없습니다. DMA buffer allocation API를 쓰면 일부 system의 bounce buffer를 피할 수 있고, 64-bit DMA 지원으로 다른 형태의 bounce buffer도 줄일 수 있습니다.

Exported core API 구현은 `drivers/usb/core/urb.c`, `message.c`, `file.c`, `driver.c`, `usb.c`, `hub.c`에 분산되어 있으며 `message.c`는 `usb_core` C namespace로 문서화됩니다.

USB core I/O layer
Layer특징
Asynchronous URB모든 transfer type, callback 기반
Control URBSetup·status 필수, data 선택
Isochronous URBLarge packet과 packet별 fault
Synchronous control·bulkURB allocate·submit·wait wrapper
Scatterlist streamingBulk·interrupt synchronous support
DMA buffer APIHCD용 mapping과 bounce buffer 최적화
Core source`urb.c`, `message.c`, `file.c`, `driver.c`, `usb.c`, `hub.c`

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:

.. c:namespace:: usb_core
.. 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 Driver API layer

180-214

Host Controller API는 주로 XHCI, EHCI, OHCI, UHCI 같은 표준 register interface를 구현하는 HCD 전용입니다.

UHCI는 Intel이 설계하고 VIA도 사용한 초기 interface로 hardware가 담당하는 일이 적습니다. OHCI는 더 큰 transfer와 protocol state 추적을 hardware에 맡겼고, USB 2.0용 EHCI는 OHCI식 hardware offload와 UHCI식 ISO·TD list 특성을 함께 가집니다. USB 3.0용 XHCI는 더 많은 기능을 hardware로 옮겼습니다.

표준 controller 외에도 PIO 기반 controller, simulator, USB를 network로 전달하는 virtual host controller가 있습니다. 모든 controller driver에는 같은 기본 API가 제공됩니다.

역사적으로 API는 두 layer입니다. 2.2 kernel부터 있던 `struct usb_bus`는 얇은 layer이고, `struct usb_hcd`는 HCD끼리 common code를 공유해 driver 크기와 HCD-specific behavior를 줄이는 풍부한 layer입니다.

구현과 export는 `drivers/usb/core/hcd.c`, PCI helper는 `hcd-pci.c`, internal buffer support는 `buffer.c`에 있습니다.

Host controller 세대와 API
대상특징
UHCISoftware 중심 초기 controller
OHCITransfer·protocol state hardware offload
EHCIUSB 2.0, OHCI·UHCI 특성 혼합
XHCIUSB 3.0, 더 많은 hardware 기능
기타 HCDPIO·simulator·network virtual controller
`struct usb_bus`역사적인 얇은 layer
`struct usb_hcd`Common code 공유와 HCD 차이 축소
Source`hcd.c`, `hcd-pci.c`, `buffer.c`

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:

USB character device와 devtmpfs node

215-259

USB driver를 위해 새 kernel code를 쓰지 않고 userspace application이나 library로 구현할 수 있습니다. Character device를 감싸는 대표 library는 C/C++용 `libusb`와 Java용 `jUSB`이며, 오래된 배경 자료는 `http://www.linux-usb.org/`의 USB Guide에 있습니다.

이 interface는 과거 `usbfs`로 구현됐지만 sysfs debug interface의 일부는 아닙니다. 특히 asynchronous mode 설명은 불완전하며 kernel 2.5.66 당시 code와 문서의 교차 검토가 필요하다고 명시되어 있습니다.

관례적으로 `/dev/bus/usb/` 아래에 있는 `/dev/bus/usb/BBB/DDD` file은 device configuration descriptor를 노출하고 device request와 endpoint I/O를 위한 ioctl을 지원합니다. Program access 전용 magic file입니다.

`BBB`는 bus enumeration 순서, `DDD`는 bus 안의 device 순서에서 받은 번호입니다. 같은 hub port에 계속 꽂혀 있어도 바뀔 수 있는 불안정 identifier이므로 application configuration에 저장해서는 안 됩니다.

HID와 networking device는 올바른 UPS 같은 특정 장치를 고를 수 있는 stable ID를 별도로 노출하지만 이 device-file interface 자체는 아직 그 ID를 제공하지 않습니다.

Userspace USB access
Interface용도·제약
`libusb`C/C++ userspace USB library
`jUSB`Java userspace USB library
`/dev/bus/usb/BBB/DDD`Descriptor read와 USB ioctl
`BBB`·`DDD`Enumeration 순서 번호, 재사용·변경 가능
Stable IDHID·networking subsystem에서 별도 제공
문서 상태Async 부분 불완전, usbfs와 debugfs 구분

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` binary와 접근 규칙

260-319

Device file을 read하면 먼저 18-byte device descriptor가 나오고 이어서 configuration descriptor가 나옵니다. Multi-byte 값은 대체로 little endian에서 host byte order로 바꿔야 하지만 device descriptor의 BCD field, vendor ID, product ID는 kernel이 byte-swap합니다.

Configuration descriptor에는 interface, alternate setting, endpoint와 추가 class descriptor가 포함될 수 있습니다. 뒤 설명에 따르면 file에는 device descriptor 다음 각 configuration descriptor가 이어지고, device descriptor multi-byte field는 host endian이지만 configuration descriptor는 bus endian입니다.

Configuration block은 `wTotalLength` byte 간격입니다. Device가 표시된 길이보다 적은 descriptor data를 반환하면 누락 byte만큼 file에 hole이 생깁니다. 같은 정보는 `/sys/kernel/debug/usb/devices`에서 text로도 볼 수 있습니다.

`ioctl()`로 synchronous·asynchronous endpoint I/O와 device 관리 request를 수행할 수 있습니다. `CAP_SYS_RAWIO` capability와 filesystem permission이 모두 필요하고 한 device file에는 한 번에 ioctl 하나만 실행할 수 있어 synchronous read 중 다른 thread의 endpoint write가 막힙니다. Half-duplex가 아니라면 asynchronous I/O를 사용해야 합니다.

Bus·device 번호는 순차 할당되고 재사용됩니다. Connected 상태에서도 power·hub·cable 접촉으로 re-enumerate되어 예를 들어 `002/027`이 나중에 `002/048`이 될 수 있으므로 stable access key로 사용할 수 없습니다.

User-level driver는 file을 read/write로 열고 descriptor로 예상 device인지 확인한 뒤 ioctl로 interface 하나 이상을 claim하고 control·bulk 등 transfer를 수행합니다. ioctl 정의는 `<linux/usbdevice_fs.h>`, 주 reference 구현은 `linux/drivers/usb/core/devio.c`입니다.

기본적으로 `BBB/DDD`는 root만 write할 수 있습니다. 필요한 user에게 `chmod`로 선택 권한을 주거나 usbfs mount option `devmode=0666` 등을 사용할 수 있습니다.

USB device file 사용 순서
`/dev/bus/usb` scan현재 BBB/DDD path 탐색
Descriptor readDevice·configuration binary 검증
Endian 변환Device와 configuration 규칙 구분
Interface claim ioctlExclusive endpoint access
Control·bulk·periodic I/OSync 또는 async request
Disconnect·re-enumerationENODEV 처리 후 path 재탐색

불안정 path를 discovery 시점에 찾고 descriptor 검증 후 interface를 claim합니다.

/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.

User-mode driver lifecycle

320-356

User-mode driver는 먼저 처리 가능한 device file을 찾아야 합니다. `/sbin/hotplug` event agent가 알려 줄 수도 있고 `/dev/bus/usb` 전체를 scan해 대부분을 무시할 수도 있습니다.

어느 방식이든 device file의 descriptor를 모두 `read()`하고 지원 policy와 대조해야 합니다. Vendor·product ID 한 쌍만 허용할 수도 있고 더 복잡한 policy가 필요할 수도 있습니다.

System에 같은 device가 하나만 있다고 가정해서는 안 됩니다. Code가 동시에 하나만 처리한다면 여러 개를 감지하고 user가 사용할 device를 고르게 해야 합니다.

단순 driver는 control request만 사용할 수 있습니다. 예를 들어 vendor-specific control request로 초기화·설정만 하고 나머지는 kernel driver가 맡습니다.

복잡한 driver는 non-control endpoint로 data를 읽고 쓰며 interface를 exclusive하게 claim합니다. Bulk가 가장 쉽지만 low-speed device에서는 interrupt만 사용할 수 있습니다. Interrupt와 isochronous는 bandwidth를 예약하는 periodic transfer이며 usbfs에서는 asynchronous call 없이 사용하기 까다롭지만 interrupt는 synchronous one-shot도 가능합니다.

Disconnect 시 request state cleanup은 kernel이 처리합니다. User-mode driver는 `ENODEV`를 보기 시작하면 open file descriptor를 가능한 빨리 닫아야 합니다.

User-mode USB driver lifecycle
Hotplug 통지 또는 scanCandidate device file 발견
Descriptor 전체 read지원 vendor·product·class policy 확인
여러 device 처리선택 또는 동시 instance 관리
Control-only 또는 interface claimDriver 복잡도 결정
Endpoint I/OBulk·interrupt·isochronous
`ENODEV`File descriptor 즉시 close

Discovery부터 disconnect 정리까지의 기본 흐름입니다.

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.

Usbfs ioctl 공통 규칙

357-386

Userspace program은 ioctl 사용을 위해 `<linux/usb.h>`, `<linux/usbdevice_fs.h>`, `<asm/byteorder.h>`를 include해야 합니다. USB 2.0 Chapter 9 standard request는 `<linux/usb/ch9.h>`를 통해 자동 포함됩니다.

별도 설명이 없으면 ioctl request가 성공할 때 적용한 usbfs file의 modification time을 갱신합니다. 반환값 `0`은 성공이고 그 밖에는 `usb-error-codes`에 설명된 standard USB error code입니다.

Device file 하나는 endpoint마다 하나씩인 여러 I/O stream을 multiplex합니다. 모든 device는 제한된 RPC-style access를 지원하는 control endpoint 0을 가집니다.

Kernel `hub_wq`는 power consumption과 기본 기능에 영향을 주는 device-wide configuration을 설정합니다. Endpoint는 interface에 속하고 interface의 alternate setting에 따라 available endpoint가 달라질 수 있습니다. 단순 device는 configuration과 interface가 하나라 driver가 이 구분을 무시하기도 합니다.

Usbfs ioctl 공통 환경
항목규칙
Headers`linux/usb.h`, `linux/usbdevice_fs.h`, `asm/byteorder.h`
Chapter 9`linux/usb/ch9.h`에서 포함
성공 반환`0`
실패 반환Standard USB error code
mtime별도 예외가 없으면 성공 request에서 갱신
Endpoint 0Device당 하나의 control RPC stream
Configuration`hub_wq`가 device-wide state 설정
AltsettingInterface별 endpoint availability 변경

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 configuration and interface, so drivers for them will
ignore configurations and altsettings.

Management와 status ioctl

387-514

Management·status request는 device I/O 자체보다 interface ownership, speed, driver binding, endpoint state를 다루며 모두 synchronous입니다.

`USBDEVFS_CLAIMINTERFACE`는 아직 usbfs나 kernel driver가 claim하지 않은 `bInterfaceNumber`를 강제로 claim합니다. Endpoint 사용 전에 명시적으로 claim하지 않아도 다른 driver가 bind하지 않았다면 usbfs가 자동 claim합니다. Claim은 `USBDEVFS_RELEASEINTERFACE` 또는 file close로 해제되며 이 두 request는 mtime을 갱신하지 않습니다.

`USBDEVFS_CONNECTINFO`는 `usbdevfs_connectinfo`에 device number와 low-speed 여부를 반환하지만 `slow=0`만으로 full speed와 480 Mbit/s high speed를 구분할 수 없습니다. `USBDEVFS_GET_SPEED`는 `enum usb_device_speed`에 맞는 숫자로 정확한 speed를 반환합니다.

`USBDEVFS_GETDRIVER`는 `usbdevfs_getdriver`를 통해 지정 interface에 bind된 kernel driver name을 반환합니다.

`USBDEVFS_IOCTL`은 `usbdevfs_ioctl` wrapper로 userspace request를 등록된 `struct usb_driver`의 ioctl entry에 전달합니다. Special character·block device를 만들지 않는 kernel driver와 filesystem operation으로 통신할 수 있고, 미리 정의된 ioctl은 kernel driver disconnect·reconnect를 통해 userspace가 binding과 configuration을 관리하게 합니다.

`USBDEVFS_RELEASEINTERFACE`에는 claim한 task와 release하는 task가 같은지 확인하는 security check가 없어 한 user-mode driver가 다른 driver를 방해할 수 있습니다.

`USBDEVFS_RESETEP`는 bulk·interrupt endpoint의 data toggle을 DATA0으로 reset합니다. Host와 device의 toggle synchronization을 잃기 쉬우므로 사용을 피하고 실제 sync loss에는 `CLEAR_HALT` 또는 `SET_INTERFACE` 같은 완전한 handshake를 써야 합니다.

`USBDEVFS_DROP_PRIVILEGES`는 arbitrary interface claim, 다른 user가 claim한 interface가 있는 device reset, `USBDEVFS_IOCTL` 실행 권한을 포기합니다. Parameter는 이 file descriptor가 claim할 수 있는 interface의 32-bit mask이며 여러 번 호출해 mask를 더 좁힐 수 있습니다.

Management·status ioctl
Request의미·주의
`USBDEVFS_CLAIMINTERFACE`Interface exclusive claim, 필요 시 auto-claim
`USBDEVFS_CONNECTINFO`Devnum과 low-speed 여부
`USBDEVFS_GET_SPEED``enum usb_device_speed` 값
`USBDEVFS_GETDRIVER`Interface kernel driver name
`USBDEVFS_IOCTL`Kernel `usb_driver->ioctl()` passthrough
`USBDEVFS_RELEASEINTERFACE`Claim 해제, owner security check 없음
`USBDEVFS_RESETEP`Toggle DATA0 reset, 사용 비권장
`USBDEVFS_DROP_PRIVILEGES`Claim·reset·passthrough 권한 축소

Management/Status Requests
~~~~~~~~~~~~~~~~~~~~~~~~~~

A number of usbfs requests don't deal very directly with device I/O.
They mostly relate to device management and status. These are all
synchronous requests.

USBDEVFS_CLAIMINTERFACE
    This is used to force usbfs to claim a specific interface, which has
    not previously been claimed by usbfs or any other kernel driver. The
    ioctl parameter is an integer holding the number of the interface
    (bInterfaceNumber from descriptor).

    Note that if your driver doesn't claim an interface before trying to
    use one of its endpoints, and no other driver has bound to it, then
    the interface is automatically claimed by usbfs.

    This claim will be released by a RELEASEINTERFACE ioctl, or by
    closing the file descriptor. File modification time is not updated
    by this request.

USBDEVFS_CONNECTINFO
    Says whether the device is lowspeed. The ioctl parameter points to a
    structure like this::

        struct usbdevfs_connectinfo {
                unsigned int   devnum;
                unsigned char  slow;
        };

    File modification time is not updated by this request.

    *You can't tell whether a "not slow" device is connected at high
    speed (480 MBit/sec) or just full speed (12 MBit/sec).* You should
    know the devnum value already, it's the DDD value of the device file
    name.

USBDEVFS_GET_SPEED
    Returns the speed of the device. The speed is returned as a
    numerical value in accordance with enum usb_device_speed

    File modification time is not updated by this request.

USBDEVFS_GETDRIVER
    Returns the name of the kernel driver bound to a given interface (a
    string). Parameter is a pointer to this structure, which is
    modified::

        struct usbdevfs_getdriver {
                unsigned int  interface;
                char          driver[USBDEVFS_MAXDRIVERNAME + 1];
        };

    File modification time is not updated by this request.

USBDEVFS_IOCTL
    Passes a request from userspace through to a kernel driver that has
    an ioctl entry in the *struct usb_driver* it registered::

        struct usbdevfs_ioctl {
                int     ifno;
                int     ioctl_code;
                void    *data;
        };

        /* user mode call looks like this.
         * 'request' becomes the driver->ioctl() 'code' parameter.
         * the size of 'param' is encoded in 'request', and that data
         * is copied to or from the driver->ioctl() 'buf' parameter.
         */
        static int
        usbdev_ioctl (int fd, int ifno, unsigned request, void *param)
        {
                struct usbdevfs_ioctl   wrapper;

                wrapper.ifno = ifno;
                wrapper.ioctl_code = request;
                wrapper.data = param;

                return ioctl (fd, USBDEVFS_IOCTL, &wrapper);
        }

    File modification time is not updated by this request.

    This request lets kernel drivers talk to user mode code through
    filesystem operations even when they don't create a character or
    block special device. It's also been used to do things like ask
    devices what device special file should be used. Two pre-defined
    ioctls are used to disconnect and reconnect kernel drivers, so that
    user mode code can completely manage binding and configuration of
    devices.

USBDEVFS_RELEASEINTERFACE
    This is used to release the claim usbfs made on interface, either
    implicitly or because of a USBDEVFS_CLAIMINTERFACE call, before the
    file descriptor is closed. The ioctl parameter is an integer holding
    the number of the interface (bInterfaceNumber from descriptor); File
    modification time is not updated by this request.

    .. warning::

        *No security check is made to ensure that the task which made
        the claim is the one which is releasing it. This means that user
        mode driver may interfere other ones.*

USBDEVFS_RESETEP
    Resets the data toggle value for an endpoint (bulk or interrupt) to
    DATA0. The ioctl parameter is an integer endpoint number (1 to 15,
    as identified in the endpoint descriptor), with USB_DIR_IN added
    if the device's endpoint sends data to the host.

    .. Warning::

        *Avoid using this request. It should probably be removed.* Using
        it typically means the device and driver will lose toggle
        synchronization. If you really lost synchronization, you likely
        need to completely handshake with the device, using a request
        like CLEAR_HALT or SET_INTERFACE.

USBDEVFS_DROP_PRIVILEGES
    This is used to relinquish the ability to do certain operations
    which are considered to be privileged on a usbfs file descriptor.
    This includes claiming arbitrary interfaces, resetting a device on
    which there are currently claimed interfaces from other users, and
    issuing USBDEVFS_IOCTL calls. The ioctl parameter is a 32 bit mask
    of interfaces the user is allowed to claim on this file descriptor.
    You may issue this ioctl more than one time to narrow said mask.

Synchronous usbfs I/O

515-620

Synchronous request는 성공 또는 error로 끝날 때까지 kernel이 calling user-mode task를 block합니다. 가장 단순한 usbfs 사용법이지만 device file 하나에서 동시에 endpoint 하나만 I/O할 수 있습니다.

`USBDEVFS_BULK`는 `usbdevfs_bulktransfer`의 endpoint, length, millisecond timeout, data pointer로 bulk read·write를 수행합니다. Endpoint는 1~15이고 device-to-host이면 `USB_DIR_IN`을 OR합니다. 당시 최신 kernel은 약 128 KByte까지 지원하며 short read와 실제 read length 설명은 원문에도 FIXME로 남아 있습니다.

`USBDEVFS_CLEAR_HALT`는 stalled bulk·interrupt endpoint의 halt와 data toggle을 clear합니다. `-EPIPE`를 반환한 endpoint에서 사용하며 control request를 직접 보내면 host의 toggle record가 깨질 수 있으므로 ioctl을 사용해야 합니다.

`USBDEVFS_CONTROL`은 `usbdevfs_ctrltransfer`로 control request를 보냅니다. 처음 8 byte가 SETUP packet이고 `bRequestType`은 `USB_TYPE_*`, `USB_DIR_*`, `USB_RECIP_*`를 조합합니다. `wLength`가 0이 아니면 OUT write 또는 IN read buffer 길이입니다.

Control data는 usbfs와 일부 HCD 제약으로 당시 4 KByte를 넘길 수 없고 short read를 허용하지 않는다고 지정할 방법도 없습니다.

`USBDEVFS_RESET`은 device-level reset 후 모든 interface를 rebind합니다. `USBDEVFS_SETINTERFACE`는 `bInterfaceNumber`와 `bAlternateSetting`으로 altsetting을 설정하며 해당 interface endpoint를 reset합니다.

`USBDEVFS_SETCONFIGURATION`은 descriptor의 `bConfigurationValue`로 `usb_set_configuration()`을 호출합니다. RESET과 SETCONFIGURATION은 device·interface·driver state를 완전히 synchronize하지 못하는 usbcore bug가 있어 사용을 피하라는 경고가 있습니다.

Synchronous I/O request
Request기능·제약
`USBDEVFS_BULK`Bulk read/write, endpoint·len·timeout·data
`USBDEVFS_CLEAR_HALT`Stall과 toggle 복구
`USBDEVFS_CONTROL`8-byte SETUP + 선택 data, 당시 4 KByte 제한
`USBDEVFS_RESET`Device reset·interface rebind, synchronization 경고
`USBDEVFS_SETINTERFACE`Altsetting 선택과 endpoint reset
`USBDEVFS_SETCONFIGURATION``usb_set_configuration()`, synchronization 경고

Synchronous I/O Support
~~~~~~~~~~~~~~~~~~~~~~~

Synchronous requests involve the kernel blocking until the user mode
request completes, either by finishing successfully or by reporting an
error. In most cases this is the simplest way to use usbfs, although as
noted above it does prevent performing I/O to more than one endpoint at
a time.

USBDEVFS_BULK
    Issues a bulk read or write request to the device. The ioctl
    parameter is a pointer to this structure::

        struct usbdevfs_bulktransfer {
                unsigned int  ep;
                unsigned int  len;
                unsigned int  timeout; /* in milliseconds */
                void          *data;
        };

    The ``ep`` value identifies a bulk endpoint number (1 to 15, as
    identified in an endpoint descriptor), masked with USB_DIR_IN when
    referring to an endpoint which sends data to the host from the
    device. The length of the data buffer is identified by ``len``; Recent
    kernels support requests up to about 128KBytes. *FIXME say how read
    length is returned, and how short reads are handled.*.

USBDEVFS_CLEAR_HALT
    Clears endpoint halt (stall) and resets the endpoint toggle. This is
    only meaningful for bulk or interrupt endpoints. The ioctl parameter
    is an integer endpoint number (1 to 15, as identified in an endpoint
    descriptor), masked with USB_DIR_IN when referring to an endpoint
    which sends data to the host from the device.

    Use this on bulk or interrupt endpoints which have stalled,
    returning ``-EPIPE`` status to a data transfer request. Do not issue
    the control request directly, since that could invalidate the host's
    record of the data toggle.

USBDEVFS_CONTROL
    Issues a control request to the device. The ioctl parameter points
    to a structure like this::

        struct usbdevfs_ctrltransfer {
                __u8   bRequestType;
                __u8   bRequest;
                __u16  wValue;
                __u16  wIndex;
                __u16  wLength;
                __u32  timeout;  /* in milliseconds */
                void   *data;
        };

    The first eight bytes of this structure are the contents of the
    SETUP packet to be sent to the device; see the USB 2.0 specification
    for details. The bRequestType value is composed by combining a
    ``USB_TYPE_*`` value, a ``USB_DIR_*`` value, and a ``USB_RECIP_*``
    value (from ``linux/usb.h``). If wLength is nonzero, it describes
    the length of the data buffer, which is either written to the device
    (USB_DIR_OUT) or read from the device (USB_DIR_IN).

    At this writing, you can't transfer more than 4 KBytes of data to or
    from a device; usbfs has a limit, and some host controller drivers
    have a limit. (That's not usually a problem.) *Also* there's no way
    to say it's not OK to get a short read back from the device.

USBDEVFS_RESET
    Does a USB level device reset. The ioctl parameter is ignored. After
    the reset, this rebinds all device interfaces. File modification
    time is not updated by this request.

.. warning::

        *Avoid using this call* until some usbcore bugs get fixed, since
        it does not fully synchronize device, interface, and driver (not
        just usbfs) state.

USBDEVFS_SETINTERFACE
    Sets the alternate setting for an interface. The ioctl parameter is
    a pointer to a structure like this::

        struct usbdevfs_setinterface {
                unsigned int  interface;
                unsigned int  altsetting;
        };

    File modification time is not updated by this request.

    Those struct members are from some interface descriptor applying to
    the current configuration. The interface number is the
    bInterfaceNumber value, and the altsetting number is the
    bAlternateSetting value. (This resets each endpoint in the
    interface.)

USBDEVFS_SETCONFIGURATION
    Issues the :c:func:`usb_set_configuration()` call for the
    device. The parameter is an integer holding the number of a
    configuration (bConfigurationValue from descriptor). File
    modification time is not updated by this request.

.. warning::

        *Avoid using this call* until some usbcore bugs get fixed, since
        it does not fully synchronize device, interface, and driver (not
        just usbfs) state.

Asynchronous usbfs URB

621-690

Userspace에서 여러 operation을 동시에 시작해야 할 때 asynchronous request가 필수입니다. 특히 interrupt·isochronous 같은 periodic transfer에 중요하지만 다른 USB request에도 사용할 수 있습니다. Submit과 completion 대기를 분리해 kernel이 request마다 block하지 않게 합니다.

Request는 kernel driver의 URB와 비슷한 `struct usbdevfs_urb`로 표현되지만 POSIX Async I/O는 아닙니다. `USBDEVFS_URB_TYPE_*` endpoint type, direction을 포함한 endpoint number, buffer와 length, request를 식별하는 userspace `usercontext`를 가집니다.

Request별로 `SIGRTMIN`부터 `SIGRTMAX` 사이 realtime signal number를 지정해 completion 시 signal을 받을 수 있습니다. Flag는 kernel URB보다 적은 범위에서 동작을 바꿉니다.

Usbfs가 URB를 반환할 때 `status`와 buffer가 갱신됩니다. ISO를 제외하면 `actual_length`가 실제 byte 수를 나타냅니다. `USBDEVFS_URB_DISABLE_SPD`를 설정하면 short packet을 허용하지 않아 요청보다 적게 읽을 때 error가 됩니다.

ISO request는 packet마다 `usbdevfs_iso_packet_desc`의 requested length, actual length, status를 가집니다. `usbdevfs_urb`에는 type, endpoint, status, flags, buffer, buffer length, actual length, start frame, packet count, error count, signal, context와 flexible ISO descriptor array가 포함됩니다.

Asynchronous request의 file mtime은 request를 시작한 시점이고 synchronous request는 완료 시점입니다. `USBDEVFS_DISCARDURB`, `USBDEVFS_DISCSIGNAL`, `USBDEVFS_REAPURB`, `USBDEVFS_REAPURBNDELAY`, `USBDEVFS_SUBMITURB`의 세부 설명은 원문에 TBS로 남아 있습니다.

Asynchronous usbfs request
Field·request역할
`type``USBDEVFS_URB_TYPE_*`
`endpoint`Number + 선택 `USB_DIR_IN`
`buffer`, `buffer_length`Transfer storage
`usercontext`Request별 userspace 식별자
`signr`Completion realtime signal
`actual_length`ISO 외 실제 byte 수
`USBDEVFS_URB_DISABLE_SPD`Short packet을 error로 처리
`iso_frame_desc[]`ISO packet별 length·actual·status
SUBMIT·REAP·DISCARD원문 세부 내용 TBS

Asynchronous I/O Support
~~~~~~~~~~~~~~~~~~~~~~~~

As mentioned above, there are situations where it may be important to
initiate concurrent operations from user mode code. This is particularly
important for periodic transfers (interrupt and isochronous), but it can
be used for other kinds of USB requests too. In such cases, the
asynchronous requests described here are essential. Rather than
submitting one request and having the kernel block until it completes,
the blocking is separate.

These requests are packaged into a structure that resembles the URB used
by kernel device drivers. (No POSIX Async I/O support here, sorry.) It
identifies the endpoint type (``USBDEVFS_URB_TYPE_*``), endpoint
(number, masked with USB_DIR_IN as appropriate), buffer and length,
and a user "context" value serving to uniquely identify each request.
(It's usually a pointer to per-request data.) Flags can modify requests
(not as many as supported for kernel drivers).

Each request can specify a realtime signal number (between SIGRTMIN and
SIGRTMAX, inclusive) to request a signal be sent when the request
completes.

When usbfs returns these urbs, the status value is updated, and the
buffer may have been modified. Except for isochronous transfers, the
actual_length is updated to say how many bytes were transferred; if the
USBDEVFS_URB_DISABLE_SPD flag is set ("short packets are not OK"), if
fewer bytes were read than were requested then you get an error report::

    struct usbdevfs_iso_packet_desc {
            unsigned int                     length;
            unsigned int                     actual_length;
            unsigned int                     status;
    };

    struct usbdevfs_urb {
            unsigned char                    type;
            unsigned char                    endpoint;
            int                              status;
            unsigned int                     flags;
            void                             *buffer;
            int                              buffer_length;
            int                              actual_length;
            int                              start_frame;
            int                              number_of_packets;
            int                              error_count;
            unsigned int                     signr;
            void                             *usercontext;
            struct usbdevfs_iso_packet_desc  iso_frame_desc[];
    };

For these asynchronous requests, the file modification time reflects
when the request was initiated. This contrasts with their use with the
synchronous requests, where it reflects when requests complete.

USBDEVFS_DISCARDURB
    *TBS* File modification time is not updated by this request.

USBDEVFS_DISCSIGNAL
    *TBS* File modification time is not updated by this request.

USBDEVFS_REAPURB
    *TBS* File modification time is not updated by this request.

USBDEVFS_REAPURBNDELAY
    *TBS* File modification time is not updated by this request.

USBDEVFS_SUBMITURB
    *TBS*

`/sys/kernel/debug/usb/devices` 개요

691-749

Kernel에 알려진 USB device와 configuration descriptor는 debugfs의 `/sys/kernel/debug/usb/devices` text file로 노출됩니다. `poll()`로 새 device 변화를 감지할 수도 있습니다.

Userspace status viewer는 text format을 scan하고 필요 없는 line을 무시할 수 있습니다. Class·vendor-specific 상세 status는 device별 file에서 확인합니다.

File descriptor를 열고 `poll()`하면 첫 호출은 즉시 반환하며, 이후 이전·현재 content를 비교하거나 filesystem을 scan해 변화를 확인합니다. 더 정확한 방법은 filesystem scan입니다.

이 behavior는 정보와 debug 목적입니다. Device 초기화나 user-mode helper 시작에는 udev나 HAL 같은 program을 사용하는 편이 더 적절합니다.

각 device는 여러 ASCII line으로 출력됩니다. `T:` line의 첫 네 topology column인 Lev, Prnt, Port, Cnt로 USB topology diagram을 만들 수 있습니다.

Line tag는 `T` topology, `B` root hub bandwidth, `D` device descriptor, `P` product ID, `S` string descriptor, `C` configuration, `I` interface, `E` endpoint입니다. Active configuration과 altsetting은 `*`로 표시됩니다.

Debugfs USB device line tag
Tag내용
`T`Topology
`B`Host controller·root hub bandwidth
`D`Device descriptor
`P`Vendor·Product·revision
`S`String descriptor
`C`Configuration, `*`는 active
`I`Interface와 bound driver
`E`Endpoint descriptor

The USB devices
===============

The USB devices are now exported via debugfs:

-  ``/sys/kernel/debug/usb/devices`` ... a text file showing each of the USB
   devices on known to the kernel, and their configuration descriptors.
   You can also poll() this to learn about new devices.

/sys/kernel/debug/usb/devices
-----------------------------

This file is handy for status viewing tools in user mode, which can scan
the text format and ignore most of it. More detailed device status
(including class and vendor status) is available from device-specific
files. For information about the current format of this file, see below.

This file, in combination with the poll() system call, can also be used
to detect when devices are added or removed::

    int fd;
    struct pollfd pfd;

    fd = open("/sys/kernel/debug/usb/devices", O_RDONLY);
    pfd = { fd, POLLIN, 0 };
    for (;;) {
        /* The first time through, this call will return immediately. */
        poll(&pfd, 1, -1);

        /* To see what's changed, compare the file's previous and current
           contents or scan the filesystem.  (Scanning is more precise.) */
    }

Note that this behavior is intended to be used for informational and
debug purposes. It would be more appropriate to use programs such as
udev or HAL to initialize a device or start a user-mode helper program,
for instance.

In this file, each device's output has multiple lines of ASCII output.

I made it ASCII instead of binary on purpose, so that someone
can obtain some useful data from it without the use of an
auxiliary program.  However, with an auxiliary program, the numbers
in the first 4 columns of each ``T:`` line (topology info:
Lev, Prnt, Port, Cnt) can be used to build a USB topology diagram.

Each line is tagged with a one-character ID for that line::

        T = Topology (etc.)
        B = Bandwidth (applies only to USB host controllers, which are
        virtualized as root hubs)
        D = Device descriptor info.
        P = Product ID info. (from Device descriptor, but they won't fit
        together on one line)
        S = String descriptors.
        C = Configuration descriptor info. (* = active configuration)
        I = Interface descriptor info.
        E = Endpoint descriptor info.

Topology `T:` line format

750-788

Output legend에서 `d`는 decimal, `x`는 hexadecimal, `s`는 string이며 숫자에는 leading space나 zero가 있을 수 있습니다.

`T:` line의 `Bus`는 bus number, `Lev`는 bus topology level, `Prnt`는 parent device number, `Port`는 parent의 connector·port, `Cnt`는 같은 level의 device count, `Dev#`는 device number, `Spd`는 Mbit/s speed, `MxCh`는 maximum children입니다.

Speed `1.5`는 low speed, `12`는 full speed, `480`은 USB 2.0 high speed, `5000`은 USB 3.0 SuperSpeed를 뜻합니다.

역사적 이유로 출력되는 `Port` number는 실제보다 항상 1 작습니다. 실제 port 4에 꽂은 device는 `Port=03`으로 표시됩니다.

`T:` topology field
Field의미
`Bus`Bus number
`Lev`Topology level
`Prnt`Parent DeviceNumber
`Port`Parent connector, 실제 번호보다 1 작음
`Cnt`이 level의 device count
`Dev#`Device address
`Spd`1.5·12·480·5000 Mbit/s
`MxCh`Maximum children

/sys/kernel/debug/usb/devices output format
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Legend::
  d = decimal number (may have leading spaces or 0's)
  x = hexadecimal number (may have leading spaces or 0's)
  s = string



Topology info
^^^^^^^^^^^^^

::

        T:  Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=dddd MxCh=dd
        |   |      |      |       |       |      |        |        |__MaxChildren
        |   |      |      |       |       |      |        |__Device Speed in Mbps
        |   |      |      |       |       |      |__DeviceNumber
        |   |      |      |       |       |__Count of devices at this level
        |   |      |      |       |__Connector/Port on Parent for this device
        |   |      |      |__Parent DeviceNumber
        |   |      |__Level in topology for this bus
        |   |__Bus number
        |__Topology info tag

Speed may be:

        ======= ======================================================
        1.5        Mbit/s for low speed USB
        12        Mbit/s for full speed USB
        480        Mbit/s for high speed USB (added for USB 2.0)
        5000        Mbit/s for SuperSpeed USB (added for USB 3.0)
        ======= ======================================================

For reasons lost in the mists of time, the Port number is always
too low by 1.  For example, a device plugged into port 4 will
show up with ``Port=03``.

Bandwidth `B:` line format

789-811

`B:` line은 `Alloc=used/reserved us (percentage)`, interrupt request 수 `#Int`, isochronous request 수 `#Iso`를 표시합니다.

Bandwidth allocation은 1 frame, 즉 1 millisecond 중 사용 중인 시간의 근사치입니다. Bandwidth를 예약하는 periodic interrupt·isochronous transfer만 반영합니다.

Control과 bulk transfer는 예약되지 않은 bandwidth와 short packet 등으로 예약됐지만 사용되지 않는 bandwidth를 모두 활용합니다.

Percentage는 periodic transfer가 reserved bandwidth 중 schedule한 비율입니다. Low·full speed bus에서는 전체의 90%, high speed bus에서는 80%가 reserved bandwidth입니다.

`B:` bandwidth field
Field의미
`Alloc=ddd/ddd us`Frame당 사용·예약 microsecond
`xx%`Reserved bandwidth 중 scheduled 비율
`#Int`Interrupt request 수
`#Iso`Isochronous request 수
Low·full speed reserveBus bandwidth의 90%
High speed reserveBus bandwidth의 80%

Bandwidth info
^^^^^^^^^^^^^^

::

        B:  Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
        |   |                       |         |__Number of isochronous requests
        |   |                       |__Number of interrupt requests
        |   |__Total Bandwidth allocated to this bus
        |__Bandwidth info tag

Bandwidth allocation is an approximation of how much of one frame
(millisecond) is in use.  It reflects only periodic transfers, which
are the only transfers that reserve bandwidth.  Control and bulk
transfers use all other bandwidth, including reserved bandwidth that
is not used for transfers (such as for short packets).

The percentage is how much of the "reserved" bandwidth is scheduled by
those transfers.  For a low or full speed bus (loosely, "USB 1.1"),
90% of the bus bandwidth is reserved.  For a high speed bus (loosely,
"USB 2.0") 80% is reserved.

Device `D:`와 Product `P:` line

812-839

`D:` line은 device USB version `Ver`, device class와 text `Cls`, subclass `Sub`, protocol `Prot`, default endpoint maximum packet size `MxPS`, configuration 수 `#Cfgs`를 표시합니다.

`P:` line은 vendor ID `Vendor`, product ID `ProdID`, product revision `Rev`를 hexadecimal·BCD-style text로 표시합니다.

Device·product descriptor field
Tag·field의미
`D: Ver`Device USB version
`Cls`Device class와 class name
`Sub`Device subclass
`Prot`Device protocol
`MxPS`Default endpoint maximum packet size
`#Cfgs`Configuration 수
`P: Vendor`Vendor ID
`ProdID`Product ID
`Rev`Product revision

Device descriptor info & Product ID info
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

        D:  Ver=x.xx Cls=xx(s) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
        P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx

where::

        D:  Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
        |   |        |             |      |       |       |__NumberConfigurations
        |   |        |             |      |       |__MaxPacketSize of Default Endpoint
        |   |        |             |      |__DeviceProtocol
        |   |        |             |__DeviceSubClass
        |   |        |__DeviceClass
        |   |__Device USB version
        |__Device info tag #1

where::

        P:  Vendor=xxxx ProdID=xxxx Rev=xx.xx
        |   |           |           |__Product revision number
        |   |           |__Product ID code
        |   |__Vendor ID code
        |__Device info tag #2

String descriptor `S:` line

840-866

`S: Manufacturer`는 device에서 읽은 manufacturer string입니다. Virtual root hub에서는 생략될 수 있고 newer HCD는 kernel version과 hub emulation driver를 표시할 수 있습니다.

`S: Product`는 device product description입니다. Older virtual root hub에서는 driver name, newer implementation에서는 kernel PCI ID database에서 온 product·vendor description을 표시하는 경우가 많습니다.

`S: SerialNumber`는 device serial number입니다. Virtual root hub에서는 다른 device와 공유할 수 없는 bus ID, address 또는 slot name 같은 unique identifier를 사용합니다.

`S:` string field
Field일반 device·virtual root hub
`Manufacturer`Manufacturer string; root hub는 kernel·driver 식별 가능
`Product`Product description; root hub는 driver 또는 PCI description
`SerialNumber`Device serial; root hub는 unique bus ID

String descriptor info
^^^^^^^^^^^^^^^^^^^^^^
::

        S:  Manufacturer=ssss
        |   |__Manufacturer of this device as read from the device.
        |      For USB host controller drivers (virtual root hubs) this may
        |      be omitted, or (for newer drivers) will identify the kernel
        |      version and the driver which provides this hub emulation.
        |__String info tag

        S:  Product=ssss
        |   |__Product description of this device as read from the device.
        |      For older USB host controller drivers (virtual root hubs) this
        |      indicates the driver; for newer ones, it's a product (and vendor)
        |      description that often comes from the kernel's PCI ID database.
        |__String info tag

        S:  SerialNumber=ssss
        |   |__Serial Number of this device as read from the device.
        |      For USB host controller drivers (virtual root hubs) this is
        |      some unique ID, normally a bus ID (address or slot name) that
        |      can't be shared with any other device.
        |__String info tag


Configuration `C:` line

867-890

`C:` line에서 `*`는 active configuration을 뜻합니다. `#Ifs`는 interface 수, `Cfg#`는 configuration number, `Atr`는 attribute, `MPwr`는 milliampere 단위 maximum power입니다.

USB device는 동작이 크게 다른 여러 configuration을 가질 수 있습니다. 예를 들어 bus-powered configuration은 self-powered configuration보다 기능이 적을 수 있습니다. 한 번에 configuration 하나만 active이며 대부분 device는 하나만 가집니다.

각 configuration에는 interface가 하나 이상 있고 각 interface는 독립 function을 제공하며 보통 서로 다른 USB driver에 bind됩니다. 예를 들어 USB speaker는 playback용 audio interface와 software volume control용 HID interface를 함께 가질 수 있습니다.

`C:` configuration field
Field의미
`*`Active configuration
`#Ifs`Number of interfaces
`Cfg#`Configuration number
`Atr`Configuration attributes
`MPwr`Maximum power in mA
InterfaceConfiguration 안의 독립 function·driver bind 단위

Configuration descriptor info
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::

        C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
        | | |       |       |      |__MaxPower in mA
        | | |       |       |__Attributes
        | | |       |__ConfiguratioNumber
        | | |__NumberOfInterfaces
        | |__ "*" indicates the active configuration (others are " ")
        |__Config info tag

USB devices may have multiple configurations, each of which act
rather differently.  For example, a bus-powered configuration
might be much less capable than one that is self-powered.  Only
one device configuration can be active at a time; most devices
have only one configuration.

Each configuration consists of one or more interfaces.  Each
interface serves a distinct "function", which is typically bound
to a different USB device driver.  One common example is a USB
speaker with an audio interface for playback, and a HID interface
for use with software volume control.

Interface `I:` line

891-916

`I:` line에서 `*`는 active alternate setting입니다. `If#`는 interface number, `Alt`는 alternate setting number, `#EPs`는 endpoint 수, `Cls`·`Sub`·`Prot`는 interface class·subclass·protocol, `Driver`는 bind된 driver name 또는 `(none)`입니다.

Interface에는 alternate setting이 하나 이상 있을 수 있습니다. Default setting은 적은 periodic bandwidth만 쓰고, bus bandwidth의 큰 비율을 사용하려면 driver가 non-default altsetting을 선택하는 방식이 일반적입니다.

한 interface에서는 한 번에 setting 하나만 active이고 driver 하나만 bind할 수 있습니다. 대부분 device는 interface마다 alternate setting 하나만 가집니다.

`I:` interface field
Field의미
`*`Active altsetting
`If#`Interface number
`Alt`Alternate setting number
`#EPs`Endpoint 수
`Cls`·`Sub`·`Prot`Interface class metadata
`Driver`Bound driver 또는 `(none)`
제약Setting 하나 active, driver 하나 bind

Interface descriptor info (can be multiple per Config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::

        I:* If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
        | | |      |      |       |             |      |       |__Driver name
        | | |      |      |       |             |      |          or "(none)"
        | | |      |      |       |             |      |__InterfaceProtocol
        | | |      |      |       |             |__InterfaceSubClass
        | | |      |      |       |__InterfaceClass
        | | |      |      |__NumberOfEndpoints
        | | |      |__AlternateSettingNumber
        | | |__InterfaceNumber
        | |__ "*" indicates the active altsetting (others are " ")
        |__Interface info tag

A given interface may have one or more "alternate" settings.
For example, default settings may not use more than a small
amount of periodic bandwidth.  To use significant fractions
of bus bandwidth, drivers must select a non-default altsetting.

Only one setting for an interface may be active at a time, and
only one driver may bind to an interface at a time.  Most devices
have only one alternate setting per interface.

Endpoint `E:` line

917-941

`E:` line의 `Ad`는 endpoint address와 IN·OUT direction, `Atr`는 endpoint type attribute, `MxPS`는 maximum packet size, `Ivl`은 transfer 사이 maximum interval입니다.

Interrupt·isochronous periodic endpoint에서는 interval이 항상 0이 아닙니다. High-speed endpoint의 interval은 millisecond가 아니라 microsecond로 표현될 수 있습니다.

High-speed periodic endpoint의 `EndpointMaxPacketSize`는 microframe당 data size입니다. High-bandwidth endpoint에서는 두세 packet을 합쳐 endpoint마다 최대 3 KByte를 125 microsecond마다 전송할 수 있습니다.

Linux USB stack의 periodic bandwidth reservation은 endpoint descriptor 값이 아니라 URB가 제공한 transfer interval과 size를 사용하며, URB 값은 descriptor보다 작을 수 있습니다.

`E:` endpoint field
Field의미
`Ad`Endpoint address와 IN·OUT direction
`Atr`Control·bulk·interrupt·isochronous type
`MxPS`Maximum packet size
`Ivl`Periodic transfer maximum interval
High-speed periodicMicroframe 단위, high-bandwidth는 최대 3 KByte/125 us
Reservation sourceURB interval·size, descriptor 이하 가능

Endpoint descriptor info (can be multiple per Interface)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

        E:  Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddss
        |   |        |            |         |__Interval (max) between transfers
        |   |        |            |__EndpointMaxPacketSize
        |   |        |__Attributes(EndpointType)
        |   |__EndpointAddress(I=In,O=Out)
        |__Endpoint info tag

The interval is nonzero for all periodic (interrupt or isochronous)
endpoints.  For high speed endpoints the transfer interval may be
measured in microseconds rather than milliseconds.

For high speed periodic endpoints, the ``EndpointMaxPacketSize`` reflects
the per-microframe data transfer size.  For "high bandwidth"
endpoints, that can reflect two or three packets (for up to
3KBytes every 125 usec) per endpoint.

With the Linux-USB stack, periodic bandwidth reservations use the
transfer intervals and sizes provided by URBs, which can be less
than those found in endpoint descriptor.

Debugfs filtering과 실제 device 예제

942-1024

Topology line만 필요하면 `grep ^T: /sys/kernel/debug/usb/devices`, T·D·P 같은 선택 tag만 필요하면 `grep -i ^[tdp]: ...`를 사용할 수 있습니다. Valid tag는 `TDPCIE`이며 `procusb` Perl script는 `TBDPSCIE`에서 고른 line 또는 전체 line을 출력하는 초기 예입니다.

Topology line으로 root hub 아래 USB device의 graphic topology를 만들 수 있습니다. Interface line은 device별 driver와 active altsetting, Configuration line은 전체 USB device의 maximum power 합계를 분석하는 데 쓸 수 있습니다. Power line만 보려면 `grep ^C:`를 사용합니다.

예제 system에는 UHCI root hub, root hub에 연결된 external four-port hub, external hub에 연결된 mouse와 serial converter가 있습니다.

Dev#1 root hub는 12 Mbit/s, port 2개, periodic bandwidth 28/900 microsecond(3%), interrupt request 2개입니다. Dev#2는 12 Mbit/s four-port hub입니다.

Dev#3은 1.5 Mbit/s HID mouse로 interrupt IN endpoint 하나를 사용합니다. Dev#4는 12 Mbit/s USB-to-serial converter로 bulk IN·OUT endpoint와 interrupt IN endpoint를 사용합니다.

`T:`와 `I:` line만 고르면 각 topology node 다음에 해당 interface driver가 나타나 hub·mouse·serial binding을 간결하게 확인할 수 있습니다.

예제 USB topology node
Device연결·속도·driver
Dev#1UHCI root hub, level 0, 12 Mbit/s, 2 ports
Dev#2External hub, root CN.0, 12 Mbit/s, 4 ports
Dev#3Mouse, hub CN.0, 1.5 Mbit/s, `mouse` driver
Dev#4Serial converter, hub CN.2, 12 Mbit/s, `serial` driver
Root bandwidth28/900 us, 3%, #Int=2, #Iso=0

Usage examples
~~~~~~~~~~~~~~

If a user or script is interested only in Topology info, for
example, use something like ``grep ^T: /sys/kernel/debug/usb/devices``
for only the Topology lines.  A command like
``grep -i ^[tdp]: /sys/kernel/debug/usb/devices`` can be used to list
only the lines that begin with the characters in square brackets,
where the valid characters are TDPCIE.  With a slightly more able
script, it can display any selected lines (for example, only T, D,
and P lines) and change their output format.  (The ``procusb``
Perl script is the beginning of this idea.  It will list only
selected lines [selected from TBDPSCIE] or "All" lines from
``/sys/kernel/debug/usb/devices``.)

The Topology lines can be used to generate a graphic/pictorial
of the USB devices on a system's root hub.  (See more below
on how to do this.)

The Interface lines can be used to determine what driver is
being used for each device, and which altsetting it activated.

The Configuration lines could be used to list maximum power
(in milliamps) that a system's USB devices are using.
For example, ``grep ^C: /sys/kernel/debug/usb/devices``.


Here's an example, from a system which has a UHCI root hub,
an external hub connected to the root hub, and a mouse and
a serial converter connected to the external hub.

::

        T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 2
        B:  Alloc= 28/900 us ( 3%), #Int=  2, #Iso=  0
        D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
        P:  Vendor=0000 ProdID=0000 Rev= 0.00
        S:  Product=USB UHCI Root Hub
        S:  SerialNumber=dce0
        C:* #Ifs= 1 Cfg#= 1 Atr=40 MxPwr=  0mA
        I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
        E:  Ad=81(I) Atr=03(Int.) MxPS=   8 Ivl=255ms

        T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 4
        D:  Ver= 1.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
        P:  Vendor=0451 ProdID=1446 Rev= 1.00
        C:* #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=100mA
        I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
        E:  Ad=81(I) Atr=03(Int.) MxPS=   1 Ivl=255ms

        T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 0
        D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
        P:  Vendor=04b4 ProdID=0001 Rev= 0.00
        C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
        I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse
        E:  Ad=81(I) Atr=03(Int.) MxPS=   3 Ivl= 10ms

        T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
        D:  Ver= 1.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs=  1
        P:  Vendor=0565 ProdID=0001 Rev= 1.08
        S:  Manufacturer=Peracom Networks, Inc.
        S:  Product=Peracom USB to Serial Converter
        C:* #Ifs= 1 Cfg#= 1 Atr=a0 MxPwr=100mA
        I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial
        E:  Ad=81(I) Atr=02(Bulk) MxPS=  64 Ivl= 16ms
        E:  Ad=01(O) Atr=02(Bulk) MxPS=  16 Ivl= 16ms
        E:  Ad=82(I) Atr=03(Int.) MxPS=   8 Ivl=  8ms


Selecting only the ``T:`` and ``I:`` lines from this (for example, by using
``procusb ti``), we have

::

        T:  Bus=00 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=12   MxCh= 2
        T:  Bus=00 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 4
        I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub
        T:  Bus=00 Lev=02 Prnt=02 Port=00 Cnt=01 Dev#=  3 Spd=1.5  MxCh= 0
        I:  If#= 0 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=01 Prot=02 Driver=mouse
        T:  Bus=00 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
        I:  If#= 0 Alt= 0 #EPs= 3 Cls=00(>ifc ) Sub=00 Prot=00 Driver=serial

예제 ASCII topology 재구성

1025-1057

원문 graphic은 level 0의 PC root hub Dev#1에서 connector 0으로 level 1의 four-port hub Dev#2가 연결되고, 그 hub의 connector 0과 2에 level 2 mouse Dev#3과 serial converter Dev#4가 연결된 구조입니다.

Root hub의 connector 1과 external hub의 connector 1·3은 비어 있습니다. Graphic의 괄호 숫자는 Mbit/s이고 `CN`은 connector 또는 port number를 뜻합니다.

같은 topology를 tree text로 쓰면 PC Dev#1 아래 CN.0에 Dev#2 hub가 있고, Dev#2 CN.0에는 mouse, CN.2에는 serial device가 있습니다. 연결 없는 port는 생략할 수도 있습니다.

USB example topology
PC / root hub Dev#1Level 0, 12 Mbit/s, 2 ports
Root CN.0 -> hub Dev#2Level 1, 12 Mbit/s, 4 ports
Hub CN.0 -> mouse Dev#3Level 2, 1.5 Mbit/s
Hub CN.1연결 없음
Hub CN.2 -> serial Dev#4Level 2, 12 Mbit/s
Hub CN.3연결 없음
Root CN.1연결 없음

원문의 두 ASCII 그림을 동일한 parent·port·speed 관계로 재구성했습니다.

Physically this looks like (or could be converted to)::

                      +------------------+
                      |  PC/root_hub (12)|   Dev# = 1
                      +------------------+   (nn) is Mbps.
    Level 0           |  CN.0   |  CN.1  |   [CN = connector/port #]
                      +------------------+
                          /
                         /
            +-----------------------+
  Level 1   | Dev#2: 4-port hub (12)|
            +-----------------------+
            |CN.0 |CN.1 |CN.2 |CN.3 |
            +-----------------------+
                \           \____________________
                 \_____                          \
                       \                          \
               +--------------------+      +--------------------+
  Level 2      | Dev# 3: mouse (1.5)|      | Dev# 4: serial (12)|
               +--------------------+      +--------------------+



Or, in a more tree-like structure (ports [Connectors] without
connections could be omitted)::

        PC:  Dev# 1, root hub, 2 ports, 12 Mbps
        |_ CN.0:  Dev# 2, hub, 4 ports, 12 Mbps
             |_ CN.0:  Dev #3, mouse, 1.5 Mbps
             |_ CN.1:
             |_ CN.2:  Dev #4, serial, 12 Mbps
             |_ CN.3:
        |_ CN.1: