# Linux Kernel Module Cheat

#### 30.7.1. ARM LDXR and STXR instructions

Parent section: atomic.cpp

userland/cpp/atomic/aarch64_ldaxr_stlxr.cpp

LDXR and STXR vs LDAXR and STLXR: https://stackoverflow.com/questions/21535058/arm64-ldxr-stxr-vs-ldaxr-stlxr TODO understand better and example.

LDXR and STXR for a so-called "Load-link/store-conditional" (LLSC) pattern: https://en.wikipedia.org/wiki/Load-link/store-conditional which appears in many RISC ISAs.

This pattern makes it such that basically:

- LDXR marks an address for exclusive access by the current CPU

- STXR:

  - marks the address as not being exclusive to other CPUs that may have done LDXR before

  - loads fine if the address is still marked as exclusive, and stores 0 on a third register for success

  - fails to load if the address is not, and stores 1 on the third register for failure

In case of failure, we just have to loop back to just before the LDXR and try again.

This is therefore basically a spinlock and should only be used to cover very short critical sections such as atomic increments.

C++ `std::atomic` uses this for increments before v8.1 ARM Large System Extensions (LSE): https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291