RE: [patch] spinlocks: remove 'volatile'

David Schwartz
2006-07-08T09:59:37Z

> On Fri, Jul 07, 2006 at 11:54:10PM -0400, Albert Cahalan wrote:
> > That's all theoretical though. Today, gcc's volatile does
> > not follow the C standard on modern hardware. Bummer.
> > It'd be low-performance anyway though.

> But gcc would follow the standard if it emitted a 'lock'
> insn on every volatile reference. It should at least
> have an option to do that.

The premise is wrong, therefore so is the conclusion. GCC does follow the C
standard on modern hardware. The 'volatile' keyword imposes the minimum
amount of pain necessary to get the two guarantees that 'volatile' is
supposed to provide. It has no special semantics on multiple CPUs, and was
never intended to have any.

The problem is that the C standard's definition of volatile is meaningless
on modern hardware (because there is no one clear true right place for
accesses to be visible, accesses occur in more than one place). All you can
do is make the cases where 'volatile has guaranteed semantics work.

There would be absolutely no point in having GCC have an option to emit a
locked instruction on every volatile reference because there would still be
no way to know what the right thing to lock is. For example:

volatile int i;
i=i+1;

Should this be a locked read, an increment in a register, followed by a
locked write? Or must this be a locked increment?

If you cannot explain in platform-independent terms the *semantics* the
option is supposed to give, then it's probably wrong. What happens when the
next CPU requires something different to get the same effect?

If you need atomic 32-bit loads, you know how to get them. If you need
atomic increments, you know how to get them. If you need memory optimization
barriers, you have them. Why ask for something new with vague,
poorly-defined semantics based on what 'lock' happens to do on current
processors? That just makes it easier to write non-portable code.

Now if you had asked for portable atomic loads, increments, stores, and the
like, that would be a sensible thing. It makes sense because you define what
behavior that function is supposed to give.

DS