[PATCH v7 3/6] rust: types: Support &'static and &'static mut ForeignOwnable

From: Matthew Maurer
Date: Tue Jun 24 2025 - 19:26:13 EST


These types live forever and do not require cleanup, so they can
serve as `ForeignOwnable`.

Signed-off-by: Matthew Maurer <mmaurer@xxxxxxxxxx>
---
rust/kernel/types.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 58 insertions(+)

diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs
index 22985b6f69820d6df8ff3aae0bf815fad36a9d92..6f9617b5b491426b1be5f3a27dc2c48ad1854da8 100644
--- a/rust/kernel/types.rs
+++ b/rust/kernel/types.rs
@@ -142,6 +142,64 @@ unsafe fn borrow<'a>(_: *mut Self::PointedTo) -> Self::Borrowed<'a> {}
unsafe fn borrow_mut<'a>(_: *mut Self::PointedTo) -> Self::BorrowedMut<'a> {}
}

+// SAFETY: The `into_foreign` function derives its pointer from a reference, so it is correctly
+// aligned.
+unsafe impl<T: 'static> ForeignOwnable for &'static T {
+ type PointedTo = T;
+ type Borrowed<'a> = &'a T;
+ type BorrowedMut<'a> = &'a T;
+
+ fn into_foreign(self) -> *mut Self::PointedTo {
+ self as *const _ as _
+ }
+
+ unsafe fn from_foreign(foreign: *mut Self::PointedTo) -> Self {
+ // SAFETY: from_foreign has stricter restrictions than borrow
+ unsafe { Self::borrow(foreign) }
+ }
+
+ unsafe fn borrow<'a>(foreign: *mut Self::PointedTo) -> Self::Borrowed<'a> {
+ // SAFETY: We know the original reference lived forever, so we can convert it back
+ unsafe { &*foreign }
+ }
+
+ unsafe fn borrow_mut<'a>(foreign: *mut Self::PointedTo) -> Self::BorrowedMut<'a> {
+ // SAFETY: borrow_mut has stricter restrictions than borrow
+ unsafe { Self::borrow(foreign) }
+ }
+}
+
+// SAFETY: The `into_foreign` function derives its pointer from a reference, so it is correctly
+// aligned.
+unsafe impl<T: 'static> ForeignOwnable for &'static mut T {
+ type PointedTo = T;
+ type Borrowed<'a> = &'a T;
+ type BorrowedMut<'a> = &'a mut T;
+
+ fn into_foreign(self) -> *mut Self::PointedTo {
+ self as *const _ as _
+ }
+
+ unsafe fn from_foreign(foreign: *mut Self::PointedTo) -> Self {
+ // SAFETY: from_foreign has stricter restrictions than `borrow_mut`
+ unsafe { Self::borrow_mut(foreign) }
+ }
+
+ unsafe fn borrow<'a>(foreign: *mut Self::PointedTo) -> Self::Borrowed<'a> {
+ // SAFETY: We know the original reference lived forever, and the requirements on the
+ // function indicate that `from_foreign` and `borrow_mut` will not happen concurrently, so
+ // we can do a shared borrow.
+ unsafe { &*foreign }
+ }
+
+ unsafe fn borrow_mut<'a>(foreign: *mut Self::PointedTo) -> Self::BorrowedMut<'a> {
+ // SAFETY: We know the original reference lived forever, and the requirements on the
+ // function indicate that no other borrows will happen concurrently, so we can do a
+ // unique borrow.
+ unsafe { &mut *foreign }
+ }
+}
+
/// Runs a cleanup function/closure when dropped.
///
/// The [`ScopeGuard::dismiss`] function prevents the cleanup function from running.

--
2.50.0.714.g196bf9f422-goog