← Documents Documentation/networking/packet_mmap.rst GitHub 원문 ↗

Linux 6.18.37 · Networking

Packet MMAP

AF_PACKET shared-memory RX·TX ring의 설정, memory layout, status protocol, TPACKET version과 fanout입니다.

Source pathDocumentation/networking/packet_mmap.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

packet_mmap.rst:1-1084

PACKET_MMAP은 kernel과 userspace가 block·frame ring을 공유해 packet마다 system call과 copy가 발생하는 비용을 줄입니다. 정확한 block/frame 산술, alignment와 status 기반 ownership protocol을 지키는 것이 핵심이며 고성능 RX에는 TPACKET_V3·fanout을 함께 사용할 수 있습니다.

PACKET_MMAP 핵심 lifecycle
PF_PACKET socketsetsockopt RX/TX_RINGmmap shared blockskernel/user status handoffpoll only when neededclose releases memory

설정부터 ring 소유권 교환까지입니다.

2. 영어 원문 전체

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

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

3. 한국어 전문 번역

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

PACKET socket mmap facility

1-24

이 문서는 `PACKET` socket interface에서 제공하는 `mmap()` facility를 설명합니다. 이 socket은 `tcpdump` 같은 utility로 network traffic을 capture하거나, network traffic을 송신하거나, network interface에 raw access가 필요한 다른 작업에 사용합니다.

How-to archive URL과 의견을 보낼 Ulisses Alonso Camaró·Johann Baudy의 연락처는 원문에 그대로 보존되어 있습니다.

.. SPDX-License-Identifier: GPL-2.0

===========
Packet MMAP
===========

Abstract
========

This file documents the mmap() facility available with the PACKET
socket interface. This type of sockets is used for

i) capture network traffic with utilities like tcpdump,
ii) transmit network traffic, or any other that needs raw
    access to network interface.

Howto can be found at:

    https://web.archive.org/web/20220404160947/https://sites.google.com/site/packetmmap/

Please send your comments to
    - Ulisses Alonso Camaró <uaca@i.hate.spam.alumni.uv.es>
    - Johann Baudy

PACKET_MMAP의 효율과 system tuning

25-49

일반 `AF_PACKET`을 쓰는 non-PACKET_MMAP capture는 매우 비효율적입니다. Buffer가 제한적이고 packet 하나를 capture할 때마다 system call 하나가 필요합니다. Libpcap처럼 timestamp까지 얻으려면 두 번 필요합니다.

반면 `PACKET_MMAP`은 크기를 설정할 수 있고 userspace에 mapping되는 circular buffer를 제공하여 송신과 수신에 모두 쓸 수 있습니다. 수신은 보통 packet을 기다리기만 하면 되어 system call이 거의 필요 없고, 송신은 한 system call로 여러 packet을 보내 최대 bandwidth를 얻을 수 있습니다. Kernel과 user가 buffer를 공유하므로 packet copy도 최소화합니다.

고속 capture에서는 PACKET_MMAP만으로 충분하지 않습니다. NIC driver가 interrupt load mitigation 또는 더 나은 NAPI를 지원하고 실제 활성화되어 있는지 확인해야 합니다. 송신에서는 network device가 사용·지원하는 MTU를 확인하고, NIC CPU IRQ pinning도 고려할 수 있습니다.

Plain AF_PACKET과 PACKET_MMAP
방식System call·copy 특성
Plain AF_PACKETpacket마다 capture call, timestamp까지 두 call, 제한된 buffer
PACKET_MMAP RXshared circular ring을 읽고 필요할 때 poll
PACKET_MMAP TX여러 ready packet을 send 한 번으로 전달

Packet I/O 비용의 핵심 차이입니다.

Why use PACKET_MMAP
===================

Non PACKET_MMAP capture process (plain AF_PACKET) is very
inefficient. It uses very limited buffers and requires one system call to
capture each packet, it requires two if you want to get packet's timestamp
(like libpcap always does).

On the other hand PACKET_MMAP is very efficient. PACKET_MMAP provides a size
configurable circular buffer mapped in user space that can be used to either
send or receive packets. This way reading packets just needs to wait for them,
most of the time there is no need to issue a single system call. Concerning
transmission, multiple packets can be sent through one system call to get the
highest bandwidth. By using a shared buffer between the kernel and the user
also has the benefit of minimizing packet copies.

It's fine to use PACKET_MMAP to improve the performance of the capture and
transmission process, but it isn't everything. At least, if you are capturing
at high speeds (this is relative to the cpu speed), you should check if the
device driver of your network interface card supports some sort of interrupt
load mitigation or (even better) if it supports NAPI, also make sure it is
enabled. For transmission, check the MTU (Maximum Transmission Unit) used and
supported by devices of your network. CPU IRQ pinning of your network interface
card can also be an advantage.

Libpcap을 통한 capture

50-59

일반 application은 사실상 표준이며 Win32를 포함한 거의 모든 OS에서 portable한 상위 library `libpcap`을 사용하는 편이 좋습니다. Packet MMAP 지원은 libpcap 1.3.0 무렵 통합되었고 `TPACKET_V3` 지원은 1.5.0에서 추가되었습니다.

How to use mmap() to improve capture process
============================================

From the user standpoint, you should use the higher level libpcap library, which
is a de facto standard, portable across nearly all operating systems
including Win32.

Packet MMAP support was integrated into libpcap around the time of version 1.3.0;
TPACKET_V3 support was added in version 1.5.0

직접 RX ring을 설정하는 절차

60-102

System-call 관점에서 capture setup은 `socket()`으로 capture socket을 만들고 `setsockopt(PACKET_RX_RING)`로 circular ring을 할당한 뒤 `mmap()`으로 process에 mapping합니다. Capture 중에는 `poll()`로 incoming packet을 기다리고, 종료할 때 `close()`가 socket과 모든 관련 resource를 파괴·해제합니다.

Socket은 `socket(PF_PACKET, mode, htons(ETH_P_ALL))`로 만듭니다. `mode=SOCK_RAW`이면 link-level 정보를 그대로 capture하고, `SOCK_DGRAM`이면 link-level capture를 지원하지 않는 cooked interface가 되어 kernel이 pseudo-header를 제공합니다. 종료는 `close(fd)` 한 번이면 됩니다.

PACKET_MMAP을 쓰지 않을 때와 마찬가지로 socket 하나를 capture와 transmission에 같이 쓸 수 있습니다. RX·TX ring을 `mmap()` 한 번으로 함께 mapping하면 되며 자세한 배치는 뒤의 circular-buffer 절에서 설명합니다.

PACKET_MMAP capture lifecycle
socket(PF_PACKET)setsockopt(PACKET_RX_RING)mmap shared ringpoll incoming packetframe 처리close

원문의 setup·capture·shutdown ASCII 절차를 구조화했습니다.

How to use mmap() directly to improve capture process
=====================================================

From the system calls stand point, the use of PACKET_MMAP involves
the following process::


    [setup]     socket() -------> creation of the capture socket
                setsockopt() ---> allocation of the circular buffer (ring)
                                  option: PACKET_RX_RING
                mmap() ---------> mapping of the allocated buffer to the
                                  user process

    [capture]   poll() ---------> to wait for incoming packets

    [shutdown]  close() --------> destruction of the capture socket and
                                  deallocation of all associated
                                  resources.


socket creation and destruction is straight forward, and is done
the same way with or without PACKET_MMAP::

 int fd = socket(PF_PACKET, mode, htons(ETH_P_ALL));

where mode is SOCK_RAW for the raw interface were link level
information can be captured or SOCK_DGRAM for the cooked
interface where link level information capture is not
supported and a link level pseudo-header is provided
by the kernel.

The destruction of the socket and all associated resources
is done by a simple call to close(fd).

Similarly as without PACKET_MMAP, it is possible to use one socket
for capture and transmission. This can be done by mapping the
allocated RX and TX buffer ring with a single mmap() call.
See "Mapping and use of the circular buffer (ring)".

Next I will describe PACKET_MMAP settings and its constraints,
also the mapping of the circular buffer in the user process and
the use of this buffer.

직접 TX ring을 설정하는 절차

103-186

Transmission도 capture와 비슷합니다. `socket()`을 만든 뒤 `setsockopt(PACKET_TX_RING)`으로 ring을 할당하고 `bind()`로 network interface에 묶은 다음 `mmap()`합니다. 필요하면 `poll()`로 빈 frame을 기다리고 `send()`로 ready 상태인 모든 packet을 보냅니다. `MSG_DONTWAIT` flag를 쓰면 transfer가 끝나기 전에 반환할 수 있고, `close()`가 socket과 resource를 정리합니다.

