Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Is ACCESS_ONCE so complex?

Tags:

c

linux-kernel

The Linux ACCESS_ONCE macro is defined as follows:

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

I understand what this does, but wondered why it is so complex ? My understanding is it does the following:

  1. Take address (create a temp pointer to) the variable of concern
  2. Cast this to a volatile pointer of the same type
  3. De-reference that pointer

Any ideas why this isn't implemented in a simpler fashion, say:

 #define ACCESS_ONCE(x) ((volatile typeof(x))(x))
like image 677
user3480510 Avatar asked Mar 31 '14 09:03

user3480510


1 Answers

The ACCESS_ONCE macro is used in situations where a value is being retrieved from a storage location that is known (or suspected) to be volatile, but is not typed as such. The purpose is to retrieve the current value of the storage location in such a way as to defeat an optimising compiler that might otherwise cache the value in a register, or not even provide a storage location at all.

The construct as written applies the 'volatile' to the storage location indirectly by declaring a suitably typed pointer to that location. As per the C standard, this mandates that the object be evaluated strictly according to the rules of the abstract machine.

Your proposed modification would not apply volatile to the storage location, so it would not achieve this purpose. The value retrieval could be subject to optimisation.

Incidentally, I regard this as a model of conciseness for the stated purpose. I reserve complex for far worse things than this.

like image 97
david.pfx Avatar answered Nov 14 '22 15:11

david.pfx