[PATCH v22 2/6] rust: page: add `from_raw()`

From: Andreas Hindborg

Date: Wed Nov 18 2026 - 11:20:19 EST


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

The method is available for all page kinds. The caller selects the page
kind and must ensure that the invariants of that kind hold for the page.

A `&Page<RefCounted>` can be converted to an `ARef<Page>`. Thus, for
`Page<RefCounted>`, the page must be managed by the page reference count
and taking additional references to it must be permitted. This is not the
case for all pages, for instance pages owned by the slab allocator. Such
pages can be referenced as `Page<Base>`.

Signed-off-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
---
rust/kernel/page.rs | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)

diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs
index b2a17c86e7de..2ceeac0237d5 100644
--- a/rust/kernel/page.rs
+++ b/rust/kernel/page.rs
@@ -217,6 +217,30 @@ pub fn nid(&self) -> i32 {
unsafe { bindings::page_to_nid(self.as_ptr()) }
}

+ /// Create a `&Page<Kind>` from a raw `struct page` pointer.
+ ///
+ /// It is up to the caller to select the correct [`PageKind`] for the page.
+ ///
+ /// # Safety
+ ///
+ /// Callers must ensure that, for the duration of `'a`:
+ /// - `ptr` is convertible to a shared reference.
+ /// - The invariants of `Kind` hold for the page pointed to by `ptr`, see the documentation of
+ /// the [`PageKind`] types.
+ ///
+ /// Note that the invariants of [`RefCounted`] do not hold for all pages. For instance, pages
+ /// owned by the slab allocator are not managed by the page reference count. Use [`Base`] for
+ /// pages where nothing is known beyond their validity.
+ #[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`
+ // for which the invariants of `Kind` hold, so the returned reference upholds the type
+ // invariants of `Page<Kind>`.
+ // 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.54.0