Skip to content

Commit c022e87

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]> Co-developed-by: Danilo Krummrich <[email protected]> Signed-off-by: Danilo Krummrich <[email protected]>
1 parent c663ada commit c022e87

File tree

2 files changed

+236
-0
lines changed

2 files changed

+236
-0
lines changed

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ pub mod pid_namespace;
6060
pub mod prelude;
6161
pub mod print;
6262
pub mod rbtree;
63+
pub mod revocable;
6364
pub mod security;
6465
pub mod seq_file;
6566
pub mod sizes;

rust/kernel/revocable.rs

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

0 commit comments

Comments
 (0)