Linus on volatile

I'm referring to this thread on kerneltrap.org, where Linus is cited to be saying:
- in other words, the *only* possible meaning for "volatile" is a purely
single-CPU meaning. And if you only have a single CPU involved in the
process, the "volatile" is by definition pointless (because even
without a volatile, the compiler is required to make the C code appear
consistent as far as a single CPU is concerned).

He's absolutely wrong in his statement here (namely, that volatile is "by definition" pointless for a single CPU). The C99 standard says that any access to volatile object is a side-effect. This does not mean that compiler optimizations are effectively disabled; rather it means that the compiler must generate memory access instruction instead of caching the value in the register. [This is because accesses to volatile objects may produce side-effects, so the read value may change between reads without an intervening store instruction.]

Now, consider the following simple code in a uniprocessor configuration:
while(!flag) ;
which simply waits for the flag to become true (e.g. set by an interrupt handler). If flag is not declared as volatile, the compiler might well generate an infinite loop, but if the flag is declared as volatile, the compiler must generate code that will check the physical memory location in every iteration and thus the flag change from an interrupt handler will be detected.

So, volatile is important even on uniprocessors whenever there is a possibility of executing asynchronous code (e.g. interrupts). And its semantics is defined well enough to prevent errors like the one I have described above.

Oh well, I don't really care nor shall I bother to comment on this on the kernel mailing list. It's his kernel, I use it only on my desktop and I don't really care what future impact this change will have (and it might have far-reaching consequences that are really hard to discover; as any bugs related to asynchronicity). I have said long time ago that I'd never consider Linux for "serious" applications (i.e. anything else than a cheap desktop), and such displays of blatant ignorance by its leading developer just make my stand firmer.

1 comment:

Sitsofe said...

I don't think Linus is ignorant. If you read the entire message he puts (within the same message as your quote):

So if "volatile" makes a difference, it is invariably a sign of a bug in serialization (the one exception is for IO - we use "volatile" to avoid having to use inline asm for IO on x86) - and for "random values" like jiffies)

So clearly he is aware of its uses...