• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Kernel types.
4 
5 use crate::init::{self, PinInit};
6 use core::{
7     cell::UnsafeCell,
8     marker::{PhantomData, PhantomPinned},
9     mem::{ManuallyDrop, MaybeUninit},
10     ops::{Deref, DerefMut},
11     ptr::NonNull,
12 };
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 pub trait ForeignOwnable: Sized {
22     /// Type of values borrowed between calls to [`ForeignOwnable::into_foreign`] and
23     /// [`ForeignOwnable::from_foreign`].
24     type Borrowed<'a>;
25 
26     /// Converts a Rust-owned object to a foreign-owned one.
27     ///
28     /// The foreign representation is a pointer to void. There are no guarantees for this pointer.
29     /// For example, it might be invalid, dangling or pointing to uninitialized memory. Using it in
30     /// any way except for [`ForeignOwnable::from_foreign`], [`ForeignOwnable::borrow`],
31     /// [`ForeignOwnable::try_from_foreign`] can result in undefined behavior.
into_foreign(self) -> *const crate::ffi::c_void32     fn into_foreign(self) -> *const crate::ffi::c_void;
33 
34     /// Borrows a foreign-owned object.
35     ///
36     /// # Safety
37     ///
38     /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for
39     /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet.
borrow<'a>(ptr: *const crate::ffi::c_void) -> Self::Borrowed<'a>40     unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> Self::Borrowed<'a>;
41 
42     /// Converts a foreign-owned object back to a Rust-owned one.
43     ///
44     /// # Safety
45     ///
46     /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for
47     /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet.
48     /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for
49     /// this object must have been dropped.
from_foreign(ptr: *const crate::ffi::c_void) -> Self50     unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self;
51 
52     /// Tries to convert a foreign-owned object back to a Rust-owned one.
53     ///
54     /// A convenience wrapper over [`ForeignOwnable::from_foreign`] that returns [`None`] if `ptr`
55     /// is null.
56     ///
57     /// # Safety
58     ///
59     /// `ptr` must either be null or satisfy the safety requirements for
60     /// [`ForeignOwnable::from_foreign`].
try_from_foreign(ptr: *const crate::ffi::c_void) -> Option<Self>61     unsafe fn try_from_foreign(ptr: *const 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 
72 impl ForeignOwnable for () {
73     type Borrowed<'a> = ();
74 
into_foreign(self) -> *const crate::ffi::c_void75     fn into_foreign(self) -> *const crate::ffi::c_void {
76         core::ptr::NonNull::dangling().as_ptr()
77     }
78 
borrow<'a>(_: *const crate::ffi::c_void) -> Self::Borrowed<'a>79     unsafe fn borrow<'a>(_: *const crate::ffi::c_void) -> Self::Borrowed<'a> {}
80 
from_foreign(_: *const crate::ffi::c_void) -> Self81     unsafe fn from_foreign(_: *const crate::ffi::c_void) -> Self {}
82 }
83 
84 /// Runs a cleanup function/closure when dropped.
85 ///
86 /// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running.
87 ///
88 /// # Examples
89 ///
90 /// In the example below, we have multiple exit paths and we want to log regardless of which one is
91 /// taken:
92 ///
93 /// ```
94 /// # use kernel::types::ScopeGuard;
95 /// fn example1(arg: bool) {
96 ///     let _log = ScopeGuard::new(|| pr_info!("example1 completed\n"));
97 ///
98 ///     if arg {
99 ///         return;
100 ///     }
101 ///
102 ///     pr_info!("Do something...\n");
103 /// }
104 ///
105 /// # example1(false);
106 /// # example1(true);
107 /// ```
108 ///
109 /// In the example below, we want to log the same message on all early exits but a different one on
110 /// the main exit path:
111 ///
112 /// ```
113 /// # use kernel::types::ScopeGuard;
114 /// fn example2(arg: bool) {
115 ///     let log = ScopeGuard::new(|| pr_info!("example2 returned early\n"));
116 ///
117 ///     if arg {
118 ///         return;
119 ///     }
120 ///
121 ///     // (Other early returns...)
122 ///
123 ///     log.dismiss();
124 ///     pr_info!("example2 no early return\n");
125 /// }
126 ///
127 /// # example2(false);
128 /// # example2(true);
129 /// ```
130 ///
131 /// In the example below, we need a mutable object (the vector) to be accessible within the log
132 /// function, so we wrap it in the [`ScopeGuard`]:
133 ///
134 /// ```
135 /// # use kernel::types::ScopeGuard;
136 /// fn example3(arg: bool) -> Result {
137 ///     let mut vec =
138 ///         ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len()));
139 ///
140 ///     vec.push(10u8, GFP_KERNEL)?;
141 ///     if arg {
142 ///         return Ok(());
143 ///     }
144 ///     vec.push(20u8, GFP_KERNEL)?;
145 ///     Ok(())
146 /// }
147 ///
148 /// # assert_eq!(example3(false), Ok(()));
149 /// # assert_eq!(example3(true), Ok(()));
150 /// ```
151 ///
152 /// # Invariants
153 ///
154 /// The value stored in the struct is nearly always `Some(_)`, except between
155 /// [`ScopeGuard::dismiss`] and [`ScopeGuard::drop`]: in this case, it will be `None` as the value
156 /// will have been returned to the caller. Since  [`ScopeGuard::dismiss`] consumes the guard,
157 /// callers won't be able to use it anymore.
158 pub struct ScopeGuard<T, F: FnOnce(T)>(Option<(T, F)>);
159 
160 impl<T, F: FnOnce(T)> ScopeGuard<T, F> {
161     /// Creates a new guarded object wrapping the given data and with the given cleanup function.
new_with_data(data: T, cleanup_func: F) -> Self162     pub fn new_with_data(data: T, cleanup_func: F) -> Self {
163         // INVARIANT: The struct is being initialised with `Some(_)`.
164         Self(Some((data, cleanup_func)))
165     }
166 
167     /// Prevents the cleanup function from running and returns the guarded data.
dismiss(mut self) -> T168     pub fn dismiss(mut self) -> T {
169         // INVARIANT: This is the exception case in the invariant; it is not visible to callers
170         // because this function consumes `self`.
171         self.0.take().unwrap().0
172     }
173 }
174 
175 impl ScopeGuard<(), fn(())> {
176     /// Creates a new guarded object with the given cleanup function.
new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())>177     pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> {
178         ScopeGuard::new_with_data((), move |()| cleanup())
179     }
180 }
181 
182 impl<T, F: FnOnce(T)> Deref for ScopeGuard<T, F> {
183     type Target = T;
184 
deref(&self) -> &T185     fn deref(&self) -> &T {
186         // The type invariants guarantee that `unwrap` will succeed.
187         &self.0.as_ref().unwrap().0
188     }
189 }
190 
191 impl<T, F: FnOnce(T)> DerefMut for ScopeGuard<T, F> {
deref_mut(&mut self) -> &mut T192     fn deref_mut(&mut self) -> &mut T {
193         // The type invariants guarantee that `unwrap` will succeed.
194         &mut self.0.as_mut().unwrap().0
195     }
196 }
197 
198 impl<T, F: FnOnce(T)> Drop for ScopeGuard<T, F> {
drop(&mut self)199     fn drop(&mut self) {
200         // Run the cleanup function if one is still present.
201         if let Some((data, cleanup)) = self.0.take() {
202             cleanup(data)
203         }
204     }
205 }
206 
207 /// Stores an opaque value.
208 ///
209 /// This is meant to be used with FFI objects that are never interpreted by Rust code.
210 #[repr(transparent)]
211 pub struct Opaque<T> {
212     value: UnsafeCell<MaybeUninit<T>>,
213     _pin: PhantomPinned,
214 }
215 
216 impl<T> Opaque<T> {
217     /// Creates a new opaque value.
new(value: T) -> Self218     pub const fn new(value: T) -> Self {
219         Self {
220             value: UnsafeCell::new(MaybeUninit::new(value)),
221             _pin: PhantomPinned,
222         }
223     }
224 
225     /// Creates an uninitialised value.
uninit() -> Self226     pub const fn uninit() -> Self {
227         Self {
228             value: UnsafeCell::new(MaybeUninit::uninit()),
229             _pin: PhantomPinned,
230         }
231     }
232 
233     /// Creates a pin-initializer from the given initializer closure.
234     ///
235     /// The returned initializer calls the given closure with the pointer to the inner `T` of this
236     /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it.
237     ///
238     /// This function is safe, because the `T` inside of an `Opaque` is allowed to be
239     /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs
240     /// to verify at that point that the inner value is valid.
ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self>241     pub fn ffi_init(init_func: impl FnOnce(*mut T)) -> impl PinInit<Self> {
242         // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully
243         // initialize the `T`.
244         unsafe {
245             init::pin_init_from_closure::<_, ::core::convert::Infallible>(move |slot| {
246                 init_func(Self::raw_get(slot));
247                 Ok(())
248             })
249         }
250     }
251 
252     /// Creates a fallible pin-initializer from the given initializer closure.
253     ///
254     /// The returned initializer calls the given closure with the pointer to the inner `T` of this
255     /// `Opaque`. Since this memory is uninitialized, the closure is not allowed to read from it.
256     ///
257     /// This function is safe, because the `T` inside of an `Opaque` is allowed to be
258     /// uninitialized. Additionally, access to the inner `T` requires `unsafe`, so the caller needs
259     /// to verify at that point that the inner value is valid.
try_ffi_init<E>( init_func: impl FnOnce(*mut T) -> Result<(), E>, ) -> impl PinInit<Self, E>260     pub fn try_ffi_init<E>(
261         init_func: impl FnOnce(*mut T) -> Result<(), E>,
262     ) -> impl PinInit<Self, E> {
263         // SAFETY: We contain a `MaybeUninit`, so it is OK for the `init_func` to not fully
264         // initialize the `T`.
265         unsafe { init::pin_init_from_closure::<_, E>(move |slot| init_func(Self::raw_get(slot))) }
266     }
267 
268     /// Returns a raw pointer to the opaque data.
get(&self) -> *mut T269     pub const fn get(&self) -> *mut T {
270         UnsafeCell::get(&self.value).cast::<T>()
271     }
272 
273     /// Gets the value behind `this`.
274     ///
275     /// This function is useful to get access to the value without creating intermediate
276     /// references.
raw_get(this: *const Self) -> *mut T277     pub const fn raw_get(this: *const Self) -> *mut T {
278         UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>()
279     }
280 }
281 
282 /// Types that are _always_ reference counted.
283 ///
284 /// It allows such types to define their own custom ref increment and decrement functions.
285 /// Additionally, it allows users to convert from a shared reference `&T` to an owned reference
286 /// [`ARef<T>`].
287 ///
288 /// This is usually implemented by wrappers to existing structures on the C side of the code. For
289 /// Rust code, the recommendation is to use [`Arc`](crate::sync::Arc) to create reference-counted
290 /// instances of a type.
291 ///
292 /// # Safety
293 ///
294 /// Implementers must ensure that increments to the reference count keep the object alive in memory
295 /// at least until matching decrements are performed.
296 ///
297 /// Implementers must also ensure that all instances are reference-counted. (Otherwise they
298 /// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object
299 /// alive.)
300 pub unsafe trait AlwaysRefCounted {
301     /// Increments the reference count on the object.
inc_ref(&self)302     fn inc_ref(&self);
303 
304     /// Decrements the reference count on the object.
305     ///
306     /// Frees the object when the count reaches zero.
307     ///
308     /// # Safety
309     ///
310     /// Callers must ensure that there was a previous matching increment to the reference count,
311     /// and that the object is no longer used after its reference count is decremented (as it may
312     /// result in the object being freed), unless the caller owns another increment on the refcount
313     /// (e.g., it calls [`AlwaysRefCounted::inc_ref`] twice, then calls
314     /// [`AlwaysRefCounted::dec_ref`] once).
dec_ref(obj: NonNull<Self>)315     unsafe fn dec_ref(obj: NonNull<Self>);
316 }
317 
318 /// An owned reference to an always-reference-counted object.
319 ///
320 /// The object's reference count is automatically decremented when an instance of [`ARef`] is
321 /// dropped. It is also automatically incremented when a new instance is created via
322 /// [`ARef::clone`].
323 ///
324 /// # Invariants
325 ///
326 /// The pointer stored in `ptr` is non-null and valid for the lifetime of the [`ARef`] instance. In
327 /// particular, the [`ARef`] instance owns an increment on the underlying object's reference count.
328 pub struct ARef<T: AlwaysRefCounted> {
329     ptr: NonNull<T>,
330     _p: PhantomData<T>,
331 }
332 
333 // SAFETY: It is safe to send `ARef<T>` to another thread when the underlying `T` is `Sync` because
334 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs
335 // `T` to be `Send` because any thread that has an `ARef<T>` may ultimately access `T` using a
336 // mutable reference, for example, when the reference count reaches zero and `T` is dropped.
337 unsafe impl<T: AlwaysRefCounted + Sync + Send> Send for ARef<T> {}
338 
339 // SAFETY: It is safe to send `&ARef<T>` to another thread when the underlying `T` is `Sync`
340 // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally,
341 // it needs `T` to be `Send` because any thread that has a `&ARef<T>` may clone it and get an
342 // `ARef<T>` on that thread, so the thread may ultimately access `T` using a mutable reference, for
343 // example, when the reference count reaches zero and `T` is dropped.
344 unsafe impl<T: AlwaysRefCounted + Sync + Send> Sync for ARef<T> {}
345 
346 impl<T: AlwaysRefCounted> ARef<T> {
347     /// Creates a new instance of [`ARef`].
348     ///
349     /// It takes over an increment of the reference count on the underlying object.
350     ///
351     /// # Safety
352     ///
353     /// Callers must ensure that the reference count was incremented at least once, and that they
354     /// are properly relinquishing one increment. That is, if there is only one increment, callers
355     /// must not use the underlying object anymore -- it is only safe to do so via the newly
356     /// created [`ARef`].
from_raw(ptr: NonNull<T>) -> Self357     pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
358         // INVARIANT: The safety requirements guarantee that the new instance now owns the
359         // increment on the refcount.
360         Self {
361             ptr,
362             _p: PhantomData,
363         }
364     }
365 
366     /// Consumes the `ARef`, returning a raw pointer.
367     ///
368     /// This function does not change the refcount. After calling this function, the caller is
369     /// responsible for the refcount previously managed by the `ARef`.
370     ///
371     /// # Examples
372     ///
373     /// ```
374     /// use core::ptr::NonNull;
375     /// use kernel::types::{ARef, AlwaysRefCounted};
376     ///
377     /// struct Empty {}
378     ///
379     /// # // SAFETY: TODO.
380     /// unsafe impl AlwaysRefCounted for Empty {
381     ///     fn inc_ref(&self) {}
382     ///     unsafe fn dec_ref(_obj: NonNull<Self>) {}
383     /// }
384     ///
385     /// let mut data = Empty {};
386     /// let ptr = NonNull::<Empty>::new(&mut data as *mut _).unwrap();
387     /// # // SAFETY: TODO.
388     /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };
389     /// let raw_ptr: NonNull<Empty> = ARef::into_raw(data_ref);
390     ///
391     /// assert_eq!(ptr, raw_ptr);
392     /// ```
into_raw(me: Self) -> NonNull<T>393     pub fn into_raw(me: Self) -> NonNull<T> {
394         ManuallyDrop::new(me).ptr
395     }
396 }
397 
398 impl<T: AlwaysRefCounted> Clone for ARef<T> {
clone(&self) -> Self399     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 
deref(&self) -> &Self::Target409     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> {
from(b: &T) -> Self416     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> {
drop(&mut self)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 macro_rules! impl_frombytes {
453     ($($({$($generics:tt)*})? $t:ty, )*) => {
454         // SAFETY: Safety comments written in the macro invocation.
455         $(unsafe impl$($($generics)*)? FromBytes for $t {})*
456     };
457 }
458 
459 impl_frombytes! {
460     // SAFETY: All bit patterns are acceptable values of the types below.
461     u8, u16, u32, u64, usize,
462     i8, i16, i32, i64, isize,
463 
464     // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
465     // patterns are also acceptable for arrays of that type.
466     {<T: FromBytes>} [T],
467     {<T: FromBytes, const N: usize>} [T; N],
468 }
469 
470 /// Types that can be viewed as an immutable slice of initialized bytes.
471 ///
472 /// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This
473 /// means that it should not have any padding, as padding bytes are uninitialized. Reading
474 /// uninitialized memory is not just undefined behavior, it may even lead to leaking sensitive
475 /// information on the stack to userspace.
476 ///
477 /// The struct should also not hold kernel pointers, as kernel pointer addresses are also considered
478 /// sensitive. However, leaking kernel pointers is not considered undefined behavior by Rust, so
479 /// this is a correctness requirement, but not a safety requirement.
480 ///
481 /// # Safety
482 ///
483 /// Values of this type may not contain any uninitialized bytes. This type must not have interior
484 /// mutability.
485 pub unsafe trait AsBytes {}
486 
487 /// Zero-sized type to mark types not [`Send`].
488 ///
489 /// Add this type as a field to your struct if your type should not be sent to a different task.
490 /// Since [`Send`] is an auto trait, adding a single field that is `!Send` will ensure that the
491 /// whole type is `!Send`.
492 ///
493 /// If a type is `!Send` it is impossible to give control over an instance of the type to another
494 /// task. This is useful to include in types that store or reference task-local information. A file
495 /// descriptor is an example of such task-local information.
496 ///
497 /// This type also makes the type `!Sync`, which prevents immutable access to the value from
498 /// several threads in parallel.
499 pub type NotThreadSafe = PhantomData<*mut ()>;
500 
501 /// Used to construct instances of type [`NotThreadSafe`] similar to how `PhantomData` is
502 /// constructed.
503 ///
504 /// [`NotThreadSafe`]: type@NotThreadSafe
505 #[allow(non_upper_case_globals)]
506 pub const NotThreadSafe: NotThreadSafe = PhantomData;
507 
508 macro_rules! impl_asbytes {
509     ($($({$($generics:tt)*})? $t:ty, )*) => {
510         // SAFETY: Safety comments written in the macro invocation.
511         $(unsafe impl$($($generics)*)? AsBytes for $t {})*
512     };
513 }
514 
515 impl_asbytes! {
516     // SAFETY: Instances of the following types have no uninitialized portions.
517     u8, u16, u32, u64, usize,
518     i8, i16, i32, i64, isize,
519     bool,
520     char,
521     str,
522 
523     // SAFETY: If individual values in an array have no uninitialized portions, then the array
524     // itself does not have any uninitialized portions either.
525     {<T: AsBytes>} [T],
526     {<T: AsBytes, const N: usize>} [T; N],
527 }
528