On Thu Jan 29, 2026 at 2:28 AM GMT, Timur Tabi wrote:
> Add UserSliceWriter::write_dma() to copy data from a CoherentAllocation<u8>
> to userspace. This provides a safe interface for copying DMA buffer
> contents to userspace without requiring callers to work with raw pointers.
>
> The method handles bounds checking and offset calculation internally,
> wrapping the unsafe copy_to_user() call.
>
> Signed-off-by: Timur Tabi <[email protected]>
> ---
> rust/kernel/uaccess.rs | 41 +++++++++++++++++++++++++++++++++++++++++
> 1 file changed, 41 insertions(+)
>
> diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs
> index f989539a31b4..f9bb88e47408 100644
> --- a/rust/kernel/uaccess.rs
> +++ b/rust/kernel/uaccess.rs
> @@ -7,6 +7,7 @@
> use crate::{
> alloc::{Allocator, Flags},
> bindings,
> + dma::CoherentAllocation,
> error::Result,
> ffi::{c_char, c_void},
> fs::file,
> @@ -481,6 +482,46 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result {
> Ok(())
> }
>
> + /// Writes raw data to this user pointer from a DMA coherent allocation.
> + ///
> + /// Returns error if the offset+count exceeds the allocation size.
> + ///
> + /// Fails with [`EFAULT`] if the write happens on a bad address, or if
> the write goes out of
> + /// bounds of this [`UserSliceWriter`]. This call may modify the
> associated userspace slice
> + /// even if it returns an error.
> + ///
> + /// Note: The memory may be concurrently modified by hardware (e.g.,
> DMA). In such cases,
> + /// the copied data may be inconsistent, but this does not cause
> undefined behavior.
> + pub fn write_dma(
> + &mut self,
> + alloc: &CoherentAllocation<u8>,
> + offset: usize,
> + count: usize,
> + ) -> Result {
> + let len = alloc.count();
> + if offset.checked_add(count).ok_or(EOVERFLOW)? > len {
> + return Err(ERANGE);
> + }
> +
> + // SAFETY: `start_ptr()` returns a valid pointer to a memory region
> of `count()` bytes,
> + // as guaranteed by the `CoherentAllocation` invariants. The check
> above ensures
> + // `offset + count <= len`.
> + let src_ptr = unsafe { alloc.start_ptr().add(offset) };
> +
> + // SAFETY: `src_ptr` is valid for reads of `count` bytes per the
> above.
> + let res = unsafe {
> + bindings::copy_to_user(self.ptr.as_mut_ptr(),
> src_ptr.cast::<c_void>(), count)
> + };
You're not checking `count` against `self.length` in this function, so you
perform an OOB write to userspace memory.
Best,
Gary
> + if res != 0 {
> + return Err(EFAULT);
> + }
> +
> + self.ptr = self.ptr.wrapping_byte_add(count);
> + self.length -= count;
> +
> + 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