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