Commit 04fede03 authored by Matthew Fernandez's avatar Matthew Fernandez
Browse files

fix: use a spurious failing CAS to read dwords on x86-64

Due to the reasons explained in the source comments, an atomic read of a 128-bit
value on x86-64 was implemented with the idiom:

  v = __sync_val_compare_and_swap(p, *p, *p);

In a race-free scenario, this CAS succeeds. I.e. The existing value of `p`
matches the expected value that is passed in and the new value -- which is
identical -- is written back. So far, so good. In a racing scenario, the value
read through the expression `*p` might *not* match the value read during the CAS
due to another thread changing the value in-between. Still fine; the CAS fails,
but all we were really after was a read of the current value, which we receive
in either case.

A third scenario -- which is also OK -- involves a torn read. The expression
`*p` evaluates to something that was never the actual value at this address, but
rather part of the value at one instance in time and the other part belonging to
a second instance in time. Why is this still OK? Well, the CAS either fails
(expected case) if the torn read does not match the observed value or succeeds
if by coincidence the torn read matches a legitimate value later written into
this location. Both cases still yield a correct atomic read of the current
value.

"OK, cut to the chase, where's the problem?" Consider a compiler that does not
optimize the two `*p` expressions into a single read of the memory location.
The location is read *twice* before performing the CAS. Ignoring torn reads
(which are still possible and further complicate the possible scenarios), it is
possible for the first `*p` to evaluate to a value present at one point in time
and the second `*p` to evaluate to a value present at a *previous* point in
time. "But surely the second expression can't see a value *before* the first?"
You would think so, but the order of evaluation of arguments to a function in C
is implementation defined, so it is perfectly legal for a compiler to generate
code that evaluates the second expression before the first.

"What's the damage?" It is possible for this CAS to inadvertently restore a
stale value to the memory location while reading from it. To be clear, this was
not observed on an x86-64 platform and it seems like it would require both bad
luck and a pathological compiler implementation, but your edge case is someone
else's happy path.

We avoid this whole conundrum by using a static constant that will cause
deterministic success or failure without side effects.
parent 839da720
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment