Skip to contentSkip to conversation

rust: sync: Introduce LazyInit

PATCH In review Lyude Paul 2 participants 6 messages May 29 – Jun 1

Subsystems (3)
lore
Share & tools
lore

Lyude Paul

author reviewer
#0 lore raw

v2 cover rust: sync: Introduce LazyInit

While trying to write up some SGTable bindings for the GEM shmem helpers, I discovered that SetOnce is actually quite difficult to make use of in a number of situations.

For one: there is (upstream) currently no way to use it with fallible initializers. Even with some of the work being done to add support for this from Gary Guo and Alvin Sun:

https://lore.kernel.org/rust-for-linux/[email protected]/

We're still left with the issue that if two callers race on trying to call init(), there's no actual way for either of them to block until the thread they raced with is done initializing the contents of the container.

LazyInit is my proposed solution to this issue. It provides a container which protects the initialization of its contents, without protecting access to its contents (implying of course, that its contents have to provide their own thread synchronization).

Lyude Paul (2):
rust: sync: lock: Add Lock::get_mut_pinned()
rust: sync: Introduce LazyInit

 rust/kernel/sync.rs           |   2 +
 rust/kernel/sync/lazy_init.rs | 352 ++++++++++++++++++++++++++++++++++
 rust/kernel/sync/lock.rs      |  11 ++
 3 files changed, 365 insertions(+)
 create mode 100644 rust/kernel/sync/lazy_init.rs

base-commit: 0e42ec83d46ab8877d38d37493328ed7d1a24de8

Signature · 1 line
2.54.0
author reviewer
#1 lore raw

PATCH v2 1/2 rust: sync: lock: Add Lock::get_mut_pinned()

These two functions are inspired by the Rust stdlib equivalent:

https://doc.rust-lang.org/std/sync/struct.Mutex.html#method.get_mut()

The idea here is very simple - if the user has access to a Pin<&mut Mutex<…>>, we can guarantee that no one else can look at the data protected by the lock. Thus in such situations, locking the mutex isn't necessary to access its contents. This can be useful in situations like Drop implementations, where we may want to access the contents of a Mutex within a struct before dropping it.

So to do this, we add get_mut_pinned() to Lock - which provides a function to access the inner contents of a Mutex provided a Pin<&mut …>.

---
 rust/kernel/sync/lock.rs | 11 +++++++++++
 1 file changed, 11 insertions(+)
rust/kernel/sync/lock.rs +11 -0
index 10b6b5e9b024f..5ca36baed34f5 100644
@@ -190,6 +190,17 @@ pub fn try_lock(&self) -> Option<Guard<'_, T, B>> {
         // that `init` was called.
         unsafe { B::try_lock(self.state.get()).map(|state| Guard::new(self, state)) }
     }
+
+    /// Returns a pinned mutable reference to the underlying data.
+    ///
+    /// Because this borrows the lock mutably, no actual locking needs to take place - as the
+    /// mutable borrow statically guarantees no new locks can be acquired while this reference
+    /// exists.
+    #[inline(always)]
+    pub fn get_mut_pinned(self: Pin<&mut Self>) -> Pin<&mut T> {
+        // SAFETY: We return a pinned T, ensuring we don't move T.
+        unsafe { self.map_unchecked_mut(|data| data.data.get_mut()) }
+    }
 }
 
 /// A lock guard.
Signature · 1 line
2.54.0
maintainer Reviewed-by on v2 1/2
#2 lore raw

Re: [PATCH v2 1/2] rust: sync: lock: Add Lock::get_mut_pinned()

Quoted 11 lines · Lyude Paul

These two functions are inspired by the Rust stdlib equivalent:

https://doc.rust-lang.org/std/sync/struct.Mutex.html#method.get_mut()

The idea here is very simple - if the user has access to a Pin<&mut Mutex<…>>, we can guarantee that no one else can look at the data protected by the lock. Thus in such situations, locking the mutex isn't necessary to access its contents. This can be useful in situations like Drop implementations, where we may want to access the contents of a Mutex within a struct before dropping it.

