|
| 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 = Box::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 = Box::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 | + data <- unsafe { |
| 94 | + init::pin_init_from_closure(move |slot: *mut MaybeUninit<UnsafeCell<T>>| { |
| 95 | + init::PinInit::<T, core::convert::Infallible>::__pinned_init(data, |
| 96 | + slot as *mut T)?; |
| 97 | + Ok::<(), core::convert::Infallible>(()) |
| 98 | + }) |
| 99 | + }, |
| 100 | + }) |
| 101 | + } |
| 102 | + |
| 103 | + /// Tries to access the \[revocable\] wrapped object. |
| 104 | + /// |
| 105 | + /// Returns `None` if the object has been revoked and is therefore no longer accessible. |
| 106 | + /// |
| 107 | + /// Returns a guard that gives access to the object otherwise; the object is guaranteed to |
| 108 | + /// remain accessible while the guard is alive. In such cases, callers are not allowed to sleep |
| 109 | + /// because another CPU may be waiting to complete the revocation of this object. |
| 110 | + pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> { |
| 111 | + let guard = rcu::read_lock(); |
| 112 | + if self.is_available.load(Ordering::Relaxed) { |
| 113 | + // SAFETY: Since `self.is_available` is true, data is initialised and has to remain |
| 114 | + // valid because the RCU read side lock prevents it from being dropped. |
| 115 | + Some(unsafe { RevocableGuard::new(self.data.assume_init_ref().get(), guard) }) |
| 116 | + } else { |
| 117 | + None |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + /// Tries to access the \[revocable\] wrapped object. |
| 122 | + /// |
| 123 | + /// Returns `None` if the object has been revoked and is therefore no longer accessible. |
| 124 | + /// |
| 125 | + /// Returns a shared reference to the object otherwise; the object is guaranteed to |
| 126 | + /// remain accessible while the rcu read side guard is alive. In such cases, callers are not |
| 127 | + /// allowed to sleep because another CPU may be waiting to complete the revocation of this |
| 128 | + /// object. |
| 129 | + pub fn try_access_with_guard<'a>(&'a self, _guard: &'a rcu::Guard) -> Option<&'a T> { |
| 130 | + if self.is_available.load(Ordering::Relaxed) { |
| 131 | + // SAFETY: Since `self.is_available` is true, data is initialised and has to remain |
| 132 | + // valid because the RCU read side lock prevents it from being dropped. |
| 133 | + Some(unsafe { &*self.data.assume_init_ref().get() }) |
| 134 | + } else { |
| 135 | + None |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + /// Revokes access to and drops the wrapped object. |
| 140 | + /// |
| 141 | + /// Access to the object is revoked immediately to new callers of [`Revocable::try_access`]. If |
| 142 | + /// there are concurrent users of the object (i.e., ones that called [`Revocable::try_access`] |
| 143 | + /// beforehand and still haven't dropped the returned guard), this function waits for the |
| 144 | + /// concurrent access to complete before dropping the wrapped object. |
| 145 | + pub fn revoke(&self) { |
| 146 | + if self |
| 147 | + .is_available |
| 148 | + .compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed) |
| 149 | + .is_ok() |
| 150 | + { |
| 151 | + // SAFETY: Just an FFI call, there are no further requirements. |
| 152 | + unsafe { bindings::synchronize_rcu() }; |
| 153 | + |
| 154 | + // SAFETY: We know `self.data` is valid because only one CPU can succeed the |
| 155 | + // `compare_exchange` above that takes `is_available` from `true` to `false`. |
| 156 | + unsafe { drop_in_place(self.data.assume_init_ref().get()) }; |
| 157 | + } |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +#[pinned_drop] |
| 162 | +impl<T> PinnedDrop for Revocable<T> { |
| 163 | + fn drop(self: Pin<&mut Self>) { |
| 164 | + // Drop only if the data hasn't been revoked yet (in which case it has already been |
| 165 | + // dropped). |
| 166 | + // SAFETY: We are not moving out of `p`, only dropping in place |
| 167 | + let p = unsafe { self.get_unchecked_mut() }; |
| 168 | + if *p.is_available.get_mut() { |
| 169 | + // SAFETY: We know `self.data` is valid because no other CPU has changed |
| 170 | + // `is_available` to `false` yet, and no other CPU can do it anymore because this CPU |
| 171 | + // holds the only reference (mutable) to `self` now. |
| 172 | + unsafe { drop_in_place(p.data.assume_init_ref().get()) }; |
| 173 | + } |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +/// A guard that allows access to a revocable object and keeps it alive. |
| 178 | +/// |
| 179 | +/// CPUs may not sleep while holding on to [`RevocableGuard`] because it's in atomic context |
| 180 | +/// holding the RCU read-side lock. |
| 181 | +/// |
| 182 | +/// # Invariants |
| 183 | +/// |
| 184 | +/// The RCU read-side lock is held while the guard is alive. |
| 185 | +pub struct RevocableGuard<'a, T> { |
| 186 | + data_ref: *const T, |
| 187 | + _rcu_guard: rcu::Guard, |
| 188 | + _p: PhantomData<&'a ()>, |
| 189 | +} |
| 190 | + |
| 191 | +impl<T> RevocableGuard<'_, T> { |
| 192 | + fn new(data_ref: *const T, rcu_guard: rcu::Guard) -> Self { |
| 193 | + Self { |
| 194 | + data_ref, |
| 195 | + _rcu_guard: rcu_guard, |
| 196 | + _p: PhantomData, |
| 197 | + } |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +impl<T> Deref for RevocableGuard<'_, T> { |
| 202 | + type Target = T; |
| 203 | + |
| 204 | + fn deref(&self) -> &Self::Target { |
| 205 | + // SAFETY: By the type invariants, we hold the rcu read-side lock, so the object is |
| 206 | + // guaranteed to remain valid. |
| 207 | + unsafe { &*self.data_ref } |
| 208 | + } |
| 209 | +} |
0 commit comments