Skip to main content

wgpu_core/lock/
ranked.rs

1//! Lock types that enforce well-ranked lock acquisition order.
2//!
3//! This module's [`Mutex`] and [`RwLock` types are instrumented to check that
4//! `wgpu-core` acquires locks according to their rank, to prevent deadlocks. To
5//! use it, put `--cfg wgpu_validate_locks` in `RUSTFLAGS`.
6//!
7//! The [`LockRank`] constants in the [`lock::rank`] module describe edges in a
8//! directed graph of lock acquisitions: each lock's rank says, if this is the most
9//! recently acquired lock that you are still holding, then these are the locks you
10//! are allowed to acquire next.
11//!
12//! As long as this graph doesn't have cycles, any number of threads can acquire
13//! locks along paths through the graph without deadlock:
14//!
15//! - Assume that if a thread is holding a lock, then it will either release it,
16//!   or block trying to acquire another one. No thread just sits on its locks
17//!   forever for unrelated reasons. If it did, then that would be a source of
18//!   deadlock "outside the system" that we can't do anything about.
19//!
20//! - This module asserts that threads acquire and release locks in a stack-like
21//!   order: a lock is dropped only when it is the *most recently acquired* lock
22//!   *still held* - call this the "youngest" lock. This stack-like ordering
23//!   isn't a Rust requirement; Rust lets you drop guards in any order you like.
24//!   This is a restriction we impose.
25//!
26//! - Consider the directed graph whose nodes are locks, and whose edges go from
27//!   each lock to its permitted followers, the locks in its [`LockRank::followers`]
28//!   set. The definition of the [`lock::rank`] module's [`LockRank`] constants
29//!   ensures that this graph has no cycles, including trivial cycles from a node to
30//!   itself.
31//!
32//! - This module then asserts that each thread attempts to acquire a lock only if
33//!   it is among its youngest lock's permitted followers. Thus, as a thread
34//!   acquires locks, it must be traversing a path through the graph along its
35//!   edges.
36//!
37//! - Because there are no cycles in the graph, whenever one thread is blocked
38//!   waiting to acquire a lock, that lock must be held by a different thread: if
39//!   you were allowed to acquire a lock you already hold, that would be a cycle in
40//!   the graph.
41//!
42//! - Furthermore, because the graph has no cycles, as we work our way from each
43//!   thread to the thread it is blocked waiting for, we must eventually reach an
44//!   end point: there must be some thread that is able to acquire its next lock, or
45//!   that is about to release a lock.
46//!
47//! Thus, the system as a whole is always able to make progress: it is free of
48//! deadlocks.
49//!
50//! Note that this validation only monitors each thread's behavior in isolation:
51//! there's only thread-local state, nothing communicated between threads. So we
52//! don't detect deadlocks, per se, only the potential to cause deadlocks. This
53//! means that the validation is conservative, but more reproducible, since it's not
54//! dependent on any particular interleaving of execution.
55//!
56//! [`lock::rank`]: crate::lock::rank
57
58use core::{cell::Cell, fmt, ops, panic::Location};
59
60use super::rank::LockRank;
61
62pub use LockState as RankData;
63
64/// A `Mutex` instrumented for deadlock prevention.
65///
66/// This is just a wrapper around a [`wgpu_sync::Mutex`], along with
67/// its rank in the `wgpu_core` lock ordering.
68///
69/// For details, see [the module documentation][self].
70pub struct Mutex<T> {
71    inner: wgpu_sync::Mutex<T>,
72    rank: LockRank,
73}
74
75/// A guard produced by locking [`Mutex`].
76///
77/// This is just a wrapper around a [`wgpu_sync::MutexGuard`], along
78/// with the state needed to track lock acquisition.
79///
80/// For details, see [the module documentation][self].
81pub struct MutexGuard<'a, T> {
82    inner: wgpu_sync::MutexGuard<'a, T>,
83    #[cfg_attr(not(miri), expect(unused))] // but `Drop` has important side effects
84    saved: LockStateGuard,
85}
86
87std::thread_local! {
88    static LOCK_STATE: Cell<LockState> = const { Cell::new(LockState::INITIAL) };
89}
90
91/// Per-thread state for the deadlock checker.
92#[derive(Debug, Copy, Clone)]
93pub struct LockState {
94    /// The last lock we acquired, and where.
95    last_acquired: Option<(LockRank, &'static Location<'static>)>,
96
97    /// The number of locks currently held.
98    ///
99    /// This is used to enforce stack-like lock acquisition and release.
100    depth: u32,
101}
102
103impl LockState {
104    const INITIAL: LockState = LockState {
105        last_acquired: None,
106        depth: 0,
107    };
108}
109
110/// A container that restores a [`LockState`] when dropped.
111///
112/// This type serves two purposes:
113///
114/// - Operations would like to be able to destructure lock guards and
115///   reassemble their pieces into new guards, but if the guard type
116///   itself implements `Drop`, we can't destructure it without unsafe
117///   code or pointless `Option`s whose state is almost always statically
118///   known.
119///
120/// - We can just implement `Drop` for this type once, and then use it in lock
121///   guards, rather than implementing `Drop` separately for each guard type.
122struct LockStateGuard(LockState);
123
124impl Drop for LockStateGuard {
125    fn drop(&mut self) {
126        release(self.0)
127    }
128}
129
130/// Check and record the acquisition of a lock with `new_rank`.
131///
132/// Check that acquiring a lock with `new_rank` is permitted at this point, and
133/// update the per-thread state accordingly.
134///
135/// Return the `LockState` that must be restored when this thread is released.
136fn acquire(new_rank: LockRank, location: &'static Location<'static>) -> LockState {
137    let state = LOCK_STATE.get();
138    // Initially, it's fine to acquire any lock. So we only
139    // need to check when `last_acquired` is `Some`.
140    if let Some((ref last_rank, ref last_location)) = state.last_acquired {
141        assert!(
142            last_rank.followers.contains(new_rank.bit),
143            "Attempt to acquire nested mutexes in wrong order:\n\
144             last locked {:<35} at {}\n\
145             now locking {:<35} at {}\n\
146             Locking {} after locking {} is not permitted.",
147            last_rank.bit.member_name(),
148            last_location,
149            new_rank.bit.member_name(),
150            location,
151            new_rank.bit.member_name(),
152            last_rank.bit.member_name(),
153        );
154    }
155    LOCK_STATE.set(LockState {
156        last_acquired: Some((new_rank, location)),
157        depth: state.depth + 1,
158    });
159    state
160}
161
162/// Record the release of a lock whose saved state was `saved`.
163///
164/// Check that locks are being acquired in stacking order, and update the
165/// per-thread state accordingly.
166fn release(saved: LockState) {
167    let saved_info = saved.last_acquired;
168
169    let prior = LOCK_STATE.replace(saved);
170
171    let (prior_rank, prior_location) = prior
172        .last_acquired
173        .expect("Releasing a lock, but no acquisition recorded");
174
175    // Although Rust allows mutex guards to be dropped in any
176    // order, this analysis requires that locks be acquired and
177    // released in stack order: the next lock to be released must be
178    // the most recently acquired lock still held.
179
180    match (saved.depth, saved_info) {
181        (saved_depth @ 0, None) => {
182            assert_eq!(
183                prior.depth,
184                saved_depth + 1,
185                "Lock not released in stacking order\n\
186                released {:<35} locked at {:?}\n\
187                when not expecting any locks to be held\n",
188                prior_rank.bit.member_name(),
189                prior_location,
190            );
191        }
192        (0, Some(_)) => {
193            panic!("Found previous lock acquisition information, but saved.depth = 0");
194        }
195        (saved_depth, Some((saved_rank, saved_location))) => {
196            assert_eq!(
197                prior.depth,
198                saved_depth + 1,
199                "Lock not released in stacking order\n\
200                expecting release of {:<35} locked at {:?}\n\
201                but instead released {:<35} locked at {:?}\n",
202                saved_rank.bit.member_name(),
203                saved_location,
204                prior_rank.bit.member_name(),
205                prior_location,
206            );
207        }
208        (saved_depth, None) => {
209            panic!(
210                "Found saved.depth = {saved_depth}, but no previous lock acquisition information"
211            );
212        }
213    }
214}
215
216impl<T> Mutex<T> {
217    pub fn new(rank: LockRank, value: T) -> Mutex<T> {
218        Mutex {
219            inner: wgpu_sync::Mutex::new(value),
220            rank,
221        }
222    }
223
224    #[track_caller]
225    pub fn lock(&self) -> MutexGuard<'_, T> {
226        let saved = acquire(self.rank, Location::caller());
227        MutexGuard {
228            inner: self.inner.lock(),
229            saved: LockStateGuard(saved),
230        }
231    }
232
233    pub fn into_inner(self) -> T {
234        self.inner.into_inner()
235    }
236}
237
238impl<'a, T> ops::Deref for MutexGuard<'a, T> {
239    type Target = T;
240
241    fn deref(&self) -> &Self::Target {
242        self.inner.deref()
243    }
244}
245
246impl<'a, T> ops::DerefMut for MutexGuard<'a, T> {
247    fn deref_mut(&mut self) -> &mut Self::Target {
248        self.inner.deref_mut()
249    }
250}
251
252impl<T: fmt::Debug> fmt::Debug for Mutex<T> {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        self.inner.fmt(f)
255    }
256}
257
258/// An `RwLock` instrumented for deadlock prevention.
259///
260/// This is just a wrapper around a [`wgpu_sync::RwLock`], along with
261/// its rank in the `wgpu_core` lock ordering.
262///
263/// For details, see [the module documentation][self].
264pub struct RwLock<T> {
265    inner: wgpu_sync::RwLock<T>,
266    rank: LockRank,
267}
268
269/// A read guard produced by locking [`RwLock`] for reading.
270///
271/// This is just a wrapper around a [`wgpu_sync::RwLockReadGuard`], along with
272/// the state needed to track lock acquisition.
273///
274/// For details, see [the module documentation][self].
275pub struct RwLockReadGuard<'a, T> {
276    inner: wgpu_sync::RwLockReadGuard<'a, T>,
277    saved: LockStateGuard,
278}
279
280/// A write guard produced by locking [`RwLock`] for writing.
281///
282/// This is just a wrapper around a [`wgpu_sync::RwLockWriteGuard`], along
283/// with the state needed to track lock acquisition.
284///
285/// For details, see [the module documentation][self].
286pub struct RwLockWriteGuard<'a, T> {
287    inner: wgpu_sync::RwLockWriteGuard<'a, T>,
288    #[cfg_attr(not(miri), expect(unused))] // but `Drop` has important side effects
289    saved: LockStateGuard,
290}
291
292impl<T> RwLock<T> {
293    pub fn new(rank: LockRank, value: T) -> RwLock<T> {
294        RwLock {
295            inner: wgpu_sync::RwLock::new(value),
296            rank,
297        }
298    }
299
300    #[track_caller]
301    pub fn read(&self) -> RwLockReadGuard<'_, T> {
302        let saved = acquire(self.rank, Location::caller());
303        RwLockReadGuard {
304            inner: self.inner.read(),
305            saved: LockStateGuard(saved),
306        }
307    }
308
309    #[track_caller]
310    pub fn write(&self) -> RwLockWriteGuard<'_, T> {
311        let saved = acquire(self.rank, Location::caller());
312        RwLockWriteGuard {
313            inner: self.inner.write(),
314            saved: LockStateGuard(saved),
315        }
316    }
317
318    /// Force an read-unlock operation on this lock.
319    ///
320    /// Safety:
321    /// - A read lock must be held which is not held by a guard.
322    pub unsafe fn force_unlock_read(&self, data: RankData) {
323        release(data);
324        unsafe { self.inner.force_unlock_read() };
325    }
326
327    /// Returns a reference to the underlying [`wgpu_sync::RwLock`].
328    ///
329    /// Marked as unsafe because it allows bypassing the rank system,
330    /// defeating the purpose of this type.
331    pub unsafe fn underlying(&self) -> &wgpu_sync::RwLock<T> {
332        &self.inner
333    }
334}
335
336impl<'a, T> RwLockReadGuard<'a, T> {
337    // Forget the read guard, leaving the lock in a locked state with no guard.
338    //
339    // Equivalent to std::mem::forget, but preserves the information about the lock
340    // rank.
341    pub fn forget(this: Self) -> RankData {
342        // Skip `Drop` for both the actual lock guard (`this.inner`) and the
343        // rank-checking state guard (`this.saved`)
344        let saved = core::mem::ManuallyDrop::new(this.saved);
345        core::mem::forget(this.inner);
346
347        // Return the `RankData` so the caller can pass it to `force_unlock_read`.
348        saved.0
349    }
350}
351
352impl<T: fmt::Debug> fmt::Debug for RwLock<T> {
353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354        self.inner.fmt(f)
355    }
356}
357
358impl<'a, T> ops::Deref for RwLockReadGuard<'a, T> {
359    type Target = T;
360
361    fn deref(&self) -> &Self::Target {
362        self.inner.deref()
363    }
364}
365
366impl<'a, T> ops::Deref for RwLockWriteGuard<'a, T> {
367    type Target = T;
368
369    fn deref(&self) -> &Self::Target {
370        self.inner.deref()
371    }
372}
373
374impl<'a, T> ops::DerefMut for RwLockWriteGuard<'a, T> {
375    fn deref_mut(&mut self) -> &mut Self::Target {
376        self.inner.deref_mut()
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use super::Mutex;
383    use crate::lock::rank;
384
385    /// Locks can be acquired in the order indicated by their ranks.
386    #[test]
387    fn permitted() {
388        let lock1 = Mutex::new(rank::PAWN, ());
389        let lock2 = Mutex::new(rank::ROOK, ());
390
391        let _guard1 = lock1.lock();
392        let _guard2 = lock2.lock();
393    }
394
395    /// Locks can only be acquired in the order indicated by their ranks.
396    #[test]
397    #[should_panic(expected = "Locking pawn after locking rook")]
398    fn forbidden_unrelated() {
399        let lock1 = Mutex::new(rank::ROOK, ());
400        let lock2 = Mutex::new(rank::PAWN, ());
401
402        let _guard1 = lock1.lock();
403        let _guard2 = lock2.lock();
404    }
405
406    /// Lock acquisitions can't skip ranks.
407    ///
408    /// These two locks *could* be acquired in this order, but only if other locks
409    /// are acquired in between them. Skipping ranks isn't allowed.
410    #[test]
411    #[should_panic(expected = "Locking knight after locking pawn")]
412    fn forbidden_skip() {
413        let lock1 = Mutex::new(rank::PAWN, ());
414        let lock2 = Mutex::new(rank::KNIGHT, ());
415
416        let _guard1 = lock1.lock();
417        let _guard2 = lock2.lock();
418    }
419
420    /// Locks can be acquired and released in a stack-like order.
421    #[test]
422    fn stack_like() {
423        let lock1 = Mutex::new(rank::PAWN, ());
424        let lock2 = Mutex::new(rank::ROOK, ());
425        let lock3 = Mutex::new(rank::BISHOP, ());
426
427        let guard1 = lock1.lock();
428        let guard2 = lock2.lock();
429        drop(guard2);
430
431        let guard3 = lock3.lock();
432        drop(guard3);
433        drop(guard1);
434    }
435
436    /// Locks can only be acquired and released in a stack-like order.
437    #[test]
438    #[should_panic(expected = "Lock not released in stacking order")]
439    fn non_stack_like() {
440        let lock1 = Mutex::new(rank::PAWN, ());
441        let lock2 = Mutex::new(rank::ROOK, ());
442
443        let guard1 = lock1.lock();
444        let guard2 = lock2.lock();
445
446        // Avoid a double panic from dropping this while unwinding due to the panic
447        // we're testing for.
448        core::mem::forget(guard2);
449
450        drop(guard1);
451    }
452}