<?xml version="1.0" encoding="UTF-8" standalone="yes"?><oembed><version><![CDATA[1.0]]></version><provider_name><![CDATA[The ryg blog]]></provider_name><provider_url><![CDATA[https://fgiesen.wordpress.com]]></provider_url><author_name><![CDATA[fgiesen]]></author_name><author_url><![CDATA[https://fgiesen.wordpress.com/author/fgiesen/]]></author_url><title><![CDATA[Cache coherency primer]]></title><type><![CDATA[link]]></type><html><![CDATA[<p>I&#8217;m planning to write a bit about data organization for multi-core scenarios. I started writing a first post but quickly realized that there are a few basics I need to cover first. In this post, I&#8217;ll try just that.</p>
<h3>Caches</h3>
<p>This is a whirlwhind primer on CPU caches. I&#8217;m assuming you know the basic concept, but you might not be familiar with some of the details. (If you are, feel free to skip this section.)</p>
<p>In modern CPUs (almost) all memory accesses go through the cache hierarchy; there are some exceptions for memory-mapped IO and write-combined memory that bypass at least parts of this process, but both of these are corner cases (in the sense that the vast majority of user-mode code will never see either), so I&#8217;ll ignore them in this post.</p>
<p>The CPU core&#8217;s load/store (and instruction fetch) units normally can&#8217;t even access memory directly &#8211; it&#8217;s physically impossible; the necessary wires don&#8217;t exist! Instead, they talk to their L1 caches which are supposed to handle it. And about 20 years ago, the L1 caches would indeed talk to memory directly. At this point, there&#8217;s generally more cache levels involved; this means the L1 cache doesn&#8217;t talk to memory directly anymore, it talks to a L2 cache &#8211; which in turns talks to memory. Or maybe to a L3 cache. You get the idea.</p>
<p>Caches are organized into &#8220;lines&#8221;, corresponding to aligned blocks of either 32 (older ARMs, 90s/early 2000s x86s/PowerPCs), 64 (newer ARMs and x86s) or 128 (newer Power ISA machines) bytes of memory. Each cache line knows what physical memory address range it corresponds to, and in this article I&#8217;m not going to differentiate between the physical cache line and the memory it represents &#8211; this is sloppy, but conventional usage, so better get used to it. In particular, I&#8217;m going to say &#8220;cache line&#8221; to mean a suitably aligned group of bytes in memory, no matter whether these bytes are currently cached (i.e. present in any of the cache levels) or not.</p>
<p>When the CPU core sees a memory load instruction, it passes the address to the L1 data cache (or &#8220;L1D$&#8221;, playing on the &#8220;cache&#8221; being pronounced the same way as &#8220;cash&#8221;). The L1D$ checks whether it contains the corresponding cache line. If not, the whole cache line is brought in from memory (or the next-deeper cache level, if present) &#8211; yes, the whole cache line; the assumption being that memory accesses are localized, so if we&#8217;re looking at some byte in memory we&#8217;re likely to access its neighbors soon. Once the cache line is present in the L1D$, the load instruction can go ahead and perform its memory read.</p>
<p>And as long as we&#8217;re dealing with read-only access, it&#8217;s all really simple, since all cache levels obey what I&#8217;ll call the</p>
<blockquote><p><b>Basic invariant</b>: the contents of all cache lines present in any of the cache levels are identical to the values in memory at the corresponding addresses, at all times.</p></blockquote>
<p>Things gets a bit more complicated once we allow stores, i.e. memory writes. There&#8217;s two basic approaches here: write-through and write-back. Write-through is the easier one: we just pass stores through to the next-level cache (or memory). If we have the corresponding line cached, we update our copy (or maybe even just discard it), but that&#8217;s it. This preserves the same invariant as before: if a cache line is present in the cache, its contents match memory, always.</p>
<p>Write-back is a bit trickier. The cache doesn&#8217;t pass writes on immediately. Instead, such modifications are applied locally to the cached data, and the corresponding cache lines are flagged &#8220;dirty&#8221;. Dirty cache lines can trigger a write-back, at which points their contents are written back to memory or the next cache level. After a write-back, dirty cache lines are &#8220;clean&#8221; again. When a dirty cache line is evicted (usually to make space for something else in the cache), it always needs to perform a write-back first. The invariant for write-back caches is slightly different.</p>
<blockquote><p><b>Write-back invariant</b>: <em>after writing back all dirty cache lines</em>, the contents of all cache lines present in any of the cache levels are identical to the values in memory at the corresponding addresses.</p></blockquote>
<p>In other words, in write-back caches we lose the &#8220;at all times&#8221; qualifier and replace it with a weaker condition: either the cache contents match memory (this is true for all clean cache lines), or they contain values that eventually need to get written back to memory (for dirty cache lines).</p>
<p>Write-through caches are simpler, but write-back has some advantages: it can filter repeated writes to the same location, and if most of the cache line changes on a write-back, it can issue one large memory transaction instead of several small ones, which is more efficient.</p>
<p>Some (mostly older) CPUs use write-through caches everywhere; some use write-back caches everywhere; some have a simpler write-through L1$ backed by a write-back L2$. This may generate redundant traffic between L1$ and L2$ but gets the write-back benefits for transfers to lower cache levels or memory. My point being that there&#8217;s a whole set of trade-offs here, and different designs use different solutions. Nor is there a requirement that cache line sizes be the same at all levels &#8211; it&#8217;s not unheard-of for CPUs to have 32-byte lines in L1$ but 128-byte lines in L2$ for example.</p>
<p>Omitted for simplicity in this section: cache associativity/sets; write-allocate or not (I described write-through without write-allocate and write-back with, which is the most common usage); unaligned accesses; virtually-addressed caches. These are all things you can look up if you&#8217;re interested, but I&#8217;m not going to go that deep here.</p>
<h3>Coherency protocols</h3>
<p>As long as that single CPU core is alone in the system, this all works just fine. Add more cores, each with their own caches, and we have a problem: what happens if some other core modifies data that&#8217;s in one of our caches?</p>
<p>Well, the answer is quite simple: nothing happens. And that&#8217;s bad, because we <em>want</em> something to happen when someone else modifies memory that we have a cached copy of. Once we have multiple caches, we really need to keep them synchronized, or we don&#8217;t really have a &#8220;shared memory&#8221; system, more like a &#8220;shared general idea of what&#8217;s in memory&#8221; system.</p>
<p>Note that the problem really is that we have multiple caches, not that we have multiple cores. We could solve the entire problem by sharing all caches between all cores: there&#8217;s only one L1$, and all processors have to share it. Each cycle, the L1$ picks one lucky core that gets to do a memory operation this cycle, and runs it.</p>
<p>This works just fine. The only problem is that it&#8217;s also slow, because cores now spend most of their time waiting in line for their next turn at a L1$ request (and processors do a <em>lot</em> of those, at least one for every load/store instruction). I&#8217;m pointing this out because it shows that the problem really isn&#8217;t so much a multi-<em>core</em> problem as it is a multi-<em>cache</em> problem. We know that one set of caches works, but when that&#8217;s too slow, the next best thing is to have multiple caches and then make them behave <em>as if</em> there was only one cache. This is what cache coherency protocols are for: as the name suggests, they ensure that the contents of multiple caches stay coherent.</p>
<p>There are multiple types of coherency protocols, but most computing devices you deal with daily fall into the category of &#8220;snooping&#8221; protocols, and that&#8217;s what I&#8217;ll cover here. (The primary alternative, directory-based systems, has higher latency but scales better to systems with lots of cores).</p>
<p>The basic idea behind snooping is that all memory transactions take place on a shared bus that&#8217;s visible to all cores: the caches themselves are independent, but memory itself is a shared resource, and memory access needs to be arbitrated: only one cache gets to read data from, or write back to, memory in any given cycle. Now the idea in a snooping protocol is that the caches don&#8217;t just interact with the bus when they want to do a memory transaction themselves; instead, each cache continuously snoops on bus traffic to keep track of what the other caches are doing. So if one cache wants to read from or write to memory on behalf of its core, all the other cores notice, and that allows them to keep their caches synchronized. As soon as one core writes to a memory location, the other cores know that their copies of the corresponding cache line are now stale and hence invalid.</p>
<p>With write-through caches, this is fairly straightforward, since writes get &#8220;published&#8221; as soon as they happen. But if there are write-back caches in the mix, this doesn&#8217;t work, since the physical write-back to memory can happen a long time after the core executed the corresponding store &#8211; and for the intervening time, the other cores and their caches are none the wiser, and might themselves try to write to the same location, causing a conflict. So with a write-back model, it&#8217;s not enough to broadcast just the writes to memory when they happen; if we want to avoid conflicts, we need to tell other cores about our intention to write <em>before</em> we start changing anything in our local copy. Working out the details, the easiest solution that fits the bill and works for write-back caches is what&#8217;s commonly called the <a href="http://en.wikipedia.org/wiki/MESI_protocol">MESI protocol</a>.</p>
<h3>MESI and friends</h3>
<p>This section is called &#8220;MESI and friends&#8221; because MESI spawned a whole host of closely related coherency protocols. Let&#8217;s start with the original though: MESI are the initials for the four states a cache line can be in for any of the multiple cores in a multi-core system. I&#8217;m gonna cover them in reverse order, because that&#8217;s the better order to explain them in:</p>
<ul>
<li><b>I</b>nvalid lines are cache lines that are either not present in the cache, or whose contents are known to be stale. For the purposes of caching, these are ignored. Once a cache line is invalidated, it&#8217;s as if it wasn&#8217;t in the cache in the first place.</li>
<li><b>S</b>hared lines are clean copies of the contents of main memory. Cache lines in the shared state can be used to serve reads but they can&#8217;t be written to. Multiple caches are allowed to have a copy of the same memory location in &#8220;shared&#8221; state at the same time, hence the name.</li>
<li><b>E</b>xclusive lines are also clean copies of the contents of main memory, just like the S state. The difference is that when one core holds a line in E state, no other core may hold it at the same time, hence &#8220;exclusive&#8221;. That is, the same line must be in the I state in the caches of all other cores.</li>
<li><b>M</b>odified lines are dirty; they have been locally modified. If a line is in the M state, it must be in the I state for all other cores, same as E. In addition, modified cache lines need to be written back to memory when they get evicted or invalidated &#8211; same as the regular dirty state in a write-back cache.</li>
</ul>
<p>If you compare this to the presentation of write-back caches in the single-core case above, you&#8217;ll see that the I, S and M states already had their equivalents: invalid/not present, clean, and dirty cache lines, respectively. So what&#8217;s new is the E state denoting exclusive access. This state solves the &#8220;we need to tell other cores before we start modifying memory&#8221; problem: each core may only write to cache lines if their caches hold them in the E or M states, i.e. they&#8217;re exclusively owned. If a core does not have exclusive access to a cache line when it wants to write, it first needs to send an &#8220;I want exclusive access&#8221; request to the bus. This tells all other cores to invalidate their copies of that cache line, if they have any. Only once that exclusive access is granted may the core start modifying data &#8211; and at that point, the core knows that the only copies of that cache line are in its own caches, so there can&#8217;t be any conflicts.</p>
<p>Conversely, once some other core wants to read from that cache line (which we learn immediately because we&#8217;re snooping the bus), exclusive and modified cache lines have to revert back to the &#8220;shared&#8221; (S) state. In the case of modified cache lines, this also involves writing their data back to memory first.</p>
<p>The MESI protocol is a proper state machine that responds both to requests coming from the local core, and to messages on the bus. I&#8217;m not going to go into detail about the full state diagram and what the different transition types are; you can find more in-depth information in books on hardware architecture if you care, but for our purposes this is overkill. As a software developer, you&#8217;ll get pretty far knowing only two things:</p>
<p>Firstly, in a multi-core system, getting read access to a cache line involves talking to the other cores, and might cause them to perform memory transactions.<br />
Writing to a cache line is a multi-step process: before you can write anything, you first need to acquire both exclusive ownership of the cache line and a copy of its existing contents (a so-called &#8220;Read For Ownership&#8221; request).</p>
<p>And secondly, while we have to do some extra gymnastics, the end result actually does provide some pretty strong guarantees. Namely, it obeys what I&#8217;ll call the</p>
<blockquote><p><b>MESI invariant</b>: after writing back all dirty (<em>M-state</em>) cache lines, the contents of all cache lines present in any of the cache levels are identical to the values in memory at the corresponding addresses. In addition, <em>at all times, when a memory location is exclusively cached (in E or M state) by one core, it is not present in any of the other core&#8217;s caches.</em>.</p></blockquote>
<p>Note that this is really just the write-back invariant we already saw with the additional exclusivity rule thrown in. My point being that the presence of MESI or multiple cores does not necessarily weaken our memory model at all.</p>
<p>Okay, so that (very roughly) covers vanilla MESI (and hence also CPUs that use it, ARMs for example). Other processors use extended variants. Popular extensions include an &#8220;O&#8221; (Owned) state similar to &#8220;E&#8221; that allows sharing of dirty cache lines without having to write them back to memory first (&#8220;dirty sharing&#8221;), yielding MOESI, and MERSI/MESIF, which are different names for the same idea, namely making one core the designated responder for read requests to a given cache line. When multiple cores hold a cache line in Shared state, only the designated responder (which holds the cache line in &#8220;R&#8221; or &#8220;F&#8221; state) replies to read requests, rather than everyone who holds the cache line in S state. This reduces bus traffic. And of course you can add both the R/F states and the O state, or get even fancier. All these are optimizations, but none of them change the basic invariants provided or guarantees made by the protocol.</p>
<p>I&#8217;m no expert on the topic, and it&#8217;s quite possible that there are other protocols in use that only provide substantially weaker guarantees, but if so I&#8217;m not aware of them, or any popular CPU core that uses them. So for our purposes, we really can assume that coherency protocols keep caches coherent, period. Not mostly-coherent, not &#8220;coherent except for a short window after a change&#8221; &#8211; properly coherent. At that level, barring hardware malfunction, there is always agreement on what the current state of memory should be. In technical terms, MESI and all its variants can, in principle anyway, provide full <a href="http://en.wikipedia.org/wiki/Sequential_consistency">sequential consistency</a>, the strongest memory ordering guarantee specified in the C++11 memory model. Which begs the question, why do we have weaker memory models, and &#8220;where do they happen&#8221;?</p>
<h3>Memory models</h3>
<p>Different architectures provide different memory models. As of this writing, ARM and POWER architecture machines have comparatively &#8220;weak&#8221; memory models: the CPU core has considerable leeway in reordering load and store operations in ways that might change the semantics of programs in a multi-core context, along with &#8220;memory barrier&#8221; instructions that can be used by the program to specify constraints: &#8220;do not reorder memory operations across this line&#8221;. By contrast, x86 comes with a quite strong memory model.</p>
<p>I won&#8217;t go into the details of memory models here; it quickly gets really technical, and is outside the scope of this article. But I do want to talk a bit about &#8220;how they happen&#8221; &#8211; that is, where the weakened guarantees (compared to the full sequential consistency we can get from MESI etc.) come from, and why. And as usual, it all boils down to performance.</p>
<p>So here&#8217;s the deal: you will indeed get full sequential consistency if a) the cache immediately responds to bus events on the very cycle it receives them, and b) the core dutifully sends each memory operation to the cache, in program order, and wait for it to complete before you send the next one. And of course, in practice modern CPUs normally do none of these things:</p>
<ul>
<li>Caches do <em>not</em> respond to bus events immediately. If a bus message triggering a cache line invalidation arrives while the cache is busy doing other things (sending data to the core for example), it might not get processed that cycle. Instead, it will enter a so-called &#8220;invalidation queue&#8221;, where it sits for a while until the cache has time to process it.</li>
<li>Cores do not, in general, send memory operations to the cache in strict program order; this is certainly the case for cores with Out-of-Order execution, but even otherwise in-order cores may have somewhat weaker ordering guarantees for memory operations (for example, to ensure that a single cache miss doesn&#8217;t immediately make the entire core grind to a halt).</li>
<li>In particular, stores are special, because they&#8217;re a two-phase operation: we first need to acquire exclusive ownership of a cache line before a store can go through. And if we don&#8217;t already have exclusive ownership, we need to talk to the other cores, which takes a while. Again, having the core idle and twiddling thumbs while this is happening is not a good use of execution resources. Instead, what happens is that stores start the process of getting exclusive ownership, then get entered into a queue of so-called &#8220;store buffers&#8221; (some refer to the entire queue as &#8220;store buffer&#8221;, but I&#8217;m going to use the term to refer to the entries). They stay around in this queue for a while until the cache is ready to actually perform the store operation, at which point the corresponding store buffer is &#8220;drained&#8221; and can be recycled to hold a new pending store.</li>
</ul>
<p>The implication of all these things is that, by default, loads can fetch stale data (if a corresponding invalidation request was sitting in the invalidation queue), stores actually finish later than their position in the code would suggest, and everything gets even more vague when Out of Order execution is involved. So going back to memory models, there are essentially two camps:</p>
<p>Architectures with a weak memory model do the minimum amount of work necessary in the core that allows software developers to write correct code. Instruction reordering and the various buffering stages are officially permitted; there are no guarantees. If you need guarantees, you need to insert the appropriate memory barriers &#8211; which will prevent reordering and drain queues of pending operations where required.</p>
<p>Architectures with stronger memory models do a lot more bookkeeping on the inside. For example, x86 processors keep track of all pending memory operations that are not fully finished (&#8220;retired&#8221;) yet, in a chip-internal data structure that&#8217;s called the MOB (&#8220;memory ordering buffer&#8221;). As part of the Out of Order infrastructure, x86 cores can roll back non-retired operations if there&#8217;s a problem &#8211; say an exception like a page fault, or a branch mispredict. I covered some of the details, as well as some of the interactions with the memory subsystem, in my earlier article &#8220;<a href="https://fgiesen.wordpress.com/2013/03/04/speculatively-speaking/">Speculatively speaking</a>&#8220;. The gist of it is that x86 processors actively watch out for external events (such as cache invalidations) that would retroactively invalidate the results of some of the operations that have already executed, but not been retired yet. That is, x86 processors know what their memory model is, and when an event happens that&#8217;s inconsistent within that model, the machine state is rolled back to the last time when it was still consistent with the rules of the memory model. This is the &#8220;memory ordering machine clear&#8221; I covered in <a href="https://fgiesen.wordpress.com/2013/01/31/cores-dont-like-to-share/">yet another earlier post</a>. The end result is that x86 processors provide very strong guarantees for all memory operations &#8211; not quite sequential consistency, though.</p>
<p>So, weaker memory models make for simpler (and potentially lower-power) cores. Stronger memory models make the design of cores (and their memory subsystems) more complex, but are easier to write code for. In theory, the weaker models allow for more scheduling freedom and can be potentially faster; in practice, x86s seem to be doing fine on the performance of memory operations, for the time being at least. So it&#8217;s hard for me to call a definite winner so far. Certainly, as a software developer I&#8217;m happy to take the stronger x86 memory model when I can get it.</p>
<p>Anyway. That&#8217;s plenty for one post. And now that I have all this written up on my blog, the idea is that future posts can just reference it. We&#8217;ll see how that goes. Thanks for reading!</p>
]]></html></oembed>