Skip to contentSkip to conversation

rust: pages that cannot be racy

PATCH In review Andreas Hindborg 3 participants 7 messages Jun 5 – Jun 10

Subsystems (3)
lore
Share & tools
lore
author reviewer
#1 lore raw

PATCH v2 1/2 rust: page: add `SafePage` for race-free page access

In reply to Andreas Hindborg

SafePage wraps a regular page but adds an invariant that the page data area does not incur data races. This means SafePage cannot be mapped to user space or shared with devices, and it becomes simpler to directly reference the contents of the page.

---
 rust/kernel/page.rs | 73 +++++++++++++++++++++++++++++++++++++++++++++--------
 1 file changed, 62 insertions(+), 11 deletions(-)
rust/kernel/page.rs +62 -11
index d56ae597f692..f143b42d1bd6 100644
@@ -8,8 +8,10 @@
         Flags, //
     },
     bindings,
-    error::code::*,
-    error::Result,
+    error::{
+        code::*,
+        Result, //
+    },
     types::{
         Opaque,
         Ownable,
@@ -20,7 +22,7 @@
 use core::{
     marker::PhantomData,
     mem::ManuallyDrop,
-    ops::Deref,
+    ops::{Deref, DerefMut},
     ptr::{
         self,
         NonNull, //
@@ -193,14 +195,10 @@ impl Page {
     /// ```
     #[inline]
     pub fn alloc_page(flags: Flags) -> Result<Owned<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)?;
-        // SAFETY: We just successfully allocated a page, so we now have ownership of the newly
-        // allocated page. We transfer that ownership to the new `Owned<Page>` object.
-        // Since `Page` is transparent, we can cast the pointer directly.
-        Ok(unsafe { Owned::from_raw(page.cast()) })
+        let page = SafePage::alloc_page(flags)?;
+        // SAFETY: `SafePage` is `#[repr(transparent)]` over `Page`, so a pointer to a `SafePage`
+        // with ownership is also a pointer to a `Page` with ownership.
+        Ok(unsafe { Owned::from_raw(Owned::into_raw(page).cast()) })
     }
 
     /// Returns a raw pointer to the page.
@@ -401,3 +399,56 @@ unsafe fn release(&mut self) {
         unsafe { bindings::__free_pages(ptr.cast(), 0) };
     }
 }
+
+/// A page whose data area follows standard Rust aliasing rules.
+///
+/// [`SafePage`] has the same usage constraints as other Rust types. Thus, it cannot be mapped to
+/// user space or shared with devices. This makes it safe to reference the contents of the page
+/// while the page is mapped in kernel space.
+///
+/// # Invariants
+///
+/// The data of this page is accessed only through references to [`SafePage`]. While a shared
+/// reference to a [`SafePage`] exists, there are no writes to its data. While an exclusive
+/// reference exists, there are no other reads or writes of its data.
+#[repr(transparent)]
+pub struct SafePage(Page);
+
+impl SafePage {
+    /// Allocate a new `SafePage`.
+    pub fn alloc_page(flags: Flags) -> Result<Owned<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)?;
+
+        // SAFETY: We just successfully allocated a page, so we now have ownership of the newly
+        // allocated page. We transfer that ownership to the new `Owned<SafePage>` object. Since
+        // `Page` and `SafePage` are transparent, we can cast to the raw page pointer directly.
+        Ok(unsafe { Owned::from_raw(page.cast()) })
+    }
+}
+
+impl Ownable for SafePage {
+    #[inline]
+    unsafe fn release(&mut self) {
+        let ptr: *mut Self = self;
+        // SAFETY: By the function safety requirements, we have ownership of the page and can free
+        // it. Since `SafePage` and `Page` are transparent, we can cast the raw pointer directly.
+        unsafe { bindings::__free_pages(ptr.cast(), 0) };
+    }
+}
+
+impl Deref for SafePage {
+    type Target = Page;
+
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
+impl DerefMut for SafePage {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.0
+    }
+}
Signature · 1 line
2.51.2

Andreas Hindborg

author reviewer
#0 lore raw

v2 cover rust: pages that cannot be racy

