The Integration Bug Hunt Across Clock Edges

The address can be right and the transfer can still fail. Find the edge when the chip needed a value.

You Will Be Able To

  • Distinguish an early first fetch from a fetch at the wrong address.
  • Explain how a stopped clock and a missed event leave different evidence.
  • Identify the condition that wrongly blocks a memory copy.
Lesson
S11.5
Time
24 min
Runs on
Your browser
Check
5 questions

Two boards start the same ROM greeting. Both consoles stay dark. A single observation at the first fetch can separate the boards before either prints a character.

Before You Start

Start with The Integration Bug Hunt and the hello, echo and copy programs from S6.

Recall how the chip samples a boot pin and waits for ROM readiness in S5.9.

Five questions this page answers
Question
1When was the ROM ready?
2Which memory did the core try first?
3Why did only the first letter appear?
4Can a receiver miss a clean pulse?
5Which request does a memory copy need?

The Idea

A wire value has a time as well as a name. Readiness observed after a failed fetch tells you little about that fetch.

Ask three questions. What allowed the first operation? What allowed the next one? What kept an event available until someone took it?

New Words

New words on this page
WordMeaning
First-fetch addressThe address of the first instruction read after the processor leaves reset.
Receiver sampling windowThe time when a receiver can capture a value. In the crossing model, it samples once every eight ticks.
Byte grantPermission for the DMA channel to move its next byte.

One Picture: The First Fetch

What Must Be True at Release?Read the saved boot selection, the ROM readiness and the first fetch together.
  • Control / FSM
  • Clock / reset
  • Processor
  • Memory
What Must Be True at Release?Read the saved boot selection, the ROM readiness and the first fetch together. component Boot pin board requests ROMor SRAM component Boot sequencer samples the pin once component Core release waits for fabric andROM component First fetch address chosen fromthe saved bit SampleReleaseFetch
  1. component Boot pinboard requests ROM or SRAM
    • Sample → Boot sequencer
  2. component Boot sequencersamples the pin once
    • Release → Core release
  3. component Core releasewaits for fabric and ROM
    • Fetch → First fetch
  4. component First fetchaddress chosen from the saved bit
  1. Sample

    Capture the strap once after lock. Later pin activity must leave the selection intact.

  2. Release

    Wait until the fabric and ROM are ready before releasing the processor.

  3. Fetch

    Check the address and readiness at this edge. They answer different questions.

Read the diagram as text
  • Boot pin: board requests ROM or SRAM
  • Boot sequencer: samples the pin once
  • Core release: waits for fabric and ROM
  • First fetch: address chosen from the saved bit
  • Boot pin → Boot sequencer: Sample
  • Boot sequencer → Core release: Release
  • Core release → First fetch: Fetch

Read the saved boot selection, the ROM readiness and the first fetch together.

The Smallest Example, Worked by Hand

Consider a receiver that samples at ticks 298 and 306. A source raises a pulse at tick 300 and drops it at 301.

At both sample times the wire is low. The receiver records no event even though the source changed twice.

Repeat with the request held until capture. At tick 306 the receiver sees it and takes the byte.

This hand example uses the phase and spacing of trial 8. The model checks digital sampling only.

The Rules

  1. Rule 1: Capture the first attempt.

    Record the address and the readiness at that edge. Reset recovery can erase both clues.

  2. Rule 2: Find the last completed operation.

    A first character proves the transmit store worked once. The second character also needs room to return.

  3. Rule 3: Follow permission to its source.

    Identify who must grant the next byte and when the receiver samples that grant.

Sources for These Rules

The ap_soc facts, sections 3, 5, 11 and 22, describe the DMA, UART, boot order and firmware kit.

Saving the first failure and changing one sampling phase are common debugging practice. The timing values below belong to the lab.

Now Run It: Five Failures in Time

Trials 6, 7 and 10 run hello. Trial 8 runs echo. Trial 9 runs the six-byte memory copy.

The live lab runs the S6 programs on the firmware model. The probe repeats the clock, crossing and DMA trials on the five-stage core.

Those three peripherals use test models. The clock enable controls transmitter progress. The crossing models a slow receiver with fixed sampling edges.

For the copy, the monitor prints destination words. The copy program itself sends no serial text.

The boot trials use the chip boot sequencer with a first-fetch model. They end at an unavailable image or an early read.

Symptom Board
TrialHealthy runSeeded runHealthy → seeded observation
6. Clock enableconsole="hi"console="h"room=0 clock enable=1 → room=0 clock enable=0
7. Reset orderconsole="hi"console=""first fetch=00000000 ROM ready=1 → first fetch=00000000 ROM ready=0
8. Crossingecho="abc"echo=""source events=3 serviced=3 → source events=3 serviced=0
9. DMA requestcopy=64636261 00006665copy=00000000 00000000bytes left=0 → bytes left=6
10. Strapconsole="hi"console=""first fetch=00000000 ROM ready=1 → first fetch=80000000 ROM ready=1

Each pair starts from reset. Quotes show bytes. Empty quotes mean the board received no characters during the run.

Clock enable. Trial 6 sends the first letter. The UART accepts it, becomes busy and needs clock ticks to make room again.

The healthy run also ends with room low because its last byte just entered the transmitter.

Compare the enable while the program waits for its second store. Keep the transmit clock running while work remains.

Reset order. In trial 7 the fetch names ROM, but the sequencer took its shortened wait path.

Waiting to inspect ROM after startup would hide this failure. Restore the readiness condition and inspect the next first fetch.

Crossing. In trial 8 the board sends all three bytes. The fault turns each held request into a one-tick pulse.

Each pulse falls between receiving edges. The receive queue gets nothing, so changing interrupt priority cannot help.

Hold each request and its data through capture. A physical crossing also needs safe synchronization and a way to prevent overwriting unconsumed data.

DMA request. In trial 9 the channel still has six bytes left. The destination remains at the zeros written by firmware.

The seeded channel waits for a UART receive request before copying between two SRAM addresses. Neither address names the UART.

Use device readiness for a device transfer. For this memory copy, let the active channel move the next byte.

Strap. In trial 10 ROM is ready, but the sampled boot pin selects SRAM. This lab loaded the greeting only in ROM.

Compare the saved bit with the board setting at the sample edge. Restore ROM selection and repeat a fresh boot.

Why It Is Built This Way

Startup has dependencies that finish at different times. A readiness input lets the same sequencer wait for each build.

The DMA also has different partners. Memory can supply bytes in this kit without an incoming character, while a device may need pacing.

The Trap: Measuring After Recovery

A late probe can show a ready ROM on both boards. One board had already tried to read it too soon.

Save readiness with the first address. That pair separates an early release from a wrong boot selection.

At Scale

One boot1 first fetch
Two boot trials2 first fetches

Keep the ten variants as replayable starting cases for system verification.

  1. At each boundary

    Save the healthy image, one seeded change, the input schedule and the first differing observation.

  2. Across clocks

    Vary the phase and spacing after the repair. A pulse can survive one phase and disappear at another.

Run the healthy smoke program first. Keep the bring-up images and ten seeded variants alongside it for replay.

Try It

Run trial 7 with the shortened wait. Read both observations at the first fetch.

Switch to trial 10. Predict which observation changes while the console stays silent.

In trial 8, remove the seeded fault. Compare source events with serviced bytes.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: console="" | first fetch=00000000 ROM ready=0
Read included file: ap_plic.sv
// One machine context, synchronous level sources. Register-side interface:
// commit pulses once at a successful word transfer's data edge.
module ap_plic #(parameter integer SOURCES = 16) (
  input logic clk, reset_n, commit, write_en,
  input logic [21:0] offset,
  input logic [31:0] wdata,
  input logic [SOURCES:1] level_irq,
  output logic [31:0] rdata,
  output logic notify_irq
);
  localparam ENABLE = 'h2000, THRESHOLD = 'h200000, CLAIM = 'h200004;
  logic [2:0] weight [1:SOURCES];
  logic [2:0] threshold, best;
  logic [SOURCES:1] pending, busy, enabled;
  integer winner;

  always_comb begin
    best = 0;
    winner = 0;
    for (int id = 1; id <= SOURCES; id++) begin
      if (pending[id] && enabled[id] && weight[id] > best) begin
        best = weight[id];
        winner = id;
      end
    end
    notify_irq = best > threshold;
    rdata = 0;
    for (int id = 1; id <= SOURCES; id++) begin
      if (offset == 4*id) rdata = weight[id];
      if (offset == 'h1000 + 4*(id/32)) rdata[id%32] = pending[id];
      if (offset == ENABLE + 4*(id/32)) rdata[id%32] = enabled[id];
    end
    case (offset)
      THRESHOLD: rdata = threshold;
      CLAIM: rdata = winner;
    endcase
  end

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      pending <= '0;
      busy <= '0;
      enabled <= '0;
      threshold <= 0;
      for (int id = 1; id <= SOURCES; id++) weight[id] <= 0;
    end else begin
      for (int id = 1; id <= SOURCES; id++) begin
        if (level_irq[id] && !busy[id]) begin
          pending[id] <= 1;
          busy[id] <= 1;
        end
        if (commit && write_en && offset == 4*id) weight[id] <= wdata[2:0];
        if (commit && write_en && offset == ENABLE + 4*(id/32))
          enabled[id] <= wdata[id%32];
        if (commit && offset == CLAIM) begin
          if (!write_en && winner == id) pending[id] <= 0;
          if (write_en && enabled[id] && wdata == id && busy[id] && !pending[id]) busy[id] <= 0;
        end
      end
      if (commit && write_en && offset == THRESHOLD) threshold <= wdata[2:0];
    end
  end
endmodule
Read included file: ap_clint_timer.sv
// Timer slice of ap_soc's local interrupt block. One hart, one timebase tick
// per clk and a registered interrupt output. Word strobes arrive at commitment.
module ap_clint_timer #(parameter logic [63:0] RESET_COMPARE = '1) (
  input logic clk, reset_n, write_cmp_low, write_cmp_high,
  input logic [31:0] wdata,
  output logic [63:0] mtime, mtimecmp,
  output logic mtip
);
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      mtime <= 0;
      mtimecmp <= RESET_COMPARE;
      mtip <= 0;
    end else begin
      mtime <= mtime + 1'b1;
      if (write_cmp_low) mtimecmp[31:0] <= wdata;
      if (write_cmp_high) mtimecmp[63:32] <= wdata;
      mtip <= mtime >= mtimecmp;
    end
  end
