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

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

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

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 dde8a0abb46d3274226014053e64578c6697fa16..38d1404ed9b4c2733e4b63eb488843b630b7efe8 100644 (file)
@@ -481,6 +481,23 @@ impl UserSliceWriter {
         Ok(())
     }
 
+    /// Writes raw data to this user pointer from a kernel buffer partially.
+    ///
+    /// This is the same as [`Self::write_slice`] but considers the given `offset` into `data` and
+    /// truncates the write to the boundaries of `self` and `data`.
+    ///
+    /// On success, returns the number of bytes written.
+    pub fn write_slice_partial(&mut self, data: &[u8], offset: usize) -> Result<usize> {
+        let end = offset.saturating_add(self.len()).min(data.len());
+
+        let Some(src) = data.get(offset..end) else {
+            return Ok(0);
+        };
+
+        self.write_slice(src)?;
+        Ok(src.len())
+    }
+
     /// Writes the provided Rust value to this userspace pointer.
     ///
     /// Fails with [`EFAULT`] if the write happens on a bad address, or if the write goes out of