]> git.ipfire.org Git - thirdparty/linux.git/commitdiff
rust: uaccess: add UserSliceReader::read_slice_partial()
authorDanilo Krummrich <dakr@kernel.org>
Wed, 22 Oct 2025 14:30:36 +0000 (16:30 +0200)
committerDanilo Krummrich <dakr@kernel.org>
Tue, 4 Nov 2025 23:35:20 +0000 (00:35 +0100)
The existing read_slice() method is a wrapper around copy_from_user()
and expects the user buffer to be larger than the destination buffer.

However, userspace may split up writes in multiple partial operations
providing an offset into the destination buffer and a smaller user
buffer.

In order to support this common case, provide a helper for partial
reads.

Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Matthew Maurer <mmaurer@google.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Acked-by: Miguel Ojeda <ojeda@kernel.org>
[ Replace map_or() with let-else; use saturating_add(). - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
rust/kernel/uaccess.rs

index a8fb4764185a1a2fc84b1e5394b0a1fe74410722..1409cb907015734ce1b7625a138ee6551ebd6540 100644 (file)
@@ -287,6 +287,23 @@ impl UserSliceReader {
         self.read_raw(out)
     }
 
+    /// Reads raw data from the user slice into a kernel buffer partially.
+    ///
+    /// This is the same as [`Self::read_slice`] but considers the given `offset` into `out` and
+    /// truncates the read to the boundaries of `self` and `out`.
+    ///
+    /// On success, returns the number of bytes read.
+    pub fn read_slice_partial(&mut self, out: &mut [u8], offset: usize) -> Result<usize> {
+        let end = offset.saturating_add(self.len()).min(out.len());
+
+        let Some(dst) = out.get_mut(offset..end) else {
+            return Ok(0);
+        };
+
+        self.read_slice(dst)?;
+        Ok(dst.len())
+    }
+
     /// Reads a value of the specified type.
     ///
     /// Fails with [`EFAULT`] if the read happens on a bad address, or if the read goes out of