From: Alice Ryhl <aliceryhl@google.com>
To: rust-for-linux@vger.kernel.org, Tejun Heo <tj@kernel.org>,
Miguel Ojeda <ojeda@kernel.org>
Cc: "Lai Jiangshan" <jiangshanlai@gmail.com>,
"Wedson Almeida Filho" <wedsonaf@gmail.com>,
"Alex Gaynor" <alex.gaynor@gmail.com>,
"Boqun Feng" <boqun.feng@gmail.com>,
"Gary Guo" <gary@garyguo.net>,
"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
"Benno Lossin" <benno.lossin@proton.me>,
"Alice Ryhl" <aliceryhl@google.com>,
linux-kernel@vger.kernel.org, patches@lists.linux.dev,
"Wedson Almeida Filho" <walmeida@microsoft.com>
Subject: [PATCH v3 2/9] rust: sync: add `Arc::{from_raw, into_raw}`
Date: Tue, 11 Jul 2023 09:32:56 +0000 [thread overview]
Message-ID: <20230711093303.1433770-3-aliceryhl@google.com> (raw)
In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com>
From: Wedson Almeida Filho <walmeida@microsoft.com>
These methods can be used to turn an `Arc` into a raw pointer and back,
in a way that preserves the metadata for fat pointers.
This is done using the unstable ptr_metadata feature [1]. However, it
could also be done using the unstable pointer_byte_offsets feature [2],
which is likely to have a shorter path to stabilization than
ptr_metadata.
Link: https://github.com/rust-lang/rust/issues/81513 [1]
Link: https://github.com/rust-lang/rust/issues/96283 [2]
Signed-off-by: Wedson Almeida Filho <walmeida@microsoft.com>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
---
v2 -> v3:
* Use `transmute_copy` to convert metadata.
* Use `add` instead of `wrapping_add`.
* Dropped Reviewed-by from Martin and Benno due to changes.
rust/kernel/lib.rs | 1 +
rust/kernel/sync/arc.rs | 49 +++++++++++++++++++++++++++++++++++++++--
2 files changed, 48 insertions(+), 2 deletions(-)
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 788914fd935f..6963d11092c4 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -17,6 +17,7 @@
#![feature(const_refs_to_cell)]
#![feature(dispatch_from_dyn)]
#![feature(new_uninit)]
+#![feature(ptr_metadata)]
#![feature(receiver_trait)]
#![feature(unsize)]
diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
index a89843cacaad..4046b534e53b 100644
--- a/rust/kernel/sync/arc.rs
+++ b/rust/kernel/sync/arc.rs
@@ -24,13 +24,13 @@
};
use alloc::boxed::Box;
use core::{
- alloc::AllocError,
+ alloc::{AllocError, Layout},
fmt,
marker::{PhantomData, Unsize},
mem::{ManuallyDrop, MaybeUninit},
ops::{Deref, DerefMut},
pin::Pin,
- ptr::NonNull,
+ ptr::{NonNull, Pointee},
};
use macros::pin_data;
@@ -212,6 +212,51 @@ unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
}
}
+ /// Convert the [`Arc`] into a raw pointer.
+ ///
+ /// The raw pointer has ownership of the refcount that this Arc object owned.
+ pub fn into_raw(self) -> *const T {
+ let ptr = self.ptr.as_ptr();
+ core::mem::forget(self);
+ // SAFETY: The pointer is valid.
+ unsafe { core::ptr::addr_of!((*ptr).data) }
+ }
+
+ /// Recreates an [`Arc`] instance previously deconstructed via [`Arc::into_raw`].
+ ///
+ /// This code relies on the `repr(C)` layout of structs as described in
+ /// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
+ ///
+ /// # Safety
+ ///
+ /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. Additionally, it
+ /// can only be called once for each previous call to [`Arc::into_raw`].
+ pub unsafe fn from_raw(ptr: *const T) -> Self {
+ let refcount_layout = Layout::new::<bindings::refcount_t>();
+ // SAFETY: The caller guarantees that the pointer is valid.
+ let val_layout = Layout::for_value(unsafe { &*ptr });
+ // SAFETY: We're computing the layout of a real struct that existed when compiling this
+ // binary, so its layout is not so large that it can trigger arithmetic overflow.
+ let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
+
+ let metadata: <T as Pointee>::Metadata = core::ptr::metadata(ptr);
+ // SAFETY: The metadata of `T` and `ArcInner<T>` is the same because `ArcInner` is a struct
+ // with `T` as its last field.
+ //
+ // This is documented at:
+ // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
+ let metadata: <ArcInner<T> as Pointee>::Metadata =
+ unsafe { core::mem::transmute_copy(&metadata) };
+ // SAFETY: The pointer is in-bounds of an allocation both before and after offsetting the
+ // pointer, since it originates from a previous call to `Arc::into_raw` and is still valid.
+ let ptr = unsafe { (ptr as *mut u8).sub(val_offset) as *mut () };
+ let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
+
+ // SAFETY: By the safety requirements we know that `ptr` came from `Arc::into_raw`, so the
+ // reference count held then will be owned by the new `Arc` object.
+ unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) }
+ }
+
/// Returns an [`ArcBorrow`] from the given [`Arc`].
///
/// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method
--
2.41.0.255.g8b1d071c50-goog
next prev parent reply other threads:[~2023-07-11 9:39 UTC|newest]
Thread overview: 31+ messages / expand[flat|nested] mbox.gz Atom feed top
2023-07-11 9:32 [PATCH v3 0/9] rust: workqueue: add bindings for the workqueue Alice Ryhl
2023-07-11 9:32 ` [PATCH v3 1/9] rust: add offset_of! macro Alice Ryhl
2023-08-21 18:43 ` Andreas Hindborg (Samsung)
2023-07-11 9:32 ` Alice Ryhl [this message]
2023-07-12 20:33 ` [PATCH v3 2/9] rust: sync: add `Arc::{from_raw, into_raw}` Martin Rodriguez Reboredo
2023-07-15 9:42 ` Benno Lossin
2023-07-17 13:47 ` Alice Ryhl
2023-08-22 11:46 ` Andreas Hindborg (Samsung)
2023-07-11 9:32 ` [PATCH 3/9] workqueue: introduce `__INIT_WORK_WITH_KEY` Alice Ryhl
2023-07-11 10:49 ` Alice Ryhl
2023-07-12 6:33 ` Boqun Feng
2023-07-12 20:34 ` Martin Rodriguez Reboredo
2023-07-11 9:32 ` [PATCH v3 4/9] rust: workqueue: add low-level workqueue bindings Alice Ryhl
2023-07-11 22:23 ` Boqun Feng
2023-07-17 13:53 ` Alice Ryhl
2023-07-11 9:32 ` [PATCH v3 5/9] rust: workqueue: define built-in queues Alice Ryhl
2023-07-11 9:33 ` [PATCH v3 6/9] rust: workqueue: add helper for defining work_struct fields Alice Ryhl
2023-07-12 20:43 ` Martin Rodriguez Reboredo
2023-07-15 9:43 ` Benno Lossin
2023-07-17 14:49 ` Alice Ryhl
2023-08-22 18:24 ` Andreas Hindborg (Samsung)
2023-08-23 9:06 ` Andreas Hindborg (Samsung)
2023-08-22 19:59 ` Andreas Hindborg (Samsung)
2023-07-11 9:33 ` [PATCH v3 7/9] rust: workqueue: implement `WorkItemPointer` for pointer types Alice Ryhl
2023-07-11 9:33 ` [PATCH v3 8/9] rust: workqueue: add `try_spawn` helper method Alice Ryhl
2023-07-11 9:33 ` [PATCH v3 9/9] rust: workqueue: add examples Alice Ryhl
2023-07-14 22:40 ` Boqun Feng
2023-07-11 22:17 ` [PATCH v3 0/9] rust: workqueue: add bindings for the workqueue Tejun Heo
2023-07-11 23:44 ` Miguel Ojeda
2023-07-12 0:27 ` Tejun Heo
2023-07-12 16:36 ` Miguel Ojeda
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20230711093303.1433770-3-aliceryhl@google.com \
--to=aliceryhl@google.com \
--cc=alex.gaynor@gmail.com \
--cc=benno.lossin@proton.me \
--cc=bjorn3_gh@protonmail.com \
--cc=boqun.feng@gmail.com \
--cc=gary@garyguo.net \
--cc=jiangshanlai@gmail.com \
--cc=linux-kernel@vger.kernel.org \
--cc=ojeda@kernel.org \
--cc=patches@lists.linux.dev \
--cc=rust-for-linux@vger.kernel.org \
--cc=tj@kernel.org \
--cc=walmeida@microsoft.com \
--cc=wedsonaf@gmail.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®