Some drivers might want to use pages for data storage in the same way one would use an array of u8. The current page cannot be used for this purpose, as it provides no guarantees for how it is accessed.

This series adds a newtype around Page with an additional invariant that the data of the page does not incur races. This makes it possible to treat the page as a regular array and even obtain a slice into the page.

---
Changes in v2:
- Reimplement Page::alloc_page() in terms of SafePage::alloc_page() to drop the duplicated raw allocation helper (Alice).
- Reword the SafePage invariant to spell out the standard Rust aliasing rules that apply to its data (Alice, Miguel).
- Replace the # Arguments list in copy_to_page with a prose description, matching the prevailing style of the kernel crate (Miguel).
- Expand the copy_to_page doctest to populate the source page,
assert that the copy succeeds and produced the expected bytes, and demonstrate the out-of-bounds error path (Miguel).
- Reword the SAFETY justification in copy_to_page from "no other writes" to "no writes" on the source side, since this call only
reads from src (Miguel).
- Rebase on v7.1-rc2.
- Link to v1: https://msgid.link/[email protected]

To: Alice Ryhl <[email protected]>
To: Lorenzo Stoakes <[email protected]>
To: "Liam R. Howlett" <[email protected]>
To: Miguel Ojeda <[email protected]>
To: Boqun Feng <[email protected]>
To: Gary Guo <[email protected]>
To: Björn Roy Baron <[email protected]>
To: Benno Lossin <[email protected]>
To: Andreas Hindborg <[email protected]>
To: Trevor Gross <[email protected]>
To: Danilo Krummrich <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]

---
Andreas Hindborg (2):
rust: page: add SafePage for race-free page access
rust: page: add method to copy data between safe pages

 rust/kernel/page.rs | 121 +++++++++++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 110 insertions(+), 11 deletions(-)

---
base-commit: 9e0898f1c0f134c6bad146ca8578f73c3e40ac0a
change-id: 20260215-page-additions-bc36046e9ffd
prerequisite-change-id: 20250305-unique-ref-29fcd675f9e9:v17
prerequisite-patch-id: 6c6a7fdd56627293ec3bba61c495f16a0858700c
prerequisite-patch-id: c1958590235ee32d6ddb31ea168105bd9cf248f2
prerequisite-patch-id: c5a4b231dc8adf37e93ebdce308dacbe6a244bf3
prerequisite-patch-id: 541dba7938ba874f8d17fee05a36b1cd9fa2c4d7
prerequisite-patch-id: 3668fd640e4c411bae0c8ea9d986c3fa5d3c9e82
prerequisite-patch-id: da1274864841e267697be9529a50531126c64872
prerequisite-patch-id: c1463b6578e94b56d2bad41f6e614b5286fb1db3
prerequisite-patch-id: a31185fe1abbf553377d6d695c5d206eebc84358
prerequisite-patch-id: 4f392b5736e55a354ec3022644389f89b52fda42
prerequisite-patch-id: b6388ff0ebdd54610010d72a5398842a3c668bbf

Best regards,

Signature · 1 line
Andreas Hindborg <[email protected]>
author reviewer
#6 lore raw

PATCH v2 2/2 rust: page: add method to copy data between safe pages

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.

---
 rust/kernel/page.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 48 insertions(+)
rust/kernel/page.rs +48 -0
index f143b42d1bd6..2307e1f06360 100644
@@ -23,6 +23,7 @@
     marker::PhantomData,
     mem::ManuallyDrop,
     ops::{Deref, DerefMut},
