Skip to content

Commit 9730145

Browse files
wedsonafDanilo Krummrich
authored andcommitted
rust: add Revocable type
Revocable allows access to objects to be safely revoked at run time. This is useful, for example, for resources allocated during device probe; when the device is removed, the driver should stop accessing the device resources even if another state is kept in memory due to existing references (i.e., device context data is ref-counted and has a non-zero refcount after removal of the device). Signed-off-by: Wedson Almeida Filho <[email protected]> Signed-off-by: Danilo Krummrich <[email protected]>
1 parent ec2e215 commit 9730145

File tree

2 files changed

+212
-0
lines changed

2 files changed

+212
-0
lines changed

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ pub mod page;
5454
pub mod prelude;
5555
pub mod print;
5656
pub mod rbtree;
57+
pub mod revocable;
5758
pub mod sizes;
5859
mod static_assert;
5960
#[doc(hidden)]

rust/kernel/revocable.rs

Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Revocable objects.
4+
//!
5+
//! The [`Revocable`] type wraps other types and allows access to them to be revoked. The existence
6+
//! of a [`RevocableGuard`] ensures that objects remain valid.
7+
8+
use crate::{
9+
bindings,
10+
init::{self},
11+
prelude::*,
12+
sync::rcu,
13+
};
14+
use core::{
15+
cell::UnsafeCell,
16+
marker::PhantomData,
17+
mem::MaybeUninit,
18+
ops::Deref,
19+
ptr::drop_in_place,
20+
sync::atomic::{AtomicBool, Ordering},
21+
};
22+
23+
/// An object that can become inaccessible at runtime.
24+
///
25+
/// Once access is revoked and all concurrent users complete (i.e., all existing instances of
26+
/// [`RevocableGuard`] are dropped), the wrapped object is also dropped.
27+
///
28+
/// # Examples
29+
///
30+
/// ```
31+
/// # use kernel::revocable::Revocable;
32+
///
33+
/// struct Example {
34+
/// a: u32,
35+
/// b: u32,
36+
/// }
37+
///
38+
/// fn add_two(v: &Revocable<Example>) -> Option<u32> {
39+
/// let guard = v.try_access()?;
40+
/// Some(guard.a + guard.b)
41+
/// }
42+
///
43+
/// let v = KBox::pin_init(Revocable::new(Example { a: 10, b: 20 }), GFP_KERNEL).unwrap();
44+
/// assert_eq!(add_two(&v), Some(30));
45+
/// v.revoke();
46+
/// assert_eq!(add_two(&v), None);
47+
/// ```
48+
///
49+
/// Sample example as above, but explicitly using the rcu read side lock.
50+
///
51+
/// ```
52+
/// # use kernel::revocable::Revocable;
53+
/// use kernel::sync::rcu;
54+
///
55+
/// struct Example {
56+
/// a: u32,
57+
/// b: u32,
58+
/// }
59+
///
60+
/// fn add_two(v: &Revocable<Example>) -> Option<u32> {
61+
/// let guard = rcu::read_lock();
62+
/// let e = v.try_access_with_guard(&guard)?;
63+
/// Some(e.a + e.b)
64+
/// }
65+
///
66+
/// let v = KBox::pin_init(Revocable::new(Example { a: 10, b: 20 }), GFP_KERNEL).unwrap();
67+
/// assert_eq!(add_two(&v), Some(30));
68+
/// v.revoke();
69+
/// assert_eq!(add_two(&v), None);
70+
/// ```
71+
#[pin_data(PinnedDrop)]
72+
pub struct Revocable<T> {
73+
is_available: AtomicBool,
74+
#[pin]
75+
data: MaybeUninit<UnsafeCell<T>>,
76+
}
77+
78+
// SAFETY: `Revocable` is `Send` if the wrapped object is also `Send`. This is because while the
79+
// functionality exposed by `Revocable` can be accessed from any thread/CPU, it is possible that
80+
// this isn't supported by the wrapped object.
81+
unsafe impl<T: Send> Send for Revocable<T> {}
82+
83+
// SAFETY: `Revocable` is `Sync` if the wrapped object is both `Send` and `Sync`. We require `Send`
84+
// from the wrapped object as well because of `Revocable::revoke`, which can trigger the `Drop`
85+
// implementation of the wrapped object from an arbitrary thread.
86+
unsafe impl<T: Sync + Send> Sync for Revocable<T> {}
87+
88+
impl<T> Revocable<T> {
89+
/// Creates a new revocable instance of the given data.
90+
pub fn new(data: impl PinInit<T>) -> impl PinInit<Self> {
91+
pin_init!(Self {
92+
is_available: AtomicBool::new(true),
93+
// SAFETY: The closure only returns `Ok(())` if `slot` is fully initialized; on error
94+
// `slot` is not partially initialized and does not need to be dropped.
95+
data <- unsafe {
96+
init::pin_init_from_closure(move |slot: *mut MaybeUninit<UnsafeCell<T>>| {
97+
init::PinInit::<T, core::convert::Infallible>::__pinned_init(data,
98+
slot as *mut T)?;
99+
Ok::<(), core::convert::Infallible>(())
100+
})
101+
},
102+
})
103+
}
104+
105+
/// Tries to access the \[revocable\] wrapped object.
106+
///
107+
/// Returns `None` if the object has been revoked and is therefore no longer accessible.
108+
///
109+
/// Returns a guard that gives access to the object otherwise; the object is guaranteed to
110+
/// remain accessible while the guard is alive. In such cases, callers are not allowed to sleep
111+
/// because another CPU may be waiting to complete the revocation of this object.
112+
pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {
113+
let guard = rcu::read_lock();
114+
if self.is_available.load(Ordering::Relaxed) {
115+
// SAFETY: Since `self.is_available` is true, data is initialised and has to remain
116+
// valid because the RCU read side lock prevents it from being dropped.
117+
Some(unsafe { RevocableGuard::new(self.data.assume_init_ref().get(), guard) })
118+
} else {
119+
None
120+
}
121+
}
122+
123+
/// Tries to access the \[revocable\] wrapped object.
124+
///
125+
/// Returns `None` if the object has been revoked and is therefore no longer accessible.
126+
///
127+
/// Returns a shared reference to the object otherwise; the object is guaranteed to
128+
/// remain accessible while the rcu read side guard is alive. In such cases, callers are not
129+
/// allowed to sleep because another CPU may be waiting to complete the revocation of this
130+
/// object.
131+
pub fn try_access_with_guard<'a>(&'a self, _guard: &'a rcu::Guard) -> Option<&'a T> {
132+
if self.is_available.load(Ordering::Relaxed) {
133+
// SAFETY: Since `self.is_available` is true, data is initialised and has to remain
134+
// valid because the RCU read side lock prevents it from being dropped.
135+
Some(unsafe { &*self.data.assume_init_ref().get() })
136+
} else {
137+
None
138+
}
139+
}
140+
141+
/// Revokes access to and drops the wrapped object.
142+
///
143+
/// Access to the object is revoked immediately to new callers of [`Revocable::try_access`]. If
144+
/// there are concurrent users of the object (i.e., ones that called [`Revocable::try_access`]
145+
/// beforehand and still haven't dropped the returned guard), this function waits for the
146+
/// concurrent access to complete before dropping the wrapped object.
147+
pub fn revoke(&self) {
148+
if self
149+
.is_available
150+
.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed)
151+
.is_ok()
152+
{
153+
// SAFETY: Just an FFI call, there are no further requirements.
154+
unsafe { bindings::synchronize_rcu() };
155+
156+
// SAFETY: We know `self.data` is valid because only one CPU can succeed the
157+
// `compare_exchange` above that takes `is_available` from `true` to `false`.
158+
unsafe { drop_in_place(self.data.assume_init_ref().get()) };
159+
}
160+
}
161+
}
162+
163+
#[pinned_drop]
164+
impl<T> PinnedDrop for Revocable<T> {
165+
fn drop(self: Pin<&mut Self>) {
166+
// Drop only if the data hasn't been revoked yet (in which case it has already been
167+
// dropped).
168+
// SAFETY: We are not moving out of `p`, only dropping in place
169+
let p = unsafe { self.get_unchecked_mut() };
170+
if *p.is_available.get_mut() {
171+
// SAFETY: We know `self.data` is valid because no other CPU has changed
172+
// `is_available` to `false` yet, and no other CPU can do it anymore because this CPU
173+
// holds the only reference (mutable) to `self` now.
174+
unsafe { drop_in_place(p.data.assume_init_ref().get()) };
175+
}
176+
}
177+
}
178+
179+
/// A guard that allows access to a revocable object and keeps it alive.
180+
///
181+
/// CPUs may not sleep while holding on to [`RevocableGuard`] because it's in atomic context
182+
/// holding the RCU read-side lock.
183+
///
184+
/// # Invariants
185+
///
186+
/// The RCU read-side lock is held while the guard is alive.
187+
pub struct RevocableGuard<'a, T> {
188+
data_ref: *const T,
189+
_rcu_guard: rcu::Guard,
190+
_p: PhantomData<&'a ()>,
191+
}
192+
193+
impl<T> RevocableGuard<'_, T> {
194+
fn new(data_ref: *const T, rcu_guard: rcu::Guard) -> Self {
195+
Self {
196+
data_ref,
197+
_rcu_guard: rcu_guard,
198+
_p: PhantomData,
199+
}
200+
}
201+
}
202+
203+
impl<T> Deref for RevocableGuard<'_, T> {
204+
type Target = T;
205+
206+
fn deref(&self) -> &Self::Target {
207+
// SAFETY: By the type invariants, we hold the rcu read-side lock, so the object is
208+
// guaranteed to remain valid.
209+
unsafe { &*self.data_ref }
210+
}
211+
}

0 commit comments

Comments
 (0)