packet_mmap.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. --------------------------------------------------------------------------------
  2. + ABSTRACT
  3. --------------------------------------------------------------------------------
  4. This file documents the CONFIG_PACKET_MMAP option available with the PACKET
  5. socket interface on 2.4 and 2.6 kernels. This type of sockets is used for
  6. capture network traffic with utilities like tcpdump or any other that uses
  7. the libpcap library.
  8. You can find the latest version of this document at
  9. http://pusa.uv.es/~ulisses/packet_mmap/
  10. Please send me your comments to
  11. Ulisses Alonso Camaró <uaca@i.hate.spam.alumni.uv.es>
  12. -------------------------------------------------------------------------------
  13. + Why use PACKET_MMAP
  14. --------------------------------------------------------------------------------
  15. In Linux 2.4/2.6 if PACKET_MMAP is not enabled, the capture process is very
  16. inefficient. It uses very limited buffers and requires one system call
  17. to capture each packet, it requires two if you want to get packet's
  18. timestamp (like libpcap always does).
  19. In the other hand PACKET_MMAP is very efficient. PACKET_MMAP provides a size
  20. configurable circular buffer mapped in user space. This way reading packets just
  21. needs to wait for them, most of the time there is no need to issue a single
  22. system call. By using a shared buffer between the kernel and the user
  23. also has the benefit of minimizing packet copies.
  24. It's fine to use PACKET_MMAP to improve the performance of the capture process,
  25. but it isn't everything. At least, if you are capturing at high speeds (this
  26. is relative to the cpu speed), you should check if the device driver of your
  27. network interface card supports some sort of interrupt load mitigation or
  28. (even better) if it supports NAPI, also make sure it is enabled.
  29. --------------------------------------------------------------------------------
  30. + How to use CONFIG_PACKET_MMAP
  31. --------------------------------------------------------------------------------
  32. From the user standpoint, you should use the higher level libpcap library, which
  33. is a de facto standard, portable across nearly all operating systems
  34. including Win32.
  35. Said that, at time of this writing, official libpcap 0.8.1 is out and doesn't include
  36. support for PACKET_MMAP, and also probably the libpcap included in your distribution.
  37. I'm aware of two implementations of PACKET_MMAP in libpcap:
  38. http://pusa.uv.es/~ulisses/packet_mmap/ (by Simon Patarin, based on libpcap 0.6.2)
  39. http://public.lanl.gov/cpw/ (by Phil Wood, based on lastest libpcap)
  40. The rest of this document is intended for people who want to understand
  41. the low level details or want to improve libpcap by including PACKET_MMAP
  42. support.
  43. --------------------------------------------------------------------------------
  44. + How to use CONFIG_PACKET_MMAP directly
  45. --------------------------------------------------------------------------------
  46. From the system calls stand point, the use of PACKET_MMAP involves
  47. the following process:
  48. [setup] socket() -------> creation of the capture socket
  49. setsockopt() ---> allocation of the circular buffer (ring)
  50. mmap() ---------> mapping of the allocated buffer to the
  51. user process
  52. [capture] poll() ---------> to wait for incoming packets
  53. [shutdown] close() --------> destruction of the capture socket and
  54. deallocation of all associated
  55. resources.
  56. socket creation and destruction is straight forward, and is done
  57. the same way with or without PACKET_MMAP:
  58. int fd;
  59. fd= socket(PF_PACKET, mode, htons(ETH_P_ALL))
  60. where mode is SOCK_RAW for the raw interface were link level
  61. information can be captured or SOCK_DGRAM for the cooked
  62. interface where link level information capture is not
  63. supported and a link level pseudo-header is provided
  64. by the kernel.
  65. The destruction of the socket and all associated resources
  66. is done by a simple call to close(fd).
  67. Next I will describe PACKET_MMAP settings and it's constraints,
  68. also the mapping of the circular buffer in the user process and
  69. the use of this buffer.
  70. --------------------------------------------------------------------------------
  71. + PACKET_MMAP settings
  72. --------------------------------------------------------------------------------
  73. To setup PACKET_MMAP from user level code is done with a call like
  74. setsockopt(fd, SOL_PACKET, PACKET_RX_RING, (void *) &req, sizeof(req))
  75. The most significant argument in the previous call is the req parameter,
  76. this parameter must to have the following structure:
  77. struct tpacket_req
  78. {
  79. unsigned int tp_block_size; /* Minimal size of contiguous block */
  80. unsigned int tp_block_nr; /* Number of blocks */
  81. unsigned int tp_frame_size; /* Size of frame */
  82. unsigned int tp_frame_nr; /* Total number of frames */
  83. };
  84. This structure is defined in /usr/include/linux/if_packet.h and establishes a
  85. circular buffer (ring) of unswappable memory mapped in the capture process.
  86. Being mapped in the capture process allows reading the captured frames and
  87. related meta-information like timestamps without requiring a system call.
  88. Captured frames are grouped in blocks. Each block is a physically contiguous
  89. region of memory and holds tp_block_size/tp_frame_size frames. The total number
  90. of blocks is tp_block_nr. Note that tp_frame_nr is a redundant parameter because
  91. frames_per_block = tp_block_size/tp_frame_size
  92. indeed, packet_set_ring checks that the following condition is true
  93. frames_per_block * tp_block_nr == tp_frame_nr
  94. Lets see an example, with the following values:
  95. tp_block_size= 4096
  96. tp_frame_size= 2048
  97. tp_block_nr = 4
  98. tp_frame_nr = 8
  99. we will get the following buffer structure:
  100. block #1 block #2
  101. +---------+---------+ +---------+---------+
  102. | frame 1 | frame 2 | | frame 3 | frame 4 |
  103. +---------+---------+ +---------+---------+
  104. block #3 block #4
  105. +---------+---------+ +---------+---------+
  106. | frame 5 | frame 6 | | frame 7 | frame 8 |
  107. +---------+---------+ +---------+---------+
  108. A frame can be of any size with the only condition it can fit in a block. A block
  109. can only hold an integer number of frames, or in other words, a frame cannot
  110. be spawned accross two blocks, so there are some details you have to take into
  111. account when choosing the frame_size. See "Mapping and use of the circular
  112. buffer (ring)".
  113. --------------------------------------------------------------------------------
  114. + PACKET_MMAP setting constraints
  115. --------------------------------------------------------------------------------
  116. In kernel versions prior to 2.4.26 (for the 2.4 branch) and 2.6.5 (2.6 branch),
  117. the PACKET_MMAP buffer could hold only 32768 frames in a 32 bit architecture or
  118. 16384 in a 64 bit architecture. For information on these kernel versions
  119. see http://pusa.uv.es/~ulisses/packet_mmap/packet_mmap.pre-2.4.26_2.6.5.txt
  120. Block size limit
  121. ------------------
  122. As stated earlier, each block is a contiguous physical region of memory. These
  123. memory regions are allocated with calls to the __get_free_pages() function. As
  124. the name indicates, this function allocates pages of memory, and the second
  125. argument is "order" or a power of two number of pages, that is
  126. (for PAGE_SIZE == 4096) order=0 ==> 4096 bytes, order=1 ==> 8192 bytes,
  127. order=2 ==> 16384 bytes, etc. The maximum size of a
  128. region allocated by __get_free_pages is determined by the MAX_ORDER macro. More
  129. precisely the limit can be calculated as:
  130. PAGE_SIZE << MAX_ORDER
  131. In a i386 architecture PAGE_SIZE is 4096 bytes
  132. In a 2.4/i386 kernel MAX_ORDER is 10
  133. In a 2.6/i386 kernel MAX_ORDER is 11
  134. So get_free_pages can allocate as much as 4MB or 8MB in a 2.4/2.6 kernel
  135. respectively, with an i386 architecture.
  136. User space programs can include /usr/include/sys/user.h and
  137. /usr/include/linux/mmzone.h to get PAGE_SIZE MAX_ORDER declarations.
  138. The pagesize can also be determined dynamically with the getpagesize (2)
  139. system call.
  140. Block number limit
  141. --------------------
  142. To understand the constraints of PACKET_MMAP, we have to see the structure
  143. used to hold the pointers to each block.
  144. Currently, this structure is a dynamically allocated vector with kmalloc
  145. called pg_vec, its size limits the number of blocks that can be allocated.
  146. +---+---+---+---+
  147. | x | x | x | x |
  148. +---+---+---+---+
  149. | | | |
  150. | | | v
  151. | | v block #4
  152. | v block #3
  153. v block #2
  154. block #1
  155. kmalloc allocates any number of bytes of physically contiguous memory from
  156. a pool of pre-determined sizes. This pool of memory is maintained by the slab
  157. allocator which is at the end the responsible for doing the allocation and
  158. hence which imposes the maximum memory that kmalloc can allocate.
  159. In a 2.4/2.6 kernel and the i386 architecture, the limit is 131072 bytes. The
  160. predetermined sizes that kmalloc uses can be checked in the "size-<bytes>"
  161. entries of /proc/slabinfo
  162. In a 32 bit architecture, pointers are 4 bytes long, so the total number of
  163. pointers to blocks is
  164. 131072/4 = 32768 blocks
  165. PACKET_MMAP buffer size calculator
  166. ------------------------------------
  167. Definitions:
  168. <size-max> : is the maximum size of allocable with kmalloc (see /proc/slabinfo)
  169. <pointer size>: depends on the architecture -- sizeof(void *)
  170. <page size> : depends on the architecture -- PAGE_SIZE or getpagesize (2)
  171. <max-order> : is the value defined with MAX_ORDER
  172. <frame size> : it's an upper bound of frame's capture size (more on this later)
  173. from these definitions we will derive
  174. <block number> = <size-max>/<pointer size>
  175. <block size> = <pagesize> << <max-order>
  176. so, the max buffer size is
  177. <block number> * <block size>
  178. and, the number of frames be
  179. <block number> * <block size> / <frame size>
  180. Suppose the following parameters, which apply for 2.6 kernel and an
  181. i386 architecture:
  182. <size-max> = 131072 bytes
  183. <pointer size> = 4 bytes
  184. <pagesize> = 4096 bytes
  185. <max-order> = 11
  186. and a value for <frame size> of 2048 bytes. These parameters will yield
  187. <block number> = 131072/4 = 32768 blocks
  188. <block size> = 4096 << 11 = 8 MiB.
  189. and hence the buffer will have a 262144 MiB size. So it can hold
  190. 262144 MiB / 2048 bytes = 134217728 frames
  191. Actually, this buffer size is not possible with an i386 architecture.
  192. Remember that the memory is allocated in kernel space, in the case of
  193. an i386 kernel's memory size is limited to 1GiB.
  194. All memory allocations are not freed until the socket is closed. The memory
  195. allocations are done with GFP_KERNEL priority, this basically means that
  196. the allocation can wait and swap other process' memory in order to allocate
  197. the necessary memory, so normally limits can be reached.
  198. Other constraints
  199. -------------------
  200. If you check the source code you will see that what I draw here as a frame
  201. is not only the link level frame. At the beginning of each frame there is a
  202. header called struct tpacket_hdr used in PACKET_MMAP to hold link level's frame
  203. meta information like timestamp. So what we draw here a frame it's really
  204. the following (from include/linux/if_packet.h):
  205. /*
  206. Frame structure:
  207. - Start. Frame must be aligned to TPACKET_ALIGNMENT=16
  208. - struct tpacket_hdr
  209. - pad to TPACKET_ALIGNMENT=16
  210. - struct sockaddr_ll
  211. - Gap, chosen so that packet data (Start+tp_net) aligns to
  212. TPACKET_ALIGNMENT=16
  213. - Start+tp_mac: [ Optional MAC header ]
  214. - Start+tp_net: Packet data, aligned to TPACKET_ALIGNMENT=16.
  215. - Pad to align to TPACKET_ALIGNMENT=16
  216. */
  217. The following are conditions that are checked in packet_set_ring
  218. tp_block_size must be a multiple of PAGE_SIZE (1)
  219. tp_frame_size must be greater than TPACKET_HDRLEN (obvious)
  220. tp_frame_size must be a multiple of TPACKET_ALIGNMENT
  221. tp_frame_nr must be exactly frames_per_block*tp_block_nr
  222. Note that tp_block_size should be chosen to be a power of two or there will
  223. be a waste of memory.
  224. --------------------------------------------------------------------------------
  225. + Mapping and use of the circular buffer (ring)
  226. --------------------------------------------------------------------------------
  227. The mapping of the buffer in the user process is done with the conventional
  228. mmap function. Even the circular buffer is compound of several physically
  229. discontiguous blocks of memory, they are contiguous to the user space, hence
  230. just one call to mmap is needed:
  231. mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  232. If tp_frame_size is a divisor of tp_block_size frames will be
  233. contiguosly spaced by tp_frame_size bytes. If not, each
  234. tp_block_size/tp_frame_size frames there will be a gap between
  235. the frames. This is because a frame cannot be spawn across two
  236. blocks.
  237. At the beginning of each frame there is an status field (see
  238. struct tpacket_hdr). If this field is 0 means that the frame is ready
  239. to be used for the kernel, If not, there is a frame the user can read
  240. and the following flags apply:
  241. from include/linux/if_packet.h
  242. #define TP_STATUS_COPY 2
  243. #define TP_STATUS_LOSING 4
  244. #define TP_STATUS_CSUMNOTREADY 8
  245. TP_STATUS_COPY : This flag indicates that the frame (and associated
  246. meta information) has been truncated because it's
  247. larger than tp_frame_size. This packet can be
  248. read entirely with recvfrom().
  249. In order to make this work it must to be
  250. enabled previously with setsockopt() and
  251. the PACKET_COPY_THRESH option.
  252. The number of frames than can be buffered to
  253. be read with recvfrom is limited like a normal socket.
  254. See the SO_RCVBUF option in the socket (7) man page.
  255. TP_STATUS_LOSING : indicates there were packet drops from last time
  256. statistics where checked with getsockopt() and
  257. the PACKET_STATISTICS option.
  258. TP_STATUS_CSUMNOTREADY: currently it's used for outgoing IP packets which
  259. it's checksum will be done in hardware. So while
  260. reading the packet we should not try to check the
  261. checksum.
  262. for convenience there are also the following defines:
  263. #define TP_STATUS_KERNEL 0
  264. #define TP_STATUS_USER 1
  265. The kernel initializes all frames to TP_STATUS_KERNEL, when the kernel
  266. receives a packet it puts in the buffer and updates the status with
  267. at least the TP_STATUS_USER flag. Then the user can read the packet,
  268. once the packet is read the user must zero the status field, so the kernel
  269. can use again that frame buffer.
  270. The user can use poll (any other variant should apply too) to check if new
  271. packets are in the ring:
  272. struct pollfd pfd;
  273. pfd.fd = fd;
  274. pfd.revents = 0;
  275. pfd.events = POLLIN|POLLRDNORM|POLLERR;
  276. if (status == TP_STATUS_KERNEL)
  277. retval = poll(&pfd, 1, timeout);
  278. It doesn't incur in a race condition to first check the status value and
  279. then poll for frames.
  280. --------------------------------------------------------------------------------
  281. + THANKS
  282. --------------------------------------------------------------------------------
  283. Jesse Brandeburg, for fixing my grammathical/spelling errors