kernel/
revocable.rs

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
8use crate::{bindings, prelude::*, sync::rcu, types::Opaque};
9use core::{
10    marker::PhantomData,
11    ops::Deref,
12    ptr::drop_in_place,
13    sync::atomic::{AtomicBool, Ordering},
14};
15
16/// An object that can become inaccessible at runtime.
17///
18/// Once access is revoked and all concurrent users complete (i.e., all existing instances of
19/// [`RevocableGuard`] are dropped), the wrapped object is also dropped.
20///
21/// # Examples
22///
23/// ```
24/// # use kernel::revocable::Revocable;
25///
26/// struct Example {
27///     a: u32,
28///     b: u32,
29/// }
30///
31/// fn add_two(v: &Revocable<Example>) -> Option<u32> {
32///     let guard = v.try_access()?;
33///     Some(guard.a + guard.b)
34/// }
35///
36/// let v = KBox::pin_init(Revocable::new(Example { a: 10, b: 20 }), GFP_KERNEL).unwrap();
37/// assert_eq!(add_two(&v), Some(30));
38/// v.revoke();
39/// assert_eq!(add_two(&v), None);
40/// ```
41///
42/// Sample example as above, but explicitly using the rcu read side lock.
43///
44/// ```
45/// # use kernel::revocable::Revocable;
46/// use kernel::sync::rcu;
47///
48/// struct Example {
49///     a: u32,
50///     b: u32,
51/// }
52///
53/// fn add_two(v: &Revocable<Example>) -> Option<u32> {
54///     let guard = rcu::read_lock();
55///     let e = v.try_access_with_guard(&guard)?;
56///     Some(e.a + e.b)
57/// }
58///
59/// let v = KBox::pin_init(Revocable::new(Example { a: 10, b: 20 }), GFP_KERNEL).unwrap();
60/// assert_eq!(add_two(&v), Some(30));
61/// v.revoke();
62/// assert_eq!(add_two(&v), None);
63/// ```
64#[pin_data(PinnedDrop)]
65pub struct Revocable<T> {
66    is_available: AtomicBool,
67    #[pin]
68    data: Opaque<T>,
69}
70
71// SAFETY: `Revocable` is `Send` if the wrapped object is also `Send`. This is because while the
72// functionality exposed by `Revocable` can be accessed from any thread/CPU, it is possible that
73// this isn't supported by the wrapped object.
74unsafe impl<T: Send> Send for Revocable<T> {}
75
76// SAFETY: `Revocable` is `Sync` if the wrapped object is both `Send` and `Sync`. We require `Send`
77// from the wrapped object as well because  of `Revocable::revoke`, which can trigger the `Drop`
78// implementation of the wrapped object from an arbitrary thread.
79unsafe impl<T: Sync + Send> Sync for Revocable<T> {}
80
81impl<T> Revocable<T> {
82    /// Creates a new revocable instance of the given data.
83    pub fn new(data: impl PinInit<T>) -> impl PinInit<Self> {
84        pin_init!(Self {
85            is_available: AtomicBool::new(true),
86            data <- Opaque::pin_init(data),
87        })
88    }
89
90    /// Tries to access the revocable wrapped object.
91    ///
92    /// Returns `None` if the object has been revoked and is therefore no longer accessible.
93    ///
94    /// Returns a guard that gives access to the object otherwise; the object is guaranteed to
95    /// remain accessible while the guard is alive. In such cases, callers are not allowed to sleep
96    /// because another CPU may be waiting to complete the revocation of this object.
97    pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {
98        let guard = rcu::read_lock();
99        if self.is_available.load(Ordering::Relaxed) {
100            // Since `self.is_available` is true, data is initialised and has to remain valid
101            // because the RCU read side lock prevents it from being dropped.
102            Some(RevocableGuard::new(self.data.get(), guard))
103        } else {
104            None
105        }
106    }
107
108    /// Tries to access the revocable wrapped object.
109    ///
110    /// Returns `None` if the object has been revoked and is therefore no longer accessible.
111    ///
112    /// Returns a shared reference to the object otherwise; the object is guaranteed to
113    /// remain accessible while the rcu read side guard is alive. In such cases, callers are not
114    /// allowed to sleep because another CPU may be waiting to complete the revocation of this
115    /// object.
116    pub fn try_access_with_guard<'a>(&'a self, _guard: &'a rcu::Guard) -> Option<&'a T> {
117        if self.is_available.load(Ordering::Relaxed) {
118            // SAFETY: Since `self.is_available` is true, data is initialised and has to remain
119            // valid because the RCU read side lock prevents it from being dropped.
120            Some(unsafe { &*self.data.get() })
121        } else {
122            None
123        }
124    }
125
126    /// Tries to access the wrapped object and run a closure on it while the guard is held.
127    ///
128    /// This is a convenience method to run short non-sleepable code blocks while ensuring the
129    /// guard is dropped afterwards. [`Self::try_access`] carries the risk that the caller will
130    /// forget to explicitly drop that returned guard before calling sleepable code; this method
131    /// adds an extra safety to make sure it doesn't happen.
132    ///
133    /// Returns [`None`] if the object has been revoked and is therefore no longer accessible, or
134    /// the result of the closure wrapped in [`Some`]. If the closure returns a [`Result`] then the
135    /// return type becomes `Option<Result<>>`, which can be inconvenient. Users are encouraged to
136    /// define their own macro that turns the [`Option`] into a proper error code and flattens the
137    /// inner result into it if it makes sense within their subsystem.
138    pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> {
139        self.try_access().map(|t| f(&*t))
140    }
141
142    /// # Safety
143    ///
144    /// Callers must ensure that there are no more concurrent users of the revocable object.
145    unsafe fn revoke_internal<const SYNC: bool>(&self) {
146        if self.is_available.swap(false, Ordering::Relaxed) {
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]
188impl<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.
211pub struct RevocableGuard<'a, T> {
212    data_ref: *const T,
213    _rcu_guard: rcu::Guard,
214    _p: PhantomData<&'a ()>,
215}
216
217impl<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
227impl<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}