송신 전용이라면 `socket(PF_PACKET, mode, 0)`처럼 protocol을 0으로 둘 수 있습니다. 그러면 비용이 큰 `packet_rcv()` 호출을 피합니다. 이때 `bind(2)`하는 TX_RING의 `sll_protocol`도 0이어야 합니다. 그렇지 않으면 `htons(ETH_P_ALL)` 또는 원하는 다른 protocol을 사용합니다.

Zero-copy에서는 circular buffer frame의 header 크기를 알려면 socket을 network interface에 bind해야 하므로 binding이 필수입니다. 각 frame은 상태를 담은 `struct tpacket_hdr`와 network interface로 보낼 data buffer로 구성됩니다. `sockaddr_ll.sll_ifindex`가 socket을 interface에 연결합니다.

초기화 예제는 `ifreq.ifr_name`에 `eth0`을 넣고 `ioctl(SIOCGIFINDEX)`로 index를 얻습니다. 이어 `sockaddr_ll`의 `sll_family=AF_PACKET`, `sll_protocol=htons(ETH_P_ALL)`, `sll_ifindex`를 채워 `bind()`합니다. 전체 tutorial URL도 원문에 보존했습니다.

기본 user data 위치는 `frame base + TPACKET_HDRLEN - sizeof(struct sockaddr_ll)`입니다. Socket이 `SOCK_DGRAM`이든 `SOCK_RAW`든 user data 시작은 `frame base + TPACKET_ALIGN(sizeof(struct tpacket_hdr))`입니다.

Frame 시작에서 custom offset을 쓰려면 `SOCK_DGRAM`은 `tp_net`, `SOCK_RAW`는 `tp_mac`을 설정합니다. Payload alignment가 필요한 경우가 예입니다. 이 기능은 먼저 `setsockopt()`의 `PACKET_TX_HAS_OFF` option으로 활성화해야 합니다.

PACKET_MMAP transmission lifecycle
socket(PF_PACKET)setsockopt(PACKET_TX_RING)bind interfacemmap ringpoll free frame (optional)send ready framesclose

원문의 TX setup·send·shutdown 절차입니다.

TX frame memory layout
Frame basestruct tpacket_hdraligned data buffernetwork interface

원문의 frame ASCII 블록을 header와 payload로 정리했습니다.

How to use mmap() directly to improve transmission process
==========================================================
Transmission process is similar to capture as shown below::

    [setup]         socket() -------> creation of the transmission socket
                    setsockopt() ---> allocation of the circular buffer (ring)
                                      option: PACKET_TX_RING
                    bind() ---------> bind transmission socket with a network interface
                    mmap() ---------> mapping of the allocated buffer to the
                                      user process

    [transmission]  poll() ---------> wait for free packets (optional)
                    send() ---------> send all packets that are set as ready in
                                      the ring
                                      The flag MSG_DONTWAIT can be used to return
                                      before end of transfer.

    [shutdown]      close() --------> destruction of the transmission socket and
                                      deallocation of all associated resources.

Socket creation and destruction is also straight forward, and is done
the same way as in capturing described in the previous paragraph::

 int fd = socket(PF_PACKET, mode, 0);

The protocol can optionally be 0 in case we only want to transmit
via this socket, which avoids an expensive call to packet_rcv().
In this case, you also need to bind(2) the TX_RING with sll_protocol = 0
set. Otherwise, htons(ETH_P_ALL) or any other protocol, for example.

Binding the socket to your network interface is mandatory (with zero copy) to
know the header size of frames used in the circular buffer.

As capture, each frame contains two parts::

    --------------------
    | struct tpacket_hdr | Header. It contains the status of
    |                    | of this frame
    |--------------------|
    | data buffer        |
    .                    .  Data that will be sent over the network interface.
    .                    .
    --------------------

 bind() associates the socket to your network interface thanks to
 sll_ifindex parameter of struct sockaddr_ll.

 Initialization example::

    struct sockaddr_ll my_addr;
    struct ifreq s_ifr;
    ...

    strscpy_pad (s_ifr.ifr_name, "eth0", sizeof(s_ifr.ifr_name));

    /* get interface index of eth0 */
    ioctl(this->socket, SIOCGIFINDEX, &s_ifr);

    /* fill sockaddr_ll struct to prepare binding */
    my_addr.sll_family = AF_PACKET;
    my_addr.sll_protocol = htons(ETH_P_ALL);
    my_addr.sll_ifindex =  s_ifr.ifr_ifindex;

    /* bind socket to eth0 */
    bind(this->socket, (struct sockaddr *)&my_addr, sizeof(struct sockaddr_ll));

 A complete tutorial is available at:
 https://web.archive.org/web/20220404160947/https://sites.google.com/site/packetmmap/

By default, the user should put data at::

 frame base + TPACKET_HDRLEN - sizeof(struct sockaddr_ll)

So, whatever you choose for the socket mode (SOCK_DGRAM or SOCK_RAW),
the beginning of the user data will be at::

 frame base + TPACKET_ALIGN(sizeof(struct tpacket_hdr))

If you wish to put user data at a custom offset from the beginning of
the frame (for payload alignment with SOCK_RAW mode for instance) you
can set tp_net (with SOCK_DGRAM) or tp_mac (with SOCK_RAW). In order
to make this work it must be enabled previously with setsockopt()
and the PACKET_TX_HAS_OFF option.

tpacket_req와 block·frame ring

187-250

Userspace에서 capture ring은 `setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &req, sizeof(req))`, transmission ring은 `PACKET_TX_RING` option으로 설정합니다. 핵심 argument `struct tpacket_req`에는 `tp_block_size`, `tp_block_nr`, `tp_frame_size`, `tp_frame_nr`가 있습니다.

이 구조체는 `/usr/include/linux/if_packet.h`에 정의되며 swap되지 않는 circular buffer를 만듭니다. Capture process에 mapping하면 system call 없이 captured frame과 timestamp 같은 metadata를 읽을 수 있습니다.

Frame은 block으로 묶입니다. 각 block은 물리적으로 contiguous한 memory region이고 `tp_block_size / tp_frame_size`개의 frame을 담습니다. Block 총수는 `tp_block_nr`입니다. `tp_frame_nr`은 중복 정보이며 `frames_per_block = tp_block_size / tp_frame_size`, `frames_per_block * tp_block_nr == tp_frame_nr` 조건을 `packet_set_ring`이 검사합니다.

예제에서 block size 4096, frame size 2048, block 4개, frame 8개를 지정하면 block마다 frame 두 개씩 들어갑니다. Block #1은 frame 1·2, #2는 3·4, #3은 5·6, #4는 7·8을 담습니다.

Frame 크기는 block 안에 들어가기만 하면 자유롭지만 block에는 정수 개 frame만 들어갑니다. Frame 하나가 block 두 개에 걸칠 수 없으므로 `tp_frame_size` 선택 시 뒤의 mapping 절에 설명한 gap 가능성을 고려해야 합니다.

struct tpacket_req
Field의미
tp_block_size물리적으로 contiguous한 block 최소 크기
tp_block_nrblock 수
tp_frame_sizeframe 크기
tp_frame_nr전체 frame 수

PACKET_RX_RING·PACKET_TX_RING의 네 설정값입니다.

4096/2048 ring 예제
BlockFrames
#11, 2
#23, 4
#35, 6
#47, 8

원문의 네 block ASCII 배치를 구조화했습니다.

PACKET_MMAP settings
====================

To setup PACKET_MMAP from user level code is done with a call like

 - Capture process::

     setsockopt(fd, SOL_PACKET, PACKET_RX_RING, (void *) &req, sizeof(req))

 - Transmission process::

     setsockopt(fd, SOL_PACKET, PACKET_TX_RING, (void *) &req, sizeof(req))

The most significant argument in the previous call is the req parameter,
this parameter must to have the following structure::

    struct tpacket_req
    {
        unsigned int    tp_block_size;  /* Minimal size of contiguous block */
        unsigned int    tp_block_nr;    /* Number of blocks */
        unsigned int    tp_frame_size;  /* Size of frame */
        unsigned int    tp_frame_nr;    /* Total number of frames */
    };

This structure is defined in /usr/include/linux/if_packet.h and establishes a
circular buffer (ring) of unswappable memory.
Being mapped in the capture process allows reading the captured frames and
related meta-information like timestamps without requiring a system call.

Frames are grouped in blocks. Each block is a physically contiguous
region of memory and holds tp_block_size/tp_frame_size frames. The total number
of blocks is tp_block_nr. Note that tp_frame_nr is a redundant parameter because::

    frames_per_block = tp_block_size/tp_frame_size

indeed, packet_set_ring checks that the following condition is true::

    frames_per_block * tp_block_nr == tp_frame_nr

Lets see an example, with the following values::

     tp_block_size= 4096
     tp_frame_size= 2048
     tp_block_nr  = 4
     tp_frame_nr  = 8

