Re: [PATCH v6 4/9] rust: sync: atomic: Add generic atomics

Boqun Feng
2025-07-11T13:22:52Z

On Fri, Jul 11, 2025 at 10:03:07AM +0200, Benno Lossin wrote:
[...]
> > +
> > + /// Returns a pointer to the underlying atomic variable.
> > + ///
> > + /// Extra safety requirement on using the return pointer: the operations done via the pointer
> > + /// cannot cause data races defined by [`LKMM`].
>
> I don't think this is correct. I could create an atomic and then share
> it with the C side via this function, since I have exclusive access, the
> writes to this pointer don't need to be atomic.
>

that's why it says "the operations done via the pointer cannot cause
data races .." instead of saying "it must be atomic".

> We also don't document additional postconditions like this... If you

Please see how Rust std document their `as_ptr()`:

https://doc.rust-lang.org/std/sync/atomic/struct.AtomicI32.html#method.as_ptr

It mentions that "Doing non-atomic reads and writes on the resulting
integer can be a data race." (although the document is a bit out of
date, since non-atomic read and atomic read are no longer data race now,
see [1])

I think we can use the similar document structure here: providing more
safety requirement on the returning pointers, and...

> really would have to do it like this (which you shouldn't given the
> example above), you would have to make this function `unsafe`, otherwise
> there is no way to ensure that people adhere to it (since it isn't part
> of the safety docs).
>

...since dereferencing pointers is always `unsafe`, users need to avoid
data races anyway, hence this is just additional information that helps
reasoning.

Regards,
Boqun

> > + ///
> > + /// [`LKMM`]: srctree/tools/memory-model
> > + pub const fn as_ptr(&self) -> *mut T {
> > + self.0.get()
> > + } …