Why is ACCESS_ONCE so complicated?

The Linux macro ACCESS_ONCE is defined as follows:

#define ACCESS_ONCE(x) (*(volatile typeof(x) *)&(x)) 

I understand what it does, but wondered why it is so complicated? I understand that he does the following:

  • Take the address (create a pace pointer) of the variable of concern
  • Drop this on a pointer of the same type
  • Cancel link to pointer

Any ideas why this is not implemented in a simpler way, say:

  #define ACCESS_ONCE(x) ((volatile typeof(x))(x)) 
+7
c linux-kernel
source share
3 answers

The ACCESS_ONCE macro is used in situations where a value is retrieved from a repository that is known (or suspected) that it is volatile, but not typed as such. The goal is to extract the current value of the storage location in such a way as to defeat the optimizing compiler, which otherwise could cache the value in the register or not provide the storage at all.

The construction, as it is written, applies “volatile” to the storage location indirectly, declaring a suitably typed pointer to this location. According to the C standard, this means that the object be evaluated strictly according to the rules of the abstract machine .

Your proposed change will not apply volatile to the storage location, so it will not achieve this goal. The search for values ​​can be optimized.

By the way, I see this as a brevity model for the stated purpose. I leave complex far worse than that.

+8
source share

Bringing variability into a "simple" variable is basically useless - it will not change the basic semantics of access, so this is not what you want.

0
source share

This explains the deep reason why the fill variable in volatile has no effects.

Casting a value to a qualified type does not affect; qualification (volatile, say) may not affect access, as it happened before the case. If you need to access a non-volatile object using mutable semantics, the method is to specify the address of the object to the corresponding pointer type, and then dereference this pointer.

-one
source share

All Articles