endmodule
Read included file: ap_crg_boot.sv
// Startup slice of ap_crg. Each ready input is already qualified in the
// always-on domain. Board supervision handles rail or lock loss after boot.
module ap_crg_boot(
  input logic aon_clk, supply_good, osc_ready, pll_locked, boot_pin,
  input logic fabric_ready, rom_ready, shorten_wait,
  output logic osc_start, pll_start, straps_valid, boot_sel,
  output logic fabric_reset_n, core_reset_n
);
  always_ff @(posedge aon_clk or negedge supply_good) begin
    if (!supply_good) begin
      {osc_start, pll_start, straps_valid, boot_sel} <= 0;
      {fabric_reset_n, core_reset_n} <= 0;
    end else begin
      osc_start <= 1;
      if (osc_start && osc_ready) pll_start <= 1;
      if (pll_start && pll_locked && !straps_valid) begin
        boot_sel <= boot_pin;
        straps_valid <= 1;
      end
      if (straps_valid) fabric_reset_n <= 1;
      if (fabric_reset_n && fabric_ready && (rom_ready || shorten_wait))
        core_reset_n <= 1;
    end
  end
endmodule
Read included file: fixture.svh
  localparam int LUI = 0, ADDI = 1, ANDI = 2, ORI = 3, SLLI = 4, SRLI = 5, ADD = 6, SUB = 7, AND = 8, OR = 9, LW = 10, SW = 11,
                 BEQ = 12, BNE = 13, BLT = 14, BGE = 15, JAL = 16, JALR = 17, CSRR = 18, CSRW = 19, CSRS = 20, CSRC = 21, MRET = 22, WORD = 23;
  localparam int MSTATUS = 'h300, MIE = 'h304, MTVEC = 'h305, MSCRATCH = 'h340, MEPC = 'h341, MCAUSE = 'h342, MIP = 'h344;
  int kind [0:1023], fa [0:1023], fb [0:1023];   // the Boot ROM: one row for each word
  logic [31:0] fc [0:1023];
  int here = 0;                                   // the address of the next row
  task automatic at(input int address);           // the rows that follow start at this address
    here = address;
  endtask
  task automatic i(input int k, input int a, input int b, input logic [31:0] c);   // add one row
    if (here < 4096) begin kind[here >> 2] = k; fa[here >> 2] = a; fb[here >> 2] = b; fc[here >> 2] = c; end
    here += 4;
  endtask
  task automatic load_hello();
    i(LUI,   2,  0,  'h80010);   // 000: lui x2, 0x80010      the stack pointer
    i(LUI,   8,  0,  'h10000);   // 004: lui x8, 0x10000      x8: UART0
    i(ADDI,  10, 0,  104);       // 008: addi x10, x0, 104      the letter h
    i(JAL,   1,  0,  'h1c);      // 00c: jal x1, 0x1c
    i(ADDI,  10, 0,  105);       // 010: addi x10, x0, 105      the letter i
    i(JAL,   1,  0,  'h1c);      // 014: jal x1, 0x1c
    i(JAL,   0,  0,  'h18);      // 018: jal x0, 0x18
    // putc: wait for room, then write the byte in x10
    i(LW,    5,  8,  4);         // 01c: lw x5, 4(x8)      STATUS
    i(ANDI,  5,  5,  1);         // 020: andi x5, x5, 1      bit 0: ROOM
    i(BEQ,   5,  0,  'h1c);      // 024: beq x5, x0, 0x1c
    i(SW,    10, 8,  0);         // 028: sw x10, 0(x8)      TXDATA
    i(JALR,  0,  1,  0);         // 02c: jalr x0, 0(x1)      return
  endtask
  task automatic load_echo();
    i(LUI,   2,  0,  'h80010);   // 000: lui x2, 0x80010      the stack pointer
    i(ADDI,  5,  0,  96);        // 004: addi x5, x0, 96
    i(CSRW,  5,  0,  MTVEC);     // 008: csrw mtvec, x5      mtvec: the handler
    i(LUI,   8,  0,  'h80000);   // 00c: lui x8, 0x80000      x8: SRAM, where the byte count is
    i(SW,    0,  8,  0);         // 010: sw x0, 0(x8)      count = 0
    i(LUI,   9,  0,  'hc000);    // 014: lui x9, 0xc000      x9: ap_plic
    i(ADDI,  5,  0,  1);         // 018: addi x5, x0, 1
    i(SW,    5,  9,  4);         // 01c: sw x5, 4(x9)      priority of source 1 (UART0) = 1
    i(LUI,   18, 0,  'hc002);    // 020: lui x18, 0xc002
    i(ADDI,  5,  0,  2);         // 024: addi x5, x0, 2
    i(SW,    5,  18, 0);         // 028: sw x5, 0(x18)      enable bit 1
    i(LUI,   19, 0,  'hc200);    // 02c: lui x19, 0xc200      x19: threshold, and claim at offset 4
    i(LUI,   20, 0,  'h10000);   // 030: lui x20, 0x10000      x20: UART0
    i(LUI,   5,  0,  'h1);       // 034: lui x5, 0x1
    i(ADDI,  5,  5,  -2048);     // 038: addi x5, x5, -2048      x5 = 0x800
    i(CSRS,  5,  0,  MIE);       // 03c: csrs mie, x5      mie: the external enable, bit 11
    i(ADDI,  5,  0,  8);         // 040: addi x5, x0, 8
    i(CSRS,  5,  0,  MSTATUS);   // 044: csrs mstatus, x5      mstatus: MIE
    i(LW,    6,  8,  0);         // 048: lw x6, 0(x8)
    i(ADDI,  7,  0,  3);         // 04c: addi x7, x0, 3
    i(BLT,   6,  7,  'h48);      // 050: blt x6, x7, 0x48      wait for 3 bytes
    i(ADDI,  5,  0,  8);         // 054: addi x5, x0, 8
    i(CSRC,  5,  0,  MSTATUS);   // 058: csrc mstatus, x5      interrupts off
    i(JAL,   0,  0,  'h5c);      // 05c: jal x0, 0x5c
    // the handler: claim, read the byte, send it back, count it, complete. It uses x28 to x30 only.
    i(LW,    28, 19, 4);         // 060: lw x28, 4(x19)      claim: which source?
    i(LW,    29, 20, 12);        // 064: lw x29, 12(x20)      RXDATA: the read removes the byte
    i(SW,    29, 20, 0);         // 068: sw x29, 0(x20)      TXDATA
    i(LW,    30, 8,  0);         // 06c: lw x30, 0(x8)
    i(ADDI,  30, 30, 1);         // 070: addi x30, x30, 1
    i(SW,    30, 8,  0);         // 074: sw x30, 0(x8)      count = count + 1
    i(SW,    28, 19, 4);         // 078: sw x28, 4(x19)      complete: the same number goes back
    i(MRET,  0,  0,  0);         // 07c: mret
  endtask
  task automatic load_dma();
    i(LUI,   2,  0,  'h80010);   // 000: lui x2, 0x80010      the stack pointer
    i(LUI,   8,  0,  'h80000);   // 004: lui x8, 0x80000      x8: SRAM
    i(LUI,   5,  0,  'h64636);   // 008: lui x5, 0x64636
    i(ADDI,  5,  5,  609);       // 00c: addi x5, x5, 609
    i(SW,    5,  8,  256);       // 010: sw x5, 256(x8)      source bytes 61 62 63 64
    i(LUI,   5,  0,  'h68676);   // 014: lui x5, 0x68676
    i(ADDI,  5,  5,  1637);      // 018: addi x5, x5, 1637
    i(SW,    5,  8,  260);       // 01c: sw x5, 260(x8)      source bytes 65 66 67 68
    i(SW,    0,  8,  512);       // 020: sw x0, 512(x8)      clear the destination
    i(SW,    0,  8,  516);       // 024: sw x0, 516(x8)
    i(LUI,   9,  0,  'h10006);   // 028: lui x9, 0x10006      x9: DMA
    i(ADDI,  5,  8,  256);       // 02c: addi x5, x8, 256
    i(SW,    5,  9,  0);         // 030: sw x5, 0(x9)      SRC
    i(ADDI,  5,  8,  512);       // 034: addi x5, x8, 512
    i(SW,    5,  9,  4);         // 038: sw x5, 4(x9)      DST
    i(ADDI,  5,  0,  6);         // 03c: addi x5, x0, 6
    i(SW,    5,  9,  8);         // 040: sw x5, 8(x9)      LEN: 6 bytes
    i(ADDI,  5,  0,  1);         // 044: addi x5, x0, 1
    i(SW,    5,  9,  12);        // 048: sw x5, 12(x9)      START, written last
    i(LUI,   18, 0,  'hc001);    // 04c: lui x18, 0xc001      x18: the pending bits of ap_plic
    i(LW,    6,  18, 0);         // 050: lw x6, 0(x18)
    i(ANDI,  6,  6,  32);        // 054: andi x6, x6, 32      bit 5: DMA
    i(BEQ,   6,  0,  'h50);      // 058: beq x6, x0, 0x50      wait until the DMA is done
    i(LW,    10, 8,  512);       // 05c: lw x10, 512(x8)      read the copy back
    i(LW,    11, 8,  516);       // 060: lw x11, 516(x8)
    i(JAL,   0,  0,  'h64);      // 064: jal x0, 0x64
  endtask
  string pad_text = "";
  bit byte_pending;
  logic [7:0] crossing_byte;
  int arrivals;
  wire tx_clock_en = fault != 6;
  wire tx_to_pad = fault != 4;
  wire memory_grant = fault != 9 || rx_ready;
  logic        clk = 0;
  logic [31:0] x [0:31];             // the 32 registers
  logic [31:0] pc;                   // the address of the next instruction
  logic [31:0] ram [0:16383];        // SRAM: 64 KiB from 8000_0000. Nothing is in it at power-on
  logic [31:0] mstatus, mie, mtvec, mscratch, mepc, mcause;   // the machine CSRs of this model
  int          steps, traps, taken;  // instructions, exceptions, interrupts
  bit          stopped;
  localparam int SHOW = 0;            // 2: print every instruction. 1: print events only. 0: print nothing
  task automatic say(input string text);
    if (SHOW != 0) $display("t=%0d | %s", ticks, text);
  endtask
  // ---- UART0 (test code). TXDATA 00, STATUS 04 (bit 0 ROOM, bit 1 RX_READY), RXDATA 0c ----
  string       uart_text = "";                 // every byte that was sent, as text
  int          uart_wait = 0;                  // after a byte: 12 ticks with no room (a lab number)
  logic [7:0]  rx_queue [0:3];                 // received bytes that software has not read yet
  int          rx_count = 0;
  logic [7:0]  rx_plan [0:7];                  // the bytes the board will send, and at which tick
  int          rx_tick [0:7], rx_planned = 0;
  wire         rx_ready = (rx_count != 0);     // UART0 asks for an interrupt while a received byte waits
  // ---- GPIO (test code). OUT 08, TGL 14 ----
  logic [15:0] gpio_out = 0;
  int          gpio_changes = 0;
  // ---- DMA (test code). SRC 00, DST 04, LEN 08, START 0c. It moves one byte of SRAM in each tick. ----
  logic [31:0] dma_src = 0, dma_dst = 0, dma_len = 0;
  int          dma_left = 0;
  bit          dma_done = 0;                   // its interrupt request: 1 from the last byte until the next start
  int          ticks = 0;

  function automatic logic [31:0] tc_peek(input logic [31:0] ad);
    case (ad)
      32'h1000_0004: return {30'b0, rx_ready, (uart_wait == 0)};
      32'h1000_000c: return {24'b0, rx_queue[0]};
      32'h1000_1008: return {16'b0, gpio_out};
      default:       return 32'h0;
    endcase
  endfunction
  function automatic bit tc_exists(input bit wr, input logic [31:0] ad);   // 1: a register is at this address
    case (ad)
      32'h1000_0000, 32'h1000_1014, 32'h1000_6000, 32'h1000_6004, 32'h1000_6008, 32'h1000_600c: return wr;
      32'h1000_0004, 32'h1000_000c: return !wr;
      32'h1000_1008: return 1;
      default: return 0;
    endcase
  endfunction
  task automatic tc_read(input logic [31:0] ad);
    if (ad == 32'h1000_000c && rx_count != 0 && fault != 5) begin        // reading RXDATA removes the oldest byte
      for (int n = 0; n < 3; n++) rx_queue[n] = rx_queue[n + 1];
      rx_count--;
    end
  endtask
  task automatic tc_write(input logic [31:0] ad, input logic [31:0] wd);
    case (fault == 2 && ad == 32'h1000_0000 ? 32'h1000_1008 : ad)
      32'h1000_0000: if (uart_wait == 0) begin             // a byte written with no room is lost
        uart_text = {uart_text, $sformatf("%c", wd[7:0])};  uart_wait = 12; if (tx_to_pad) pad_text = {pad_text, $sformatf("%c", wd[7:0])};
        say($sformatf("UART0 sends %02h \"%c\"", wd[7:0], wd[7:0]));
      end else say($sformatf("UART0 has no room: %02h is lost", wd[7:0]));
      32'h1000_1008: begin gpio_out = wd[15:0];  gpio_changes++;  say($sformatf("GPIO OUT = %04h", gpio_out)); end
      32'h1000_1014: begin gpio_out = gpio_out ^ wd[15:0];  gpio_changes++;  say($sformatf("GPIO OUT = %04h", gpio_out)); end
      32'h1000_6000: dma_src = wd;
      32'h1000_6004: dma_dst = wd;
      32'h1000_6008: dma_len = wd;
      32'h1000_600c: if (wd[0]) begin
        dma_left = dma_len;  dma_done = 0;
        say($sformatf("DMA starts: %0d bytes from %08h to %08h", dma_len, dma_src, dma_dst));
      end
      default: ;
    endcase
  endtask
  task automatic tc_tick();
    ticks++;
    if (uart_wait != 0 && tx_clock_en) uart_wait--;
    for (int n = 0; n < rx_planned; n++) if (rx_tick[n] == ticks) begin
      arrivals++;
      crossing_byte = rx_plan[n];
      byte_pending = 1;
    end
    if (byte_pending && (trial != 8 || ticks % 8 == 2) && rx_count < 4) begin
      rx_queue[rx_count] = crossing_byte;
      rx_count++;
      byte_pending = 0;
    end
    if (fault == 8) byte_pending = 0; // source drops the pulse after one tick
    if (dma_left != 0 && memory_grant) begin                               // one byte: read it from SRAM, write it to SRAM
      ram[dma_dst[15:2]][8 * dma_dst[1:0] +: 8] = ram[dma_src[15:2]][8 * dma_src[1:0] +: 8];
      dma_src++;  dma_dst++;  dma_left--;
      if (dma_left == 0) begin dma_done = 1;  say("DMA done"); end
    end
  endtask
  task automatic board_sends(input int tick, input logic [7:0] value);   // plan one received byte
    rx_plan[rx_planned] = value;  rx_tick[rx_planned] = tick;  rx_planned++;
  endtask
  // Interrupt sources of ap_soc: 1 UART0, 2 GPIO, 3 timer and PWM, 4 SPI, 5 DMA, 6 watchdog, 7 to 16 spare.
  wire         wdg_warn;                       // the early warning of the watchdog; tied to 0 where a lab has none
  wire [16:1] sources = {10'b0, wdg_warn, dma_done, 2'b0, (fault == 3 && rx_ready), (fault != 3 && rx_ready)};
  // ---- The two chip blocks of ap_soc, unchanged: the interrupt controller and the machine timer ----
  logic        reset_n = 0, plic_commit = 0, plic_write = 0, cmp_low = 0, cmp_high = 0;
  logic [21:0] plic_offset = 0;
  logic [31:0] dev_wdata = 0;
  wire  [31:0] plic_rdata;
  wire  [63:0] mtime, mtimecmp;
  wire         irq_external, irq_timer;
  ap_plic plic (.clk, .reset_n, .commit(plic_commit), .write_en(plic_write), .offset(plic_offset), .wdata(dev_wdata),
                .level_irq(sources), .rdata(plic_rdata), .notify_irq(irq_external));
  ap_clint_timer clint (.clk, .reset_n, .write_cmp_low(cmp_low), .write_cmp_high(cmp_high), .wdata(dev_wdata),
                        .mtime, .mtimecmp, .mtip(irq_timer));
  assign wdg_warn = 1'b0;                      // no watchdog in this lab
  wire [31:0] mip = {20'b0, irq_external, 3'b0, irq_timer, 7'b0};   // bit 11: external. bit 7: machine timer

  function automatic string cn(input logic [11:0] a);   // the name of a CSR
    case (a)
      MSTATUS: return "mstatus";  MIE: return "mie";  MTVEC: return "mtvec";  MSCRATCH: return "mscratch";
      MEPC: return "mepc";  MCAUSE: return "mcause";  MIP: return "mip";
      default: return "?";
    endcase
  endfunction
  function automatic logic [31:0] csr_value(input logic [11:0] a);
    case (a)
      MSTATUS: return mstatus;  MIE: return mie;  MTVEC: return mtvec;  MSCRATCH: return mscratch;
      MEPC: return mepc;  MCAUSE: return mcause;
      default: return mip;
    endcase
  endfunction
  task automatic csr_store(input logic [11:0] a, input logic [31:0] v);   // each CSR keeps only its writable bits
    case (a)
      MSTATUS:  begin mstatus[3] = v[3];  mstatus[7] = v[7]; end           // MIE and MPIE
      MIE:      mie = v & 32'h0000_0888;                                   // external, timer and software enables
      MTVEC:    mtvec = v & 32'hffff_fffd;
      MSCRATCH: mscratch = v;
      MEPC:     mepc = v & 32'hffff_fffc;
      MCAUSE:   mcause = v;
      default: ;                                                           // mip is read-only
    endcase
  endtask
  // The entry of a trap, for an exception or an interrupt: what the processor does by itself.
  task automatic enter(input logic [31:0] cause, input string text);
    mepc = pc & 32'hffff_fffc;  mcause = cause;
    mstatus[7] = mstatus[3];  mstatus[3] = 1'b0;                           // MPIE takes MIE, MIE closes
    say($sformatf("%s: mcause=%08h mepc=%08h, next is %08h", text, cause, mepc, mtvec & 32'hffff_fffc));
    pc = mtvec & 32'hffff_fffc;
  endtask
  // Start one read or write of a word. The value of a read is in bus_rdata after half a tick.
  logic [31:0] bus_rdata;
  bit          bus_fault;
  task automatic bus(input bit wr, input logic [31:0] ad, input logic [31:0] wd);
    bus_fault = 0;  bus_rdata = 0;
    if (ad[31:12] == 20'h0) begin                                          // Boot ROM: data words can be read
      if (wr) bus_fault = 1;
      else bus_rdata = (kind[ad[11:2]] == WORD) ? fc[ad[11:2]] : 32'h0;
    end
    else if (ad[31:16] == 16'h8000) begin                                  // SRAM
      if (wr) ram[ad[15:2]] = wd;
      else bus_rdata = ram[ad[15:2]];
    end
    else if (ad[31:22] == 10'h030) begin                                   // ap_plic, from 0c00_0000
      plic_offset = ad[21:0];  plic_write = wr;  dev_wdata = wd;  plic_commit = 1;
    end
    else if (ad == 32'h0200_4000 || ad == 32'h0200_4004) begin              // ap_clint: mtimecmp
      if (wr) begin dev_wdata = wd;  cmp_low = !ad[2];  cmp_high = ad[2]; end
      else bus_rdata = ad[2] ? mtimecmp[63:32] : mtimecmp[31:0];
    end
    else if (ad == 32'h0200_bff8 || ad == 32'h0200_bffc) begin              // ap_clint: mtime, read only here
      if (wr) bus_fault = 1;
      else bus_rdata = ad[2] ? mtime[63:32] : mtime[31:0];
    end
    else if (tc_exists(wr, ad)) begin                                      // UART0, GPIO, DMA
      if (wr) tc_write(ad, wd);
      else begin bus_rdata = tc_peek(ad);  tc_read(ad); end
    end
    else bus_fault = 1;                                                    // nothing answers at this address
  endtask
  // One tick: one instruction, then one rising clock edge.
  task automatic step();
    int k, a, b;
    logic [31:0] c, r1, r2, res, next, ad;
    string text, effect;
    bit writes, take, done, access;
    // An interrupt is taken between two instructions: MIE at 1, and a request that is pending and enabled.
    if (mstatus[3] && (mie & mip) != 0) begin
      if (mie[11] && mip[11]) enter(32'h8000_000b, "interrupt, external");
      else                    enter(32'h8000_0007, "interrupt, machine timer");
      taken++;
    end
    done = 0;  writes = 1;  access = 0;  res = 0;  effect = "";  next = pc + 4;  text = "";
    if (pc >= 32'h1000) begin enter(1, "exception, no instruction at this address");  traps++;  done = 1;  k = WORD;  a = 0;  b = 0;  c = 0; end
    else begin k = kind[pc >> 2];  a = fa[pc >> 2];  b = fb[pc >> 2];  c = fc[pc >> 2]; end
    r1 = x[b[4:0]];  r2 = x[c[4:0]];
    // An immediate has 12 bits with a sign (20 bits in lui). A row outside that range is no instruction.
    if (!done && ((k == LUI && c[31:20] != 0) || ((k == ADDI || k == ANDI || k == ORI || k == LW || k == SW || k == JALR) && !($signed(c) >= -2048 && $signed(c) <= 2047)))) begin
      enter(2, $sformatf("exception, immediate out of range at %08h", pc));  traps++;  done = 1;
    end
    if (!done) case (k)
      LUI:  begin res = c << 12;  text = $sformatf("lui x%0d, 0x%0h", a, c); end
      ADDI: begin res = r1 + c;          text = $sformatf("addi x%0d, x%0d, %0d", a, b, $signed(c)); end
      ANDI: begin res = r1 & c;          text = $sformatf("andi x%0d, x%0d, %0d", a, b, $signed(c)); end
      ORI:  begin res = r1 | c;          text = $sformatf("ori x%0d, x%0d, %0d", a, b, $signed(c)); end
      SLLI: begin res = r1 << c[4:0];    text = $sformatf("slli x%0d, x%0d, %0d", a, b, c); end
      SRLI: begin res = r1 >> c[4:0];    text = $sformatf("srli x%0d, x%0d, %0d", a, b, c); end
      ADD:  begin res = r1 + r2;         text = $sformatf("add x%0d, x%0d, x%0d", a, b, c[4:0]); end
      SUB:  begin res = r1 - r2;         text = $sformatf("sub x%0d, x%0d, x%0d", a, b, c[4:0]); end
      AND:  begin res = r1 & r2;         text = $sformatf("and x%0d, x%0d, x%0d", a, b, c[4:0]); end
      OR:   begin res = r1 | r2;         text = $sformatf("or x%0d, x%0d, x%0d", a, b, c[4:0]); end
      LW, SW: begin
        ad = r1 + c;  access = 1;
        text = $sformatf("%s x%0d, %0d(x%0d)", (k == LW) ? "lw" : "sw", a, $signed(c), b);
        bus(k == SW, ad, x[a[4:0]]);
        if (k == SW) begin writes = 0;  effect = $sformatf("mem[%08h] = %08h", ad, x[a[4:0]]); end
      end
      BEQ, BNE, BLT, BGE: begin
        r1 = x[a[4:0]];  r2 = x[b[4:0]];  writes = 0;
        case (k)
          BEQ: take = (r1 == r2);
          BNE: take = (r1 != r2);
          BLT: take = ($signed(r1) < $signed(r2));
          default: take = ($signed(r1) >= $signed(r2));
        endcase
        text = $sformatf("%s x%0d, x%0d, 0x%0h", (k == BEQ) ? "beq" : (k == BNE) ? "bne" : (k == BLT) ? "blt" : "bge", a, b, c);
        if (take) begin next = c;  effect = $sformatf("taken: next is %08h", next); end
        else effect = "not taken";
      end
      JAL, JALR: begin
        res = pc + 4;
        if (k == JAL) begin next = c;  text = $sformatf("jal x%0d, 0x%0h", a, c); end
        else begin next = (r1 + c) & ~32'd1;  text = $sformatf("jalr x%0d, %0d(x%0d)", a, $signed(c), b); end
        if (k == JAL && next == pc) begin
          if (SHOW == 2) $display("%08h | %s | the program stops here", pc, text);
          else say($sformatf("the program stops at %08h", pc));
          stopped = 1;  done = 1;
        end
      end
      CSRR: begin res = csr_value(c[11:0]);  text = $sformatf("csrr x%0d, %s", a, cn(c[11:0])); end
      CSRW, CSRS, CSRC: begin
        writes = 0;
        case (k)
          CSRW:    csr_store(c[11:0], x[a[4:0]]);
          CSRS:    csr_store(c[11:0], csr_value(c[11:0]) | x[a[4:0]]);
          default: csr_store(c[11:0], csr_value(c[11:0]) & ~x[a[4:0]]);
        endcase
        text = $sformatf("%s %s, x%0d", (k == CSRW) ? "csrw" : (k == CSRS) ? "csrs" : "csrc", cn(c[11:0]), a);
        effect = $sformatf("%s = %08h", cn(c[11:0]), csr_value(c[11:0]));
      end
      MRET: begin
        writes = 0;  next = mepc;  text = "mret";
        mstatus[3] = mstatus[7];  mstatus[7] = 1'b1;                       // MIE takes MPIE back
        effect = $sformatf("next is %08h, MIE=%0d", next, mstatus[3]);
        if (SHOW == 1) say($sformatf("mret: back to %08h", next));
      end
      default: begin enter(2, $sformatf("exception, illegal instruction %08h at %08h", c, pc));  traps++;  done = 1; end
    endcase
    #1;                                                                    // half a tick: the devices answer
    if (access && !done) begin
      if (plic_commit && !plic_write) begin
        bus_rdata = plic_rdata;
        if (plic_offset == 22'h20_0004) say($sformatf("PLIC claim returns %0d", plic_rdata));
      end
      if (plic_commit && plic_write && plic_offset == 22'h20_0004) say($sformatf("PLIC complete %0d", dev_wdata));
      if (bus_fault) begin
        enter((k == LW) ? 5 : 7, $sformatf("exception, no memory at %08h for %s at %08h", ad, (k == LW) ? "a load" : "a store", pc));
        traps++;  done = 1;
      end
      else if (k == LW) begin res = bus_rdata;  effect = $sformatf(" from mem[%08h]", ad); end
    end
    if (!done) begin
      if (writes) begin
        if (a[4:0] != 0) x[a[4:0]] = res;                                  // register 0 is never written
        effect = {$sformatf("x%0d = %08h", a, x[a[4:0]]), effect};
        if (k == JAL || k == JALR) effect = {effect, $sformatf(", next is %08h", next)};
      end
      if (SHOW == 2) $display("%08h | %s | %s", pc, text, effect);
      pc = next;  steps++;
    end
    tc_tick();
    clk = 1;  #1;  clk = 0;                                                // the rising edge: registers of the chip blocks load
    plic_commit = 0;  plic_write = 0;  cmp_low = 0;  cmp_high = 0;
  endtask
  task automatic power_on();
    for (int n = 0; n < 32; n++) x[n] = 0;
    for (int n = 0; n < 16384; n++) ram[n] = 'x;                           // SRAM holds nothing known
    mstatus = 32'h0000_1800;  mie = 0;  mtvec = 0;  mscratch = 0;  mepc = 0;  mcause = 0;   // the values after reset
    pc = 0;  steps = 0;  traps = 0;  taken = 0;  stopped = 0;
    uart_text = "";  uart_wait = 0;  rx_count = 0;  rx_planned = 0;  gpio_out = 0;  gpio_changes = 0;
    dma_left = 0;  dma_done = 0;  ticks = 0;
    reset_n = 0;  #1 clk = 1;  #1 clk = 0;  reset_n = 1;                   // one clock edge in reset for the chip blocks
  endtask
  task automatic run();
    while (!stopped && steps + traps + taken < 400) step();
  endtask
  bit aon, supply_good;
  wire fabric_up, core_up, boot_sel;
  int rom_edges;
  wire rom_ready = rom_edges >= 4;
  always @(posedge aon) if (fabric_up) rom_edges <= rom_edges + 1;
  ap_crg_boot boot(.aon_clk(aon), .supply_good, .osc_ready(1'b1), .pll_locked(1'b1),
    .boot_pin(fault == 10), .fabric_ready(1'b1), .rom_ready, .shorten_wait(fault == 7),
    .fabric_reset_n(fabric_up), .core_reset_n(core_up), .boot_sel);
  task automatic release_core();
    #1 aon = 1; #1 aon = 0; supply_good = 1;
    while (!core_up) begin #1 aon = 1; #1 aon = 0; end
    first_address = boot_sel ? 32'h8000_0000 : 0;
    first_ready = rom_ready;
  endtask

Check Yourself

Predict the outputWith the DMA request fault removed, which full line does the copy monitor print?
// Choose a trial from 1 to 10. Set SEEDED to 0 for the healthy board.
module tb;
  localparam int trial = 9;
  localparam bit SEEDED = 0;
  localparam int fault = SEEDED ? trial : 0;
  logic [31:0] first_address, status_address;
  bit first_ready;
  `include "fixture.svh"

  initial begin
    case (trial)
      3,5,8: load_echo();
      9: load_dma();
      default: load_hello();
    endcase
    if (fault == 1) fc[1] = 'h10001; // hello's UART base in the software map
    power_on();
    release_core();
    pc = first_address;
    if (trial == 3 || trial == 5 || trial == 8) board_sends(300, "a");
    if (trial == 3 || trial == 5 || trial == 8) board_sends(600, "b");
    if (trial == 3 || trial == 5 || trial == 8) board_sends(900, "c");
    // Stop at the first failed fetch or data access. Bound every polling loop.
    if (first_ready && pc == 0) begin
      while (!stopped && !traps && ticks < 1500) begin
        if (kind[pc >> 2] == LW && fb[pc >> 2] == 8 && fc[pc >> 2] == 4)
          status_address = x[8] + 4;
        step();
      end
    end
    case (trial)
    1: $display("console=\"%s\" | status address=%08h", pad_text, status_address);
    2: $display("console=\"%s\" | GPIO writes=%0d", pad_text, gpio_changes);
    3: $display("echo=\"%s\" | queued=%0d pending[2:1]=%02b", pad_text, rx_count, plic.pending[2:1]);
    4: $display("console=\"%s\" | UART accepted=\"%s\"", pad_text, uart_text);
    5: $display("first three=\"%s\" | queued=%0d", pad_text.substr(0,2), rx_count);
    6: $display("console=\"%s\" | room=%0d clock enable=%0d", pad_text, uart_wait == 0, tx_clock_en);
    7,10: $display("console=\"%s\" | first fetch=%08h ROM ready=%0d", pad_text, first_address, first_ready);
    8: $display("echo=\"%s\" | source events=%0d serviced=%0d", pad_text, arrivals, ram[0]);
    9: $display("copy=%08h %08h | bytes left=%0d", ram[128], ram[129], dma_left);
  endcase
    $finish;
  end
endmodule
Read included file: ap_plic.sv
// One machine context, synchronous level sources. Register-side interface:
// commit pulses once at a successful word transfer's data edge.
module ap_plic #(parameter integer SOURCES = 16) (
  input logic clk, reset_n, commit, write_en,
  input logic [21:0] offset,
  input logic [31:0] wdata,
  input logic [SOURCES:1] level_irq,
  output logic [31:0] rdata,
  output logic notify_irq
);
  localparam ENABLE = 'h2000, THRESHOLD = 'h200000, CLAIM = 'h200004;
  logic [2:0] weight [1:SOURCES];
  logic [2:0] threshold, best;
  logic [SOURCES:1] pending, busy, enabled;
  integer winner;

  always_comb begin
    best = 0;
    winner = 0;
    for (int id = 1; id <= SOURCES; id++) begin
      if (pending[id] && enabled[id] && weight[id] > best) begin
        best = weight[id];
        winner = id;
      end
    end
    notify_irq = best > threshold;
    rdata = 0;
    for (int id = 1; id <= SOURCES; id++) begin
      if (offset == 4*id) rdata = weight[id];
      if (offset == 'h1000 + 4*(id/32)) rdata[id%32] = pending[id];
      if (offset == ENABLE + 4*(id/32)) rdata[id%32] = enabled[id];
    end
    case (offset)
      THRESHOLD: rdata = threshold;
      CLAIM: rdata = winner;
    endcase
  end

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      pending <= '0;
      busy <= '0;
      enabled <= '0;
      threshold <= 0;
      for (int id = 1; id <= SOURCES; id++) weight[id] <= 0;
    end else begin
      for (int id = 1; id <= SOURCES; id++) begin
        if (level_irq[id] && !busy[id]) begin
          pending[id] <= 1;
          busy[id] <= 1;
        end
        if (commit && write_en && offset == 4*id) weight[id] <= wdata[2:0];
        if (commit && write_en && offset == ENABLE + 4*(id/32))
          enabled[id] <= wdata[id%32];
        if (commit && offset == CLAIM) begin
          if (!write_en && winner == id) pending[id] <= 0;
          if (write_en && enabled[id] && wdata == id && busy[id] && !pending[id]) busy[id] <= 0;
        end
      end
      if (commit && write_en && offset == THRESHOLD) threshold <= wdata[2:0];
    end
  end
endmodule
Read included file: ap_clint_timer.sv
// Timer slice of ap_soc's local interrupt block. One hart, one timebase tick
// per clk and a registered interrupt output. Word strobes arrive at commitment.
module ap_clint_timer #(parameter logic [63:0] RESET_COMPARE = '1) (
  input logic clk, reset_n, write_cmp_low, write_cmp_high,
  input logic [31:0] wdata,
  output logic [63:0] mtime, mtimecmp,
  output logic mtip
);
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      mtime <= 0;
      mtimecmp <= RESET_COMPARE;
      mtip <= 0;
    end else begin
      mtime <= mtime + 1'b1;
      if (write_cmp_low) mtimecmp[31:0] <= wdata;
      if (write_cmp_high) mtimecmp[63:32] <= wdata;
      mtip <= mtime >= mtimecmp;
    end
  end
endmodule
Read included file: ap_crg_boot.sv
// Startup slice of ap_crg. Each ready input is already qualified in the
// always-on domain. Board supervision handles rail or lock loss after boot.
module ap_crg_boot(
  input logic aon_clk, supply_good, osc_ready, pll_locked, boot_pin,
  input logic fabric_ready, rom_ready, shorten_wait,
  output logic osc_start, pll_start, straps_valid, boot_sel,
  output logic fabric_reset_n, core_reset_n
);
  always_ff @(posedge aon_clk or negedge supply_good) begin
    if (!supply_good) begin
      {osc_start, pll_start, straps_valid, boot_sel} <= 0;
      {fabric_reset_n, core_reset_n} <= 0;
    end else begin
      osc_start <= 1;
      if (osc_start && osc_ready) pll_start <= 1;
      if (pll_start && pll_locked && !straps_valid) begin
        boot_sel <= boot_pin;
        straps_valid <= 1;
      end
      if (straps_valid) fabric_reset_n <= 1;
      if (fabric_reset_n && fabric_ready && (rom_ready || shorten_wait))
        core_reset_n <= 1;
    end
  end
endmodule
Read included file: fixture.svh
  localparam int LUI = 0, ADDI = 1, ANDI = 2, ORI = 3, SLLI = 4, SRLI = 5, ADD = 6, SUB = 7, AND = 8, OR = 9, LW = 10, SW = 11,
                 BEQ = 12, BNE = 13, BLT = 14, BGE = 15, JAL = 16, JALR = 17, CSRR = 18, CSRW = 19, CSRS = 20, CSRC = 21, MRET = 22, WORD = 23;
  localparam int MSTATUS = 'h300, MIE = 'h304, MTVEC = 'h305, MSCRATCH = 'h340, MEPC = 'h341, MCAUSE = 'h342, MIP = 'h344;
  int kind [0:1023], fa [0:1023], fb [0:1023];   // the Boot ROM: one row for each word
  logic [31:0] fc [0:1023];
  int here = 0;                                   // the address of the next row
  task automatic at(input int address);           // the rows that follow start at this address
    here = address;
  endtask
  task automatic i(input int k, input int a, input int b, input logic [31:0] c);   // add one row
    if (here < 4096) begin kind[here >> 2] = k; fa[here >> 2] = a; fb[here >> 2] = b; fc[here >> 2] = c; end
    here += 4;
  endtask
  task automatic load_hello();
    i(LUI,   2,  0,  'h80010);   // 000: lui x2, 0x80010      the stack pointer
    i(LUI,   8,  0,  'h10000);   // 004: lui x8, 0x10000      x8: UART0
    i(ADDI,  10, 0,  104);       // 008: addi x10, x0, 104      the letter h
    i(JAL,   1,  0,  'h1c);      // 00c: jal x1, 0x1c
    i(ADDI,  10, 0,  105);       // 010: addi x10, x0, 105      the letter i
    i(JAL,   1,  0,  'h1c);      // 014: jal x1, 0x1c
    i(JAL,   0,  0,  'h18);      // 018: jal x0, 0x18
    // putc: wait for room, then write the byte in x10
    i(LW,    5,  8,  4);         // 01c: lw x5, 4(x8)      STATUS
    i(ANDI,  5,  5,  1);         // 020: andi x5, x5, 1      bit 0: ROOM
    i(BEQ,   5,  0,  'h1c);      // 024: beq x5, x0, 0x1c
    i(SW,    10, 8,  0);         // 028: sw x10, 0(x8)      TXDATA
    i(JALR,  0,  1,  0);         // 02c: jalr x0, 0(x1)      return
  endtask
  task automatic load_echo();
    i(LUI,   2,  0,  'h80010);   // 000: lui x2, 0x80010      the stack pointer
    i(ADDI,  5,  0,  96);        // 004: addi x5, x0, 96
    i(CSRW,  5,  0,  MTVEC);     // 008: csrw mtvec, x5      mtvec: the handler
    i(LUI,   8,  0,  'h80000);   // 00c: lui x8, 0x80000      x8: SRAM, where the byte count is
    i(SW,    0,  8,  0);         // 010: sw x0, 0(x8)      count = 0
    i(LUI,   9,  0,  'hc000);    // 014: lui x9, 0xc000      x9: ap_plic
    i(ADDI,  5,  0,  1);         // 018: addi x5, x0, 1
    i(SW,    5,  9,  4);         // 01c: sw x5, 4(x9)      priority of source 1 (UART0) = 1
    i(LUI,   18, 0,  'hc002);    // 020: lui x18, 0xc002
    i(ADDI,  5,  0,  2);         // 024: addi x5, x0, 2
    i(SW,    5,  18, 0);         // 028: sw x5, 0(x18)      enable bit 1
    i(LUI,   19, 0,  'hc200);    // 02c: lui x19, 0xc200      x19: threshold, and claim at offset 4
    i(LUI,   20, 0,  'h10000);   // 030: lui x20, 0x10000      x20: UART0
    i(LUI,   5,  0,  'h1);       // 034: lui x5, 0x1
    i(ADDI,  5,  5,  -2048);     // 038: addi x5, x5, -2048      x5 = 0x800
    i(CSRS,  5,  0,  MIE);       // 03c: csrs mie, x5      mie: the external enable, bit 11
    i(ADDI,  5,  0,  8);         // 040: addi x5, x0, 8
    i(CSRS,  5,  0,  MSTATUS);   // 044: csrs mstatus, x5      mstatus: MIE
    i(LW,    6,  8,  0);         // 048: lw x6, 0(x8)
    i(ADDI,  7,  0,  3);         // 04c: addi x7, x0, 3
    i(BLT,   6,  7,  'h48);      // 050: blt x6, x7, 0x48      wait for 3 bytes
    i(ADDI,  5,  0,  8);         // 054: addi x5, x0, 8
    i(CSRC,  5,  0,  MSTATUS);   // 058: csrc mstatus, x5      interrupts off
    i(JAL,   0,  0,  'h5c);      // 05c: jal x0, 0x5c
    // the handler: claim, read the byte, send it back, count it, complete. It uses x28 to x30 only.
    i(LW,    28, 19, 4);         // 060: lw x28, 4(x19)      claim: which source?
    i(LW,    29, 20, 12);        // 064: lw x29, 12(x20)      RXDATA: the read removes the byte
    i(SW,    29, 20, 0);         // 068: sw x29, 0(x20)      TXDATA
    i(LW,    30, 8,  0);         // 06c: lw x30, 0(x8)
    i(ADDI,  30, 30, 1);         // 070: addi x30, x30, 1
    i(SW,    30, 8,  0);         // 074: sw x30, 0(x8)      count = count + 1
    i(SW,    28, 19, 4);         // 078: sw x28, 4(x19)      complete: the same number goes back
    i(MRET,  0,  0,  0);         // 07c: mret
  endtask
  task automatic load_dma();
    i(LUI,   2,  0,  'h80010);   // 000: lui x2, 0x80010      the stack pointer
    i(LUI,   8,  0,  'h80000);   // 004: lui x8, 0x80000      x8: SRAM
    i(LUI,   5,  0,  'h64636);   // 008: lui x5, 0x64636
    i(ADDI,  5,  5,  609);       // 00c: addi x5, x5, 609
    i(SW,    5,  8,  256);       // 010: sw x5, 256(x8)      source bytes 61 62 63 64
    i(LUI,   5,  0,  'h68676);   // 014: lui x5, 0x68676
    i(ADDI,  5,  5,  1637);      // 018: addi x5, x5, 1637
    i(SW,    5,  8,  260);       // 01c: sw x5, 260(x8)      source bytes 65 66 67 68
    i(SW,    0,  8,  512);       // 020: sw x0, 512(x8)      clear the destination
    i(SW,    0,  8,  516);       // 024: sw x0, 516(x8)
    i(LUI,   9,  0,  'h10006);   // 028: lui x9, 0x10006      x9: DMA
    i(ADDI,  5,  8,  256);       // 02c: addi x5, x8, 256
    i(SW,    5,  9,  0);         // 030: sw x5, 0(x9)      SRC
    i(ADDI,  5,  8,  512);       // 034: addi x5, x8, 512
    i(SW,    5,  9,  4);         // 038: sw x5, 4(x9)      DST
    i(ADDI,  5,  0,  6);         // 03c: addi x5, x0, 6
    i(SW,    5,  9,  8);         // 040: sw x5, 8(x9)      LEN: 6 bytes
    i(ADDI,  5,  0,  1);         // 044: addi x5, x0, 1
    i(SW,    5,  9,  12);        // 048: sw x5, 12(x9)      START, written last
    i(LUI,   18, 0,  'hc001);    // 04c: lui x18, 0xc001      x18: the pending bits of ap_plic
    i(LW,    6,  18, 0);         // 050: lw x6, 0(x18)
    i(ANDI,  6,  6,  32);        // 054: andi x6, x6, 32      bit 5: DMA
    i(BEQ,   6,  0,  'h50);      // 058: beq x6, x0, 0x50      wait until the DMA is done
    i(LW,    10, 8,  512);       // 05c: lw x10, 512(x8)      read the copy back
    i(LW,    11, 8,  516);       // 060: lw x11, 516(x8)
    i(JAL,   0,  0,  'h64);      // 064: jal x0, 0x64
  endtask
  string pad_text = "";
  bit byte_pending;
  logic [7:0] crossing_byte;
  int arrivals;
  wire tx_clock_en = fault != 6;
  wire tx_to_pad = fault != 4;
  wire memory_grant = fault != 9 || rx_ready;
  logic        clk = 0;
  logic [31:0] x [0:31];             // the 32 registers
  logic [31:0] pc;                   // the address of the next instruction
  logic [31:0] ram [0:16383];        // SRAM: 64 KiB from 8000_0000. Nothing is in it at power-on
  logic [31:0] mstatus, mie, mtvec, mscratch, mepc, mcause;   // the machine CSRs of this model
  int          steps, traps, taken;  // instructions, exceptions, interrupts
  bit          stopped;
  localparam int SHOW = 0;            // 2: print every instruction. 1: print events only. 0: print nothing
  task automatic say(input string text);
    if (SHOW != 0) $display("t=%0d | %s", ticks, text);
  endtask
  // ---- UART0 (test code). TXDATA 00, STATUS 04 (bit 0 ROOM, bit 1 RX_READY), RXDATA 0c ----
  string       uart_text = "";                 // every byte that was sent, as text
  int          uart_wait = 0;                  // after a byte: 12 ticks with no room (a lab number)
  logic [7:0]  rx_queue [0:3];                 // received bytes that software has not read yet
  int          rx_count = 0;
  logic [7:0]  rx_plan [0:7];                  // the bytes the board will send, and at which tick
  int          rx_tick [0:7], rx_planned = 0;
  wire         rx_ready = (rx_count != 0);     // UART0 asks for an interrupt while a received byte waits
  // ---- GPIO (test code). OUT 08, TGL 14 ----
  logic [15:0] gpio_out = 0;
  int          gpio_changes = 0;
  // ---- DMA (test code). SRC 00, DST 04, LEN 08, START 0c. It moves one byte of SRAM in each tick. ----
  logic [31:0] dma_src = 0, dma_dst = 0, dma_len = 0;
  int          dma_left = 0;
  bit          dma_done = 0;                   // its interrupt request: 1 from the last byte until the next start
  int          ticks = 0;

  function automatic logic [31:0] tc_peek(input logic [31:0] ad);
    case (ad)
      32'h1000_0004: return {30'b0, rx_ready, (uart_wait == 0)};
      32'h1000_000c: return {24'b0, rx_queue[0]};
      32'h1000_1008: return {16'b0, gpio_out};
      default:       return 32'h0;
    endcase
  endfunction
  function automatic bit tc_exists(input bit wr, input logic [31:0] ad);   // 1: a register is at this address
    case (ad)
      32'h1000_0000, 32'h1000_1014, 32'h1000_6000, 32'h1000_6004, 32'h1000_6008, 32'h1000_600c: return wr;
      32'h1000_0004, 32'h1000_000c: return !wr;
      32'h1000_1008: return 1;
      default: return 0;
    endcase
  endfunction
  task automatic tc_read(input logic [31:0] ad);
    if (ad == 32'h1000_000c && rx_count != 0 && fault != 5) begin        // reading RXDATA removes the oldest byte
      for (int n = 0; n < 3; n++) rx_queue[n] = rx_queue[n + 1];
      rx_count--;
    end
  endtask
  task automatic tc_write(input logic [31:0] ad, input logic [31:0] wd);
    case (fault == 2 && ad == 32'h1000_0000 ? 32'h1000_1008 : ad)
      32'h1000_0000: if (uart_wait == 0) begin             // a byte written with no room is lost
        uart_text = {uart_text, $sformatf("%c", wd[7:0])};  uart_wait = 12; if (tx_to_pad) pad_text = {pad_text, $sformatf("%c", wd[7:0])};
        say($sformatf("UART0 sends %02h \"%c\"", wd[7:0], wd[7:0]));
      end else say($sformatf("UART0 has no room: %02h is lost", wd[7:0]));
      32'h1000_1008: begin gpio_out = wd[15:0];  gpio_changes++;  say($sformatf("GPIO OUT = %04h", gpio_out)); end
      32'h1000_1014: begin gpio_out = gpio_out ^ wd[15:0];  gpio_changes++;  say($sformatf("GPIO OUT = %04h", gpio_out)); end
      32'h1000_6000: dma_src = wd;
      32'h1000_6004: dma_dst = wd;
      32'h1000_6008: dma_len = wd;
      32'h1000_600c: if (wd[0]) begin
        dma_left = dma_len;  dma_done = 0;
        say($sformatf("DMA starts: %0d bytes from %08h to %08h", dma_len, dma_src, dma_dst));
      end
      default: ;
    endcase
  endtask
  task automatic tc_tick();
    ticks++;
    if (uart_wait != 0 && tx_clock_en) uart_wait--;
    for (int n = 0; n < rx_planned; n++) if (rx_tick[n] == ticks) begin
      arrivals++;
      crossing_byte = rx_plan[n];
      byte_pending = 1;
    end
    if (byte_pending && (trial != 8 || ticks % 8 == 2) && rx_count < 4) begin
      rx_queue[rx_count] = crossing_byte;
      rx_count++;
      byte_pending = 0;
    end
    if (fault == 8) byte_pending = 0; // source drops the pulse after one tick
    if (dma_left != 0 && memory_grant) begin                               // one byte: read it from SRAM, write it to SRAM
      ram[dma_dst[15:2]][8 * dma_dst[1:0] +: 8] = ram[dma_src[15:2]][8 * dma_src[1:0] +: 8];
      dma_src++;  dma_dst++;  dma_left--;
      if (dma_left == 0) begin dma_done = 1;  say("DMA done"); end
    end
  endtask
  task automatic board_sends(input int tick, input logic [7:0] value);   // plan one received byte
    rx_plan[rx_planned] = value;  rx_tick[rx_planned] = tick;  rx_planned++;
  endtask
  // Interrupt sources of ap_soc: 1 UART0, 2 GPIO, 3 timer and PWM, 4 SPI, 5 DMA, 6 watchdog, 7 to 16 spare.
  wire         wdg_warn;                       // the early warning of the watchdog; tied to 0 where a lab has none
  wire [16:1] sources = {10'b0, wdg_warn, dma_done, 2'b0, (fault == 3 && rx_ready), (fault != 3 && rx_ready)};
  // ---- The two chip blocks of ap_soc, unchanged: the interrupt controller and the machine timer ----
  logic        reset_n = 0, plic_commit = 0, plic_write = 0, cmp_low = 0, cmp_high = 0;
  logic [21:0] plic_offset = 0;
  logic [31:0] dev_wdata = 0;
  wire  [31:0] plic_rdata;
  wire  [63:0] mtime, mtimecmp;
  wire         irq_external, irq_timer;
  ap_plic plic (.clk, .reset_n, .commit(plic_commit), .write_en(plic_write), .offset(plic_offset), .wdata(dev_wdata),
                .level_irq(sources), .rdata(plic_rdata), .notify_irq(irq_external));
  ap_clint_timer clint (.clk, .reset_n, .write_cmp_low(cmp_low), .write_cmp_high(cmp_high), .wdata(dev_wdata),
                        .mtime, .mtimecmp, .mtip(irq_timer));
  assign wdg_warn = 1'b0;                      // no watchdog in this lab
  wire [31:0] mip = {20'b0, irq_external, 3'b0, irq_timer, 7'b0};   // bit 11: external. bit 7: machine timer

  function automatic string cn(input logic [11:0] a);   // the name of a CSR
    case (a)
      MSTATUS: return "mstatus";  MIE: return "mie";  MTVEC: return "mtvec";  MSCRATCH: return "mscratch";
      MEPC: return "mepc";  MCAUSE: return "mcause";  MIP: return "mip";
      default: return "?";
    endcase
  endfunction
  function automatic logic [31:0] csr_value(input logic [11:0] a);
    case (a)
      MSTATUS: return mstatus;  MIE: return mie;  MTVEC: return mtvec;  MSCRATCH: return mscratch;
      MEPC: return mepc;  MCAUSE: return mcause;
      default: return mip;
    endcase
  endfunction
  task automatic csr_store(input logic [11:0] a, input logic [31:0] v);   // each CSR keeps only its writable bits
    case (a)
      MSTATUS:  begin mstatus[3] = v[3];  mstatus[7] = v[7]; end           // MIE and MPIE
      MIE:      mie = v & 32'h0000_0888;                                   // external, timer and software enables
      MTVEC:    mtvec = v & 32'hffff_fffd;
      MSCRATCH: mscratch = v;
      MEPC:     mepc = v & 32'hffff_fffc;
      MCAUSE:   mcause = v;
      default: ;                                                           // mip is read-only
    endcase
  endtask
  // The entry of a trap, for an exception or an interrupt: what the processor does by itself.
  task automatic enter(input logic [31:0] cause, input string text);
    mepc = pc & 32'hffff_fffc;  mcause = cause;
    mstatus[7] = mstatus[3];  mstatus[3] = 1'b0;                           // MPIE takes MIE, MIE closes
    say($sformatf("%s: mcause=%08h mepc=%08h, next is %08h", text, cause, mepc, mtvec & 32'hffff_fffc));
    pc = mtvec & 32'hffff_fffc;
  endtask
  // Start one read or write of a word. The value of a read is in bus_rdata after half a tick.
  logic [31:0] bus_rdata;
  bit          bus_fault;
  task automatic bus(input bit wr, input logic [31:0] ad, input logic [31:0] wd);
    bus_fault = 0;  bus_rdata = 0;
    if (ad[31:12] == 20'h0) begin                                          // Boot ROM: data words can be read
      if (wr) bus_fault = 1;
      else bus_rdata = (kind[ad[11:2]] == WORD) ? fc[ad[11:2]] : 32'h0;
    end
    else if (ad[31:16] == 16'h8000) begin                                  // SRAM
      if (wr) ram[ad[15:2]] = wd;
      else bus_rdata = ram[ad[15:2]];
    end
    else if (ad[31:22] == 10'h030) begin                                   // ap_plic, from 0c00_0000
      plic_offset = ad[21:0];  plic_write = wr;  dev_wdata = wd;  plic_commit = 1;
    end
    else if (ad == 32'h0200_4000 || ad == 32'h0200_4004) begin              // ap_clint: mtimecmp
      if (wr) begin dev_wdata = wd;  cmp_low = !ad[2];  cmp_high = ad[2]; end
      else bus_rdata = ad[2] ? mtimecmp[63:32] : mtimecmp[31:0];
    end
    else if (ad == 32'h0200_bff8 || ad == 32'h0200_bffc) begin              // ap_clint: mtime, read only here
      if (wr) bus_fault = 1;
      else bus_rdata = ad[2] ? mtime[63:32] : mtime[31:0];
    end
    else if (tc_exists(wr, ad)) begin                                      // UART0, GPIO, DMA
      if (wr) tc_write(ad, wd);
      else begin bus_rdata = tc_peek(ad);  tc_read(ad); end
    end
    else bus_fault = 1;                                                    // nothing answers at this address
  endtask
  // One tick: one instruction, then one rising clock edge.
  task automatic step();
    int k, a, b;
    logic [31:0] c, r1, r2, res, next, ad;
    string text, effect;
    bit writes, take, done, access;
    // An interrupt is taken between two instructions: MIE at 1, and a request that is pending and enabled.
    if (mstatus[3] && (mie & mip) != 0) begin
      if (mie[11] && mip[11]) enter(32'h8000_000b, "interrupt, external");
      else                    enter(32'h8000_0007, "interrupt, machine timer");
      taken++;
    end
    done = 0;  writes = 1;  access = 0;  res = 0;  effect = "";  next = pc + 4;  text = "";
    if (pc >= 32'h1000) begin enter(1, "exception, no instruction at this address");  traps++;  done = 1;  k = WORD;  a = 0;  b = 0;  c = 0; end
    else begin k = kind[pc >> 2];  a = fa[pc >> 2];  b = fb[pc >> 2];  c = fc[pc >> 2]; end
    r1 = x[b[4:0]];  r2 = x[c[4:0]];
    // An immediate has 12 bits with a sign (20 bits in lui). A row outside that range is no instruction.
    if (!done && ((k == LUI && c[31:20] != 0) || ((k == ADDI || k == ANDI || k == ORI || k == LW || k == SW || k == JALR) && !($signed(c) >= -2048 && $signed(c) <= 2047)))) begin
      enter(2, $sformatf("exception, immediate out of range at %08h", pc));  traps++;  done = 1;
    end
    if (!done) case (k)
      LUI:  begin res = c << 12;  text = $sformatf("lui x%0d, 0x%0h", a, c); end
      ADDI: begin res = r1 + c;          text = $sformatf("addi x%0d, x%0d, %0d", a, b, $signed(c)); end
      ANDI: begin res = r1 & c;          text = $sformatf("andi x%0d, x%0d, %0d", a, b, $signed(c)); end
      ORI:  begin res = r1 | c;          text = $sformatf("ori x%0d, x%0d, %0d", a, b, $signed(c)); end
      SLLI: begin res = r1 << c[4:0];    text = $sformatf("slli x%0d, x%0d, %0d", a, b, c); end
      SRLI: begin res = r1 >> c[4:0];    text = $sformatf("srli x%0d, x%0d, %0d", a, b, c); end
      ADD:  begin res = r1 + r2;         text = $sformatf("add x%0d, x%0d, x%0d", a, b, c[4:0]); end
      SUB:  begin res = r1 - r2;         text = $sformatf("sub x%0d, x%0d, x%0d", a, b, c[4:0]); end
      AND:  begin res = r1 & r2;         text = $sformatf("and x%0d, x%0d, x%0d", a, b, c[4:0]); end
      OR:   begin res = r1 | r2;         text = $sformatf("or x%0d, x%0d, x%0d", a, b, c[4:0]); end
      LW, SW: begin
        ad = r1 + c;  access = 1;
        text = $sformatf("%s x%0d, %0d(x%0d)", (k == LW) ? "lw" : "sw", a, $signed(c), b);
        bus(k == SW, ad, x[a[4:0]]);
        if (k == SW) begin writes = 0;  effect = $sformatf("mem[%08h] = %08h", ad, x[a[4:0]]); end
      end
      BEQ, BNE, BLT, BGE: begin
        r1 = x[a[4:0]];  r2 = x[b[4:0]];  writes = 0;
        case (k)
          BEQ: take = (r1 == r2);
          BNE: take = (r1 != r2);
          BLT: take = ($signed(r1) < $signed(r2));
          default: take = ($signed(r1) >= $signed(r2));
        endcase
        text = $sformatf("%s x%0d, x%0d, 0x%0h", (k == BEQ) ? "beq" : (k == BNE) ? "bne" : (k == BLT) ? "blt" : "bge", a, b, c);
        if (take) begin next = c;  effect = $sformatf("taken: next is %08h", next); end
        else effect = "not taken";
      end
      JAL, JALR: begin
        res = pc + 4;
        if (k == JAL) begin next = c;  text = $sformatf("jal x%0d, 0x%0h", a, c); end
        else begin next = (r1 + c) & ~32'd1;  text = $sformatf("jalr x%0d, %0d(x%0d)", a, $signed(c), b); end
        if (k == JAL && next == pc) begin
          if (SHOW == 2) $display("%08h | %s | the program stops here", pc, text);
          else say($sformatf("the program stops at %08h", pc));
          stopped = 1;  done = 1;
        end
      end
      CSRR: begin res = csr_value(c[11:0]);  text = $sformatf("csrr x%0d, %s", a, cn(c[11:0])); end
      CSRW, CSRS, CSRC: begin
        writes = 0;
        case (k)
          CSRW:    csr_store(c[11:0], x[a[4:0]]);
          CSRS:    csr_store(c[11:0], csr_value(c[11:0]) | x[a[4:0]]);
          default: csr_store(c[11:0], csr_value(c[11:0]) & ~x[a[4:0]]);
        endcase
        text = $sformatf("%s %s, x%0d", (k == CSRW) ? "csrw" : (k == CSRS) ? "csrs" : "csrc", cn(c[11:0]), a);
        effect = $sformatf("%s = %08h", cn(c[11:0]), csr_value(c[11:0]));
      end
      MRET: begin
        writes = 0;  next = mepc;  text = "mret";
        mstatus[3] = mstatus[7];  mstatus[7] = 1'b1;                       // MIE takes MPIE back
        effect = $sformatf("next is %08h, MIE=%0d", next, mstatus[3]);
        if (SHOW == 1) say($sformatf("mret: back to %08h", next));
      end
      default: begin enter(2, $sformatf("exception, illegal instruction %08h at %08h", c, pc));  traps++;  done = 1; end
    endcase
    #1;                                                                    // half a tick: the devices answer
    if (access && !done) begin
      if (plic_commit && !plic_write) begin
        bus_rdata = plic_rdata;
        if (plic_offset == 22'h20_0004) say($sformatf("PLIC claim returns %0d", plic_rdata));
      end
      if (plic_commit && plic_write && plic_offset == 22'h20_0004) say($sformatf("PLIC complete %0d", dev_wdata));
      if (bus_fault) begin
        enter((k == LW) ? 5 : 7, $sformatf("exception, no memory at %08h for %s at %08h", ad, (k == LW) ? "a load" : "a store", pc));
        traps++;  done = 1;
      end
      else if (k == LW) begin res = bus_rdata;  effect = $sformatf(" from mem[%08h]", ad); end
    end
    if (!done) begin
      if (writes) begin
        if (a[4:0] != 0) x[a[4:0]] = res;                                  // register 0 is never written
        effect = {$sformatf("x%0d = %08h", a, x[a[4:0]]), effect};
        if (k == JAL || k == JALR) effect = {effect, $sformatf(", next is %08h", next)};
      end
      if (SHOW == 2) $display("%08h | %s | %s", pc, text, effect);
      pc = next;  steps++;
    end
    tc_tick();
    clk = 1;  #1;  clk = 0;                                                // the rising edge: registers of the chip blocks load
    plic_commit = 0;  plic_write = 0;  cmp_low = 0;  cmp_high = 0;
  endtask
  task automatic power_on();
    for (int n = 0; n < 32; n++) x[n] = 0;
    for (int n = 0; n < 16384; n++) ram[n] = 'x;                           // SRAM holds nothing known
    mstatus = 32'h0000_1800;  mie = 0;  mtvec = 0;  mscratch = 0;  mepc = 0;  mcause = 0;   // the values after reset
    pc = 0;  steps = 0;  traps = 0;  taken = 0;  stopped = 0;
    uart_text = "";  uart_wait = 0;  rx_count = 0;  rx_planned = 0;  gpio_out = 0;  gpio_changes = 0;
    dma_left = 0;  dma_done = 0;  ticks = 0;
    reset_n = 0;  #1 clk = 1;  #1 clk = 0;  reset_n = 1;                   // one clock edge in reset for the chip blocks
  endtask
  task automatic run();
    while (!stopped && steps + traps + taken < 400) step();
  endtask
  bit aon, supply_good;
  wire fabric_up, core_up, boot_sel;
  int rom_edges;
  wire rom_ready = rom_edges >= 4;
  always @(posedge aon) if (fabric_up) rom_edges <= rom_edges + 1;
  ap_crg_boot boot(.aon_clk(aon), .supply_good, .osc_ready(1'b1), .pll_locked(1'b1),
    .boot_pin(fault == 10), .fabric_ready(1'b1), .rom_ready, .shorten_wait(fault == 7),
    .fabric_reset_n(fabric_up), .core_reset_n(core_up), .boot_sel);
  task automatic release_core();
    #1 aon = 1; #1 aon = 0; supply_good = 1;
    while (!core_up) begin #1 aon = 1; #1 aon = 0; end
    first_address = boot_sel ? 32'h8000_0000 : 0;
    first_ready = rom_ready;
  endtask
ConceptWhat separates the two silent boot cases?
ConceptWhy is room low even at the end of a healthy hello?
ConceptA pulse fits entirely between two sampling edges. What does the receiver capture?
ConceptWhich input should pace this six-byte memory copy?

Common Mistakes

Wrong Wait longer whenever polling stalls.

A stopped clock cannot create room, however long software waits.

Fix Probe the enable and the state that needs the clock.

Wrong Use the current pin level to explain a boot.

The chip saved the value earlier.

Fix Check the pin at sampling and the saved selection at release.

Wrong Synchronize a short pulse and assume it arrived.

The first sampling edge can miss the whole pulse.

Fix Hold the event until capture or transfer a suitably spaced toggle.

Remember

  • Inspect boot selection and readiness at the first fetch.
  • Track progress from one operation to the next.
  • Observe a request at its receiving edge and use the grant appropriate to the transfer.

Practice

Report a problem with this page