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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
//! `sendmmsg` batch syscall backend — fast Linux, ~10M pps.
//!
//! Uses `AF_INET` raw sockets with `sendmmsg()` to batch up to 1024 packets
//! per syscall, reducing overhead by ~1000x vs individual `sendto()`.
//!
//! Also uses `recvmmsg()` for batched packet reception.
//!
//! # Requirements
//! - Linux only (`sendmmsg` is Linux-specific)
//! - `CAP_NET_RAW` or root
//! - Feature: `sendmmsg-backend`
#[cfg(all(target_os = "linux", feature = "sendmmsg-backend"))]
mod inner {
use std::net::Ipv4Addr;
use std::os::fd::RawFd;
use std::sync::Mutex;
use crate::engine::{EngineConfig, EngineError, EngineStats, PacketEngine, RxPacket};
use crate::packet::{RawPacket, offsets};
use crate::stats_window::PpsTracker;
/// Maximum packets per `sendmmsg` call.
const BATCH_SIZE: usize = 1024;
/// Raw socket wrapper for `sendmmsg`-based packet I/O.
pub struct SendmmsgEngine {
tx_fd: RawFd,
rx_fd: RawFd,
// Stored so tests / diagnostics can inspect the bound
// configuration; not read in the hot path.
#[allow(dead_code)]
config: EngineConfig,
tx_stats: PpsTracker,
rx_stats: PpsTracker,
// Keep the file descriptors alive
_tx_sock: Mutex<std::net::UdpSocket>,
}
impl SendmmsgEngine {
/// Create a new `sendmmsg` engine with `AF_INET` + `SOCK_RAW`.
pub fn new(config: EngineConfig) -> Result<Self, EngineError> {
// Create raw socket for TCP (protocol 6)
let tx_fd = unsafe {
libc::socket(libc::AF_INET, libc::SOCK_RAW, libc::IPPROTO_TCP)
};
if tx_fd < 0 {
return Err(EngineError::PermissionDenied(
"failed to create SOCK_RAW socket".into(),
));
}
// Enable IP_HDRINCL — we provide our own IP header
let one: libc::c_int = 1;
let ret = unsafe {
libc::setsockopt(
tx_fd,
libc::IPPROTO_IP,
libc::IP_HDRINCL,
&one as *const _ as *const libc::c_void,
std::mem::size_of::<libc::c_int>() as libc::socklen_t,
)
};
if ret < 0 {
unsafe { libc::close(tx_fd); }
return Err(EngineError::Io(std::io::Error::last_os_error()));
}
// Create a separate RX socket
let rx_fd = unsafe {
libc::socket(libc::AF_INET, libc::SOCK_RAW, libc::IPPROTO_TCP)
};
if rx_fd < 0 {
unsafe { libc::close(tx_fd); }
return Err(EngineError::PermissionDenied(
"failed to create RX SOCK_RAW socket".into(),
));
}
// Set RX socket to non-blocking
unsafe {
let flags = libc::fcntl(rx_fd, libc::F_GETFL);
libc::fcntl(rx_fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
// We use a UdpSocket just to keep the fd alive via Rust ownership.
// The actual I/O goes through the raw fd.
let placeholder = std::net::UdpSocket::bind("0.0.0.0:0")
.map_err(EngineError::Io)?;
Ok(Self {
tx_fd,
rx_fd,
config,
tx_stats: PpsTracker::new(),
rx_stats: PpsTracker::new(),
_tx_sock: Mutex::new(placeholder),
})
}
}
impl Drop for SendmmsgEngine {
fn drop(&mut self) {
unsafe {
libc::close(self.tx_fd);
libc::close(self.rx_fd);
}
}
}
impl PacketEngine for SendmmsgEngine {
fn tx_batch(&self, packets: &[RawPacket]) -> Result<usize, EngineError> {
let mut total_sent = 0usize;
// Process in chunks of BATCH_SIZE
for chunk in packets.chunks(BATCH_SIZE) {
let count = chunk.len();
// Build iovec and mmsghdr arrays on stack
let mut iovecs: Vec<libc::iovec> = Vec::with_capacity(count);
let mut addrs: Vec<libc::sockaddr_in> = Vec::with_capacity(count);
let mut msgs: Vec<libc::mmsghdr> = Vec::with_capacity(count);
for pkt in chunk {
if pkt.len < 40 {
self.tx_stats.record_drop(1);
continue;
}
let dst_ip = u32::from_be_bytes([
pkt.buf[offsets::IP_DST],
pkt.buf[offsets::IP_DST + 1],
pkt.buf[offsets::IP_DST + 2],
pkt.buf[offsets::IP_DST + 3],
]);
addrs.push(libc::sockaddr_in {
sin_family: libc::AF_INET as u16,
sin_port: 0,
sin_addr: libc::in_addr { s_addr: dst_ip.to_be() },
sin_zero: [0; 8],
});
iovecs.push(libc::iovec {
iov_base: pkt.buf.as_ptr() as *mut libc::c_void,
iov_len: pkt.len as usize,
});
}
// Build mmsghdr array
for i in 0..iovecs.len() {
msgs.push(libc::mmsghdr {
msg_hdr: libc::msghdr {
msg_name: &mut addrs[i] as *mut _ as *mut libc::c_void,
msg_namelen: std::mem::size_of::<libc::sockaddr_in>() as u32,
msg_iov: &mut iovecs[i],
msg_iovlen: 1,
msg_control: std::ptr::null_mut(),
msg_controllen: 0,
msg_flags: 0,
},
msg_len: 0,
});
}
if msgs.is_empty() {
continue;
}
let sent = unsafe {
libc::sendmmsg(
self.tx_fd,
msgs.as_mut_ptr(),
msgs.len() as u32,
0, // flags
)
};
if sent > 0 {
let sent = sent as usize;
total_sent += sent;
self.tx_stats.record(sent as u64);
if sent < msgs.len() {
self.tx_stats.record_drop((msgs.len() - sent) as u64);
}
} else {
self.tx_stats.record_drop(msgs.len() as u64);
}
}
Ok(total_sent)
}
fn rx_batch(&self, buf: &mut [RxPacket]) -> Result<usize, EngineError> {
// Batched reception via recvmmsg(): up to RX_BATCH_CAP
// packets per syscall instead of one recv() per packet.
// At 1M+ pps the per-packet syscall path is the actual
// bottleneck — this drop alone collapses ~1000x of
// syscall overhead into a single ring traversal.
//
// We allocate the iovec backing buffers on the stack
// (via fixed arrays) so the hot path stays alloc-free.
const RX_BATCH_CAP: usize = 256;
const PKT_CAP: usize = 65_536;
let want = buf.len().min(RX_BATCH_CAP);
if want == 0 {
return Ok(0);
}
// Per-slot scratch storage. Heap-allocated once per call
// (not per packet) — the hot loop is the syscall, not
// these Vec allocations.
let mut pkt_bufs: Vec<[u8; PKT_CAP]> = Vec::with_capacity(want);
let mut iovecs: Vec<libc::iovec> = Vec::with_capacity(want);
let mut msgs: Vec<libc::mmsghdr> = Vec::with_capacity(want);
// SAFETY: we initialise every slot we read from, and only
// read up to `received`. Uninitialised stack bytes never
// escape the function.
unsafe {
pkt_bufs.set_len(want);
}
for i in 0..want {
iovecs.push(libc::iovec {
iov_base: pkt_bufs[i].as_mut_ptr() as *mut libc::c_void,
iov_len: PKT_CAP,
});
}
for i in 0..want {
msgs.push(libc::mmsghdr {
msg_hdr: libc::msghdr {
msg_name: std::ptr::null_mut(),
msg_namelen: 0,
msg_iov: &mut iovecs[i],
msg_iovlen: 1,
msg_control: std::ptr::null_mut(),
msg_controllen: 0,
msg_flags: 0,
},
msg_len: 0,
});
}
let n_recv = unsafe {
libc::recvmmsg(
self.rx_fd,
msgs.as_mut_ptr(),
msgs.len() as u32,
libc::MSG_DONTWAIT,
std::ptr::null_mut(),
)
};
if n_recv <= 0 {
return Ok(0);
}
// n_recv is checked > 0 above so the `as usize` cast is
// sign-safe; recvmmsg returns -1 on error and 0..=msgs.len()
// on success.
let n_recv_usize = usize::try_from(n_recv).unwrap_or(0);
let mut received = 0usize;
for i in 0..n_recv_usize {
let n = msgs[i].msg_len as usize;
if n < 40 {
continue; // Too short for IP + TCP
}
let pkt_buf = &pkt_bufs[i];
// Parse IP header
let ihl = (pkt_buf[0] & 0x0F) as usize * 4;
if n < ihl + 20 {
continue;
}
let src_ip = Ipv4Addr::new(
pkt_buf[12], pkt_buf[13], pkt_buf[14], pkt_buf[15],
);
let ttl = pkt_buf[8];
// Parse TCP header
let tcp = &pkt_buf[ihl..];
let src_port = u16::from_be_bytes([tcp[0], tcp[1]]);
let dst_port = u16::from_be_bytes([tcp[2], tcp[3]]);
let seq_num = u32::from_be_bytes([tcp[4], tcp[5], tcp[6], tcp[7]]);
let ack_num = u32::from_be_bytes([tcp[8], tcp[9], tcp[10], tcp[11]]);
let tcp_data_offset = ((tcp[12] >> 4) as usize) * 4;
let tcp_flags = tcp[13];
let window = u16::from_be_bytes([tcp[14], tcp[15]]);
let payload_start = ihl + tcp_data_offset;
let payload = if n > payload_start {
pkt_buf[payload_start..n].to_vec()
} else {
Vec::new()
};
buf[received] = RxPacket {
packet: RawPacket::from_bytes(&pkt_buf[..n]).unwrap_or_default(),
src_ip,
src_port,
dst_port,
tcp_flags,
ack_num,
seq_num,
ttl,
window,
payload,
};
received += 1;
}
self.rx_stats.record(received as u64);
Ok(received)
}
fn stats(&self) -> EngineStats {
EngineStats {
tx_packets: self.tx_stats.total(),
rx_packets: self.rx_stats.total(),
tx_drops: self.tx_stats.drops(),
rx_drops: self.rx_stats.drops(),
tx_pps: self.tx_stats.snapshot_pps(),
rx_pps: self.rx_stats.snapshot_pps(),
}
}
fn name(&self) -> &'static str {
"sendmmsg"
}
}
// Safety: the raw fds are only accessed through synchronized methods
unsafe impl Send for SendmmsgEngine {}
unsafe impl Sync for SendmmsgEngine {}
}
#[cfg(all(target_os = "linux", feature = "sendmmsg-backend"))]
pub use inner::SendmmsgEngine;