we will get the following buffer structure::

            block #1                 block #2
    +---------+---------+    +---------+---------+
    | frame 1 | frame 2 |    | frame 3 | frame 4 |
    +---------+---------+    +---------+---------+

            block #3                 block #4
    +---------+---------+    +---------+---------+
    | frame 5 | frame 6 |    | frame 7 | frame 8 |
    +---------+---------+    +---------+---------+

A frame can be of any size with the only condition it can fit in a block. A block
can only hold an integer number of frames, or in other words, a frame cannot
be spawned across two blocks, so there are some details you have to take into
account when choosing the frame_size. See "Mapping and use of the circular
buffer (ring)".

Block size와 block count 제약

251-317

2.4 branch의 2.4.26 이전과 2.6 branch의 2.6.5 이전 kernel에서는 PACKET_MMAP buffer가 32비트 architecture에서 32768 frame, 64비트에서 16384 frame만 담을 수 있었습니다.

각 block은 contiguous physical memory이며 `__get_free_pages()`로 할당합니다. 두 번째 argument `order`는 2의 거듭제곱 page 수입니다. `PAGE_SIZE=4096`일 때 order 0·1·2는 각각 4096·8192·16384 byte입니다. 최대 region은 `MAX_PAGE_ORDER`가 정하며 `PAGE_SIZE << MAX_PAGE_ORDER`로 계산합니다.

i386의 page size는 4096 byte이고 2.4 kernel의 `MAX_PAGE_ORDER`는 10, 2.6 kernel은 11이므로 `get_free_pages`가 할당할 수 있는 최대치는 각각 4 MB와 8 MB입니다. Program은 `sys/user.h`와 `linux/mmzone.h`에서 선언을 얻거나 `getpagesize(2)`로 page size를 동적으로 구할 수 있습니다.

Block pointer는 `kmalloc`으로 동적 할당한 vector `pg_vec`에 저장됩니다. Vector 크기가 block 수를 제한합니다. `kmalloc`은 slab allocator가 관리하는 미리 정한 크기의 pool에서 물리적으로 contiguous한 byte를 할당하므로 slab allocator의 최대 allocation이 한도입니다.

2.4/2.6 i386 kernel의 예시 한도는 131072 byte이며 `/proc/slabinfo`의 `size-<bytes>` entry에서 `kmalloc` 크기를 확인할 수 있습니다. 32비트 pointer는 4 byte이므로 최대 pointer 수는 `131072 / 4 = 32768 blocks`입니다.

pg_vec block pointer
pg_vec[0]block #1
pg_vec[1]block #2
pg_vec[2]block #3
pg_vec[3]block #4

원문의 pointer-vector ASCII 구조를 재구성했습니다.

PACKET_MMAP setting constraints
===============================

In kernel versions prior to 2.4.26 (for the 2.4 branch) and 2.6.5 (2.6 branch),
the PACKET_MMAP buffer could hold only 32768 frames in a 32 bit architecture or
16384 in a 64 bit architecture.

Block size limit
----------------

As stated earlier, each block is a contiguous physical region of memory. These
memory regions are allocated with calls to the __get_free_pages() function. As
the name indicates, this function allocates pages of memory, and the second
argument is "order" or a power of two number of pages, that is
(for PAGE_SIZE == 4096) order=0 ==> 4096 bytes, order=1 ==> 8192 bytes,
order=2 ==> 16384 bytes, etc. The maximum size of a
region allocated by __get_free_pages is determined by the MAX_PAGE_ORDER macro.
More precisely the limit can be calculated as::

   PAGE_SIZE << MAX_PAGE_ORDER

   In a i386 architecture PAGE_SIZE is 4096 bytes
   In a 2.4/i386 kernel MAX_PAGE_ORDER is 10
   In a 2.6/i386 kernel MAX_PAGE_ORDER is 11

So get_free_pages can allocate as much as 4MB or 8MB in a 2.4/2.6 kernel
respectively, with an i386 architecture.

User space programs can include /usr/include/sys/user.h and
/usr/include/linux/mmzone.h to get PAGE_SIZE MAX_PAGE_ORDER declarations.

The pagesize can also be determined dynamically with the getpagesize (2)
system call.

Block number limit
------------------

To understand the constraints of PACKET_MMAP, we have to see the structure
used to hold the pointers to each block.

Currently, this structure is a dynamically allocated vector with kmalloc
called pg_vec, its size limits the number of blocks that can be allocated::

    +---+---+---+---+
    | x | x | x | x |
    +---+---+---+---+
      |   |   |   |
      |   |   |   v
      |   |   v  block #4
      |   v  block #3
      v  block #2
     block #1

kmalloc allocates any number of bytes of physically contiguous memory from
a pool of pre-determined sizes. This pool of memory is maintained by the slab
allocator which is at the end the responsible for doing the allocation and
hence which imposes the maximum memory that kmalloc can allocate.

In a 2.4/2.6 kernel and the i386 architecture, the limit is 131072 bytes. The
predetermined sizes that kmalloc uses can be checked in the "size-<bytes>"
entries of /proc/slabinfo

In a 32 bit architecture, pointers are 4 bytes long, so the total number of
pointers to blocks is::

     131072/4 = 32768 blocks

최대 buffer와 frame 수 계산

318-369

계산에 쓰는 `<size-max>`는 `kmalloc`의 최대 할당 크기(`/proc/slabinfo`), `<pointer size>`는 architecture의 `sizeof(void *)`, `<page size>`는 `PAGE_SIZE` 또는 `getpagesize(2)`, `<max-order>`는 `MAX_PAGE_ORDER`, `<frame size>`는 frame capture 크기의 상한입니다.

여기서 `<block number> = <size-max> / <pointer size>`, `<block size> = <page size> << <max-order>`를 얻습니다. 최대 buffer 크기는 `<block number> * <block size>`, frame 수는 그 값을 `<frame size>`로 나눈 것입니다.

2.6 i386 예제로 size-max 131072 byte, pointer 4 byte, page 4096 byte, max-order 11, frame 2048 byte를 대입합니다. Block 수는 32768, block 크기는 8 MiB이며 계산상 buffer는 262144 MiB, frame은 134217728개입니다.

하지만 i386에서는 이 buffer가 실제로 가능하지 않습니다. Memory가 kernel space에서 할당되고 i386 kernel memory는 1 GiB로 제한되기 때문입니다. Allocation은 socket을 닫을 때까지 해제되지 않습니다. `GFP_KERNEL` priority로 할당하므로 기다리거나 다른 process memory를 swap할 수 있어 일반적으로 현실적 한도까지 접근할 수 있습니다.

PACKET_MMAP capacity 공식
항목공식
block numbersize-max / pointer size
block sizepage size << max-order
buffer sizeblock number * block size
frame countbuffer size / frame size

Block pointer와 page-order 제약을 결합합니다.

PACKET_MMAP buffer size calculator
==================================

Definitions:

==============  ================================================================
<size-max>      is the maximum size of allocable with kmalloc
                (see /proc/slabinfo)
<pointer size>  depends on the architecture -- ``sizeof(void *)``
<page size>     depends on the architecture -- PAGE_SIZE or getpagesize (2)
<max-order>     is the value defined with MAX_PAGE_ORDER
<frame size>    it's an upper bound of frame's capture size (more on this later)
==============  ================================================================

from these definitions we will derive::

        <block number> = <size-max>/<pointer size>
        <block size> = <pagesize> << <max-order>

so, the max buffer size is::

        <block number> * <block size>

and, the number of frames be::

        <block number> * <block size> / <frame size>

Suppose the following parameters, which apply for 2.6 kernel and an
i386 architecture::

        <size-max> = 131072 bytes
        <pointer size> = 4 bytes
        <pagesize> = 4096 bytes
        <max-order> = 11

and a value for <frame size> of 2048 bytes. These parameters will yield::

        <block number> = 131072/4 = 32768 blocks
        <block size> = 4096 << 11 = 8 MiB.

and hence the buffer will have a 262144 MiB size. So it can hold
262144 MiB / 2048 bytes = 134217728 frames

Actually, this buffer size is not possible with an i386 architecture.
Remember that the memory is allocated in kernel space, in the case of
an i386 kernel's memory size is limited to 1GiB.

All memory allocations are not freed until the socket is closed. The memory
allocations are done with GFP_KERNEL priority, this basically means that
the allocation can wait and swap other process' memory in order to allocate
the necessary memory, so normally limits can be reached.

실제 frame layout과 packet_set_ring 검사

370-402

