Skip to contentSkip to conversation

rust: add `UnsafePinned` type

PATCH Superseded Christian Schrefl 2 participants 5 messages May 10, 2025 – May 11, 2025 Rust

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v3 cover rust: add `UnsafePinned` type

This version now only has the kernel implementation without the config flag for using the upstream version. Additionally now commits for using UnsafePinned in Opaque were added.

Checkpatch warns about rust/kernel/types/unsafe_pinned.rs missing a MAINTAINERS entry. This should be fine because it will be included in the RUST entry.

This patchset is based on the pin-init-next branch.

---
Changes in v3:
- Dropped CONFIG_RUSTC_HAS_UNSAFE_PINNED and feature(unsafe_pinned) (Alice)
- Add comment to Opaque reasoning about included UnsafeCell (Benno)
- Small changes in commit message of Patch 3 (Benno)
- Removed docs mentioning not included functions (Benno)
- Removed docs mentioning implementation details and added that as
comment instead (Benno)
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Expanded UnsafePinned documentation to describe differences
with upstream rust implementation.
- Removed config flag for using upstream UnsafePinned type.
- Add patch implementing Wrapper for Opaque
- Add patch for using UnsafePinned internally in Opaque
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Christian Schrefl (3):
rust: add UnsafePinned type
rust: implement Wrapper<T> for Opaque<T>
rust: use UnsafePinned in the implementation of Opaque

 rust/kernel/revocable.rs           |   2 +
 rust/kernel/types.rs               |  45 ++++++++-------
 rust/kernel/types/unsafe_pinned.rs | 113 +++++++++++++++++++++++++++++++++++++
 3 files changed, 140 insertions(+), 20 deletions(-)

---
base-commit: 9de1a293c8ece00d226b21a35751ec178be2a9fa
change-id: 20250418-rust_unsafe_pinned-891dce27418d

Best regards,

Signature · 1 line
Christian Schrefl <[email protected]>
#1 lore raw

PATCH v3 1/3 rust: add UnsafePinned type

UnsafePinned<T> is useful for cases where a value might be shared with C code but not directly used by it. In particular this is added for storing additional data in the MiscDeviceRegistration which will be shared between fops->open and the containing struct.

Similar to Opaque but guarantees that the value is always initialized and that the inner value is dropped when UnsafePinned is dropped.

This was originally proposed for the IRQ abstractions [0] and is also useful for other where the inner data may be aliased, but is always valid and automatic Drop is desired.

Since then the UnsafePinned type was added to upstream Rust [1] by Sky as a unstable feature, therefore this patch implements the subset of the upstream API for the UnsafePinned type required for additional data in MiscDeviceRegistration and in the implementation of the Opaque type.

Some differences to the upstream type definition are required in the kernel implementation, because upstream type uses some compiler changes to opt out of certain optimizations, this is documented in the documentation and a comment on the UnsafePinned type.

The documentation on is based on the upstream rust documentation with minor modifications for the kernel implementation.

---
 rust/kernel/types.rs               |   6 ++
 rust/kernel/types/unsafe_pinned.rs | 113 +++++++++++++++++++++++++++++++++++++
 2 files changed, 119 insertions(+)
