packet_mmap.txt 34 KB

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