Re: [PATCH v14 02/11] rust: add dma coherent allocator abstraction.
From: Boqun Feng
Date: Tue Mar 11 2025 - 14:14:42 EST
On Tue, Mar 11, 2025 at 07:47:58PM +0200, Abdiel Janulgue wrote:
[...]
> + /// Reads the value of `field` and ensures that its type is [`FromBytes`].
> + ///
> + /// # Safety
> + ///
> + /// This must be called from the [`dma_read`] macro which ensures that the `field` pointer is
> + /// validated beforehand.
> + ///
> + /// Public but hidden since it should only be used from [`dma_read`] macro.
> + #[doc(hidden)]
> + pub unsafe fn field_read<F: FromBytes>(&self, field: *const F) -> F {
> + // SAFETY: By the safety requirements field is valid.
> + unsafe { field.read_volatile() }
I agree with Andreas that we should document the exception of usage on
{read,write}_volatile() here. How about:
When dealing with a potential race from a hardware or code outside
kernel (e.g. user-space program), we need that read and write on a valid
memory are not UBs. Currently {read,write}_volatile() are used for this,
and the rationale behind is that they should generate the same code as
READ_ONCE() and WRITE_ONCE() which kernel already relies on to avoid UBs
on data races. Note that the usage of {read,write}_volatile() is limited
to this particular case, they cannot be used to emit the UBs caused by
racing between two kernel functions nor do they provide atomicity.
Thoughts? One problem is that I don't know where to put this document
:-( Any suggestion?
Regards,
Boqun
> + }
> +
> + /// Writes a value to `field` and ensures that its type is [`AsBytes`].
> + ///
> + /// # Safety
> + ///
> + /// This must be called from the [`dma_write`] macro which ensures that the `field` pointer is
> + /// validated beforehand.
> + ///
> + /// Public but hidden since it should only be used from [`dma_write`] macro.
> + #[doc(hidden)]
> + pub unsafe fn field_write<F: AsBytes>(&self, field: *mut F, val: F) {
> + // SAFETY: By the safety requirements field is valid.
> + unsafe { field.write_volatile(val) }
> + }
> +}
[...]