Re: [PATCH v11 2/3] rust: add dma coherent allocator abstraction.

Boqun Feng
2025-01-27T19:37:09Z

On Mon, Jan 27, 2025 at 11:21:52AM -0800, Boqun Feng wrote:
[...]
> > > Depending on the granularity that tearing can happen, if .foo is an enum
> > > (or any other type that not all bit combinations are valid) and tearing
> > > can happen at byte levels, then a racing dma_read() may read invalid
> > > data.
> >
> > T: FromBytes + ToBytes is already required for these types. You can't
> > use these operations with such an enum.
> >
>
> I was talking about a wider problem, but fine ;-) So the assumption is
> the read_volatile() or copy_nonoverlapping() provide byte-level
> atomicity? Although unlikely, but if tearing happens at sub-byte level,
> then even if `T: FromBytes + ToBytes` you can still get invalid data.
>

OK, `FromBytes + ToBytes` should tolerate sub-byte level tearing, so I
was wrong on this.

> > > I think it's fine to expect read_volatile() and write_volatile()
> > > themselves don't trigger UB, but we will need to be careful about the
> > > atomic granularity that we can expect on them. It would be more clear if
> > > we use the atomic API here (and implementation can be read_volatile()
> > > and write_volatile()), and it can avoid coding based on tribal knowledge
> > > such as "in kernel, read_volatile() and write_volatile() imply atomic".
> >
> > Why should we use atomics for operations that don't need to be atomic?

And yes, given the `FromBytes + ToBytes`, it looks like you don't need
any atomicity for the basic DMA read/write operation.

Regards,
Boqun

> > Most of the time, dma memory is not *actually* changed while you read
> > it.
> >
>
> Because the requirement here actually needs atomic at byte level, it's
> similar to:
>
> https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p1478r8.html
>
> also, notice that for byte level atomic, it's actually free on most of
> the architectures (i.e. no extra cost). Again, it's more of a "how do we
> express our assumption" question. If indeed we expect byte-level
> atomicity, then I see no harm to use atomic API here.
>
> Regards,
> Boqun
>
> > Alice