Understanding Hardware Transactional Memory in Intel's Haswell Architecture
It's been quite a few years since the last time a new generation of Intel processors excited me. The past decade has been largely categorized by small improvements in instructions-per-click and power efficiency, and large improvements in obscure algorithms that now have dedicated instructions.
Intel's Haswell microarchitecture, however, has something fun and of widespread utility. The transactional memory extensions are relevant to a wide range of applications and, as an added bonus, are actually interesting architecturally.
Transactional Memory
I've written previously about transactional memory. From the point of view of the programmer, it's one of the nicest ways of writing concurrent software. You assume that there's no contention on shared data structures, and you modify them. If contentions exist, the routine fails, and none of your changes become globally visible.
There's just one problem with this approach: Transactional memory implemented entirely in software is slow. The easiest way of implementing software transactional memory (STM) is to acquire a global lock when you enter a transactional region, releasing it when you leave. The problem with this technique is that it completely eliminates all parallelism.
You can use a set of locks for different regions of memory, but this design ends up being very costly for entering transactions. Alternatively, you can use a read-copy-update approach, where you copy all of a data structure, modify it, and then use an atomic compare-and-exchange instruction to make your copy the global one. This approach works well for small data structures, but is very difficult to retrofit to existing programs.
Hardware Transactions
Before we look at how hardware transactional memory (HTM) works, it's worth noting that hardware transactions and optimistic concurrency are nothing new in modern processors. Every processor with a branch predictor does speculative execution of instructions after a branch, either committing the results or aborting and discarding the changes based on whether the branch is really taken.
Transactional memory can be seen as a simple extension of this design, with the state of the cache as well as the state of the registers being part of the processor's internal state, rather than a view on the global state.
Hardware transactional memory also isn't a new idea. IBM's Blue Gene/Q has supported it for a little while, and Sun's Rock CPU was intended to do so (before Oracle canceled it), not to mention a large number of research CPUs over the years. For HTM to be useful, however, you need multiple cores and large caches, a combination that has only occurred relatively recently.
With large caches, a CPU can buffer a large number of memory writes without having to store things out to main memory. A multicore CPU already has a mechanism for cache coherency. This ensures that cache lines representing the same memory address in different cores are synchronized, by maintaining a small state machine for each cache line and requiring it to be in the exclusive state (that is, not present in any other caches) before it can be written. It's fairly easy—conceptually, at least—to extend this approach, simply keeping track of whether a core has tried to modify a memory address that another has in its cache.
The idea behind hardware transactional memory is to allow two cores to execute code speculatively if they touch global state, and both should always succeed unless they touch the same bit of global state. For example, if two cores are updating entries in a tree, both will read from the root to a leaf and then each will modify one leaf. In a traditional locking model, you might have a single lock for the entire tree, so that accesses are serialized. With a transactional approach, each starts a transaction, walks to the desired node, and then updates it. The transactions would always succeed, unless both cores tried to update the same node.
In this case, the hardware keeps track of which cache lines have been read from and which have been written to. If another core reads the same cache line addresses as you do, there's no conflict. If either writes to a cache line that another has read or written to, then there's a conflict, and one of the transactions will fail. (Which one fails is defined by implementation.)
Transactional Failure
There are lots of possible things to do when a transaction fails. The most obvious is simply to restart it. This is very easy to do in hardware: You discard all modified cache lines, reset the registers to their initial state (including the program counter), and continue. Unfortunately, this is one of the cases of a solution that's simple, obvious—and wrong.
The problem with this approach is that it doesn't guarantee forward progress, unless you ensure that at least one transaction will succeed. It also makes it impossible, for example, to respect thread priorities, so a high-priority thread could be starving while a lower-priority thread with shorter transactions always succeeds.
The solution in Blue Gene/Q is also simple: If a transaction fails more than a few times in a row, you acquire a global (per CPU) lock, which prevents any other cores from making forward progress until the starved process is finished. This is a good solution for high-performance computing, where most threads have the same priority and throughput is very important. It's not quite as good for general-purpose computing.
Intel adopts the same approach as Rock: If a transaction fails, you jump to a designated failure handler. In Intel's more traditional HTM model, transactions are bracketed by XBEGIN and XEND instructions. The XBEGIN instruction takes an address as an argument and will jump there if the transaction fails, or continue if it succeeds. The address is provided at the start, so the transaction can abort as soon as a conflict is detected. Intel calls this interface Reduced Transactional Memory (RTM), because it doesn't guarantee that a transaction will ever succeed, even if it doesn't conflict. It may fail for a number of reasons, such as executing some floating-point instructions that aren't supported in transactional mode, running out of cache, poor cache aliasing, receiving an interrupt, and so on. In fact, a conforming implementation of RTM could simply discard all memory writes in a transaction and always fail at XEND.
This design is intended to allow hybrid transactional memory implementations, where HTM is used for the fast path and a much slower software implementation is used for cases that the hardware can't handle. The software path might use a single global lock, or a set of locks for different addresses, or any of the other approaches for STM, but it doesn't need to be very efficient because it shouldn't be used very often.
Hardware Lock Elision
In addition to the RTM interface, Intel provides hardware lock elision (HLE) as a simple way of deploying transactional memory in existing code. The idea of HLE is that mutex lock and unlock operations already implicitly define transactional boundaries. You typically use a mutex to protect a shared data structure. It's a logical extension of existing speculative execution mechanisms for a CPU to execute all of the operations that are inside the mutex operation, failing only if they actually conflict.
In theory, this technique wouldn't be at all useful: You'd only bother protecting a data structure with a mutex if concurrent writes to it would be conflicting. In practice, however, there's always a tradeoff to be made with respect to granularity. Acquiring a lock requires (at least) an atomic operation, which traditionally is quite expensive. If you have coarse-grained locking, the cost of acquiring the locks is relatively small, but the potential for parallelism is also small. In contrast, fine-grained locking is expensive, but allows much more parallelism.
The first attempts to implement parallelism in UNIX kernels protected the entire kernel with a single lock. Any code that entered the kernel acquired the lock. This worked very well when a typical system had one or two CPUs, because it was relatively rare to have two cores calling into the kernel at the same time. On core systems with four to eight CPUs, it became a much bigger problem.
With HLE, the atomic operations that acquire and release the lock are prefixed with XACQUIRE and XRELEASE, respectively. The instruction set in x86 uses a variable-length encoding, where instructions are sometimes prefixed by modifiers. For example, an atomic add is a normal add instruction with the LOCK prefix. The two new prefixes have the same byte encoding as existing prefixes on string-manipulation instructions, which makes no sense on the kinds of operations that are used for locks and therefore are ignored by existing processors. This means that you can deploy them unconditionally and they'll simply be ignored on processors that don't support HLE.
When you acquire a lock with an XACQUIRE-prefixed instruction, the lock isn't actually acquired. The write operation is ignored, but the address is added to the set of addresses that the transaction reads, so the transaction will fail if something else writes to that address (for example, some legacy code trying to acquire the lock with the old instruction). Execution continues until the XRELEASE-prefixed instruction, and the transaction is then committed. If it succeeds, the code acts exactly as it would have if the mutex had been acquired: None of the memory operations conflicted, and the lock has been elided.
If the transaction fails, the thread returns to the start. This time, it actually acquires the lock. The acquire instruction proceeds as if the XACQUIRE prefix didn't exist, and execution proceeds just as it would on any other processor.
This is safer than in the pure transactional memory case, because code using locks should already be written to avoid priority inversion. If it isn't, then it's buggy already; HLE hasn't introduced more bugs.
The nice thing about HLE is that you don't have to think too much about locking granularity (at least, if Haswell is your only deployment target). You can just use very coarse-grained locking, and you'll end up with code that will exhibit as much parallelism as is present in the access patterns, not in the locking designs.
There are some limitations, as with RTM. In both cases, the cache detects concurrent accesses at a cache-line granularity. If you have a large array, for example, and two threads are writing to adjacent elements, this will often cause the transaction to fail spuriously, because the transactional hardware can't distinguish between two accesses to the same address, and two accesses to different addresses in the same cache line.
Nesting
One of the most complex issues when implementing transactional memory is how to handle nested transactions. If a transaction within another succeeds, it can't be committed immediately in case the outer transaction fails.
With RTM, the hardware simply maintains a counter of the nesting depth and commits the transaction only when the counter reaches zero. This technique simplifies the implementation somewhat, as the hardware has to store only one fallback address: If any transaction within a nested region fails, it can just jump back to the fallback address for the start of the nested set.
Nesting has a subtly different meaning in HLE, where regions are defined by lock acquisitions. A thread that tries to acquire multiple locks can be seen as entering a nested transaction, but the hardware determines how many locks it will try to elide. The first lock will always be elided by a chip that supports HLE, but subsequent ones may not. This makes sense, as locks are usually acquired in a coarse-to-fine order, so the gains from eliding the outer ones are more significant.
Power Considerations
While this design is great for high-end applications on multiple-core machines, it comes at a price. The more work that's executed speculatively, the more time the CPU spends doing work that ultimately will be discarded. Therefore it's unlikely to be a benefit on systems where power is at a premium, such as mobile devices. On these systems, it's better to identify contention earlier and allow one core to sleep or run a different process cheaply while a lock is held. This is one of the ideas behind simultaneous multithreading (hyperthreading, in Intel terminology): Making it cheap to perform context switches, so threads that are blocking can be temporarily descheduled without operating system involvement.
It's not clear exactly where the correct tradeoff is, in terms of power efficiency and multicore scalability. On the same process technology, two 500 MHz cores awill use less power than a single 1 GHz core, so there's a clear power win from making more scalable code. This is especially true in the context of something like ARM's big.LITTLE designs, where running code on two or more Cortex-A7 cores can use less power than running on one Cortex-A15, as long as the extra communication overhead doesn't cost too much.
Intel's transactional memory extensions are another step toward finding the "sweet spot." I wouldn't be at all surprised to find that it's very different between low-power and high-performance systems.