On Tue Oct 28, 2025 at 10:18 PM CET, 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.

While I generally agree with this, the catch is that it would also enforce that
you would need a lock for calling dma_write!() in a concurrent context.

I.e. if your CoherentAllocation is shared between tasks we can currently have
the tasks calling dma_write!() and dma_read!() concurrently without requiring a
lock for the CoherentAllocation.

Requiring a spinlock for such a case wouldn't be the end of the world of course,
but it would still be unnecessary.

Reply via email to