More Than One Core

A second processor on the chip does nothing until someone starts it. Starting it takes two stores, in the right order, and the second one must go to the right address.

You Will Be Able To

  • Explain how two identical harts that start at one address take two different jobs.
  • Wake a parked hart with a software interrupt, and say why the woken hart clears the request.
  • Show why the data must be written before the wake-up.
Lesson
S9.1
Time
25 min
Runs on
Your browser
Check
5 questions

The first chip with two processors comes up on the bench. Hart 0 prints its banner, the console waits for hart 1, and nothing arrives.

Two identical processors, and one never started.

Before You Start

You need A Processor in One Picture: the PC, registers, and a load or a store as a bus transfer.

You need Reset and Interrupts in One Picture: the reset address, an interrupt request and a pending bit.

It helps to have read Many Managers: Arbitration and the Bus Matrix: two managers share one bus.

Five questions this page answers
Question
1Two harts leave reset at the same address. How does each one know its job?
2What does a parked hart wait for?
3Which store wakes hart 1, and why does hart 1 clear the bit afterwards?
4Why must the mailbox be written before the wake-up?
5Hart 0 writes the wake-up to the wrong word. What does the lab print last?

The Idea: One Starts, the Others Wait to Be Told

For a long time a chip got faster by running one program faster. Then the power that this took became the limit. So designers put several processors on one chip. Each is called a core. Two cores can do two pieces of work at the same time.

RISC-V has a more exact word. A hart is one hardware thread: one PC and one set of registers. On our chip each core is one hart, so this page says hart.

Two harts bring a problem on the first clock edge. Both leave reset together, and both fetch from the same reset address. If both run the start-up code, they clear the same memory twice and build one stack on top of the other.

The way out is a number. Every hart has a fixed hart id, and its first instructions read it. Hart 0 carries on: it is the boot hart. Every other hart parks: it stops and waits for an interrupt.

Later the boot hart must start the others. It cannot reach into another hart and set its PC. A hart can only load and store. So the wake-up is a store: one bit, at a known address, that raises an interrupt request at one hart. And before that store, the boot hart writes down where the other hart must begin.

New Words

New words on this page
WordMeaning
Processor coreOne complete processor on a chip. This page says core for short.
HartThe RISC-V word for one hardware thread: one PC and one set of registers.
Hart idA fixed number, different for each hart. In RISC-V a hart reads it from a register named mhartid.
Boot hartThe one hart that runs the start-up code. Here it is hart 0.
Parked hartA hart that was stopped on purpose. It does nothing until an interrupt arrives.
wfiWait for interrupt: the RISC-V instruction that stops a hart until an interrupt request is pending.
Interrupt from softwareAn interrupt request that software raises by writing a register bit. No device asks for it. Engineers say software interrupt.
msipThe software interrupt bit of one hart. Each hart has one, in a word of its own.
MailboxA memory word that two harts agree on. One writes a message there, and the other reads it.
Entry addressThe address at which a hart must start to run. Here it is the message in the mailbox.

One Picture: Park, Publish, Wake

Two Harts, One Mailbox and One Wake-Up BitStep through the picture. It starts with two harts at reset and ends with both at work.
  • Processor
  • Bus
  • Memory
  • Peripheral
Two Harts, One Mailbox and One Wake-Up BitStep through the picture. It starts with two harts at reset and ends with both at work. component Hart 0 hart id 0: the boothart component Hart 1 hart id 1: parks, thenwaits component Bus both harts aremanagers on it component Mailbox one word of SRAM:where hart 1 muststart component Wake-up bit ofhart 1 a register bit thatany hart can write storeswrite the startaddresswrite 1software interruptclears the bit, readsthe mailbox
  1. component Hart 0hart id 0: the boot hart
    • stores → Bus
  2. component Hart 1hart id 1: parks, then waits
    • clears the bit, reads the mailbox → Bus
  3. component Busboth harts are managers on it
    • write the start address → Mailbox
    • write 1 → Wake-up bit of hart 1
  4. component Mailboxone word of SRAM: where hart 1 must start
  5. component Wake-up bit of hart 1a register bit that any hart can write
    • software interrupt → Hart 1
  1. The same start

    Both harts leave reset together and fetch from the same address. Each reads its own hart id first.

  2. One boots, one parks

    Hart 0 runs the start-up code. Hart 1 does nothing: it waits for an interrupt.

  3. Publish

    Hart 0 writes into the mailbox the address at which hart 1 must start.

  4. Wake

    Hart 0 writes 1 to the wake-up bit of hart 1. The bit raises a software interrupt at hart 1.

  5. Clear and go

    Hart 1 wakes, writes 0 to its own bit, reads the mailbox and jumps to that address.

