Safe Systems Programming Series III: Managing Reliable Sequenced Data in Rust
Reliable Network Buffers
UDP does not guarantee delivery order, so packets can arrive out of sequence. A reliable protocol, like TCP, must reorder the packets that it receives. For this, we need a network buffer that stores packets of different sizes and puts them back in sequence.
This article will implement an OrderedBuffer that meets the requirements to consume data from a reliable protocol over UDP:
let mut socket: std::net::UdpSocket;
let mut buffer: OrderedBuffer<'_, '_>;
// Receive data into `OrderedBuffer`
buffer.push_with(MTU, |mut view| {
let written = socket.recv(view.data_mut())?;
let data = Message::from_bytes(&view.data()[0..written]);
view.set_sequence_number(data.sequence_number);
view.set_length(written as u32);
Ok(())
});
Recall the requirements for a network buffer:
- The buffer stores network bytes in the same memory allocation
- The length of a packet is unknown in advance
- Receiving a packet can fail
- Packets may arrive out of order
This article is the final part in the series on designing network buffers. To learn how to implement a simple ring buffer and
UnorderedBuffer, read the previous two articles in the series:
Network Buffers in Linux
OrderedBuffer uses the same two parts as AF_XDP: a metadata buffer and a data buffer. Safe Systems Programming Series II: Network Buffers in Rust explains this design. The RX ring of an AF_XDP socket gives the descriptors in the sequence that the packets arrive. The application must put the packets back in the order of their sequence numbers. OrderedBuffer does this with a metadata buffer that is a linked list in a ring buffer. The ring buffer gives better memory locality.
Ordered Metadata Buffers
Metadata buffers track the location and length of each packet in the data buffer. OrderedMetadataBuffer is a linked list, because a linked list inserts, removes and reorders entries in constant time. A ring buffer, Ring, stores the linked list.
/// Metadata for ordered network packets
pub struct OrderedMetadata {
sequence_number: u32,
storage_index: u32,
storage_length: u32,
storage_padding: u32,
metadata_next_index: u32,
}
Each OrderedMetadata entry holds its own sequence number. OrderedMetadataBuffer holds the index of the first and the last entry for efficient insertion and removal.
/// [`OrderedMetadataBuffer`] that stores [`OrderedMetadata`] as a
/// singly linked list backed by a circular [`Ring`]
#[derive(Debug)]
pub struct OrderedMetadataBuffer<'m> {
first_index: u32,
last_index: u32,
ring: Ring<'m, OrderedMetadata>,
}
Metadata Insertion
OrderedMetadataBuffer::push_with allocates an entry in the ring buffer and gives it to the closure. Then insert_metadata links the entry into the list. The ring buffer commits the entry only if both steps succeed:
impl<'m> OrderedMetadataBuffer<'m> {
pub fn push_with<R, F>(&mut self, f: F) -> Result<R, std::io::Error>
where
F: FnOnce(&mut OrderedMetadata) -> Result<R, std::io::Error>,
{
// Allocate new metadata conditional on linked list insert success
self.ring.push_with(|mut view| {
let res = f(view.data_mut())?;
Self::insert_metadata(&mut view, &mut self.first_index, &mut self.last_index)?;
Ok(res)
})
// ...
}
}
insert_metadata handles four cases. The first three cases take constant time.
When the buffer is empty, we insert the first packet at the head of the buffer:
index is the slot of the new entry. The new entry is at the head of the ring only when the buffer is empty:
impl<'m> OrderedMetadataBuffer<'m> {
fn insert_metadata(
view: &mut RingMutView<'_, 'm, OrderedMetadata>,
first_index: &mut u32,
last_index: &mut u32,
) -> Result<(), std::io::Error> {
let index = view.index();
let ring = view.ring_mut();
let sequence_number = ring.get(index).unwrap().sequence_number;
// The buffer is empty if the new element is at the head of the ring
if ring.head() == index {
*first_index = index;
*last_index = index;
return Ok(());
}
// ...
}
}
Next, we receive a packet with a sequence number larger than the sequence number at the last index. We rearrange the linked list so that the last index points to the new packet:
fn insert_metadata(/* ... */) -> Result<(), std::io::Error> {
// ...
// Insert after the last element
let last = ring.get_mut(*last_index).unwrap();
match sequence_number.cmp(&last.sequence_number) {
Ordering::Less => {}
Ordering::Equal => return Err(ErrorKind::AlreadyExists.into()),
Ordering::Greater => {
last.metadata_next_index = index;
*last_index = index;
return Ok(());
}
}
// ...
}
Similarly, we can receive a packet with a sequence number smaller than the sequence number at the first index. We insert this packet at the start of the linked list:
fn insert_metadata(/* ... */) -> Result<(), std::io::Error> {
// ...
// Insert before the first element
let first = ring.get_mut(*first_index).unwrap();
match sequence_number.cmp(&first.sequence_number) {
Ordering::Less => {
ring.get_mut(index).unwrap().metadata_next_index = *first_index;
*first_index = index;
return Ok(());
}
Ordering::Equal => return Err(ErrorKind::AlreadyExists.into()),
Ordering::Greater => {}
}
// ...
}
A packet can also have a sequence number between the sequence numbers at the first and the last index. Then we must rearrange multiple metadata entries:
This is the only case that walks the linked list. We start at the first index, because the receiver usually waits for the packets near the start of the list:
fn insert_metadata(/* ... */) -> Result<(), std::io::Error> {
// ...
// Walk the linked list from the first element to find the position
let mut prev_index = *first_index;
let mut current_index = *first_index;
loop {
let current = ring.get_mut(current_index).unwrap();
match sequence_number.cmp(¤t.sequence_number) {
Ordering::Less => {
ring.get_mut(index).unwrap().metadata_next_index = current_index;
ring.get_mut(prev_index).unwrap().metadata_next_index = index;
return Ok(());
}
Ordering::Equal => return Err(ErrorKind::AlreadyExists.into()),
Ordering::Greater => {}
}
prev_index = current_index;
current_index = current.metadata_next_index;
}
}
If the insertion succeeds, we commit the new metadata entry to the metadata buffer:
Each case returns ErrorKind::AlreadyExists when the sequence number is already in the list. Then push_with returns the error, and the ring buffer does not commit the entry. Thus the buffer stores each sequence number only once:
Metadata Removal
OrderedMetadataBuffer removes entries in the order of the linked list. But the ring buffer can only free entries at its head, and these entries are in the order of arrival. Consider packets that arrive in the order 3, 1 and 2:
pop_with gives the entry at the first index to the closure. If the closure returns Some, pop_with moves the first index to the next entry:
impl OrderedMetadataBuffer<'_> {
pub fn pop_with<R, F>(&mut self, deallocated: &mut u32, f: F) -> Option<R>
where
F: FnOnce(&OrderedMetadata) -> Option<R>,
{
let first = self.peek()?;
let res = f(first)?;
let sequence_number = first.sequence_number;
self.first_index = first.metadata_next_index;
Self::pop_inner(&mut self.ring, deallocated, sequence_number);
Some(res)
}
}
When we pop 1 and 2, the first index moves to entry 3. The ring buffer cannot free entries 1 and 2 yet, because entry 3 is still at its head:
pop_inner frees the entries at the head of the ring while their sequence numbers are not larger than the popped sequence number. The receiver pops in sequence order, so it already popped each of these entries. deallocated collects the length and padding of each freed entry:
fn pop_until_inner(ring: &mut Ring<'_, OrderedMetadata>, deallocated: &mut u32, sequence_number: u32) -> u32 {
let mut count = 0;
ring.pop_many_with(|entries| {
for m in entries.iter().take_while(|m| m.sequence_number <= sequence_number) {
count += 1;
*deallocated += m.storage_length + m.storage_padding;
}
count
});
count
}
Ring::pop_many_with only gives the entries from the head to the end of the ring. When the freed entries continue past the end, pop_inner does a second pass from the start of the ring:
fn pop_inner(ring: &mut Ring<'_, OrderedMetadata>, deallocated: &mut u32, sequence_number: u32) {
*deallocated = 0;
let window = ring.full_tail_window();
let count = Self::pop_until_inner(ring, deallocated, sequence_number);
// The freed entries continue at the start of the ring
if count == window {
Self::pop_until_inner(ring, deallocated, sequence_number);
}
}
pop_innermust readRing::full_tail_windowbefore the first pass. The first pass moves the head of the ring, so the window that it returns after the pass is a different window. If the second pass compares against that window, it can skip entries that are ready to free. Then the list is empty, but the ring still holds entries, sopeekfollows a stale index.
When we pop 3, the ring buffer frees all three entries together:
Without a reset, the head of the empty ring stays at the fourth slot. The ring buffer moves its head back to the start when it becomes empty, so the next entries reuse the same cache lines. Padding Packet Data explains the concept.
![]()
Ordered Network Buffers
OrderedBuffer combines OrderedMetadataBuffer with a data buffer, in the same way as UnorderedBuffer. The data buffer stores the packets in the order of arrival. The metadata buffer links them in sequence order:
pub struct OrderedBuffer<'m, 's> {
receive_ring: OrderedMetadataBuffer<'m>,
storage_ring: Ring<'s, u8>,
}
OrderedBuffer::push_with handles the tail of the data buffer in the same way as UnorderedBuffer::push_with. Padding Packet Data explains this procedure. The only addition to PushView is the sequence number, which the closure reads from the packet:
impl PushView<'_, '_> {
/// Set sequence number of element
pub fn set_sequence_number(&mut self, sequence_number: u32) -> &mut Self {
self.metadata.set_sequence_number(sequence_number);
self
}
}
The data allocation happens inside the metadata allocation, so that the closure can write the packet and set its sequence number together:
impl<'s> OrderedBuffer<'_, 's> {
fn push_with_inner<R, F>(&mut self, f: F) -> Result<R, std::io::Error>
where
F: FnOnce(PushView<'_, 's>) -> Result<R, std::io::Error>,
{
// Allocate metadata conditional on storage allocation succeeding
let res = self.receive_ring.push_with(|metadata| {
self.storage_ring.push_many_with(|view| {
metadata.set_index(view.index());
f(PushView { metadata, view })
})
});
// ...
}
}
The data buffer commits the packet before
insert_metadataruns. Ifinsert_metadatarejects a duplicate, the metadata buffer does not commit the entry, but the packet stays in the data buffer. No metadata entry owns these bytes:![]()
push_withmust release the bytes that the rejected packet left at the end of the data buffer:fn push_with_inner(/* ... */) -> Result<R, std::io::Error> { // The length of the data buffer before the allocation let storage_len = self.storage_ring.len(); // ... if res.is_err() { let leaked = self.storage_ring.len() - storage_len; self.storage_ring.truncate_many_end(leaked).unwrap(); } res }
OrderedBuffer::pop_with reads the packet at the first index. Then it frees the bytes that pop_inner collected in deallocated:
impl OrderedBuffer<'_, '_> {
pub fn pop_with<R, F>(&mut self, f: F) -> Option<R>
where
F: FnOnce(&[u8]) -> Option<R>,
{
let deallocated = &mut 0;
let res = self.receive_ring.pop_with(deallocated, |m| {
let data = self.storage_ring.get_many(m.index(), m.length()).unwrap();
f(data)
})?;
self.storage_ring.truncate_many_head(*deallocated).unwrap();
Some(res)
}
}
After we pop 1 and 2, the data buffer still holds their bytes, because packet 3 is at its head:
When we pop 3, deallocated holds the length of all three packets, and the data buffer frees them together.
Receiving Ordered Messages
The receiver pushes each packet into OrderedBuffer. Then it pops packets while the first entry holds the next sequence number, next_sequence_number:
fn receive(socket: &mut UdpSocket, buffer: &mut OrderedBuffer<'_, '_>) {
let mut next_sequence_number = 1;
loop {
// Receive a packet into the buffer, as in the first example
let res = buffer.push_with(MTU, |mut view| {
let written = socket.recv(view.data_mut())?;
let data: &Message = from_bytes(&view.data()[0..written]);
view.set_sequence_number(data.seq);
view.set_length(written as u32);
Ok(())
});
if let Err(err) = res {
match err.kind() {
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::AlreadyExists => {}
_ => return,
}
}
// Deliver every message that is next in sequence
loop {
let res = buffer.pop_with(|message| {
let data = Message::from_bytes(message);
match data.sequence_number.cmp(&next_sequence_number) {
// Already received this sequence number, returns `Some`
// so `pop_with` removes the stale packet
Ordering::Less => Some(()),
Ordering::Equal => {
next_sequence_number += 1;
Some(())
}
// Missing packet, closure returns `None` so packet stays
// in the buffer until the missing packet arrives
Ordering::Greater => None,
}
});
if res.is_none() {
break;
}
}
}
}
This receiver cannot recover a lost packet. If a packet never arrives, the receiver keeps the later packets in the buffer until the buffer is full. A reliable protocol must also request and retransmit lost packets, for example with negative acknowledgements (NACK).
- RFC 5401 describes the building blocks of multicast protocols that use NACK.
Testing
Our integration test runs the receivers on an unreliable network. A transmitter sends numbered messages to two receivers. One receiver uses OrderedBuffer, and the other receiver uses UnorderedBuffer. On the way, netem delays the messages, changes their order and copies some of them:
The test does not drop messages, because our receiver cannot recover a lost message yet.
netem(Network Emulator) is a queueing discipline of the Linux traffic control tool,tc. It changes the packets that leave a network interface. It can delay, drop, duplicate, corrupt and reorder packets. The transmitter addsnetemto its network interface:tc qdisc add dev eth0 root netem delay 20ms 10ms reorder 25% 50% duplicate 20%
delay 20ms 10ms: Each packet waits for 20 ms plus a random jitter. The jitter adds or removes up to 10 ms from the delay. Thus each packet gets a different delay, and the jitter alone reorders packets.reorder 25% 50%:netemsends 25% of the packets without the delay. These packets arrive before packets that the transmitter sent earlier. The second value is the correlation with the previous packet.duplicate 20%:netemsends a second copy of 20% of the packets.For example,
netemcan change the order of six packets like this:![]()
In one run, the transmitter sends 20 messages. UnorderedBuffer delivers the messages in a mixed order:
received | { seq: 4 }
received | { seq: 6 }
received | { seq: 12 }
...
received | { seq: 1 }
received | { seq: 5 }
OrderedBuffer delivers each message once and in the correct order:
received | { seq: 1 }
received | { seq: 2 }
received | { seq: 3 }
...
received | { seq: 19 }
received | { seq: 20 }
Conclusion
In this article, we implemented an OrderedBuffer that puts UDP packets back in sequence. Its metadata buffer is a linked list in a ring buffer. Thus it inserts packets in any order, and frees memory in the order of arrival.
The receiver delivers each sequence number once and in order, and netem lets us test this behavior on an impaired network. A reliable protocol must also recover lost packets, for example with negative acknowledgements and retransmission.