여기서 말하는 frame은 link-level frame만이 아닙니다. 앞부분에 timestamp 같은 link-level metadata를 담는 `struct tpacket_hdr`가 있습니다. `include/linux/if_packet.h`가 설명하는 순서는 16-byte `TPACKET_ALIGNMENT`에 맞춘 frame 시작, `tpacket_hdr`, 16-byte padding, `sockaddr_ll`, packet data가 정렬되도록 고른 gap, 선택적 MAC header(`Start+tp_mac`), 정렬된 packet data(`Start+tp_net`), 마지막 padding입니다.

`packet_set_ring`은 `tp_block_size`가 `PAGE_SIZE`의 배수인지, `tp_frame_size`가 `TPACKET_HDRLEN`보다 큰지, frame size가 `TPACKET_ALIGNMENT`의 배수인지, `tp_frame_nr`이 정확히 `frames_per_block * tp_block_nr`인지 검사합니다.

`tp_block_size`를 2의 거듭제곱으로 고르지 않으면 memory가 낭비될 수 있습니다.

PACKET_MMAP frame layout
16-byte aligned frame startstruct tpacket_hdralignment padstruct sockaddr_llalignment gapoptional MAC header at tp_macpacket data at tp_netfinal pad

원문의 include/linux/if_packet.h 주석 구조를 순서대로 옮겼습니다.

Other constraints
-----------------

If you check the source code you will see that what I draw here as a frame
is not only the link level frame. At the beginning of each frame there is a
header called struct tpacket_hdr used in PACKET_MMAP to hold link level's frame
meta information like timestamp. So what we draw here a frame it's really
the following (from include/linux/if_packet.h)::

 /*
   Frame structure:

   - Start. Frame must be aligned to TPACKET_ALIGNMENT=16
   - struct tpacket_hdr
   - pad to TPACKET_ALIGNMENT=16
   - struct sockaddr_ll
   - Gap, chosen so that packet data (Start+tp_net) aligns to
     TPACKET_ALIGNMENT=16
   - Start+tp_mac: [ Optional MAC header ]
   - Start+tp_net: Packet data, aligned to TPACKET_ALIGNMENT=16.
   - Pad to align to TPACKET_ALIGNMENT=16
 */

The following are conditions that are checked in packet_set_ring

   - tp_block_size must be a multiple of PAGE_SIZE (1)
   - tp_frame_size must be greater than TPACKET_HDRLEN (obvious)
   - tp_frame_size must be a multiple of TPACKET_ALIGNMENT
   - tp_frame_nr   must be exactly frames_per_block*tp_block_nr

Note that tp_block_size should be chosen to be a power of two or there will
be a waste of memory.

Ring mmap과 RX·TX 동시 mapping

403-436

User process는 일반 `mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)` 호출로 buffer를 mapping합니다. Circular buffer가 물리적으로 떨어진 여러 block으로 구성되어도 userspace에서는 contiguous하게 보이므로 `mmap()` 한 번이면 됩니다.

`tp_frame_size`가 `tp_block_size`의 divisor이면 frame이 `tp_frame_size` byte 간격으로 연속 배치됩니다. 아니면 block마다 `tp_block_size / tp_frame_size`개 frame 뒤에 gap이 생깁니다. Frame은 block 두 개에 걸칠 수 없기 때문입니다.

Socket 하나를 capture와 transmission에 같이 쓰려면 RX_RING과 TX_RING을 설정한 뒤 `mmap()` 한 번으로 크기 합계를 mapping합니다. Kernel은 TX ring memory를 RX 바로 뒤에 mapping하므로 RX가 먼저 와야 합니다. 예제는 `rx_ring = mmap(..., size * 2, ...)`, `tx_ring = rx_ring + size`로 나눕니다.

각 frame 시작의 `tpacket_hdr`에는 status field가 있습니다. 0이면 kernel이 사용할 준비가 된 frame이고, 0이 아니면 user가 읽을 frame이 있으며 다음 절의 flag가 적용됩니다.

Combined RX·TX mmap
mmap baseRX ring [size]TX ring [size]base + 2*size

두 ring을 하나의 userspace virtual range에 배치합니다.

Mapping and use of the circular buffer (ring)
---------------------------------------------

The mapping of the buffer in the user process is done with the conventional
mmap function. Even the circular buffer is compound of several physically
discontiguous blocks of memory, they are contiguous to the user space, hence
just one call to mmap is needed::

    mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

If tp_frame_size is a divisor of tp_block_size frames will be
contiguously spaced by tp_frame_size bytes. If not, each
tp_block_size/tp_frame_size frames there will be a gap between
the frames. This is because a frame cannot be spawn across two
blocks.

