Sunday, 24 July 2011

Memory Barriers/Fences

In this article I'll discuss the most fundamental technique in concurrent programming known as memory barriers, or fences, that make the memory state within a processor visible to other processors.

CPUs have employed many techniques to try and accommodate the fact that CPU execution unit performance has greatly outpaced main memory performance.  In my “Write Combining” article I touched on just one of these techniques.  The most common technique employed by CPUs to hide memory latency is to pipeline instructions and then spend significant effort, and resource, on trying to re-order these pipelines to minimise stalls related to cache misses.

When a program is executed it does not matter if its instructions are re-ordered provided the same end result is achieved.  For example, within a loop it does not matter when the loop counter is updated if no operation within the loop uses it.  The compiler and CPU are free to re-order the instructions to best utilise the CPU provided it is updated by the time the next iteration is about to commence.  Also over the execution of a loop this variable may be stored in a register and never pushed out to cache or main memory, thus it is never visible to another CPU.

CPU cores contain multiple execution units.  For example, a modern Intel CPU contains 6 execution units which can do a combination of arithmetic, conditional logic, and memory manipulation.  Each execution unit can do some combination of these tasks.  These execution units operate in parallel allowing instructions to be executed in parallel.  This introduces another level of non-determinism to program order if it was observed from another CPU.

Finally, when a cache-miss occurs, a modern CPU can make an assumption on the results of a memory load and continue executing based on this assumption until the load returns the actual data.

Provided “program order” is preserved the CPU, and compiler, are free to do whatever they see fit to improve performance.

Figure 1.

Loads and stores to the caches and main memory are buffered and re-ordered using the load, store, and write-combining buffers.  These buffers are associative queues that allow fast lookup.  This lookup is necessary when a later load needs to read the value of a previous store that has not yet reached the cache.  Figure 1 above depicts a simplified view of a modern multi-core CPU.  It shows how the execution units can use the local registers and buffers to manage memory while it is being transferred back and forth from the cache sub-system.

In a multi-threaded environment techniques need to be employed for making program results visible in a timely manner.  I will not cover cache coherence in this article.  Just assume that once memory has been pushed to the cache then a protocol of messages will occur to ensure all caches are coherent for any shared data.  The techniques for making memory visible from a processor core are known as memory barriers or fences.

Memory barriers provide two properties.  Firstly, they preserve externally visible program order by ensuring all instructions either side of the barrier appear in the correct program order if observed from another CPU and, secondly, they make the memory visible by ensuring the data is propagated to the cache sub-system.

Memory barriers are a complex subject.  They are implemented very differently across CPU architectures.  At one end of the spectrum there is a relatively strong memory model on Intel CPUs that is more simple than say the weak and complex memory model on a DEC Alpha with its partitioned caches in addition to cache layers.  Since x86 CPUs are the most common for multi-threaded programming I’ll try and simplify to this level.

Store Barrier
A store barrier, “sfence” instruction on x86, forces all store instructions prior to the barrier to happen before the barrier and have the store buffers flushed to cache for the CPU on which it is issued.  This will make the program state visible to other CPUs so they can act on it if necessary.  A good example of this in action is the following simplified code from the BatchEventProcessor in the Disruptor.  When the sequence is updated other consumers and producers know how far this consumer has progressed and thus can take appropriate action.  All previous updates to memory that happened before the barrier are now visible.
private volatile long sequence = RingBuffer.INITIAL_CURSOR_VALUE;

// from inside the run() method

T event = null;
long nextSequence = sequence.get() + 1L;
while (running)
{
    try
    {
        final long availableSequence = barrier.waitFor(nextSequence);

        while (nextSequence <= availableSequence)
        {
            event = ringBuffer.get(nextSequence);
            boolean endOfBatch = nextSequence == availableSequence;
            eventHandler.onEvent(event, nextSequence, endOfBatch);
            nextSequence++;
        }

        sequence.set(nextSequence - 1L); 
        // store barrier inserted here !!!
    }
    catch (final Exception ex)
    {
        exceptionHandler.handle(ex, nextSequence, event);
        sequence.set(nextSequence);
        // store barrier inserted here !!!
        nextSequence++;
    }
}
Load Barrier
A load barrier, “lfence” instruction on x86, forces all load instructions after the barrier to happen after the barrier and then wait on the load buffer to drain for that CPU.  This makes program state exposed from other CPUs visible to this CPU before making further progress.  A good example of this is when the BatchEventProcessor sequence referenced above is read by producers, or consumers, in the corresponding barriers of the Disruptor.