Read the diagram as text
  • Hart 0: hart id 0: the boot hart
  • Hart 1: hart id 1: parks, then waits
  • Bus: both harts are managers on it
  • Mailbox: one word of SRAM: where hart 1 must start
  • Wake-up bit of hart 1: a register bit that any hart can write
  • Hart 0 → Bus: stores
  • Bus → Mailbox: write the start address
  • Bus → Wake-up bit of hart 1: write 1
  • Wake-up bit of hart 1 → Hart 1: software interrupt
  • Hart 1 → Bus: clears the bit, reads the mailbox

The wake-up of a second hart. Hart 0 can only write to addresses. It cannot reach into hart 1.

The Smallest Example, Worked by Hand

No simulator yet. Hart 1 is parked. Its entry address is 200. The mailbox holds 0, left there by reset. Hart 0 has two stores to make. First take them in the right order.

Publish first, then wake
StepHart 0Hart 1MailboxWake-up bit
1Stores 200 to the mailboxParked2000
2Stores 1 to the wake-up bitParked2001
3Wakes, stores 0 to the bit2000
4Loads the mailbox, gets 200, jumps to 2002000

Now put the two stores of hart 0 in the other order. Nothing else changes.

Wake first: the same four moves in the wrong order
StepHart 0Hart 1MailboxWake-up bit
1Stores 1 to the wake-up bitParked01
2Wakes, stores 0 to the bit00
3Loads the mailbox, gets 0, jumps to 000
4Stores 200 to the mailboxRuns from address 02000

Read step 3 of the second table. Hart 1 was fast, and the mailbox still held 0. Address 0 is the reset address, so hart 1 runs the start-up code a second time. The store of step 4 is correct and too late.

The Rules

  1. Rule 1: Every hart reads its hart id first.

    One hart boots. Every other hart parks.

  2. Rule 2: A parked hart is woken by an interrupt, and by nothing else.

    A software interrupt is the one that another hart can raise with a store.

  3. Rule 3: Each hart has a wake-up bit of its own.

    On ap_soc the word for hart h is at the base of ap_clint plus 4 times h.

  4. Rule 4: The woken hart clears its own bit.

    The bit is a level. While it stays 1, the request stays pending and is taken again.

  5. Rule 5: Publish first, then wake.

    A wake-up says "look now". It does not say that the data is there.

  6. Rule 6: What belongs to one hart is copied. The rest is shared.

    The table below sorts the parts.

What each hart owns on ap_soc
PartHow manyWhy
Registers and PCOne set for each hartEach hart runs a program of its own.
Wake-up bit and timer compare valueOne for each hartA wake-up or a deadline is meant for one hart.
Time counterOne for the chipBoth harts must agree on the time.
SRAM, the mailbox and UART0One for the chipShared parts are how harts work together.
StackOne for each hart, cut from the shared SRAMTwo harts on one stack overwrite each other.
Sources for These Rules

Why chips moved to several processors: Patterson and Hennessy, Computer Organization and Design, ARM edition, sections 1.8 and 6.1.

The part of a job that only one processor can do limits the gain: the same book, section 6.2.

All processors of a shared-memory machine see one address space: the same book, section 6.5.

Hart, mhartid, msip and wfi are RISC-V names. The RISC-V manuals are not in our reference library, so these names are used unchecked, and no rule here is stated as a rule of RISC-V.

The place of the wake-up words (4 bytes for each hart id), the mailbox and its address are choices of ap_soc. The layout follows a common RISC-V convention, also unchecked.

Now Run It

The lab at the end of this page has two harts on one bus. Each hart is a bus-functional model: test code that makes the loads and stores that a program would make. The mailbox is the first word of SRAM, at address 80000000 in hex. The wake-up word of hart 1 is at 02000004.

Printed by the lab on Icarus: the two first lines, five of its edges and the last line. msip is written as hart 1, then hart 0.
hart1 id=1: parks in wfi
hart0 id=0: boot hart, runs start-up code
e7 hart=0 op=store addr=80000000 wdata=80000100 result=00000000 resv=00 msip=00
e9 hart=0 op=store addr=02000004 wdata=00000001 result=00000000 resv=00 msip=00
e10 hart=- op=idle resv=00 msip=10
e11 hart=1 op=store addr=02000004 wdata=00000000 result=00000000 resv=00 msip=10
e13 hart=1 op=load addr=80000000 wdata=00000000 result=80000100 resv=00 msip=00
hart1 wakes and jumps to 80000100

