[PATCH v2 3/8] rust: uaccess: add UserSliceWriter::write_slice_partial()

Danilo Krummrich
2025-10-20T22:27:55Z

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.

Signed-off-by: Danilo Krummrich <dakr@kernel.org>
---
rust/kernel/uaccess.rs | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)

diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs
index 2061a7e10c65..40d47e94b54f 100644
--- a/rust/kernel/uaccess.rs
+++ b/rust/kernel/uaccess.rs
@@ -463,6 +463,30 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result {
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: file::Offset) -> Result<usize> {
+ if offset < 0 {
+ return Err(EINVAL);
+ }
+
+ let Ok(offset) = usize::try_from(offset) else {
+ return Ok(0);
+ };
+
+ let end = offset
+ .checked_add(self.len())
+ .unwrap_or(data.len())
+ .min(data.len());
+
+ data.get(offset..end)
+ .map_or(Ok(0), |src| self.write_slice(src).map(|()| 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
--
2.51.0