Linux driver-core infrastructure
 help / color / mirror / Atom feed
From: Andreas Hindborg <a.hindborg@kernel.org>
To: "Alice Ryhl" <aliceryhl@google.com>,
	"Lorenzo Stoakes" <ljs@kernel.org>,
	"Liam R. Howlett" <liam@infradead.org>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Boqun Feng" <boqun@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>,
	"Will Deacon" <will@kernel.org>,
	"Peter Zijlstra" <peterz@infradead.org>,
	"Mark Rutland" <mark.rutland@arm.com>,
	"Lyude Paul" <lyude@redhat.com>,
	"Greg Kroah-Hartman" <gregkh@linuxfoundation.org>,
	"Arve Hjønnevåg" <arve@android.com>,
	"Todd Kjos" <tkjos@android.com>,
	"Christian Brauner" <brauner@kernel.org>,
	"Carlos Llamas" <cmllamas@google.com>, "Zi Yan" <ziy@nvidia.com>
Cc: linux-mm@kvack.org, rust-for-linux@vger.kernel.org,
	 linux-kernel@vger.kernel.org, driver-core@lists.linux.dev,
	 Andreas Hindborg <a.hindborg@kernel.org>
Subject: [PATCH 09/11] rust: page: add `Page::with_page_as_sysmem_local`
Date: Fri, 20 Nov 2026 11:27:08 +0100	[thread overview]
Message-ID: <20261120-page-shared-v1-9-66f8c4c62822@kernel.org> (raw)
In-Reply-To: <20261120-page-shared-v1-0-66f8c4c62822@kernel.org>

The data of a `Page<Shared>` is initialized and is not referenced by Rust
references, so it can be accessed safely with byte-wise atomic operations.
The existing accessors of `Page` are available for all page kinds and are
thus unsafe: a write can alias a slice obtained from a `Page<Exclusive>`.

Add the safe method `Page::with_page_as_sysmem_local()` for
`Page<Shared>`. It maps a range of the page and passes it to a closure as
a `SysMemLocal` view. The view is not `Send`, since the mapping that backs
it can be local to the current task.

A `Page<Exclusive>` does not dereference to a `Page<Shared>`, so the
method is not available for it.

Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
 rust/kernel/page.rs | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 85 insertions(+), 4 deletions(-)

diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs
index 85c710fa3dfd..7fa037f5938b 100644
--- a/rust/kernel/page.rs
+++ b/rust/kernel/page.rs
@@ -20,7 +20,8 @@
         Io,
         IoCopyable,
         SysMem,
