[PATCH v4 4/5] rust: types: ForeignOwnable: Add type Target

From: Danilo Krummrich
Date: Thu Jun 26 2025 - 16:02:19 EST


ForeignOwnable::Target defines the payload data of a ForeignOwnable. For
Arc<T> for instance, ForeignOwnable::Target would just be T.

This is useful for cases where a trait bound is required on the target
type of the ForeignOwnable. For instance:

fn example<P>(data: P)
where
P: ForeignOwnable,
P::Target: MyTrait,
{}

Suggested-by: Benno Lossin <lossin@xxxxxxxxxx>
Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx>
---
rust/kernel/alloc/kbox.rs | 2 ++
rust/kernel/sync/arc.rs | 1 +
rust/kernel/types.rs | 4 ++++
3 files changed, 7 insertions(+)

diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs
index c386ff771d50..66fad9777567 100644
--- a/rust/kernel/alloc/kbox.rs
+++ b/rust/kernel/alloc/kbox.rs
@@ -403,6 +403,7 @@ unsafe impl<T: 'static, A> ForeignOwnable for Box<T, A>
where
A: Allocator,
{
+ type Target = T;
type PointedTo = T;
type Borrowed<'a> = &'a T;
type BorrowedMut<'a> = &'a mut T;
@@ -435,6 +436,7 @@ unsafe impl<T: 'static, A> ForeignOwnable for Pin<Box<T, A>>
where
A: Allocator,
{
+ type Target = T;
type PointedTo = T;
type Borrowed<'a> = Pin<&'a T>;
type BorrowedMut<'a> = Pin<&'a mut T>;
diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
index c7af0aa48a0a..24fb63597d35 100644
--- a/rust/kernel/sync/arc.rs
+++ b/rust/kernel/sync/arc.rs
@@ -374,6 +374,7 @@ pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {

// SAFETY: The `into_foreign` function returns a pointer that is well-aligned.
unsafe impl<T: 'static> ForeignOwnable for Arc<T> {
+ type Target = T;
type PointedTo = ArcInner<T>;
type Borrowed<'a> = ArcBorrow<'a, T>;
type BorrowedMut<'a> = Self::Borrowed<'a>;
diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs
index 3958a5f44d56..74c787b352a9 100644
--- a/rust/kernel/types.rs
+++ b/rust/kernel/types.rs
@@ -27,6 +27,9 @@
/// [`into_foreign`]: Self::into_foreign
/// [`PointedTo`]: Self::PointedTo
pub unsafe trait ForeignOwnable: Sized {
+ /// The payload type of the foreign-owned value.
+ type Target;
+
/// Type used when the value is foreign-owned. In practical terms only defines the alignment of
/// the pointer.
type PointedTo;
@@ -128,6 +131,7 @@ unsafe fn try_from_foreign(ptr: *mut Self::PointedTo) -> Option<Self> {

// SAFETY: The `into_foreign` function returns a pointer that is dangling, but well-aligned.
unsafe impl ForeignOwnable for () {
+ type Target = ();
type PointedTo = ();
type Borrowed<'a> = ();
type BorrowedMut<'a> = ();
--
2.49.0