Rule 1 at work, in the first two lines. Each hart read its id. Hart 1 parked before the first bus edge.

Rule 5, in rows e7 and e9. The entry address 80000100 goes into the mailbox first. The store of 1 to the wake-up word comes two edges later.

Rules 2 and 3, in row e10. msip reads 10: the bit of hart 1 is set, and hart 1 wakes.

Rule 4, in row e11. The first thing hart 1 does is store 0 to its own word. Then, at e13, its load returns 80000100.

One Wake-Up, Edge by EdgeEdges e7 to e13 of the lab. msip1 is hart 1's software-interrupt bit.
storemsip1accessHart 0ap_clintmsip word per hartSRAMmailbox at 0x80000000Hart 1
store→ SRAMmsip1→ Hart 1access→ SRAMHart 0ap_clintmsip word per hartSRAMmailbox at 0x80000000Hart 1

A lit wire carries a 1. A pill is a transfer in that cycle.

0123456clkhart0hart1opstoreidlestoreidlestoreidleloadaddr80000000-02000004-02000004-80000000wdata80000100-1-0-msip1
Scroll horizontally ↔
  1. Cycle 0

    At e7, hart 0 stores the entry address 80000100 to the mailbox.

  2. Cycle 2

    At e9, hart 0 stores 1 to 0x02000004, hart 1's msip word.

  3. Cycle 3

    msip1 is now 1. Hart 1 wakes.

  4. Cycle 4

    At e11, hart 1 stores 0 to its own msip word, clearing the request.

  5. Cycle 6

    At e13, hart 1 loads the mailbox and gets 80000100.

Recorded rising-edge samples from the Icarus lab. Bus-functional models stand in for both harts.

Now the wrong order of the hand example. With RAISE_FIRST at 1, the wake-up store moves to the front.

The same lab with RAISE_FIRST = 1.
e1 hart=0 op=store addr=02000004 wdata=00000001 result=00000000 resv=00 msip=00
e5 hart=1 op=load addr=80000000 wdata=00000000 result=00000000 resv=00 msip=00
hart1 wakes and jumps to 00000000
e10 hart=0 op=store addr=80000000 wdata=80000100 result=00000000 resv=00 msip=00

Hart 1 loads the mailbox at e5 and gets 00000000. The entry address arrives at e10, five edges too late.

This lab leaves things out. No processor runs here, so no instruction named wfi is executed: a task of the test code waits for the bit. The harts make their stores in program order. A processor that may reorder its stores needs one more instruction between the two.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
A parked hart sleeps until an interruptIt reads the mailbox in a loop until the value changesA sleeping hart uses no bus time and little power. It needs an interrupt wire for each hart.
The wake-up is a level that software clearsA pulse of one clockA level cannot be missed by a hart that was busy. The woken hart must clear it.
The message is in memory, not in the interruptThe interrupt carries the entry addressOne bit serves every kind of message. The order of two stores now matters.

A fourth choice is in the practice. ap_soc can also hold hart 1 in reset until hart 0 writes an entry register and a release bit. You build those two registers in "Wake the Second Hart".

The Trap: One Word Off

A team moved the wake-up code from a board with four harts to one with two. Hart 1 never came up. The stores were in the right order, and every one of them got a good reply from the bus.

The address was the fault. The store went to the base of ap_clint, which is the word of hart 0. Our lab shows it: at e9 the store goes to 02000000, and at e10 msip reads 01. Hart 0 had interrupted itself. Hart 1 slept on, and the lab ends with "hart1 still asleep".

Nothing fails loudly here, because every word of that block is a legal address. So check the wake-up at the far end: which bit rose, and which hart cleared it.

The second trap is the bit left at 1. The hart wakes, does its work and enables interrupts again. The request is still pending, so it takes the same interrupt a second time.

At Scale

This page2 harts
A server chipdozens of cores

This section looks ahead. Two harts become dozens, and they stop being identical.

  1. The part that cannot be shared

    If half of a job can run on one hart only, more harts can never make the job twice as fast.

  2. Different cores on one chip

    Our harts are identical, so any program runs on either. Many chips mix large and small cores, and software must choose.

  3. A wake-up through a large chip

    The mailbox and the interrupt may take different routes. Rule 5 must still hold at the far end of both.

  4. Shared parts need turns

    Two harts that print at once mix their letters. Two harts that count into one word lose counts. The next lesson shows why.