To use one socket for capture and transmission, the mapping of both the
RX and TX buffer ring has to be done with one call to mmap::

    ...
    setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &foo, sizeof(foo));
    setsockopt(fd, SOL_PACKET, PACKET_TX_RING, &bar, sizeof(bar));
    ...
    rx_ring = mmap(0, size * 2, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    tx_ring = rx_ring + size;

RX must be the first as the kernel maps the TX ring memory right
after the RX one.

At the beginning of each frame there is an status field (see
struct tpacket_hdr). If this field is 0 means that the frame is ready
to be used for the kernel, If not, there is a frame the user can read
and the following flags apply:

RX frame status와 소유권

437-502

Capture status에는 `TP_STATUS_COPY`, `TP_STATUS_LOSING`, `TP_STATUS_CSUMNOTREADY`, `TP_STATUS_CSUM_VALID`가 있습니다. `COPY`는 packet과 metadata가 `tp_frame_size`보다 커 잘렸음을 뜻하며 `recvfrom()`으로 전체 packet을 읽을 수 있습니다. 먼저 `setsockopt(PACKET_COPY_THRESH)`로 켜야 하고, 일반 socket처럼 `SO_RCVBUF`에 의해 recvfrom용 buffered frame 수가 제한됩니다.

`TP_STATUS_LOSING`은 마지막으로 `getsockopt(PACKET_STATISTICS)`를 확인한 뒤 packet drop이 있었음을 뜻합니다. `TP_STATUS_CSUMNOTREADY`는 현재 hardware가 checksum을 계산할 outgoing IP packet에 사용되므로 읽을 때 checksum을 검사하면 안 됩니다.

`TP_STATUS_CSUM_VALID`는 적어도 transport-header checksum이 kernel에서 이미 검증되었음을 뜻합니다. 이 flag가 없고 `CSUMNOTREADY`도 없다면 application이 직접 checksum을 검사할 수 있습니다.

편의상 `TP_STATUS_KERNEL=0`, `TP_STATUS_USER=1`도 정의됩니다. Kernel은 모든 frame을 KERNEL 상태로 초기화하고 packet을 받으면 buffer에 넣은 뒤 최소 USER flag를 설정합니다. User는 읽은 뒤 status를 0으로 되돌려 kernel이 frame을 재사용하게 해야 합니다.

새 packet 여부는 `poll()` 계열로 확인할 수 있습니다. 예제는 `POLLIN|POLLRDNORM|POLLERR`를 기다립니다. 먼저 status가 `TP_STATUS_KERNEL`인지 검사한 뒤 poll해도 race condition이 생기지 않습니다.

RX status flags
Flag의미
TP_STATUS_KERNELKernel이 frame 사용 가능
TP_STATUS_USERUser가 읽을 packet 존재
TP_STATUS_COPYFrame이 잘렸으며 recvfrom으로 전체 읽기 가능
TP_STATUS_LOSING통계 확인 뒤 drop 발생
TP_STATUS_CSUMNOTREADYHardware checksum 예정
TP_STATUS_CSUM_VALIDTransport checksum kernel 검증 완료

Capture ring에서 metadata와 소유권을 해석합니다.

RX frame ownership
TP_STATUS_KERNELkernel receives packetTP_STATUS_USERuser reads packetuser clears statusTP_STATUS_KERNEL

Kernel과 userspace가 status로 ring frame을 넘깁니다.

Capture process
^^^^^^^^^^^^^^^

From include/linux/if_packet.h::

     #define TP_STATUS_COPY          (1 << 1)
     #define TP_STATUS_LOSING        (1 << 2)
     #define TP_STATUS_CSUMNOTREADY  (1 << 3)
     #define TP_STATUS_CSUM_VALID    (1 << 7)

======================  =======================================================
TP_STATUS_COPY                This flag indicates that the frame (and associated
                        meta information) has been truncated because it's
                        larger than tp_frame_size. This packet can be
                        read entirely with recvfrom().

                        In order to make this work it must to be
                        enabled previously with setsockopt() and
                        the PACKET_COPY_THRESH option.

                        The number of frames that can be buffered to
                        be read with recvfrom is limited like a normal socket.
                        See the SO_RCVBUF option in the socket (7) man page.

TP_STATUS_LOSING        indicates there were packet drops from last time
                        statistics where checked with getsockopt() and
                        the PACKET_STATISTICS option.

TP_STATUS_CSUMNOTREADY        currently it's used for outgoing IP packets which
                        its checksum will be done in hardware. So while
                        reading the packet we should not try to check the
                        checksum.

TP_STATUS_CSUM_VALID        This flag indicates that at least the transport
                        header checksum of the packet has been already
                        validated on the kernel side. If the flag is not set
                        then we are free to check the checksum by ourselves
                        provided that TP_STATUS_CSUMNOTREADY is also not set.
======================  =======================================================

for convenience there are also the following defines::

     #define TP_STATUS_KERNEL        0
     #define TP_STATUS_USER          1

The kernel initializes all frames to TP_STATUS_KERNEL, when the kernel
receives a packet it puts in the buffer and updates the status with
at least the TP_STATUS_USER flag. Then the user can read the packet,
once the packet is read the user must zero the status field, so the kernel
can use again that frame buffer.

The user can use poll (any other variant should apply too) to check if new
packets are in the ring::

    struct pollfd pfd;

    pfd.fd = fd;
    pfd.revents = 0;
    pfd.events = POLLIN|POLLRDNORM|POLLERR;

    if (status == TP_STATUS_KERNEL)
        retval = poll(&pfd, 1, timeout);

It doesn't incur in a race condition to first check the status value and
then poll for frames.

TX frame status와 send

503-540

Transmission에는 `TP_STATUS_AVAILABLE=0`, `TP_STATUS_SEND_REQUEST=1`, `TP_STATUS_SENDING=2`, `TP_STATUS_WRONG_FORMAT=4`를 사용합니다. 각각 사용 가능, 다음 `send()`에서 송신, 송신 중, frame format 오류를 뜻합니다.

Kernel은 모든 TX frame을 AVAILABLE로 초기화합니다. User는 available frame의 data buffer를 채우고 `tp_len`을 현재 data size로 설정한 뒤 status를 SEND_REQUEST로 바꿉니다. 여러 frame에 반복할 수 있습니다. `send()`를 호출하면 모든 SEND_REQUEST buffer가 network device로 전달되고 kernel은 transfer가 끝날 때까지 각 status를 SENDING으로 둡니다. 끝나면 AVAILABLE로 돌아옵니다.

원문 예제는 `header->tp_len`, `header->tp_status`를 설정한 뒤 payload argument 없이 `send(socket, NULL, 0, 0)`을 호출합니다. Buffer가 SENDING이면 `POLLOUT`을 기다리는 `poll()`로 다시 available해지는 시점을 확인할 수 있습니다.

TX status
State의미
0AVAILABLEUser가 채울 수 있음
1SEND_REQUEST다음 send에서 전송
2SENDING현재 전송 중
4WRONG_FORMATFrame 형식 오류

Transmission ring frame 상태입니다.

TX frame lifecycle
AVAILABLEuser fills data + tp_lenSEND_REQUESTsend()SENDINGtransfer completeAVAILABLE

User fill부터 device 전송 완료까지입니다.

Transmission process
^^^^^^^^^^^^^^^^^^^^

Those defines are also used for transmission::

     #define TP_STATUS_AVAILABLE        0 // Frame is available
     #define TP_STATUS_SEND_REQUEST     1 // Frame will be sent on next send()
     #define TP_STATUS_SENDING          2 // Frame is currently in transmission
     #define TP_STATUS_WRONG_FORMAT     4 // Frame format is not correct

First, the kernel initializes all frames to TP_STATUS_AVAILABLE. To send a
packet, the user fills a data buffer of an available frame, sets tp_len to
current data buffer size and sets its status field to TP_STATUS_SEND_REQUEST.
This can be done on multiple frames. Once the user is ready to transmit, it
calls send(). Then all buffers with status equal to TP_STATUS_SEND_REQUEST are
forwarded to the network device. The kernel updates each status of sent
frames with TP_STATUS_SENDING until the end of transfer.

At the end of each transfer, buffer status returns to TP_STATUS_AVAILABLE.

::

    header->tp_len = in_i_size;
    header->tp_status = TP_STATUS_SEND_REQUEST;
    retval = send(this->socket, NULL, 0, 0);

The user can also use poll() to check if a buffer is available:

(status == TP_STATUS_SENDING)

::

    struct pollfd pfd;
    pfd.fd = fd;
    pfd.revents = 0;
    pfd.events = POLLOUT;
    retval = poll(&pfd, 1, timeout);

TPACKET_V1·V2·V3 선택

541-598

`setsockopt(PACKET_VERSION)`과 `getsockopt(PACKET_VERSION)`으로 version을 설정·조회합니다. 값은 기본 `TPACKET_V1`, `TPACKET_V2`, `TPACKET_V3` 중 하나입니다. V1은 별도 설정이 없을 때 기본이며 RX_RING과 TX_RING을 지원합니다.

V2는 V1 구조체의 `unsigned long` 문제를 고쳐 64-bit clean합니다. 따라서 64-bit kernel과 32-bit userspace 조합도 지원합니다. Timestamp resolution은 microsecond에서 nanosecond로 바뀌고 RX_RING·TX_RING을 모두 지원합니다.

V2의 `tpacket2_hdr`에는 VLAN metadata가 있습니다. `tp_status`의 `TP_STATUS_VLAN_VALID`는 `tp_vlan_tci`가 유효함을, `TP_STATUS_VLAN_TPID_VALID`는 `tp_vlan_tpid`가 유효함을 뜻합니다.

V2로 전환하려면 `struct tpacket_hdr`를 `struct tpacket2_hdr`로 바꾸고 header length를 조회해 저장한 뒤 protocol version 2를 설정하고 평소처럼 ring을 만듭니다. `sockaddr_ll` 주소는 고정 `sizeof(struct tpacket_hdr)`가 아니라 `(void *)hdr + TPACKET_ALIGN(hdrlen)`으로 구합니다.

V3는 RX_RING에 flexible buffer를 도입합니다. Block은 non-static frame size를 쓸 수 있고 read/poll 단위가 packet이 아니라 block이며, idle link에서 userspace가 무기한 기다리지 않도록 poll timeout을 추가합니다. User가 `block::timeout`과 `tpkt_hdr::sk_rxhash`를 설정할 수 있고 RX hash를 userspace에 제공합니다.

V3 TX_RING semantics는 개념상 V2와 비슷하되 `tpacket3_hdr`와 `TPACKET3_HDRLEN`을 사용합니다. 현재 구현에서는 ring이 variable-sized frame을 담지 않는다는 뜻으로 `tpacket3_hdr.tp_next_offset`을 반드시 0으로 설정해야 하며, 0이 아닌 packet은 drop됩니다.

TPACKET version 비교
Version특징
V1기본, RX_RING·TX_RING
V264-bit clean, ns timestamp, VLAN TCI·TPID metadata
V3RX variable frame size, block poll, timeout, RX hash; TX는 next_offset=0

Version별 주요 차이와 ring 지원입니다.

What TPACKET versions are available and when to use them?
=========================================================

::

 int val = tpacket_version;
 setsockopt(fd, SOL_PACKET, PACKET_VERSION, &val, sizeof(val));
 getsockopt(fd, SOL_PACKET, PACKET_VERSION, &val, sizeof(val));

where 'tpacket_version' can be TPACKET_V1 (default), TPACKET_V2, TPACKET_V3.

TPACKET_V1:
        - Default if not otherwise specified by setsockopt(2)
        - RX_RING, TX_RING available

TPACKET_V1 --> TPACKET_V2:
        - Made 64 bit clean due to unsigned long usage in TPACKET_V1
          structures, thus this also works on 64 bit kernel with 32 bit
          userspace and the like
        - Timestamp resolution in nanoseconds instead of microseconds
        - RX_RING, TX_RING available
        - VLAN metadata information available for packets
          (TP_STATUS_VLAN_VALID, TP_STATUS_VLAN_TPID_VALID),
          in the tpacket2_hdr structure:

                - TP_STATUS_VLAN_VALID bit being set into the tp_status field indicates
                  that the tp_vlan_tci field has valid VLAN TCI value
                - TP_STATUS_VLAN_TPID_VALID bit being set into the tp_status field
                  indicates that the tp_vlan_tpid field has valid VLAN TPID value

        - How to switch to TPACKET_V2:

                1. Replace struct tpacket_hdr by struct tpacket2_hdr
                2. Query header len and save
                3. Set protocol version to 2, set up ring as usual
                4. For getting the sockaddr_ll,
                   use ``(void *)hdr + TPACKET_ALIGN(hdrlen)`` instead of
                   ``(void *)hdr + TPACKET_ALIGN(sizeof(struct tpacket_hdr))``

TPACKET_V2 --> TPACKET_V3:
        - Flexible buffer implementation for RX_RING:
                1. Blocks can be configured with non-static frame-size
                2. Read/poll is at a block-level (as opposed to packet-level)
                3. Added poll timeout to avoid indefinite user-space wait
                   on idle links
                4. Added user-configurable knobs:

                        4.1 block::timeout
                        4.2 tpkt_hdr::sk_rxhash

        - RX Hash data available in user space
        - TX_RING semantics are conceptually similar to TPACKET_V2;
          use tpacket3_hdr instead of tpacket2_hdr, and TPACKET3_HDRLEN
          instead of TPACKET2_HDRLEN. In the current implementation,
          the tp_next_offset field in the tpacket3_hdr MUST be set to
          zero, indicating that the ring does not hold variable sized frames.
          Packets with non-zero values of tp_next_offset will be dropped.

AF_PACKET fanout policy와 예제

599-754

AF_PACKET fanout mode는 packet reception을 여러 process에 load-balance하며 packet socket의 `mmap(2)`와 함께 쓸 수 있습니다.

구현된 policy는 skb packet hash로 socket을 정하는 `PACKET_FANOUT_HASH`, round-robin `LB`, packet 도착 CPU 기준 `CPU`, random `RND`, socket이 가득 차면 다른 socket으로 넘기는 `ROLLOVER`, skb의 기록된 `queue_mapping`을 사용하는 `QM`입니다.

David S. Miller의 최소 C 예제는 interface와 `hash` 또는 `lb` argument를 받습니다. `setup_socket()`은 `AF_PACKET/SOCK_RAW/ETH_P_IP` socket을 만들고 `SIOCGIFINDEX`로 device index를 얻어 bind합니다. `fanout_id | (fanout_type << 16)`으로 option 값을 만들어 `setsockopt(PACKET_FANOUT)`에 전달합니다.

`fanout_thread()`는 socket 하나를 만들고 최대 10000 packet을 `read()`하며 열 packet마다 PID를 출력합니다. `main()`은 fanout type을 선택하고 process PID 하위 16 bit를 group ID로 사용한 뒤 reader process 네 개를 `fork()`합니다. Parent는 네 child를 모두 `wait()`합니다. 전체 include, error path와 함수 구현은 원문 C code에 그대로 보존되어 있습니다.

AF_PACKET fanout policy
PolicySocket 선택 기준
HASHskb packet hash
LBround-robin
CPUpacket 도착 CPU
RNDrandom
ROLLOVERfull socket에서 다음 socket
QMskb queue_mapping

현재 구현된 여섯 scheduling 방식입니다.

Fanout example process model
AF_PACKET ingressPACKET_FANOUT policychild socket 1
AF_PACKET ingressPACKET_FANOUT policychild socket 2
AF_PACKET ingressPACKET_FANOUT policychild socket 3
AF_PACKET ingressPACKET_FANOUT policychild socket 4

동일 fanout group의 네 process가 traffic을 분담합니다.

AF_PACKET fanout mode
=====================

In the AF_PACKET fanout mode, packet reception can be load balanced among
processes. This also works in combination with mmap(2) on packet sockets.

Currently implemented fanout policies are:

  - PACKET_FANOUT_HASH: schedule to socket by skb's packet hash
  - PACKET_FANOUT_LB: schedule to socket by round-robin
  - PACKET_FANOUT_CPU: schedule to socket by CPU packet arrives on
  - PACKET_FANOUT_RND: schedule to socket by random selection
  - PACKET_FANOUT_ROLLOVER: if one socket is full, rollover to another
  - PACKET_FANOUT_QM: schedule to socket by skbs recorded queue_mapping

Minimal example code by David S. Miller (try things like "./test eth0 hash",
"./test eth0 lb", etc.)::

    #include <stddef.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>

    #include <sys/types.h>
    #include <sys/wait.h>
    #include <sys/socket.h>
    #include <sys/ioctl.h>

    #include <unistd.h>

    #include <linux/if_ether.h>
    #include <linux/if_packet.h>

    #include <net/if.h>

    static const char *device_name;
    static int fanout_type;
    static int fanout_id;

    #ifndef PACKET_FANOUT
    # define PACKET_FANOUT                        18
    # define PACKET_FANOUT_HASH                0
    # define PACKET_FANOUT_LB                1
    #endif

    static int setup_socket(void)
    {
            int err, fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP));
            struct sockaddr_ll ll;
            struct ifreq ifr;
            int fanout_arg;

            if (fd < 0) {
                    perror("socket");
                    return EXIT_FAILURE;
            }

            memset(&ifr, 0, sizeof(ifr));
            strcpy(ifr.ifr_name, device_name);
            err = ioctl(fd, SIOCGIFINDEX, &ifr);
            if (err < 0) {
                    perror("SIOCGIFINDEX");
                    return EXIT_FAILURE;
            }

            memset(&ll, 0, sizeof(ll));
            ll.sll_family = AF_PACKET;
            ll.sll_ifindex = ifr.ifr_ifindex;
            err = bind(fd, (struct sockaddr *) &ll, sizeof(ll));
            if (err < 0) {
                    perror("bind");
                    return EXIT_FAILURE;
            }

            fanout_arg = (fanout_id | (fanout_type << 16));
            err = setsockopt(fd, SOL_PACKET, PACKET_FANOUT,
                            &fanout_arg, sizeof(fanout_arg));
            if (err) {
                    perror("setsockopt");
                    return EXIT_FAILURE;
            }

            return fd;
    }

    static void fanout_thread(void)
    {
            int fd = setup_socket();
            int limit = 10000;

            if (fd < 0)
                    exit(fd);

            while (limit-- > 0) {
                    char buf[1600];
                    int err;

                    err = read(fd, buf, sizeof(buf));
                    if (err < 0) {
                            perror("read");
                            exit(EXIT_FAILURE);
                    }
                    if ((limit % 10) == 0)
                            fprintf(stdout, "(%d) \n", getpid());
            }

            fprintf(stdout, "%d: Received 10000 packets\n", getpid());

            close(fd);
            exit(0);
    }

    int main(int argc, char **argp)
    {
            int fd, err;
            int i;

            if (argc != 3) {
                    fprintf(stderr, "Usage: %s INTERFACE {hash|lb}\n", argp[0]);
                    return EXIT_FAILURE;
            }

            if (!strcmp(argp[2], "hash"))
                    fanout_type = PACKET_FANOUT_HASH;
            else if (!strcmp(argp[2], "lb"))
                    fanout_type = PACKET_FANOUT_LB;
            else {
                    fprintf(stderr, "Unknown fanout type [%s]\n", argp[2]);
                    exit(EXIT_FAILURE);
            }

            device_name = argp[1];
            fanout_id = getpid() & 0xffff;

            for (i = 0; i < 4; i++) {
                    pid_t pid = fork();

                    switch (pid) {
                    case 0:
                            fanout_thread();

                    case -1:
                            perror("fork");
                            exit(EXIT_FAILURE);
                    }
            }

            for (i = 0; i < 4; i++) {
                    int status;

                    wait(&status);
            }

            return 0;
    }

