summaryrefslogtreecommitdiff
path: root/ring_tx.c
blob: b8ce4461577178130cbbf1b9bb9e5101a0224556 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
 * netsniff-ng - the packet sniffing beast
 * Copyright 2009, 2010 Daniel Borkmann.
 * Copyright 2009, 2010 Emmanuel Roullit.
 * Copyright 2014, 2015 Tobias Klauser.
 * Subject to the GPL, version 2.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/if_ether.h>

#include "die.h"
#include "xmalloc.h"
#include "ring_tx.h"
#include "built_in.h"

static void set_packet_loss_discard(int sock)
{
	int ret, discard = 1;
	ret = setsockopt(sock, SOL_PACKET, PACKET_LOSS, (void *) &discard,
			 sizeof(discard));
	if (ret < 0)
		panic("setsockopt: cannot set packet loss");
}

void destroy_tx_ring(int sock, struct ring *ring)
{
	int ret;

	munmap(ring->mm_space, ring->mm_len);
	ring->mm_len = 0;

	fmemset(&ring->layout, 0, sizeof(ring->layout));
	ret = setsockopt(sock, SOL_PACKET, PACKET_TX_RING, &ring->layout,
			 sizeof(ring->layout));
	if (unlikely(ret))
		panic("Cannot destroy the TX_RING: %s!\n", strerror(errno));

	xfree(ring->frames);
}

static void setup_tx_ring_layout(int sock, struct ring *ring, size_t size,
				 bool jumbo_support)
{
	setup_ring_layout_generic(sock, ring, size, jumbo_support);

	set_sockopt_tpacket_v2(sock);

	ring_verify_layout(ring);
}

static void create_tx_ring(int sock, struct ring *ring, bool verbose)
{
	int ret;
retry:
	ret = setsockopt(sock, SOL_PACKET, PACKET_TX_RING, &ring->layout,
			 sizeof(ring->layout));

	if (errno == ENOMEM && ring->layout.tp_block_nr > 1) {
		shrink_ring_layout_generic(ring);
		goto retry;
	}

	if (ret < 0)
		panic("Cannot allocate TX_RING!\n");

	ring->mm_len = (size_t) ring->layout.tp_block_size * ring->layout.tp_block_nr;

	if (verbose) {
		printf("TX,V2: %.2Lf MiB, %u Frames, each %u Byte allocated\n",
		       (long double) ring->mm_len / (1 << 20),
		       ring->layout.tp_frame_nr, ring->layout.tp_frame_size);
	}
}

static void alloc_tx_ring_frames(int sock __maybe_unused, struct ring *ring)
{
	alloc_ring_frames_generic(ring, ring->layout.tp_frame_nr,
				  ring->layout.tp_frame_size);
}

void ring_tx_setup(struct ring *ring, int sock, size_t size, int ifindex,
		   bool jumbo_support, bool verbose)
{
	fmemset(ring, 0, sizeof(*ring));
	set_packet_loss_discard(sock);
	setup_tx_ring_layout(sock, ring, size, jumbo_support);
	create_tx_ring(sock, ring, verbose);
	mmap_ring_generic(sock, ring);
	alloc_tx_ring_frames(sock, ring);
	bind_ring_generic(sock, ring, ifindex, true);
}