Full Barrier
A full barrier, "mfence" instruction on x86, is a composite of both load and store barriers happening on a CPU.

Java Memory Model
In the Java Memory Model a volatile field has a store barrier inserted after a write to it and a load barrier inserted before a read of it.  Qualified final fields of a class have a store barrier inserted after their initialisation to ensure these fields are visible once the constructor completes when a reference to the object is available.

Atomic Instructions and Software Locks
Atomic instructions, such as the “lock ...” instructions on x86, are effectively a full barrier as they lock the memory sub-system to perform an operation and have guaranteed total order, even across CPUs.  Software locks usually employ memory barriers, or atomic instructions, to achieve visibility and preserve program order.

Performance Impact of Memory Barriers
Memory barriers prevent a CPU from performing a lot of techniques to hide memory latency therefore they have a significant performance cost which must be considered.  To achieve maximum performance it is best to model the problem so the processor can do units of work, then have all the necessary memory barriers occur on the boundaries of these work units.  Taking this approach allows the processor to optimise the units of work without restriction.  There is an advantage to grouping necessary memory barriers in that buffers flushed after the first one will be less costly because no work will be under way to refill them.

20 comments:

  1. Hi Martin,

    I read the artical serval times but I still feel I didn't fully understand when we need a memory barrier. Let's take simple example (single reader single writer circular buffer), can you please help me identify where and why we need memory barriers?

    static const std::size_t N = 1024;
    static const uint64_t read = 0;
    static const uint64_t write = 0;
    T buffer[N];

    //writer:
    while(true) {
    do {
    //W1
    } while (write - read == N);
    produce(buffer[write & N]);
    //W2
    ++write;
    //W3
    }

    //reader:
    while(true) {
    do {
    //R1
    } while (read==write);
    consume(buffer[read & N]);
    //R2
    ++read;
    //R3
    }

    I am wondering if we need memory barrier on:
    //W1 to make sure we get the latest value of variable "read"?
    //W2 to make sure that the value in buffer[write & N] is seen by reader before the variable "write" is updated?
    //W3 to make the variable "write" observable by reader?
    How about reader?

    Thank you!

    ReplyDelete
  2. Hi,

    On x64 you need an mfence after, or better still do a "lock addq" on, the read and write variables when incrementing. That is at point W3 and R3 in your code. Note R3 needs to be a mfence or sfence and not a lfence.

    You need this because you want to ensure the "produce(buffer[write & N])" happens before updating the counter to make it visible. By the way N needs to be N - 1 for the mask to work in your code.

    If you are on a weaker memory model than x64 you would need a load barrier at W1 and R1.

    Hope this helps.

    Martin...

    ReplyDelete
  3. Thanks Martin.
    "You need this because you want to ensure the "produce(buffer[write & N])" happens before updating the counter to make it visible."
    Are you talking about mem barrier at W2 and R2?

    ReplyDelete
  4. You need W3, don't need W2, on the producer side to make both the production of the item in the buffer and the write sequence increment visible in the correct order.

    You need the R3 to be a store barrier to ensure the producer can see the progress of the consumer without over running it.

    W2 and R2 are not needed on any architecture. W1 and R1 might be needed as load barriers on some architectures.

    ReplyDelete
    Replies
    1. Hi Martin,

      I don't understand why W2 wouldn't be necessary in Xin Wang's above.

      My understanding is (and it could very well be wrong) that the sfence instruction makes store instructions preceding the sfence globally visible before store instructions that follow the sfence. In Xin's example, we have to be sure that the produced data is globally visible before the incremented counter is visible. If we don't put an sfence between these stores, isn't there a risk that the reader is seeing the incremented counter before the new data in the buffer? Putting the fence after counter is incremented only makes sure that the counter is visible before any stores following the counter increment, but that is not really what we need here.

      Delete
    2. You are correct, my mistake.

      It should be noted that on x86_64 there is no need for a hardware memory barrier at all because the code respects the Single Writer Principle. Other platforms are different!

      However this does not make any guarantees about the compiler when we go with C/C++. This code needs the synchronisation variables to be declared volatile and access to be wrapped using functions like the following:

      /*
      * Load a sequence and ensure instructions after, happen after.
      */
      static inline int64 load_acquire(volatile int64* sequencePtr)
      {
      int64 sequence = *sequencePtr;
      __asm__ __volatile__("" ::: "memory");
      return sequence;
      }

      /*
      * Store a sequence and ensure previous stores, happen before.
      */
      static inline void store_release(volatile int64* sequencePtr, int64 sequence)
      {
      __asm__ __volatile__("" ::: "memory");
      *sequencePtr = sequence;
      }

      Delete
    3. Is x86 hotspot using the above fences? Looks to me more like a xchgq
      http://hg.openjdk.java.net/jdk7/jdk7/hotspot/file/4fc084dac61e/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp

      Delete
    4. The release_store options are just memory stores if you look at the code. Depending on what compiler and setting are used this may be an issue. The XCHG(implicit lock instruction) is not used in the release_store methods in the linked file. The store_release will simply generate a MOV instruction which is sufficient for the hardware memory model. The ASM example I give above is a directive to GCC to not reorder the code.

      Delete
  5. Hi Martin, I am still a little confused:
    To ensure "produce(buffer(write & (N-1))" happens before the updated counter is visible, shouldn't we insert a store barrier between producer() and ++write?
    Can you please recommend some articles or books if I want to learn the memory model/memory barrier?

    ReplyDelete
  6. It is not necessary to have a memory barrier on every line. Memory barriers are used to create reference points when you can determine an order. The memory model is different for most CPUs. The link below is for the Intel x64 processors which is one of the more simple to understand. Others such as the Dec Alpha, on which the Linux memory model is based, are much more complicated. The more complex models are usually a super set of the less complex models.

    http://www.multicoreinfo.com/research/papers/2008/damp08-intel64.pdf

    The CPU manufactures publish their memory models so compiler writers can understand them.

    ReplyDelete
  7. Hi Martin,

    Regarding your comment:

    "You need this because you want to ensure the "produce(buffer[write & N])" happens before updating the counter to make it visible. By the way N needs to be N - 1 for the mask to work in your code."

    The Intel x86 memory orderding is saying that "Writes by a single processor are observed in the same order by all processors". I am not sure how to interpret this, but I would think that it's guaranteed that these two writes are observed in the same order by other processers on Intel x86 without a fence:

    produce(buffer[write & N]);
    ++write;

    I have spent quote some time reading Intel x86 documentation and but a bit confused. Because of all guarantee that Intel x86 gives us I don't see applicability of sfence except for the case to prevent reordering loads with older stores.

    Thank you!

    ReplyDelete
    Replies
    1. Siarhei,

      You are correct in that a fence is not required on x86 if you are sure a variable only has a single writer. It is required if you have multiple writers. This is because the store buffer needs flushed so you see the latest value and not your own last write. Other processors don't have such a strong memory model, e.g. ARM, MIPS and ALPHA. From Java you have limited options to make sure a variable is not register allocated. If it is register allocated in a loop, then it may not be made visible. To get around this the variable needs to be declared volatile, therefore generating a lock instruction with a fence. There is a trick that works with Atomic*.lazySet() but this is not officially defined in the Java memory model.

      Delete
    2. Martin,

      My understanding is that the Atomic*.lazySet() only prevents a variable from being register allocated and does not use a fence. Is it correct?

      Thank you!

      Delete
    3. Siarhei,

      Atomic*.lazySet() not only prevents the variable being register allocated it also imposing ordering. This ordering is only at a software level as there is no explicit hardware fence. If you follow the code down into unsafe it calls putOrdered*().

      Delete
    4. Hi Martin,
      as you said above about multiple writers,only the barrier-w3 can ensure "buffer[write & N])" and "++write" be executed in a atomic way? I think the 2 lines are in a Critical Section.

      Delete
    5. Jimmy,

      The above algorithm will only work with single producer and single consumer. Multiple writers of the "++write" would result in a corrupt sequence.

      Delete
  8. Hi Martin,

    Does the barrier just work on a specific field(by volatile modifier), or all the memory in cache?

    "A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking. " (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html)

    So it says here it can only guarantee the visibility of the volatile fields.

    Also I'm reading the white paper of Distruptor, it seems it just rely on the ProducerBarrier and ConsumerBarrier to guarantee the visibility on ValueEntry.
    Just wonder if my understanding to the description in javadoc is wrong, or this is an implementation specific behavior of oracle jdk.

    ReplyDelete
    Replies
    1. The barrier is associated with release and subsequent acquire of a specific field. What this means is that when you write the volatile field then all writes before that write in program order are visible to any thread that observes the write when they read the field. This is defined in the Java Memory Model for all JVM from Java 5 onwards.

      Delete
  9. Fantastic article! I have read a few of your articles. They are high quality and great for learning about low level architectures.

    ReplyDelete
  10. Hi, thank you for this article. I think you succeed to explain simply these complex things. It reminded me some details I forgot because I don't use them in my daily work.

    ReplyDelete