Skip to content

Commit 7eb264a

Browse files
authored
net: replace RwLock<Slab> with a lock free slab (tokio-rs#1625)
## Motivation The `tokio_net::driver` module currently stores the state associated with scheduled IO resources in a `Slab` implementation from the `slab` crate. Because inserting items into and removing items from `slab::Slab` requires mutable access, the slab must be placed within a `RwLock`. This has the potential to be a performance bottleneck especially in the context of the work-stealing scheduler where tasks and the reactor are often located on the same thread. `tokio-net` currently reimplements the `ShardedRwLock` type from `crossbeam` on top of `parking_lot`'s `RwLock` in an attempt to squeeze as much performance as possible out of the read-write lock around the slab. This introduces several dependencies that are not used elsewhere. ## Solution This branch replaces the `RwLock<Slab>` with a lock-free sharded slab implementation. The sharded slab is based on the concept of _free list sharding_ described by Leijen, Zorn, and de Moura in [_Mimalloc: Free List Sharding in Action_][mimalloc], which describes the implementation of a concurrent memory allocator. In this approach, the slab is sharded so that each thread has its own thread-local list of slab _pages_. Objects are always inserted into the local slab of the thread where the insertion is performed. Therefore, the insert operation needs not be synchronized. However, since objects can be _removed_ from the slab by threads other than the one on which they were inserted, removal operations can still occur concurrently. Therefore, Leijen et al. introduce a concept of _local_ and _global_ free lists. When an object is removed on the same thread it was originally inserted on, it is placed on the local free list; if it is removed on another thread, it goes on the global free list for the heap of the thread from which it originated. To find a free slot to insert into, the local free list is used first; if it is empty, the entire global free list is popped onto the local free list. Since the local free list is only ever accessed by the thread it belongs to, it does not require synchronization at all, and because the global free list is popped from infrequently, the cost of synchronization has a reduced impact. A majority of insertions can occur without any synchronization at all; and removals only require synchronization when an object has left its parent thread. The sharded slab was initially implemented in a separate crate (soon to be released), vendored in-tree to decrease `tokio-net`'s dependencies. Some code from the original implementation was removed or simplified, since it is only necessary to support `tokio-net`'s use case, rather than to provide a fully generic implementation. [mimalloc]: https://www.microsoft.com/en-us/research/uploads/prod/2019/06/mimalloc-tr-v1.pdf ## Performance These graphs were produced by out-of-tree `criterion` benchmarks of the sharded slab implementation. The first shows the results of a benchmark where an increasing number of items are inserted and then removed into a slab concurrently by five threads. It compares the performance of the sharded slab implementation with a `RwLock<slab::Slab>`: <img width="1124" alt="Screen Shot 2019-10-01 at 5 09 49 PM" src="https://user-images.githubusercontent.com/2796466/66078398-cd6c9f80-e516-11e9-9923-0ed6292e8498.png"> The second graph shows the results of a benchmark where an increasing number of items are inserted and then removed by a _single_ thread. It compares the performance of the sharded slab implementation with an `RwLock<slab::Slab>` and a `mut slab::Slab`. <img width="925" alt="Screen Shot 2019-10-01 at 5 13 45 PM" src="https://user-images.githubusercontent.com/2796466/66078469-f0974f00-e516-11e9-95b5-f65f0aa7e494.png"> Note that while the `mut slab::Slab` (i.e. no read-write lock) is (unsurprisingly) faster than the sharded slab in the single-threaded benchmark, the sharded slab outperforms the un-contended `RwLock<slab::Slab>`. This case, where the lock is uncontended and only accessed from a single thread, represents the best case for the current use of `slab` in `tokio-net`, since the lock cannot be conditionally removed in the single-threaded case. These benchmarks demonstrate that, while the sharded approach introduces a small constant-factor overhead, it offers significantly better performance across concurrent accesses. ## Notes This branch removes the following dependencies `tokio-net`: - `parking_lot` - `num_cpus` - `crossbeam_util` - `slab` This branch adds the following dev-dependencies: - `proptest` - `loom` Note that these dev dependencies were used to implement tests for the sharded-slab crate out-of-tree, and were necessary in order to vendor the existing tests. Alternatively, since the implementation is tested externally, we _could_ remove these tests in order to avoid picking up dev-dependencies. However, this means that we should try to ensure that `tokio-net`'s vendored implementation doesn't diverge significantly from upstream's, since it would be missing a majority of its tests. Signed-off-by: Eliza Weisman <[email protected]>
1 parent 1195263 commit 7eb264a

28 files changed

+2326
-314
lines changed

azure-pipelines.yml

+1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ jobs:
8282
rust: beta
8383
crates:
8484
- tokio-executor
85+
- tokio
8586

8687
# Try cross compiling
8788
- template: ci/azure-cross-compile.yml

tokio/Cargo.toml

+9-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ io-util = ["io-traits", "pin-project", "memchr"]
4141
io = ["io-traits", "io-util"]
4242
macros = ["tokio-macros"]
4343
net-full = ["tcp", "udp", "uds"]
44-
net-driver = ["mio", "tokio-executor/blocking"]
44+
net-driver = ["mio", "tokio-executor/blocking", "lazy_static"]
4545
rt-current-thread = [
4646
"timer",
4747
"tokio-executor/current-thread",
@@ -113,6 +113,10 @@ version = "0.3.8"
113113
default-features = false
114114
optional = true
115115

116+
[target.'cfg(loom)'.dependencies]
117+
# play nice with loom tests in other crates.
118+
loom = "0.2.11"
119+
116120
[dev-dependencies]
117121
tokio-test = { version = "=0.2.0-alpha.6", path = "../tokio-test" }
118122
tokio-util = { version = "=0.2.0-alpha.6", path = "../tokio-util" }
@@ -130,5 +134,9 @@ serde_json = "1.0"
130134
tempfile = "3.1.0"
131135
time = "0.1"
132136

137+
# sharded slab tests
138+
loom = "0.2.11"
139+
proptest = "0.9.4"
140+
133141
[package.metadata.docs.rs]
134142
all-features = true

tokio/src/lib.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,6 @@
6969
//! }
7070
//! }
7171
//! ```
72-
7372
macro_rules! if_runtime {
7473
($($i:item)*) => ($(
7574
#[cfg(any(
@@ -97,6 +96,9 @@ pub mod io;
9796
#[cfg(feature = "net-driver")]
9897
pub mod net;
9998

99+
#[cfg(feature = "net-driver")]
100+
mod loom;
101+
100102
pub mod prelude;
101103

102104
#[cfg(feature = "process")]

tokio/src/loom.rs

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//! This module abstracts over `loom` and `std::sync` depending on whether we
2+
//! are running tests or not.
3+
pub(crate) use self::inner::*;
4+
5+
#[cfg(all(test, loom))]
6+
mod inner {
7+
pub(crate) use loom::sync::CausalCell;
8+
pub(crate) use loom::sync::Mutex;
9+
pub(crate) mod atomic {
10+
pub(crate) use loom::sync::atomic::*;
11+
pub(crate) use std::sync::atomic::Ordering;
12+
}
13+
}
14+
15+
#[cfg(not(all(test, loom)))]
16+
mod inner {
17+
use std::cell::UnsafeCell;
18+
pub(crate) use std::sync::atomic;
19+
pub(crate) use std::sync::Mutex;
20+
21+
#[derive(Debug)]
22+
pub(crate) struct CausalCell<T>(UnsafeCell<T>);
23+
24+
impl<T> CausalCell<T> {
25+
pub(crate) fn new(data: T) -> CausalCell<T> {
26+
CausalCell(UnsafeCell::new(data))
27+
}
28+
29+
#[inline(always)]
30+
pub(crate) fn with<F, R>(&self, f: F) -> R
31+
where
32+
F: FnOnce(*const T) -> R,
33+
{
34+
f(self.0.get())
35+
}
36+
37+
#[inline(always)]
38+
pub(crate) fn with_mut<F, R>(&self, f: F) -> R
39+
where
40+
F: FnOnce(*mut T) -> R,
41+
{
42+
f(self.0.get())
43+
}
44+
}
45+
}

tokio/src/net/driver/mod.rs

+8
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,15 @@
124124
//! [`PollEvented`]: struct.PollEvented.html
125125
//! [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
126126
//! [`std::io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
127+
#[cfg(loom)]
128+
macro_rules! loom_thread_local {
129+
($($tts:tt)+) => { loom::thread_local!{ $($tts)+ } }
130+
}
127131

132+
#[cfg(not(loom))]
133+
macro_rules! loom_thread_local {
134+
($($tts:tt)+) => { std::thread_local!{ $($tts)+ } }
135+
}
128136
pub(crate) mod platform;
129137
mod reactor;
130138
mod registration;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
use super::{
2+
page::{self, ScheduledIo},
3+
Shard,
4+
};
5+
use std::slice;
6+
7+
pub(in crate::net::driver::reactor) struct UniqueIter<'a> {
8+
pub(super) shards: slice::IterMut<'a, Shard>,
9+
pub(super) pages: slice::Iter<'a, page::Shared>,
10+
pub(super) slots: Option<page::Iter<'a>>,
11+
}
12+
13+
impl<'a> Iterator for UniqueIter<'a> {
14+
type Item = &'a ScheduledIo;
15+
fn next(&mut self) -> Option<Self::Item> {
16+
loop {
17+
if let Some(item) = self.slots.as_mut().and_then(|slots| slots.next()) {
18+
return Some(item);
19+
}
20+
21+
if let Some(page) = self.pages.next() {
22+
self.slots = page.iter();
23+
}
24+
25+
if let Some(shard) = self.shards.next() {
26+
self.pages = shard.iter();
27+
} else {
28+
return None;
29+
}
30+
}
31+
}
32+
}
33+
34+
pub(in crate::net::driver::reactor) struct ShardIter<'a> {
35+
pub(super) pages: slice::IterMut<'a, page::Shared>,
36+
pub(super) slots: Option<page::Iter<'a>>,
37+
}
38+
39+
impl<'a> Iterator for ShardIter<'a> {
40+
type Item = &'a ScheduledIo;
41+
fn next(&mut self) -> Option<Self::Item> {
42+
loop {
43+
if let Some(item) = self.slots.as_mut().and_then(|slots| slots.next()) {
44+
return Some(item);
45+
}
46+
if let Some(page) = self.pages.next() {
47+
self.slots = page.iter();
48+
} else {
49+
return None;
50+
}
51+
}
52+
}
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//! A lock-free concurrent slab.
2+
3+
#[cfg(all(test, loom))]
4+
macro_rules! test_println {
5+
($($arg:tt)*) => {
6+
println!("{:?} {}", crate::net::driver::reactor::dispatch::Tid::current(), format_args!($($arg)*))
7+
}
8+
}
9+
10+
mod iter;
11+
mod pack;
12+
mod page;
13+
mod sharded_slab;
14+
mod tid;
15+
16+
#[cfg(all(test, loom))]
17+
// this is used by sub-modules
18+
use self::tests::test_util;
19+
use pack::{Pack, WIDTH};
20+
use sharded_slab::Shard;
21+
#[cfg(all(test, loom))]
22+
pub(crate) use sharded_slab::Slab;
23+
pub(crate) use sharded_slab::{SingleShard, MAX_SOURCES};
24+
use tid::Tid;
25+
26+
#[cfg(target_pointer_width = "64")]
27+
const MAX_THREADS: usize = 4096;
28+
#[cfg(target_pointer_width = "32")]
29+
const MAX_THREADS: usize = 2048;
30+
const INITIAL_PAGE_SIZE: usize = 32;
31+
const MAX_PAGES: usize = WIDTH / 4;
32+
// Chosen arbitrarily.
33+
const RESERVED_BITS: usize = 5;
34+
35+
#[cfg(test)]
36+
mod tests;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
pub(super) const WIDTH: usize = std::mem::size_of::<usize>() * 8;
2+
3+
/// Trait encapsulating the calculations required for bit-packing slab indices.
4+
///
5+
/// This allows us to avoid manually repeating some calculations when packing
6+
/// and unpacking indices.
7+
pub(crate) trait Pack: Sized {
8+
// ====== provided by each implementation =================================
9+
10+
/// The number of bits occupied by this type when packed into a usize.
11+
///
12+
/// This must be provided to determine the number of bits into which to pack
13+
/// the type.
14+
const LEN: usize;
15+
/// The type packed on the less significant side of this type.
16+
///
17+
/// If this type is packed into the least significant bit of a usize, this
18+
/// should be `()`, which occupies no bytes.
19+
///
20+
/// This is used to calculate the shift amount for packing this value.
21+
type Prev: Pack;
22+
23+
// ====== calculated automatically ========================================
24+
25+
/// A number consisting of `Self::LEN` 1 bits, starting at the least
26+
/// significant bit.
27+
///
28+
/// This is the higest value this type can represent. This number is shifted
29+
/// left by `Self::SHIFT` bits to calculate this type's `MASK`.
30+
///
31+
/// This is computed automatically based on `Self::LEN`.
32+
const BITS: usize = {
33+
let shift = 1 << (Self::LEN - 1);
34+
shift | (shift - 1)
35+
};
36+
/// The number of bits to shift a number to pack it into a usize with other
37+
/// values.
38+
///
39+
/// This is caculated automatically based on the `LEN` and `SHIFT` constants
40+
/// of the previous value.
41+
const SHIFT: usize = Self::Prev::SHIFT + Self::Prev::LEN;
42+
43+
/// The mask to extract only this type from a packed `usize`.
44+
///
45+
/// This is calculated by shifting `Self::BITS` left by `Self::SHIFT`.
46+
const MASK: usize = Self::BITS << Self::SHIFT;
47+
48+
fn as_usize(&self) -> usize;
49+
fn from_usize(val: usize) -> Self;
50+
51+
#[inline(always)]
52+
fn pack(&self, to: usize) -> usize {
53+
let value = self.as_usize();
54+
debug_assert!(value <= Self::BITS);
55+
56+
(to & !Self::MASK) | (value << Self::SHIFT)
57+
}
58+
59+
#[inline(always)]
60+
fn from_packed(from: usize) -> Self {
61+
let value = (from & Self::MASK) >> Self::SHIFT;
62+
debug_assert!(value <= Self::BITS);
63+
Self::from_usize(value)
64+
}
65+
}
66+
67+
impl Pack for () {
68+
const BITS: usize = 0;
69+
const LEN: usize = 0;
70+
const SHIFT: usize = 0;
71+
const MASK: usize = 0;
72+
73+
type Prev = ();
74+
75+
fn as_usize(&self) -> usize {
76+
unreachable!()
77+
}
78+
fn from_usize(_val: usize) -> Self {
79+
unreachable!()
80+
}
81+
82+
fn pack(&self, _to: usize) -> usize {
83+
unreachable!()
84+
}
85+
86+
fn from_packed(_from: usize) -> Self {
87+
unreachable!()
88+
}
89+
}

0 commit comments

Comments
 (0)