Currently, Rust's RCU abstractions only provide a full synchronize_rcu(). Many users, however, only want to wait for one grace period if a specific grace period has not already passed.
Add RcuState, an object identifying a grace period, and implement a method to conditionally synchronize for that grace period. Signed-off-by: Philipp Stanner <[email protected]> Suggested-by: Gary Guo <[email protected]> --- rust/helpers/rcu.c | 5 +++++ rust/kernel/sync/rcu.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/rust/helpers/rcu.c b/rust/helpers/rcu.c index 481274c05857..570ee76b7247 100644 --- a/rust/helpers/rcu.c +++ b/rust/helpers/rcu.c @@ -11,3 +11,8 @@ __rust_helper void rust_helper_rcu_read_unlock(void) { rcu_read_unlock(); } + +__rust_helper void rust_helper_cond_synchronize_rcu(unsigned long cookie) +{ + cond_synchronize_rcu(cookie); +} diff --git a/rust/kernel/sync/rcu.rs b/rust/kernel/sync/rcu.rs index 0daa1ac87d81..7cb5a7d31e57 100644 --- a/rust/kernel/sync/rcu.rs +++ b/rust/kernel/sync/rcu.rs @@ -86,3 +86,38 @@ pub fn synchronize_rcu() { // SAFETY: `synchronize_rcu()` is always safe to be called from process context. unsafe { bindings::synchronize_rcu() }; } + +/// An RCU grace period snapshot. +/// +/// Useful for waiting for said grace period if necessary. If you just drop this +/// object, nothing happens. +#[derive(Copy, Clone)] +pub struct RcuState(usize); + +impl RcuState { + /// Create a new RcuState. It stores an identifier of the current grace + /// period so that you can later water on it. + pub fn new() -> Self { + // SAFETY: `get_state_synchronize_rcu()` is always safe to be called. + let cookie: usize = unsafe { bindings::get_state_synchronize_rcu() }; + + Self(cookie) + } + + /// Make sure that a full RCU grace period has passed since this RcuState + /// was created. + /// + /// Executes a [`synchronize_rcu()`] if that's not the case. Thus, you must + /// not call this in atomic context. + pub fn cond_synchronize(self) { + // SAFETY: This is the right cookie. The function runs in process context. + unsafe { bindings::cond_synchronize_rcu(self.0) }; + } +} + +impl Default for RcuState { + #[inline] + fn default() -> Self { + Self::new() + } +} -- 2.56.0