Try It

Run the lab. Find the edge on which msip for hart 1 rises, and the edge on which hart 1 clears it.

Set RAISE_FIRST to 1. Find the load that returns the old content of the mailbox, and the store that came too late.

In the line that sets MSIP1, change the offset from 4 to 0. Which bit of msip rises now, and what does hart 1 print?

Names Printed by the Lab
NameMeaning
e0, e1, ...Rising edges of the clock. The bus serves one access on an edge, or none.
hartThe hart whose access was served on that edge. A dash means none.
opThe kind of access: load, store or idle.
addr, wdataThe address of the access, and the value of a store.
resultThe value that a load returned.
msipThe two wake-up bits, written as hart 1, then hart 0. So 10 means that the bit of hart 1 is set.
resvUsed in the next lesson. It stays 00 here.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: hart1 id=1: parks in wfi hart0 id=0: boot hart, runs start-up code e0 hart=- op=idle resv=00 msip=00 e1 hart=0 op=store addr=80000004 wdata=00000000 result=00000000 resv=00 msip=00 e2 hart=- op=idle resv=00 msip=00 e3 hart=0 op=store addr=80000008 wdata=00000000 result=00000000 resv=00 msip=00 e4 hart=- op=idle resv=00 msip=00 e5 hart=0 op=store addr=8000000c wdata=00000000 result=00000000 resv=00 msip=00 e6 hart=- op=idle resv=00 msip=00 e7 hart=0 op=store addr=80000000 wdata=80000100 result=00000000 resv=00 msip=00 e8 hart=- op=idle resv=00 msip=00 e9 hart=0 op=store addr=02000004 wdata=00000001 result=00000000 resv=00 msip=00 e10 hart=- op=idle resv=00 msip=10 e11 hart=1 op=store addr=02000004 wdata=00000000 result=00000000 resv=00 msip=10 e12 hart=- op=idle resv=00 msip=00 e13 hart=1 op=load addr=80000000 wdata=00000000 result=80000100 resv=00 msip=00 hart1 wakes and jumps to 80000100
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 hart 0 stores the 1 to 0x02000000, the base of ap_clint. What is the last line that the lab prints?
module tb;
  `include "soc-s91-harts.svh"
  localparam logic [31:0] MAILBOX = SRAM, ENTRY = 32'h8000_0100;
  localparam logic [31:0] MSIP1 = CLINT + 32'h0;  // 4 bytes per hart id
  // Exercise: set RAISE_FIRST to 1 to raise msip before the mailbox write.
  localparam bit RAISE_FIRST = 0;

  // Both harts leave reset together. Each reads its own hart id first.
  task automatic hart0();
    $display("hart0 id=0: boot hart, runs start-up code");
    if (RAISE_FIRST) store(0, MSIP1, 1);
    for (int i = 1; i <= 3; i++) store(0, SRAM + 4 * i, 0);  // clear shared data
    store(0, MAILBOX, ENTRY);                                // publish the entry address
    if (!RAISE_FIRST) store(0, MSIP1, 1);                    // then wake hart 1
  endtask

  task automatic hart1();
    bit woke;
    logic [31:0] entry;
    $display("hart1 id=1: parks in wfi");
    wfi(1, woke);
    if (woke) begin
      store(1, MSIP1, 0);          // clear its own request, or it wakes again
      load(1, MAILBOX, entry);
      $display("hart1 wakes and jumps to %08h", entry);
    end else
      $display("hart1 still asleep");
  endtask

  initial begin
    start();
    fork hart0(); hart1(); join
    $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
ConceptTwo harts leave reset at the same address. How does each one know its job?
ConceptWhat does a parked hart wait for?
ConceptWhy does the woken hart clear its wake-up bit?
ConceptWhy must the mailbox be written before the wake-up?

Common Mistakes

Wrong Let every hart run the start-up code.

They set up the same memory twice, one on top of the other.

Fix Read the hart id first, and park every hart but one.

Wrong Raise the wake-up bit before the mailbox is written.

The woken hart can read the old content.

Fix Publish the data, then wake.

Wrong Leave the wake-up bit at 1.

It is a level, so the interrupt is taken again.

Fix The woken hart clears its own bit first.

Remember

  • Every hart reads its hart id: one boots and the others park.
  • A store to the wake-up word of a hart raises its software interrupt, and that hart clears the bit.
  • Publish the data first, then wake.
  • Registers, PC, wake-up bit and stack are one for each hart. Memory and devices are shared.

Practice

Report a problem with this page