ring: add necessary structures and helper functions for v3
[netsniff-ng.git] / ring.h
blob5e47d371b874fb8d25f6dd288acaacfdecc74afa
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009, 2010 Daniel Borkmann.
4 * Subject to the GPL, version 2.
5 */
7 #ifndef RING_H
8 #define RING_H
11 * "I love the smell of 10GbE in the morning. Smells like ... victory."
12 * - W. Richard Stevens, "Secret Teachings of the UNIX Environment"
15 #include <stdio.h>
16 #include <stdint.h>
17 #include <linux/if_packet.h>
18 #include <linux/socket.h>
19 #include <linux/sockios.h>
20 #include <sys/ioctl.h>
21 #include <string.h>
22 #include <poll.h>
23 #include <sys/poll.h>
25 #include "xutils.h"
26 #include "built_in.h"
27 #include "die.h"
29 struct frame_map {
30 struct tpacket2_hdr tp_h __aligned_tpacket;
31 struct sockaddr_ll s_ll __align_tpacket(sizeof(struct tpacket2_hdr));
34 struct block_desc {
35 uint32_t version;
36 uint32_t offset_to_priv;
37 struct tpacket_hdr_v1 h1;
40 struct ring {
41 struct iovec *frames;
42 uint8_t *mm_space;
43 size_t mm_len;
44 struct sockaddr_ll s_ll;
45 union {
46 struct tpacket_req layout;
47 struct tpacket_req3 layout3;
51 static inline void next_rnd_slot(unsigned int *it, struct ring *ring)
53 *it = rand() % ring->layout.tp_frame_nr;
56 static inline unsigned int ring_size(char *ifname, unsigned int size)
58 if (size > 0)
59 return size;
62 * Device bitrate in bytes times two as ring size.
63 * Fallback => ~ 64,00 MB
64 * 10 MBit => ~ 2,38 MB
65 * 54 MBit => ~ 12,88 MB
66 * 100 MBit => ~ 23,84 MB
67 * 300 MBit => ~ 71,52 MB
68 * 1.000 MBit => ~ 238,42 MB
69 * 10.000 MBit => ~ 2.384.18 MB
71 size = device_bitrate(ifname);
72 size = (size * 1000000) / 8;
73 size = size * 2;
74 if (size == 0)
75 size = 1 << 26;
77 return round_up_cacheline(size);
80 static inline unsigned int ring_frame_size(struct ring *ring)
82 return ring->layout.tp_frame_size;
85 static inline void tpacket_hdr_clone(struct tpacket2_hdr *thdrd,
86 struct tpacket2_hdr *thdrs)
88 thdrd->tp_sec = thdrs->tp_sec;
89 thdrd->tp_nsec = thdrs->tp_nsec;
90 thdrd->tp_snaplen = thdrs->tp_snaplen;
91 thdrd->tp_len = thdrs->tp_len;
94 static inline void prepare_polling(int sock, struct pollfd *pfd)
96 memset(pfd, 0, sizeof(*pfd));
97 pfd->fd = sock;
98 pfd->revents = 0;
99 pfd->events = POLLIN | POLLRDNORM | POLLERR;
102 static inline void __set_sockopt_tpacket(int sock, int val)
104 int ret = setsockopt(sock, SOL_PACKET, PACKET_VERSION, &val, sizeof(val));
105 if (ret)
106 panic("Cannot set tpacketv2!\n");
109 static inline void set_sockopt_tpacket_v2(int sock)
111 __set_sockopt_tpacket(sock, TPACKET_V2);
114 static inline void set_sockopt_tpacket_v3(int sock)
116 __set_sockopt_tpacket(sock, TPACKET_V3);
119 #endif /* RING_H */