Skip to content

Commit 39a6a12

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 990c811 commit 39a6a12

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

rust/kernel/sync/lock.rs

Lines changed: 27 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,
11+
try_pin_init,
1112
types::{NotThreadSafe, Opaque, ScopeGuard},
1213
};
1314
use core::{cell::UnsafeCell, marker::PhantomPinned, pin::Pin};
@@ -115,6 +116,7 @@ pub struct Lock<T: ?Sized, B: Backend> {
115116
_pin: PhantomPinned,
116117

117118
/// The data protected by the lock.
119+
#[pin]
118120
pub(crate) data: UnsafeCell<T>,
119121
}
120122

@@ -138,6 +140,31 @@ impl<T, B: Backend> Lock<T, B> {
138140
}),
139141
})
140142
}
143+
144+
/// Constructs a new lock initialiser taking an initialiser.
145+
pub fn pin_init<E>(
146+
t: impl PinInit<T, E>,
147+
name: &'static CStr,
148+
key: &'static LockClassKey,
149+
) -> impl PinInit<Self, E>
150+
where
151+
E: core::convert::From<core::convert::Infallible>,
152+
{
153+
try_pin_init!(Self {
154+
// SAFETY: We are just forwarding the initialization across a
155+
// cast away from UnsafeCell, so the pin_init_from_closure and
156+
// __pinned_init() requirements are in sync.
157+
data <- unsafe { pin_init::pin_init_from_closure(move |slot: *mut UnsafeCell<T>| {
158+
t.__pinned_init(slot as *mut T)
159+
})},
160+
_pin: PhantomPinned,
161+
// SAFETY: `slot` is valid while the closure is called and both `name` and `key` have
162+
// static lifetimes so they live indefinitely.
163+
state <- Opaque::ffi_init(|slot| unsafe {
164+
B::init(slot, name.as_char_ptr(), key.as_ptr())
165+
}),
166+
}? E)
167+
}
141168
}
142169

143170
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)