+    pin::Pin,
     ptr::{
         self,
         NonNull, //
@@ -427,6 +428,53 @@ pub fn alloc_page(flags: Flags) -> Result<Owned<Self>, AllocError> {
         // `Page` and `SafePage` are transparent, we can cast to the raw page pointer directly.
         Ok(unsafe { Owned::from_raw(page.cast()) })
     }
+
+    /// Copies `len` bytes from this page to `dst` at the specified byte offset.
+    ///
+    /// Copying starts within both pages at the same offset.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::error::code::EINVAL;
+    /// use kernel::page::{SafePage, PAGE_SIZE};
+    ///
+    /// let mut src_page = SafePage::alloc_page(GFP_KERNEL)?;
+    /// let mut dst_page = SafePage::alloc_page(GFP_KERNEL)?;
+    ///
+    /// let data = [0xdeu8, 0xad, 0xbe, 0xef];
+    /// // SAFETY: `data` is valid for reading `data.len()` bytes, and `src_page` is exclusively
+    /// // owned, so there is no concurrent access to its data.
+    /// unsafe { src_page.write_raw(data.as_ptr(), 0, data.len())? };
+    ///
+    /// assert!(src_page.copy_to_page(dst_page.as_pin_mut(), 0, data.len()).is_ok());
+    ///
+    /// let mut buf = [0u8; 4];
+    /// // SAFETY: `buf` is valid for writing `buf.len()` bytes, and `dst_page` is exclusively
+    /// // owned, so there is no concurrent access to its data.
+    /// unsafe { dst_page.read_raw(buf.as_mut_ptr(), 0, buf.len())? };
+    /// assert_eq!(buf, data);
+    ///
+    /// // A copy that would extend past the end of the page fails with `EINVAL`.
+    /// assert_eq!(
+    ///     src_page.copy_to_page(dst_page.as_pin_mut(), 0, PAGE_SIZE + 1),
+    ///     Err(EINVAL),
+    /// );
+    /// # 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 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) }
+        })
+    }
 }
 
 impl Ownable for SafePage {
Signature · 1 line
2.51.2
maintainer
#2 lore raw

Re: [PATCH v2 1/2] rust: page: add `SafePage` for race-free page access

In reply to Andreas Hindborg
Quoted 6 lines · Andreas Hindborg

SafePage wraps a regular page but adds an invariant that the page data area does not incur data races. This means SafePage cannot be mapped to user space or shared with devices, and it becomes simpler to directly reference the contents of the page.

Perhaps it should be called ExclusivePage?

Quoted 110 lines
 rust/kernel/page.rs | 73 +++++++++++++++++++++++++++++++++++++++++++++--------
 1 file changed, 62 insertions(+), 11 deletions(-)
rust/kernel/page.rs +62 -11
index d56ae597f692..f143b42d1bd6 100644
@@ -8,8 +8,10 @@
         Flags, //
     },
     bindings,
-    error::code::*,
-    error::Result,
+    error::{
+        code::*,
+        Result, //
+    },
     types::{
         Opaque,
         Ownable,
@@ -20,7 +22,7 @@
 use core::{
     marker::PhantomData,
     mem::ManuallyDrop,
-    ops::Deref,
+    ops::{Deref, DerefMut},
     ptr::{
         self,
         NonNull, //
@@ -193,14 +195,10 @@ impl Page {
     /// ```
     #[inline]
     pub fn alloc_page(flags: Flags) -> Result<Owned<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)?;
-        // SAFETY: We just successfully allocated a page, so we now have ownership of the newly
-        // allocated page. We transfer that ownership to the new `Owned<Page>` object.
-        // Since `Page` is transparent, we can cast the pointer directly.
-        Ok(unsafe { Owned::from_raw(page.cast()) })
+        let page = SafePage::alloc_page(flags)?;
+        // SAFETY: `SafePage` is `#[repr(transparent)]` over `Page`, so a pointer to a `SafePage`
+        // with ownership is also a pointer to a `Page` with ownership.
+        Ok(unsafe { Owned::from_raw(Owned::into_raw(page).cast()) })
     }
 
     /// Returns a raw pointer to the page.
@@ -401,3 +399,56 @@ unsafe fn release(&mut self) {
         unsafe { bindings::__free_pages(ptr.cast(), 0) };
     }
 }
+
+/// A page whose data area follows standard Rust aliasing rules.
+///
+/// [`SafePage`] has the same usage constraints as other Rust types. Thus, it cannot be mapped to
+/// user space or shared with devices. This makes it safe to reference the contents of the page
+/// while the page is mapped in kernel space.
+///
+/// # Invariants
+///
+/// The data of this page is accessed only through references to [`SafePage`]. While a shared
+/// reference to a [`SafePage`] exists, there are no writes to its data. While an exclusive
+/// reference exists, there are no other reads or writes of its data.
+#[repr(transparent)]
+pub struct SafePage(Page);
+
+impl SafePage {
+    /// Allocate a new `SafePage`.
+    pub fn alloc_page(flags: Flags) -> Result<Owned<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)?;
+
+        // SAFETY: We just successfully allocated a page, so we now have ownership of the newly
+        // allocated page. We transfer that ownership to the new `Owned<SafePage>` object. Since
+        // `Page` and `SafePage` are transparent, we can cast to the raw page pointer directly.
+        Ok(unsafe { Owned::from_raw(page.cast()) })
+    }
+}
+
+impl Ownable for SafePage {
+    #[inline]
+    unsafe fn release(&mut self) {
+        let ptr: *mut Self = self;
+        // SAFETY: By the function safety requirements, we have ownership of the page and can free
+        // it. Since `SafePage` and `Page` are transparent, we can cast the raw pointer directly.
+        unsafe { bindings::__free_pages(ptr.cast(), 0) };
+    }
+}
+
+impl Deref for SafePage {
+    type Target = Page;
+
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
+impl DerefMut for SafePage {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.0
+    }
+}
Signature · 2 lines
-- 
2.51.2
#4 lore raw