rust/kernel/types.rs +6 -0
index 9d0471afc9648f2973235488b441eb109069adb1..705f420fdfbc4a576de1c4546578f2f04cdf615e 100644
@@ -253,6 +253,9 @@ fn drop(&mut self) {
 ///
 /// [`Opaque<T>`] is meant to be used with FFI objects that are never interpreted by Rust code.
 ///
+/// In cases where the contained data is only used by Rust, is not allowed to be
+/// uninitialized and automatic [`Drop`] is desired [`UnsafePinned`] should be used instead.
+///
 /// It is used to wrap structs from the C side, like for example `Opaque<bindings::mutex>`.
 /// It gets rid of all the usual assumptions that Rust has for a value:
 ///
@@ -578,3 +581,6 @@ pub enum Either<L, R> {
 /// [`NotThreadSafe`]: type@NotThreadSafe
 #[allow(non_upper_case_globals)]
 pub const NotThreadSafe: NotThreadSafe = PhantomData;
+
+mod unsafe_pinned;
+pub use unsafe_pinned::UnsafePinned;
rust/kernel/types/unsafe_pinned.rs new file +113 -0

113 lines not on this page · raw message

Signature · 1 line
2.49.0
#2 lore raw

Re: [PATCH v3 1/3] rust: add UnsafePinned type

kernel test robot noticed the following build errors:

Hi Christian,

kernel test robot noticed the following build errors:

[auto build test ERROR on 9de1a293c8ece00d226b21a35751ec178be2a9fa]

url:    https://github.com/intel-lab-lkp/linux/commits/Christian-Schrefl/rust-add-UnsafePinned-type/20250510-173533
base:   9de1a293c8ece00d226b21a35751ec178be2a9fa
patch link:    https://lore.kernel.org/r/20250510-rust_unsafe_pinned-v3-1-57ce151123f9%40gmail.com
patch subject: [PATCH v3 1/3] rust: add UnsafePinned type
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20250511/[email protected]/config)
compiler: clang version 18.1.8 (https://github.com/llvm/llvm-project 3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff)
rustc: rustc 1.78.0 (9b00956e5 2024-04-29)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250511/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

>> error[E0599]: no method named `get_mut_unchecked` found for struct `UnsafePinned` in the current scope

--> rust/doctests_kernel_generated.rs:7770:7
|
7770 | x.get_mut_unchecked().write(1);
| ^^^^^^^^^^^^^^^^^ method not found in UnsafePinned<{integer}>

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#3 lore raw

PATCH v3 2/3 rust: implement `Wrapper<T>` for `Opaque<T>`

In reply to Christian Schrefl

Moves the implementation for pin-init from an associated function to the trait function of the Wrapper trait and extends the implementation to support pin-initializers with error types.

This allows to declare functions that are generic over Wrapper types.

Adds a use for the Wrapper trait in revocable.rs, to use the new pin-init function. This is currently the only usage in the kernel.

---
 rust/kernel/revocable.rs |  2 ++
 rust/kernel/types.rs     | 25 +++++++++++++------------
 2 files changed, 15 insertions(+), 12 deletions(-)
rust/kernel/revocable.rs +2 -0
index 1e5a9d25c21b279b01f90b02997492aa4880d84f..4db68ea2207ebafcc09d082fdc1e281f31846a38 100644
@@ -5,6 +5,8 @@
 //! The [`Revocable`] type wraps other types and allows access to them to be revoked. The existence
 //! of a [`RevocableGuard`] ensures that objects remain valid.
 
+use pin_init::Wrapper;
+
 use crate::{bindings, prelude::*, sync::rcu, types::Opaque};
 use core::{
     marker::PhantomData,
rust/kernel/types.rs +13 -12
index 705f420fdfbc4a576de1c4546578f2f04cdf615e..f06e8720e012102e5c41e79fd97b0607e927d71c 100644
@@ -9,7 +9,7 @@
     ops::{Deref, DerefMut},
     ptr::NonNull,
 };
-use pin_init::{PinInit, Zeroable};
+use pin_init::{PinInit, Wrapper, Zeroable};
 
 /// Used to transfer ownership to and from foreign (non-Rust) languages.
 ///
@@ -332,17 +332,6 @@ pub const fn uninit() -> Self {
         }
     }
 
-    /// Create an opaque pin-initializer from the given pin-initializer.
-    pub fn pin_init(slot: impl PinInit<T>) -> impl PinInit<Self> {
-        Self::ffi_init(|ptr: *mut T| {
-            // SAFETY:
-            //   - `ptr` is a valid pointer to uninitialized memory,
-            //   - `slot` is not accessed on error; the call is infallible,
-            //   - `slot` is pinned in memory.
-            let _ = unsafe { PinInit::<T>::__pinned_init(slot, ptr) };
-        })
-    }
-
     /// Creates a pin-initializer from the given initializer closure.
     ///
     /// The returned initializer calls the given closure with the pointer to the inner `T` of this
@@ -393,6 +382,18 @@ pub const fn raw_get(this: *const Self) -> *mut T {
         UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>()
     }
 }
+impl<T> Wrapper<T> for Opaque<T> {
+    /// Create an opaque pin-initializer from the given pin-initializer.
+    fn pin_init<E>(slot: impl PinInit<T, E>) -> impl PinInit<Self, E> {
+        Self::try_ffi_init(|ptr: *mut T| {
+            // SAFETY:
+            //   - `ptr` is a valid pointer to uninitialized memory,
+            //   - `slot` is not accessed on error; the call is infallible,
+            //   - `slot` is pinned in memory.
+            unsafe { PinInit::<T, E>::__pinned_init(slot, ptr) }
+        })
+    }
+}
 
 /// Types that are _always_ reference counted.
 ///
