xref: /linux-6.15/rust/kernel/types.rs (revision 6c2d0ad5)
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     pin::Pin,
13     ptr::NonNull,
14 };
15 
16 /// Used to transfer ownership to and from foreign (non-Rust) languages.
17 ///
18 /// Ownership is transferred from Rust to a foreign language by calling [`Self::into_foreign`] and
19 /// later may be transferred back to Rust by calling [`Self::from_foreign`].
20 ///
21 /// This trait is meant to be used in cases when Rust objects are stored in C objects and
22 /// eventually "freed" back to Rust.
23 pub trait ForeignOwnable: Sized {
24     /// Type of values borrowed between calls to [`ForeignOwnable::into_foreign`] and
25     /// [`ForeignOwnable::from_foreign`].
26     type Borrowed<'a>;
27 
28     /// Converts a Rust-owned object to a foreign-owned one.
29     ///
30     /// The foreign representation is a pointer to void.
31     fn into_foreign(self) -> *const core::ffi::c_void;
32 
33     /// Borrows a foreign-owned object.
34     ///
35     /// # Safety
36     ///
37     /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for
38     /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet.
39     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Self::Borrowed<'a>;
40 
41     /// Converts a foreign-owned object back to a Rust-owned one.
42     ///
43     /// # Safety
44     ///
45     /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for
46     /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet.
47     /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for
48     /// this object must have been dropped.
49     unsafe fn from_foreign(ptr: *const core::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
59     /// [`ForeignOwnable::from_foreign`].
60     unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option<Self> {
61         if ptr.is_null() {
62             None
63         } else {
64             // SAFETY: Since `ptr` is not null here, then `ptr` satisfies the safety requirements
65             // of `from_foreign` given the safety requirements of this function.
66             unsafe { Some(Self::from_foreign(ptr)) }
67         }
68     }
69 }
70 
71 impl<T: 'static> ForeignOwnable for Box<T> {
72     type Borrowed<'a> = &'a T;
73 
74     fn into_foreign(self) -> *const core::ffi::c_void {
75         Box::into_raw(self) as _
76     }
77 
78     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T {
79         // SAFETY: The safety requirements for this function ensure that the object is still alive,
80         // so it is safe to dereference the raw pointer.
81         // The safety requirements of `from_foreign` also ensure that the object remains alive for
82         // the lifetime of the returned value.
83         unsafe { &*ptr.cast() }
84     }
85 
86     unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
87         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
88         // call to `Self::into_foreign`.
89         unsafe { Box::from_raw(ptr as _) }
90     }
91 }
92 
93 impl<T: 'static> ForeignOwnable for Pin<Box<T>> {
94     type Borrowed<'a> = Pin<&'a T>;
95 
96     fn into_foreign(self) -> *const core::ffi::c_void {
97         // SAFETY: We are still treating the box as pinned.
98         Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _
99     }
100 
101     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> {
102         // SAFETY: The safety requirements for this function ensure that the object is still alive,
103         // so it is safe to dereference the raw pointer.
104         // The safety requirements of `from_foreign` also ensure that the object remains alive for
105         // the lifetime of the returned value.
106         let r = unsafe { &*ptr.cast() };
107 
108         // SAFETY: This pointer originates from a `Pin<Box<T>>`.
109         unsafe { Pin::new_unchecked(r) }
110     }
111 
112     unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self {
113         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
114         // call to `Self::into_foreign`.
115         unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) }
116     }
117 }
118 
119 impl ForeignOwnable for () {
120     type Borrowed<'a> = ();
121 
122     fn into_foreign(self) -> *const core::ffi::c_void {
123         core::ptr::NonNull::dangling().as_ptr()
124     }
125 
126     unsafe fn borrow<'a>(_: *const core::ffi::c_void) -> Self::Borrowed<'a> {}
127 
128     unsafe fn from_foreign(_: *const core::ffi::c_void) -> Self {}
129 }
130 
131 /// Runs a cleanup function/closure when dropped.
132 ///
133 /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running.
134 ///
135 /// # Examples
136 ///
137 /// In the example below, we have multiple exit paths and we want to log regardless of which one is
138 /// taken:
139 ///
140 /// ```
141 /// # use kernel::types::ScopeGuard;
142 /// fn example1(arg: bool) {
143 ///     let _log = ScopeGuard::new(|| pr_info!("example1 completed\n"));
144 ///
145 ///     if arg {
146 ///         return;
147 ///     }
148 ///
149 ///     pr_info!("Do something...\n");
150 /// }
151 ///
152 /// # example1(false);
153 /// # example1(true);
154 /// ```
155 ///
156 /// In the example below, we want to log the same message on all early exits but a different one on
157 /// the main exit path:
158 ///
159 /// ```
160 /// # use kernel::types::ScopeGuard;
161 /// fn example2(arg: bool) {
162 ///     let log = ScopeGuard::new(|| pr_info!("example2 returned early\n"));
163 ///
164 ///     if arg {
165 ///         return;
166 ///     }
167 ///
168 ///     // (Other early returns...)
169 ///
170 ///     log.dismiss();
171 ///     pr_info!("example2 no early return\n");
172 /// }
173 ///
174 /// # example2(false);
175 /// # example2(true);
176 /// ```
177 ///
178 /// In the example below, we need a mutable object (the vector) to be accessible within the log
179 /// function, so we wrap it in the [`ScopeGuard`]:
180 ///
181 /// ```
182 /// # use kernel::types::ScopeGuard;
183 /// fn example3(arg: bool) -> Result {
184 ///     let mut vec =
185 ///         ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len()));
186 ///
187 ///     vec.push(10u8, GFP_KERNEL)?;
188 ///     if arg {
189 ///         return Ok(());
190 ///     }
191 ///     vec.push(20u8, GFP_KERNEL)?;
192 ///     Ok(())
193 /// }
194 ///
195 /// # assert_eq!(example3(false), Ok(()));
196 /// # assert_eq!(example3(true), Ok(()));
197 /// ```
198 ///
199 /// # Invariants
200 ///
201 /// The value stored in the struct is nearly always `Some(_)`, except between
202 /// [`ScopeGuard::dismiss`] and [`ScopeGuard::drop`]: in this case, it will be `None` as the value
203 /// will have been returned to the caller. Since  [`ScopeGuard::dismiss`] consumes the guard,
204 /// callers won't be able to use it anymore.
205 pub struct ScopeGuard<T, F: FnOnce(T)>(Option<(T, F)>);
206 
207 impl<T, F: FnOnce(T)> ScopeGuard<T, F> {
208     /// Creates a new guarded object wrapping the given data and with the given cleanup function.
209     pub fn new_with_data(data: T, cleanup_func: F) -> Self {
210         // INVARIANT: The struct is being initialised with `Some(_)`.
211         Self(Some((data, cleanup_func)))
212     }
213 
214     /// Prevents the cleanup function from running and returns the guarded data.
215     pub fn dismiss(mut self) -> T {
216         // INVARIANT: This is the exception case in the invariant; it is not visible to callers
217         // because this function consumes `self`.
218         self.0.take().unwrap().0
219     }
220 }
221 
222 impl ScopeGuard<(), fn(())> {
223     /// Creates a new guarded object with the given cleanup function.
224     pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> {
225         ScopeGuard::new_with_data((), move |_| cleanup())
226     }
227 }
228 
229 impl<T, F: FnOnce(T)> Deref for ScopeGuard<T, F> {
230     type Target = T;
231 
232     fn deref(&self) -> &T {
233         // The type invariants guarantee that `unwrap` will succeed.
234         &self.0.as_ref().unwrap().0
235     }
236 }
237 
238 impl<T, F: FnOnce(T)> DerefMut for ScopeGuard<T, F> {
239     fn deref_mut(&mut self) -> &mut T {
240         // The type invariants guarantee that `unwrap` will succeed.
241         &mut self.0.as_mut().unwrap().0
242     }
243 }
244 
245 impl<T, F: FnOnce(T)> Drop for ScopeGuard<T, F> {
246     fn drop(&mut self) {
247         // Run the cleanup function if one is still present.
248         if let Some((data, cleanup)) = self.0.take() {
249             cleanup(data)
250         }
251     }
252 }
253 
254 /// Stores an opaque value.
255 ///
256 /// This is meant to be used with FFI objects that are never interpreted by Rust code.
257 #[repr(transparent)]
258 pub struct Opaque<T> {
259     value: UnsafeCell<MaybeUninit<T>>,
260     _pin: PhantomPinned,
261 }
262 
263 impl<T> Opaque<T> {
264     /// Creates a new opaque value.
265     pub const fn new(value: T) -> Self {
266         Self {
267             value: UnsafeCell::new(MaybeUninit::new(value)),
268             _pin: PhantomPinned,
269         }
270     }
271 
272     /// Creates an uninitialised value.
273     pub const fn uninit() -> Self {
274         Self {
275             value: UnsafeCell::new(MaybeUninit::uninit()),
276             _pin: PhantomPinned,
277         }
278     }
279 
280     /// Creates a pin-initializer from the given initializer closure.
281     ///
282     /// The returned initializer calls the given closure with the pointer to the inner `T` of this
283     /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it.
284     ///
285     /// This function is safe, because the `T` inside of an `Opaque` is allowed to be
286     /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs
287     /// to verify at that point that the inner value is valid.
288     pub fn ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self> {
289         // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully
290         // initialize the `T`.
291         unsafe {
292             init::pin_init_from_closure::<_, ::core::convert::Infallible>(move |slot| {
293                 init_func(Self::raw_get(slot));
294                 Ok(())
295             })
296         }
297     }
298 
299     /// Returns a raw pointer to the opaque data.
300     pub const fn get(&self) -> *mut T {
301         UnsafeCell::get(&self.value).cast::<T>()
302     }
303 
304     /// Gets the value behind `this`.
305     ///
306     /// This function is useful to get access to the value without creating intermediate
307     /// references.
308     pub const fn raw_get(this: *const Self) -> *mut T {
309         UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>()
310     }
311 }
312 
313 /// Types that are _always_ reference counted.
314 ///
315 /// It allows such types to define their own custom ref increment and decrement functions.
316 /// Additionally, it allows users to convert from a shared reference `&T` to an owned reference
317 /// [`ARef<T>`].
318 ///
319 /// This is usually implemented by wrappers to existing structures on the C side of the code. For
320 /// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted
321 /// instances of a type.
322 ///
323 /// # Safety
324 ///
325 /// Implementers must ensure that increments to the reference count keep the object alive in memory
326 /// at least until matching decrements are performed.
327 ///
328 /// Implementers must also ensure that all instances are reference-counted. (Otherwise they
329 /// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object
330 /// alive.)
331 pub unsafe trait AlwaysRefCounted {
332     /// Increments the reference count on the object.
333     fn inc_ref(&self);
334 
335     /// Decrements the reference count on the object.
336     ///
337     /// Frees the object when the count reaches zero.
338     ///
339     /// # Safety
340     ///
341     /// Callers must ensure that there was a previous matching increment to the reference count,
342     /// and that the object is no longer used after its reference count is decremented (as it may
343     /// result in the object being freed), unless the caller owns another increment on the refcount
344     /// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls
345     /// [`AlwaysRefCounted::dec_ref`] once).
346     unsafe fn dec_ref(obj: NonNull<Self>);
347 }
348 
349 /// An owned reference to an always-reference-counted object.
350 ///
351 /// The object's reference count is automatically decremented when an instance of [`ARef`] is
352 /// dropped. It is also automatically incremented when a new instance is created via
353 /// [`ARef::clone`].
354 ///
355 /// # Invariants
356 ///
357 /// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In
358 /// particular, the [`ARef`] instance owns an increment on the underlying object's reference count.
359 pub struct ARef<T: AlwaysRefCounted> {
360     ptr: NonNull<T>,
361     _p: PhantomData<T>,
362 }
363 
364 // SAFETY: It is safe to send `ARef<T>` to another thread when the underlying `T` is `Sync` because
365 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
366 // `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a
367 // mutable reference, for example, when the reference count reaches zero and `T` is dropped.
368 unsafe impl<T: AlwaysRefCounted + Sync + Send> Send for ARef<T> {}
369 
370 // SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync`
371 // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally,
372 // it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an
373 // `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for
374 // example, when the reference count reaches zero and `T` is dropped.
375 unsafe impl<T: AlwaysRefCounted + Sync + Send> Sync for ARef<T> {}
376 
377 impl<T: AlwaysRefCounted> ARef<T> {
378     /// Creates a new instance of [`ARef`].
379     ///
380     /// It takes over an increment of the reference count on the underlying object.
381     ///
382     /// # Safety
383     ///
384     /// Callers must ensure that the reference count was incremented at least once, and that they
385     /// are properly relinquishing one increment. That is, if there is only one increment, callers
386     /// must not use the underlying object anymore -- it is only safe to do so via the newly
387     /// created [`ARef`].
388     pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
389         // INVARIANT: The safety requirements guarantee that the new instance now owns the
390         // increment on the refcount.
391         Self {
392             ptr,
393             _p: PhantomData,
394         }
395     }
396 }
397 
398 impl<T: AlwaysRefCounted> Clone for ARef<T> {
399     fn clone(&self) -> Self {
400         self.inc_ref();
401         // SAFETY: We just incremented the refcount above.
402         unsafe { Self::from_raw(self.ptr) }
403     }
404 }
405 
406 impl<T: AlwaysRefCounted> Deref for ARef<T> {
407     type Target = T;
408 
409     fn deref(&self) -> &Self::Target {
410         // SAFETY: The type invariants guarantee that the object is valid.
411         unsafe { self.ptr.as_ref() }
412     }
413 }
414 
415 impl<T: AlwaysRefCounted> From<&T> for ARef<T> {
416     fn from(b: &T) -> Self {
417         b.inc_ref();
418         // SAFETY: We just incremented the refcount above.
419         unsafe { Self::from_raw(NonNull::from(b)) }
420     }
421 }
422 
423 impl<T: AlwaysRefCounted> Drop for ARef<T> {
424     fn drop(&mut self) {
425         // SAFETY: The type invariants guarantee that the `ARef` owns the reference we're about to
426         // decrement.
427         unsafe { T::dec_ref(self.ptr) };
428     }
429 }
430 
431 /// A sum type that always holds either a value of type `L` or `R`.
432 pub enum Either<L, R> {
433     /// Constructs an instance of [`Either`] containing a value of type `L`.
434     Left(L),
435 
436     /// Constructs an instance of [`Either`] containing a value of type `R`.
437     Right(R),
438 }
439 
440 /// Types for which any bit pattern is valid.
441 ///
442 /// Not all types are valid for all values. For example, a `bool` must be either zero or one, so
443 /// reading arbitrary bytes into something that contains a `bool` is not okay.
444 ///
445 /// It's okay for the type to have padding, as initializing those bytes has no effect.
446 ///
447 /// # Safety
448 ///
449 /// All bit-patterns must be valid for this type. This type must not have interior mutability.
450 pub unsafe trait FromBytes {}
451 
452 // SAFETY: All bit patterns are acceptable values of the types below.
453 unsafe impl FromBytes for u8 {}
454 unsafe impl FromBytes for u16 {}
455 unsafe impl FromBytes for u32 {}
456 unsafe impl FromBytes for u64 {}
457 unsafe impl FromBytes for usize {}
458 unsafe impl FromBytes for i8 {}
459 unsafe impl FromBytes for i16 {}
460 unsafe impl FromBytes for i32 {}
461 unsafe impl FromBytes for i64 {}
462 unsafe impl FromBytes for isize {}
463 // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
464 // patterns are also acceptable for arrays of that type.
465 unsafe impl<T: FromBytes> FromBytes for [T] {}
466 unsafe impl<T: FromBytes, const N: usize> FromBytes for [T; N] {}
467 
468 /// Types that can be viewed as an immutable slice of initialized bytes.
469 ///
470 /// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This
471 /// means that it should not have any padding, as padding bytes are uninitialized. Reading
472 /// uninitialized memory is not just undefined behavior, it may even lead to leaking sensitive
473 /// information on the stack to userspace.
474 ///
475 /// The struct should also not hold kernel pointers, as kernel pointer addresses are also considered
476 /// sensitive. However, leaking kernel pointers is not considered undefined behavior by Rust, so
477 /// this is a correctness requirement, but not a safety requirement.
478 ///
479 /// # Safety
480 ///
481 /// Values of this type may not contain any uninitialized bytes. This type must not have interior
482 /// mutability.
483 pub unsafe trait AsBytes {}
484 
485 // SAFETY: Instances of the following types have no uninitialized portions.
486 unsafe impl AsBytes for u8 {}
487 unsafe impl AsBytes for u16 {}
488 unsafe impl AsBytes for u32 {}
489 unsafe impl AsBytes for u64 {}
490 unsafe impl AsBytes for usize {}
491 unsafe impl AsBytes for i8 {}
492 unsafe impl AsBytes for i16 {}
493 unsafe impl AsBytes for i32 {}
494 unsafe impl AsBytes for i64 {}
495 unsafe impl AsBytes for isize {}
496 unsafe impl AsBytes for bool {}
497 unsafe impl AsBytes for char {}
498 unsafe impl AsBytes for str {}
499 // SAFETY: If individual values in an array have no uninitialized portions, then the array itself
500 // does not have any uninitialized portions either.
501 unsafe impl<T: AsBytes> AsBytes for [T] {}
502 unsafe impl<T: AsBytes, const N: usize> AsBytes for [T; N] {}
503