TPACKET_V3 block-ring 전체 예제

755-1004

TPACKET_V3 ring은 자체 memory management로 non-static frame size를 사용할 수 있습니다. V2와 이전 version이 ring 단위로 poll한 것과 달리 block을 기반으로 하고 block별로 poll합니다.

문서가 제시하는 장점은 CPU 사용량 약 15~20% 감소, packet capture rate 약 20% 증가, packet density 약 2배 증가, port aggregation analysis, 전체 packet payload를 capture할 수 있는 non-static frame size입니다. 따라서 packet fanout과 함께 쓰기 좋은 후보입니다.

Daniel Borkmann이 Chetan Loke의 lolpcap을 바탕으로 작성한 전체 예제는 `gcc -Wall -O2 blob.c`로 build하고 interface name을 argument로 실행합니다. `block_desc`는 version·private offset·`tpacket_hdr_v1`, `ring`은 block iovec·mmap base·`tpacket_req3`를 저장합니다.

`setup_socket()`은 `TPACKET_V3`인 AF_PACKET raw socket을 만들고 block size `1<<22`, frame size `1<<11`, block 64개를 설정합니다. `tp_frame_nr`은 전체 byte를 frame size로 나누고 block retire timeout은 60, feature는 `TP_FT_REQ_FILL_RXHASH`입니다. `PACKET_RX_RING`을 설정한 뒤 전체 ring을 `MAP_SHARED|MAP_LOCKED`로 mapping합니다.

이어서 block마다 `iovec`를 만들어 mapping의 정확한 block offset과 length를 기록합니다. `sockaddr_ll`에 `PF_PACKET`, `ETH_P_ALL`, `if_nametoindex(netdev)`를 채워 socket을 bind합니다.

