Refactor debug sync methods into helper functions
[rust-lightning] / lightning / src / debug_sync.rs
1 pub use ::alloc::sync::Arc;
2 use core::ops::{Deref, DerefMut};
3 use core::time::Duration;
4
5 use std::collections::HashSet;
6 use std::cell::RefCell;
7
8 use std::sync::atomic::{AtomicUsize, Ordering};
9
10 use std::sync::Mutex as StdMutex;
11 use std::sync::MutexGuard as StdMutexGuard;
12 use std::sync::RwLock as StdRwLock;
13 use std::sync::RwLockReadGuard as StdRwLockReadGuard;
14 use std::sync::RwLockWriteGuard as StdRwLockWriteGuard;
15 use std::sync::Condvar as StdCondvar;
16
17 #[cfg(feature = "backtrace")]
18 use backtrace::Backtrace;
19
20 pub type LockResult<Guard> = Result<Guard, ()>;
21
22 pub struct Condvar {
23         inner: StdCondvar,
24 }
25
26 impl Condvar {
27         pub fn new() -> Condvar {
28                 Condvar { inner: StdCondvar::new() }
29         }
30
31         pub fn wait<'a, T>(&'a self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
32                 let mutex: &'a Mutex<T> = guard.mutex;
33                 self.inner.wait(guard.into_inner()).map(|lock| MutexGuard { mutex, lock }).map_err(|_| ())
34         }
35
36         #[allow(unused)]
37         pub fn wait_timeout<'a, T>(&'a self, guard: MutexGuard<'a, T>, dur: Duration) -> LockResult<(MutexGuard<'a, T>, ())> {
38                 let mutex = guard.mutex;
39                 self.inner.wait_timeout(guard.into_inner(), dur).map(|(lock, _)| (MutexGuard { mutex, lock }, ())).map_err(|_| ())
40         }
41
42         pub fn notify_all(&self) { self.inner.notify_all(); }
43 }
44
45 thread_local! {
46         /// We track the set of locks currently held by a reference to their `MutexMetadata`
47         static MUTEXES_HELD: RefCell<HashSet<Arc<MutexMetadata>>> = RefCell::new(HashSet::new());
48 }
49 static MUTEX_IDX: AtomicUsize = AtomicUsize::new(0);
50
51 /// Metadata about a single mutex, by id, the set of things locked-before it, and the backtrace of
52 /// when the Mutex itself was constructed.
53 struct MutexMetadata {
54         mutex_idx: u64,
55         locked_before: StdMutex<HashSet<Arc<MutexMetadata>>>,
56         #[cfg(feature = "backtrace")]
57         mutex_construction_bt: Backtrace,
58 }
59 impl PartialEq for MutexMetadata {
60         fn eq(&self, o: &MutexMetadata) -> bool { self.mutex_idx == o.mutex_idx }
61 }
62 impl Eq for MutexMetadata {}
63 impl std::hash::Hash for MutexMetadata {
64         fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) { hasher.write_u64(self.mutex_idx); }
65 }
66
67 impl MutexMetadata {
68         fn new() -> MutexMetadata {
69                 MutexMetadata {
70                         locked_before: StdMutex::new(HashSet::new()),
71                         mutex_idx: MUTEX_IDX.fetch_add(1, Ordering::Relaxed) as u64,
72                         #[cfg(feature = "backtrace")]
73                         mutex_construction_bt: Backtrace::new(),
74                 }
75         }
76
77         fn pre_lock(this: &Arc<MutexMetadata>) {
78                 MUTEXES_HELD.with(|held| {
79                         // For each mutex which is currently locked, check that no mutex's locked-before
80                         // set includes the mutex we're about to lock, which would imply a lockorder
81                         // inversion.
82                         for locked in held.borrow().iter() {
83                                 for locked_dep in locked.locked_before.lock().unwrap().iter() {
84                                         if *locked_dep == *this {
85                                                 #[cfg(feature = "backtrace")]
86                                                 panic!("Tried to violate existing lockorder.\nMutex that should be locked after the current lock was created at the following backtrace.\nNote that to get a backtrace for the lockorder violation, you should set RUST_BACKTRACE=1\n{:?}", locked.mutex_construction_bt);
87                                                 #[cfg(not(feature = "backtrace"))]
88                                                 panic!("Tried to violate existing lockorder. Build with the backtrace feature for more info.");
89                                         }
90                                 }
91                                 // Insert any already-held mutexes in our locked-before set.
92                                 this.locked_before.lock().unwrap().insert(Arc::clone(locked));
93                         }
94                         held.borrow_mut().insert(Arc::clone(this));
95                 });
96         }
97
98         fn try_locked(this: &Arc<MutexMetadata>) {
99                 MUTEXES_HELD.with(|held| {
100                         // Since a try-lock will simply fail if the lock is held already, we do not
101                         // consider try-locks to ever generate lockorder inversions. However, if a try-lock
102                         // succeeds, we do consider it to have created lockorder dependencies.
103                         for locked in held.borrow().iter() {
104                                 this.locked_before.lock().unwrap().insert(Arc::clone(locked));
105                         }
106                         held.borrow_mut().insert(Arc::clone(this));
107                 });
108         }
109 }
110
111 pub struct Mutex<T: Sized> {
112         inner: StdMutex<T>,
113         deps: Arc<MutexMetadata>,
114 }
115
116 #[must_use = "if unused the Mutex will immediately unlock"]
117 pub struct MutexGuard<'a, T: Sized + 'a> {
118         mutex: &'a Mutex<T>,
119         lock: StdMutexGuard<'a, T>,
120 }
121
122 impl<'a, T: Sized> MutexGuard<'a, T> {
123         fn into_inner(self) -> StdMutexGuard<'a, T> {
124                 // Somewhat unclear why we cannot move out of self.lock, but doing so gets E0509.
125                 unsafe {
126                         let v: StdMutexGuard<'a, T> = std::ptr::read(&self.lock);
127                         std::mem::forget(self);
128                         v
129                 }
130         }
131 }
132
133 impl<T: Sized> Drop for MutexGuard<'_, T> {
134         fn drop(&mut self) {
135                 MUTEXES_HELD.with(|held| {
136                         held.borrow_mut().remove(&self.mutex.deps);
137                 });
138         }
139 }
140
141 impl<T: Sized> Deref for MutexGuard<'_, T> {
142         type Target = T;
143
144         fn deref(&self) -> &T {
145                 &self.lock.deref()
146         }
147 }
148
149 impl<T: Sized> DerefMut for MutexGuard<'_, T> {
150         fn deref_mut(&mut self) -> &mut T {
151                 self.lock.deref_mut()
152         }
153 }
154
155 impl<T> Mutex<T> {
156         pub fn new(inner: T) -> Mutex<T> {
157                 Mutex { inner: StdMutex::new(inner), deps: Arc::new(MutexMetadata::new()) }
158         }
159
160         pub fn lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
161                 MutexMetadata::pre_lock(&self.deps);
162                 self.inner.lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ())
163         }
164
165         pub fn try_lock<'a>(&'a self) -> LockResult<MutexGuard<'a, T>> {
166                 let res = self.inner.try_lock().map(|lock| MutexGuard { mutex: self, lock }).map_err(|_| ());
167                 if res.is_ok() {
168                         MutexMetadata::try_locked(&self.deps);
169                 }
170                 res
171         }
172 }
173
174 pub struct RwLock<T: ?Sized> {
175         inner: StdRwLock<T>
176 }
177
178 pub struct RwLockReadGuard<'a, T: ?Sized + 'a> {
179         lock: StdRwLockReadGuard<'a, T>,
180 }
181
182 pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> {
183         lock: StdRwLockWriteGuard<'a, T>,
184 }
185
186 impl<T: ?Sized> Deref for RwLockReadGuard<'_, T> {
187         type Target = T;
188
189         fn deref(&self) -> &T {
190                 &self.lock.deref()
191         }
192 }
193
194 impl<T: ?Sized> Deref for RwLockWriteGuard<'_, T> {
195         type Target = T;
196
197         fn deref(&self) -> &T {
198                 &self.lock.deref()
199         }
200 }
201
202 impl<T: ?Sized> DerefMut for RwLockWriteGuard<'_, T> {
203         fn deref_mut(&mut self) -> &mut T {
204                 self.lock.deref_mut()
205         }
206 }
207
208 impl<T> RwLock<T> {
209         pub fn new(inner: T) -> RwLock<T> {
210                 RwLock { inner: StdRwLock::new(inner) }
211         }
212
213         pub fn read<'a>(&'a self) -> LockResult<RwLockReadGuard<'a, T>> {
214                 self.inner.read().map(|lock| RwLockReadGuard { lock }).map_err(|_| ())
215         }
216
217         pub fn write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
218                 self.inner.write().map(|lock| RwLockWriteGuard { lock }).map_err(|_| ())
219         }
220
221         pub fn try_write<'a>(&'a self) -> LockResult<RwLockWriteGuard<'a, T>> {
222                 self.inner.try_write().map(|lock| RwLockWriteGuard { lock }).map_err(|_| ())
223         }
224 }