Re: [PATCH v2 1/2] rust: page: add `SafePage` for race-free page access

In reply to Andreas Hindborg
Quoted 10 lines · Andreas Hindborg

bindings,

rust/kernel/page.rs +4 -2
-    error::code::*,
-    error::Result,
+    error::{
+        code::*,
+        Result, //
+    },
     types::{
         Opaque,

rust/kernel/page.rs

Quoted 10 lines
rust/kernel/page.rs +1 -1
         Ownable,
 
 use core::{
     marker::PhantomData,
     mem::ManuallyDrop,
-    ops::Deref,
+    ops::{Deref, DerefMut},
     ptr::{
         self,
         NonNull, //

The first hunk fixes the imports, but the second introduces an import in the wrong style.

I think the first part should be in its own commit, and the second should be here but with the correct style.

But I just noticed the first part should also have been done as part of your other patch I applied yesterday, so I just rebased to fix that:

dea66841b9f8 ("rust: page: use the "kernel vertical" imports style").

Cheers,
Miguel

author reviewer
#5 lore raw

Re: [PATCH v2 1/2] rust: page: add `SafePage` for race-free page access

Quoted 22 lines · Miguel Ojeda
Quoted 10 lines · Andreas Hindborg

bindings,

rust/kernel/page.rs +4 -2
-    error::code::*,
-    error::Result,
+    error::{
+        code::*,
+        Result, //
+    },
     types::{
         Opaque,

rust/kernel/page.rs

Quoted 10 lines
rust/kernel/page.rs +1 -1
         Ownable,
 
 use core::{
     marker::PhantomData,
     mem::ManuallyDrop,
-    ops::Deref,
+    ops::{Deref, DerefMut},
     ptr::{
         self,
         NonNull, //
Quoted 5 lines

The first hunk fixes the imports, but the second introduces an import in the wrong style.

I think the first part should be in its own commit, and the second should be here but with the correct style.

This was sitting in my tree on top of already fixed imports. I probably made a mistake when I separated it for submission.

I am looking forward to the day where rustfmt will be able to handle this for us without the added slashes.

Quoted 6 lines

But I just noticed the first part should also have been done as part of your other patch I applied yesterday, so I just rebased to fix that:

dea66841b9f8 ("rust: page: use the "kernel vertical" imports style").

Great, just the second part left then!

Best regards,
Andreas Hindborg

author reviewer
#3 lore raw

Re: [PATCH v2 1/2] rust: page: add `SafePage` for race-free page access

In reply to Alice Ryhl
Quoted 9 lines · Alice Ryhl
Quoted 6 lines · Andreas Hindborg

SafePage wraps a regular page but adds an invariant that the page data area does not incur data races. This means SafePage cannot be mapped to user space or shared with devices, and it becomes simpler to directly reference the contents of the page.

Perhaps it should be called ExclusivePage?

Yes, let's do that.

Best regards,
Andreas Hindborg