`display()`는 `tpacket3_hdr.tp_mac`으로 Ethernet header를 찾고 IPv4라면 source·destination을 numeric string으로 바꿔 출력한 뒤 `hv1.tp_rxhash`도 출력합니다. `walk_block()`은 block의 packet 수와 첫 packet offset을 읽고 각 packet의 `tp_snaplen`을 합산하며 `tp_next_offset`으로 다음 packet을 방문합니다.

`flush_block()`은 block status를 `TP_STATUS_KERNEL`로 돌려주고 `teardown_socket()`은 mapping, iovec, socket을 정리합니다. `main()`은 SIGINT handler와 ring을 준비한 뒤 `POLLIN|POLLERR`를 설정합니다. 현재 block이 USER 소유가 아니면 poll하고, 준비되면 block을 순회·반납한 뒤 index를 64로 modulo 증가시킵니다.

종료 시 `getsockopt(PACKET_STATISTICS)`로 `tpacket_stats_v3`를 읽어 수신 packet, 누적 byte, drop, `tp_freeze_q_cnt`를 출력하고 teardown합니다. 전체 C code와 모든 source coordinate는 원문 block에 그대로 들어 있습니다.

TPACKET_V3 example ring
ParameterValue
tp_block_size1 << 22 (4 MiB)
tp_frame_size1 << 11 (2 KiB)
tp_block_nr64
tp_retire_blk_tov60
tp_feature_req_wordTP_FT_REQ_FILL_RXHASH
mmap flagsMAP_SHARED | MAP_LOCKED

예제가 선택한 핵심 값입니다.

TPACKET_V3 block loop
Current blockTP_STATUS_USER 확인poll if unavailablewalk packets by tp_next_offsetdisplay + accountset TP_STATUS_KERNELnext block modulo 64

Block-level polling과 ownership 반환입니다.

AF_PACKET TPACKET_V3 example
============================

AF_PACKET's TPACKET_V3 ring buffer can be configured to use non-static frame
sizes by doing its own memory management. It is based on blocks where polling
works on a per block basis instead of per ring as in TPACKET_V2 and predecessor.

It is said that TPACKET_V3 brings the following benefits:

 * ~15% - 20% reduction in CPU-usage
 * ~20% increase in packet capture rate
 * ~2x increase in packet density
 * Port aggregation analysis
 * Non static frame size to capture entire packet payload

So it seems to be a good candidate to be used with packet fanout.

Minimal example code by Daniel Borkmann based on Chetan Loke's lolpcap (compile
it with gcc -Wall -O2 blob.c, and try things like "./a.out eth0", etc.)::

    /* Written from scratch, but kernel-to-user space API usage
    * dissected from lolpcap:
    *  Copyright 2011, Chetan Loke <loke.chetan@gmail.com>
    *  License: GPL, version 2.0
    */

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>
    #include <string.h>
    #include <assert.h>
    #include <net/if.h>
    #include <arpa/inet.h>
    #include <netdb.h>
    #include <poll.h>
    #include <unistd.h>
    #include <signal.h>
    #include <inttypes.h>
    #include <sys/socket.h>
    #include <sys/mman.h>
    #include <linux/if_packet.h>
    #include <linux/if_ether.h>
    #include <linux/ip.h>

    #ifndef likely
    # define likely(x)                __builtin_expect(!!(x), 1)
    #endif
    #ifndef unlikely
    # define unlikely(x)                __builtin_expect(!!(x), 0)
    #endif

    struct block_desc {
            uint32_t version;
            uint32_t offset_to_priv;
            struct tpacket_hdr_v1 h1;
    };

    struct ring {
            struct iovec *rd;
            uint8_t *map;
            struct tpacket_req3 req;
    };

    static unsigned long packets_total = 0, bytes_total = 0;
    static sig_atomic_t sigint = 0;

    static void sighandler(int num)
    {
            sigint = 1;
    }

    static int setup_socket(struct ring *ring, char *netdev)
    {
            int err, i, fd, v = TPACKET_V3;
            struct sockaddr_ll ll;
            unsigned int blocksiz = 1 << 22, framesiz = 1 << 11;
            unsigned int blocknum = 64;

            fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
            if (fd < 0) {
                    perror("socket");
                    exit(1);
            }

            err = setsockopt(fd, SOL_PACKET, PACKET_VERSION, &v, sizeof(v));
            if (err < 0) {
                    perror("setsockopt");
                    exit(1);
            }

            memset(&ring->req, 0, sizeof(ring->req));
            ring->req.tp_block_size = blocksiz;
            ring->req.tp_frame_size = framesiz;
            ring->req.tp_block_nr = blocknum;
            ring->req.tp_frame_nr = (blocksiz * blocknum) / framesiz;
            ring->req.tp_retire_blk_tov = 60;
            ring->req.tp_feature_req_word = TP_FT_REQ_FILL_RXHASH;

            err = setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &ring->req,
                            sizeof(ring->req));
            if (err < 0) {
                    perror("setsockopt");
                    exit(1);
            }

            ring->map = mmap(NULL, ring->req.tp_block_size * ring->req.tp_block_nr,
                            PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, fd, 0);
            if (ring->map == MAP_FAILED) {
                    perror("mmap");
                    exit(1);
            }

            ring->rd = malloc(ring->req.tp_block_nr * sizeof(*ring->rd));
            assert(ring->rd);
            for (i = 0; i < ring->req.tp_block_nr; ++i) {
                    ring->rd[i].iov_base = ring->map + (i * ring->req.tp_block_size);
                    ring->rd[i].iov_len = ring->req.tp_block_size;
            }

            memset(&ll, 0, sizeof(ll));
            ll.sll_family = PF_PACKET;
            ll.sll_protocol = htons(ETH_P_ALL);
            ll.sll_ifindex = if_nametoindex(netdev);
            ll.sll_hatype = 0;
            ll.sll_pkttype = 0;
            ll.sll_halen = 0;

            err = bind(fd, (struct sockaddr *) &ll, sizeof(ll));
            if (err < 0) {
                    perror("bind");
                    exit(1);
            }

            return fd;
    }

    static void display(struct tpacket3_hdr *ppd)
    {
            struct ethhdr *eth = (struct ethhdr *) ((uint8_t *) ppd + ppd->tp_mac);
            struct iphdr *ip = (struct iphdr *) ((uint8_t *) eth + ETH_HLEN);

            if (eth->h_proto == htons(ETH_P_IP)) {
                    struct sockaddr_in ss, sd;
                    char sbuff[NI_MAXHOST], dbuff[NI_MAXHOST];

                    memset(&ss, 0, sizeof(ss));
                    ss.sin_family = PF_INET;
                    ss.sin_addr.s_addr = ip->saddr;
                    getnameinfo((struct sockaddr *) &ss, sizeof(ss),
                                sbuff, sizeof(sbuff), NULL, 0, NI_NUMERICHOST);

                    memset(&sd, 0, sizeof(sd));
                    sd.sin_family = PF_INET;
                    sd.sin_addr.s_addr = ip->daddr;
                    getnameinfo((struct sockaddr *) &sd, sizeof(sd),
                                dbuff, sizeof(dbuff), NULL, 0, NI_NUMERICHOST);

                    printf("%s -> %s, ", sbuff, dbuff);
            }

            printf("rxhash: 0x%x\n", ppd->hv1.tp_rxhash);
    }

    static void walk_block(struct block_desc *pbd, const int block_num)
    {
            int num_pkts = pbd->h1.num_pkts, i;
            unsigned long bytes = 0;
            struct tpacket3_hdr *ppd;

            ppd = (struct tpacket3_hdr *) ((uint8_t *) pbd +
                                        pbd->h1.offset_to_first_pkt);
            for (i = 0; i < num_pkts; ++i) {
                    bytes += ppd->tp_snaplen;
                    display(ppd);

                    ppd = (struct tpacket3_hdr *) ((uint8_t *) ppd +
                                                ppd->tp_next_offset);
            }

            packets_total += num_pkts;
            bytes_total += bytes;
    }

    static void flush_block(struct block_desc *pbd)
    {
            pbd->h1.block_status = TP_STATUS_KERNEL;
    }

    static void teardown_socket(struct ring *ring, int fd)
    {
            munmap(ring->map, ring->req.tp_block_size * ring->req.tp_block_nr);
            free(ring->rd);
            close(fd);
    }

    int main(int argc, char **argp)
    {
            int fd, err;
            socklen_t len;
            struct ring ring;
            struct pollfd pfd;
            unsigned int block_num = 0, blocks = 64;
            struct block_desc *pbd;
            struct tpacket_stats_v3 stats;

            if (argc != 2) {
                    fprintf(stderr, "Usage: %s INTERFACE\n", argp[0]);
                    return EXIT_FAILURE;
            }

            signal(SIGINT, sighandler);

            memset(&ring, 0, sizeof(ring));
            fd = setup_socket(&ring, argp[argc - 1]);
            assert(fd > 0);

            memset(&pfd, 0, sizeof(pfd));
            pfd.fd = fd;
            pfd.events = POLLIN | POLLERR;
            pfd.revents = 0;

            while (likely(!sigint)) {
                    pbd = (struct block_desc *) ring.rd[block_num].iov_base;

                    if ((pbd->h1.block_status & TP_STATUS_USER) == 0) {
                            poll(&pfd, 1, -1);
                            continue;
                    }

                    walk_block(pbd, block_num);
                    flush_block(pbd);
                    block_num = (block_num + 1) % blocks;
            }

            len = sizeof(stats);
            err = getsockopt(fd, SOL_PACKET, PACKET_STATISTICS, &stats, &len);
            if (err < 0) {
                    perror("getsockopt");
                    exit(1);
            }

            fflush(stdout);
            printf("\nReceived %u packets, %lu bytes, %u dropped, freeze_q_cnt: %u\n",
                stats.tp_packets, bytes_total, stats.tp_drops,
                stats.tp_freeze_q_cnt);

            teardown_socket(&ring, fd);
            return 0;
    }

