From a58f5fabcab0c3e15b59462637b123d4edc851c7 Mon Sep 17 00:00:00 2001 From: Benno Lossin Date: Fri, 30 Jun 2023 15:03:23 +0000 Subject: [PATCH] rust: types: make `Opaque` be `!Unpin` [ Upstream commit 0b4e3b6f6b79b1add04008a6ceaaf661107e8902 ] Adds a `PhantomPinned` field to `Opaque`. This removes the last Rust guarantee: the assumption that the type `T` can be freely moved. This is not the case for many types from the C side (e.g. if they contain a `struct list_head`). This change removes the need to add a `PhantomPinned` field manually to Rust structs that contain C structs which must not be moved. Signed-off-by: Benno Lossin Reviewed-by: Gary Guo Reviewed-by: Alice Ryhl Reviewed-by: Andreas Hindborg Link: https://lore.kernel.org/r/20230630150216.109789-1-benno.lossin@proton.me Signed-off-by: Miguel Ojeda Signed-off-by: Sasha Levin --- rust/kernel/types.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index c0b8bb1a7539..50cbd767ea9d 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -6,7 +6,7 @@ use crate::init::{self, PinInit}; use alloc::boxed::Box; use core::{ cell::UnsafeCell, - marker::PhantomData, + marker::{PhantomData, PhantomPinned}, mem::MaybeUninit, ops::{Deref, DerefMut}, ptr::NonNull, @@ -206,17 +206,26 @@ impl Drop for ScopeGuard { /// /// This is meant to be used with FFI objects that are never interpreted by Rust code. #[repr(transparent)] -pub struct Opaque(UnsafeCell>); +pub struct Opaque { + value: UnsafeCell>, + _pin: PhantomPinned, +} impl Opaque { /// Creates a new opaque value. pub const fn new(value: T) -> Self { - Self(UnsafeCell::new(MaybeUninit::new(value))) + Self { + value: UnsafeCell::new(MaybeUninit::new(value)), + _pin: PhantomPinned, + } } /// Creates an uninitialised value. pub const fn uninit() -> Self { - Self(UnsafeCell::new(MaybeUninit::uninit())) + Self { + value: UnsafeCell::new(MaybeUninit::uninit()), + _pin: PhantomPinned, + } } /// Creates a pin-initializer from the given initializer closure. @@ -240,7 +249,7 @@ impl Opaque { /// Returns a raw pointer to the opaque data. pub fn get(&self) -> *mut T { - UnsafeCell::get(&self.0).cast::() + UnsafeCell::get(&self.value).cast::() } /// Gets the value behind `this`.