Section 9.25

ABA problem

Definition

The ABA problem is a failure of concurrent algorithms §14.1 built on compare-and-swap §9.9 (CAS), an atomic instruction that writes a new value to a memory location only if the location still holds an expected value. A thread reads value A, other threads change the location to B and back to A, and the first thread’s CAS succeeds because it finds A again, although the state the thread relied on has changed. The name is the sequence of values, A then B then A; it is not an abbreviation.

The idea

Many algorithms that avoid locks update shared data in a loop. A thread (one of several instruction sequences sharing one memory) reads the shared value, computes a new value from it, and then applies CAS with the value it read as the expected value. If the CAS fails, another thread changed the location, so the thread starts again. The loop rests on an assumption: if the location still holds the value read earlier, nothing has changed since. CAS checks only that the location equals the expected value at the instant the CAS runs. It cannot see what happened in between.

When the value is a pointer, equal does not mean same. Memory that was freed can be handed out again, so a new object can appear at the address of an old one, and a node removed from a linked structure can be put back. The worked example shows a stack corrupted this way.

Someone leaves a full cup of coffee on a desk to answer the door. Meanwhile a colleague drinks it, washes the cup and fills it again with fresh coffee to the same level. On returning, the first person sees a full cup in the same place and concludes that nothing happened. The picture stops at the consequence: in a program, the refilled cup can be a pointer into freed memory, and acting on it corrupts a data structure.

How it works

A stack that uses no lock (see the lock-free versus wait-free §9.13 entry) shows the mechanism. The stack is a linked list §14.6 of nodes, and a shared pointer top holds the address of the first node. To remove the first node, called a pop, a thread runs three steps.

  1. Read top; call the address read old.

  2. Read the next field of the node at old, the address of the second node; call it next.

  3. Run CAS on top with expected value old and new value next. If the CAS fails, start again.

Step 3 assumes that if top still equals old, the node at old still has next as its successor. If other threads pop that node, pop its successor and push the first node back, top equals old again, but the successor has changed. This design is known as the Treiber stack, after R. Kent Treiber, who described it in 1986 [304].

Three remedies exist.

  1. Generation tag. Keep a counter next to the pointer, in the same word that the CAS compares, and make every successful CAS add 1 to it. The CAS then compares the pointer and the tag together. Any change in between changes the tag, so the stale CAS fails even if the pointer is back to its old value. The pointer and the tag must fit into one unit that the processor can compare and swap atomically. 64-bit x86 processors offer a 16-byte CAS, enough for a 64-bit pointer and a 64-bit tag. On a 32-bit microcontroller §6.1, a usual choice is a 16-bit index into an array §14.5 of nodes and a 16-bit tag in one 32-bit word. A tag of ww bits returns to the same value after 2w2^{w} increments, a counter wraparound §6.21.

  2. Safe memory reclamation. Never free a node while any thread may still hold its address from an earlier read. Hazard pointers do this: each thread announces, in a shared slot, the address it is about to use, and a node is freed only when no slot holds its address. Epoch-based reclamation and read-copy update §9.20 (RCU) reach the same goal by waiting until every thread that might hold the old address has finished its operation. Then an address cannot be given to a new node while a stale reader holds it, so equal addresses mean the same node. This removes ABA caused by memory reuse. It does not help when the algorithm itself takes a node out and puts the same node back, which still needs a tag.

  3. Load-linked and store-conditional (LL/SC). Some processors, including Arm processors, pair a load that starts watching a location with a store that succeeds only if nothing has written the location since. The 32-bit Arm instruction sets call the pair LDREX (load exclusive) and STREX (store exclusive). The store fails after any intervening write, even one that restored the old value. But C and C++ code reaches these instructions through a compare-and-swap interface, which compares values and so brings the problem back.

A tag protects the comparison, not the memory. Between steps 1 and 3, the popping thread reads the next field of the node at old. If that node has been freed and its memory returned to the general allocator, the read is a use-after-free §4.6, even though the CAS will fail afterwards. Tagged designs therefore keep their nodes in a private pool that is never returned to the allocator, so the stale read, made with an atomic load, only returns a wrong value that the failing CAS then discards.

Worked example

The stack holds three nodes. top points to node A at address 0x2000, A’s next field points to node B at 0x2010, and B’s next field points to node C at 0x2020.

  1. Thread T1 starts a pop. T1 reads top = 0x2000 and A’s next field = 0x2010. Then T1 is interrupted before its CAS.

  2. Thread T2 pops A: its CAS changes top from 0x2000 to 0x2010.

  3. T2 pops B: top becomes 0x2020. T2 frees B.

  4. T2 pushes A back, with A’s next field set to 0x2020, so top is 0x2000 again.

  5. T1 resumes and runs CAS on top with expected value 0x2000 and new value 0x2010. top holds 0x2000, so the CAS succeeds, and top becomes 0x2010.

T1 returns A, which is correct. But C is lost from the stack, and the stack now begins at B, whose memory was freed in step 3; the next pop returns freed memory.

