I was reading a section of kernel/timer.c file and came across this section which uses READ_ONCE and a comment which states that using READ_ONCE() prevents multiple reads by the compiler.
/*
* We need to use READ_ONCE() here, otherwise the compiler
* might re-read @tf between the check for TIMER_MIGRATING
* and spin_lock().
*/
tf = READ_ONCE(timer->flags);
if (!(tf & TIMER_MIGRATING)) {
base = get_timer_base(tf);
raw_spin_lock_irqsave(&base->lock, *flags);
if (timer->flags == tf)
return base;
I then found this question on SO: Can a compiler read twice from a global variable, instead of storing a local one?
which tells, that the compiler will indeed read the global variable multiple times. However, in this case, a shared global variable is assigned to a local non volatile variable. As per this question: $tf can also not be elided. So since they are assigning a volatile variable (flags) to a non-volatile variable ($tf), does the properties of volatile transfer to a non-volatile variable ($tf) as well, so that $tf can also be prevented from re-reads ?