[PATCH v21 8/9] rust: page: add `from_raw()`

From: Andreas Hindborg

Date: Thu Sep 10 2026 - 05:18:01 EST


From: Andreas Hindborg <a.hindborg@xxxxxxxxxxx>

Add a method to `Page` that allows construction of an instance from `struct
page` pointer.

Assisted-by: LLM
Signed-off-by: Andreas Hindborg <a.hindborg@xxxxxxxxxxx>
Reviewed-by: Onur Özkan <work@xxxxxxxxxxxxx>
---
rust/kernel/page.rs | 14 ++++++++++++++
1 file changed, 14 insertions(+)

diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs
index a2610774c749..cd394b0656c0 100644
--- a/rust/kernel/page.rs
+++ b/rust/kernel/page.rs
@@ -146,6 +146,20 @@ pub fn nid(&self) -> i32 {
unsafe { bindings::page_to_nid(self.as_ptr()) }
}

+ /// Create a `&Page` from a raw `struct page` pointer.
+ ///
+ /// # Safety
+ ///
+ /// `ptr` must be convertible to a shared reference with a lifetime of `'a`.
+ #[inline]
+ pub unsafe fn from_raw<'a>(ptr: *const bindings::page) -> &'a Self {
+ // INVARIANT: By the function safety requirements, `ptr` refers to a valid `struct page`, so
+ // the returned reference upholds the type invariant of `Page`.
+ // SAFETY: By function safety requirements, `ptr` is not null and is convertible to a shared
+ // reference.
+ unsafe { &*ptr.cast() }
+ }
+
/// Runs a piece of code with this page mapped to an address.
///
/// The page is unmapped when this call returns.

--
2.51.2