[PATCH 1/3] rust: page: replace the page pointer wrapper with Opaque

From: Abdiel Janulgue
Date: Mon Oct 07 2024 - 16:29:18 EST


Replace NonNull with Opaque to make it possible to cast to a Page pointer
from a raw struct page pointer.

Signed-off-by: Abdiel Janulgue <abdiel.janulgue@xxxxxxxxx>
---
rust/kernel/page.rs | 19 +++++++++++++------
1 file changed, 13 insertions(+), 6 deletions(-)

diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs
index 208a006d587c..08ff09a25223 100644
--- a/rust/kernel/page.rs
+++ b/rust/kernel/page.rs
@@ -8,8 +8,9 @@
error::code::*,
error::Result,
uaccess::UserSliceReader,
+ types::Opaque,
};
-use core::ptr::{self, NonNull};
+use core::ptr::{self};

/// A bitwise shift for the page size.
pub const PAGE_SHIFT: usize = bindings::PAGE_SHIFT as usize;
@@ -25,8 +26,9 @@
/// # Invariants
///
/// The pointer is valid, and has ownership over the page.
+#[repr(transparent)]
pub struct Page {
- page: NonNull<bindings::page>,
+ page: Opaque<bindings::page>,
}

// SAFETY: Pages have no logic that relies on them staying on a given thread, so moving them across
@@ -65,15 +67,20 @@ pub fn alloc_page(flags: Flags) -> Result<Self, AllocError> {
// SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it
// is always safe to call this method.
let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) };
- let page = NonNull::new(page).ok_or(AllocError)?;
+ if page.is_null() {
+ return Err(AllocError);
+ }
+ // CAST: Self` is a `repr(transparent)` wrapper around `bindings::page`.
+ let ptr = page.cast::<Self>();
// INVARIANT: We just successfully allocated a page, so we now have ownership of the newly
// allocated page. We transfer that ownership to the new `Page` object.
- Ok(Self { page })
+ // SAFETY: According to invariant above ptr is valid.
+ Ok(unsafe { ptr::read(ptr) })
}

/// Returns a raw pointer to the page.
pub fn as_ptr(&self) -> *mut bindings::page {
- self.page.as_ptr()
+ self.page.get()
}

/// Runs a piece of code with this page mapped to an address.
@@ -245,6 +252,6 @@ pub unsafe fn copy_from_user_slice_raw(
impl Drop for Page {
fn drop(&mut self) {
// SAFETY: By the type invariants, we have ownership of the page and can free it.
- unsafe { bindings::__free_pages(self.page.as_ptr(), 0) };
+ unsafe { bindings::__free_pages(self.page.get(), 0) };
}
}
--
2.34.1