Quoted 4 lines

So to do this, we add get_mut_pinned() to Lock - which provides a function to access the inner contents of a Mutex provided a Pin<&mut …>.

Quoted 8 lines
 rust/kernel/sync/lock.rs | 11 +++++++++++
 1 file changed, 11 insertions(+)
rust/kernel/sync/lock.rs +0 -0
index 10b6b5e9b024f..5ca36baed34f5 100644

rust/kernel/sync/lock.rs pub fn try_lock(&self) -> Option<Guard<'_, T, B>> { · line 199

Quoted 10 lines
rust/kernel/sync/lock.rs +7 -0
@@ -190,6 +190,17 @@ pub fn try_lock(&self) -> Option<Guard<'_, T, B>> {
         // that `init` was called.
         unsafe { B::try_lock(self.state.get()).map(|state| Guard::new(self, state)) }
     }
+
+    /// Returns a pinned mutable reference to the underlying data.
+    ///
+    /// Because this borrows the lock mutably, no actual locking needs to take place - as the
+    /// mutable borrow statically guarantees no new locks can be acquired while this reference
+    /// exists.
+    #[inline(always)]

Normal #[inline] is sufficient.

Quoted 10 lines
rust/kernel/sync/lock.rs +4 -0
+    pub fn get_mut_pinned(self: Pin<&mut Self>) -> Pin<&mut T> {
+        // SAFETY: We return a pinned T, ensuring we don't move T.
+        unsafe { self.map_unchecked_mut(|data| data.data.get_mut()) }
+    }
 }
 
 /// A lock guard.
Signature · 1 line
2.54.0
author reviewer
#3 lore raw

PATCH v2 2/2 rust: sync: Introduce LazyInit

In reply to Lyude Paul

SetOnce is nice, but it does have one problem - you can't use it with fallible initializers. While we will be adding support for doing that with SetOnce, this leads into another problem: There's no way for racing callers to actually block on the initialization of SetOnce, which makes it a difficult type to use safely for situations where we want to initialize data fallibly once, and then provide access to it to multiple users at once until drop.

So to solve this, introduce a new type: LazyInit. LazyInit is like SetOnce with a couple of important differences:

* It can't be used in const context
* It can handle in-place fallible initializers.
* It uses a Mutex for synchronization instead of an atomic, allowing callers to block on initialization.
* It requires its contents already be Send + Sync, since the Mutex protects initializing data and not the data itself.

---
V2:
* Get rid of references to populate() in safety comments
* Drop unused import in kunit tests
* s/r @ _/r/ in unit tests
* Fix many safety comments, a few of them did not get updated by me by mistake before submitting the first version of this series.
* Pin-project harder, since the last time I looked at this I've got a better understanding of pin projection - so let's take advantage of that to cut down on some unsafe blocks.
* Improve root doc comment a little bit
* Improve INVARIANT comments

 rust/kernel/sync.rs           |   2 +
 rust/kernel/sync/lazy_init.rs | 352 ++++++++++++++++++++++++++++++++++
 2 files changed, 354 insertions(+)
 create mode 100644 rust/kernel/sync/lazy_init.rs
rust/kernel/sync.rs +2 -0
index 993dbf2caa0e3..d18c26c56c4d2 100644
@@ -15,6 +15,7 @@
 pub mod barrier;
 pub mod completion;
 mod condvar;
+mod lazy_init;
 pub mod lock;
 mod locked_by;
 pub mod poll;
@@ -25,6 +26,7 @@
 pub use arc::{Arc, ArcBorrow, UniqueArc};
 pub use completion::Completion;
 pub use condvar::{new_condvar, CondVar, CondVarTimeoutResult};
+pub use lazy_init::*;
 pub use lock::global::{global_lock, GlobalGuard, GlobalLock, GlobalLockBackend, GlobalLockedBy};
 pub use lock::mutex::{new_mutex, Mutex, MutexGuard};
 pub use lock::spinlock::{new_spinlock, SpinLock, SpinLockGuard};
