Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Ordering on WordLock (tsan detected) #292

Merged
merged 2 commits into from Aug 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions core/build.rs
@@ -0,0 +1,10 @@
// Automatically detect tsan in a way that's compatible with both stable (which
// doesn't support sanitizers) and nightly (which does). Works because build
// scripts gets `cfg` info, even if the cfg is unstable.
fn main() {
println!("cargo:rerun-if-changed=build.rs");
let santizer_list = std::env::var("CARGO_CFG_SANITIZE").unwrap_or_default();
if santizer_list.contains("thread") {
println!("cargo:rustc-cfg=tsan_enabled");
}
}
17 changes: 14 additions & 3 deletions core/src/word_lock.rs
Expand Up @@ -154,7 +154,7 @@ impl WordLock {
if let Err(x) = self.state.compare_exchange_weak(
state,
state.with_queue_head(thread_data),
Ordering::Release,
Ordering::AcqRel,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch! Thinking about it for a bit, an acquire is indeed needed here so that the call to park happens after the thread is inserted into the queue.

Ordering::Relaxed,
) {
return x;
Expand Down Expand Up @@ -238,7 +238,7 @@ impl WordLock {
}

// Need an acquire fence before reading the new queue
fence(Ordering::Acquire);
fence_acquire(&self.state);
continue;
}

Expand All @@ -263,7 +263,7 @@ impl WordLock {
continue;
} else {
// Need an acquire fence before reading the new queue
fence(Ordering::Acquire);
fence_acquire(&self.state);
continue 'outer;
}
}
Expand All @@ -286,6 +286,17 @@ impl WordLock {
}
}

// Thread-Sanitizer only has partial fence support, so when running under it, we
// try and avoid false positives by using a discarded acquire load instead.
#[inline]
fn fence_acquire(a: &AtomicUsize) {
if cfg!(tsan_enabled) {
let _ = a.load(Ordering::Acquire);
} else {
fence(Ordering::Acquire);
}
}

trait LockState {
fn is_locked(self) -> bool;
fn is_queue_locked(self) -> bool;
Expand Down