Thread (121 messages) 121 messages, 13 authors, 2021-09-24

Re: [RFC] LKMM: Add volatile_if()

From: Peter Zijlstra <peterz@infradead.org>
Date: 2021-06-07 10:43:19
Also in: linux-toolchains, lkml

On Sun, Jun 06, 2021 at 11:43:42AM -0700, Linus Torvalds wrote:
So while the example code is insane and pointless (and you shouldn't
read *too* much into it), conceptually the notion of that pattern of

    if (READ_ONCE(a)) {
        WRITE_ONCE(b,1);
        .. do something ..
    } else {
        WRITE_ONCE(b,1);
        .. do something else ..
    }
This is actually more tricky than it would appear (isn't it always).

The thing is, that normally we must avoid speculative stores, because
they'll result in out-of-thin-air values.

*Except* in this case, where both branches emit the same store, then
it's a given that the store will happen and it will not be OOTA.
Someone's actually done the proof for that apparently (Will, you have a
reference to Jade's paper?)

There's apparently also a competition going on who can build the
weakestest ARM64 implementation ever.

Combine the two, and you'll get a CPU that *will* emit the store early
:/

So it might be prudent to make this pattern as difficult as possible (a
compiler implementation of volatile_if might be able to observe and WARN
about this).

How's something like (leaving the improved barrier() aside for now):

#define volatile_if(x) \
	if (!(({ _Bool __x = (x); BUILD_BUG_ON(__builtin_constant_p(__x)); __x; }) && \
	     ({ barrier(); 1; }))) { } else

That makes writing:

	volatile_if(READ_ONCE(a)) {
		WRITE_ONCE(b, 1);
		// something
	} else {
		WRITE_ONCE(b, 1);
		// something else
	}

A syntax error, due to volatile_if() already being an else. And yes,
there's plenty other ways to write the same :/
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help