title: Read and Write atomic operation implementation in the Linux Kernel
body: <p>Recently I've peeked into the Linux kernel implementation of an atomic read and write and a few questions came up.</p>
  
  <p>First the relevant code from the ia64 architecture:</p>
  
  <pre><code>typedef struct {
      int counter;
  } atomic_t;
  
  #define atomic_read(v)      (*(volatile int *)&amp;(v)-&gt;counter)
  #define atomic64_read(v)    (*(volatile long *)&amp;(v)-&gt;counter)
  
  #define atomic_set(v,i)     (((v)-&gt;counter) = (i))
  #define atomic64_set(v,i)   (((v)-&gt;counter) = (i))
  </code></pre>
  
  <ol>
  <li><p>For both read and write operations, it seems that the direct approach was taken to read from or write to the variable. Unless there is another trick somewhere, I do not understand what guarantees exist that this operation will be atomic in the assembly domain. I guess  an obvious answer will be that such an operation translates to one assembly opcode, but even so, how is that guaranteed when taking into account the different memory cache levels (or other optimizations)?</p></li>
  <li><p>On the read macros, the volatile type is used in a casting trick. Anyone has a clue how this affects the atomicity here? (Note that it is not used in the write operation)</p></li>
  </ol>