Skip to content

Commit

Permalink
Merge pull request #3319 from tnull/2024-09-rustfmt-sync
Browse files Browse the repository at this point in the history
`rustfmt`: Run on `lightning/src/sync/*`
  • Loading branch information
TheBlueMatt committed Sep 17, 2024
2 parents 866cedf + 555bd75 commit 815d255
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 45 deletions.
67 changes: 47 additions & 20 deletions lightning/src/sync/debug_sync.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
pub use ::alloc::sync::Arc;
pub use alloc::sync::Arc;
use core::ops::{Deref, DerefMut};
use core::time::Duration;

use std::cell::RefCell;

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Condvar as StdCondvar;
use std::sync::Mutex as StdMutex;
use std::sync::MutexGuard as StdMutexGuard;
use std::sync::RwLock as StdRwLock;
use std::sync::RwLockReadGuard as StdRwLockReadGuard;
use std::sync::RwLockWriteGuard as StdRwLockWriteGuard;
use std::sync::Condvar as StdCondvar;

pub use std::sync::WaitTimeoutResult;

use crate::prelude::*;

use super::{LockTestExt, LockHeldState};
use super::{LockHeldState, LockTestExt};

#[cfg(feature = "backtrace")]
use {crate::prelude::hash_map, backtrace::Backtrace, std::sync::Once};

#[cfg(not(feature = "backtrace"))]
struct Backtrace{}
struct Backtrace {}
#[cfg(not(feature = "backtrace"))]
impl Backtrace { fn new() -> Backtrace { Backtrace {} } }
impl Backtrace {
fn new() -> Backtrace {
Backtrace {}
}
}

pub type LockResult<Guard> = Result<Guard, ()>;

Expand All @@ -37,22 +41,30 @@ impl Condvar {
Condvar { inner: StdCondvar::new() }
}

pub fn wait_while<'a, T, F: FnMut(&mut T) -> bool>(&'a self, guard: MutexGuard<'a, T>, condition: F)
-> LockResult<MutexGuard<'a, T>> {
pub fn wait_while<'a, T, F: FnMut(&mut T) -> bool>(
&'a self, guard: MutexGuard<'a, T>, condition: F,
) -> LockResult<MutexGuard<'a, T>> {
let mutex: &'a Mutex<T> = guard.mutex;
self.inner.wait_while(guard.into_inner(), condition).map(|lock| MutexGuard { mutex, lock })
self.inner
.wait_while(guard.into_inner(), condition)
.map(|lock| MutexGuard { mutex, lock })
.map_err(|_| ())
}

#[allow(unused)]
pub fn wait_timeout_while<'a, T, F: FnMut(&mut T) -> bool>(&'a self, guard: MutexGuard<'a, T>, dur: Duration, condition: F)
-> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
pub fn wait_timeout_while<'a, T, F: FnMut(&mut T) -> bool>(
&'a self, guard: MutexGuard<'a, T>, dur: Duration, condition: F,
) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
let mutex = guard.mutex;
self.inner.wait_timeout_while(guard.into_inner(), dur, condition).map_err(|_| ())
self.inner
.wait_timeout_while(guard.into_inner(), dur, condition)
.map_err(|_| ())
.map(|(lock, e)| (MutexGuard { mutex, lock }, e))
}

pub fn notify_all(&self) { self.inner.notify_all(); }
pub fn notify_all(&self) {
self.inner.notify_all();
}
}

thread_local! {
Expand Down Expand Up @@ -99,14 +111,19 @@ fn locate_call_symbol(backtrace: &Backtrace) -> (String, Option<u32>) {
symbol_after_latest_debug_sync = Some(symbol);
found_debug_sync = false;
}
} else { found_debug_sync = true; }
} else {
found_debug_sync = true;
}
}
}
}
let symbol = symbol_after_latest_debug_sync.unwrap_or_else(|| {
panic!("Couldn't find lock call symbol in trace {:?}", backtrace);
});
(format!("{}:{}", symbol.filename().unwrap().display(), symbol.lineno().unwrap()), symbol.colno())
(
format!("{}:{}", symbol.filename().unwrap().display(), symbol.lineno().unwrap()),
symbol.colno(),
)
}

