kernel/
types.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! Kernel types.
4
5use core::{
6    cell::UnsafeCell,
7    marker::{PhantomData, PhantomPinned},
8    mem::{ManuallyDrop, MaybeUninit},
9    ops::{Deref, DerefMut},
10    ptr::NonNull,
11};
12use pin_init::{PinInit, Zeroable};
13
14/// Used to transfer ownership to and from foreign (non-Rust) languages.
15///
16/// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and
17/// later may be transferred back to Rust by calling [`Self::from_foreign`].
18///
19/// This trait is meant to be used in cases when Rust objects are stored in C objects and
20/// eventually "freed" back to Rust.
21///
22/// # Safety
23///
24/// Implementers must ensure that [`into_foreign`] returns a pointer which meets the alignment
25/// requirements of [`PointedTo`].
26///
27/// [`into_foreign`]: Self::into_foreign
28/// [`PointedTo`]: Self::PointedTo
29pub unsafe trait ForeignOwnable: Sized {
30    /// Type used when the value is foreign-owned. In practical terms only defines the alignment of
31    /// the pointer.
32    type PointedTo;
33
34    /// Type used to immutably borrow a value that is currently foreign-owned.
35    type Borrowed<'a>;
36
37    /// Type used to mutably borrow a value that is currently foreign-owned.
38    type BorrowedMut<'a>;
39
40    /// Converts a Rust-owned object to a foreign-owned one.
41    ///
42    /// # Guarantees
43    ///
44    /// The return value is guaranteed to be well-aligned, but there are no other guarantees for
45    /// this pointer. For example, it might be null, dangling, or point to uninitialized memory.
46    /// Using it in any way except for [`ForeignOwnable::from_foreign`], [`ForeignOwnable::borrow`],
47    /// [`ForeignOwnable::try_from_foreign`] can result in undefined behavior.
48    ///
49    /// [`from_foreign`]: Self::from_foreign
50    /// [`try_from_foreign`]: Self::try_from_foreign
51    /// [`borrow`]: Self::borrow
52    /// [`borrow_mut`]: Self::borrow_mut
53    fn into_foreign(self) -> *mut Self::PointedTo;
54
55    /// Converts a foreign-owned object back to a Rust-owned one.
56    ///
57    /// # Safety
58    ///
59    /// The provided pointer must have been returned by a previous call to [`into_foreign`], and it
60    /// must not be passed to `from_foreign` more than once.
61    ///
62    /// [`into_foreign`]: Self::into_foreign
63    unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self;
64
65    /// Tries to convert a foreign-owned object back to a Rust-owned one.
66    ///
67    /// A convenience wrapper over [`ForeignOwnable::from_foreign`] that returns [`None`] if `ptr`
68    /// is null.
69    ///
70    /// # Safety
71    ///
72    /// `ptr` must either be null or satisfy the safety requirements for [`from_foreign`].
73    ///
74    /// [`from_foreign`]: Self::from_foreign
75    unsafe fn try_from_foreign(ptr: *mut Self::PointedTo) -> Option<Self> {
76        if ptr.is_null() {
77            None
78        } else {
79            // SAFETY: Since `ptr` is not null here, then `ptr` satisfies the safety requirements
80            // of `from_foreign` given the safety requirements of this function.
81            unsafe { Some(Self::from_foreign(ptr)) }
82        }
83    }
84
85    /// Borrows a foreign-owned object immutably.
86    ///
87    /// This method provides a way to access a foreign-owned value from Rust immutably. It provides
88    /// you with exactly the same abilities as an `&Self` when the value is Rust-owned.
89    ///
90    /// # Safety
91    ///
92    /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if
93    /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of
94    /// the lifetime `'a`.
95    ///
96    /// [`into_foreign`]: Self::into_foreign
97    /// [`from_foreign`]: Self::from_foreign
98    unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> Self::Borrowed<'a>;
99
100    /// Borrows a foreign-owned object mutably.
101    ///
102    /// This method provides a way to access a foreign-owned value from Rust mutably. It provides
103    /// you with exactly the same abilities as an `&mut Self` when the value is Rust-owned, except
104    /// that the address of the object must not be changed.
105    ///
106    /// Note that for types like [`Arc`], an `&mut Arc<T>` only gives you immutable access to the
107    /// inner value, so this method also only provides immutable access in that case.
108    ///
109    /// In the case of `Box<T>`, this method gives you the ability to modify the inner `T`, but it
110    /// does not let you change the box itself. That is, you cannot change which allocation the box
111    /// points at.
112    ///
113    /// # Safety
114    ///
115    /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if
116    /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of
117    /// the lifetime `'a`.
118    ///
119    /// The lifetime `'a` must not overlap with the lifetime of any other call to [`borrow`] or
120    /// `borrow_mut` on the same object.
121    ///
122    /// [`into_foreign`]: Self::into_foreign
123    /// [`from_foreign`]: Self::from_foreign
124    /// [`borrow`]: Self::borrow
125    /// [`Arc`]: crate::sync::Arc
126    unsafe fn borrow_mut<'a>(ptr: *mut Self::PointedTo) -> Self::BorrowedMut<'a>;
127}
128
129// SAFETY: The `into_foreign` function returns a pointer that is dangling, but well-aligned.
130unsafe impl ForeignOwnable for () {
131    type PointedTo = ();
132    type Borrowed<'a> = ();
133    type BorrowedMut<'a> = ();
134
135    fn into_foreign(self) -> *mut Self::PointedTo {
136        core::ptr::NonNull::dangling().as_ptr()
137    }
138
139    unsafe fn from_foreign(_: *mut Self::PointedTo) -> Self {}
140
141    unsafe fn borrow<'a>(_: *mut Self::PointedTo) -> Self::Borrowed<'a> {}
142    unsafe fn borrow_mut<'a>(_: *mut Self::PointedTo) -> Self::BorrowedMut<'a> {}
143}
144
145/// Runs a cleanup function/closure when dropped.
146///
147/// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running.
148///
149/// # Examples
150///
151/// In the example below, we have multiple exit paths and we want to log regardless of which one is
152/// taken:
153///
154/// ```
155/// # use kernel::types::ScopeGuard;
156/// fn example1(arg: bool) {
157///     let _log = ScopeGuard::new(|| pr_info!("example1 completed\n"));
158///
159///     if arg {
160///         return;
161///     }
162///
163///     pr_info!("Do something...\n");
164/// }
165///
166/// # example1(false);
167/// # example1(true);
168/// ```
169///
170/// In the example below, we want to log the same message on all early exits but a different one on
171/// the main exit path:
172///
173/// ```
174/// # use kernel::types::ScopeGuard;
175/// fn example2(arg: bool) {
176///     let log = ScopeGuard::new(|| pr_info!("example2 returned early\n"));
177///
178///     if arg {
179///         return;
180///     }
181///
182///     // (Other early returns...)
183///
184///     log.dismiss();
185///     pr_info!("example2 no early return\n");
186/// }
187///
188/// # example2(false);
189/// # example2(true);
190/// ```
191///
192/// In the example below, we need a mutable object (the vector) to be accessible within the log
193/// function, so we wrap it in the [`ScopeGuard`]:
194///
195/// ```
196/// # use kernel::types::ScopeGuard;
197/// fn example3(arg: bool) -> Result {
198///     let mut vec =
199///         ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len()));
200///
201///     vec.push(10u8, GFP_KERNEL)?;
202///     if arg {
203///         return Ok(());
204///     }
205///     vec.push(20u8, GFP_KERNEL)?;
206///     Ok(())
207/// }
208///
209/// # assert_eq!(example3(false), Ok(()));
210/// # assert_eq!(example3(true), Ok(()));
211/// ```
212///
213/// # Invariants
214///
215/// The value stored in the struct is nearly always `Some(_)`, except between
216/// [`ScopeGuard::dismiss`] and [`ScopeGuard::drop`]: in this case, it will be `None` as the value
217/// will have been returned to the caller. Since  [`ScopeGuard::dismiss`] consumes the guard,
218/// callers won't be able to use it anymore.
219pub struct ScopeGuard<T, F: FnOnce(T)>(Option<(T, F)>);
220
221impl<T, F: FnOnce(T)> ScopeGuard<T, F> {
222    /// Creates a new guarded object wrapping the given data and with the given cleanup function.
223    pub fn new_with_data(data: T, cleanup_func: F) -> Self {
224        // INVARIANT: The struct is being initialised with `Some(_)`.
225        Self(Some((data, cleanup_func)))
226    }
227
228    /// Prevents the cleanup function from running and returns the guarded data.
229    pub fn dismiss(mut self) -> T {
230        // INVARIANT: This is the exception case in the invariant; it is not visible to callers
231        // because this function consumes `self`.
232        self.0.take().unwrap().0
233    }
234}
235
236impl ScopeGuard<(), fn(())> {
237    /// Creates a new guarded object with the given cleanup function.
238    pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> {
239        ScopeGuard::new_with_data((), move |()| cleanup())
240    }
241}
242
243impl<T, F: FnOnce(T)> Deref for ScopeGuard<T, F> {
244    type Target = T;
245
246    fn deref(&self) -> &T {
247        // The type invariants guarantee that `unwrap` will succeed.
248        &self.0.as_ref().unwrap().0
249    }
250}
251
252impl<T, F: FnOnce(T)> DerefMut for ScopeGuard<T, F> {
253    fn deref_mut(&mut self) -> &mut T {
254        // The type invariants guarantee that `unwrap` will succeed.
255        &mut self.0.as_mut().unwrap().0
256    }
257}
258
259impl<T, F: FnOnce(T)> Drop for ScopeGuard<T, F> {
260    fn drop(&mut self) {
261        // Run the cleanup function if one is still present.
262        if let Some((data, cleanup)) = self.0.take() {
263            cleanup(data)
264        }
265    }
266}
267
268/// Stores an opaque value.
269///
270/// [`Opaque<T>`] is meant to be used with FFI objects that are never interpreted by Rust code.
271///
272/// It is used to wrap structs from the C side, like for example `Opaque<bindings::mutex>`.
273/// It gets rid of all the usual assumptions that Rust has for a value:
274///
275/// * The value is allowed to be uninitialized (for example have invalid bit patterns: `3` for a
276///   [`bool`]).
277/// * The value is allowed to be mutated, when a `&Opaque<T>` exists on the Rust side.
278/// * No uniqueness for mutable references: it is fine to have multiple `&mut Opaque<T>` point to
279///   the same value.
280/// * The value is not allowed to be shared with other threads (i.e. it is `!Sync`).
281///
282/// This has to be used for all values that the C side has access to, because it can't be ensured
283/// that the C side is adhering to the usual constraints that Rust needs.
284///
285/// Using [`Opaque<T>`] allows to continue to use references on the Rust side even for values shared
286/// with C.
287///
288/// # Examples
289///
290/// ```
291/// # #![expect(unreachable_pub, clippy::disallowed_names)]
292/// use kernel::types::Opaque;
293/// # // Emulate a C struct binding which is from C, maybe uninitialized or not, only the C side
294/// # // knows.
295/// # mod bindings {
296/// #     pub struct Foo {
297/// #         pub val: u8,
298/// #     }
299/// # }
300///
301/// // `foo.val` is assumed to be handled on the C side, so we use `Opaque` to wrap it.
302/// pub struct Foo {
303///     foo: Opaque<bindings::Foo>,
304/// }
305///
306/// impl Foo {
307///     pub fn get_val(&self) -> u8 {
308///         let ptr = Opaque::get(&self.foo);
309///
310///         // SAFETY: `Self` is valid from C side.
311///         unsafe { (*ptr).val }
312///     }
313/// }
314///
315/// // Create an instance of `Foo` with the `Opaque` wrapper.
316/// let foo = Foo {
317///     foo: Opaque::new(bindings::Foo { val: 0xdb }),
318/// };
319///
320/// assert_eq!(foo.get_val(), 0xdb);
321/// ```
322#[repr(transparent)]
323pub struct Opaque<T> {
324    value: UnsafeCell<MaybeUninit<T>>,
325    _pin: PhantomPinned,
326}
327
328// SAFETY: `Opaque<T>` allows the inner value to be any bit pattern, including all zeros.
329unsafe impl<T> Zeroable for Opaque<T> {}
330
331impl<T> Opaque<T> {
332    /// Creates a new opaque value.
333    pub const fn new(value: T) -> Self {
334        Self {
335            value: UnsafeCell::new(MaybeUninit::new(value)),
336            _pin: PhantomPinned,
337        }
338    }
339
340    /// Creates an uninitialised value.
341    pub const fn uninit() -> Self {
342        Self {
343            value: UnsafeCell::new(MaybeUninit::uninit()),
344            _pin: PhantomPinned,
345        }
346    }
347
348    /// Creates a new zeroed opaque value.
349    pub const fn zeroed() -> Self {
350        Self {
351            value: UnsafeCell::new(MaybeUninit::zeroed()),
352            _pin: PhantomPinned,
353        }
354    }
355
356    /// Create an opaque pin-initializer from the given pin-initializer.
357    pub fn pin_init(slot: impl PinInit<T>) -> impl PinInit<Self> {
358        Self::ffi_init(|ptr: *mut T| {
359            // SAFETY:
360            //   - `ptr` is a valid pointer to uninitialized memory,
361            //   - `slot` is not accessed on error; the call is infallible,
362            //   - `slot` is pinned in memory.
363            let _ = unsafe { PinInit::<T>::__pinned_init(slot, ptr) };
364        })
365    }
366
367    /// Creates a pin-initializer from the given initializer closure.
368    ///
369    /// The returned initializer calls the given closure with the pointer to the inner `T` of this
370    /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it.
371    ///
372    /// This function is safe, because the `T` inside of an `Opaque` is allowed to be
373    /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs
374    /// to verify at that point that the inner value is valid.
375    pub fn ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self> {
376        // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully
377        // initialize the `T`.
378        unsafe {
379            pin_init::pin_init_from_closure::<_, ::core::convert::Infallible>(move |slot| {
380                init_func(Self::raw_get(slot));
381                Ok(())
382            })
383        }
384    }
385
386    /// Creates a fallible pin-initializer from the given initializer closure.
387    ///
388    /// The returned initializer calls the given closure with the pointer to the inner `T` of this
389    /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it.
390    ///
391    /// This function is safe, because the `T` inside of an `Opaque` is allowed to be
392    /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs
393    /// to verify at that point that the inner value is valid.
394    pub fn try_ffi_init<E>(
395        init_func: impl FnOnce(*mut T) -> Result<(), E>,
396    ) -> impl PinInit<Self, E> {
397        // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully
398        // initialize the `T`.
399        unsafe {
400            pin_init::pin_init_from_closure::<_, E>(move |slot| init_func(Self::raw_get(slot)))
401        }
402    }
403
404    /// Returns a raw pointer to the opaque data.
405    pub const fn get(&self) -> *mut T {
406        UnsafeCell::get(&self.value).cast::<T>()
407    }
408
409    /// Gets the value behind `this`.
410    ///
411    /// This function is useful to get access to the value without creating intermediate
412    /// references.
413    pub const fn raw_get(this: *const Self) -> *mut T {
414        UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>()
415    }
416}
417
418/// Types that are _always_ reference counted.
419///
420/// It allows such types to define their own custom ref increment and decrement functions.
421/// Additionally, it allows users to convert from a shared reference `&T` to an owned reference
422/// [`ARef<T>`].
423///
424/// This is usually implemented by wrappers to existing structures on the C side of the code. For
425/// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted
426/// instances of a type.
427///
428/// # Safety
429///
430/// Implementers must ensure that increments to the reference count keep the object alive in memory
431/// at least until matching decrements are performed.
432///
433/// Implementers must also ensure that all instances are reference-counted. (Otherwise they
434/// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object
435/// alive.)
436pub unsafe trait AlwaysRefCounted {
437    /// Increments the reference count on the object.
438    fn inc_ref(&self);
439
440    /// Decrements the reference count on the object.
441    ///
442    /// Frees the object when the count reaches zero.
443    ///
444    /// # Safety
445    ///
446    /// Callers must ensure that there was a previous matching increment to the reference count,
447    /// and that the object is no longer used after its reference count is decremented (as it may
448    /// result in the object being freed), unless the caller owns another increment on the refcount
449    /// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls
450    /// [`AlwaysRefCounted::dec_ref`] once).
451    unsafe fn dec_ref(obj: NonNull<Self>);
452}
453
454/// An owned reference to an always-reference-counted object.
455///
456/// The object's reference count is automatically decremented when an instance of [`ARef`] is
457/// dropped. It is also automatically incremented when a new instance is created via
458/// [`ARef::clone`].
459///
460/// # Invariants
461///
462/// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In
463/// particular, the [`ARef`] instance owns an increment on the underlying object's reference count.
464pub struct ARef<T: AlwaysRefCounted> {
465    ptr: NonNull<T>,
466    _p: PhantomData<T>,
467}
468
469// SAFETY: It is safe to send `ARef<T>` to another thread when the underlying `T` is `Sync` because
470// it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
471// `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a
472// mutable reference, for example, when the reference count reaches zero and `T` is dropped.
473unsafe impl<T: AlwaysRefCounted + Sync + Send> Send for ARef<T> {}
474
475// SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync`
476// because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally,
477// it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an
478// `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for
479// example, when the reference count reaches zero and `T` is dropped.
480unsafe impl<T: AlwaysRefCounted + Sync + Send> Sync for ARef<T> {}
481
482impl<T: AlwaysRefCounted> ARef<T> {
483    /// Creates a new instance of [`ARef`].
484    ///
485    /// It takes over an increment of the reference count on the underlying object.
486    ///
487    /// # Safety
488    ///
489    /// Callers must ensure that the reference count was incremented at least once, and that they
490    /// are properly relinquishing one increment. That is, if there is only one increment, callers
491    /// must not use the underlying object anymore -- it is only safe to do so via the newly
492    /// created [`ARef`].
493    pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
494        // INVARIANT: The safety requirements guarantee that the new instance now owns the
495        // increment on the refcount.
496        Self {
497            ptr,
498            _p: PhantomData,
499        }
500    }
501
502    /// Consumes the `ARef`, returning a raw pointer.
503    ///
504    /// This function does not change the refcount. After calling this function, the caller is
505    /// responsible for the refcount previously managed by the `ARef`.
506    ///
507    /// # Examples
508    ///
509    /// ```
510    /// use core::ptr::NonNull;
511    /// use kernel::types::{ARef, AlwaysRefCounted};
512    ///
513    /// struct Empty {}
514    ///
515    /// # // SAFETY: TODO.
516    /// unsafe impl AlwaysRefCounted for Empty {
517    ///     fn inc_ref(&self) {}
518    ///     unsafe fn dec_ref(_obj: NonNull<Self>) {}
519    /// }
520    ///
521    /// let mut data = Empty {};
522    /// let ptr = NonNull::<Empty>::new(&mut data).unwrap();
523    /// # // SAFETY: TODO.
524    /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };
525    /// let raw_ptr: NonNull<Empty> = ARef::into_raw(data_ref);
526    ///
527    /// assert_eq!(ptr, raw_ptr);
528    /// ```
529    pub fn into_raw(me: Self) -> NonNull<T> {
530        ManuallyDrop::new(me).ptr
531    }
532}
533
534impl<T: AlwaysRefCounted> Clone for ARef<T> {
535    fn clone(&self) -> Self {
536        self.inc_ref();
537        // SAFETY: We just incremented the refcount above.
538        unsafe { Self::from_raw(self.ptr) }
539    }
540}
541
542impl<T: AlwaysRefCounted> Deref for ARef<T> {
543    type Target = T;
544
545    fn deref(&self) -> &Self::Target {
546        // SAFETY: The type invariants guarantee that the object is valid.
547        unsafe { self.ptr.as_ref() }
548    }
549}
550
551impl<T: AlwaysRefCounted> From<&T> for ARef<T> {
552    fn from(b: &T) -> Self {
553        b.inc_ref();
554        // SAFETY: We just incremented the refcount above.
555        unsafe { Self::from_raw(NonNull::from(b)) }
556    }
557}
558
559impl<T: AlwaysRefCounted> Drop for ARef<T> {
560    fn drop(&mut self) {
561        // SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to
562        // decrement.
563        unsafe { T::dec_ref(self.ptr) };
564    }
565}
566
567/// A sum type that always holds either a value of type `L` or `R`.
568///
569/// # Examples
570///
571/// ```
572/// use kernel::types::Either;
573///
574/// let left_value: Either<i32, &str> = Either::Left(7);
575/// let right_value: Either<i32, &str> = Either::Right("right value");
576/// ```
577pub enum Either<L, R> {
578    /// Constructs an instance of [`Either`] containing a value of type `L`.
579    Left(L),
580
581    /// Constructs an instance of [`Either`] containing a value of type `R`.
582    Right(R),
583}
584
585/// Zero-sized type to mark types not [`Send`].
586///
587/// Add this type as a field to your struct if your type should not be sent to a different task.
588/// Since [`Send`] is an auto trait, adding a single field that is `!Send` will ensure that the
589/// whole type is `!Send`.
590///
591/// If a type is `!Send` it is impossible to give control over an instance of the type to another
592/// task. This is useful to include in types that store or reference task-local information. A file
593/// descriptor is an example of such task-local information.
594///
595/// This type also makes the type `!Sync`, which prevents immutable access to the value from
596/// several threads in parallel.
597pub type NotThreadSafe = PhantomData<*mut ()>;
598
599/// Used to construct instances of type [`NotThreadSafe`] similar to how `PhantomData` is
600/// constructed.
601///
602/// [`NotThreadSafe`]: type@NotThreadSafe
603#[allow(non_upper_case_globals)]
604pub const NotThreadSafe: NotThreadSafe = PhantomData;