Skip to content

Commit 594c417

Browse files
authored
Make tcp id globally unique (#50)
1 parent 862e522 commit 594c417

File tree

1 file changed

+10
-22
lines changed

1 file changed

+10
-22
lines changed

msim/src/sim/net/mod.rs

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@
3636
//! ```
3737
3838
use std::{
39-
collections::{hash_map::Entry, HashMap, HashSet},
39+
collections::{HashMap, HashSet},
4040
io,
4141
net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs},
4242
os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd},
43-
sync::{Arc, Mutex},
43+
sync::{Arc, atomic::{AtomicU32, Ordering}, Mutex},
4444
task::Context,
4545
};
4646
use tap::TapFallible;
@@ -70,7 +70,7 @@ pub struct NetSim {
7070
host_state: Mutex<HostNetworkState>,
7171
rand: GlobalRng,
7272
time: TimeHandle,
73-
next_tcp_id_map: Mutex<HashMap<NodeId, u32>>,
73+
next_tcp_id: AtomicU32, // We always allocate new globally unique tcp id.
7474
}
7575

7676
#[derive(Debug)]
@@ -896,7 +896,8 @@ impl plugin::Simulator for NetSim {
896896
rand: rand.clone(),
897897
time: time.clone(),
898898
host_state: Default::default(),
899-
next_tcp_id_map: Mutex::new(HashMap::new()),
899+
// tcp ids start at 1, 0 is used for new connections (see poll_accept_internal)
900+
next_tcp_id: AtomicU32::new(1),
900901
}
901902
}
902903

@@ -944,7 +945,7 @@ impl NetSim {
944945
let mut host_state = self.host_state.lock().unwrap();
945946
host_state.delete_node(id);
946947

947-
// We do not reset self.next_tcp_id_map - we do not want to re-use tcp ids after a node is
948+
// We do not reset self.next_tcp_id - we do not want to re-use tcp ids after a node is
948949
// restarted.
949950
}
950951

@@ -991,22 +992,9 @@ impl NetSim {
991992
self.time.sleep(delay).await;
992993
}
993994

994-
/// Get the next unused tcp id for this node.
995-
pub fn next_tcp_id(&self, node: NodeId) -> u32 {
996-
let mut map = self.next_tcp_id_map.lock().unwrap();
997-
match map.entry(node) {
998-
Entry::Occupied(mut cur) => {
999-
let cur = cur.get_mut();
1000-
// limited to 2^32 - 1 tcp sessions per node per simulation run.
1001-
*cur = cur.checked_add(1).unwrap();
1002-
*cur
1003-
}
1004-
Entry::Vacant(e) => {
1005-
// tcp ids start at 1, 0 is used for new connections (see poll_accept_internal)
1006-
e.insert(1);
1007-
1
1008-
}
1009-
}
995+
/// Get the next unused tcp id.
996+
pub fn next_tcp_id(&self) -> u32 {
997+
self.next_tcp_id.fetch_add(1, Ordering::SeqCst)
1010998
}
1011999
}
10121000

@@ -1111,7 +1099,7 @@ impl Endpoint {
11111099

11121100
/// Allocate a new tcp id number for this node. Ids are never reused.
11131101
pub fn allocate_local_tcp_id(&self) -> u32 {
1114-
let id = self.net.next_tcp_id(self.node);
1102+
let id = self.net.next_tcp_id();
11151103
trace!(
11161104
"Allocate local tcp id {} to node {} address {}",
11171105
id,

0 commit comments

Comments
 (0)