packet_mmap.txt 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. --------------------------------------------------------------------------------
  2. + ABSTRACT
  3. --------------------------------------------------------------------------------
  4. This file documents the mmap() facility available with the PACKET
  5. socket interface on 2.4/2.6/3.x kernels. This type of sockets is used for
  6. i) capture network traffic with utilities like tcpdump, ii) transmit network
  7. traffic, or any other that needs raw access to network interface.
  8. You can find the latest version of this document at:
  9. http://wiki.ipxwarzone.com/index.php5?title=Linux_packet_mmap
  10. Howto can be found at:
  11. http://wiki.gnu-log.net (packet_mmap)
  12. Please send your comments to
  13. Ulisses Alonso Camaró <uaca@i.hate.spam.alumni.uv.es>
  14. Johann Baudy <johann.baudy@gnu-log.net>
  15. -------------------------------------------------------------------------------
  16. + Why use PACKET_MMAP
  17. --------------------------------------------------------------------------------
  18. In Linux 2.4/2.6/3.x if PACKET_MMAP is not enabled, the capture process is very
  19. inefficient. It uses very limited buffers and requires one system call to
  20. capture each packet, it requires two if you want to get packet's timestamp
  21. (like libpcap always does).
  22. In the other hand PACKET_MMAP is very efficient. PACKET_MMAP provides a size
  23. configurable circular buffer mapped in user space that can be used to either
  24. send or receive packets. This way reading packets just needs to wait for them,
  25. most of the time there is no need to issue a single system call. Concerning
  26. transmission, multiple packets can be sent through one system call to get the
  27. highest bandwidth. By using a shared buffer between the kernel and the user
  28. also has the benefit of minimizing packet copies.
  29. It's fine to use PACKET_MMAP to improve the performance of the capture and
  30. transmission process, but it isn't everything. At least, if you are capturing
  31. at high speeds (this is relative to the cpu speed), you should check if the
  32. device driver of your network interface card supports some sort of interrupt
  33. load mitigation or (even better) if it supports NAPI, also make sure it is
  34. enabled. For transmission, check the MTU (Maximum Transmission Unit) used and
  35. supported by devices of your network. CPU IRQ pinning of your network interface
  36. card can also be an advantage.
  37. --------------------------------------------------------------------------------
  38. + How to use mmap() to improve capture process
  39. --------------------------------------------------------------------------------
  40. From the user standpoint, you should use the higher level libpcap library, which
  41. is a de facto standard, portable across nearly all operating systems
  42. including Win32.
  43. Said that, at time of this writing, official libpcap 0.8.1 is out and doesn't include
  44. support for PACKET_MMAP, and also probably the libpcap included in your distribution.
  45. I'm aware of two implementations of PACKET_MMAP in libpcap:
  46. http://wiki.ipxwarzone.com/ (by Simon Patarin, based on libpcap 0.6.2)
  47. http://public.lanl.gov/cpw/ (by Phil Wood, based on lastest libpcap)
  48. The rest of this document is intended for people who want to understand
  49. the low level details or want to improve libpcap by including PACKET_MMAP
  50. support.
  51. --------------------------------------------------------------------------------
  52. + How to use mmap() directly to improve capture process
  53. --------------------------------------------------------------------------------
  54. From the system calls stand point, the use of PACKET_MMAP involves
  55. the following process:
  56. [setup] socket() -------> creation of the capture socket
  57. setsockopt() ---> allocation of the circular buffer (ring)
  58. option: PACKET_RX_RING
  59. mmap() ---------> mapping of the allocated buffer to the
  60. user process
  61. [capture] poll() ---------> to wait for incoming packets
  62. [shutdown] close() --------> destruction of the capture socket and
  63. deallocation of all associated
  64. resources.
  65. socket creation and destruction is straight forward, and is done
  66. the same way with or without PACKET_MMAP:
  67. int fd = socket(PF_PACKET, mode, htons(ETH_P_ALL));
  68. where mode is SOCK_RAW for the raw interface were link level
  69. information can be captured or SOCK_DGRAM for the cooked
  70. interface where link level information capture is not
  71. supported and a link level pseudo-header is provided
  72. by the kernel.
  73. The destruction of the socket and all associated resources
  74. is done by a simple call to close(fd).
  75. Similarly as without PACKET_MMAP, it is possible to use one socket
  76. for capture and transmission. This can be done by mapping the
  77. allocated RX and TX buffer ring with a single mmap() call.
  78. See "Mapping and use of the circular buffer (ring)".
  79. Next I will describe PACKET_MMAP settings and its constraints,
  80. also the mapping of the circular buffer in the user process and
  81. the use of this buffer.
  82. --------------------------------------------------------------------------------
  83. + How to use mmap() directly to improve transmission process
  84. --------------------------------------------------------------------------------
  85. Transmission process is similar to capture as shown below.
  86. [setup] socket() -------> creation of the transmission socket
  87. setsockopt() ---> allocation of the circular buffer (ring)
  88. option: PACKET_TX_RING
  89. bind() ---------> bind transmission socket with a network interface
  90. mmap() ---------> mapping of the allocated buffer to the
  91. user process
  92. [transmission] poll() ---------> wait for free packets (optional)
  93. send() ---------> send all packets that are set as ready in
  94. the ring
  95. The flag MSG_DONTWAIT can be used to return
  96. before end of transfer.
  97. [shutdown] close() --------> destruction of the transmission socket and
  98. deallocation of all associated resources.
  99. Socket creation and destruction is also straight forward, and is done
  100. the same way as in capturing described in the previous paragraph:
  101. int fd = socket(PF_PACKET, mode, 0);
  102. The protocol can optionally be 0 in case we only want to transmit
  103. via this socket, which avoids an expensive call to packet_rcv().
  104. In this case, you also need to bind(2) the TX_RING with sll_protocol = 0
  105. set. Otherwise, htons(ETH_P_ALL) or any other protocol, for example.
  106. Binding the socket to your network interface is mandatory (with zero copy) to
  107. know the header size of frames used in the circular buffer.
  108. As capture, each frame contains two parts:
  109. --------------------
  110. | struct tpacket_hdr | Header. It contains the status of
  111. | | of this frame
  112. |--------------------|
  113. | data buffer |
  114. . . Data that will be sent over the network interface.
  115. . .
  116. --------------------
  117. bind() associates the socket to your network interface thanks to
  118. sll_ifindex parameter of struct sockaddr_ll.
  119. Initialization example:
  120. struct sockaddr_ll my_addr;
  121. struct ifreq s_ifr;
  122. ...
  123. strncpy (s_ifr.ifr_name, "eth0", sizeof(s_ifr.ifr_name));
  124. /* get interface index of eth0 */
  125. ioctl(this->socket, SIOCGIFINDEX, &s_ifr);
  126. /* fill sockaddr_ll struct to prepare binding */
  127. my_addr.sll_family = AF_PACKET;
  128. my_addr.sll_protocol = htons(ETH_P_ALL);
  129. my_addr.sll_ifindex = s_ifr.ifr_ifindex;
  130. /* bind socket to eth0 */
  131. bind(this->socket, (struct sockaddr *)&my_addr, sizeof(struct sockaddr_ll));
  132. A complete tutorial is available at: http://wiki.gnu-log.net/
  133. By default, the user should put data at :
  134. frame base + TPACKET_HDRLEN - sizeof(struct sockaddr_ll)
  135. So, whatever you choose for the socket mode (SOCK_DGRAM or SOCK_RAW),
  136. the beginning of the user data will be at :
  137. frame base + TPACKET_ALIGN(sizeof(struct tpacket_hdr))
  138. If you wish to put user data at a custom offset from the beginning of
  139. the frame (for payload alignment with SOCK_RAW mode for instance) you
  140. can set tp_net (with SOCK_DGRAM) or tp_mac (with SOCK_RAW). In order
  141. to make this work it must be enabled previously with setsockopt()
  142. and the PACKET_TX_HAS_OFF option.
  143. --------------------------------------------------------------------------------
  144. + PACKET_MMAP settings
  145. --------------------------------------------------------------------------------
  146. To setup PACKET_MMAP from user level code is done with a call like
  147. - Capture process
  148. setsockopt(fd, SOL_PACKET, PACKET_RX_RING, (void *) &req, sizeof(req))
  149. - Transmission process
  150. setsockopt(fd, SOL_PACKET, PACKET_TX_RING, (void *) &req, sizeof(req))
  151. The most significant argument in the previous call is the req parameter,
  152. this parameter must to have the following structure:
  153. struct tpacket_req
  154. {
  155. unsigned int tp_block_size; /* Minimal size of contiguous block */
  156. unsigned int tp_block_nr; /* Number of blocks */
  157. unsigned int tp_frame_size; /* Size of frame */
  158. unsigned int tp_frame_nr; /* Total number of frames */
  159. };
  160. This structure is defined in /usr/include/linux/if_packet.h and establishes a
  161. circular buffer (ring) of unswappable memory.
  162. Being mapped in the capture process allows reading the captured frames and
  163. related meta-information like timestamps without requiring a system call.
  164. Frames are grouped in blocks. Each block is a physically contiguous
  165. region of memory and holds tp_block_size/tp_frame_size frames. The total number
  166. of blocks is tp_block_nr. Note that tp_frame_nr is a redundant parameter because
  167. frames_per_block = tp_block_size/tp_frame_size
  168. indeed, packet_set_ring checks that the following condition is true
  169. frames_per_block * tp_block_nr == tp_frame_nr
  170. Lets see an example, with the following values:
  171. tp_block_size= 4096
  172. tp_frame_size= 2048
  173. tp_block_nr = 4
  174. tp_frame_nr = 8
  175. we will get the following buffer structure:
  176. block #1 block #2
  177. +---------+---------+ +---------+---------+
  178. | frame 1 | frame 2 | | frame 3 | frame 4 |
  179. +---------+---------+ +---------+---------+
  180. block #3 block #4
  181. +---------+---------+ +---------+---------+
  182. | frame 5 | frame 6 | | frame 7 | frame 8 |
  183. +---------+---------+ +---------+---------+
  184. A frame can be of any size with the only condition it can fit in a block. A block
  185. can only hold an integer number of frames, or in other words, a frame cannot
  186. be spawned across two blocks, so there are some details you have to take into
  187. account when choosing the frame_size. See "Mapping and use of the circular
  188. buffer (ring)".
  189. --------------------------------------------------------------------------------
  190. + PACKET_MMAP setting constraints
  191. --------------------------------------------------------------------------------
  192. In kernel versions prior to 2.4.26 (for the 2.4 branch) and 2.6.5 (2.6 branch),
  193. the PACKET_MMAP buffer could hold only 32768 frames in a 32 bit architecture or
  194. 16384 in a 64 bit architecture. For information on these kernel versions
  195. see http://pusa.uv.es/~ulisses/packet_mmap/packet_mmap.pre-2.4.26_2.6.5.txt
  196. Block size limit
  197. ------------------
  198. As stated earlier, each block is a contiguous physical region of memory. These
  199. memory regions are allocated with calls to the __get_free_pages() function. As
  200. the name indicates, this function allocates pages of memory, and the second
  201. argument is "order" or a power of two number of pages, that is
  202. (for PAGE_SIZE == 4096) order=0 ==> 4096 bytes, order=1 ==> 8192 bytes,
  203. order=2 ==> 16384 bytes, etc. The maximum size of a
  204. region allocated by __get_free_pages is determined by the MAX_ORDER macro. More
  205. precisely the limit can be calculated as:
  206. PAGE_SIZE << MAX_ORDER
  207. In a i386 architecture PAGE_SIZE is 4096 bytes
  208. In a 2.4/i386 kernel MAX_ORDER is 10
  209. In a 2.6/i386 kernel MAX_ORDER is 11
  210. So get_free_pages can allocate as much as 4MB or 8MB in a 2.4/2.6 kernel
  211. respectively, with an i386 architecture.
  212. User space programs can include /usr/include/sys/user.h and
  213. /usr/include/linux/mmzone.h to get PAGE_SIZE MAX_ORDER declarations.
  214. The pagesize can also be determined dynamically with the getpagesize (2)
  215. system call.
  216. Block number limit
  217. --------------------
  218. To understand the constraints of PACKET_MMAP, we have to see the structure
  219. used to hold the pointers to each block.
  220. Currently, this structure is a dynamically allocated vector with kmalloc
  221. called pg_vec, its size limits the number of blocks that can be allocated.
  222. +---+---+---+---+
  223. | x | x | x | x |
  224. +---+---+---+---+
  225. | | | |
  226. | | | v
  227. | | v block #4
  228. | v block #3
  229. v block #2
  230. block #1
  231. kmalloc allocates any number of bytes of physically contiguous memory from
  232. a pool of pre-determined sizes. This pool of memory is maintained by the slab
  233. allocator which is at the end the responsible for doing the allocation and
  234. hence which imposes the maximum memory that kmalloc can allocate.
  235. In a 2.4/2.6 kernel and the i386 architecture, the limit is 131072 bytes. The
  236. predetermined sizes that kmalloc uses can be checked in the "size-<bytes>"
  237. entries of /proc/slabinfo
  238. In a 32 bit architecture, pointers are 4 bytes long, so the total number of
  239. pointers to blocks is
  240. 131072/4 = 32768 blocks
  241. PACKET_MMAP buffer size calculator
  242. ------------------------------------
  243. Definitions:
  244. <size-max> : is the maximum size of allocable with kmalloc (see /proc/slabinfo)
  245. <pointer size>: depends on the architecture -- sizeof(void *)
  246. <page size> : depends on the architecture -- PAGE_SIZE or getpagesize (2)
  247. <max-order> : is the value defined with MAX_ORDER
  248. <frame size> : it's an upper bound of frame's capture size (more on this later)
  249. from these definitions we will derive
  250. <block number> = <size-max>/<pointer size>
  251. <block size> = <pagesize> << <max-order>
  252. so, the max buffer size is
  253. <block number> * <block size>
  254. and, the number of frames be
  255. <block number> * <block size> / <frame size>
  256. Suppose the following parameters, which apply for 2.6 kernel and an
  257. i386 architecture:
  258. <size-max> = 131072 bytes
  259. <pointer size> = 4 bytes
  260. <pagesize> = 4096 bytes
  261. <max-order> = 11
  262. and a value for <frame size> of 2048 bytes. These parameters will yield
  263. <block number> = 131072/4 = 32768 blocks
  264. <block size> = 4096 << 11 = 8 MiB.
  265. and hence the buffer will have a 262144 MiB size. So it can hold
  266. 262144 MiB / 2048 bytes = 134217728 frames
  267. Actually, this buffer size is not possible with an i386 architecture.
  268. Remember that the memory is allocated in kernel space, in the case of
  269. an i386 kernel's memory size is limited to 1GiB.
  270. All memory allocations are not freed until the socket is closed. The memory
  271. allocations are done with GFP_KERNEL priority, this basically means that
  272. the allocation can wait and swap other process' memory in order to allocate
  273. the necessary memory, so normally limits can be reached.
  274. Other constraints
  275. -------------------
  276. If you check the source code you will see that what I draw here as a frame
  277. is not only the link level frame. At the beginning of each frame there is a
  278. header called struct tpacket_hdr used in PACKET_MMAP to hold link level's frame
  279. meta information like timestamp. So what we draw here a frame it's really
  280. the following (from include/linux/if_packet.h):
  281. /*
  282. Frame structure:
  283. - Start. Frame must be aligned to TPACKET_ALIGNMENT=16
  284. - struct tpacket_hdr
  285. - pad to TPACKET_ALIGNMENT=16
  286. - struct sockaddr_ll
  287. - Gap, chosen so that packet data (Start+tp_net) aligns to
  288. TPACKET_ALIGNMENT=16
  289. - Start+tp_mac: [ Optional MAC header ]
  290. - Start+tp_net: Packet data, aligned to TPACKET_ALIGNMENT=16.
  291. - Pad to align to TPACKET_ALIGNMENT=16
  292. */
  293. The following are conditions that are checked in packet_set_ring
  294. tp_block_size must be a multiple of PAGE_SIZE (1)
  295. tp_frame_size must be greater than TPACKET_HDRLEN (obvious)
  296. tp_frame_size must be a multiple of TPACKET_ALIGNMENT
  297. tp_frame_nr must be exactly frames_per_block*tp_block_nr
  298. Note that tp_block_size should be chosen to be a power of two or there will
  299. be a waste of memory.
  300. --------------------------------------------------------------------------------
  301. + Mapping and use of the circular buffer (ring)
  302. --------------------------------------------------------------------------------
  303. The mapping of the buffer in the user process is done with the conventional
  304. mmap function. Even the circular buffer is compound of several physically
  305. discontiguous blocks of memory, they are contiguous to the user space, hence
  306. just one call to mmap is needed:
  307. mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  308. If tp_frame_size is a divisor of tp_block_size frames will be
  309. contiguously spaced by tp_frame_size bytes. If not, each
  310. tp_block_size/tp_frame_size frames there will be a gap between
  311. the frames. This is because a frame cannot be spawn across two
  312. blocks.
  313. To use one socket for capture and transmission, the mapping of both the
  314. RX and TX buffer ring has to be done with one call to mmap:
  315. ...
  316. setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &foo, sizeof(foo));
  317. setsockopt(fd, SOL_PACKET, PACKET_TX_RING, &bar, sizeof(bar));
  318. ...
  319. rx_ring = mmap(0, size * 2, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  320. tx_ring = rx_ring + size;
  321. RX must be the first as the kernel maps the TX ring memory right
  322. after the RX one.
  323. At the beginning of each frame there is an status field (see
  324. struct tpacket_hdr). If this field is 0 means that the frame is ready
  325. to be used for the kernel, If not, there is a frame the user can read
  326. and the following flags apply:
  327. +++ Capture process:
  328. from include/linux/if_packet.h
  329. #define TP_STATUS_COPY (1 << 1)
  330. #define TP_STATUS_LOSING (1 << 2)
  331. #define TP_STATUS_CSUMNOTREADY (1 << 3)
  332. #define TP_STATUS_CSUM_VALID (1 << 7)
  333. TP_STATUS_COPY : This flag indicates that the frame (and associated
  334. meta information) has been truncated because it's
  335. larger than tp_frame_size. This packet can be
  336. read entirely with recvfrom().
  337. In order to make this work it must to be
  338. enabled previously with setsockopt() and
  339. the PACKET_COPY_THRESH option.
  340. The number of frames that can be buffered to
  341. be read with recvfrom is limited like a normal socket.
  342. See the SO_RCVBUF option in the socket (7) man page.
  343. TP_STATUS_LOSING : indicates there were packet drops from last time
  344. statistics where checked with getsockopt() and
  345. the PACKET_STATISTICS option.
  346. TP_STATUS_CSUMNOTREADY: currently it's used for outgoing IP packets which
  347. its checksum will be done in hardware. So while
  348. reading the packet we should not try to check the
  349. checksum.
  350. TP_STATUS_CSUM_VALID : This flag indicates that at least the transport
  351. header checksum of the packet has been already
  352. validated on the kernel side. If the flag is not set
  353. then we are free to check the checksum by ourselves
  354. provided that TP_STATUS_CSUMNOTREADY is also not set.
  355. for convenience there are also the following defines:
  356. #define TP_STATUS_KERNEL 0
  357. #define TP_STATUS_USER 1
  358. The kernel initializes all frames to TP_STATUS_KERNEL, when the kernel
  359. receives a packet it puts in the buffer and updates the status with
  360. at least the TP_STATUS_USER flag. Then the user can read the packet,
  361. once the packet is read the user must zero the status field, so the kernel
  362. can use again that frame buffer.
  363. The user can use poll (any other variant should apply too) to check if new
  364. packets are in the ring:
  365. struct pollfd pfd;
  366. pfd.fd = fd;
  367. pfd.revents = 0;
  368. pfd.events = POLLIN|POLLRDNORM|POLLERR;
  369. if (status == TP_STATUS_KERNEL)
  370. retval = poll(&pfd, 1, timeout);
  371. It doesn't incur in a race condition to first check the status value and
  372. then poll for frames.
  373. ++ Transmission process
  374. Those defines are also used for transmission:
  375. #define TP_STATUS_AVAILABLE 0 // Frame is available
  376. #define TP_STATUS_SEND_REQUEST 1 // Frame will be sent on next send()
  377. #define TP_STATUS_SENDING 2 // Frame is currently in transmission
  378. #define TP_STATUS_WRONG_FORMAT 4 // Frame format is not correct
  379. First, the kernel initializes all frames to TP_STATUS_AVAILABLE. To send a
  380. packet, the user fills a data buffer of an available frame, sets tp_len to
  381. current data buffer size and sets its status field to TP_STATUS_SEND_REQUEST.
  382. This can be done on multiple frames. Once the user is ready to transmit, it
  383. calls send(). Then all buffers with status equal to TP_STATUS_SEND_REQUEST are
  384. forwarded to the network device. The kernel updates each status of sent
  385. frames with TP_STATUS_SENDING until the end of transfer.
  386. At the end of each transfer, buffer status returns to TP_STATUS_AVAILABLE.
  387. header->tp_len = in_i_size;
  388. header->tp_status = TP_STATUS_SEND_REQUEST;
  389. retval = send(this->socket, NULL, 0, 0);
  390. The user can also use poll() to check if a buffer is available:
  391. (status == TP_STATUS_SENDING)
  392. struct pollfd pfd;
  393. pfd.fd = fd;
  394. pfd.revents = 0;
  395. pfd.events = POLLOUT;
  396. retval = poll(&pfd, 1, timeout);
  397. -------------------------------------------------------------------------------
  398. + What TPACKET versions are available and when to use them?
  399. -------------------------------------------------------------------------------
  400. int val = tpacket_version;
  401. setsockopt(fd, SOL_PACKET, PACKET_VERSION, &val, sizeof(val));
  402. getsockopt(fd, SOL_PACKET, PACKET_VERSION, &val, sizeof(val));
  403. where 'tpacket_version' can be TPACKET_V1 (default), TPACKET_V2, TPACKET_V3.
  404. TPACKET_V1:
  405. - Default if not otherwise specified by setsockopt(2)
  406. - RX_RING, TX_RING available
  407. TPACKET_V1 --> TPACKET_V2:
  408. - Made 64 bit clean due to unsigned long usage in TPACKET_V1
  409. structures, thus this also works on 64 bit kernel with 32 bit
  410. userspace and the like
  411. - Timestamp resolution in nanoseconds instead of microseconds
  412. - RX_RING, TX_RING available
  413. - VLAN metadata information available for packets
  414. (TP_STATUS_VLAN_VALID, TP_STATUS_VLAN_TPID_VALID),
  415. in the tpacket2_hdr structure:
  416. - TP_STATUS_VLAN_VALID bit being set into the tp_status field indicates
  417. that the tp_vlan_tci field has valid VLAN TCI value
  418. - TP_STATUS_VLAN_TPID_VALID bit being set into the tp_status field
  419. indicates that the tp_vlan_tpid field has valid VLAN TPID value
  420. - How to switch to TPACKET_V2:
  421. 1. Replace struct tpacket_hdr by struct tpacket2_hdr
  422. 2. Query header len and save
  423. 3. Set protocol version to 2, set up ring as usual
  424. 4. For getting the sockaddr_ll,
  425. use (void *)hdr + TPACKET_ALIGN(hdrlen) instead of
  426. (void *)hdr + TPACKET_ALIGN(sizeof(struct tpacket_hdr))
  427. TPACKET_V2 --> TPACKET_V3:
  428. - Flexible buffer implementation:
  429. 1. Blocks can be configured with non-static frame-size
  430. 2. Read/poll is at a block-level (as opposed to packet-level)
  431. 3. Added poll timeout to avoid indefinite user-space wait
  432. on idle links
  433. 4. Added user-configurable knobs:
  434. 4.1 block::timeout
  435. 4.2 tpkt_hdr::sk_rxhash
  436. - RX Hash data available in user space
  437. - Currently only RX_RING available
  438. -------------------------------------------------------------------------------
  439. + AF_PACKET fanout mode
  440. -------------------------------------------------------------------------------
  441. In the AF_PACKET fanout mode, packet reception can be load balanced among
  442. processes. This also works in combination with mmap(2) on packet sockets.
  443. Currently implemented fanout policies are:
  444. - PACKET_FANOUT_HASH: schedule to socket by skb's packet hash
  445. - PACKET_FANOUT_LB: schedule to socket by round-robin
  446. - PACKET_FANOUT_CPU: schedule to socket by CPU packet arrives on
  447. - PACKET_FANOUT_RND: schedule to socket by random selection
  448. - PACKET_FANOUT_ROLLOVER: if one socket is full, rollover to another
  449. - PACKET_FANOUT_QM: schedule to socket by skbs recorded queue_mapping
  450. Minimal example code by David S. Miller (try things like "./test eth0 hash",
  451. "./test eth0 lb", etc.):
  452. #include <stddef.h>
  453. #include <stdlib.h>
  454. #include <stdio.h>
  455. #include <string.h>
  456. #include <sys/types.h>
  457. #include <sys/wait.h>
  458. #include <sys/socket.h>
  459. #include <sys/ioctl.h>
  460. #include <unistd.h>
  461. #include <linux/if_ether.h>
  462. #include <linux/if_packet.h>
  463. #include <net/if.h>
  464. static const char *device_name;
  465. static int fanout_type;
  466. static int fanout_id;
  467. #ifndef PACKET_FANOUT
  468. # define PACKET_FANOUT 18
  469. # define PACKET_FANOUT_HASH 0
  470. # define PACKET_FANOUT_LB 1
  471. #endif
  472. static int setup_socket(void)
  473. {
  474. int err, fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP));
  475. struct sockaddr_ll ll;
  476. struct ifreq ifr;
  477. int fanout_arg;
  478. if (fd < 0) {
  479. perror("socket");
  480. return EXIT_FAILURE;
  481. }
  482. memset(&ifr, 0, sizeof(ifr));
  483. strcpy(ifr.ifr_name, device_name);
  484. err = ioctl(fd, SIOCGIFINDEX, &ifr);
  485. if (err < 0) {
  486. perror("SIOCGIFINDEX");
  487. return EXIT_FAILURE;
  488. }
  489. memset(&ll, 0, sizeof(ll));
  490. ll.sll_family = AF_PACKET;
  491. ll.sll_ifindex = ifr.ifr_ifindex;
  492. err = bind(fd, (struct sockaddr *) &ll, sizeof(ll));
  493. if (err < 0) {
  494. perror("bind");
  495. return EXIT_FAILURE;
  496. }
  497. fanout_arg = (fanout_id | (fanout_type << 16));
  498. err = setsockopt(fd, SOL_PACKET, PACKET_FANOUT,
  499. &fanout_arg, sizeof(fanout_arg));
  500. if (err) {
  501. perror("setsockopt");
  502. return EXIT_FAILURE;
  503. }
  504. return fd;
  505. }
  506. static void fanout_thread(void)
  507. {
  508. int fd = setup_socket();
  509. int limit = 10000;
  510. if (fd < 0)
  511. exit(fd);
  512. while (limit-- > 0) {
  513. char buf[1600];
  514. int err;
  515. err = read(fd, buf, sizeof(buf));
  516. if (err < 0) {
  517. perror("read");
  518. exit(EXIT_FAILURE);
  519. }
  520. if ((limit % 10) == 0)
  521. fprintf(stdout, "(%d) \n", getpid());
  522. }
  523. fprintf(stdout, "%d: Received 10000 packets\n", getpid());
  524. close(fd);
  525. exit(0);
  526. }
  527. int main(int argc, char **argp)
  528. {
  529. int fd, err;
  530. int i;
  531. if (argc != 3) {
  532. fprintf(stderr, "Usage: %s INTERFACE {hash|lb}\n", argp[0]);
  533. return EXIT_FAILURE;
  534. }
  535. if (!strcmp(argp[2], "hash"))
  536. fanout_type = PACKET_FANOUT_HASH;
  537. else if (!strcmp(argp[2], "lb"))
  538. fanout_type = PACKET_FANOUT_LB;
  539. else {
  540. fprintf(stderr, "Unknown fanout type [%s]\n", argp[2]);
  541. exit(EXIT_FAILURE);
  542. }
  543. device_name = argp[1];
  544. fanout_id = getpid() & 0xffff;
  545. for (i = 0; i < 4; i++) {
  546. pid_t pid = fork();
  547. switch (pid) {
  548. case 0:
  549. fanout_thread();
  550. case -1:
  551. perror("fork");
  552. exit(EXIT_FAILURE);
  553. }
  554. }
  555. for (i = 0; i < 4; i++) {
  556. int status;
  557. wait(&status);
  558. }
  559. return 0;
  560. }
  561. -------------------------------------------------------------------------------
  562. + AF_PACKET TPACKET_V3 example
  563. -------------------------------------------------------------------------------
  564. AF_PACKET's TPACKET_V3 ring buffer can be configured to use non-static frame
  565. sizes by doing it's own memory management. It is based on blocks where polling
  566. works on a per block basis instead of per ring as in TPACKET_V2 and predecessor.
  567. It is said that TPACKET_V3 brings the following benefits:
  568. *) ~15 - 20% reduction in CPU-usage
  569. *) ~20% increase in packet capture rate
  570. *) ~2x increase in packet density
  571. *) Port aggregation analysis
  572. *) Non static frame size to capture entire packet payload
  573. So it seems to be a good candidate to be used with packet fanout.
  574. Minimal example code by Daniel Borkmann based on Chetan Loke's lolpcap (compile
  575. it with gcc -Wall -O2 blob.c, and try things like "./a.out eth0", etc.):
  576. /* Written from scratch, but kernel-to-user space API usage
  577. * dissected from lolpcap:
  578. * Copyright 2011, Chetan Loke <loke.chetan@gmail.com>
  579. * License: GPL, version 2.0
  580. */
  581. #include <stdio.h>
  582. #include <stdlib.h>
  583. #include <stdint.h>
  584. #include <string.h>
  585. #include <assert.h>
  586. #include <net/if.h>
  587. #include <arpa/inet.h>
  588. #include <netdb.h>
  589. #include <poll.h>
  590. #include <unistd.h>
  591. #include <signal.h>
  592. #include <inttypes.h>
  593. #include <sys/socket.h>
  594. #include <sys/mman.h>
  595. #include <linux/if_packet.h>
  596. #include <linux/if_ether.h>
  597. #include <linux/ip.h>
  598. #ifndef likely
  599. # define likely(x) __builtin_expect(!!(x), 1)
  600. #endif
  601. #ifndef unlikely
  602. # define unlikely(x) __builtin_expect(!!(x), 0)
  603. #endif
  604. struct block_desc {
  605. uint32_t version;
  606. uint32_t offset_to_priv;
  607. struct tpacket_hdr_v1 h1;
  608. };
  609. struct ring {
  610. struct iovec *rd;
  611. uint8_t *map;
  612. struct tpacket_req3 req;
  613. };
  614. static unsigned long packets_total = 0, bytes_total = 0;
  615. static sig_atomic_t sigint = 0;
  616. static void sighandler(int num)
  617. {
  618. sigint = 1;
  619. }
  620. static int setup_socket(struct ring *ring, char *netdev)
  621. {
  622. int err, i, fd, v = TPACKET_V3;
  623. struct sockaddr_ll ll;
  624. unsigned int blocksiz = 1 << 22, framesiz = 1 << 11;
  625. unsigned int blocknum = 64;
  626. fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
  627. if (fd < 0) {
  628. perror("socket");
  629. exit(1);
  630. }
  631. err = setsockopt(fd, SOL_PACKET, PACKET_VERSION, &v, sizeof(v));
  632. if (err < 0) {
  633. perror("setsockopt");
  634. exit(1);
  635. }
  636. memset(&ring->req, 0, sizeof(ring->req));
  637. ring->req.tp_block_size = blocksiz;
  638. ring->req.tp_frame_size = framesiz;
  639. ring->req.tp_block_nr = blocknum;
  640. ring->req.tp_frame_nr = (blocksiz * blocknum) / framesiz;
  641. ring->req.tp_retire_blk_tov = 60;
  642. ring->req.tp_feature_req_word = TP_FT_REQ_FILL_RXHASH;
  643. err = setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &ring->req,
  644. sizeof(ring->req));
  645. if (err < 0) {
  646. perror("setsockopt");
  647. exit(1);
  648. }
  649. ring->map = mmap(NULL, ring->req.tp_block_size * ring->req.tp_block_nr,
  650. PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, fd, 0);
  651. if (ring->map == MAP_FAILED) {
  652. perror("mmap");
  653. exit(1);
  654. }
  655. ring->rd = malloc(ring->req.tp_block_nr * sizeof(*ring->rd));
  656. assert(ring->rd);
  657. for (i = 0; i < ring->req.tp_block_nr; ++i) {
  658. ring->rd[i].iov_base = ring->map + (i * ring->req.tp_block_size);
  659. ring->rd[i].iov_len = ring->req.tp_block_size;
  660. }
  661. memset(&ll, 0, sizeof(ll));
  662. ll.sll_family = PF_PACKET;
  663. ll.sll_protocol = htons(ETH_P_ALL);
  664. ll.sll_ifindex = if_nametoindex(netdev);
  665. ll.sll_hatype = 0;
  666. ll.sll_pkttype = 0;
  667. ll.sll_halen = 0;
  668. err = bind(fd, (struct sockaddr *) &ll, sizeof(ll));
  669. if (err < 0) {
  670. perror("bind");
  671. exit(1);
  672. }
  673. return fd;
  674. }
  675. static void display(struct tpacket3_hdr *ppd)
  676. {
  677. struct ethhdr *eth = (struct ethhdr *) ((uint8_t *) ppd + ppd->tp_mac);
  678. struct iphdr *ip = (struct iphdr *) ((uint8_t *) eth + ETH_HLEN);
  679. if (eth->h_proto == htons(ETH_P_IP)) {
  680. struct sockaddr_in ss, sd;
  681. char sbuff[NI_MAXHOST], dbuff[NI_MAXHOST];
  682. memset(&ss, 0, sizeof(ss));
  683. ss.sin_family = PF_INET;
  684. ss.sin_addr.s_addr = ip->saddr;
  685. getnameinfo((struct sockaddr *) &ss, sizeof(ss),
  686. sbuff, sizeof(sbuff), NULL, 0, NI_NUMERICHOST);
  687. memset(&sd, 0, sizeof(sd));
  688. sd.sin_family = PF_INET;
  689. sd.sin_addr.s_addr = ip->daddr;
  690. getnameinfo((struct sockaddr *) &sd, sizeof(sd),
  691. dbuff, sizeof(dbuff), NULL, 0, NI_NUMERICHOST);
  692. printf("%s -> %s, ", sbuff, dbuff);
  693. }
  694. printf("rxhash: 0x%x\n", ppd->hv1.tp_rxhash);
  695. }
  696. static void walk_block(struct block_desc *pbd, const int block_num)
  697. {
  698. int num_pkts = pbd->h1.num_pkts, i;
  699. unsigned long bytes = 0;
  700. struct tpacket3_hdr *ppd;
  701. ppd = (struct tpacket3_hdr *) ((uint8_t *) pbd +
  702. pbd->h1.offset_to_first_pkt);
  703. for (i = 0; i < num_pkts; ++i) {
  704. bytes += ppd->tp_snaplen;
  705. display(ppd);
  706. ppd = (struct tpacket3_hdr *) ((uint8_t *) ppd +
  707. ppd->tp_next_offset);
  708. }
  709. packets_total += num_pkts;
  710. bytes_total += bytes;
  711. }
  712. static void flush_block(struct block_desc *pbd)
  713. {
  714. pbd->h1.block_status = TP_STATUS_KERNEL;
  715. }
  716. static void teardown_socket(struct ring *ring, int fd)
  717. {
  718. munmap(ring->map, ring->req.tp_block_size * ring->req.tp_block_nr);
  719. free(ring->rd);
  720. close(fd);
  721. }
  722. int main(int argc, char **argp)
  723. {
  724. int fd, err;
  725. socklen_t len;
  726. struct ring ring;
  727. struct pollfd pfd;
  728. unsigned int block_num = 0, blocks = 64;
  729. struct block_desc *pbd;
  730. struct tpacket_stats_v3 stats;
  731. if (argc != 2) {
  732. fprintf(stderr, "Usage: %s INTERFACE\n", argp[0]);
  733. return EXIT_FAILURE;
  734. }
  735. signal(SIGINT, sighandler);
  736. memset(&ring, 0, sizeof(ring));
  737. fd = setup_socket(&ring, argp[argc - 1]);
  738. assert(fd > 0);
  739. memset(&pfd, 0, sizeof(pfd));
  740. pfd.fd = fd;
  741. pfd.events = POLLIN | POLLERR;
  742. pfd.revents = 0;
  743. while (likely(!sigint)) {
  744. pbd = (struct block_desc *) ring.rd[block_num].iov_base;
  745. if ((pbd->h1.block_status & TP_STATUS_USER) == 0) {
  746. poll(&pfd, 1, -1);
  747. continue;
  748. }
  749. walk_block(pbd, block_num);
  750. flush_block(pbd);
  751. block_num = (block_num + 1) % blocks;
  752. }
  753. len = sizeof(stats);
  754. err = getsockopt(fd, SOL_PACKET, PACKET_STATISTICS, &stats, &len);
  755. if (err < 0) {
  756. perror("getsockopt");
  757. exit(1);
  758. }
  759. fflush(stdout);
  760. printf("\nReceived %u packets, %lu bytes, %u dropped, freeze_q_cnt: %u\n",
  761. stats.tp_packets, bytes_total, stats.tp_drops,
  762. stats.tp_freeze_q_cnt);
  763. teardown_socket(&ring, fd);
  764. return 0;
  765. }
  766. -------------------------------------------------------------------------------
  767. + PACKET_QDISC_BYPASS
  768. -------------------------------------------------------------------------------
  769. If there is a requirement to load the network with many packets in a similar
  770. fashion as pktgen does, you might set the following option after socket
  771. creation:
  772. int one = 1;
  773. setsockopt(fd, SOL_PACKET, PACKET_QDISC_BYPASS, &one, sizeof(one));
  774. This has the side-effect, that packets sent through PF_PACKET will bypass the
  775. kernel's qdisc layer and are forcedly pushed to the driver directly. Meaning,
  776. packet are not buffered, tc disciplines are ignored, increased loss can occur
  777. and such packets are also not visible to other PF_PACKET sockets anymore. So,
  778. you have been warned; generally, this can be useful for stress testing various
  779. components of a system.
  780. On default, PACKET_QDISC_BYPASS is disabled and needs to be explicitly enabled
  781. on PF_PACKET sockets.
  782. -------------------------------------------------------------------------------
  783. + PACKET_TIMESTAMP
  784. -------------------------------------------------------------------------------
  785. The PACKET_TIMESTAMP setting determines the source of the timestamp in
  786. the packet meta information for mmap(2)ed RX_RING and TX_RINGs. If your
  787. NIC is capable of timestamping packets in hardware, you can request those
  788. hardware timestamps to be used. Note: you may need to enable the generation
  789. of hardware timestamps with SIOCSHWTSTAMP (see related information from
  790. Documentation/networking/timestamping.txt).
  791. PACKET_TIMESTAMP accepts the same integer bit field as SO_TIMESTAMPING:
  792. int req = SOF_TIMESTAMPING_RAW_HARDWARE;
  793. setsockopt(fd, SOL_PACKET, PACKET_TIMESTAMP, (void *) &req, sizeof(req))
  794. For the mmap(2)ed ring buffers, such timestamps are stored in the
  795. tpacket{,2,3}_hdr structure's tp_sec and tp_{n,u}sec members. To determine
  796. what kind of timestamp has been reported, the tp_status field is binary |'ed
  797. with the following possible bits ...
  798. TP_STATUS_TS_RAW_HARDWARE
  799. TP_STATUS_TS_SOFTWARE
  800. ... that are equivalent to its SOF_TIMESTAMPING_* counterparts. For the
  801. RX_RING, if neither is set (i.e. PACKET_TIMESTAMP is not set), then a
  802. software fallback was invoked *within* PF_PACKET's processing code (less
  803. precise).
  804. Getting timestamps for the TX_RING works as follows: i) fill the ring frames,
  805. ii) call sendto() e.g. in blocking mode, iii) wait for status of relevant
  806. frames to be updated resp. the frame handed over to the application, iv) walk
  807. through the frames to pick up the individual hw/sw timestamps.
  808. Only (!) if transmit timestamping is enabled, then these bits are combined
  809. with binary | with TP_STATUS_AVAILABLE, so you must check for that in your
  810. application (e.g. !(tp_status & (TP_STATUS_SEND_REQUEST | TP_STATUS_SENDING))
  811. in a first step to see if the frame belongs to the application, and then
  812. one can extract the type of timestamp in a second step from tp_status)!
  813. If you don't care about them, thus having it disabled, checking for
  814. TP_STATUS_AVAILABLE resp. TP_STATUS_WRONG_FORMAT is sufficient. If in the
  815. TX_RING part only TP_STATUS_AVAILABLE is set, then the tp_sec and tp_{n,u}sec
  816. members do not contain a valid value. For TX_RINGs, by default no timestamp
  817. is generated!
  818. See include/linux/net_tstamp.h and Documentation/networking/timestamping
  819. for more information on hardware timestamps.
  820. -------------------------------------------------------------------------------
  821. + Miscellaneous bits
  822. -------------------------------------------------------------------------------
  823. - Packet sockets work well together with Linux socket filters, thus you also
  824. might want to have a look at Documentation/networking/filter.txt
  825. --------------------------------------------------------------------------------
  826. + THANKS
  827. --------------------------------------------------------------------------------
  828. Jesse Brandeburg, for fixing my grammathical/spelling errors