rust/kernel/sync/lazy_init.rs new file +352 -0

352 lines not on this page · raw message

Signature · 1 line
2.54.0
maintainer
#4 lore raw
Quoted 27 lines · Lyude Paul

SetOnce is nice, but it does have one problem - you can't use it with fallible initializers. While we will be adding support for doing that with SetOnce, this leads into another problem: There's no way for racing callers to actually block on the initialization of SetOnce, which makes it a difficult type to use safely for situations where we want to initialize data fallibly once, and then provide access to it to multiple users at once until drop.

So to solve this, introduce a new type: LazyInit. LazyInit is like SetOnce with a couple of important differences:

* It can't be used in const context
* It can handle in-place fallible initializers.
* It uses a Mutex for synchronization instead of an atomic, allowing callers to block on initialization.
* It requires its contents already be Send + Sync, since the Mutex protects initializing data and not the data itself.

rust/kernel/sync/lazy_init.rs new file +7 -0
+    /// Retrieve the contents of `inner.data` and extend their lifetime.
+    ///
+    /// # Safety
+    ///
+    /// The caller guarantees that `self.inner.data` has been previously initialized.
+    #[inline(always)]
+    unsafe fn data<'a>(&'a self, inner: &MutexGuard<'_, Inner<T>>) -> &'a T {

rust/kernel/sync/lazy_init.rs line 180

Quoted 10 lines
rust/kernel/sync/lazy_init.rs new file +10 -0
+        // SAFETY:
+        // - Our safety contract guarantees `inner.data` is initialized.
+        // - `T` is `Send` + `Sync`, and thus does not need the `Mutex` for synchronization, making
+        //   it safe to hold onto outside of the lock.
+        // - We're guaranteed via `Inner`'s type invariants that so long as immutable references to
+        //   self exist, `data` cannot be uninitialized - ensuring it lives throughout the lifetime
+        //   of A.
+        // - We're guaranteed the container of `T` will not be written to via `Inner`s type
+        //   invariants until `Drop`, ensuring it remains populated for the lifetime of 'a.
+        unsafe { mem::transmute::<&_, &'a _>(inner.data.assume_init_ref()) }

I'm not a big fan of using these kinds of tricks to access the contents of a mutex after unlocking it. Could we instead use a struct like this:

struct LazyInit<T> {
    data: UnsafeCell<MaybeUninit<T>>,
    set: AtomicBool,
    lock: Mutex<()>,
}

or even:

struct LazyInit<T> {
    data: SetOnce<T>,
    lock: Mutex<()>,
}

I think this logic will be simpler for everyone.

By the way, another option is to use a similar strategy to
https://lore.kernel.org/rust-for-linux/[email protected]/
where you just use SetOnce and protect calls to populate by another mutex in the structure. Then you don't need a separate LazyInit.

Alice

author reviewer
#5 lore raw
Quoted 18 lines · Alice Ryhl

I'm not a big fan of using these kinds of tricks to access the contents
of a mutex after unlocking it. Could we instead use a struct like this:

struct LazyInit<T> {
    data: UnsafeCell<MaybeUninit<T>>,
    set: AtomicBool,
    lock: Mutex<()>,
}

or even:

struct LazyInit<T> {
    data: SetOnce<T>,
    lock: Mutex<()>,
}

Quoted 6 lines

I think this logic will be simpler for everyone.

By the way, another option is to use a similar strategy to
https://lore.kernel.org/rust-for-linux/[email protected]/
where you just use SetOnce and protect calls to populate by another mutex in the structure. Then you don't need a separate LazyInit.

ooo - yeah, that definitely works for me and would be preferable. I still will like to make one change to SetOnce that I think isn't too
crazy: writing up a reset() function for SetOnce that works through a &mut like what I had here for LazyInit, since that would be quite helpful to have in the gem shmem free_callback() function.

Quoted 2 lines

Alice