usbmon.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. * Introduction
  2. The name "usbmon" in lowercase refers to a facility in kernel which is
  3. used to collect traces of I/O on the USB bus. This function is analogous
  4. to a packet socket used by network monitoring tools such as tcpdump(1)
  5. or Ethereal. Similarly, it is expected that a tool such as usbdump or
  6. USBMon (with uppercase letters) is used to examine raw traces produced
  7. by usbmon.
  8. The usbmon reports requests made by peripheral-specific drivers to Host
  9. Controller Drivers (HCD). So, if HCD is buggy, the traces reported by
  10. usbmon may not correspond to bus transactions precisely. This is the same
  11. situation as with tcpdump.
  12. * How to use usbmon to collect raw text traces
  13. Unlike the packet socket, usbmon has an interface which provides traces
  14. in a text format. This is used for two purposes. First, it serves as a
  15. common trace exchange format for tools while most sophisticated formats
  16. are finalized. Second, humans can read it in case tools are not available.
  17. To collect a raw text trace, execute following steps.
  18. 1. Prepare
  19. Mount debugfs (it has to be enabled in your kernel configuration), and
  20. load the usbmon module (if built as module). The second step is skipped
  21. if usbmon is built into the kernel.
  22. # mount -t debugfs none_debugs /sys/kernel/debug
  23. # modprobe usbmon
  24. #
  25. Verify that bus sockets are present.
  26. # ls /sys/kernel/debug/usbmon
  27. 1s 1t 2s 2t 3s 3t 4s 4t
  28. #
  29. 2. Find which bus connects to the desired device
  30. Run "cat /proc/bus/usb/devices", and find the T-line which corresponds to
  31. the device. Usually you do it by looking for the vendor string. If you have
  32. many similar devices, unplug one and compare two /proc/bus/usb/devices outputs.
  33. The T-line will have a bus number. Example:
  34. T: Bus=03 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#= 2 Spd=12 MxCh= 0
  35. D: Ver= 1.10 Cls=00(>ifc ) Sub=00 Prot=00 MxPS= 8 #Cfgs= 1
  36. P: Vendor=0557 ProdID=2004 Rev= 1.00
  37. S: Manufacturer=ATEN
  38. S: Product=UC100KM V2.00
  39. Bus=03 means it's bus 3.
  40. 3. Start 'cat'
  41. # cat /sys/kernel/debug/usbmon/3t > /tmp/1.mon.out
  42. This process will be reading until killed. Naturally, the output can be
  43. redirected to a desirable location. This is preferred, because it is going
  44. to be quite long.
  45. 4. Perform the desired operation on the USB bus
  46. This is where you do something that creates the traffic: plug in a flash key,
  47. copy files, control a webcam, etc.
  48. 5. Kill cat
  49. Usually it's done with a keyboard interrupt (Control-C).
  50. At this point the output file (/tmp/1.mon.out in this example) can be saved,
  51. sent by e-mail, or inspected with a text editor. In the last case make sure
  52. that the file size is not excessive for your favourite editor.
  53. * Raw text data format
  54. The '1t' type data consists of a stream of events, such as URB submission,
  55. URB callback, submission error. Every event is a text line, which consists
  56. of whitespace separated words. The number or position of words may depend
  57. on the event type, but there is a set of words, common for all types.
  58. Here is the list of words, from left to right:
  59. - URB Tag. This is used to identify URBs is normally a kernel mode address
  60. of the URB structure in hexadecimal.
  61. - Timestamp in microseconds, a decimal number. The timestamp's resolution
  62. depends on available clock, and so it can be much worse than a microsecond
  63. (if the implementation uses jiffies, for example).
  64. - Event Type. This type refers to the format of the event, not URB type.
  65. Available types are: S - submission, C - callback, E - submission error.
  66. - "Pipe". The pipe concept is deprecated. This is a composite word, used to
  67. be derived from information in pipes. It consists of three fields, separated
  68. by colons: URB type and direction, Device address, Endpoint number.
  69. Type and direction are encoded with two bytes in the following manner:
  70. Ci Co Control input and output
  71. Zi Zo Isochronous input and output
  72. Ii Io Interrupt input and output
  73. Bi Bo Bulk input and output
  74. Device address and Endpoint number are 3-digit and 2-digit (respectively)
  75. decimal numbers, with leading zeroes.
  76. - URB Status. In most cases, this field contains a number, sometimes negative,
  77. which represents a "status" field of the URB. This field makes no sense for
  78. submissions, but is present anyway to help scripts with parsing. When an
  79. error occurs, the field contains the error code. In case of a submission of
  80. a Control packet, this field contains a Setup Tag instead of an error code.
  81. It is easy to tell whether the Setup Tag is present because it is never a
  82. number. Thus if scripts find a number in this field, they proceed to read
  83. Data Length. If they find something else, like a letter, they read the setup
  84. packet before reading the Data Length.
  85. - Setup packet, if present, consists of 5 words: one of each for bmRequestType,
  86. bRequest, wValue, wIndex, wLength, as specified by the USB Specification 2.0.
  87. These words are safe to decode if Setup Tag was 's'. Otherwise, the setup
  88. packet was present, but not captured, and the fields contain filler.
  89. - Data Length. For submissions, this is the requested length. For callbacks,
  90. this is the actual length.
  91. - Data tag. The usbmon may not always capture data, even if length is nonzero.
  92. The data words are present only if this tag is '='.
  93. - Data words follow, in big endian hexadecimal format. Notice that they are
  94. not machine words, but really just a byte stream split into words to make
  95. it easier to read. Thus, the last word may contain from one to four bytes.
  96. The length of collected data is limited and can be less than the data length
  97. report in Data Length word.
  98. Here is an example of code to read the data stream in a well known programming
  99. language:
  100. class ParsedLine {
  101. int data_len; /* Available length of data */
  102. byte data[];
  103. void parseData(StringTokenizer st) {
  104. int availwords = st.countTokens();
  105. data = new byte[availwords * 4];
  106. data_len = 0;
  107. while (st.hasMoreTokens()) {
  108. String data_str = st.nextToken();
  109. int len = data_str.length() / 2;
  110. int i;
  111. int b; // byte is signed, apparently?! XXX
  112. for (i = 0; i < len; i++) {
  113. // data[data_len] = Byte.parseByte(
  114. // data_str.substring(i*2, i*2 + 2),
  115. // 16);
  116. b = Integer.parseInt(
  117. data_str.substring(i*2, i*2 + 2),
  118. 16);
  119. if (b >= 128)
  120. b *= -1;
  121. data[data_len] = (byte) b;
  122. data_len++;
  123. }
  124. }
  125. }
  126. }
  127. This format may be changed in the future.
  128. Examples:
  129. An input control transfer to get a port status.
  130. d5ea89a0 3575914555 S Ci:001:00 s a3 00 0000 0003 0004 4 <
  131. d5ea89a0 3575914560 C Ci:001:00 0 4 = 01050000
  132. An output bulk transfer to send a SCSI command 0x5E in a 31-byte Bulk wrapper
  133. to a storage device at address 5:
  134. dd65f0e8 4128379752 S Bo:005:02 -115 31 = 55534243 5e000000 00000000 00000600 00000000 00000000 00000000 000000
  135. dd65f0e8 4128379808 C Bo:005:02 0 31 >
  136. * Raw binary format and API
  137. The overall architecture of the API is about the same as the one above,
  138. only the events are delivered in binary format. Each event is sent in
  139. the following structure (its name is made up, so that we can refer to it):
  140. struct usbmon_packet {
  141. u64 id; /* 0: URB ID - from submission to callback */
  142. unsigned char type; /* 8: Same as text; extensible. */
  143. unsigned char xfer_type; /* ISO (0), Intr, Control, Bulk (3) */
  144. unsigned char epnum; /* Endpoint number and transfer direction */
  145. unsigned char devnum; /* Device address */
  146. u16 busnum; /* 12: Bus number */
  147. char flag_setup; /* 14: Same as text */
  148. char flag_data; /* 15: Same as text; Binary zero is OK. */
  149. s64 ts_sec; /* 16: gettimeofday */
  150. s32 ts_usec; /* 24: gettimeofday */
  151. int status; /* 28: */
  152. unsigned int length; /* 32: Length of data (submitted or actual) */
  153. unsigned int len_cap; /* 36: Delivered length */
  154. unsigned char setup[8]; /* 40: Only for Control 'S' */
  155. }; /* 48 bytes total */
  156. These events can be received from a character device by reading with read(2),
  157. with an ioctl(2), or by accessing the buffer with mmap.
  158. The character device is usually called /dev/usbmonN, where N is the USB bus
  159. number. Number zero (/dev/usbmon0) is special and means "all buses".
  160. However, this feature is not implemented yet. Note that specific naming
  161. policy is set by your Linux distribution.
  162. If you create /dev/usbmon0 by hand, make sure that it is owned by root
  163. and has mode 0600. Otherwise, unpriviledged users will be able to snoop
  164. keyboard traffic.
  165. The following ioctl calls are available, with MON_IOC_MAGIC 0x92:
  166. MON_IOCQ_URB_LEN, defined as _IO(MON_IOC_MAGIC, 1)
  167. This call returns the length of data in the next event. Note that majority of
  168. events contain no data, so if this call returns zero, it does not mean that
  169. no events are available.
  170. MON_IOCG_STATS, defined as _IOR(MON_IOC_MAGIC, 3, struct mon_bin_stats)
  171. The argument is a pointer to the following structure:
  172. struct mon_bin_stats {
  173. u32 queued;
  174. u32 dropped;
  175. };
  176. The member "queued" refers to the number of events currently queued in the
  177. buffer (and not to the number of events processed since the last reset).
  178. The member "dropped" is the number of events lost since the last call
  179. to MON_IOCG_STATS.
  180. MON_IOCT_RING_SIZE, defined as _IO(MON_IOC_MAGIC, 4)
  181. This call sets the buffer size. The argument is the size in bytes.
  182. The size may be rounded down to the next chunk (or page). If the requested
  183. size is out of [unspecified] bounds for this kernel, the call fails with
  184. -EINVAL.
  185. MON_IOCQ_RING_SIZE, defined as _IO(MON_IOC_MAGIC, 5)
  186. This call returns the current size of the buffer in bytes.
  187. MON_IOCX_GET, defined as _IOW(MON_IOC_MAGIC, 6, struct mon_get_arg)
  188. This call waits for events to arrive if none were in the kernel buffer,
  189. then returns the first event. Its argument is a pointer to the following
  190. structure:
  191. struct mon_get_arg {
  192. struct usbmon_packet *hdr;
  193. void *data;
  194. size_t alloc; /* Length of data (can be zero) */
  195. };
  196. Before the call, hdr, data, and alloc should be filled. Upon return, the area
  197. pointed by hdr contains the next event structure, and the data buffer contains
  198. the data, if any. The event is removed from the kernel buffer.
  199. MON_IOCX_MFETCH, defined as _IOWR(MON_IOC_MAGIC, 7, struct mon_mfetch_arg)
  200. This ioctl is primarily used when the application accesses the buffer
  201. with mmap(2). Its argument is a pointer to the following structure:
  202. struct mon_mfetch_arg {
  203. uint32_t *offvec; /* Vector of events fetched */
  204. uint32_t nfetch; /* Number of events to fetch (out: fetched) */
  205. uint32_t nflush; /* Number of events to flush */
  206. };
  207. The ioctl operates in 3 stages.
  208. First, it removes and discards up to nflush events from the kernel buffer.
  209. The actual number of events discarded is returned in nflush.
  210. Second, it waits for an event to be present in the buffer, unless the pseudo-
  211. device is open with O_NONBLOCK.
  212. Third, it extracts up to nfetch offsets into the mmap buffer, and stores
  213. them into the offvec. The actual number of event offsets is stored into
  214. the nfetch.
  215. MON_IOCH_MFLUSH, defined as _IO(MON_IOC_MAGIC, 8)
  216. This call removes a number of events from the kernel buffer. Its argument
  217. is the number of events to remove. If the buffer contains fewer events
  218. than requested, all events present are removed, and no error is reported.
  219. This works when no events are available too.
  220. FIONBIO
  221. The ioctl FIONBIO may be implemented in the future, if there's a need.
  222. In addition to ioctl(2) and read(2), the special file of binary API can
  223. be polled with select(2) and poll(2). But lseek(2) does not work.
  224. * Memory-mapped access of the kernel buffer for the binary API
  225. The basic idea is simple:
  226. To prepare, map the buffer by getting the current size, then using mmap(2).
  227. Then, execute a loop similar to the one written in pseudo-code below:
  228. struct mon_mfetch_arg fetch;
  229. struct usbmon_packet *hdr;
  230. int nflush = 0;
  231. for (;;) {
  232. fetch.offvec = vec; // Has N 32-bit words
  233. fetch.nfetch = N; // Or less than N
  234. fetch.nflush = nflush;
  235. ioctl(fd, MON_IOCX_MFETCH, &fetch); // Process errors, too
  236. nflush = fetch.nfetch; // This many packets to flush when done
  237. for (i = 0; i < nflush; i++) {
  238. hdr = (struct ubsmon_packet *) &mmap_area[vec[i]];
  239. if (hdr->type == '@') // Filler packet
  240. continue;
  241. caddr_t data = &mmap_area[vec[i]] + 64;
  242. process_packet(hdr, data);
  243. }
  244. }
  245. Thus, the main idea is to execute only one ioctl per N events.
  246. Although the buffer is circular, the returned headers and data do not cross
  247. the end of the buffer, so the above pseudo-code does not need any gathering.