Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's ARM instruction equivalent to Intel's xchgl?

I found LDREX and STREX might be the ones to use. But they are two instructions (and thus not provide the atomicity of xchgl). The value I want to exchange atomically is a 32-bit value. Can LDREX and STREX be used in a way that provides atomic exchange of a 32-bit value or are they other ways to achieve it (provided it works on armv7l or higher)?

Normally, I'd the gcc's atomic builtins or the more recent (C++11 equivalent) builtin functions for such atomic operations. But in this case, I have to use inline assembly in C (to port an x86-based futex implementation to ARM architecture). Thanks!

like image 787
P.P Avatar asked Oct 14 '25 03:10

P.P


2 Answers

In the ARM instruction set, there is no atomic exchange instruction. Instead you use ldrex and strex and code like this:

@ exchange r0 and [r1]
ldrex r2,[r1]
strex r3, r0,[r1]
mov   r0,r2

When [r1] is modified between ldrex and strex or the exchange cannot be guaranteed to be atomic for some other reason, 1 is returned in r3 and the store isn't performed. If the sequence is atomic, 0 is returned. Thus, by executing this snippet in a loop until you get a zero r3 you can eventually reach an atomic exchange operation. That's actually how gcc and clang implement the corresponding intrinsic; pass -S to the compiler to observe what it does.

like image 50
fuz Avatar answered Oct 17 '25 00:10

fuz


SWP is still supported on some cores despite what the docs say (they often say please dont use rather than we have removed it) but it is going away or may be gone on your core.

Atomics are costly, CISC is costly so perhaps it is fine there, but RISC it makes sense what they have done. You are basically synthesizing the atomic but you may have to repeat it until it works (rather than stopping all data movement on the bus while the atomic happens). Not limited to a RISC/CISC thing but simply a performance thing.

like image 44
old_timer Avatar answered Oct 17 '25 00:10

old_timer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!