Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

rust: implement ForeignOwnable for Pin<Box<T>>

We already implement ForeignOwnable for Box<T>, but it may be useful to
store pinned data in a ForeignOwnable container. This patch makes that
possible.

This will be used together with upcoming miscdev abstractions, which
Binder will use when binderfs is disabled.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20240730-foreign-ownable-pin-box-v1-1-b1d70cdae541@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>

authored by

Alice Ryhl and committed by
Miguel Ojeda
6c2d0ad5 08f983a5

+27
+27
rust/kernel/types.rs
··· 9 9 marker::{PhantomData, PhantomPinned}, 10 10 mem::MaybeUninit, 11 11 ops::{Deref, DerefMut}, 12 + pin::Pin, 12 13 ptr::NonNull, 13 14 }; 14 15 ··· 87 86 // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous 88 87 // call to `Self::into_foreign`. 89 88 unsafe { Box::from_raw(ptr as _) } 89 + } 90 + } 91 + 92 + impl<T: 'static> ForeignOwnable for Pin<Box<T>> { 93 + type Borrowed<'a> = Pin<&'a T>; 94 + 95 + fn into_foreign(self) -> *const core::ffi::c_void { 96 + // SAFETY: We are still treating the box as pinned. 97 + Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ 98 + } 99 + 100 + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { 101 + // SAFETY: The safety requirements for this function ensure that the object is still alive, 102 + // so it is safe to dereference the raw pointer. 103 + // The safety requirements of `from_foreign` also ensure that the object remains alive for 104 + // the lifetime of the returned value. 105 + let r = unsafe { &*ptr.cast() }; 106 + 107 + // SAFETY: This pointer originates from a `Pin<Box<T>>`. 108 + unsafe { Pin::new_unchecked(r) } 109 + } 110 + 111 + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { 112 + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous 113 + // call to `Self::into_foreign`. 114 + unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } 90 115 } 91 116 } 92 117