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