impl LockMetadata {
Expand All @@ -124,16 +141,20 @@ impl LockMetadata {
{
let (lock_constr_location, lock_constr_colno) =
locate_call_symbol(&res._lock_construction_bt);
LOCKS_INIT.call_once(|| { unsafe { LOCKS = Some(StdMutex::new(new_hash_map())); } });
LOCKS_INIT.call_once(|| unsafe {
LOCKS = Some(StdMutex::new(new_hash_map()));
});
let mut locks = unsafe { LOCKS.as_ref() }.unwrap().lock().unwrap();
match locks.entry(lock_constr_location) {
hash_map::Entry::Occupied(e) => {
assert_eq!(lock_constr_colno,
locate_call_symbol(&e.get()._lock_construction_bt).1,
"Because Windows doesn't support column number results in backtraces, we cannot construct two mutexes on the same line or we risk lockorder detection false positives.");
return Arc::clone(e.get())
return Arc::clone(e.get());
},
hash_map::Entry::Vacant(e) => {
e.insert(Arc::clone(&res));
},
hash_map::Entry::Vacant(e) => { e.insert(Arc::clone(&res)); },
}
}
res
Expand Down Expand Up @@ -213,7 +234,8 @@ impl LockMetadata {
let mut locked_before = this.locked_before.lock().unwrap();
for (locked_idx, locked) in held.borrow().iter() {
if !locked_before.contains_key(locked_idx) {
let lockdep = LockDep { lock: Arc::clone(locked), _lockdep_trace: Backtrace::new() };
let lockdep =
LockDep { lock: Arc::clone(locked), _lockdep_trace: Backtrace::new() };
locked_before.insert(*locked_idx, lockdep);
}
}
Expand Down Expand Up @@ -282,7 +304,8 @@ impl<T> Mutex<T> {
}

pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
let res = self.inner.try_lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ());
let res =
self.inner.try_lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ());
if res.is_ok() {
LockMetadata::try_locked(&self.deps);
}
Expand Down Expand Up @@ -376,7 +399,11 @@ impl<T> RwLock<T> {
}

pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
let res = self.inner.try_write().map(|guard| RwLockWriteGuard { lock: self, guard }).map_err(|_| ());
let res = self
.inner
.try_write()
.map(|guard| RwLockWriteGuard { lock: self, guard })
.map_err(|_| ());
if res.is_ok() {
LockMetadata::try_locked(&self.deps);
}
Expand Down
4 changes: 2 additions & 2 deletions lightning/src/sync/fairrwlock.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::{LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockResult};
use std::sync::atomic::{AtomicUsize, Ordering};
use super::{LockHeldState, LockTestExt};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{LockResult, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockResult};

/// Rust libstd's RwLock does not provide any fairness guarantees (and, in fact, when used on
/// Linux with pthreads under the hood, readers trivially and completely starve writers).
Expand Down
21 changes: 16 additions & 5 deletions lightning/src/sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,24 +31,35 @@ mod test_lockorder_checks;
#[cfg(all(feature = "std", any(ldk_bench, not(test))))]
pub(crate) mod fairrwlock;
#[cfg(all(feature = "std", any(ldk_bench, not(test))))]
pub use {std::sync::{Arc, Mutex, Condvar, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}, fairrwlock::FairRwLock};
pub use {
fairrwlock::FairRwLock,
std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard},
};

#[cfg(all(feature = "std", any(ldk_bench, not(test))))]
mod ext_impl {
use super::*;
impl<'a, T: 'a> LockTestExt<'a> for Mutex<T> {
#[inline]
fn held_by_thread(&self) -> LockHeldState { LockHeldState::Unsupported }
fn held_by_thread(&self) -> LockHeldState {
LockHeldState::Unsupported
}
type ExclLock = MutexGuard<'a, T>;
#[inline]
fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<T> { self.lock().unwrap() }
fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<T> {
self.lock().unwrap()
}
}
impl<'a, T: 'a> LockTestExt<'a> for RwLock<T> {
#[inline]
fn held_by_thread(&self) -> LockHeldState { LockHeldState::Unsupported }
fn held_by_thread(&self) -> LockHeldState {
LockHeldState::Unsupported
}
type ExclLock = RwLockWriteGuard<'a, T>;
#[inline]
fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<T> { self.write().unwrap() }
fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<T> {
self.write().unwrap()
}
}
}

