xref: /linux/rust/kernel/types.rs (revision 6269fadf351eafad6f890091eed69875125285b6)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Kernel types.
4 
5 use crate::init::{self, PinInit};
6 use alloc::boxed::Box;
7 use core::{
8     cell::UnsafeCell,
9     marker::{PhantomData, PhantomPinned},
10     mem::MaybeUninit,
11     ops::{Deref, DerefMut},
12     ptr::NonNull,
13 };
14 
15 /// Used to transfer ownership to and from foreign (non-Rust) languages.
16 ///
17 /// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and
18 /// later may be transferred back to Rust by calling [`Self::from_foreign`].
19 ///
20 /// This trait is meant to be used in cases when Rust objects are stored in C objects and
21 /// eventually "freed" back to Rust.
22 pub trait ForeignOwnable: Sized {
23     /// Type of values borrowed between calls to [`ForeignOwnable::into_foreign`] and
24     /// [`ForeignOwnable::from_foreign`].
25     type Borrowed<'a>;
26 
27     /// Converts a Rust-owned object to a foreign-owned one.
28     ///
29     /// The foreign representation is a pointer to void.
30     fn into_foreign(self) -> *const core::ffi::c_void;
31 
32     /// Borrows a foreign-owned object.
33     ///
34     /// # Safety
35     ///
36     /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for
37     /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet.
38     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Self::Borrowed<'a>;
39 
40     /// Converts a foreign-owned object back to a Rust-owned one.
41     ///
42     /// # Safety
43     ///
44     /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for
45     /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet.
46     /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for
47     /// this object must have been dropped.
48     unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self;
49 }
50 
51 impl<T: 'static> ForeignOwnable for Box<T> {
52     type Borrowed<'a> = &'a T;
53 
54     fn into_foreign(self) -> *const core::ffi::c_void {
55         Box::into_raw(self) as _
56     }
57 
58     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T {
59         // SAFETY: The safety requirements for this function ensure that the object is still alive,
60         // so it is safe to dereference the raw pointer.
61         // The safety requirements of `from_foreign` also ensure that the object remains alive for
62         // the lifetime of the returned value.
63         unsafe { &*ptr.cast() }
64     }
65 
66     unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
67         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
68         // call to `Self::into_foreign`.
69         unsafe { Box::from_raw(ptr as _) }
70     }
71 }
72 
73 impl ForeignOwnable for () {
74     type Borrowed<'a> = ();
75 
76     fn into_foreign(self) -> *const core::ffi::c_void {
77         core::ptr::NonNull::dangling().as_ptr()
78     }
79 
80     unsafe fn borrow<'a>(_: *const core::ffi::c_void) -> Self::Borrowed<'a> {}
81 
82     unsafe fn from_foreign(_: *const core::ffi::c_void) -> Self {}
83 }
84 
85 /// Runs a cleanup function/closure when dropped.
86 ///
87 /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running.
88 ///
89 /// # Examples
90 ///
91 /// In the example below, we have multiple exit paths and we want to log regardless of which one is
92 /// taken:
93 ///
94 /// ```
95 /// # use kernel::types::ScopeGuard;
96 /// fn example1(arg: bool) {
97 ///     let _log = ScopeGuard::new(|| pr_info!("example1 completed\n"));
98 ///
99 ///     if arg {
100 ///         return;
101 ///     }
102 ///
103 ///     pr_info!("Do something...\n");
104 /// }
105 ///
106 /// # example1(false);
107 /// # example1(true);
108 /// ```
109 ///
110 /// In the example below, we want to log the same message on all early exits but a different one on
111 /// the main exit path:
112 ///
113 /// ```
114 /// # use kernel::types::ScopeGuard;
115 /// fn example2(arg: bool) {
116 ///     let log = ScopeGuard::new(|| pr_info!("example2 returned early\n"));
117 ///
118 ///     if arg {
119 ///         return;
120 ///     }
121 ///
122 ///     // (Other early returns...)
123 ///
124 ///     log.dismiss();
125 ///     pr_info!("example2 no early return\n");
126 /// }
127 ///
128 /// # example2(false);
129 /// # example2(true);
130 /// ```
131 ///
132 /// In the example below, we need a mutable object (the vector) to be accessible within the log
133 /// function, so we wrap it in the [`ScopeGuard`]:
134 ///
135 /// ```
136 /// # use kernel::types::ScopeGuard;
137 /// fn example3(arg: bool) -> Result {
138 ///     let mut vec =
139 ///         ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len()));
140 ///
141 ///     vec.try_push(10u8)?;
142 ///     if arg {
143 ///         return Ok(());
144 ///     }
145 ///     vec.try_push(20u8)?;
146 ///     Ok(())
147 /// }
148 ///
149 /// # assert_eq!(example3(false), Ok(()));
150 /// # assert_eq!(example3(true), Ok(()));
151 /// ```
152 ///
153 /// # Invariants
154 ///
155 /// The value stored in the struct is nearly always `Some(_)`, except between
156 /// [`ScopeGuard::dismiss`] and [`ScopeGuard::drop`]: in this case, it will be `None` as the value
157 /// will have been returned to the caller. Since  [`ScopeGuard::dismiss`] consumes the guard,
158 /// callers won't be able to use it anymore.
159 pub struct ScopeGuard<T, F: FnOnce(T)>(Option<(T, F)>);
160 
161 impl<T, F: FnOnce(T)> ScopeGuard<T, F> {
162     /// Creates a new guarded object wrapping the given data and with the given cleanup function.
163     pub fn new_with_data(data: T, cleanup_func: F) -> Self {
164         // INVARIANT: The struct is being initialised with `Some(_)`.
165         Self(Some((data, cleanup_func)))
166     }
167 
168     /// Prevents the cleanup function from running and returns the guarded data.
169     pub fn dismiss(mut self) -> T {
170         // INVARIANT: This is the exception case in the invariant; it is not visible to callers
171         // because this function consumes `self`.
172         self.0.take().unwrap().0
173     }
174 }
175 
176 impl ScopeGuard<(), fn(())> {
177     /// Creates a new guarded object with the given cleanup function.
178     pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> {
179         ScopeGuard::new_with_data((), move |_| cleanup())
180     }
181 }
182 
183 impl<T, F: FnOnce(T)> Deref for ScopeGuard<T, F> {
184     type Target = T;
185 
186     fn deref(&self) -> &T {
187         // The type invariants guarantee that `unwrap` will succeed.
188         &self.0.as_ref().unwrap().0
189     }
190 }
191 
192 impl<T, F: FnOnce(T)> DerefMut for ScopeGuard<T, F> {
193     fn deref_mut(&mut self) -> &mut T {
194         // The type invariants guarantee that `unwrap` will succeed.
195         &mut self.0.as_mut().unwrap().0
196     }
197 }
198 
199 impl<T, F: FnOnce(T)> Drop for ScopeGuard<T, F> {
200     fn drop(&mut self) {
201         // Run the cleanup function if one is still present.
202         if let Some((data, cleanup)) = self.0.take() {
203             cleanup(data)
204         }
205     }
206 }
207 
208 /// Stores an opaque value.
209 ///
210 /// This is meant to be used with FFI objects that are never interpreted by Rust code.
211 #[repr(transparent)]
212 pub struct Opaque<T> {
213     value: UnsafeCell<MaybeUninit<T>>,
214     _pin: PhantomPinned,
215 }
216 
217 impl<T> Opaque<T> {
218     /// Creates a new opaque value.
219     pub const fn new(value: T) -> Self {
220         Self {
221             value: UnsafeCell::new(MaybeUninit::new(value)),
222             _pin: PhantomPinned,
223         }
224     }
225 
226     /// Creates an uninitialised value.
227     pub const fn uninit() -> Self {
228         Self {
229             value: UnsafeCell::new(MaybeUninit::uninit()),
230             _pin: PhantomPinned,
231         }
232     }
233 
234     /// Creates a pin-initializer from the given initializer closure.
235     ///
236     /// The returned initializer calls the given closure with the pointer to the inner `T` of this
237     /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it.
238     ///
239     /// This function is safe, because the `T` inside of an `Opaque` is allowed to be
240     /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs
241     /// to verify at that point that the inner value is valid.
242     pub fn ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self> {
243         // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully
244         // initialize the `T`.
245         unsafe {
246             init::pin_init_from_closure::<_, ::core::convert::Infallible>(move |slot| {
247                 init_func(Self::raw_get(slot));
248                 Ok(())
249             })
250         }
251     }
252 
253     /// Returns a raw pointer to the opaque data.
254     pub fn get(&self) -> *mut T {
255         UnsafeCell::get(&self.value).cast::<T>()
256     }
257 
258     /// Gets the value behind `this`.
259     ///
260     /// This function is useful to get access to the value without creating intermediate
261     /// references.
262     pub const fn raw_get(this: *const Self) -> *mut T {
263         UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>()
264     }
265 }
266 
267 /// Types that are _always_ reference counted.
268 ///
269 /// It allows such types to define their own custom ref increment and decrement functions.
270 /// Additionally, it allows users to convert from a shared reference `&T` to an owned reference
271 /// [`ARef<T>`].
272 ///
273 /// This is usually implemented by wrappers to existing structures on the C side of the code. For
274 /// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted
275 /// instances of a type.
276 ///
277 /// # Safety
278 ///
279 /// Implementers must ensure that increments to the reference count keep the object alive in memory
280 /// at least until matching decrements are performed.
281 ///
282 /// Implementers must also ensure that all instances are reference-counted. (Otherwise they
283 /// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object
284 /// alive.)
285 pub unsafe trait AlwaysRefCounted {
286     /// Increments the reference count on the object.
287     fn inc_ref(&self);
288 
289     /// Decrements the reference count on the object.
290     ///
291     /// Frees the object when the count reaches zero.
292     ///
293     /// # Safety
294     ///
295     /// Callers must ensure that there was a previous matching increment to the reference count,
296     /// and that the object is no longer used after its reference count is decremented (as it may
297     /// result in the object being freed), unless the caller owns another increment on the refcount
298     /// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls
299     /// [`AlwaysRefCounted::dec_ref`] once).
300     unsafe fn dec_ref(obj: NonNull<Self>);
301 }
302 
303 /// An owned reference to an always-reference-counted object.
304 ///
305 /// The object's reference count is automatically decremented when an instance of [`ARef`] is
306 /// dropped. It is also automatically incremented when a new instance is created via
307 /// [`ARef::clone`].
308 ///
309 /// # Invariants
310 ///
311 /// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In
312 /// particular, the [`ARef`] instance owns an increment on the underlying object's reference count.
313 pub struct ARef<T: AlwaysRefCounted> {
314     ptr: NonNull<T>,
315     _p: PhantomData<T>,
316 }
317 
318 // SAFETY: It is safe to send `ARef<T>` to another thread when the underlying `T` is `Sync` because
319 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
320 // `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a
321 // mutable reference, for example, when the reference count reaches zero and `T` is dropped.
322 unsafe impl<T: AlwaysRefCounted + Sync + Send> Send for ARef<T> {}
323 
324 // SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync`
325 // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally,
326 // it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an
327 // `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for
328 // example, when the reference count reaches zero and `T` is dropped.
329 unsafe impl<T: AlwaysRefCounted + Sync + Send> Sync for ARef<T> {}
330 
331 impl<T: AlwaysRefCounted> ARef<T> {
332     /// Creates a new instance of [`ARef`].
333     ///
334     /// It takes over an increment of the reference count on the underlying object.
335     ///
336     /// # Safety
337     ///
338     /// Callers must ensure that the reference count was incremented at least once, and that they
339     /// are properly relinquishing one increment. That is, if there is only one increment, callers
340     /// must not use the underlying object anymore -- it is only safe to do so via the newly
341     /// created [`ARef`].
342     pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
343         // INVARIANT: The safety requirements guarantee that the new instance now owns the
344         // increment on the refcount.
345         Self {
346             ptr,
347             _p: PhantomData,
348         }
349     }
350 }
351 
352 impl<T: AlwaysRefCounted> Clone for ARef<T> {
353     fn clone(&self) -> Self {
354         self.inc_ref();
355         // SAFETY: We just incremented the refcount above.
356         unsafe { Self::from_raw(self.ptr) }
357     }
358 }
359 
360 impl<T: AlwaysRefCounted> Deref for ARef<T> {
361     type Target = T;
362 
363     fn deref(&self) -> &Self::Target {
364         // SAFETY: The type invariants guarantee that the object is valid.
365         unsafe { self.ptr.as_ref() }
366     }
367 }
368 
369 impl<T: AlwaysRefCounted> From<&T> for ARef<T> {
370     fn from(b: &T) -> Self {
371         b.inc_ref();
372         // SAFETY: We just incremented the refcount above.
373         unsafe { Self::from_raw(NonNull::from(b)) }
374     }
375 }
376 
377 impl<T: AlwaysRefCounted> Drop for ARef<T> {
378     fn drop(&mut self) {
379         // SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to
380         // decrement.
381         unsafe { T::dec_ref(self.ptr) };
382     }
383 }
384 
385 /// A sum type that always holds either a value of type `L` or `R`.
386 pub enum Either<L, R> {
387     /// Constructs an instance of [`Either`] containing a value of type `L`.
388     Left(L),
389 
390     /// Constructs an instance of [`Either`] containing a value of type `R`.
391     Right(R),
392 }
393