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