Expand Down
34 changes: 22 additions & 12 deletions lightning/src/sync/nostd_sync.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
pub use ::alloc::sync::Arc;
use super::{LockHeldState, LockTestExt};
pub use alloc::sync::Arc;
use core::cell::{Ref, RefCell, RefMut};
use core::ops::{Deref, DerefMut};
use core::cell::{RefCell, Ref, RefMut};
use super::{LockTestExt, LockHeldState};

pub type LockResult<Guard> = Result<Guard, ()>;

pub struct Mutex<T: ?Sized> {
inner: RefCell<T>
inner: RefCell<T>,
}

#[must_use = "if unused the Mutex will immediately unlock"]
Expand Down Expand Up @@ -45,16 +45,21 @@ impl<T> Mutex<T> {
impl<'a, T: 'a> LockTestExt<'a> for Mutex<T> {
#[inline]
fn held_by_thread(&self) -> LockHeldState {
if self.inner.try_borrow_mut().is_err() { return LockHeldState::HeldByThread; }
else { return LockHeldState::NotHeldByThread; }
if self.inner.try_borrow_mut().is_err() {
return LockHeldState::HeldByThread;
} else {
return LockHeldState::NotHeldByThread;
}
}
type ExclLock = MutexGuard<'a, T>;
#[inline]
fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<T> { self.lock().unwrap() }
fn unsafe_well_ordered_double_lock_self(&'a self) -> MutexGuard<T> {
self.lock().unwrap()
}
}

pub struct RwLock<T: ?Sized> {
inner: RefCell<T>
inner: RefCell<T>,
}

pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
Expand Down Expand Up @@ -103,20 +108,25 @@ impl<T> RwLock<T> {
pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
match self.inner.try_borrow_mut() {
Ok(lock) => Ok(RwLockWriteGuard { lock }),
Err(_) => Err(())
Err(_) => Err(()),
}
}
}

impl<'a, T: 'a> LockTestExt<'a> for RwLock<T> {
#[inline]
fn held_by_thread(&self) -> LockHeldState {
if self.inner.try_borrow_mut().is_err() { return LockHeldState::HeldByThread; }
else { return LockHeldState::NotHeldByThread; }
if self.inner.try_borrow_mut().is_err() {
return LockHeldState::HeldByThread;
} else {
return LockHeldState::NotHeldByThread;
}
}
type ExclLock = RwLockWriteGuard<'a, T>;
#[inline]
fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<T> { self.write().unwrap() }
fn unsafe_well_ordered_double_lock_self(&'a self) -> RwLockWriteGuard<T> {
self.write().unwrap()
}
}

pub type FairRwLock<T> = RwLock<T>;
2 changes: 1 addition & 1 deletion lightning/src/sync/test_lockorder_checks.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::sync::debug_sync::{RwLock, Mutex};
use crate::sync::debug_sync::{Mutex, RwLock};

use super::{LockHeldState, LockTestExt};

Expand Down
5 changes: 0 additions & 5 deletions rustfmt_excluded_files
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,6 @@
./lightning/src/routing/scoring.rs
./lightning/src/routing/test_utils.rs
./lightning/src/routing/utxo.rs
./lightning/src/sync/debug_sync.rs
./lightning/src/sync/fairrwlock.rs
./lightning/src/sync/mod.rs
./lightning/src/sync/nostd_sync.rs
./lightning/src/sync/test_lockorder_checks.rs
./lightning/src/util/atomic_counter.rs
./lightning/src/util/base32.rs
./lightning/src/util/byte_utils.rs
Expand Down

0 comments on commit 815d255

Please sign in to comment.