Signature · 1 line
2.49.0
#4 lore raw

PATCH v3 3/3 rust: use `UnsafePinned` in the implementation of `Opaque`

In reply to Christian Schrefl

Make the semantics of the Opaque implementation clearer and prepare for the switch to the upstream rust UnsafePinned type in the future.

Opaque still uses UnsafeCell even though the kernel implementation of UnsafePinned already includes it, since the current upstream version does not.

---
 rust/kernel/types.rs | 32 +++++++++++++++-----------------
 1 file changed, 15 insertions(+), 17 deletions(-)
rust/kernel/types.rs +15 -17
index f06e8720e012102e5c41e79fd97b0607e927d71c..e32905c42453132fbea49d37a6457547d42465ce 100644
@@ -4,12 +4,12 @@
 
 use core::{
     cell::UnsafeCell,
-    marker::{PhantomData, PhantomPinned},
+    marker::PhantomData,
     mem::{ManuallyDrop, MaybeUninit},
     ops::{Deref, DerefMut},
     ptr::NonNull,
 };
-use pin_init::{PinInit, Wrapper, Zeroable};
+use pin_init::{cast_pin_init, PinInit, Wrapper, Zeroable};
 
 /// Used to transfer ownership to and from foreign (non-Rust) languages.
 ///
@@ -308,8 +308,10 @@ fn drop(&mut self) {
 /// ```
 #[repr(transparent)]
 pub struct Opaque<T> {
-    value: UnsafeCell<MaybeUninit<T>>,
-    _pin: PhantomPinned,
+    // The kernel implementation of `UnsafePinned` uses `UnsafeCell` internally, but the
+    // upstream rust `UnsafePinned` will not. So to make sure this is compatible with
+    // the upstream version use `UnsafeCell` here.
+    value: UnsafePinned<UnsafeCell<MaybeUninit<T>>>,
 }
 
 // SAFETY: `Opaque<T>` allows the inner value to be any bit pattern, including all zeros.
@@ -319,16 +321,14 @@ impl<T> Opaque<T> {
     /// Creates a new opaque value.
     pub const fn new(value: T) -> Self {
         Self {
-            value: UnsafeCell::new(MaybeUninit::new(value)),
-            _pin: PhantomPinned,
+            value: UnsafePinned::new(UnsafeCell::new(MaybeUninit::new(value))),
         }
     }
 
     /// Creates an uninitialised value.
     pub const fn uninit() -> Self {
         Self {
-            value: UnsafeCell::new(MaybeUninit::uninit()),
-            _pin: PhantomPinned,
+            value: UnsafePinned::new(UnsafeCell::new(MaybeUninit::uninit())),
         }
     }
 
@@ -371,7 +371,7 @@ pub fn try_ffi_init<E>(
 
     /// Returns a raw pointer to the opaque data.
     pub const fn get(&self) -> *mut T {
-        UnsafeCell::get(&self.value).cast::<T>()
+        UnsafeCell::raw_get(self.value.get()).cast::<T>()
     }
 
     /// Gets the value behind `this`.
@@ -384,14 +384,12 @@ pub const fn raw_get(this: *const Self) -> *mut T {
 }
 impl<T> Wrapper<T> for Opaque<T> {
     /// Create an opaque pin-initializer from the given pin-initializer.
-    fn pin_init<E>(slot: impl PinInit<T, E>) -> impl PinInit<Self, E> {
-        Self::try_ffi_init(|ptr: *mut T| {
-            // SAFETY:
-            //   - `ptr` is a valid pointer to uninitialized memory,
-            //   - `slot` is not accessed on error; the call is infallible,
-            //   - `slot` is pinned in memory.
-            unsafe { PinInit::<T, E>::__pinned_init(slot, ptr) }
-        })
+    fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
+        let value_init =
+            UnsafePinned::pin_init(UnsafeCell::pin_init(MaybeUninit::pin_init(value_init)));
+        // SAFETY: `Opaque<T>` is a `repr(transparent)` wrapper around
+        // `UnsafePinned<UnsafeCell<MabeUninit<T>>>` so the memory representation is compatible.
+        unsafe { cast_pin_init(value_init) }
     }
 }
 
Signature · 1 line
2.49.0