Re: [PATCH] rust/dma: Take &mut self in CoherentAllocation::field_write()

From: Alice Ryhl

Date: Tue Oct 28 2025 - 17:52:44 EST


On Tue, Oct 28, 2025 at 05:18:01PM -0400, Lyude Paul wrote:
> At the moment - CoherentAllocation::field_write() only takes an immutable
> reference to self. This means it's possible for a user to mistakenly call
> field_write() while Rust still has a slice taken out for the coherent
> allocation:
>
> let alloc: CoherentAllocation<CoolStruct> = /* … */;
>
> let evil_slice = unsafe { alloc.as_slice(/* … */)? };
> dma_write!(alloc[1].cool_field = 42); /* UB! */
>
> Keep in mind: the above example is technically a violation of the safety
> contract of as_slice(), so luckily this detail shouldn't currently be
> causing any UB in the kernel. But, there's no reason we should be solely
> relying on the safety contract for enforcing this when we can just use a
> mutable reference and already do so in other parts of the API.
>
> Signed-off-by: Lyude Paul <lyude@xxxxxxxxxx>
> Cc: Danilo Krummrich <dakr@xxxxxxxxxx>

Didn't we do this intentionally so that it's possible to write to
different parts of the allocation without protecting the entire region
with a lock?

Alice