Atomic Operations on the Bus: Swap, Exclusive and Locked Transfers
A bus offers three tools that make an update atomic: a swap, an exclusive pair and a locked sequence. All three give the right answer. They differ in who waits while one hart works.
You Will Be Able To
- Build a lock from a swap, and follow two harts through it.
- Describe an exclusive read and write on the bus, and say who answers the write.
- Compare the three tools by who waits, and name the block that carries each promise.
- Lesson
- S9.7
- Time
- 25 min
- Runs on
- Your browser
- Check
- 5 questions
A field log shows two harts inside the same piece of code at the same time, and a lock guards that code.
Each hart had found the code free, and each had then marked it as taken. So something came between a read and the write that followed it.
Before You Start
You need Atomic Operations: The Lost Update and LR/SC: the lost update, the reservation and the monitor.
You need Bursts, Locks and the Waiting Request: a locked sequence, and the wire HMASTLOCK.
You need Many Managers: Arbitration and the Bus Matrix: the arbiter chooses which manager is served.
| Question | |
|---|---|
| 1 | What does a swap do, and how do two harts build a lock from it? |
| 2 | How is an exclusive write answered on the bus, and by whom? |
| 3 | Who waits during a locked sequence? |
| 4 | Which of the three tools can guard an update of several words? |
| 5 | One update changes two words under the lock. What does the lab print last? |
The Idea: Three Tools, One Question
The last lesson made one update of one word atomic, with a store that checks. Real code often needs more. Several words must change together, or a device may be used by one hart at a time. For that, software uses a lock.
A lock is one word in memory. 0 means free and 1 means taken. To take it, a hart must read the word and write a 1, and nothing may come between the two. That is a swap: write a new value and get the old one back, as one step. If the old value was 0, the hart now holds the lock. If it was 1, someone else does, and the hart tries again. A lock used this way is a spin lock.
The bus must make the swap one step. It has three tools for an atomic update. The memory can do the read and the write itself, in one transfer. The monitor of the last lesson can answer a marked pair of transfers. Or one manager can keep the bus for both transfers.
All three give the right answer. So ask a different thing of each: while one hart works, who waits?
New Words
| Word | Meaning |
|---|---|
| Atomic swap | Write a new value to a word and get the old value back, as one step. This page says swap for short. |
| Lock word | A word that says whether shared data is in use. Here 0 is free and 1 is taken. Holding the lock means having set it to 1. |
| Spin lock | A lock that a hart takes by trying the swap again and again until a 0 comes back. |
| Critical section | The code between taking a lock and giving it back. One hart at a time may be in it. |
| Exclusive transfer | A bus transfer that is marked as half of a pair: an exclusive read, then an exclusive write. |
| HEXCL | The AHB wire that marks a transfer as exclusive. It travels with the address. |
| HEXOKAY | The AHB wire with which the monitor answers an exclusive write: 1 means written. |
| HMASTER | The AHB wires that say which manager made a transfer. The monitor needs them to keep the reservations apart. |
One Picture: Swap, Pair, Locked Sequence
- Processor
- Peripheral
- Bus
- Control / FSM
- Memory
- The problem
Two harts want to change the same data. A load and a store from each can mix, as the last lesson showed.
- A lock word and a swap
A hart swaps a 1 into the lock word. If a 0 comes back, it holds the lock and may change the data. The other hart keeps trying.
- An exclusive pair
A hart marks its read and its write as exclusive. The monitor lets the write through only if nobody wrote in between. Only the loser repeats.
- A locked sequence
A hart keeps the bus for its read and its write. The arbiter serves nobody else in between, so the DMA waits too.
Read the diagram as text
- Hart 0: wants to change shared data
- Hart 1: wants the same data
- DMA: a third manager, with other work
- Arbiter: chooses the manager that is served
- Monitor: answers an exclusive write: written or not
- Lock word: 0 is free, 1 is taken
- Shared data: one word or many
- Hart 0 → Arbiter: request
- Hart 1 → Arbiter: request
- DMA → Arbiter: request
- Arbiter → Lock word: swap
- Arbiter → Shared data: load, store
- Arbiter → Monitor: exclusive read, exclusive write
A swap, an exclusive pair and a locked sequence. The first makes the loser spin, the second makes the loser repeat, the third makes everybody wait.
The Smallest Example, Worked by Hand
No simulator yet. The lock word holds 0 and the data word holds 0. Each hart wants to add 1 to the data, under the lock. The bus serves the two harts in turn: hart 0 on odd steps, hart 1 on even steps.
| Step | Hart 0 | Hart 1 | Lock word after | Data after |
|---|---|---|---|---|
| 1 | Swaps in 1, gets 0: holds the lock | 1 | 0 | |
| 2 | Swaps in 1, gets 1: not free | 1 | 0 | |
| 3 | Loads the data, gets 0 | 1 | 0 | |
| 4 | Swaps in 1, gets 1 | 1 | 0 | |
| 5 | Stores 1 to the data | 1 | 1 | |
| 6 | Swaps in 1, gets 1 | 1 | 1 | |
| 7 | Stores 0 to the lock word | 0 | 1 | |
| 8 | Swaps in 1, gets 0: holds the lock | 1 | 1 |
Read steps 2, 4 and 6. Hart 1 used the bus three times and got nothing done. Its swaps did no harm either: each wrote a 1 where a 1 already was. Hart 0 was never disturbed between its load and its store.
Read step 7. Hart 0 gives the lock back only after its store of step 5. One step later hart 1 gets a 0 and goes on to load the data, which now holds 1.
The Rules
Rule 1: A swap is one step.
No other manager is served between its read and its write. The bus, or the memory, must see to that.
Rule 2: A hart holds the lock when its swap of 1 returns 0.
A swap that returns 1 changed nothing: the word held 1 already.
Rule 3: The holder gives the lock back last.
It stores 0 to the lock word only after its last write to the data.
Rule 4: An exclusive write is answered by the monitor.
HEXCL marks the read and the write. HEXOKAY at 1 says that the write went through. At 0, memory is unchanged.
Rule 5: A locked sequence keeps the bus.
The manager holds HMASTLOCK at 1. The arbiter must serve no other manager between its transfers.
Rule 6: Choose the tool by who waits.
A spin lock: the loser spins. An exclusive pair: the loser repeats. A locked sequence: every other manager waits.
Sources for These Rules
Exclusive transfers, HEXCL, HMASTER and HEXOKAY: Arm AMBA AHB Protocol Specification, IHI 0033 issue C, sections 10.1 to 10.3.
The write goes through only if no other manager wrote the address since the read: the same specification, section 10.1.
Locked transfers with HMASTLOCK, and that a read followed by a write is their usual use: the same specification, section 3.3.
The arbiter must grant no other manager until a locked sequence has ended: Arm AMBA Specification, Rev 2.0, IHI 0011A, section 3.11.5.
A lock built from an atomic exchange, with 0 for free and 1 for taken: Patterson and Hennessy, Computer Organization and Design, ARM edition, section 2.11.
Rule 3 is common practice, shown by the hand example. In our lab the bus model does a swap in one access. That is a choice of the lab.
Now Run It
The lab at the end of this page is the hand example. Two harts, a lock word at address 80000000 in hex and a data word at 80000004. Each hart is a bus-functional model: test code that makes the accesses of a program.
e1 hart=0 op=swap addr=80000000 wdata=00000001 result=00000000 resv=00 msip=00
e2 hart=1 op=swap addr=80000000 wdata=00000001 result=00000001 resv=00 msip=00
e3 hart=0 op=load addr=80000004 wdata=00000000 result=00000000 resv=00 msip=00
e5 hart=0 op=store addr=80000004 wdata=00000001 result=00000000 resv=00 msip=00
e7 hart=0 op=store addr=80000000 wdata=00000000 result=00000000 resv=00 msip=00
e8 hart=1 op=swap addr=80000000 wdata=00000001 result=00000000 resv=00 msip=00
word=2 spins=3 retries=0 bus_edges=15Rule 2 at work, in rows e1 and e2. The swap of hart 0 returns 0, and the swap of hart 1 returns 1.
Rule 3, in rows e5 and e7. Hart 0 stores the data first and the 0 to the lock word afterwards. At e8 the swap of hart 1 returns 0.
Rule 6, in the last line: spins=3. Hart 1 was served on e2, e4 and e6 and gained nothing. The whole run takes 15 edges.
Now the second tool. With TOOL at 1 the two updates use a load-reserved and a store-conditional. The lab then ends with "word=2 spins=0 retries=1 bus_edges=9". One try of hart 1 failed, and it repeated two accesses. Nobody spun.
The gap grows with the work. With three updates for each hart, the lock costs 15 spins and 43 edges. The pair costs 3 retries and 25 edges.
This lab leaves things out. It has no arbiter with HMASTLOCK and no wire named HEXCL. The bus model does a swap in one access and keeps the reservations itself. A locked sequence on a real arbiter is the subject of the practice problem "A Lock That Two Harts Entered".
Why It Is Built This Way
| Tool | What it can guard | Who waits | Who carries the promise |
|---|---|---|---|
| Spin lock, built from a swap | Any number of words, or a device | The loser, and it spends bus time while it spins | Software: every user must take the lock |
| Exclusive pair | One word | Nobody. The loser repeats two transfers | The monitor, which must see every write |
| Locked sequence | What one short sequence touches | Every other manager on that bus | The arbiter |
So the tools are not rivals. A swap is itself made atomic by one of the other two: on AHB it is a locked read and write. An exclusive pair guards one word, and a lock is the way to guard many.
The Trap: A Lock That Two Harts Entered
This is the field log from the top of the page. Each hart took the lock with a locked read and write of the lock word. Under load, both harts read 0.
The arbiter had a fault. It gave the bus to hart 1 while hart 0 was between its locked read and its locked write. Both reads saw a free lock, and both writes stored a 1. Every transfer was legal by itself. The promise of rule 5 was broken in one cycle, and only an arbiter can break it.
The second trap is the hart that sleeps with the lock. An interrupt arrives inside the critical section, and its handler wants the same lock. The handler spins for ever, because the code that would give the lock back is the code it interrupted.
The third trap is the long critical section. Rule 6 says that the loser spins. In the lab one more word under the lock costs hart 1 two more spins.
At Scale
This section looks ahead, to other buses and to larger chips.
The same pair on AXI
AXI also has exclusive transfers. It tells managers apart by the ID of the transfer, and answers the write with a response of its own.
Send the work to the data
Newer AXI can carry a whole swap, or a compare and store, as one transaction. The memory does it, so the word is busy for a shorter time.
A cache in front of the monitor
An exclusive transfer must reach the monitor. With a cache in between it must be marked so that the cache does not answer it.
Many harts, one lock
With many harts most swaps fail, and the bus fills with spins. Software then lets a waiting hart sleep, or splits the data so that fewer harts share a lock.
Try It
Run the lab. Count the rows in which a swap returns 1. Which hart made them, and what was the other hart doing?
Set TOOL to 1. The same two updates now use a load-reserved and a store-conditional. Compare bus_edges.
Set TOOL back to 0 and WORDS to 3. One update now changes three words under one lock. What happens to spins?
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, op | The hart that was served, and the kind of access: swap, load, store, lr or sc. |
| result | For a swap, the old value of the word. For a load, the value read. |
| word | The first data word at the end of the run. Each hart added 1 to it. |
| spins | How many swaps returned 1: tries that did not get the lock. |
| retries | With TOOL at 1: how many store-conditionals did not write. |
| bus_edges | How many clock edges the whole run took. |
| resv, msip | The reservations and the wake-up bits of the two lessons before. Not used with TOOL at 0. |
e0 hart=- op=idle resv=00 msip=00 e1 hart=0 op=swap addr=80000000 wdata=00000001 result=00000000 resv=00 msip=00 e2 hart=1 op=swap addr=80000000 wdata=00000001 result=00000001 resv=00 msip=00 e3 hart=0 op=load addr=80000004 wdata=00000000 result=00000000 resv=00 msip=00 e4 hart=1 op=swap addr=80000000 wdata=00000001 result=00000001 resv=00 msip=00 e5 hart=0 op=store addr=80000004 wdata=00000001 result=00000000 resv=00 msip=00 e6 hart=1 op=swap addr=80000000 wdata=00000001 result=00000001 resv=00 msip=00 e7 hart=0 op=store addr=80000000 wdata=00000000 result=00000000 resv=00 msip=00 e8 hart=1 op=swap addr=80000000 wdata=00000001 result=00000000 resv=00 msip=00 e9 hart=- op=idle resv=00 msip=00 e10 hart=1 op=load addr=80000004 wdata=00000000 result=00000001 resv=00 msip=00 e11 hart=- op=idle resv=00 msip=00 e12 hart=1 op=store addr=80000004 wdata=00000002 result=00000000 resv=00 msip=00 e13 hart=- op=idle resv=00 msip=00 e14 hart=1 op=store addr=80000000 wdata=00000000 result=00000000 resv=00 msip=00 word=2 spins=3 retries=0 bus_edges=15Read 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 Give the lock back before the last write to the data.
The next holder loads data that is about to change.
Fix Store 0 to the lock word last.
Wrong Use locked sequences freely on a busy bus.
Every other manager waits for the whole sequence.
Fix Keep them to a read and a write, or use an exclusive pair.
Wrong Guard several words with one exclusive pair.
A reservation covers one address.
Fix Use the pair for one word, and a lock for more.
Remember
- A swap is one step. A hart holds the lock when its swap of 1 returns 0.
- An exclusive pair is answered by the monitor, and only the loser repeats.
- A locked sequence keeps the bus, and the arbiter carries the promise.
- Choose the tool by who waits, and by how many words must change together.