Now give top a tag and write its content as the pair (address, tag), starting at (0x2000, 5). In step 1, T1 reads (0x2000, 5). Step 2 makes top (0x2010, 6), step 3 makes it (0x2020, 7), and step 4 makes it (0x2000, 8). In step 5, T1’s CAS expects (0x2000, 5) but finds (0x2000, 8). Since 8≠58 \ne 5, the CAS fails. T1 starts again: it reads (0x2000, 8) and A’s next field 0x2020, and its CAS installs (0x2020, 9). The stack is correct, with C now first.

How long a tag lasts depends on its width and on the update rate. Suppose top changes once every microsecond (μ\mus). A 16-bit tag has 216=65,5362^{16} = 65{,}536 values, so it repeats after 65,536μs=65.53665{,}536\ \mu\text{s} = 65.536 ms. A thread paused for 100 ms, for example while higher-priority threads run, sees its saved tag again if exactly 65,536 updates, or another multiple of 65,536, happen during its pause. A 32-bit tag repeats only after 232μs≈42952^{32}\ \mu\text{s} \approx 4295 s, about 71.6 minutes, and a 64-bit tag after 264μs2^{64}\ \mu\text{s}, about 585,000 years.

Stated precisely

Let thread T read location XX at time t1t_1 and see the value vv, and let T’s CAS on XX, with expected value vv, take effect at time t2t_2. The CAS succeeds exactly when XX holds vv at t2t_2. The algorithm’s correctness argument usually needs the stronger fact that no thread wrote XX between t1t_1 and t2t_2. An ABA execution is one in which some thread wrote XX at least once between t1t_1 and t2t_2 and XX holds vv again at t2t_2.

Tagged location. Let XX hold a pair (p,g)(p, g), where pp is a pointer and gg is a tag of ww bits. Let every write to XX be a CAS that sets the tag to (g+1)mod2w(g + 1) \bmod 2^{w}, where amodma \bmod m is the remainder of aa divided by mm. If kk writes happen between t1t_1 and t2t_2, the tag at t2t_2 is (g+k)mod2w(g + k) \bmod 2^{w}, which equals gg only when kk is a multiple of 2w2^{w}. The smallest such kk above zero is 2w2^{w}. Hence, if fewer than 2w2^{w} writes to XX can happen while any thread is between its read and its CAS, a successful CAS proves that XX was not written in between. The proof assumes that the pointer and the tag are compared in one atomic CAS, that every write to XX increments the tag, and that the bound on writes per window holds.

Safe reclamation. If no node is freed while any thread holds its address from an earlier read, then no other node can occupy that address during the thread’s window, so pp at t2t_2 refers to the same node as at t1t_1. This proves that the node is the same node. It does not prove that the node is unchanged, or that the node was never removed and inserted again.

Limits and common mistakes

ABA is not a data race §9.3 and not a torn read. Every access can be atomic and use the strongest memory ordering, sequential consistency §9.12, and the ABA problem still occurs, because memory ordering controls when writes become visible, not whether a location’s history is recorded.

Tags wrap, as the worked example computes. A narrow tag, such as the 3 low bits that are always zero in an address aligned to 8 bytes, repeats after only 23=82^{3} = 8 updates.

A CAS twice as wide as a pointer is not available on every processor, and a pointer has few spare bits. An index plus a tag in one word limits how many nodes the structure can address: a 16-bit index addresses at most 216=65,5362^{16} = 65{,}536 nodes.

A tag protects the comparison, not the memory: the stale thread’s reads through its old pointer must still be safe.

Safe reclamation alone does not catch an algorithm that removes a node and inserts the same node again.

ABA is not limited to pointers. A state variable that goes from idle to busy and back to idle, or a counter that wraps around, can fool a CAS in the same way. Whether that matters depends on whether the algorithm relies on the value not having changed in between, or only on its current value.

Questions answered

How can generation tags or safe reclamation prevent the mistaken conclusion?

Generation tags and safe reclamation prevent the mistaken conclusion that a shared location which still holds the value a thread read earlier has not changed in between. Compare-and-swap, which writes a new value only if the location equals an expected value, checks equality at one instant and cannot see a change from A to B and back to A.

A generation tag makes such a return visible. The location holds a pointer together with a counter that every successful write increments, and the compare-and-swap compares both in one atomic step. Any intervening write changes the counter, so the stale compare-and-swap fails, unless the ww-bit counter has wrapped all the way round, which takes 2w2^{w} writes. The tag must be wide enough that this many writes cannot happen while a thread waits between its read and its compare-and-swap.

Safe memory reclamation, such as hazard pointers, epoch-based reclamation or read-copy update, prevents the most dangerous case, memory reuse. A node is not freed while any thread still holds its address from an earlier read, so no new node can appear at that address, and equal addresses mean the same node. Safe reclamation does not detect a node that the algorithm itself removed and inserted again, so such an algorithm still needs a tag.

Related entries: Compare-and-swap (§9.9), Reference counting (§9.22), Object lifetime (§4.1), Use-after-free (§4.6), Counter wraparound (§6.21), Lock-free versus wait-free (§9.13), Read-copy update (RCU) (§9.20). Further reading: [304].