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.

Five questions this page answers
Question
1What does a swap do, and how do two harts build a lock from it?
2How is an exclusive write answered on the bus, and by whom?
3Who waits during a locked sequence?
4Which of the three tools can guard an update of several words?
5One 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

New words on this page
WordMeaning
Atomic swapWrite a new value to a word and get the old value back, as one step. This page says swap for short.
Lock wordA 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 lockA lock that a hart takes by trying the swap again and again until a 0 comes back.
Critical sectionThe code between taking a lock and giving it back. One hart at a time may be in it.
Exclusive transferA bus transfer that is marked as half of a pair: an exclusive read, then an exclusive write.
HEXCLThe AHB wire that marks a transfer as exclusive. It travels with the address.
HEXOKAYThe AHB wire with which the monitor answers an exclusive write: 1 means written.
HMASTERThe AHB wires that say which manager made a transfer. The monitor needs them to keep the reservations apart.

One Picture: Swap, Pair, Locked Sequence

Three Tools, and Who WaitsStep through the picture. Each step is one way to make an update atomic, and each makes somebody else wait.
  • Processor
  • Peripheral
  • Bus
  • Control / FSM
  • Memory
Three Tools, and Who WaitsStep through the picture. Each step is one way to make an update atomic, and each makes somebody else wait. component Hart 0 wants to changeshared data component Hart 1 wants the same data component DMA a third manager, withother work component Arbiter chooses the managerthat is served component Monitor answers an exclusivewrite: written or not component Lock word 0 is free, 1 is taken component Shared data one word or many requestrequestrequestswapload, storeexclusive read,exclusive write
  1. component Hart 0wants to change shared data
    • request → Arbiter
  2. component Hart 1wants the same data
    • request → Arbiter
  3. component Arbiterchooses the manager that is served
    • swap → Lock word
    • load, store → Shared data
    • exclusive read, exclusive write → Monitor
  4. component Shared dataone word or many
  5. component Lock word0 is free, 1 is taken
  6. component Monitoranswers an exclusive write: written or not
  7. component DMAa third manager, with other work
    • request → Arbiter
  1. The problem

    Two harts want to change the same data. A load and a store from each can mix, as the last lesson showed.

  2. 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.

  3. 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.

  4. 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.

Two harts and one spin lock
StepHart 0Hart 1Lock word afterData after
1Swaps in 1, gets 0: holds the lock10
2Swaps in 1, gets 1: not free10
3Loads the data, gets 010
4Swaps in 1, gets 110
5Stores 1 to the data11
6Swaps in 1, gets 111
7Stores 0 to the lock word01
8Swaps in 1, gets 0: holds the lock11

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

  1. 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.

  2. 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.

  3. Rule 3: The holder gives the lock back last.

    It stores 0 to the lock word only after its last write to the data.

  4. 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.

  5. Rule 5: A locked sequence keeps the bus.

    The manager holds HMASTLOCK at 1. The arbiter must serve no other manager between its transfers.

  6. 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.

Printed by the lab on Icarus with TOOL = 0: six of its accesses and its last line. For a swap, result is the old value.
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=15

Rule 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

ToolWhat it can guardWho waitsWho carries the promise
Spin lock, built from a swapAny number of words, or a deviceThe loser, and it spends bus time while it spinsSoftware: every user must take the lock
Exclusive pairOne wordNobody. The loser repeats two transfersThe monitor, which must see every write
Locked sequenceWhat one short sequence touchesEvery other manager on that busThe 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 page2 harts, 1 lock
A server chipdozens of cores

This section looks ahead, to other buses and to larger chips.

  1. 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.

  2. 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.

  3. 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.

  4. 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
NameMeaning
e0, e1, ...Rising edges of the clock. The bus serves one access on an edge, or none.
hart, opThe hart that was served, and the kind of access: swap, load, store, lr or sc.
resultFor a swap, the old value of the word. For a load, the value read.
wordThe first data word at the end of the run. Each hart added 1 to it.
spinsHow many swaps returned 1: tries that did not get the lock.
retriesWith TOOL at 1: how many store-conditionals did not write.
bus_edgesHow many clock edges the whole run took.
resv, msipThe reservations and the wake-up bits of the two lessons before. Not used with TOOL at 0.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: 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=15
Read 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

Predict the outputIn this run one update changes two words under the lock (WORDS = 2). What is the last line? Its form is: word=2 spins=.. retries=0 bus_edges=23
module tb;
  `include "soc-s91-harts.svh"
  // The tool that makes an update atomic.
  // 0: a spin lock built from a swap. 1: a load-reserved and a store-conditional.
  localparam int TOOL = 0;
  localparam int TIMES = 1;   // updates made by each hart
  localparam int WORDS = 2;   // words that one update changes while it holds the lock
  localparam logic [31:0] LOCK = SRAM, DATA = SRAM + 32'h4;
  int spins = 0, retries = 0;

  task automatic update(input int h);
    logic [31:0] value, old, status;
    if (TOOL == 0) begin
      swap(h, LOCK, 1, old);               // write 1, get the old value back
      while (old != 0) begin               // someone holds the lock: try again
        spins++;
        swap(h, LOCK, 1, old);
      end
      for (int w = 0; w < WORDS; w++) begin
        load(h, DATA + 4 * w, value);
        store(h, DATA + 4 * w, value + 1);
      end
      store(h, LOCK, 0);                   // release
    end else do begin
      load_reserved(h, DATA, value);
      store_conditional(h, DATA, value + 1, status);
      retries += status;
    end while (status != 0);
  endtask

  task automatic hart(input int h);
    repeat (TIMES) update(h);
  endtask

  initial begin
    trace_limit = 64;
    start();
    fork hart(0); hart(1); join
    $display("word=%0d spins=%0d retries=%0d bus_edges=%0d", sram[1], spins, retries, edge_no);
    $finish;
  end
endmodule
Read 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
ConceptHow does a hart know that it holds a spin lock?
ConceptWho answers an exclusive write on the bus?
ConceptWho waits during a locked sequence?
ConceptAn update must change three words together. Which tool fits?

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.

Practice

Report a problem with this page