2

The following code snippet is from Computer Organization and Design, RISC-V edition, 2nd edition.

Suppose that the memory location that is addressed by x20 register is modified after execution of lr.w instruction and before execution of sc.w. My Question is that how does the sc.w instruction realize that the content of the memory location is changed.

again:
lr.w x10, (x20)       // load-reserved
sc.w x11, x23, (x20)  // store-conditional
bne x11, x0, again    // branch if store fails (0)
addi x23, x10, 0      // put loaded value in x23
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
user153245
  • 259
  • 3
  • 10
  • Ideally, the `lr` instruction performs the load and put the address used in a CAM (read: hash table) of watched address. The CPU snoops memory traffic and if any hit a target in that CAM a corresponding flag is set. The `sc` most likely only checks that flag. – Margaret Bloom Nov 19 '22 at 09:34
  • 1
    Probably by tracking MESI cache invalidation for the cache line containing that word, with the `lr.w` "arming the monitor". (ARM CPUs have equivalent instructions, and the documentation of the internals calls it a "monitor".) It doesn't actually check for modification, it just has to check that it kept the cache line in Modified or Exclusive state since the `lr.w`. (That's why C++ has `compare_exchange_weak` which can be non-looping, exposing the "spurious failures" when LL/SC wasn't sure even though the data wasn't actually modified.) – Peter Cordes Nov 19 '22 at 09:35

0 Answers0