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