Re: [RFC] LKMM: Add volatile_if()

From: Alan Stern
Date: Fri Jun 04 2021 - 23:14:09 EST


On Fri, Jun 04, 2021 at 12:09:26PM -0700, Linus Torvalds wrote:
> Side note: it is worth noting that my version of "volatile_if()" has
> an added little quirk: it _ONLY_ orders the stuff inside the
> if-statement.
>
> I do think it's worth not adding new special cases (especially that
> "asm goto" hack that will generate worse code than the compiler could
> do), but it means that
>
> x = READ_ONCE(ptr);
> volatile_if (x > 0)
> WRITE_ONCE(*z, 42);
>
> has an ordering, but if you write it as
>
> x = READ_ONCE(ptr);
> volatile_if (x <= 0)
> return;
> WRITE_ONCE(*z, 42);
>
> then I could in theory see teh compiler doing that WRITE_ONCE() as
> some kind of non-control dependency.

This may be a minor point, but can that loophole be closed as follows?

define volatile_if(x) \
if ((({ _Bool __x = (x); BUILD_BUG_ON(__builtin_constant_p(__x)); __x; }) && \
({ barrier(); 1; })) || ({ barrier(); 0; }))

(It's now a little later at night than when I usually think about this
sort of thing, so my brain isn't firing on all its cylinders. Forgive
me if this is a dumb question.)

Alan