[PATCH 2/2] rust: page: add method to copy data between safe pages
From: Andreas Hindborg
Date: Sun Feb 15 2026 - 15:04:31 EST
Add `SafePage::copy_to_page` to copy data from one page to another at a
given offset. Because `SafePage` cannot be mapped to user space or shared
with devices, there are no data races and the copy can be performed using
the existing `with_pointer_into_page` and `write_raw` methods.
Signed-off-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
---
rust/kernel/page.rs | 33 +++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs
index af6d2ad408ed7..c780d10bcf909 100644
--- a/rust/kernel/page.rs
+++ b/rust/kernel/page.rs
@@ -23,6 +23,7 @@
marker::PhantomData,
mem::ManuallyDrop,
ops::{Deref, DerefMut},
+ pin::Pin,
ptr::{
self,
NonNull, //
@@ -407,6 +408,38 @@ pub fn alloc_page(flags: Flags) -> Result<Owned<Self>, AllocError> {
// Since `Page` and `SafePage` is transparent, we can cast the pointer directly.
Ok(unsafe { Owned::from_raw(page.cast()) })
}
+
+ /// Copies data from this page to another page at the specified offset.
+ ///
+ /// # Arguments
+ ///
+ /// - `dst` - The destination page to copy data to.
+ /// - `offset` - The byte offset within both pages where copying starts.
+ /// - `len` - The number of bytes to copy.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use kernel::page::SafePage;
+ /// # use kernel::alloc::flags::GFP_KERNEL;
+ /// let mut src_page = SafePage::alloc_page(GFP_KERNEL)?;
+ /// let mut dst_page = SafePage::alloc_page(GFP_KERNEL)?;
+ /// src_page.copy_to_page(dst_page.get_pin_mut(), 0, 1024)?;
+ /// # Ok::<(), kernel::error::Error>(())
+ /// ```
+ pub fn copy_to_page(&self, dst: Pin<&mut Self>, offset: usize, len: usize) -> Result {
+ // INVARIANT: The following code makes sure to not cause data races.
+ self.with_pointer_into_page(offset, len, |src| {
+ // SAFETY:
+ // - If `with_pointer_into_page` calls into this closure, then it has performed a
+ // bounds check and guarantees that `src` is valid for `len` bytes.
+ // - By type invariant and existence of shared reference, there are no other writes to
+ // `src` during this call.
+ // - By exclusive ownership of `dst`, there are no other writes to `dst` during this
+ // call.
+ unsafe { dst.write_raw(src, offset, len) }
+ })
+ }
}
// SAFETY: `Owned<SafePage>` objects returned by SafePage::alloc_page() follow the requirements of
--
2.51.2