9

I'm studying Linux kernel with Linux Kernel Development by Robert Love.

As you know, this book uses old version of Linux. It's in 2.6 version

atomic_t has "volatile int counter". But newly Linux version's atomic_t has "int counter" not volatile. Why this volatile has erased?

A.Cho
  • 571
  • 1
  • 6
  • 17
  • Maybe because it is not sufficient in a multi-CPU system? Or maybe because the API has changed? Get a more recent ressource, the Linux kernel has no fixed internal API. – too honest for this site Jan 12 '16 at 15:26
  • Also see [Why is volatile needed in C?](https://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c) and related. – edmz Jan 12 '16 at 20:31

1 Answers1

10

Because volatile variables are not atomic variables. The only point in using volatile is to prevent possible compiler optimisations, which is not the same as preventing unwanted concurrent access.

In that regard, the use of volatile is almost never correct.

You can read more about it in Semantics and Behavior of Atomic and Bitmask Operations.

Quoting a small part of it:

* WARNING: atomic_read() and atomic_set() DO NOT IMPLY BARRIERS! *

Some architectures may choose to use the volatile keyword, barriers, or inline assembly to guarantee some degree of immediacy for atomic_read() and atomic_set(). This is not uniformly guaranteed, and may change in the future, so all users of atomic_t should treat atomic_read() and atomic_set() as simple C statements that may be reordered or optimized away entirely by the compiler or processor, and explicitly invoke the appropriate compiler and/or memory barrier for each use case. Failure to do so will result in code that may suddenly break when used with different architectures or compiler optimizations, or even changes in unrelated code which changes how the compiler optimizes the section accessing atomic_t variables.

* YOU HAVE BEEN WARNED! *

Uwe Geuder
  • 2,236
  • 1
  • 15
  • 21
jweyrich
  • 31,198
  • 5
  • 66
  • 97
  • Thank you. But then, I want to know why kernel use struct for int variable. I mean why not just use "atomic_t counter;"(if int is type defined as atomic_t) rather atomic_t structure which only has one varaible:"int counter"? – A.Cho Jan 12 '16 at 16:00
  • 2
    According to the document I pointed, the reason they wrap the variable in a struct and define it as a type is to prevent any kind of cast to a normal C integer type. – jweyrich Jan 12 '16 at 16:06