PACKET_QDISC_BYPASS

1005-1024

`pktgen`처럼 많은 packet으로 network에 부하를 주려면 socket 생성 뒤 `setsockopt(PACKET_QDISC_BYPASS)`를 1로 설정할 수 있습니다.

그러면 PF_PACKET 송신 packet이 kernel qdisc layer를 우회해 driver로 직접 밀려갑니다. Packet이 buffer되지 않고 tc discipline이 무시되어 loss가 늘 수 있으며 다른 PF_PACKET socket에도 더 이상 보이지 않습니다. 따라서 system component stress test에는 유용할 수 있지만 부작용을 이해해야 합니다.

`PACKET_QDISC_BYPASS`는 기본적으로 꺼져 있으며 PF_PACKET socket마다 명시적으로 켜야 합니다.

Qdisc bypass path
PF_PACKET TXqdiscdriver
PF_PACKET TX + BYPASSdriver 직접 전달buffer·tc·peer visibility 없음

일반 경로와 stress-test 경로를 비교합니다.

PACKET_QDISC_BYPASS
===================

If there is a requirement to load the network with many packets in a similar
fashion as pktgen does, you might set the following option after socket
creation::

    int one = 1;
    setsockopt(fd, SOL_PACKET, PACKET_QDISC_BYPASS, &one, sizeof(one));

This has the side-effect, that packets sent through PF_PACKET will bypass the
kernel's qdisc layer and are forcedly pushed to the driver directly. Meaning,
packet are not buffered, tc disciplines are ignored, increased loss can occur
and such packets are also not visible to other PF_PACKET sockets anymore. So,
you have been warned; generally, this can be useful for stress testing various
components of a system.

On default, PACKET_QDISC_BYPASS is disabled and needs to be explicitly enabled
on PF_PACKET sockets.

PACKET_TIMESTAMP와 RX·TX timestamp

1025-1074

`PACKET_TIMESTAMP`는 mmap된 RX_RING·TX_RING의 packet metadata에 사용할 timestamp source를 정합니다. NIC가 hardware timestamp를 지원하면 이를 요청할 수 있으며, 생성 자체는 `SIOCSHWTSTAMP`로 활성화해야 할 수 있습니다. 관련 문서는 `Documentation/networking/timestamping.rst`입니다.

Option은 `SO_TIMESTAMPING`과 같은 integer bit field를 받습니다. 예제는 `SOF_TIMESTAMPING_RAW_HARDWARE`를 `setsockopt(PACKET_TIMESTAMP)`에 전달합니다. Ring timestamp는 `tpacket{,2,3}_hdr`의 `tp_sec`과 `tp_{n,u}sec` member에 저장됩니다.

보고된 종류는 `tp_status`에 OR된 `TP_STATUS_TS_RAW_HARDWARE` 또는 `TP_STATUS_TS_SOFTWARE`로 판단하며 대응 `SOF_TIMESTAMPING_*` bit와 같습니다. RX_RING에서 둘 다 없고 PACKET_TIMESTAMP도 설정하지 않았다면 PF_PACKET 처리 code 내부의 정밀도가 낮은 software fallback을 사용한 것입니다.

TX_RING timestamp를 얻으려면 ring frame을 채우고 blocking `sendto()` 등을 호출한 뒤 관련 frame status가 application에 반환될 때까지 기다리고 frame을 순회해 개별 hardware/software timestamp를 꺼냅니다.

TX timestamping을 켠 경우에만 timestamp bit가 `TP_STATUS_AVAILABLE`과 OR되므로 application은 bit mask로 확인해야 합니다. 먼저 `!(tp_status & (TP_STATUS_SEND_REQUEST | TP_STATUS_SENDING))`처럼 frame이 application 소유인지 검사하고 두 번째 단계에서 timestamp type을 추출합니다.

Timestamp가 필요 없어 기능을 끈 경우 AVAILABLE 또는 WRONG_FORMAT만 확인하면 됩니다. TX_RING에서 AVAILABLE만 설정되어 있으면 `tp_sec`·`tp_{n,u}sec`은 유효하지 않습니다. TX_RING은 기본적으로 timestamp를 만들지 않습니다. 자세한 내용은 `include/linux/net_tstamp.h`와 timestamping 문서를 참조합니다.

PACKET_TIMESTAMP status
Status bit의미
TP_STATUS_TS_RAW_HARDWARENIC raw hardware timestamp
TP_STATUS_TS_SOFTWAREsoftware timestamp
RX에서 둘 다 없음PF_PACKET 내부 software fallback
TX AVAILABLE만 있음timestamp 값 무효

Ring header에서 timestamp source를 판별합니다.

PACKET_TIMESTAMP
================

The PACKET_TIMESTAMP setting determines the source of the timestamp in
the packet meta information for mmap(2)ed RX_RING and TX_RINGs.  If your
NIC is capable of timestamping packets in hardware, you can request those
hardware timestamps to be used. Note: you may need to enable the generation
of hardware timestamps with SIOCSHWTSTAMP (see related information from
Documentation/networking/timestamping.rst).

PACKET_TIMESTAMP accepts the same integer bit field as SO_TIMESTAMPING::

    int req = SOF_TIMESTAMPING_RAW_HARDWARE;
    setsockopt(fd, SOL_PACKET, PACKET_TIMESTAMP, (void *) &req, sizeof(req))

For the mmap(2)ed ring buffers, such timestamps are stored in the
``tpacket{,2,3}_hdr`` structure's tp_sec and ``tp_{n,u}sec`` members.
To determine what kind of timestamp has been reported, the tp_status field
is binary or'ed with the following possible bits ...

::

    TP_STATUS_TS_RAW_HARDWARE
    TP_STATUS_TS_SOFTWARE

... that are equivalent to its ``SOF_TIMESTAMPING_*`` counterparts. For the
RX_RING, if neither is set (i.e. PACKET_TIMESTAMP is not set), then a
software fallback was invoked *within* PF_PACKET's processing code (less
precise).

Getting timestamps for the TX_RING works as follows: i) fill the ring frames,
ii) call sendto() e.g. in blocking mode, iii) wait for status of relevant
frames to be updated resp. the frame handed over to the application, iv) walk
through the frames to pick up the individual hw/sw timestamps.

Only (!) if transmit timestamping is enabled, then these bits are combined
with binary | with TP_STATUS_AVAILABLE, so you must check for that in your
application (e.g. !(tp_status & (TP_STATUS_SEND_REQUEST | TP_STATUS_SENDING))
in a first step to see if the frame belongs to the application, and then
one can extract the type of timestamp in a second step from tp_status)!

If you don't care about them, thus having it disabled, checking for
TP_STATUS_AVAILABLE resp. TP_STATUS_WRONG_FORMAT is sufficient. If in the
TX_RING part only TP_STATUS_AVAILABLE is set, then the tp_sec and tp_{n,u}sec
members do not contain a valid value. For TX_RINGs, by default no timestamp
is generated!

See include/linux/net_tstamp.h and Documentation/networking/timestamping.rst
for more information on hardware timestamps.

Socket filter와 감사

1075-1084

Packet socket은 Linux socket filter와 잘 동작하므로 `Documentation/networking/filter.rst`도 함께 참고할 수 있습니다.

문서 끝에서는 문법·철자 오류를 고친 Jesse Brandeburg에게 감사를 전합니다.

Miscellaneous bits
==================

- Packet sockets work well together with Linux socket filters, thus you also
  might want to have a look at Documentation/networking/filter.rst

THANKS
======

   Jesse Brandeburg, for fixing my grammathical/spelling errors