Re: why are some atomic_t's not volatile, while most are?

Chris Snook
2007-08-07T21:44:20Z

Chris Friesen wrote:
> Chris Snook wrote:
>
>> But if you're not using SMP, the only way you get a race condition is
>> if your compiler is reordering instructions that have side effects
>> which are invisible to the compiler. This can happen with MMIO
>> registers, but it's not an issue with an atomic_t we're declaring in
>> real memory.
>
> I refer back to the interrupt handler case. Suppose we have:
>
> while(!atomic_read(flag))
> continue;
>
> where flag is an atomic_t that is set in an interrupt handler, the
> volatile may be necessary on some architectures to force the compiler to
> re-read "flag" each time through the loop.
>
> Without the "volatile", the compiler could be perfectly within its
> rights to evaluate "flag" once and create an infinite loop.
>
> Now I'm not trying to say that we should explictly use "volatile" in
> common code, but that it is possible that it is required within the
> arch-specific atomic_t accessors even on uniprocessor systems.
>
> Chris

That's why we define atomic_read like so:

#define atomic_read(v) ((v)->counter)

This avoids the aliasing problem, because the compiler must de-reference the
pointer every time, which requires a memory fetch. This is usually fast thanks
to caching, and hardware cache invalidation enforces correctness when it does
change.