Skip to content

Commit 0cb1a8e

Browse files
hoshinolinajannau
authored andcommitted
rust: kernel: lock: Add Lock::pin_init()
This allows initializing a lock using pin_init!(), instead of requiring the inner data to be passed through the stack. Signed-off-by: Asahi Lina <lina@asahilina.net>
1 parent fcb2bf6 commit 0cb1a8e

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

rust/kernel/sync/lock.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use super::LockClassKey;
99
use crate::{
1010
str::{CStr, CStrExt as _},
11+
try_pin_init,
1112
types::{NotThreadSafe, Opaque, ScopeGuard},
1213
};
1314
use core::{cell::UnsafeCell, marker::PhantomPinned, pin::Pin};
@@ -143,6 +144,31 @@ impl<T, B: Backend> Lock<T, B> {
143144
}),
144145
})
145146
}
147+
148+
/// Constructs a new lock initialiser taking an initialiser.
149+
pub fn pin_init<E>(
150+
t: impl PinInit<T, E>,
151+
name: &'static CStr,
152+
key: &'static LockClassKey,
153+
) -> impl PinInit<Self, E>
154+
where
155+
E: core::convert::From<core::convert::Infallible>,
156+
{
157+
try_pin_init!(Self {
158+
// SAFETY: We are just forwarding the initialization across a
159+
// cast away from UnsafeCell, so the pin_init_from_closure and
160+
// __pinned_init() requirements are in sync.
161+
data <- unsafe { pin_init::pin_init_from_closure(move |slot: *mut UnsafeCell<T>| {
162+
t.__pinned_init(slot as *mut T)
163+
})},
164+
_pin: PhantomPinned,
165+
// SAFETY: `slot` is valid while the closure is called and both `name` and `key` have
166+
// static lifetimes so they live indefinitely.
167+
state <- Opaque::ffi_init(|slot| unsafe {
168+
B::init(slot, name.as_char_ptr(), key.as_ptr())
169+
}),
170+
}? E)
171+
}
146172
}
147173

148174
impl<B: Backend> Lock<(), B> {

rust/kernel/sync/lock/mutex.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,19 @@ macro_rules! new_mutex {
1717
}
1818
pub use new_mutex;
1919

20+
/// Creates a [`Mutex`] initialiser with the given name and a newly-created lock class,
21+
/// given an initialiser for the inner type.
22+
///
23+
/// It uses the name if one is given, otherwise it generates one based on the file name and line
24+
/// number.
25+
#[macro_export]
26+
macro_rules! new_mutex_pinned {
27+
($inner:expr $(, $name:literal)? $(,)?) => {
28+
$crate::sync::Mutex::pin_init(
29+
$inner, $crate::optional_name!($($name)?), $crate::static_lock_class!())
30+
};
31+
}
32+
2033
/// A mutual exclusion primitive.
2134
///
2235
/// Exposes the kernel's [`struct mutex`]. When multiple threads attempt to lock the same mutex,

0 commit comments

Comments
 (0)