-        SysMemBackend, //
+        SysMemBackend,
+        SysMemLocal, //
     },
     sync::aref::{
         self,
@@ -132,6 +133,8 @@ impl PageKind for Base {}
 ///
 /// The data of a [`Page<Shared>`] can be accessed concurrently by other parties, such as user
 /// space, devices or other kernel code. Thus, no Rust reference to the data of the page exists.
+/// The data is accessed with volatile or byte-wise atomic operations through a [`SysMemLocal`],
+/// see [`Page::with_page_as_sysmem_local`].
 ///
 /// A [`Page<RefCounted>`] and a [`Page<Frozen>`] dereference to a [`Page<Shared>`]. A page that
 /// is managed by other means can be referenced as a [`Page<Shared>`] with [`Page::from_raw`].
@@ -374,13 +377,14 @@ fn with_pointer_into_page<T>(
     /// Runs a piece of code with a range of this page mapped as a [`SysMem`] view.
     ///
     /// If `f` is called, then it is called with a view of the `len` bytes of the page that start
-    /// at `offset`. Accesses through the view are volatile or byte-wise atomic, so the view is
-    /// suitable for a page whose data is subject to concurrent writes by hardware or user space.
-    /// The view is valid for the duration of the call to `f`.
+    /// at `offset`. The view is valid for the duration of the call to `f`.
     ///
     /// If `offset` and `len` refer to a region outside of this page, then this method returns
     /// [`EINVAL`] and does not call `f`.
     ///
+    /// This is the building block for the accessors of [`Page`]. Use
+    /// [`Page::with_page_as_sysmem_local`] for safe access to the data of a [`Page<Shared>`].
+    ///
     /// # Safety
     ///
     /// * Callers must ensure that no plain access to the mapped range races with an access
@@ -658,6 +662,83 @@ pub unsafe fn copy_from_user_slice_raw(
     }
 }
 
+impl Page<Shared> {
+    /// Runs a piece of code with a range of this page mapped as a [`SysMemLocal`] view.
+    ///
+    /// If `f` is called, then it is called with a view of the `len` bytes of the page that start
+    /// at `offset`. Accesses through the view are volatile or byte-wise atomic, so the view is
+    /// suitable for a page whose data is subject to concurrent accesses by hardware, by user space
+    /// or by other kernel code. When an access races with a write, the data observed may be
+    /// arbitrary. The view is valid for the duration of the call to `f`.
+    ///
+    /// The view is not [`Send`], as it can be backed by a mapping that is local to the current
+    /// task.
+    ///
+    /// If `offset` and `len` refer to a region outside of this page, then this method returns
+    /// [`EINVAL`] and does not call `f`.
+    ///
+    /// This method is not available for a [`Page<Exclusive>`], as writing through the view would
+    /// violate the aliasing rules for the slices returned by [`Page::as_slice`] and
+    /// [`Page::as_mut_slice`].
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::{
+    ///     io::Io,
+    ///     page::Page, //
+    /// };
+    ///
+    /// let page = Page::alloc_page(GFP_KERNEL)?;
+    /// let mut buf = [0xffu8; 4];
+    ///
+    /// page.with_page_as_sysmem_local(8, 4, |view| {
+    ///     view.copy_to_slice(&mut buf);
+    ///     assert_eq!(buf, [0u8; 4]);
+    ///
+    ///     view.copy_from_slice(&[1, 2, 3, 4]);
+    ///     view.copy_to_slice(&mut buf);
+    ///     assert_eq!(buf, [1, 2, 3, 4]);
+    ///
+    ///     view.fill_zero();
+    ///     view.copy_to_slice(&mut buf);
+    ///     assert_eq!(buf, [0u8; 4]);
+    ///     Ok(())
+    /// })?;
+    /// # Ok::<(), Error>(())
+    /// ```
+    ///
+    /// Copy data from user space to a page:
+    ///
+    /// ```
+    /// use kernel::{
+    ///     page::Page,
+    ///     uaccess::UserSliceReader, //
+    /// };
+    ///
+    /// fn copy_to_page(page: &Page, reader: &mut UserSliceReader, len: usize) -> Result {
+    ///     page.with_page_as_sysmem_local(0, len, |view| reader.read_sysmem(view))
+    /// }
+    /// ```
+    pub fn with_page_as_sysmem_local<T>(
+        &self,
+        offset: usize,
+        len: usize,
+        f: impl FnOnce(SysMemLocal<'_, [u8]>) -> Result<T>,
+    ) -> Result<T> {
+        let f = move |mem: SysMem<'_, [u8]>| f(SysMemLocal::from(mem));
+
+        // SAFETY:
+        // - By the type invariant of `Page<Shared>`, no plain access to the data of the page races
+        //   with another access, and no Rust reference to the data of the page exists.
+        // - Safe code can only write initialized bytes through a `SysMemLocal`.
+        // - `f` converts the view to a `SysMemLocal` before it is used. A `SysMemLocal` is not
+        //   `Send` and it cannot outlive the call to `f`, so the view is only used on the current
+        //   task.
+        unsafe { self.with_page_as_sysmem(offset, len, f) }
+    }
+}
+
 // SAFETY: By the type invariant, a `Page<RefCounted>` is managed by the page reference count.
 // Incrementing it via `get_page()` keeps the page alive at least until a matching `put_page()`,
 // which frees the page when the count reaches zero.

-- 
2.54.0



  parent reply	other threads:[~2026-11-20 10:28 UTC|newest]

Thread overview: 12+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-20 10:26 [PATCH 00/11] rust: page: improve access methods for racy memory regions Andreas Hindborg
2026-11-20 10:27 ` [PATCH 01/11] rust: page: tighten safety requirements of `SysMem` copy methods Andreas Hindborg
2026-11-20 10:27 ` [PATCH 02/11] rust: sync: atomic: add memset Andreas Hindborg
2026-11-20 10:27 ` [PATCH 03/11] rust: io: add `SysMem::fill_zero` Andreas Hindborg
2026-11-20 10:27 ` [PATCH 04/11] rust: page: use byte-wise atomic operations in raw accessors Andreas Hindborg
2026-11-20 10:27 ` [PATCH 05/11] rust: uaccess: take a raw pointer in `UserSliceReader::read_raw` Andreas Hindborg
2026-11-20 10:27 ` [PATCH 06/11] rust: uaccess: add `UserSliceReader::read_sysmem` Andreas Hindborg
2026-11-20 10:27 ` [PATCH 07/11] rust: page: add `Shared` page kind Andreas Hindborg
2026-11-20 10:27 ` [PATCH 08/11] rust: io: add `SysMemLocal` Andreas Hindborg
2026-11-20 10:27 ` Andreas Hindborg [this message]
2026-11-20 10:27 ` [PATCH 10/11] rust_binder: access page data through `SysMemLocal` Andreas Hindborg
2026-11-20 10:27 ` [PATCH 11/11] rust: page: remove `Page::copy_from_user_slice_raw` Andreas Hindborg

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261120-page-shared-v1-9-66f8c4c62822@kernel.org \
    --to=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=arve@android.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=brauner@kernel.org \
    --cc=cmllamas@google.com \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=driver-core@lists.linux.dev \
    --cc=gary@garyguo.net \
    --cc=gregkh@linuxfoundation.org \
    --cc=liam@infradead.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-mm@kvack.org \
    --cc=ljs@kernel.org \
    --cc=lossin@kernel.org \
    --cc=lyude@redhat.com \
    --cc=mark.rutland@arm.com \
    --cc=ojeda@kernel.org \
    --cc=peterz@infradead.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=tamird@kernel.org \
    --cc=tkjos@android.com \
    --cc=tmgross@umich.edu \
    --cc=will@kernel.org \
    --cc=work@onurozkan.dev \
    --cc=ziy@nvidia.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox