Atomic Operations: The Lost Update and LR/SC
Two harts add 1 to the same counter, three times each. The answer should be 6. It comes out as 3, and no access failed. A store that checks before it writes brings the missing counts back.
You Will Be Able To
- Explain why a load and a store from two harts can lose an update.
- Follow a load-reserved and a store-conditional, and name what ends a reservation.
- Say what a hart does when its store-conditional fails.
- Lesson
- S9.2
- Time
- 25 min
- Runs on
- Your browser
- Check
- 5 questions
Both harts of the chip count events into one shared word. After six events the word reads 3.
Every load got a good reply, and so did every store. Three counts are gone, and nothing reported an error.
Before You Start
You need More Than One Core: two harts on one bus, and memory that both can reach.
You need A Processor in One Picture: arithmetic works on registers, so a value is loaded first and stored afterwards.
It helps to have read Bursts, Locks and the Waiting Request, which meets the same lost addition between two managers.
| Question | |
|---|---|
| 1 | Why can two harts that each add 1 to a word lose a count? |
| 2 | What does a load-reserved leave behind, and what does a store-conditional check? |
| 3 | What ends a reservation? |
| 4 | What does a hart do when its store-conditional fails? |
| 5 | Each hart adds 1 once, with a plain load and store. What does the lab print last? |
The Idea: Nothing May Come Between the Read and the Write
Adding 1 to a word in memory looks like one step. For a hart it is three. It loads the word into a register, adds 1 there, and stores the result. Between the load and the store, the word sits in memory with nobody watching it.
With one hart that does no harm. With two, the second hart can load the same word in that gap. Now both hold the same old value. Both add 1, and both store the same result. One count is lost. This is a lost update, and the general name for the fault is a data race.
What is needed is an atomic update: a read and a write that nothing can come between. One way is to stop everybody else for a while. A lighter way lets everybody run, and makes the store check.
That lighter way is a pair of instructions. A load-reserved reads the word and leaves a reservation on its address. A store-conditional writes only if that reservation still stands. A write by anybody else ends it. So the store goes through only when nobody came between, and the hart is told which way it went.
New Words
| Word | Meaning |
|---|---|
| Lost update | A write that is overwritten by a value worked out from older data. |
| Data race | Two harts use one memory word, at least one writes it, and the result depends on who is first. |
| Atomic | Done as one step for everybody else: nobody can see or change the word halfway. |
| Load-reserved (LR) | A load that also leaves a reservation on its address. |
| Store-conditional (SC) | A store that writes only while the reservation of its hart stands. It returns 0 for written, 1 for not written. |
| Reservation of a hart | A note that the hart has read one address and means to write it. Each hart has at most one. |
| Monitor | The logic that keeps the reservations and sees every write to the memory. On a bus it is called an exclusive access monitor. |
| Retry loop | Code that repeats the load-reserved and the store-conditional until the store writes. |
One Picture: The Gap and the Check
- Processor
- Bus
- Memory
- Control / FSM
- Three steps, not one
To add 1, a hart loads the word, adds 1 in a register and stores the result. The bus sees two accesses.
- The gap
Between the load and the store of hart 0, the bus may serve hart 1. Both harts then hold the same old value.
- A reservation
A load-reserved reads the word, and the monitor writes down its address for that hart.
- A write ends it
The monitor sees every write to the word. A write by anyone ends every reservation on it.
- The store asks first
A store-conditional writes only if the reservation of its hart still stands. If not, nothing is written, and the hart is told.
Read the diagram as text
- Hart 0: loads the word, adds 1 in a register, stores it back
- Hart 1: does the same, at the same time
- Bus: serves one access at a time
- Shared word: a counter in SRAM
- Monitor: remembers one reserved address for each hart
- Hart 0 → Bus: load, then store
- Hart 1 → Bus: load, then store
- Bus → Shared word: read or write
- Bus → Monitor: every access to the word
- Monitor → Shared word: write allowed, or not
Load-reserved and store-conditional. The monitor is the one place that sees every write to the word.
The Smallest Example, Worked by Hand
No simulator yet. The counter holds 0. Each hart adds 1 once, so the right answer is 2. The bus serves the two harts in turn. First with a plain load and a plain store.
| Step | Hart 0 | Hart 1 | Counter after |
|---|---|---|---|
| 1 | Loads, gets 0 | 0 | |
| 2 | Loads, gets 0 | 0 | |
| 3 | Stores 1 | 1 | |
| 4 | Stores 1 | 1 |
Step 2 is the fault. Hart 1 loaded in the gap of hart 0, so step 4 writes a 1 on top of a 1. Now the same work with the pair.
| Step | Hart 0 | Hart 1 | Counter after | Reservations after |
|---|---|---|---|---|
| 1 | Load-reserved, gets 0 | 0 | Hart 0 | |
| 2 | Load-reserved, gets 0 | 0 | Hart 0 and hart 1 | |
| 3 | Store-conditional of 1: written, returns 0 | 1 | None | |
| 4 | Store-conditional of 1: not written, returns 1 | 1 | None | |
| 5 | Load-reserved, gets 1 | 1 | Hart 1 | |
| 6 | Store-conditional of 2: written, returns 0 | 2 | None |
Read step 3. The write of hart 0 went through, and it ended both reservations. So in step 4 the store of hart 1 finds no reservation. Nothing is written, and hart 1 is told. It loads again, gets the new value, and its second try writes 2.
The Rules
Rule 1: A change to a shared word is a load, a change and a store.
Another hart can be served between the load and the store.
Rule 2: A load-reserved reads the word and leaves a reservation on its address.
A hart holds one reservation. A new load-reserved replaces the old one.
Rule 3: A store-conditional writes only if the reservation of its hart still stands.
It returns 0 if it wrote and 1 if it did not. A store that did not write changes nothing in memory.
Rule 4: A write to the word by anybody else ends the reservation.
A read ends nothing. The monitor must see every write, whoever makes it.
Rule 5: A store-conditional uses up the reservation, written or not.
One reservation buys one try.
Rule 6: A store-conditional that did not write is not an error.
The hart loads again and tries again, with the new value.
Sources for These Rules
The data race, and a pair of a load and a conditional store that returns 0 for written (in Arm form): Patterson and Hennessy, Computer Organization and Design, ARM edition, section 2.11. The same section warns about the code between the two, as in the trap below.
On a bus the store goes ahead only if no other manager wrote the address since the read: Arm AMBA AHB Protocol Specification, IHI 0033 issue C, section 10.1.
A store that fails leaves memory as it was: the same section. The monitor must see every access to the address: section 10.2.
Rule 2, second sentence: AXI says the same of an exclusive read with the same ID (IHI 0022 issue L, section A6.3.1). The earlier page cited that section for a rule of RISC-V. It is not one.
Load-reserved, store-conditional, LR and SC are RISC-V names. The RISC-V manuals are not in our reference library. Rules 2 to 5 describe our lab. Whether RISC-V states each of them the same way is not checked.
The reservation on one whole word and the turns of the bus are choices of our lab.
Now Run It
The lab at the end of this page has two harts on one bus. A counter sits in SRAM, at address 80000004 in hex. Each hart is a bus-functional model: test code that makes the loads and stores of a program. Each adds 1 three times. First with a plain load and store.
Each row has a field for resv, the reservations, written as hart 1 and then hart 0. In this first run it stays 00.
e1 hart=0 op=load addr=80000004 wdata=00000000 result=00000000 resv=00 msip=00
e2 hart=1 op=load addr=80000004 wdata=00000000 result=00000000 resv=00 msip=00
e3 hart=0 op=store addr=80000004 wdata=00000001 result=00000000 resv=00 msip=00
e4 hart=1 op=store addr=80000004 wdata=00000001 result=00000000 resv=00 msip=00
counter=3 expected=6 sc_failures=0 lock_spins=0 bus_edges=13Rule 1 at work, in rows e1 and e2. Both loads return 0, so both stores write 1. The last line says it: the counter holds 3, and 6 was expected. Every pair of additions lost one.
A lit wire carries a 1. A pill is a transfer in that cycle.
- Cycle 1
Hart 0 loads the counter and gets 0.
- Cycle 2
Hart 1 loads before hart 0 has stored. It also gets 0.
- Cycle 3
Hart 0 stores 1.
- Cycle 4
Hart 1 stores 1 on top of it. One count is gone.
Recorded rising-edge samples from the Icarus lab. Bus-functional models stand in for both harts.
Now the same program with the pair. Set MODE to 1.
e1 hart=0 op=lr addr=80000004 wdata=00000000 result=00000000 resv=01 msip=00
e2 hart=1 op=lr addr=80000004 wdata=00000000 result=00000000 resv=11 msip=00
e3 hart=0 op=sc addr=80000004 wdata=00000001 result=00000000 resv=00 msip=00
e4 hart=1 op=sc addr=80000004 wdata=00000001 result=00000001 resv=00 msip=00
e6 hart=1 op=lr addr=80000004 wdata=00000000 result=00000001 resv=11 msip=00
counter=6 expected=6 sc_failures=3 lock_spins=0 bus_edges=25Rule 2, in rows e1 and e2: resv goes to 01 and then to 11. Both harts hold a reservation on the counter.
Rules 3 and 4, in row e3. The store-conditional of hart 0 returns 0, so it wrote. resv falls to 00: that write ended the reservation of hart 1 as well.
Rule 6, in rows e4 and e6. The store-conditional of hart 1 returns 1. At e6 hart 1 loads again and gets 1, the new value.
The last line reads counter=6 with sc_failures=3. The three failures are the three counts that the plain run lost. The price is time: 25 bus edges in place of 13.
This lab leaves things out. The reservation and the monitor are test code beside the memory, not a block of the chip. No processor runs, so nothing can interrupt a hart between its two accesses.
Why It Is Built This Way
| Design choice | The alternative | What the choice buys, and costs |
|---|---|---|
| The store checks, and the loser tries again | Lock the bus for the load and the store | Nobody waits who does not use the word. The loser pays two more accesses for each try. |
| The check sits beside the memory | Each hart watches the other | One place sees every write, also those of DMA and the debugger. Every route to the memory must pass it. |
| One reservation for each hart | A reservation on every word | One address register for each hart is enough. A hart cannot hold two words at once. |
On a bus the pair travels as two marked transfers. The bus also has a second and a third way to make an update atomic. The next lesson, Atomic Operations on the Bus, compares the three.
The Trap: The Loop That Never Wins
A retry loop ran well for months. Then someone added a line between the load-reserved and the store-conditional: one more load, from another word. On one chip the loop never ended.
On that chip any other use of memory ended the reservation. So every store-conditional came back with 1, every time, for ever. The rule of thumb in the textbooks is short: between the two instructions, work on registers only.
The second trap is the write that the monitor does not see. A team put the monitor on the port of the processors. The DMA got a port of its own to the same memory. A DMA write changed the word, and no reservation ended. Two harts both got a 0 from their store-conditional, and both believed they held the lock.
The third trap is to treat the 1 as a failure of the chip. It is the normal answer when someone else was first.
At Scale
This section looks ahead. Two harts and one word become many harts, caches and several memories.
A wider reservation
A monitor may watch a block of bytes around the address, not one word. It is cheaper, and a write to a neighbour then ends the reservation too.
Many harts, one word
With many harts on one counter, most store-conditionals fail. Bus time goes into retries. Software then gives each hart a counter of its own.
Caches in between
With a cache at each hart, the newest value may not be in memory at all. Cache Coherence deals with that.
The same idea on the bus
A bus carries the pair as an exclusive read and an exclusive write. The next lesson shows them beside two other tools.
Try It
Run the lab with MODE at 0. Find the two loads that return the same value.
Set MODE to 1. Find the first store-conditional whose result is 1, and the write that ended its reservation.
Keep MODE at 1 and set TIMES to 1. How many store-conditionals fail now, and why can it not be zero?
Names Printed by the Lab
| Name | Meaning |
|---|---|
| e0, e1, ... | Rising edges of the clock. The bus serves one access on an edge, or none. |
| hart | The hart whose access was served on that edge. |
| op | The kind of access: load, store, lr for a load-reserved, sc for a store-conditional. |
| result | For a load, the value read. For a store-conditional, 0 for written and 1 for not written. |
| resv | The reservations after that edge, written as hart 1, then hart 0. So 01 means that only hart 0 holds one. |
| sc_failures | How many store-conditionals did not write. |
| bus_edges | How many clock edges the whole run took. |
| msip, lock_spins | Not used on this page. They belong to the lessons before and after. |
e0 hart=- op=idle resv=00 msip=00 e1 hart=0 op=load addr=80000004 wdata=00000000 result=00000000 resv=00 msip=00 e2 hart=1 op=load addr=80000004 wdata=00000000 result=00000000 resv=00 msip=00 e3 hart=0 op=store addr=80000004 wdata=00000001 result=00000000 resv=00 msip=00 e4 hart=1 op=store addr=80000004 wdata=00000001 result=00000000 resv=00 msip=00 e5 hart=0 op=load addr=80000004 wdata=00000000 result=00000001 resv=00 msip=00 e6 hart=1 op=load addr=80000004 wdata=00000000 result=00000001 resv=00 msip=00 e7 hart=0 op=store addr=80000004 wdata=00000002 result=00000000 resv=00 msip=00 e8 hart=1 op=store addr=80000004 wdata=00000002 result=00000000 resv=00 msip=00 e9 hart=0 op=load addr=80000004 wdata=00000000 result=00000002 resv=00 msip=00 e10 hart=1 op=load addr=80000004 wdata=00000000 result=00000002 resv=00 msip=00 e11 hart=0 op=store addr=80000004 wdata=00000003 result=00000000 resv=00 msip=00 e12 hart=1 op=store addr=80000004 wdata=00000003 result=00000000 resv=00 msip=00 counter=3 expected=6 sc_failures=0 lock_spins=0 bus_edges=13Read included file: soc-s91-msip.sv
// ap_clint, software-interrupt slice, for the dual-hart option of ap_soc.
// Design choice: one msip bit per hart, in the word at byte offset 4 * hart id
// from the ap_clint base. Bit 0 of a written word sets or clears that request.
// The timer registers (mtime, mtimecmp) are not part of this slice.
module ap_clint_msip #(parameter int HARTS = 2) (
input logic clk, reset_n,
input logic sel, write,
input logic [15:0] offset, // byte offset inside the 64 KiB ap_clint window
input logic [31:0] wdata,
output logic [31:0] rdata,
output logic [HARTS-1:0] msip // one software-interrupt request per hart
);
wire [13:0] hart = offset[15:2];
wire hit = sel && offset[1:0] == 2'b00 && hart < HARTS;
always_ff @(posedge clk) begin
if (!reset_n)
msip <= '0;
else if (hit && write)
msip[hart] <= wdata[0];
end
assign rdata = hit && !write ? {31'b0, msip[hart]} : 32'b0;
endmodule
Read included file: soc-s91-harts.svh
// Include inside the testbench module of an S9 lab.
// Two hart bus-functional models share one bus. ap_rv32 is built later in the
// track, so each task issues the bus request that one load, store or atomic
// instruction would issue. Aligned words only. SRAM holds 16 words here.
localparam logic [31:0] CLINT = 32'h0200_0000, SRAM = 32'h8000_0000;
localparam logic [2:0] LOAD = 0, STORE = 1, LR = 2, SC = 3, SWAP = 4;
logic clk = 0, reset_n = 0;
always #5 clk = ~clk;
// One request slot per hart. The bus serves one slot per rising edge.
logic [1:0] req = 0, served = 0;
logic [2:0] op [2];
logic [31:0] addr [2], wdata [2], rdata [2];
logic last = 1; // the hart served most recently; a tie goes to the other one
wire busy = |req;
wire pick = req == 2'b11 ? !last : req[1];
wire [2:0] bus_op = pick ? op[1] : op[0];
wire [31:0] bus_addr = pick ? addr[1] : addr[0];
wire [31:0] bus_wdata = pick ? wdata[1] : wdata[0];
wire to_clint = bus_addr[31:16] == CLINT[31:16];
// ap_clint software-interrupt slice: msip[h] is hart h's wake-up request.
wire [1:0] msip;
wire [31:0] clint_rdata;
ap_clint_msip clint (
.clk(clk), .reset_n(reset_n), .sel(busy && to_clint), .write(bus_op == STORE),
.offset(bus_addr[15:0]), .wdata(bus_wdata), .rdata(clint_rdata), .msip(msip)
);
// Shared SRAM, and the lab's reservation model: one word address per hart.
logic [31:0] sram [16];
logic [1:0] resv = 0;
logic [31:0] resv_addr [2];
initial for (int i = 0; i < 16; i++) sram[i] = 0;
bit trace = 0;
int trace_limit = 16, edge_no = 0;
function automatic string op_name(input logic [2:0] code);
case (code)
LOAD: return "load"; STORE: return "store"; LR: return "lr";
SC: return "sc"; default: return "swap";
endcase
endfunction
// Every committed write ends the reservations that cover its word.
task automatic commit_write(input logic [31:0] a, input logic [31:0] d);
sram[a[5:2]] = d;
for (int h = 0; h < 2; h++)
if (resv[h] && resv_addr[h] == a) resv[h] = 0;
endtask
always @(posedge clk) begin
logic [31:0] result;
served = 0;
result = 0;
if (busy) begin
last = pick;
if (to_clint) result = clint_rdata;
else begin
result = sram[bus_addr[5:2]];
case (bus_op)
STORE: begin commit_write(bus_addr, bus_wdata); result = 0; end
LR: begin resv[pick] = 1; resv_addr[pick] = bus_addr; end
SC: begin
// Like a store-exclusive: 0 means it wrote, 1 means it did not.
if (resv[pick] && resv_addr[pick] == bus_addr) begin
commit_write(bus_addr, bus_wdata);
result = 0;
end else result = 1;
resv[pick] = 0;
end
SWAP: commit_write(bus_addr, bus_wdata);
default: ;
endcase
end
rdata[pick] = result;
served[pick] = 1;
end
if (trace && edge_no < trace_limit) begin
if (busy)
$display("e%0d hart=%0d op=%s addr=%08h wdata=%08h result=%08h resv=%b msip=%b",
edge_no, pick, op_name(bus_op), bus_addr, bus_wdata, result, resv, msip);
else
$display("e%0d hart=- op=idle resv=%b msip=%b", edge_no, resv, msip);
end
if (trace) edge_no++;
end
task automatic start();
repeat (2) @(negedge clk);
reset_n = 1;
trace = 1;
endtask
// One bus access for hart h: post the request, wait for the edge that serves it.
task automatic access(input int h, input logic [2:0] kind, input logic [31:0] a,
input logic [31:0] d, output logic [31:0] q);
@(negedge clk);
op[h] = kind;
addr[h] = a;
wdata[h] = d;
req[h] = 1;
do @(negedge clk); while (!served[h]);
req[h] = 0;
q = rdata[h];
endtask
task automatic store(input int h, input logic [31:0] a, input logic [31:0] d);
logic [31:0] ignored;
access(h, STORE, a, d, ignored);
endtask
task automatic load(input int h, input logic [31:0] a, output logic [31:0] q);
access(h, LOAD, a, 0, q);
endtask
task automatic load_reserved(input int h, input logic [31:0] a, output logic [31:0] q);
access(h, LR, a, 0, q);
endtask
task automatic store_conditional(input int h, input logic [31:0] a, input logic [31:0] d,
output logic [31:0] status);
access(h, SC, a, d, status);
endtask
task automatic swap(input int h, input logic [31:0] a, input logic [31:0] d,
output logic [31:0] old);
access(h, SWAP, a, d, old);
endtask
// Wait for interrupt: sleep until msip[h] rises, or give up after 40 cycles.
task automatic wfi(input int h, output bit woke);
woke = 0;
for (int i = 0; i < 40 && !woke; i++) begin
@(negedge clk);
woke = msip[h];
end
endtask
Check Yourself
Common Mistakes
Wrong Treat a store-conditional that returns 1 as an error.
It is the normal answer when another write was first.
Fix Load again and try again.
Wrong Put the monitor where a DMA write can pass it by.
A reservation then outlives a real change, and two harts both win.
Fix Put it where it sees every write to the memory.
Wrong Do other memory work between the load-reserved and the store-conditional.
It can end the reservation every time.
Fix Use registers only between the two.
Remember
- A load and a store from two harts can lose an update, and no access fails.
- A load-reserved leaves a reservation. A store-conditional writes only while it stands.
- A write by anybody else ends the reservation, so the monitor must see every write.
- A store-conditional that did not write is not an error: load again and try again.