ap_soc v1.0: The Whole Chip on One Page

Start with a store instruction. Follow its address, its completion and its effect outside the chip.

You Will Be Able To

  • Trace a transfer from a manager to a physical pin.
  • Resolve a software assumption against the source line that implements it.
  • Explain what the release smoke program establishes about each path.
Lesson
S11.1
Time
30 min
Runs on
Your browser
Check
5 questions

Firmware says it sent a character. A board engineer sees a quiet pin. Where can both observations be true?

Before You Start

Recall the address decode and bridge lessons. A manager starts a transfer and a subordinate answers it.

Five questions this page answers
Question
1Which port carries the payload of an SRAM copy?
2Which action consumes input?
3What can cause a silent console after a successful transmit store?
4Which observation distinguishes PWM routing from programming alone?
5With SAMPLE changed to hexadecimal 52, which final application line appears?

The Idea

A chip drawing answers who connects to whom. An architecture reference adds what each connection promises.

Read across three boundaries. An address chooses a destination. A register operation changes state. A signal carries that change elsewhere.

Keep the software view beside the board view. A successful store can start a transmitter while a different function owns the pin.

New Words

New words on this page
WordMeaning
Release smoke programA short program with observable results on each major path of one chip configuration.
DescriptorThe source address, destination address and length for a copy.
Configuration parameterA choice made when building a block, such as the number of stored words.
Pin functionThe signal a board design allows a digital pad to drive or sample.

One Picture: Find the Owner

The v1.0 Chip and Its SourcesSelect any block or pad to reach its lesson and numbered source listing. Play the route to follow one console write.
The v1.0 Chip and Its SourcesManagers connect to the AHB-Lite backbone. A bridge connects its peripheral window to APB. Arrows show request or signal direction. Dashed lines distribute clock and reset. ap_soc v1.0 Interrupt requests AHB-Lite fabric. AHB-Lite fabric AHB-Lite fabric APB peripheral bus. APB peripheral bus APB peripheral bus ap_rv32. Issues instruction fetches, loads and stores. ap_rv32Processor JTAG debug. Provides external debug access to the core and fabric. JTAG debug AHB-to-APB bridge. Accepts AHB transfers and issues APB peripheral accesses. AHB-to-APB bridge ap_crg. Distributes clocks and resets. ap_crgClock / reset Power control. Sequences supply domains. Power control Pin mux. Selects the peripheral function connected to each pad. Pin mux Boot ROM. Reset vector and boot code. Boot ROM4 KiB ap_clint. Core-local timer and software interrupts. ap_clint ap_plic. Platform interrupt controller, 16 sources. ap_plic UART0. Serial console. UART0 GPIO. 16 general-purpose pins. GPIO Timer / PWM. Timer and pulse-width modulation. Timer / PWM Watchdog. Watchdog reset control. Watchdog ap_sysctl. Chip ID, reset cause, clock control, pin mux and straps. ap_sysctl SPI. SPI controller. SPI DMA. DMA control registers; transfers use its AHB manager port. DMA SRAM. Program and data memory. SRAM64 KiB CLK. Package connection. CLK RST. Package connection. RST JTAG. Package connection. JTAG UART TX. Package connection. UART TX UART RX. Package connection. UART RX GPIO pins. Package connection. GPIO pins
The v1.0 Chip and Its SourcesManagers connect to the AHB-Lite backbone. A bridge connects its peripheral window to APB. Arrows show request or signal direction. Dashed lines distribute clock and reset. ap_soc v1.0 AHB-Lite fabric. AHB-Lite fabric AHB-Lite fabric APB peripheral bus. APB peripheral bus APB peripheral bus ap_rv32. Issues instruction fetches, loads and stores. ap_rv32Processor JTAG debug. Provides external debug access to the core and fabric. JTAG debug AHB-to-APB bridge. Accepts AHB transfers and issues APB peripheral accesses. AHB-to-APB bridge ap_crg. Distributes clocks and resets. ap_crgClock / reset Power control. Sequences supply domains. Power control Pin mux. Selects the peripheral function connected to each pad. Pin mux Boot ROM. Reset vector and boot code. Boot ROM4 KiB ap_clint. Core-local timer and software interrupts. ap_clint ap_plic. Platform interrupt controller, 16 sources. ap_plic UART0. Serial console. UART0 GPIO. 16 general-purpose pins. GPIO Timer / PWM. Timer and pulse-width modulation. Timer / PWM Watchdog. Watchdog reset control. Watchdog ap_sysctl. Chip ID, reset cause, clock control, pin mux and straps. ap_sysctl SPI. SPI controller. SPI DMA. DMA control registers; transfers use its AHB manager port. DMA SRAM. Program and data memory. SRAM64 KiB CLK. Package connection. CLK RST. Package connection. RST JTAG. Package connection. JTAG UART TX. Package connection. UART TX UART RX. Package connection. UART RX GPIO pins. Package connection. GPIO pins
Read the chip as text

Managers connect to the AHB-Lite backbone. A bridge connects its peripheral window to APB. Arrows show request or signal direction. Dashed lines distribute clock and reset.

  • AHB-Lite fabric · AHB-Lite fabric
  • APB peripheral bus · APB peripheral bus
  • ap_rv32 · Issues instruction fetches, loads and stores.
  • JTAG debug · Provides external debug access to the core and fabric.
  • AHB-to-APB bridge · Accepts AHB transfers and issues APB peripheral accesses.
  • ap_crg · Distributes clocks and resets.
  • Power control · Sequences supply domains.
  • Pin mux · Selects the peripheral function connected to each pad.
  • Boot ROM · Reset vector and boot code.
  • ap_clint · Core-local timer and software interrupts.
  • ap_plic · Platform interrupt controller, 16 sources.
  • UART0 · Serial console.
  • GPIO · 16 general-purpose pins.
  • Timer / PWM · Timer and pulse-width modulation.
  • Watchdog · Watchdog reset control.
  • ap_sysctl · Chip ID, reset cause, clock control, pin mux and straps.
  • SPI · SPI controller.
  • DMA · DMA control registers; transfers use its AHB manager port.
  • SRAM · Program and data memory.
  • CLK · Package connection.
  • RST · Package connection.
  • JTAG · Package connection.
  • UART TX · Package connection.
  • UART RX · Package connection.
  • GPIO pins · Package connection.
  • CLK → ap_crg (clock)
  • RST → ap_crg (clock)
  • Power control → ap_crg (power)
  • ap_crg → ap_rv32 (clock)
  • ap_crg → AHB-Lite fabric (clock)
  • ap_crg → Boot ROM (clock)
  • ap_crg → APB peripheral bus (clock)
  • ap_clint → ap_rv32 (interrupt)
  • ap_plic → ap_rv32 (interrupt)
  • AHB-Lite fabric → ap_clint (data)
  • JTAG → JTAG debug (debug)
  • DMA → AHB-Lite fabric (data)
  • UART0 → Pin mux (data)
  • GPIO → Pin mux (data)
  • Pin mux → UART TX (data)
  • UART RX → Pin mux (data)
  • Pin mux → GPIO pins (data)
  • ap_rv32 → AHB-Lite fabric (data)
  • JTAG debug → AHB-Lite fabric (data)
  • AHB-to-APB bridge → APB peripheral bus (data)
  • AHB-Lite fabric → AHB-to-APB bridge (data)
  • AHB-Lite fabric → Boot ROM (data)
  • AHB-Lite fabric → ap_plic (data)
  • APB peripheral bus → UART0 (data)
  • APB peripheral bus → GPIO (data)
  • APB peripheral bus → Timer / PWM (data)
  • APB peripheral bus → Watchdog (data)
  • APB peripheral bus → ap_sysctl (data)
  • APB peripheral bus → SPI (data)
  • APB peripheral bus → DMA (data)
  • AHB-Lite fabric → SRAM (data)
  1. The core issues a store of 0x68 to 0x1000_0000.
  2. The fabric decodes the address into the APB bridge window.
  3. The bridge holds the write across the APB setup and access phases.
  4. The peripheral decode asserts the select for UART0.
  5. UART0 accepts the byte on the completing access edge. The lab observes delivery here.
  6. In silicon, the mux routes the serialized UART output to the assigned pad.
  7. The TX pad drives the framed bits onto the board.
Block Lessons and Source Listings
Explore ap_rv32 · lesson and source

Open the ap_rv32 lesson.

Download ap_rv32.sv
Numbered source for ap_rv32.sv.
  1  // ap_rv32: the five-stage build of the core, as it sits in ap_soc.
  2  // The pipeline ap_rv32_p5 and two adapters that turn its native memory ports into AHB-Lite
  3  // manager ports: i_ for instruction fetch, d_ for loads and stores.
  4  // Five-stage build only. Taught in S2.16. Blueprint: sections 2.2 and 3 (every port).
  5  module ap_rv32 (
  6    input  logic        hclk,            // the only clock
  7    input  logic        hresetn,         // reset, active low
  8    input  logic [31:0] reset_vector,    // address of the first instruction
  9    input  logic [31:0] hart_id,         // value of mhartid
 10    output logic [31:0] i_haddr,         // instruction port: address of the next instruction
 11    output logic [1:0]  i_htrans,        // NONSEQ to fetch, IDLE when asleep or in reset
 12    output logic        i_hwrite,        // always 0
 13    output logic [2:0]  i_hsize,         // always a word
 14    output logic [2:0]  i_hburst,        // always SINGLE
 15    output logic [3:0]  i_hprot,         // opcode fetch, privileged
 16    output logic        i_hmastlock,     // always 0
 17    output logic [31:0] i_hwdata,        // always 0
 18    input  logic [31:0] i_hrdata,        // the instruction
 19    input  logic        i_hready,        // transfer done
 20    input  logic        i_hresp,         // 1: ERROR
 21    output logic [31:0] d_haddr,         // data port: address of the load or store
 22    output logic [1:0]  d_htrans,        // NONSEQ for a load or store, else IDLE
 23    output logic        d_hwrite,        // 1 for a store
 24    output logic [2:0]  d_hsize,         // byte, half or word
 25    output logic [2:0]  d_hburst,        // always SINGLE
 26    output logic [3:0]  d_hprot,         // data access, privileged
 27    output logic        d_hmastlock,     // always 0
 28    output logic [31:0] d_hwdata,        // store data on the active byte lanes
 29    input  logic [31:0] d_hrdata,        // load data on the active byte lanes
 30    input  logic        d_hready,        // transfer done
 31    input  logic        d_hresp,         // 1: ERROR
 32    input  logic        irq_external,    // external interrupt, a level: mip.MEIP
 33    input  logic        irq_timer,       // timer interrupt, a level: mip.MTIP
 34    input  logic        irq_software,    // software interrupt, a level: mip.MSIP
 35    output logic        core_sleep,      // asleep after a wfi, with both ports idle
 36    output logic        core_wake,       // an interrupt enabled in mie is pending
 37    output logic        trace_valid,     // retire trace (blueprint 3.5): a record is present
 38    output logic [63:0] trace_order,     // record number since reset
 39    output logic [31:0] trace_pc,        // address of the instruction
 40    output logic [31:0] trace_insn,      // the instruction word; 0 when its fetch faulted
 41    output logic [31:0] trace_next_pc,   // address executed next
 42    output logic [1:0]  trace_priv,      // privilege level: always machine
 43    output logic        trace_trap,      // a trap was taken instead of the instruction
 44    output logic [31:0] trace_cause,     // on a trap: the new mcause
 45    output logic [31:0] trace_tval,      // on a trap: the new mtval
 46    output logic [4:0]  trace_rs1_addr,  // register read as rs1
 47    output logic [31:0] trace_rs1_rdata, // its value
 48    output logic [4:0]  trace_rs2_addr,  // register read as rs2
 49    output logic [31:0] trace_rs2_rdata, // its value
 50    output logic [4:0]  trace_rd_addr,   // register written
 51    output logic [31:0] trace_rd_wdata,  // value written
 52    output logic [31:0] trace_mem_addr,  // address of the load or store
 53    output logic [3:0]  trace_mem_rmask, // bytes read
 54    output logic [3:0]  trace_mem_wmask, // bytes written
 55    output logic [31:0] trace_mem_rdata, // bytes read, first byte in bits 7:0
 56    output logic [31:0] trace_mem_wdata, // bytes written, first byte in bits 7:0
 57    output logic        trace_csr_write, // a CSR instruction wrote a CSR
 58    output logic [11:0] trace_csr_addr,  // address of that CSR
 59    output logic [31:0] trace_csr_wdata, // value the CSR holds after the write
 60    output logic [31:0] trace_mstatus,   // mstatus after this record
 61    output logic [31:0] trace_mip,       // interrupt-pending bits this record was decided with
 62    output logic        view_valid_f,    // pipeline view (blueprint 3.6): observation only
 63    output logic        view_valid_d,    // ID holds an instruction
 64    output logic        view_valid_e,    // EX holds an instruction
 65    output logic        view_valid_m,    // MEM holds an instruction
 66    output logic        view_valid_w,    // WB holds an instruction
 67    output logic [31:0] view_pc_f,       // address of the instruction in IF
 68    output logic [31:0] view_pc_d,       // address of the instruction in ID
 69    output logic [31:0] view_pc_e,       // address of the instruction in EX
 70    output logic [31:0] view_pc_m,       // address of the instruction in MEM
 71    output logic [31:0] view_pc_w,       // address of the instruction in WB
 72    output logic        view_stall_f,    // the fetch repeats: IF could not hand its instruction over
 73    output logic        view_stall_d,    // ID keeps its instruction (load-use)
 74    output logic        view_bubble_e,   // EX receives a bubble
 75    output logic        view_freeze,     // all five stages hold (the data bus is not ready)
 76    output logic        view_flush_d,    // the instruction in ID is discarded
 77    output logic        view_flush_e,    // the instruction in EX is discarded
 78    output logic [1:0]  view_forward_a,  // rs1 of EX is used and forwarded: 1 from MEM, 2 from WB
 79    output logic [1:0]  view_forward_b,  // the same for rs2
 80    output logic        view_redirect_e, // a taken branch or a jump leaves EX and is not discarded
 81    output logic        view_redirect_m  // a trap or a system instruction leaves MEM
 82  );
 83    import ap_rv32_p5_pkg::*;
 84  
 85    logic        imem_req;       // native instruction port of the pipeline (blueprint 3.3)
 86    logic [31:0] imem_addr;      // address of the next instruction to fetch
 87    logic        imem_ready;     // the fetch in flight is complete, imem_addr is accepted
 88    logic [31:0] imem_rdata;     // the instruction word, valid with imem_ready
 89    logic        imem_err_first; // the fetch completing now ends in a bus error
 90    logic        dmem_req;       // native data port of the pipeline
 91    logic        dmem_write;     // 1: store; 0: load
 92    logic [1:0]  dmem_size;      // 0, 1, 2: byte, half, word
 93    logic [31:0] dmem_addr;      // its address
 94    logic [31:0] dmem_wdata;     // store data on its byte lanes, in the response phase (MEM)
 95    logic        dmem_ready;     // the access in MEM is complete, the one in EX is accepted
 96    logic [31:0] dmem_rdata;     // load data, valid with dmem_ready
 97    logic        dmem_err_first; // the access completing now ends in a bus error
 98  
 99    ap_rv32_p5 u_p5 (.clk(hclk), .rst_n(hresetn), .*);
100  
101    // Instruction port: always a read of one word. A fetch behind an ERROR is not cancelled.
102    ap_rv32_ahb_manager #(.HPROT(HPROT_INSTRUCTION), .CANCEL_ON_ERROR(1'b0)) u_instr_port (
103      .hclk(hclk), .hresetn(hresetn),
104      .req(imem_req), .addr(imem_addr), .write(1'b0), .size(ap_rv32_pkg::SIZE_WORD), .wdata('0),
105      .ready(imem_ready), .rdata(imem_rdata), .err_first(imem_err_first),
106      .haddr(i_haddr), .htrans(i_htrans), .hwrite(i_hwrite), .hsize(i_hsize), .hburst(i_hburst),
107      .hprot(i_hprot), .hmastlock(i_hmastlock), .hwdata(i_hwdata),
108      .hrdata(i_hrdata), .hready(i_hready), .hresp(i_hresp)
109    );
110  
111    // Data port: the load or store behind an ERROR is cancelled (rule B4).
112    ap_rv32_ahb_manager #(.HPROT(HPROT_DATA), .CANCEL_ON_ERROR(1'b1)) u_data_port (
113      .hclk(hclk), .hresetn(hresetn),
114      .req(dmem_req), .addr(dmem_addr), .write(dmem_write), .size(dmem_size), .wdata(dmem_wdata),
115      .ready(dmem_ready), .rdata(dmem_rdata), .err_first(dmem_err_first),
116      .haddr(d_haddr), .htrans(d_htrans), .hwrite(d_hwrite), .hsize(d_hsize), .hburst(d_hburst),
117      .hprot(d_hprot), .hmastlock(d_hmastlock), .hwdata(d_hwdata),
118      .hrdata(d_hrdata), .hready(d_hready), .hresp(d_hresp)
119    );
120  
121  endmodule
Explore Boot ROM · lesson and source

Open the Boot ROM lesson.

Download ap_rom.sv
Numbered source for ap_rom.sv.
  1  // A model of the Boot ROM of ap_soc: 1,024 words of 32 bits, read only.
  2  // It has the read half of the SRAM port: a read shows its word after the rising clock edge.
  3  // There is no write pin. A test bench fills the array "mem" directly before the run: the back-door load path.
  4  module ap_rom #(parameter int WORDS = 1024) (
  5    input  logic                     clk,
  6    input  logic                     ce,     // chip enable: 1 = this edge is a read
  7    input  logic [$clog2(WORDS)-1:0] addr,   // a word address, not a byte address
  8    output logic [31:0]              rdata
  9  );
 10    logic [31:0] mem [0:WORDS-1];
 11    always_ff @(posedge clk) if (ce) rdata <= mem[addr];       // rdata changes on a read edge only
 12  endmodule
Explore SRAM · lesson and source

Open the SRAM lesson.

Download ap_sram.sv
Numbered source for ap_sram.sv.
  1  // A model of the on-chip SRAM of ap_soc: one port, words of 32 bits, one strobe for each byte.
  2  // Everything is sampled on the rising clock edge. A read shows its word after that edge.
  3  // This is a model for simulation. A real chip uses a block made by a memory generator, with these pins.
  4  module ap_sram #(parameter int WORDS = 16384) (
  5    input  logic                     clk,
  6    input  logic                     ce,     // chip enable: 1 = this edge is an access
  7    input  logic                     we,     // 1 = write, 0 = read
  8    input  logic [3:0]               be,     // byte strobes of a write. Bit 0 is the lowest byte
  9    input  logic [$clog2(WORDS)-1:0] addr,   // a word address, not a byte address
 10    input  logic [31:0]              wdata,
 11    output logic [31:0]              rdata
 12  );
 13    logic [31:0] mem [0:WORDS-1];
 14    always_ff @(posedge clk) begin
 15      if (ce && we) begin
 16        for (int i = 0; i < 4; i++)
 17          if (be[i]) mem[addr][8*i +: 8] <= wdata[8*i +: 8];   // only the strobed bytes change
 18      end
 19      if (ce && !we) rdata <= mem[addr];                       // rdata changes on a read edge only
 20    end
 21  endmodule
Explore AHB · lesson and source

Open the AHB lesson.

Download full_decode.sv
Numbered source for full_decode.sv.
  1  module \full_decode (input wire [31:0] addr, output wire [10:0] sel, output wire error_sel);
  2    // sel[0]: Boot ROM
  3    assign sel[0] = ((addr & 32'hfffff000) == 32'h00000000);
  4    // sel[1]: ap_clint
  5    assign sel[1] = ((addr & 32'hffff0000) == 32'h02000000);
  6    // sel[2]: ap_plic
  7    assign sel[2] = ((addr & 32'hffc00000) == 32'h0c000000);
  8    // sel[3]: UART0
  9    assign sel[3] = ((addr & 32'hfffff000) == 32'h10000000);
 10    // sel[4]: GPIO
 11    assign sel[4] = ((addr & 32'hfffff000) == 32'h10001000);
 12    // sel[5]: Timer and PWM
 13    assign sel[5] = ((addr & 32'hfffff000) == 32'h10002000);
 14    // sel[6]: Watchdog
 15    assign sel[6] = ((addr & 32'hfffff000) == 32'h10003000);
 16    // sel[7]: ap_sysctl
 17    assign sel[7] = ((addr & 32'hfffff000) == 32'h10004000);
 18    // sel[8]: SPI
 19    assign sel[8] = ((addr & 32'hfffff000) == 32'h10005000);
 20    // sel[9]: DMA
 21    assign sel[9] = ((addr & 32'hfffff000) == 32'h10006000);
 22    // sel[10]: SRAM
 23    assign sel[10] = ((addr & 32'hffff0000) == 32'h80000000);
 24    assign error_sel = ~|sel;
 25  endmodule
Explore AHB-to-APB bridge · lesson and source

Open the AHB-to-APB bridge lesson.

Download ahb_apb_bridge.sv
Numbered source for ahb_apb_bridge.sv.
  1  `timescale 1ns/1ns
  2  // ahb_apb_bridge.sv: an AHB subordinate that turns each accepted transfer into one APB transfer
  3  // (read-only). The address phase is registered when HSEL, HREADY and a NONSEQ or SEQ transfer are
  4  // all present. During SETUP and unfinished ACCESS the bridge keeps HREADYOUT low. A successful APB
  5  // completion ends the AHB data phase with OKAY and HRDATA = PRDATA. A failed APB completion starts
  6  // the two-cycle ERROR (HREADYOUT low then high, HRESP high in both). HWDATA and HWSTRB are data-phase signals the manager holds
  7  // through the wait states, so PWDATA and PSTRB are driven from them directly; PADDR is the aligned
  8  // word address (IHI 0024E 2.1.1 leaves an unaligned PADDR unpredictable). HPROT maps onto PPROT:
  9  // privileged from HPROT[1], instruction from HPROT[0] = 0, and the access is Secure.
 10  // A write therefore costs one setup and one access cycle: two cycles of data phase with no APB wait.
 11  module ahb_apb_bridge (
 12    input  logic        hclk,
 13    input  logic        hresetn,
 14    input  logic        hsel,
 15    input  logic [31:0] haddr,
 16    input  logic [1:0]  htrans,
 17    input  logic        hwrite,
 18    input  logic [3:0]  hprot,
 19    input  logic [31:0] hwdata,
 20    input  logic [3:0]  hwstrb,
 21    input  logic        hready,
 22    output logic        hreadyout,
 23    output logic        hresp,
 24    output logic [31:0] hrdata,
 25    output logic        psel,
 26    output logic        penable,
 27    output logic        pwrite,
 28    output logic [31:0] paddr,
 29    output logic [31:0] pwdata,
 30    output logic [3:0]  pstrb,
 31    output logic [2:0]  pprot,
 32    input  logic        pready,
 33    input  logic [31:0] prdata,
 34    input  logic        pslverr);
 35    localparam int IDLE = 0, SETUP = 1, ACCESS = 2, ERR1 = 3, ERR2 = 4;
 36    bit trace = 0;
 37    int st = IDLE;
 38    logic        wr = 0;
 39    logic [31:0] a = 0;
 40    logic [2:0]  prot = 0;
 41    wire take = hsel && hready && htrans[1];
 42    assign psel      = (st == SETUP || st == ACCESS);
 43    assign penable   = (st == ACCESS);
 44    assign pwrite    = wr;
 45    assign paddr     = {a[31:2], 2'b00};     // APB leaves an unaligned PADDR unpredictable: the word, and PSTRB picks the bytes
 46    assign pwdata    = wr ? hwdata : 32'h0;
 47    assign pstrb     = wr ? hwstrb : 4'h0;
 48    assign pprot     = prot;
 49    assign hreadyout = (st == IDLE || st == ERR2) ? 1'b1 : (st == ACCESS) ? (pready === 1'b1 && pslverr !== 1'b1) : 1'b0;
 50    assign hresp     = (st == ERR1 || st == ERR2);
 51    assign hrdata    = (st == ACCESS) ? prdata : 32'h0;
 52    always @(posedge hclk or negedge hresetn) begin
 53      if (!hresetn) st <= IDLE;
 54      else begin
 55        case (st)
 56          SETUP:  st <= ACCESS;
 57          ACCESS: if (pready === 1'b1) begin
 58                    if (trace) $display("apb e%0d: %0s 0x%03h%0s", ($time - 5) / 10, wr ? "write" : "read", a[11:0], pslverr === 1'b1 ? " PSLVERR" : "");
 59                    st <= (pslverr === 1'b1) ? ERR1 : IDLE;
 60                  end
 61          ERR1:   st <= ERR2;
 62          default: st <= IDLE;
 63        endcase
 64        // A new address phase can be taken whenever HREADY is 1: in IDLE, in the last cycle of ERROR,
 65        // or at the edge an access completes with OKAY.
 66        if (take && (st == IDLE || st == ERR2 || (st == ACCESS && pready === 1'b1 && pslverr !== 1'b1))) begin
 67          wr <= hwrite; a <= haddr; prot <= {~hprot[0], 1'b0, hprot[1]}; st <= SETUP;
 68        end
 69      end
 70    end
 71  endmodule
Explore APB · lesson and source

Open the APB lesson.

Download apb_io_pair.sv
Numbered source for apb_io_pair.sv.
  1  // The two register ports exercised in S4.5. Only UART can stretch a transfer.
  2  module ap_uart_tx_port(
  3    input  logic        clk, reset_n, sel, enable, write,
  4    input  logic [11:0] offset,
  5    input  logic [31:0] data, wait_edges,
  6    input  logic [3:0]  strb,
  7    output logic        ready, error, push,
  8    output logic [7:0]  tx_byte
  9  );
 10    logic [31:0] elapsed;
 11    always_ff @(posedge clk or negedge reset_n) begin
 12      if (!reset_n) elapsed <= 0;
 13      else if (sel && enable && !ready) elapsed <= elapsed + 1;
 14      else elapsed <= 0;
 15    end
 16  
 17    assign ready = sel && enable && elapsed >= wait_edges;
 18    assign error = ready && (!write || offset != 12'h000);
 19    assign push = ready && !error && strb[0];
 20    assign tx_byte = data[7:0];
 21  endmodule
 22  
 23  module ap_gpio_input_port(
 24    input  logic        sel, enable, write,
 25    input  logic [11:0] offset,
 26    input  logic [15:0] pins,
 27    output logic        ready, error,
 28    output logic [31:0] data
 29  );
 30    wire input_word = !write && offset == 12'h004;
 31    assign ready = sel && enable;
 32    assign error = ready && !input_word;
 33    assign data = sel && input_word ? {16'b0, pins} : 32'b0;
 34  endmodule
Explore JTAG debug · lesson and source

Open the JTAG debug lesson.

Download soc-s83-debug.svh
Numbered source for soc-s83-debug.svh.
  1  // Single-clock bench slice. The host starts in Run-Test/Idle with the lab
  2  // data register selected. Only the direct DR scan path is exercised.
  3  bit tck, tms, tdi, reset_n, authenticated, core_reset = 1;
  4  logic [34:0] shift_dr = 0;
  5  wire tdo = shift_dr[0];
  6  typedef enum {IDLE, SELECT_DR, CAPTURE_DR, SHIFT_DR, EXIT_DR, UPDATE_DR} tap_state;
  7  tap_state tap = IDLE;
  8  logic [31:0] reply = 0, address = 32'h80000000, payload = 0;
  9  logic halt_on_reset = 0, halted = 0, was_reset = 1;
 10  logic [31:0] boot_marker = 32'h00000040;
 11  typedef enum {FREE, ADDRESS, DATA} bus_state;
 12  bus_state bus = FREE;
 13  logic writing = 0;
 14  wire selected = address[31:16] == 16'h8000;
 15  wire ready, error_response;
 16  wire [31:0] read_data;
 17  ahb_mem ram(.hclk(tck), .hresetn(reset_n), .hsel(selected),
 18    .haddr(address), .htrans(bus == ADDRESS ? 2'b10 : 2'b00),
 19    .hwrite(writing), .hsize(3'd2), .hburst(3'b0), .hprot(4'b0011),
 20    .hmastlock(1'b0), .hwdata(payload), .hwstrb(4'hf), .hexcl(1'b0),
 21    .hmaster(4'd1), .hready(ready), .hreadyout(ready), .hresp(error_response),
 22    .hrdata(read_data), .hexokay());
 23  
 24  always @(posedge tck) begin
 25    case (tap)
 26      IDLE: if (tms) tap <= SELECT_DR;
 27      SELECT_DR: tap <= CAPTURE_DR;
 28      CAPTURE_DR: begin
 29        shift_dr <= {authenticated ? reply : 32'b0, 3'b0};
 30        tap <= SHIFT_DR;
 31      end
 32      SHIFT_DR: begin
 33        shift_dr <= {tdi, shift_dr[34:1]};
 34        if (tms) tap <= EXIT_DR;
 35      end
 36      EXIT_DR: tap <= UPDATE_DR;
 37      UPDATE_DR: begin
 38        tap <= IDLE;
 39        if (authenticated) begin
 40          case (shift_dr[2:0])
 41            1: address <= shift_dr[34:3];
 42            2,3: if (bus == FREE && selected && address[1:0] == 0) begin
 43              payload <= shift_dr[34:3];
 44              writing <= shift_dr[2:0] == 2;
 45              bus <= ADDRESS;
 46            end
 47            4: halt_on_reset <= shift_dr[3];
 48            5: if (halted) reply <= boot_marker;
 49            default: ;
 50          endcase
 51        end
 52      end
 53    endcase
 54    was_reset <= core_reset;
 55    if (core_reset) halted <= 0;
 56    else if (was_reset && halt_on_reset) halted <= 1;
 57    if (bus == ADDRESS && ready) begin
 58      $display("address %08h write=%b ready=%b", address, writing, ready);
 59      bus <= DATA;
 60    end
 61    if (bus == DATA) begin
 62      $display("data    write=%b ready=%b response=%b", writing, ready, error_response);
 63      if (ready) begin
 64        if (!writing && !error_response) reply <= read_data;
 65        bus <= FREE;
 66      end
 67    end
 68  end
 69  
 70  task automatic tick(input bit mode, serial_in);
 71    tms = mode; tdi = serial_in;
 72    #2; tck = 1; #2; tck = 0;
 73  endtask
 74  
 75  task automatic scan(input logic [2:0] op, input logic [31:0] value,
 76                      output logic [31:0] returned);
 77    logic [34:0] outgoing, incoming;
 78    outgoing = {value, op};
 79    tick(1,0); tick(0,0); tick(0,0);
 80    for (int i=0; i<35; i++) begin
 81      incoming[i] = tdo;
 82      tick(i == 34, outgoing[i]);
 83    end
 84    tick(1,0); tick(0,0);
 85    returned = incoming[34:3];
 86  endtask
Explore JTAG · lesson and source

Open the JTAG lesson.

Download soc-s81-tap.sv
Numbered source for soc-s81-tap.sv.
  1  // Small board model. DR and IR share the same capture/shift/pause sequencer.
  2  // Only IDCODE and BYPASS have data paths in this fixture.
  3  module board_tap #(parameter logic [31:0] ID = 32'h2a53_10c5) (
  4    input logic tck, tms, tdi, output logic tdo
  5  );
  6    typedef enum {RESET, IDLE, SELECT_DR, SELECT_IR, CAPTURE, SHIFT,
  7                  EXIT1, PAUSE_SCAN, EXIT2, UPDATE_SCAN} phase_t;
  8    phase_t phase = RESET;
  9    logic ir_branch = 0;
 10    logic [1:0] opcode = 1, ir_shift;
 11    logic [31:0] data_shift;
 12    always @(posedge tck) begin
 13      case (phase)
 14        RESET: if (!tms) phase <= IDLE;
 15        IDLE: if (tms) phase <= SELECT_DR;
 16        SELECT_DR: if (tms) phase <= SELECT_IR;
 17                   else begin phase <= CAPTURE; ir_branch <= 0; end
 18        SELECT_IR: if (tms) phase <= RESET;
 19                   else begin phase <= CAPTURE; ir_branch <= 1; end
 20        CAPTURE: begin
 21          if (ir_branch) ir_shift <= 2'b01;
 22          else data_shift <= (opcode == 1) ? ID : 0;
 23          if (tms) phase <= EXIT1; else phase <= SHIFT;
 24        end
 25        SHIFT: begin
 26          if (ir_branch) ir_shift <= {tdi, ir_shift[1]};
 27          else if (opcode == 1) data_shift <= {tdi, data_shift[31:1]};
 28          else data_shift[0] <= tdi;
 29          if (tms) phase <= EXIT1;
 30        end
 31        EXIT1: if (tms) phase <= UPDATE_SCAN; else phase <= PAUSE_SCAN;
 32        PAUSE_SCAN: if (tms) phase <= EXIT2;
 33        EXIT2: if (tms) phase <= UPDATE_SCAN; else phase <= SHIFT;
 34        UPDATE_SCAN: if (tms) phase <= SELECT_DR; else phase <= IDLE;
 35      endcase
 36    end
 37    always @(negedge tck) begin
 38      if (phase == RESET) opcode <= 1;
 39      if (phase == UPDATE_SCAN && ir_branch) opcode <= ir_shift;
 40      if (phase == SHIFT) tdo <= ir_branch ? ir_shift[0] : data_shift[0];
 41      else tdo <= 1'bz;
 42    end
 43  endmodule
Explore ap_crg · lesson and source

Open the ap_crg lesson.

Download ap_crg_boot.sv
Numbered source for ap_crg_boot.sv.
  1  // Startup slice of ap_crg. Each ready input is already qualified in the
  2  // always-on domain. Board supervision handles rail or lock loss after boot.
  3  module ap_crg_boot(
  4    input logic aon_clk, supply_good, osc_ready, pll_locked, boot_pin,
  5    input logic fabric_ready, rom_ready, shorten_wait,
  6    output logic osc_start, pll_start, straps_valid, boot_sel,
  7    output logic fabric_reset_n, core_reset_n
  8  );
  9    always_ff @(posedge aon_clk or negedge supply_good) begin
 10      if (!supply_good) begin
 11        {osc_start, pll_start, straps_valid, boot_sel} <= 0;
 12        {fabric_reset_n, core_reset_n} <= 0;
 13      end else begin
 14        osc_start <= 1;
 15        if (osc_start && osc_ready) pll_start <= 1;
 16        if (pll_start && pll_locked && !straps_valid) begin
 17          boot_sel <= boot_pin;
 18          straps_valid <= 1;
 19        end
 20        if (straps_valid) fabric_reset_n <= 1;
 21        if (fabric_reset_n && fabric_ready && (rom_ready || shorten_wait))
 22          core_reset_n <= 1;
 23      end
 24    end
 25  endmodule
Explore CLK · lesson and source

Open the CLK lesson.

Download clock_source_model.sv
Numbered source for clock_source_model.sv.
  1  // Simulation-only nominal sources. REF_PERIOD is in ns; no jitter or analog loop.
  2  // REF_START: how long the crystal oscillator takes to start, in ns (0: it runs from the first moment).
  3  `timescale 1ns/1ns
  4  module clock_source_model #(parameter REF_PERIOD = 20, LOCK_EDGES = 5, REF_START = 0)
  5    (output bit clk_ref, clk_rc, clk_pll, locked);
  6    bit ref_running;
  7    initial #(REF_START) ref_running <= 1;
  8    always #(REF_PERIOD/2) if (ref_running) clk_ref = ~clk_ref;
  9    always #20 clk_rc = ~clk_rc;
 10    initial begin
 11      @(posedge clk_ref);
 12      forever #(REF_PERIOD/4) clk_pll = ~clk_pll;
 13    end
 14    initial begin
 15      repeat (LOCK_EDGES) @(posedge clk_ref);
 16      locked <= 1;
 17    end
 18  endmodule
Explore RST · lesson and source

Open the RST lesson.

Download reset_sources.sv
Numbered source for reset_sources.sv.
  1  // ap_soc lesson slice. The four warm requests are in the always-on clock domain.
  2  // pin_sample is the pad level AFTER synchronization. POR starts a new log.
  3  module reset_sources (
  4    input logic clk, por, pin_sample, watchdog, software_req, debug_req,
  5    output logic core_reset, io_reset, debug_reset,
  6    output logic [4:0] cause
  7  );
  8    logic previous_pin;
  9    logic pin_qualified;
 10    assign io_reset = por || pin_qualified || watchdog || software_req;
 11    assign core_reset = io_reset || debug_req;
 12    assign debug_reset = por;
 13  
 14    always_ff @(posedge clk) begin
 15      if (por) begin
 16        previous_pin <= 0;
 17        pin_qualified <= 0;
 18        cause <= 5'b00001;
 19      end else begin
 20        previous_pin <= pin_sample;
 21        pin_qualified <= previous_pin && pin_sample;
 22        if (previous_pin && pin_sample) cause[1] <= 1;
 23        if (watchdog)      cause[2] <= 1;
 24        if (software_req)  cause[3] <= 1;
 25        if (debug_req)     cause[4] <= 1;
 26      end
 27    end
 28  endmodule
Explore Power control · lesson and source

Open the Power control lesson.

Download ap_power_slice.upf
Numbered source for ap_power_slice.upf.
  1  upf_version 4.0
  2  set_design_top ap_power_slice
  3  create_power_domain PD_AON -include_scope
  4  create_power_domain PD_PER -elements {u_timer}
  5  create_supply_port VA
  6  create_supply_port VP
  7  create_supply_port VG
  8  create_supply_net NA
  9  create_supply_net NP
 10  create_supply_net NG
 11  connect_supply_net NA -ports {VA}
 12  connect_supply_net NP -ports {VP}
 13  connect_supply_net NG -ports {VG}
 14  create_supply_set AON -function {power NA} -function {ground NG}
 15  create_supply_set PER -function {power NP} -function {ground NG}
 16  associate_supply_set AON -handle PD_AON.primary
 17  associate_supply_set PER -handle PD_PER.primary
 18  set_isolation QUIET -domain PD_PER -applies_to outputs -clamp_value 0 -isolation_signal isolate -isolation_supply AON -location parent
Explore ap_clint · lesson and source

Open the ap_clint lesson.

Download ap_clint_timer.sv
Numbered source for ap_clint_timer.sv.
  1  // Timer slice of ap_soc's local interrupt block. One hart, one timebase tick
  2  // per clk and a registered interrupt output. Word strobes arrive at commitment.
  3  module ap_clint_timer #(parameter logic [63:0] RESET_COMPARE = '1) (
  4    input logic clk, reset_n, write_cmp_low, write_cmp_high,
  5    input logic [31:0] wdata,
  6    output logic [63:0] mtime, mtimecmp,
  7    output logic mtip
  8  );
  9    always_ff @(posedge clk) begin
 10      if (!reset_n) begin
 11        mtime <= 0;
 12        mtimecmp <= RESET_COMPARE;
 13        mtip <= 0;
 14      end else begin
 15        mtime <= mtime + 1'b1;
 16        if (write_cmp_low) mtimecmp[31:0] <= wdata;
 17        if (write_cmp_high) mtimecmp[63:32] <= wdata;
 18        mtip <= mtime >= mtimecmp;
 19      end
 20    end
 21  endmodule
Explore ap_plic · lesson and source

Open the ap_plic lesson.

Download ap_plic.sv
Numbered source for ap_plic.sv.
  1  // One machine context, synchronous level sources. Register-side interface:
  2  // commit pulses once at a successful word transfer's data edge.
  3  module ap_plic #(parameter integer SOURCES = 16) (
  4    input logic clk, reset_n, commit, write_en,
  5    input logic [21:0] offset,
  6    input logic [31:0] wdata,
  7    input logic [SOURCES:1] level_irq,
  8    output logic [31:0] rdata,
  9    output logic notify_irq
 10  );
 11    localparam ENABLE = 'h2000, THRESHOLD = 'h200000, CLAIM = 'h200004;
 12    logic [2:0] weight [1:SOURCES];
 13    logic [2:0] threshold, best;
 14    logic [SOURCES:1] pending, busy, enabled;
 15    integer winner;
 16  
 17    always_comb begin
 18      best = 0;
 19      winner = 0;
 20      for (int id = 1; id <= SOURCES; id++) begin
 21        if (pending[id] && enabled[id] && weight[id] > best) begin
 22          best = weight[id];
 23          winner = id;
 24        end
 25      end
 26      notify_irq = best > threshold;
 27      rdata = 0;
 28      for (int id = 1; id <= SOURCES; id++) begin
 29        if (offset == 4*id) rdata = weight[id];
 30        if (offset == 'h1000 + 4*(id/32)) rdata[id%32] = pending[id];
 31        if (offset == ENABLE + 4*(id/32)) rdata[id%32] = enabled[id];
 32      end
 33      case (offset)
 34        THRESHOLD: rdata = threshold;
 35        CLAIM: rdata = winner;
 36      endcase
 37    end
 38  
 39    always_ff @(posedge clk) begin
 40      if (!reset_n) begin
 41        pending <= '0;
 42        busy <= '0;
 43        enabled <= '0;
 44        threshold <= 0;
 45        for (int id = 1; id <= SOURCES; id++) weight[id] <= 0;
 46      end else begin
 47        for (int id = 1; id <= SOURCES; id++) begin
 48          if (level_irq[id] && !busy[id]) begin
 49            pending[id] <= 1;
 50            busy[id] <= 1;
 51          end
 52          if (commit && write_en && offset == 4*id) weight[id] <= wdata[2:0];
 53          if (commit && write_en && offset == ENABLE + 4*(id/32))
 54            enabled[id] <= wdata[id%32];
 55          if (commit && offset == CLAIM) begin
 56            if (!write_en && winner == id) pending[id] <= 0;
 57            if (write_en && enabled[id] && wdata == id && busy[id] && !pending[id]) busy[id] <= 0;
 58          end
 59        end
 60        if (commit && write_en && offset == THRESHOLD) threshold <= wdata[2:0];
 61      end
 62    end
 63  endmodule
Explore GPIO · lesson and source

Open the GPIO lesson.

Download soc-s71-gpio.sv
Numbered source for soc-s71-gpio.sv.
  1  // Digital GPIO bank. The mux, pad driver and board live outside this block.
  2  module ap_gpio_bank (
  3    input logic pclk, presetn, psel, penable, pwrite,
  4    input logic [11:0] offset,
  5    input logic [31:0] pwdata,
  6    input logic [3:0] pstrb,
  7    input logic [15:0] pad_in,
  8    output logic [15:0] pad_out, pad_oe,
  9    output logic pready, pslverr, irq,
 10    output logic [31:0] prdata
 11  );
 12    localparam DIR=12'h000, IN_WORD=12'h004, OUT_WORD=12'h008,
 13               SET_BITS=12'h00c, CLR_BITS=12'h010, TGL_BITS=12'h014,
 14               IRQ_ENABLE=12'h018, LEVEL_MODE=12'h01c, ACTIVE_HIGH=12'h020,
 15               STATUS=12'h024, MASKED_STATUS=12'h028;
 16    logic [15:0] sample_meta, sample, previous, edge_latch;
 17    logic [15:0] irq_enable, level_mode, active_high;
 18    wire [15:0] lanes = {{8{pstrb[1]}}, {8{pstrb[0]}}};
 19    wire [15:0] selected = pwdata[15:0] & lanes;
 20    wire [15:0] active = ~(sample ^ active_high);
 21    wire [15:0] arrivals = (sample ^ previous) & active & ~level_mode;
 22    wire [15:0] status = (edge_latch & ~level_mode) | (level_mode & active);
 23    assign irq = |(status & irq_enable);
 24    assign pready = 1'b1;
 25    logic valid;
 26    always_comb begin
 27      valid = 1;
 28      prdata = '0;
 29      case (offset)
 30        DIR: prdata[15:0] = pad_oe;
 31        IN_WORD: begin prdata[15:0] = sample; valid = !pwrite; end
 32        OUT_WORD: prdata[15:0] = pad_out;
 33        IRQ_ENABLE: prdata[15:0] = irq_enable;
 34        LEVEL_MODE: prdata[15:0] = level_mode;
 35        ACTIVE_HIGH: prdata[15:0] = active_high;
 36        STATUS: prdata[15:0] = status;
 37        MASKED_STATUS: begin prdata[15:0] = status & irq_enable; valid = !pwrite; end
 38        SET_BITS, CLR_BITS, TGL_BITS: valid = pwrite;
 39        default: valid = 0;
 40      endcase
 41    end
 42    assign pslverr = psel && penable && !valid;
 43    wire wr = psel && penable && pready && pwrite && valid;
 44    wire [15:0] clear_edges = wr && offset == STATUS ? selected : '0;
 45  
 46    always_ff @(posedge pclk or negedge presetn) begin
 47      if (!presetn) begin
 48        sample_meta <= 0;
 49        sample <= 0;
 50        previous <= 0;
 51        edge_latch <= 0;
 52        irq_enable <= 0;
 53        level_mode <= 0;
 54        active_high <= '1;
 55        pad_out <= 0;
 56        pad_oe <= 0;
 57      end else begin
 58        sample_meta <= pad_in;
 59        sample <= sample_meta;
 60        previous <= sample;
 61        edge_latch <= (edge_latch & ~clear_edges & ~level_mode) | arrivals;
 62        if (wr) begin
 63          case (offset)
 64            DIR: pad_oe <= (pad_oe & ~lanes) | selected;
 65            OUT_WORD: pad_out <= (pad_out & ~lanes) | selected;
 66            SET_BITS: pad_out <= pad_out | selected;
 67            CLR_BITS: pad_out <= pad_out & ~selected;
 68            TGL_BITS: pad_out <= pad_out ^ selected;
 69            IRQ_ENABLE: irq_enable <= (irq_enable & ~lanes) | selected;
 70            LEVEL_MODE: level_mode <= (level_mode & ~lanes) | selected;
 71            ACTIVE_HIGH: active_high <= (active_high & ~lanes) | selected;
 72            default: ;
 73          endcase
 74        end
 75      end
 76    end
 77  endmodule
Explore Timer and PWM · lesson and source

Open the Timer and PWM lesson.

Download capture_pwm.sv
Numbered source for capture_pwm.sv.
  1  // Four-slot peripheral timer. The prescaler top is the last count before a step.
  2  // capture is a synchronous event strobe from the input front end.
  3  module capture_pwm (
  4    input logic clk, reset_n, psel, penable, pwrite, capture,
  5    input logic [11:0] offset,
  6    input logic [31:0] pwdata,
  7    output logic [31:0] prdata,
  8    output logic [1:0] phase,
  9    output logic pwm, match
 10  );
 11    localparam RUN = 0, DUTY = 4, CAPTURED = 8, DIV_TOP = 12, COMPARE = 16;
 12    logic running;
 13    logic [7:0] divider, prescale_top;
 14    logic [2:0] duty;
 15    logic [1:0] captured, compare_phase;
 16    wire write_word = psel && penable && pwrite;
 17  
 18    always_ff @(posedge clk) begin
 19      if (!reset_n) begin
 20        running <= 0;
 21        divider <= 0;
 22        prescale_top <= 0;
 23        phase <= 0;
 24        duty <= 0;
 25        compare_phase <= 0;
 26        captured <= 0;
 27      end else begin
 28        if (write_word && offset == RUN) running <= pwdata[0];
 29        if (write_word && offset == DUTY) duty <= pwdata[2:0];
 30        if (write_word && offset == COMPARE) compare_phase <= pwdata[1:0];
 31  
 32        if (write_word && offset == DIV_TOP) begin
 33          prescale_top <= pwdata[7:0];
 34          divider <= 0;
 35        end else if (running) begin
 36          if (divider == prescale_top) begin
 37            divider <= 0;
 38            phase <= phase + 1'b1;
 39          end else divider <= divider + 1'b1;
 40        end
 41        if (capture) captured <= phase;
 42      end
 43    end
 44    assign prdata = offset == CAPTURED ? {30'b0,captured} : 0;
 45    assign pwm = running && phase < duty;
 46    assign match = running && phase == compare_phase;
 47  endmodule
Explore Watchdog · lesson and source

Open the Watchdog lesson.

Download watchdog_supervisor.sv
Numbered source for watchdog_supervisor.sv.
  1  // ap_soc teaching policy. Input tick is an enable from the supervision clock.
  2  // A privileged boot writer may arm once. Reset request persists until reset.
  3  module watchdog_supervisor (
  4    input logic clk, reset_n, tick, debug_halt, dev_mode, privileged,
  5    input logic psel, penable, pwrite,
  6    input logic [11:0] offset,
  7    input logic [31:0] pwdata,
  8    output logic armed, irq, reset_req,
  9    output logic [3:0] remaining
 10  );
 11    localparam KEY = 0, CONTROL = 4, SERVICE = 8;
 12    localparam RELOAD = 6, OPEN = 3;
 13    logic first_key, unlocked;
 14    logic [1:0] grace;
 15    wire write_word = psel && penable && pwrite;
 16    wire arm = write_word && privileged && unlocked && offset == CONTROL && pwdata == 1;
 17    wire kick = write_word && offset == SERVICE && pwdata == 1;
 18  
 19    always_ff @(posedge clk) begin
 20      if (!reset_n) begin
 21        first_key <= 0;
 22        unlocked <= 0;
 23        armed <= 0;
 24        remaining <= 0;
 25        irq <= 0;
 26        reset_req <= 0;
 27        grace <= 0;
 28      end else begin
 29        if (write_word) begin
 30          first_key <= privileged && offset == KEY && pwdata == 'h51;
 31          unlocked <= privileged && first_key && offset == KEY && pwdata == 'ha2;
 32        end
 33        if (!armed && arm) begin
 34          armed <= 1;
 35          remaining <= RELOAD;
 36        end else if (armed && !reset_req && !(dev_mode && debug_halt)) begin
 37          if (irq) begin
 38            if (tick && grace == 1) reset_req <= 1;
 39            else if (tick) grace <= grace - 1'b1;
 40          end else if ((kick && remaining > OPEN) || (tick && remaining == 1 && !kick)) begin
 41            irq <= 1;
 42            grace <= 2;
 43            remaining <= 0;
 44          end else if (kick) remaining <= RELOAD;
 45          else if (tick) remaining <= remaining - 1'b1;
 46        end
 47      end
 48    end
 49  endmodule
Explore ap_sysctl · lesson and source

Open the ap_sysctl lesson.

Download ap_sysctl_reset_port.sv
Numbered source for ap_sysctl_reset_port.sv.
  1  // Reset-service words within the ap_soc laboratory system-control page.
  2  // All manager accesses to this port are aligned, full-word APB transfers.
  3  // The cause storage has a separate reset owner and enters through cause.
  4  module ap_sysctl_reset_port (
  5    input  logic        clk, bus_reset_n,
  6    input  logic        sel, enable, writing,
  7    input  logic [31:0] paddr, pwdata,
  8    input  logic [4:0]  cause,
  9    input  logic        service_slot,
 10    output logic        page_selected, access_error, armed,
 11    output logic [31:0] read_data
 12  );
 13    localparam logic [31:0] CAUSE = 32'h1000_4004, COMMAND = 32'h1000_4008;
 14    wire cause_read = !writing && paddr == CAUSE;
 15    wire command_write = writing && paddr == COMMAND;
 16  
 17    assign page_selected = sel && paddr[31:12] == CAUSE[31:12];
 18    assign read_data = cause_read ? {27'b0,cause} : 32'b0;
 19    assign access_error = page_selected && enable && !(cause_read || command_write);
 20  
 21    always_ff @(posedge clk or negedge bus_reset_n) begin
 22      if (!bus_reset_n)
 23        armed <= 0;
 24      else if (page_selected && enable && command_write)
 25        armed <= pwdata[0];
 26      else if (service_slot)
 27        armed <= 0;
 28    end
 29  endmodule
Explore DMA · lesson and source

Open the DMA lesson.

Download s6_io_slice.svh
Numbered source for s6_io_slice.svh.
  1  // Simulation fixture. A transfer task stands in for each manager.
  2  // P4 supplies the two-manager arbitration point and APB bridge.
  3  logic clk = 0, reset_n = 0;
  4  always #5 clk = ~clk;
  5  localparam logic [31:0] UART = 'h10000000, STATUS = UART+4, MASK = UART+8,
  6                          RX = UART+12, CFG = 'h10006000, RAM = 'h80000000;
  7  logic [31:0] addr[2], data[2];
  8  logic [1:0] trans[2];
  9  logic wr[2];
 10  logic [2:0] size[2];
 11  wire ready[2];
 12  wire [31:0] address, payload, paddr, pwdata, bridge_data;
 13  wire [1:0] transfer;
 14  wire [2:0] bus_size;
 15  wire write_en, bridge_ready, bridge_error, psel, penable, pwrite;
 16  
 17  ahb_2m matrix (
 18    .hclk(clk), .hresetn(reset_n),
 19    .htrans0(trans[0]), .htrans1(trans[1]), .haddr0(addr[0]), .haddr1(addr[1]),
 20    .hwrite0(wr[0]), .hwrite1(wr[1]), .hwdata0(data[0]), .hwdata1(data[1]),
 21    .hmastlock0(1'b0), .hmastlock1(1'b0), .hsize0(size[0]), .hsize1(size[1]),
 22    .hready0(ready[0]), .hready1(ready[1]), .s_htrans(transfer), .s_haddr(address),
 23    .s_hwdata(payload), .s_hwrite(write_en), .s_hmastlock(), .s_hsize(bus_size),
 24    .s_hready(bridge_ready)
 25  );
 26  logic [7:0] rom[0:3], ram[0:3];
 27  logic [31:0] saved_addr;
 28  logic saved_write, saved_active;
 29  wire [31:0] rom_word = {rom[3],rom[2],rom[1],rom[0]};
 30  wire [31:0] bus_read_data = saved_addr < 4 ? rom_word : bridge_data;
 31  wire peripheral = address[31:16] == 16'h1000;
 32  logic [31:0] src, dst, length;
 33  logic launch, mask;
 34  logic done = 0, fault = 0;
 35  int cooldown, gap = 12, rx_count, fault_at = -1;
 36  int cycle = 0, busy_cycles = 0;
 37  bit charge_cpu, log_moves, trace_access;
 38  logic [31:0] console_text;
 39  int tx_count, cpu_at_tx[4];
 40  wire room = cooldown == 0;
 41  wire irq = mask && room;
 42  wire rx_request = rx_count < 4;
 43  wire rx_fault = paddr == RX && rx_count == fault_at;
 44  wire [31:0] prdata = paddr == STATUS ? {31'b0,room} :
 45                       paddr == RX && rx_request ? {24'b0,rom[rx_count]} : 0;
 46  ahb_apb_bridge bridge (
 47    .hclk(clk), .hresetn(reset_n), .hsel(peripheral), .haddr(address),
 48    .htrans(transfer), .hwrite(write_en), .hprot(4'b0011), .hwdata(payload),
 49    .hwstrb(4'hf), .hready(bridge_ready), .hreadyout(bridge_ready),
 50    .hresp(bridge_error), .hrdata(bridge_data), .psel(psel), .penable(penable),
 51    .pwrite(pwrite), .paddr(paddr), .pwdata(pwdata), .pstrb(), .pprot(),
 52    .pready(1'b1), .prdata(prdata), .pslverr(rx_fault)
 53  );
 54  
 55  always @(posedge clk) begin
 56    cycle <= cycle + 1;
 57    if (trace_access && (transfer[1] || psel))
 58      $display("access e%0d active=%b setup=%b access=%b ready=%b",cycle,
 59               transfer[1],psel && !penable,psel && penable,bridge_ready);
 60    if (charge_cpu) busy_cycles <= busy_cycles + 1;
 61    if (bridge_ready) begin
 62      saved_active <= transfer[1];
 63      saved_addr <= address;
 64      saved_write <= write_en;
 65    end
 66    if (saved_active && saved_write && saved_addr >= RAM && saved_addr < RAM+4)
 67      ram[saved_addr-RAM] <= payload[8*saved_addr[1:0] +: 8];
 68    launch <= 0;
 69    if (!reset_n) begin
 70      cooldown <= 0;
 71      rx_count <= 0;
 72      console_text <= 0;
 73      tx_count <= 0;
 74      mask <= 0;
 75    end else begin
 76      if (!room) cooldown <= cooldown-1;
 77      if (psel && penable && !rx_fault) begin
 78        if (pwrite) case (paddr)
 79          UART: begin
 80            if (!room) $fatal(1,"TX register full");
 81            if (tx_count < 4) cpu_at_tx[tx_count] <= busy_cycles + int'(charge_cpu);
 82            tx_count <= tx_count + 1;
 83            console_text <= {console_text[23:0],pwdata[7:0]};
 84            cooldown <= gap;
 85          end
 86          MASK: mask <= pwdata[0];
 87          CFG: src <= pwdata;
 88          CFG+4: dst <= pwdata;
 89          CFG+8: length <= pwdata;
 90          CFG+12: launch <= pwdata[0];
 91        endcase
 92        else if (paddr == RX && rx_request) rx_count <= rx_count+1;
 93      end
 94    end
 95  end
 96  
 97  // All bus drives change away from the active edge. Count address arbitration,
 98  // address acceptance and every data-phase wait inside the CPU charge interval.
 99  task automatic access_bus(input int m, input bit writing, input logic [31:0] a, d,
100                            output logic [31:0] result, output bit failed);
101    @(negedge clk);
102    if (m == 0) charge_cpu = 1;
103    addr[m] = a;
104    wr[m] = writing;
105    size[m] = a[31:16] == 16'h1000 ? 2 : 0;
106    data[m] = d;
107    trans[m] = 2'b10;
108    do @(posedge clk); while (!ready[m]);
109    @(negedge clk);
110    trans[m] = 0;
111    do @(posedge clk); while (!bridge_ready);
112    failed = bridge_error;
113    result = a < 4 ? {24'b0,bus_read_data[8*a[1:0] +: 8]} : bus_read_data;
114    if (log_moves && m == 1)
115      $display("e%0d cpu_request=%b %s %08h byte=%02h error=%b",cycle,trans[0][1],
116               writing ? "write" : " read",a,writing ? d[8*a[1:0] +: 8] : result[7:0],failed);
117    #1;
118    if (m == 0) charge_cpu = 0;
119  endtask
120  
121  task automatic cpu_write(input logic [31:0] a, d);
122    logic [31:0] unused;
123    bit failed;
124    access_bus(0,1,a,d,unused,failed);
125    if (failed) $fatal(1,"control write failed");
126  endtask
127  
128  task automatic program_channel(input logic [31:0] from_addr,to_addr,count);
129    if (!(from_addr == RX || from_addr < 4) ||
130        !(to_addr == UART || (to_addr >= RAM && to_addr < RAM+4)))
131      $fatal(1,"Use the four-byte ROM or UART RX and the four-byte RAM or UART TX");
132    if (count > 4 || (from_addr == RX && count > 4-rx_count) ||
133        (from_addr < 4 && count > 4-from_addr) ||
134        (to_addr != UART && count > RAM+4-to_addr))
135      $fatal(1,"Job would exceed the fixture buffer");
136    cpu_write(CFG,from_addr);
137    cpu_write(CFG+4,to_addr);
138    cpu_write(CFG+8,count);
139    cpu_write(CFG+12,1);
140  endtask
141  
142  // Behavioral transfer agent, for the documented ROM/RX and RAM/TX routes.
143  // ROM reads below return a byte extracted from its addressed lane.
144  initial forever begin : channel
145    logic [31:0] a,b,value,unused,byte_count;
146    bit failed;
147    @(posedge launch);
148    done = 0;
149    fault = 0;
150    a = src;
151    b = dst;
152    byte_count = length;
153    for (int i=0; i<byte_count && !fault; i++) begin
154      if (a == RX) wait(rx_request);
155      if (b == UART) wait(room);
156      access_bus(1,0,a,0,value,failed);
157      if (!failed)
158        access_bus(1,1,b,{4{value[7:0]}},unused,failed);
159      fault = failed;
160      if (a != RX) a++;
161      if (b != UART) b++;
162    end
163    done = !fault;
164  end
165  
166  task automatic initialize;
167    for (int m=0; m<2; m++) begin
168      trans[m]=0; wr[m]=0; addr[m]=0; data[m]=0; size[m]=0;
169    end
170    {rom[0],rom[1],rom[2],rom[3]} = "send";
171    for (int i=0; i<4; i++) ram[i]=0;
172    repeat (2) @(negedge clk);
173    reset_n=1;
174  endtask
Explore UART0 · lesson and source

Open the UART0 lesson.

Download soc-s73-serial.sv
Numbered source for soc-s73-serial.sv.
  1  // APB teaching slice. Aligned word transfers, no waits, one system clock.
  2  // UART receives frame-complete bytes from the P6 receiver. SPI uses mode 0.
  3  module serial_slice(
  4    input wire clk, reset_n, sel, enable, wr,
  5    input wire [31:0] addr, wdata,
  6    output logic [31:0] rdata,
  7    input wire rx_done, input wire [7:0] rx_data,
  8    output wire tx, irq, dma_req, cs_n, mosi,
  9    output logic sclk, input wire miso
 10  );
 11    // UART0: transmit data 0x00 (write), status 0x04 (read), receive data 0x0C (read).
 12    // Status bits: 0 = room to transmit, 1 = a received byte waits, 2 = the receive queue is full.
 13    localparam UART_TXDATA = 32'h10000000, UART_STATUS = 32'h10000004, UART_RXDATA = 32'h1000000c,
 14               SPI_DATA = 32'h10005000, SPI_STATUS = 32'h10005004;
 15    wire access = sel && enable;
 16    logic [7:0] fifo [0:1];
 17    logic head, tail;
 18    logic [1:0] used;
 19    wire pop = access && !wr && addr == UART_RXDATA && used != 0;
 20    wire push = rx_done && (used < 2 || pop);
 21    assign irq = used != 0;
 22    assign dma_req = used == 2;
 23    logic [9:0] frame;
 24    logic [3:0] bits_left, tick;
 25    assign tx = frame[0];
 26  
 27    logic [31:0] shift;
 28    logic [23:0] flash_id;
 29    logic [5:0] clocks_left;
 30    logic half_tick;
 31    assign cs_n = clocks_left == 0;
 32    assign mosi = shift[31];
 33    always_comb begin
 34      case (addr)
 35        UART_RXDATA: rdata = irq ? fifo[head] : 0;
 36        UART_STATUS: rdata = {29'b0, dma_req, irq, bits_left == 0};
 37        SPI_DATA:    rdata = {8'b0, flash_id};
 38        SPI_STATUS:  rdata = {31'b0, !cs_n};
 39        default:     rdata = 0;
 40      endcase
 41    end
 42    always_ff @(posedge clk) begin
 43      if (!reset_n) begin
 44        used <= 0;
 45        head <= 0;
 46        tail <= 0;
 47        frame <= '1;
 48        bits_left <= 0;
 49        tick <= 0;
 50        clocks_left <= 0;
 51        half_tick <= 0;
 52        sclk <= 0;
 53        shift <= 0;
 54        flash_id <= 0;
 55      end else begin
 56        if (push) begin
 57          fifo[tail] <= rx_data;
 58          tail <= !tail;
 59        end
 60        if (pop) head <= !head;
 61        case ({push,pop})
 62          2'b10: used <= used + 1'b1;
 63          2'b01: used <= used - 1'b1;
 64          default: ;
 65        endcase
 66  
 67        if (bits_left != 0) begin
 68          tick <= tick + 1'b1;
 69          if (tick == 15) begin
 70            frame <= {1'b1, frame[9:1]};
 71            bits_left <= bits_left - 1'b1;
 72          end
 73        end else if (access && wr && addr == UART_TXDATA) begin
 74          frame <= {1'b1, wdata[7:0], 1'b0};
 75          bits_left <= 10;
 76          tick <= 0;
 77        end
 78  
 79        if (cs_n) begin
 80          if (access && wr && addr == SPI_DATA) begin
 81            shift <= {wdata[7:0], 24'b0};
 82            clocks_left <= 32;
 83            half_tick <= 0;
 84          end
 85        end else begin
 86          half_tick <= !half_tick;
 87          if (half_tick) begin
 88            sclk <= !sclk;
 89            if (!sclk) flash_id <= {flash_id[22:0], miso};
 90            else begin
 91              shift <= shift << 1;
 92              clocks_left <= clocks_left - 1'b1;
 93            end
 94          end
 95        end
 96      end
 97    end
 98  endmodule
Explore SPI · lesson and source

Open the SPI lesson.

Download soc-s73-serial.sv
Numbered source for soc-s73-serial.sv.
  1  // APB teaching slice. Aligned word transfers, no waits, one system clock.
  2  // UART receives frame-complete bytes from the P6 receiver. SPI uses mode 0.
  3  module serial_slice(
  4    input wire clk, reset_n, sel, enable, wr,
  5    input wire [31:0] addr, wdata,
  6    output logic [31:0] rdata,
  7    input wire rx_done, input wire [7:0] rx_data,
  8    output wire tx, irq, dma_req, cs_n, mosi,
  9    output logic sclk, input wire miso
 10  );
 11    // UART0: transmit data 0x00 (write), status 0x04 (read), receive data 0x0C (read).
 12    // Status bits: 0 = room to transmit, 1 = a received byte waits, 2 = the receive queue is full.
 13    localparam UART_TXDATA = 32'h10000000, UART_STATUS = 32'h10000004, UART_RXDATA = 32'h1000000c,
 14               SPI_DATA = 32'h10005000, SPI_STATUS = 32'h10005004;
 15    wire access = sel && enable;
 16    logic [7:0] fifo [0:1];
 17    logic head, tail;
 18    logic [1:0] used;
 19    wire pop = access && !wr && addr == UART_RXDATA && used != 0;
 20    wire push = rx_done && (used < 2 || pop);
 21    assign irq = used != 0;
 22    assign dma_req = used == 2;
 23    logic [9:0] frame;
 24    logic [3:0] bits_left, tick;
 25    assign tx = frame[0];
 26  
 27    logic [31:0] shift;
 28    logic [23:0] flash_id;
 29    logic [5:0] clocks_left;
 30    logic half_tick;
 31    assign cs_n = clocks_left == 0;
 32    assign mosi = shift[31];
 33    always_comb begin
 34      case (addr)
 35        UART_RXDATA: rdata = irq ? fifo[head] : 0;
 36        UART_STATUS: rdata = {29'b0, dma_req, irq, bits_left == 0};
 37        SPI_DATA:    rdata = {8'b0, flash_id};
 38        SPI_STATUS:  rdata = {31'b0, !cs_n};
 39        default:     rdata = 0;
 40      endcase
 41    end
 42    always_ff @(posedge clk) begin
 43      if (!reset_n) begin
 44        used <= 0;
 45        head <= 0;
 46        tail <= 0;
 47        frame <= '1;
 48        bits_left <= 0;
 49        tick <= 0;
 50        clocks_left <= 0;
 51        half_tick <= 0;
 52        sclk <= 0;
 53        shift <= 0;
 54        flash_id <= 0;
 55      end else begin
 56        if (push) begin
 57          fifo[tail] <= rx_data;
 58          tail <= !tail;
 59        end
 60        if (pop) head <= !head;
 61        case ({push,pop})
 62          2'b10: used <= used + 1'b1;
 63          2'b01: used <= used - 1'b1;
 64          default: ;
 65        endcase
 66  
 67        if (bits_left != 0) begin
 68          tick <= tick + 1'b1;
 69          if (tick == 15) begin
 70            frame <= {1'b1, frame[9:1]};
 71            bits_left <= bits_left - 1'b1;
 72          end
 73        end else if (access && wr && addr == UART_TXDATA) begin
 74          frame <= {1'b1, wdata[7:0], 1'b0};
 75          bits_left <= 10;
 76          tick <= 0;
 77        end
 78  
 79        if (cs_n) begin
 80          if (access && wr && addr == SPI_DATA) begin
 81            shift <= {wdata[7:0], 24'b0};
 82            clocks_left <= 32;
 83            half_tick <= 0;
 84          end
 85        end else begin
 86          half_tick <= !half_tick;
 87          if (half_tick) begin
 88            sclk <= !sclk;
 89            if (!sclk) flash_id <= {flash_id[22:0], miso};
 90            else begin
 91              shift <= shift << 1;
 92              clocks_left <= clocks_left - 1'b1;
 93            end
 94          end
 95        end
 96      end
 97    end
 98  endmodule
Explore UART TX · lesson and source

Open the UART TX lesson.

Download soc-s73-serial.sv
Numbered source for soc-s73-serial.sv.
  1  // APB teaching slice. Aligned word transfers, no waits, one system clock.
  2  // UART receives frame-complete bytes from the P6 receiver. SPI uses mode 0.
  3  module serial_slice(
  4    input wire clk, reset_n, sel, enable, wr,
  5    input wire [31:0] addr, wdata,
  6    output logic [31:0] rdata,
  7    input wire rx_done, input wire [7:0] rx_data,
  8    output wire tx, irq, dma_req, cs_n, mosi,
  9    output logic sclk, input wire miso
 10  );
 11    // UART0: transmit data 0x00 (write), status 0x04 (read), receive data 0x0C (read).
 12    // Status bits: 0 = room to transmit, 1 = a received byte waits, 2 = the receive queue is full.
 13    localparam UART_TXDATA = 32'h10000000, UART_STATUS = 32'h10000004, UART_RXDATA = 32'h1000000c,
 14               SPI_DATA = 32'h10005000, SPI_STATUS = 32'h10005004;
 15    wire access = sel && enable;
 16    logic [7:0] fifo [0:1];
 17    logic head, tail;
 18    logic [1:0] used;
 19    wire pop = access && !wr && addr == UART_RXDATA && used != 0;
 20    wire push = rx_done && (used < 2 || pop);
 21    assign irq = used != 0;
 22    assign dma_req = used == 2;
 23    logic [9:0] frame;
 24    logic [3:0] bits_left, tick;
 25    assign tx = frame[0];
 26  
 27    logic [31:0] shift;
 28    logic [23:0] flash_id;
 29    logic [5:0] clocks_left;
 30    logic half_tick;
 31    assign cs_n = clocks_left == 0;
 32    assign mosi = shift[31];
 33    always_comb begin
 34      case (addr)
 35        UART_RXDATA: rdata = irq ? fifo[head] : 0;
 36        UART_STATUS: rdata = {29'b0, dma_req, irq, bits_left == 0};
 37        SPI_DATA:    rdata = {8'b0, flash_id};
 38        SPI_STATUS:  rdata = {31'b0, !cs_n};
 39        default:     rdata = 0;
 40      endcase
 41    end
 42    always_ff @(posedge clk) begin
 43      if (!reset_n) begin
 44        used <= 0;
 45        head <= 0;
 46        tail <= 0;
 47        frame <= '1;
 48        bits_left <= 0;
 49        tick <= 0;
 50        clocks_left <= 0;
 51        half_tick <= 0;
 52        sclk <= 0;
 53        shift <= 0;
 54        flash_id <= 0;
 55      end else begin
 56        if (push) begin
 57          fifo[tail] <= rx_data;
 58          tail <= !tail;
 59        end
 60        if (pop) head <= !head;
 61        case ({push,pop})
 62          2'b10: used <= used + 1'b1;
 63          2'b01: used <= used - 1'b1;
 64          default: ;
 65        endcase
 66  
 67        if (bits_left != 0) begin
 68          tick <= tick + 1'b1;
 69          if (tick == 15) begin
 70            frame <= {1'b1, frame[9:1]};
 71            bits_left <= bits_left - 1'b1;
 72          end
 73        end else if (access && wr && addr == UART_TXDATA) begin
 74          frame <= {1'b1, wdata[7:0], 1'b0};
 75          bits_left <= 10;
 76          tick <= 0;
 77        end
 78  
 79        if (cs_n) begin
 80          if (access && wr && addr == SPI_DATA) begin
 81            shift <= {wdata[7:0], 24'b0};
 82            clocks_left <= 32;
 83            half_tick <= 0;
 84          end
 85        end else begin
 86          half_tick <= !half_tick;
 87          if (half_tick) begin
 88            sclk <= !sclk;
 89            if (!sclk) flash_id <= {flash_id[22:0], miso};
 90            else begin
 91              shift <= shift << 1;
 92              clocks_left <= clocks_left - 1'b1;
 93            end
 94          end
 95        end
 96      end
 97    end
 98  endmodule
Explore UART RX · lesson and source

Open the UART RX lesson.

Download soc-s73-serial.sv
Numbered source for soc-s73-serial.sv.
  1  // APB teaching slice. Aligned word transfers, no waits, one system clock.
  2  // UART receives frame-complete bytes from the P6 receiver. SPI uses mode 0.
  3  module serial_slice(
  4    input wire clk, reset_n, sel, enable, wr,
  5    input wire [31:0] addr, wdata,
  6    output logic [31:0] rdata,
  7    input wire rx_done, input wire [7:0] rx_data,
  8    output wire tx, irq, dma_req, cs_n, mosi,
  9    output logic sclk, input wire miso
 10  );
 11    // UART0: transmit data 0x00 (write), status 0x04 (read), receive data 0x0C (read).
 12    // Status bits: 0 = room to transmit, 1 = a received byte waits, 2 = the receive queue is full.
 13    localparam UART_TXDATA = 32'h10000000, UART_STATUS = 32'h10000004, UART_RXDATA = 32'h1000000c,
 14               SPI_DATA = 32'h10005000, SPI_STATUS = 32'h10005004;
 15    wire access = sel && enable;
 16    logic [7:0] fifo [0:1];
 17    logic head, tail;
 18    logic [1:0] used;
 19    wire pop = access && !wr && addr == UART_RXDATA && used != 0;
 20    wire push = rx_done && (used < 2 || pop);
 21    assign irq = used != 0;
 22    assign dma_req = used == 2;
 23    logic [9:0] frame;
 24    logic [3:0] bits_left, tick;
 25    assign tx = frame[0];
 26  
 27    logic [31:0] shift;
 28    logic [23:0] flash_id;
 29    logic [5:0] clocks_left;
 30    logic half_tick;
 31    assign cs_n = clocks_left == 0;
 32    assign mosi = shift[31];
 33    always_comb begin
 34      case (addr)
 35        UART_RXDATA: rdata = irq ? fifo[head] : 0;
 36        UART_STATUS: rdata = {29'b0, dma_req, irq, bits_left == 0};
 37        SPI_DATA:    rdata = {8'b0, flash_id};
 38        SPI_STATUS:  rdata = {31'b0, !cs_n};
 39        default:     rdata = 0;
 40      endcase
 41    end
 42    always_ff @(posedge clk) begin
 43      if (!reset_n) begin
 44        used <= 0;
 45        head <= 0;
 46        tail <= 0;
 47        frame <= '1;
 48        bits_left <= 0;
 49        tick <= 0;
 50        clocks_left <= 0;
 51        half_tick <= 0;
 52        sclk <= 0;
 53        shift <= 0;
 54        flash_id <= 0;
 55      end else begin
 56        if (push) begin
 57          fifo[tail] <= rx_data;
 58          tail <= !tail;
 59        end
 60        if (pop) head <= !head;
 61        case ({push,pop})
 62          2'b10: used <= used + 1'b1;
 63          2'b01: used <= used - 1'b1;
 64          default: ;
 65        endcase
 66  
 67        if (bits_left != 0) begin
 68          tick <= tick + 1'b1;
 69          if (tick == 15) begin
 70            frame <= {1'b1, frame[9:1]};
 71            bits_left <= bits_left - 1'b1;
 72          end
 73        end else if (access && wr && addr == UART_TXDATA) begin
 74          frame <= {1'b1, wdata[7:0], 1'b0};
 75          bits_left <= 10;
 76          tick <= 0;
 77        end
 78  
 79        if (cs_n) begin
 80          if (access && wr && addr == SPI_DATA) begin
 81            shift <= {wdata[7:0], 24'b0};
 82            clocks_left <= 32;
 83            half_tick <= 0;
 84          end
 85        end else begin
 86          half_tick <= !half_tick;
 87          if (half_tick) begin
 88            sclk <= !sclk;
 89            if (!sclk) flash_id <= {flash_id[22:0], miso};
 90            else begin
 91              shift <= shift << 1;
 92              clocks_left <= clocks_left - 1'b1;
 93            end
 94          end
 95        end
 96      end
 97    end
 98  endmodule
Explore GPIO pins · lesson and source

Open the GPIO pins lesson.

Download soc-s73-pads.sv
Numbered source for soc-s73-pads.sv.
  1  // Each 12-bit row holds four three-bit endpoint numbers, indexed by function select.
  2  // The board table is an elaboration parameter. An empty table releases every pad.
  3  module pad_slice #(parameter logic [47:0] ROUTES = 0) (input wire clk,reset_n,psel,penable,pwrite,sample,
  4    input wire [31:0] paddr,pwdata, output wire [31:0] prdata,
  5    input wire [3:0] gpio_data,gpio_oe, input wire uart_tx,pwm,spi_clk,
  6    inout wire [3:0] pad, output logic strap, output wire uart_rx,spi_in,
  7    output wire [3:0] capture,oe);
  8    localparam MUX = 32'h10004010;
  9    logic [7:0] sel;
 10    wire [3:0] rx_lines, spi_lines;
 11    assign prdata = paddr == MUX ? {24'b0,sel} : 0;
 12    always_ff @(posedge clk) begin
 13      if (!reset_n) begin
 14        sel <= 0;
 15        strap <= 0;
 16      end else begin
 17        if (sample) strap <= pad[0];
 18        if (psel && penable && pwrite && paddr == MUX) sel <= pwdata[7:0];
 19      end
 20    end
 21    localparam GPIO=1, UART_TX=2, UART_RX=3, SCLK=4, MISO=5, PWM=6, CAPTURE=7;
 22    for (genvar p=0; p<4; p++) begin : drivers
 23      localparam logic [11:0] ROW = ROUTES[12*p +: 12];
 24      wire [1:0] field = sel[2*p +: 2];
 25      wire [2:0] endpoint = ROW[3*field +: 3];
 26      logic data, drive;
 27      always_comb begin
 28        case (endpoint)
 29          GPIO:    {drive,data} = {gpio_oe[p],gpio_data[p]};
 30          UART_TX: {drive,data} = {1'b1,uart_tx};
 31          SCLK:    {drive,data} = {1'b1,spi_clk};
 32          PWM:     {drive,data} = {1'b1,pwm};
 33          default: {drive,data} = 2'b00;
 34        endcase
 35      end
 36      assign oe[p] = drive;
 37      assign pad[p] = drive ? data : 1'bz;
 38      assign rx_lines[p] = endpoint == UART_RX ? pad[p] : 1'b1;
 39      assign spi_lines[p] = endpoint == MISO ? pad[p] : 1'b0;
 40      assign capture[p] = endpoint == CAPTURE ? pad[p] : 1'b0;
 41    end
 42    // This table assigns at most one source each to UART RX and SPI input.
 43    assign uart_rx = &rx_lines;
 44    assign spi_in = |spi_lines;
 45  endmodule
Explore Pin mux · lesson and source

Open the Pin mux lesson.

Download soc-s73-pads.sv
Numbered source for soc-s73-pads.sv.
  1  // Each 12-bit row holds four three-bit endpoint numbers, indexed by function select.
  2  // The board table is an elaboration parameter. An empty table releases every pad.
  3  module pad_slice #(parameter logic [47:0] ROUTES = 0) (input wire clk,reset_n,psel,penable,pwrite,sample,
  4    input wire [31:0] paddr,pwdata, output wire [31:0] prdata,
  5    input wire [3:0] gpio_data,gpio_oe, input wire uart_tx,pwm,spi_clk,
  6    inout wire [3:0] pad, output logic strap, output wire uart_rx,spi_in,
  7    output wire [3:0] capture,oe);
  8    localparam MUX = 32'h10004010;
  9    logic [7:0] sel;
 10    wire [3:0] rx_lines, spi_lines;
 11    assign prdata = paddr == MUX ? {24'b0,sel} : 0;
 12    always_ff @(posedge clk) begin
 13      if (!reset_n) begin
 14        sel <= 0;
 15        strap <= 0;
 16      end else begin
 17        if (sample) strap <= pad[0];
 18        if (psel && penable && pwrite && paddr == MUX) sel <= pwdata[7:0];
 19      end
 20    end
 21    localparam GPIO=1, UART_TX=2, UART_RX=3, SCLK=4, MISO=5, PWM=6, CAPTURE=7;
 22    for (genvar p=0; p<4; p++) begin : drivers
 23      localparam logic [11:0] ROW = ROUTES[12*p +: 12];
 24      wire [1:0] field = sel[2*p +: 2];
 25      wire [2:0] endpoint = ROW[3*field +: 3];
 26      logic data, drive;
 27      always_comb begin
 28        case (endpoint)
 29          GPIO:    {drive,data} = {gpio_oe[p],gpio_data[p]};
 30          UART_TX: {drive,data} = {1'b1,uart_tx};
 31          SCLK:    {drive,data} = {1'b1,spi_clk};
 32          PWM:     {drive,data} = {1'b1,pwm};
 33          default: {drive,data} = 2'b00;
 34        endcase
 35      end
 36      assign oe[p] = drive;
 37      assign pad[p] = drive ? data : 1'bz;
 38      assign rx_lines[p] = endpoint == UART_RX ? pad[p] : 1'b1;
 39      assign spi_lines[p] = endpoint == MISO ? pad[p] : 1'b0;
 40      assign capture[p] = endpoint == CAPTURE ? pad[p] : 1'b0;
 41    end
 42    // This table assigns at most one source each to UART RX and SPI input.
 43    assign uart_rx = &rx_lines;
 44    assign spi_in = |spi_lines;
 45  endmodule
Find a File by Its Function
Implementation Files
FileTable
full_decode.svGenerated address selections
clock_source_model.svClocks
ap_crg_timing.vClocks
reset_sources.svReset Reach
ap_irq_map.svhInterrupt Routes
ap_plic.svInterrupt Routes
ap_clint_timer.svInterrupt Routes
ap_rv32.svInterrupt Routes
ap_crg_boot.svPins and Board Functions
soc-s81-tap.svPins and Board Functions
soc-s73-pads.svPins and Board Functions
soc-s71-gpio.svPins and Board Functions
s6_io_slice.svhRegister Index
capture_pwm.svRegister Index
timer_irq_slice.svRegister Index
event_word.svRegister Index
watchdog_supervisor.svRegister Index
ap_sysctl_reset_port.svRegister Index
soc-s73-serial.svRegister Index
soc-s91-msip.svRegister Index
machine_time.svRegister Index
ap_rom.svConfiguration Before the First Instruction
ap_sram.svConfiguration Before the First Instruction
boot_rom_port.svConfiguration Before the First Instruction

The Smallest Example, Worked by Hand

Consider a write to 0x1000600c. The fast decoder selects the peripheral window. Page six selects DMA.

Subtract 0x10006000. The remaining twelve bytes select START. A one in bit zero launches the programmed transfer.

Now follow the payload. DMA becomes a manager and addresses SRAM directly. The payload never needs the DMA register page.

Two Addresses for Two Different JobsTrace programming and payload separately.
  • Processor
  • Peripheral
  • Bus
  • Memory
Two Addresses for Two Different JobsTrace programming and payload separately. component Core issues the command component DMA registers describe the copy component DMA manager requests memory component SRAM stores each byte ProgramLaunchWrite
  1. component Coreissues the command
    • Program → DMA registers
  2. component DMA registersdescribe the copy
    • Launch → DMA manager
  3. component DMA managerrequests memory
    • Write → SRAM
  4. component SRAMstores each byte
  1. Program

    A store sets the start bit.

  2. Launch

    The mover accepts the descriptor.

  3. Write

    Read back the programmed destination.

Read the diagram as text
  • Core: issues the command
  • DMA registers: describe the copy
  • DMA manager: requests memory
  • SRAM: stores each byte
  • Core → DMA registers: Program
  • DMA registers → DMA manager: Launch
  • DMA manager → SRAM: Write

Trace programming and payload separately.

The Rules

  1. Rule 1: Read bounds inclusively.

    Last byte equals base plus size minus one.

  2. Rule 2: Look up register direction.

    A read and write at the same address may perform different jobs.

  3. Rule 3: Identify the domain.

    Find which clock moves the receiver and which reset clears its state.

Read the Address and Register Tables

The decoder generates one selection for each implemented region. Its final reduction detects every address without an owner.

Address Ownership
DestinationBusFirst to last byte (hex)Generated full_decode.sv line
Boot ROMAHB00000000 – 00000fff3
ap_clintAHB02000000 – 0200ffff5
ap_plicAHB0c000000 – 0c3fffff7
UART0APB10000000 – 10000fff9
GPIOAPB10001000 – 10001fff11
Timer and PWMAPB10002000 – 10002fff13
WatchdogAPB10003000 – 10003fff15
ap_sysctlAPB10004000 – 10004fff17
SPIAPB10005000 – 10005fff19
DMAAPB10006000 – 10006fff21
Reserved APB expansionAPB10008000 – 1000ffff24
SRAMAHB80000000 – 8000ffff23
Reserved SRAM expansionAHB80010000 – 8001ffff24
UnassignedAPB10007000 – 10007fff24

A selected page still contains holes. Check the device offset and access direction before calling an operation valid.

Open the Register Index
Register Index
BlockByte offsets in hex, in name orderSource lines
UART000 transmit, 04 status, 08 transmit IRQ enable, 0c receive and pops6_io_slice.svh 5–6, 40–45, 79–92
GPIO data00 direction, 04 input, 08 output, 0c set, 10 clear, 14 togglesoc-s71-gpio.sv 12–13, 64–68
GPIO events18 enable, 1c level mode, 20 polarity, 24 status/clear, 28 masked statussoc-s71-gpio.sv 14–15, 33–37, 69–71
Timer / PWM00 run, 04 duty, 08 captured, 0c divider, 10 comparecapture_pwm.sv 11, 28–44
Timer events14 clear, 18 enable, 20 event fields, 24/28 count halvestimer_irq_slice.sv 11, 31–32; event_word.sv 12–20
Watchdog00 key, 04 control, 08 servicewatchdog_supervisor.sv 11–17
System control04 reset cause, 08 local restart, 10 pin selectionap_sysctl_reset_port.sv 13–26; soc-s73-pads.sv 8–18
SPI00 command/reply, 04 busysoc-s73-serial.sv 14, 37–38, 80–83
DMA00 source, 04 destination, 08 byte count, 0c starts6_io_slice.svh 87–90
Local interrupts0000 software request (hart zero); 4000/4004 compare; bff8/bffc timesoc-s91-msip.sv 3–18; machine_time.sv 25–33
External controller4 × ID priority; 1000 pending; 2000 enable; 200000 threshold; 200004 claim/completeap_plic.sv 11–12, 29–35, 52–60

The receive request belongs to the receive-ready model. The transmit interrupt enable belongs to the transmit-room slice.

The system-control map describes additional functions. Only the listed offsets have corresponding register slices here.

Read Time, Reset and Events

Clocks
Source or leafRate or relationshipSource lines
RC25 MHz at resetclock_source_model.sv 9
Crystal50 MHz referenceclock_source_model.sv 4–8
PLL100 MHz after selection; lock on reference edge fiveclock_source_model.sv 10–16
Core / peripheral10 ns / 20 ns in the timing exerciseap_crg_timing.v 13–17 (divide by two)
RTCSeparate oscillator; 14 ns in the crossing exerciseap_crg_timing.v 4–11 (independent input)
Reset Reach
Cause bitWho restartsSource lines
0 · supply startCore, bus, I/O and debug; starts a fresh cause recordreset_sources.sv 10–18
1 · pinCore, bus and I/O after two high samplesreset_sources.sv 10–11, 20–22
2 · watchdog / 3 · softwareCore, bus and I/O; earlier causes stay recordedreset_sources.sv 10–12, 23–24
4 · debug requestOnly the corereset_sources.sv 11–12, 25
Interrupt Routes
OriginRoute or numberSource lines
UART0 / GPIO / timerExternal sources 1 / 2 / 3ap_irq_map.svh 4
SPI / DMA / watchdog warningExternal sources 4 / 5 / 6; SPI has an assignment onlyap_irq_map.svh 4
Spare inputs7 through 16; claim zero means no winnerap_plic.sv 3, 18–21, 35
Machine timer / softwareDirect to core; timer compares two 64-bit wordsap_clint_timer.sv 18; ap_rv32.sv 32–34

A reset cause records history. A reset wire tells you what is being held now. Reading one cannot substitute for probing the other.

Two timers live on this diagram. The core-local comparator signals the processor directly. A peripheral match goes through source three.

Read the Package and Build Choices

Pins and Board Functions
InterfaceOwner and directionSource lines
Clock and resetBoard inputs; reset release waits for local readinessap_crg_boot.sv 3–7, 14–22
JTAGClock, mode and serial data in; serial data outsoc-s81-tap.sv 3–5, 37–41
UART TX / RXTransmit drives out; receive samples insoc-s73-pads.sv 28–39
GPIO16 logical bits; direction selects which outputs drivesoc-s71-gpio.sv 3–15, 64–68
Multifunction padsFour in the pad slice; each selects release, GPIO, serial or auxiliarysoc-s73-pads.sv 18–42
Boot strapBoard holds a level until the sequencer samples onceap_crg_boot.sv 16–19
Configuration Before the First Instruction
SettingDefault and consequenceSource lines
ROM / SRAM WORDS1024 / 16384 words of four bytes eachap_rom.sv 3–9; ap_sram.sv 4–11
SOURCES16 external inputs; the enable and pending masks use source numbersap_plic.sv 3–12
REF_PERIOD / REF_START / LOCK_EDGES20 ns / 0 ns / 5 edgesclock_source_model.sv 4–16
START_EDGESFour ROM edges after release before readyboot_rom_port.sv 3–13
ROUTES48 board-specific bits; zero releases every multiplexed padsoc-s73-pads.sv 3, 21–25
Reset vector / hart IDInputs chosen by integration; this image starts hart zero at address zeroap_rv32.sv 6–12

The release has one hart and no cache. HARTS is one. The two-hart exercise uses two software-interrupt words.

The S9 build choices EXCLUSIVE, FIREWALL, BOOT_CHECK, LIFE_CYCLE and CRC_ENGINE are all zero for v1.0.

These are architecture choices. The individual slices expose their own parameters. No single top-level module implements all six switches.

Power intent keeps the controller on its own supply. Isolation clamps a switched timer output low when its supply is unavailable.

A board can expose fewer physical pads than the GPIO register width. Trace a selector through its route table before assigning a pin.

Changing a memory depth changes the storage instance. Update the decoder and linker boundaries together before releasing that configuration.

Now Run It

The release image boots, receives a byte by interrupt, copies a word and sends the byte back after wake.

The board shifts the debug identification register, then writes and reads a scratch word through the debug manager. The smoke branch runs PWM through a selected pad and reads a serial reply.

It reads machine time and arms the watchdog. A high SPI input makes each of the 24 reply bits one.

Final observations from the release run.
address 80000010 write=0 ready=1
data    write=0 ready=0 response=0
data    write=0 ready=1 response=0
debug scratch=0000004b transfers=2
smoke SPI=ffffff PWM_pad_edges=38 mtime_read=201 watchdog_armed=1
decoded windows=7ff
copy=0000004b console=K interrupts=1 exceptions=0
checker: 1 writes, 0 reads, 0 wait edges, 0 rules broken, 0 notes

The S6 kit models instruction execution, ROM, SRAM, completed bus accesses, UART bytes, GPIO and the DMA mover. The generated decoder checks all eleven mapped selections.

Boot release, clock gating, the interrupt controller, machine timer, watchdog, SPI, pad selection and PWM run their teaching RTL.

The board drives supply and lock indications. The debug fixture owns a separate scratch SRAM. The final transmit store also runs through the S4 RTL bridge. Supply ramp time is a board input.

Why It Is Built This Way

For an architecture interview, pick one observed byte. Explain who issued the address, who accepted the transfer and who drove the pad.

Use the interview bank to practice the same walk without the diagram.

Each register table describes a boundary two teams can test independently. Firmware can prepare a descriptor before the mover owns the bus.

A pin measurement adds evidence downstream of a register write. The smoke run counts actual edges on the selected PWM pad.

The Trap: One Passing Byte

A greeting exercises a small part of the map. Even a wrong selector can pass if two destinations return zero.

Choose an observation that depends on the destination. A serial reply, a changing pad and a copied word distinguish different paths.

At Scale

ap_soc~12 blocks
Phone-class SoChundreds of blocks

A verification team can replay this revision before injecting integration faults.

  1. Freeze the inputs

    Keep the v1.0 map, slice settings, image and board stimulus together.

  2. Compare boundaries

    Replay the ten faults in S11.3 and S11.5. Keep the first boundary where each run departs from the control.

Try It

Run the release image and find the debug scan before driver entry.

Compare source and destination at the copy and resume breakpoints.

Change SAMPLE and predict which observations belong to the board and which follow the new input.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: edge=2 boot osc=1 pll=0 strap_valid=0 fabric=0 ready=0 core=0 edge=3 boot osc=1 pll=1 strap_valid=0 fabric=0 ready=0 core=0 edge=4 boot osc=1 pll=1 strap_valid=1 fabric=0 ready=0 core=0 edge=5 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=0 core=0 edge=6 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=0 core=0 edge=7 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=0 core=0 edge=8 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=0 core=0 edge=9 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=1 core=0 edge=10 boot osc=1 pll=1 strap_valid=1 fabric=1 ready=1 core=1 edge=11 fetch pc=00000000 jump_target=00000004 debug IDCODE=2a5310c5 edge=12 start pc=00000004 sp=00000000 source=xxxxxxxx copy=xxxxxxxx edge=19 drivers pc=00000020 sp=80010000 source=00001234 copy=00000000 t=36 | UART0 receives 4b "K" t=36 | interrupt, external: mcause=8000000b mepc=00000060, next is 00000180 t=36 | PLIC claim returns 1 t=39 | PLIC complete 1 t=41 | mret: back to 00000060 edge=56 copy pc=00000064 sp=80010000 source=0000004b copy=00000000 t=51 | DMA starts: 4 bytes from 80000000 to 80000004 t=55 | DMA done t=207 | watchdog armed, 6 ticks left t=207 | GPIO OUT = 0001 edge=219 sleep pc=000000e4 edge=226 wake pending=1 gated_edges=0 pc=000000e4 edge=226 resume pc=000000e4 sp=80010000 source=0000004b copy=0000004b t=208 | GPIO OUT = 0000 bridge TX=4b accepted=1 t=210 | UART0 sends 4b "K" address 80000010 write=1 ready=1 data write=1 ready=0 response=0 data write=1 ready=1 response=0 address 80000010 write=0 ready=1 data write=0 ready=0 response=0 data write=0 ready=1 response=0 debug scratch=0000004b transfers=2 smoke SPI=ffffff PWM_pad_edges=38 mtime_read=201 watchdog_armed=1 decoded windows=7ff copy=0000004b console=K interrupts=1 exceptions=0 checker: 1 writes, 0 reads, 0 wait edges, 0 rules broken, 0 notes
Read included file: slices.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

// 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

// ap_soc teaching policy. Input tick is an enable from the supervision clock.
// A privileged boot writer may arm once. Reset request persists until reset.
module watchdog_supervisor (
  input logic clk, reset_n, tick, debug_halt, dev_mode, privileged,
  input logic psel, penable, pwrite,
  input logic [11:0] offset,
  input logic [31:0] pwdata,
  output logic armed, irq, reset_req,
  output logic [3:0] remaining
);
  localparam KEY = 0, CONTROL = 4, SERVICE = 8;
  localparam RELOAD = 6, OPEN = 3;
  logic first_key, unlocked;
  logic [1:0] grace;
  wire write_word = psel && penable && pwrite;
  wire arm = write_word && privileged && unlocked && offset == CONTROL && pwdata == 1;
  wire kick = write_word && offset == SERVICE && pwdata == 1;

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      first_key <= 0;
      unlocked <= 0;
      armed <= 0;
      remaining <= 0;
      irq <= 0;
      reset_req <= 0;
      grace <= 0;
    end else begin
      if (write_word) begin
        first_key <= privileged && offset == KEY && pwdata == 'h51;
        unlocked <= privileged && first_key && offset == KEY && pwdata == 'ha2;
      end
      if (!armed && arm) begin
        armed <= 1;
        remaining <= RELOAD;
      end else if (armed && !reset_req && !(dev_mode && debug_halt)) begin
        if (irq) begin
          if (tick && grace == 1) reset_req <= 1;
          else if (tick) grace <= grace - 1'b1;
        end else if ((kick && remaining > OPEN) || (tick && remaining == 1 && !kick)) begin
          irq <= 1;
          grace <= 2;
          remaining <= 0;
        end else if (kick) remaining <= RELOAD;
        else if (tick) remaining <= remaining - 1'b1;
      end
    end
  end
endmodule

// 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

// A one-word boot ROM for the startup lab. Unavailable and unmapped reads
// both complete with an error. START_EDGES counts local edges after release.
module boot_rom_port #(
  parameter integer START_EDGES = 4
)(
  input  logic clk, reset_n, req,
  input  logic [31:0] addr,
  output wire ready,
  output logic valid, error,
  output logic [31:0] data
);
  integer warm_edges;
  assign ready = reset_n && warm_edges >= START_EDGES;
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      warm_edges <= 0;
      valid <= 0;
      error <= 0;
      data <= 0;
    end else begin
      if (!ready) warm_edges <= warm_edges + 1;
      valid <= req;
      if (req) begin
        error <= !ready || addr != 0;
        data <= ready && addr == 0 ? 32'h00000013 : 0;
      end
    end
  end
endmodule

// Clock-only sleep slice. The board holds the button until it is serviced.
// Inputs other than button belong to the ungated reference-clock domain.
module sleep_clock(
  input logic ref_clk, reset_n, button, sleep_request, bus_idle, serviced,
  output logic pending, output wire core_clk
);
  logic sample, synced, previous, enabled;
  always_ff @(posedge ref_clk or negedge reset_n) begin
    if (!reset_n) begin
      {sample, synced, previous} <= 0;
      pending <= 0;
    end else begin
      {previous, synced, sample} <= {synced, sample, button};
      if (synced && !previous) pending <= 1;
      else if (serviced) pending <= 0;
    end
  end

  // Model a gate which changes its decision only during the low phase.
  always_ff @(negedge ref_clk or negedge reset_n)
    if (!reset_n) enabled <= 1;
    else enabled <= !sleep_request || !bus_idle || pending;
  assign core_clk = ref_clk && enabled;
endmodule

// Four-slot peripheral timer. The prescaler top is the last count before a step.
// capture is a synchronous event strobe from the input front end.
module capture_pwm (
  input logic clk, reset_n, psel, penable, pwrite, capture,
  input logic [11:0] offset,
  input logic [31:0] pwdata,
  output logic [31:0] prdata,
  output logic [1:0] phase,
  output logic pwm, match
);
  localparam RUN = 0, DUTY = 4, CAPTURED = 8, DIV_TOP = 12, COMPARE = 16;
  logic running;
  logic [7:0] divider, prescale_top;
  logic [2:0] duty;
  logic [1:0] captured, compare_phase;
  wire write_word = psel && penable && pwrite;

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      running <= 0;
      divider <= 0;
      prescale_top <= 0;
      phase <= 0;
      duty <= 0;
      compare_phase <= 0;
      captured <= 0;
    end else begin
      if (write_word && offset == RUN) running <= pwdata[0];
      if (write_word && offset == DUTY) duty <= pwdata[2:0];
      if (write_word && offset == COMPARE) compare_phase <= pwdata[1:0];

      if (write_word && offset == DIV_TOP) begin
        prescale_top <= pwdata[7:0];
        divider <= 0;
      end else if (running) begin
        if (divider == prescale_top) begin
          divider <= 0;
          phase <= phase + 1'b1;
        end else divider <= divider + 1'b1;
      end
      if (capture) captured <= phase;
    end
  end
  assign prdata = offset == CAPTURED ? {30'b0,captured} : 0;
  assign pwm = running && phase < duty;
  assign match = running && phase == compare_phase;
endmodule

// Each 12-bit row holds four three-bit endpoint numbers, indexed by function select.
// The board table is an elaboration parameter. An empty table releases every pad.
module pad_slice #(parameter logic [47:0] ROUTES = 0) (input wire clk,reset_n,psel,penable,pwrite,sample,
  input wire [31:0] paddr,pwdata, output wire [31:0] prdata,
  input wire [3:0] gpio_data,gpio_oe, input wire uart_tx,pwm,spi_clk,
  inout wire [3:0] pad, output logic strap, output wire uart_rx,spi_in,
  output wire [3:0] capture,oe);
  localparam MUX = 32'h10004010;
  logic [7:0] sel;
  wire [3:0] rx_lines, spi_lines;
  assign prdata = paddr == MUX ? {24'b0,sel} : 0;
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      sel <= 0;
      strap <= 0;
    end else begin
      if (sample) strap <= pad[0];
      if (psel && penable && pwrite && paddr == MUX) sel <= pwdata[7:0];
    end
  end
  localparam GPIO=1, UART_TX=2, UART_RX=3, SCLK=4, MISO=5, PWM=6, CAPTURE=7;
  for (genvar p=0; p<4; p++) begin : drivers
    localparam logic [11:0] ROW = ROUTES[12*p +: 12];
    wire [1:0] field = sel[2*p +: 2];
    wire [2:0] endpoint = ROW[3*field +: 3];
    logic data, drive;
    always_comb begin
      case (endpoint)
        GPIO:    {drive,data} = {gpio_oe[p],gpio_data[p]};
        UART_TX: {drive,data} = {1'b1,uart_tx};
        SCLK:    {drive,data} = {1'b1,spi_clk};
        PWM:     {drive,data} = {1'b1,pwm};
        default: {drive,data} = 2'b00;
      endcase
    end
    assign oe[p] = drive;
    assign pad[p] = drive ? data : 1'bz;
    assign rx_lines[p] = endpoint == UART_RX ? pad[p] : 1'b1;
    assign spi_lines[p] = endpoint == MISO ? pad[p] : 1'b0;
    assign capture[p] = endpoint == CAPTURE ? pad[p] : 1'b0;
  end
  // This table assigns at most one source each to UART RX and SPI input.
  assign uart_rx = &rx_lines;
  assign spi_in = |spi_lines;
endmodule

// APB teaching slice. Aligned word transfers, no waits, one system clock.
// UART receives frame-complete bytes from the P6 receiver. SPI uses mode 0.
module serial_slice(
  input wire clk, reset_n, sel, enable, wr,
  input wire [31:0] addr, wdata,
  output logic [31:0] rdata,
  input wire rx_done, input wire [7:0] rx_data,
  output wire tx, irq, dma_req, cs_n, mosi,
  output logic sclk, input wire miso
);
  // UART0: transmit data 0x00 (write), status 0x04 (read), receive data 0x0C (read).
  // Status bits: 0 = room to transmit, 1 = a received byte waits, 2 = the receive queue is full.
  localparam UART_TXDATA = 32'h10000000, UART_STATUS = 32'h10000004, UART_RXDATA = 32'h1000000c,
             SPI_DATA = 32'h10005000, SPI_STATUS = 32'h10005004;
  wire access = sel && enable;
  logic [7:0] fifo [0:1];
  logic head, tail;
  logic [1:0] used;
  wire pop = access && !wr && addr == UART_RXDATA && used != 0;
  wire push = rx_done && (used < 2 || pop);
  assign irq = used != 0;
  assign dma_req = used == 2;
  logic [9:0] frame;
  logic [3:0] bits_left, tick;
  assign tx = frame[0];

  logic [31:0] shift;
  logic [23:0] flash_id;
  logic [5:0] clocks_left;
  logic half_tick;
  assign cs_n = clocks_left == 0;
  assign mosi = shift[31];
  always_comb begin
    case (addr)
      UART_RXDATA: rdata = irq ? fifo[head] : 0;
      UART_STATUS: rdata = {29'b0, dma_req, irq, bits_left == 0};
      SPI_DATA:    rdata = {8'b0, flash_id};
      SPI_STATUS:  rdata = {31'b0, !cs_n};
      default:     rdata = 0;
    endcase
  end
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      used <= 0;
      head <= 0;
      tail <= 0;
      frame <= '1;
      bits_left <= 0;
      tick <= 0;
      clocks_left <= 0;
      half_tick <= 0;
      sclk <= 0;
      shift <= 0;
      flash_id <= 0;
    end else begin
      if (push) begin
        fifo[tail] <= rx_data;
        tail <= !tail;
      end
      if (pop) head <= !head;
      case ({push,pop})
        2'b10: used <= used + 1'b1;
        2'b01: used <= used - 1'b1;
        default: ;
      endcase

      if (bits_left != 0) begin
        tick <= tick + 1'b1;
        if (tick == 15) begin
          frame <= {1'b1, frame[9:1]};
          bits_left <= bits_left - 1'b1;
        end
      end else if (access && wr && addr == UART_TXDATA) begin
        frame <= {1'b1, wdata[7:0], 1'b0};
        bits_left <= 10;
        tick <= 0;
      end

      if (cs_n) begin
        if (access && wr && addr == SPI_DATA) begin
          shift <= {wdata[7:0], 24'b0};
          clocks_left <= 32;
          half_tick <= 0;
        end
      end else begin
        half_tick <= !half_tick;
        if (half_tick) begin
          sclk <= !sclk;
          if (!sclk) flash_id <= {flash_id[22:0], miso};
          else begin
            shift <= shift << 1;
            clocks_left <= clocks_left - 1'b1;
          end
        end
      end
    end
  end
endmodule

// Small board model. DR and IR share the same capture/shift/pause sequencer.
// Only IDCODE and BYPASS have data paths in this fixture.
module board_tap #(parameter logic [31:0] ID = 32'h2a53_10c5) (
  input logic tck, tms, tdi, output logic tdo
);
  typedef enum {RESET, IDLE, SELECT_DR, SELECT_IR, CAPTURE, SHIFT,
                EXIT1, PAUSE_SCAN, EXIT2, UPDATE_SCAN} phase_t;
  phase_t phase = RESET;
  logic ir_branch = 0;
  logic [1:0] opcode = 1, ir_shift;
  logic [31:0] data_shift;
  always @(posedge tck) begin
    case (phase)
      RESET: if (!tms) phase <= IDLE;
      IDLE: if (tms) phase <= SELECT_DR;
      SELECT_DR: if (tms) phase <= SELECT_IR;
                 else begin phase <= CAPTURE; ir_branch <= 0; end
      SELECT_IR: if (tms) phase <= RESET;
                 else begin phase <= CAPTURE; ir_branch <= 1; end
      CAPTURE: begin
        if (ir_branch) ir_shift <= 2'b01;
        else data_shift <= (opcode == 1) ? ID : 0;
        if (tms) phase <= EXIT1; else phase <= SHIFT;
      end
      SHIFT: begin
        if (ir_branch) ir_shift <= {tdi, ir_shift[1]};
        else if (opcode == 1) data_shift <= {tdi, data_shift[31:1]};
        else data_shift[0] <= tdi;
        if (tms) phase <= EXIT1;
      end
      EXIT1: if (tms) phase <= UPDATE_SCAN; else phase <= PAUSE_SCAN;
      PAUSE_SCAN: if (tms) phase <= EXIT2;
      EXIT2: if (tms) phase <= UPDATE_SCAN; else phase <= SHIFT;
      UPDATE_SCAN: if (tms) phase <= SELECT_DR; else phase <= IDLE;
    endcase
  end
  always @(negedge tck) begin
    if (phase == RESET) opcode <= 1;
    if (phase == UPDATE_SCAN && ir_branch) opcode <= ir_shift;
    if (phase == SHIFT) tdo <= ir_branch ? ir_shift[0] : data_shift[0];
    else tdo <= 1'bz;
  end
endmodule

module \full_decode (input wire [31:0] addr, output wire [10:0] sel, output wire error_sel);
  // sel[0]: Boot ROM
  assign sel[0] = ((addr & 32'hfffff000) == 32'h00000000);
  // sel[1]: ap_clint
  assign sel[1] = ((addr & 32'hffff0000) == 32'h02000000);
  // sel[2]: ap_plic
  assign sel[2] = ((addr & 32'hffc00000) == 32'h0c000000);
  // sel[3]: UART0
  assign sel[3] = ((addr & 32'hfffff000) == 32'h10000000);
  // sel[4]: GPIO
  assign sel[4] = ((addr & 32'hfffff000) == 32'h10001000);
  // sel[5]: Timer and PWM
  assign sel[5] = ((addr & 32'hfffff000) == 32'h10002000);
  // sel[6]: Watchdog
  assign sel[6] = ((addr & 32'hfffff000) == 32'h10003000);
  // sel[7]: ap_sysctl
  assign sel[7] = ((addr & 32'hfffff000) == 32'h10004000);
  // sel[8]: SPI
  assign sel[8] = ((addr & 32'hfffff000) == 32'h10005000);
  // sel[9]: DMA
  assign sel[9] = ((addr & 32'hfffff000) == 32'h10006000);
  // sel[10]: SRAM
  assign sel[10] = ((addr & 32'hffff0000) == 32'h80000000);
  assign error_sel = ~|sel;
endmodule

`timescale 1ns/1ns
// ahb_apb_bridge.sv: an AHB subordinate that turns each accepted transfer into one APB transfer
// (read-only). The address phase is registered when HSEL, HREADY and a NONSEQ or SEQ transfer are
// all present. During SETUP and unfinished ACCESS the bridge keeps HREADYOUT low. A successful APB
// completion ends the AHB data phase with OKAY and HRDATA = PRDATA. A failed APB completion starts
// the two-cycle ERROR (HREADYOUT low then high, HRESP high in both). HWDATA and HWSTRB are data-phase signals the manager holds
// through the wait states, so PWDATA and PSTRB are driven from them directly; PADDR is the aligned
// word address (IHI 0024E 2.1.1 leaves an unaligned PADDR unpredictable). HPROT maps onto PPROT:
// privileged from HPROT[1], instruction from HPROT[0] = 0, and the access is Secure.
// A write therefore costs one setup and one access cycle: two cycles of data phase with no APB wait.
module ahb_apb_bridge (
  input  logic        hclk,
  input  logic        hresetn,
  input  logic        hsel,
  input  logic [31:0] haddr,
  input  logic [1:0]  htrans,
  input  logic        hwrite,
  input  logic [3:0]  hprot,
  input  logic [31:0] hwdata,
  input  logic [3:0]  hwstrb,
  input  logic        hready,
  output logic        hreadyout,
  output logic        hresp,
  output logic [31:0] hrdata,
  output logic        psel,
  output logic        penable,
  output logic        pwrite,
  output logic [31:0] paddr,
  output logic [31:0] pwdata,
  output logic [3:0]  pstrb,
  output logic [2:0]  pprot,
  input  logic        pready,
  input  logic [31:0] prdata,
  input  logic        pslverr);
  localparam int IDLE = 0, SETUP = 1, ACCESS = 2, ERR1 = 3, ERR2 = 4;
  bit trace = 0;
  int st = IDLE;
  logic        wr = 0;
  logic [31:0] a = 0;
  logic [2:0]  prot = 0;
  wire take = hsel && hready && htrans[1];
  assign psel      = (st == SETUP || st == ACCESS);
  assign penable   = (st == ACCESS);
  assign pwrite    = wr;
  assign paddr     = {a[31:2], 2'b00};     // APB leaves an unaligned PADDR unpredictable: the word, and PSTRB picks the bytes
  assign pwdata    = wr ? hwdata : 32'h0;
  assign pstrb     = wr ? hwstrb : 4'h0;
  assign pprot     = prot;
  assign hreadyout = (st == IDLE || st == ERR2) ? 1'b1 : (st == ACCESS) ? (pready === 1'b1 && pslverr !== 1'b1) : 1'b0;
  assign hresp     = (st == ERR1 || st == ERR2);
  assign hrdata    = (st == ACCESS) ? prdata : 32'h0;
  always @(posedge hclk or negedge hresetn) begin
    if (!hresetn) st <= IDLE;
    else begin
      case (st)
        SETUP:  st <= ACCESS;
        ACCESS: if (pready === 1'b1) begin
                  if (trace) $display("apb e%0d: %0s 0x%03h%0s", ($time - 5) / 10, wr ? "write" : "read", a[11:0], pslverr === 1'b1 ? " PSLVERR" : "");
                  st <= (pslverr === 1'b1) ? ERR1 : IDLE;
                end
        ERR1:   st <= ERR2;
        default: st <= IDLE;
      endcase
      // A new address phase can be taken whenever HREADY is 1: in IDLE, in the last cycle of ERROR,
      // or at the edge an access completes with OKAY.
      if (take && (st == IDLE || st == ERR2 || (st == ACCESS && pready === 1'b1 && pslverr !== 1'b1))) begin
        wr <= hwrite; a <= haddr; prot <= {~hprot[0], 1'b0, hprot[1]}; st <= SETUP;
      end
    end
  end
endmodule

`timescale 1ns/1ns
// apb_checker.sv: the rules of an APB interface, checked at every rising edge (read-only).
//   reset        PSEL is 1 while PRESETn is low;
//   known        PSEL is x, or a control signal, a strobed write byte or PREADY in access is x;
//   setup        PENABLE is 1 without a setup cycle (PSEL 1, PENABLE 0) before it;
//   setup_len    a setup cycle not followed by an access cycle;
//   stable       PSEL, PADDR, PWRITE, PPROT, PSTRB or the write data changed inside a transfer,
//                or PSEL or PENABLE dropped before PREADY;
//   enable_drop  PENABLE still 1 in the cycle after a completed transfer;
//   strb_read    PSTRB not zero during a read;
//   onehot       more than one PSELx at once;
//   timeout      no PREADY after TIMEOUT wait cycles (a liveness watchdog, not a protocol rule).
// A NOTE (not a broken rule): PSLVERR is 1 outside the completion cycle, which the spec allows
// and recommends against (IHI 0024E 3.4).
module apb_checker #(parameter int NSEL = 1, parameter int TIMEOUT = 16) (
  input logic            pclk,
  input logic            presetn,
  input logic [NSEL-1:0] psel,
  input logic            penable,
  input logic            pwrite,
  input logic [31:0]     paddr,
  input logic [31:0]     pwdata,
  input logic [3:0]      pstrb,
  input logic [2:0]      pprot,
  input logic            pready,
  input logic            pslverr);
  int broken = 0, notes = 0, writes = 0, reads = 0, waits = 0, edge_n = -1, stall = 0;
  logic            p_any = 0, p_en = 0, p_rdy = 0, p_wr = 0;
  logic [NSEL-1:0] p_sel = 0;
  logic [31:0]     p_addr = 0, p_wdata = 0;
  logic [3:0]      p_strb = 0;
  logic [2:0]      p_prot = 0;
  task automatic report(input string rule, input string msg);
    broken++;
    $display("RULE %0s broken at edge %0d: %0s", rule, edge_n, msg);
  endtask
  task automatic note(input string rule, input string msg);
    notes++;
    $display("NOTE %0s at edge %0d: %0s", rule, edge_n, msg);
  endtask
  always @(posedge pclk) begin
    logic any, en, rdy, bytes_x;
    edge_n = edge_n + 1;
    any = (|psel) === 1'b1; en = (penable === 1'b1); rdy = (pready === 1'b1);
    if (presetn !== 1'b1) begin
      if (any) report("reset", "PSEL is 1 while PRESETn is low");
      any = 0; en = 0;
    end else begin
      bytes_x = 0;
      for (int l = 0; l < 4; l++) if (pstrb[l] === 1'b1 && (^pwdata[8*l +: 8]) === 1'bx) bytes_x = 1;
      if ((^psel) === 1'bx) report("known", "PSEL is x");
      else if (any && (^{paddr, pwrite, penable, pstrb, pprot}) === 1'bx) report("known", "a control signal is x while PSEL is 1");
      else if (any && pwrite === 1'b1 && bytes_x) report("known", "a strobed byte of PWDATA is x");
      else if (any && en && pready === 1'bx) report("known", "PREADY is x in an access cycle");
      if (any && en && !(p_any && (!p_en || !p_rdy)))
        report("setup", "PENABLE is 1 without a setup cycle (PSEL 1, PENABLE 0) before it");
      if (p_any && !p_en && !(any && en))
        report("setup_len", "the setup cycle was not followed by an access cycle");
      if (p_any && (!p_en || !p_rdy) && any) begin
        if (psel !== p_sel) report("stable", $sformatf("PSEL changed from %b to %b inside a transfer", p_sel, psel));
        if (paddr !== p_addr) report("stable", $sformatf("PADDR changed from 0x%0h to 0x%0h inside a transfer", p_addr, paddr));
        if (pwrite !== p_wr) report("stable", "PWRITE changed inside a transfer");
        if (pprot !== p_prot) report("stable", "PPROT changed inside a transfer");
        if (pstrb !== p_strb) report("stable", "PSTRB changed inside a transfer");
        if (p_wr && pwdata !== p_wdata) report("stable", $sformatf("PWDATA changed from 0x%0h to 0x%0h inside a transfer", p_wdata, pwdata));
        if (p_en && !en) report("stable", "PENABLE dropped before PREADY");
      end
      if (p_any && p_en && !p_rdy && !any) report("stable", "PSEL dropped before PREADY");
      if (p_any && p_en && p_rdy && en) report("enable_drop", "PENABLE is still 1 in the cycle after a completed transfer");
      if (any && pwrite === 1'b0 && pstrb !== 4'b0000) report("strb_read", $sformatf("PSTRB is %b during a read", pstrb));
      if ($countones(psel) > 1) report("onehot", $sformatf("PSELx is %b: two completers selected", psel));
      if (any && en && rdy) begin
        if (pwrite === 1'b1) writes++; else reads++;
        stall = 0;
      end else if (any && en) begin
        waits++; stall++;
        if (stall == TIMEOUT) report("timeout", $sformatf("no PREADY after %0d wait cycles", TIMEOUT));
      end
      if (pslverr === 1'b1 && !(any && en && rdy))
        note("pslverr", "PSLVERR is 1 outside the completion cycle (ignored by the requester; recommended LOW)");
    end
    p_any = any; p_en = en; p_rdy = rdy; p_sel = psel; p_addr = paddr; p_wr = (pwrite === 1'b1);
    p_wdata = pwdata; p_strb = pstrb; p_prot = pprot;
  end
  final $display("checker: %0d writes, %0d reads, %0d wait edges, %0d rules broken, %0d notes", writes, reads, waits, broken, notes);
endmodule

// The two register ports exercised in S4.5. Only UART can stretch a transfer.
module ap_uart_tx_port(
  input  logic        clk, reset_n, sel, enable, write,
  input  logic [11:0] offset,
  input  logic [31:0] data, wait_edges,
  input  logic [3:0]  strb,
  output logic        ready, error, push,
  output logic [7:0]  tx_byte
);
  logic [31:0] elapsed;
  always_ff @(posedge clk or negedge reset_n) begin
    if (!reset_n) elapsed <= 0;
    else if (sel && enable && !ready) elapsed <= elapsed + 1;
    else elapsed <= 0;
  end

  assign ready = sel && enable && elapsed >= wait_edges;
  assign error = ready && (!write || offset != 12'h000);
  assign push = ready && !error && strb[0];
  assign tx_byte = data[7:0];
endmodule

module ap_gpio_input_port(
  input  logic        sel, enable, write,
  input  logic [11:0] offset,
  input  logic [15:0] pins,
  output logic        ready, error,
  output logic [31:0] data
);
  wire input_word = !write && offset == 12'h004;
  assign ready = sel && enable;
  assign error = ready && !input_word;
  assign data = sel && input_word ? {16'b0, pins} : 32'b0;
endmodule

module release_bridge;
// Two pages of the ap_soc v1.0 map. Other addresses in this bench's APB
// envelope receive a local error. Both buses use the same clock.
localparam logic [31:0] TX = 32'h1000_0000, INPUT_WORD = 32'h1000_1004;
logic hclk=0, hresetn=0;
always #5 hclk = ~hclk;
logic [31:0] haddr=0, hwdata=0;
logic [1:0] htrans=0;
logic hwrite=0;
wire hsel = haddr[31:16] == 16'h1000;
wire hready, hresp, psel, penable, pwrite;
wire [31:0] paddr, pwdata, hrdata, gpio_data;
wire [3:0] pstrb;
wire [2:0] pprot;
wire uart_selected = psel && paddr[31:12] == TX[31:12];
wire gpio_selected = psel && paddr[31:12] == INPUT_WORD[31:12];
logic [31:0] waits=0;
wire uart_ready, uart_error, push, gpio_ready, gpio_error;
wire [7:0] tx_byte;
wire selected_hole = psel && !uart_selected && !gpio_selected;
wire pready = uart_selected ? uart_ready :
              gpio_selected ? gpio_ready : selected_hole && penable;
wire pslverr = uart_selected ? uart_error :
               gpio_selected ? gpio_error : selected_hole && penable;
wire [31:0] prdata = gpio_selected ? gpio_data : 32'b0;

ap_uart_tx_port uart(
  .clk(hclk), .reset_n(hresetn), .sel(uart_selected), .enable(penable), .write(pwrite),
  .offset(paddr[11:0]), .data(pwdata), .strb(pstrb), .wait_edges(waits),
  .ready(uart_ready), .error(uart_error), .push(push), .tx_byte(tx_byte)
);
ap_gpio_input_port gpio(
  .sel(gpio_selected), .enable(penable), .write(pwrite), .offset(paddr[11:0]),
  .pins(16'h8042), .ready(gpio_ready), .error(gpio_error), .data(gpio_data)
);
ahb_apb_bridge bridge(
  .hclk, .hresetn, .hsel, .haddr, .htrans, .hwrite, .hwdata, .hprot(4'b0011),
  .hwstrb(4'hf), .hready, .hreadyout(hready), .hresp, .hrdata,
  .psel, .penable, .pwrite, .paddr, .pwdata, .pstrb, .pprot, .pready, .pslverr, .prdata
);
apb_checker #(.NSEL(2)) watch_bus(
  .pclk(hclk), .presetn(hresetn), .psel({gpio_selected,uart_selected}),
  .penable, .pwrite, .paddr, .pwdata, .pstrb, .pprot, .pready, .pslverr
);

// Aligned, non-overlapping, full-word writes from a bus-functional manager.
task automatic write_word(input logic [31:0] address, data, output logic failed);
  @(negedge hclk);
  haddr=address;
  hwrite=1;
  htrans=2'b10;
  @(negedge hclk);
  htrans=0;
  haddr=0;
  hwdata=data;
  do @(posedge hclk); while (!hready);
  failed=hresp;
  #1;
endtask

  int pushes;
  logic [7:0] accepted;
  always @(posedge hclk) if (push) begin pushes++; accepted=tx_byte; end
  task automatic send_byte(input logic [31:0] payload);
    logic failed;
    hresetn=1;
    write_word(TX,payload,failed);
    if (failed || pushes!=1 || accepted!==payload[7:0]) $fatal(1,"bridge delivery");
    $display("bridge TX=%02h accepted=%0d",accepted,pushes);
  endtask
endmodule
`timescale 1ns/1ns
// ahb_pkg.sv: the encodings and the arithmetic of a burst (read-only).
// The memory, the driver, the checker and the lesson text all use these functions, so they never
// disagree about the address of a beat or the lanes it uses.
package ahb_pkg;
  localparam logic [1:0] IDLE = 2'b00, BUSY = 2'b01, NONSEQ = 2'b10, SEQ = 2'b11;
  localparam logic [2:0] SINGLE = 3'b000, INCR = 3'b001, WRAP4 = 3'b010, INCR4 = 3'b011,
                         WRAP8 = 3'b100, INCR8 = 3'b101, WRAP16 = 3'b110, INCR16 = 3'b111;
  localparam logic OKAY = 1'b0, ERROR = 1'b1;

  function automatic string trans_name(input logic [1:0] t);
    case (t) IDLE: return "IDLE"; BUSY: return "BUSY"; NONSEQ: return "NONSEQ"; default: return "SEQ"; endcase
  endfunction
  function automatic string burst_name(input logic [2:0] b);
    case (b)
      SINGLE: return "SINGLE"; INCR: return "INCR"; WRAP4: return "WRAP4"; INCR4: return "INCR4";
      WRAP8: return "WRAP8"; INCR8: return "INCR8"; WRAP16: return "WRAP16"; default: return "INCR16";
    endcase
  endfunction
  function automatic string resp_name(input logic r);
    return r ? "ERROR" : "OKAY";
  endfunction
  // s when c is 1, else the empty string (a string-typed result prints the same on every simulator).
  function automatic string opt(input bit c, input string s);
    if (c) return s;
    return "";
  endfunction

  // Beats in a burst: 1 for SINGLE, 4, 8 or 16 for the fixed bursts, 0 for INCR (undefined length).
  function automatic int beats_of(input logic [2:0] b);
    case (b) SINGLE: return 1; INCR: return 0; WRAP4, INCR4: return 4; WRAP8, INCR8: return 8; default: return 16; endcase
  endfunction
  function automatic bit is_wrap(input logic [2:0] b);
    return b == WRAP4 || b == WRAP8 || b == WRAP16;
  endfunction

  // The address of the beat after the one at a: the size in bytes further on; a wrapping burst
  // returns to the start of its window (beats x size bytes, aligned to that total) at the window's end.
  function automatic int unsigned next_addr(input int unsigned a, input logic [2:0] size, input logic [2:0] b);
    int unsigned nb = 1 << size;
    int unsigned window = nb * beats_of(b);
    int unsigned base;
    if (!is_wrap(b)) return a + nb;
    base = (a / window) * window;
    if (a + nb >= base + window) return base;
    return a + nb;
  endfunction

  // The address of beat n of a burst that starts at start.
  function automatic int unsigned beat_addr(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int unsigned a = start;
    for (int k = 0; k < n; k++) a = next_addr(a, size, b);
    return a;
  endfunction

  // The lanes a transfer at address a uses on a bus of bus_bytes bytes, packed as {upper, lower}.
  // Every AHB transfer is aligned to its size, so it uses size bytes from its own lane upwards.
  function automatic logic [15:0] beat_lanes(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    int lower = a % bus_bytes;
    int upper = lower + (1 << size) - 1;
    if (upper > bus_bytes - 1) upper = bus_bytes - 1;
    return {upper[7:0], lower[7:0]};
  endfunction

  // The strobe of a transfer: a 1 for every lane it uses (bit l is lane l).
  function automatic logic [63:0] beat_strb(input int unsigned a, input logic [2:0] size, input int bus_bytes);
    logic [15:0] lanes = beat_lanes(a, size, bus_bytes);
    logic [63:0] s = 0;
    for (int l = lanes[7:0]; l <= lanes[15:8]; l++) s[l] = 1'b1;
    return s;
  endfunction

  function automatic bit aligned(input int unsigned a, input logic [2:0] size);
    return (a % (1 << size)) == 0;
  endfunction

  // True when an incrementing burst of n beats (n is used only for INCR) crosses a 1 KB boundary.
  function automatic bit crosses_1k(input int unsigned start, input logic [2:0] size, input logic [2:0] b, input int n);
    int beats = beats_of(b) ? beats_of(b) : n;
    if (is_wrap(b) || beats < 2) return 0;
    return (start / 1024) != ((start + beats * (1 << size) - 1) / 1024);
  endfunction
endpackage

`timescale 1ns/1ns
// ahb_mem.sv: an AHB subordinate with a byte-addressed memory behind it (read-only in this lesson).
// It registers an address phase at an edge where HSEL is 1, HTRANS is NONSEQ or SEQ and HREADY is 1,
// then runs the data phase: wait states with HREADYOUT low, a write takes HWDATA (and HWSTRB) at the
// edge that ends the data phase, a read drives HRDATA for the cycle that ends it. IDLE and BUSY get a
// zero-wait OKAY and change nothing. The switches below are plain variables: the stimulus sets them by
// name (mem.waits = 2;).
//   waits          wait states inserted in every data phase
//   waits_at[k]    wait states for the k-th transfer this memory takes (from 0; -1 = use waits)
//   err_above      transfers at or above this address get the two-cycle ERROR (and write nothing)
//   excl_on        AHB5 exclusive access: one monitor per HMASTER, HEXOKAY on success
//   trace          print every transfer the memory takes and every byte it writes
// Broken twins, each off by default:
//   ignore_hready    registers an address phase while HREADY is low (another subordinate is stretching),
//                    so it acts on a transfer the manager may still change or cancel
//   wdata_in_addr    takes HWDATA in the address phase, so a write stores the previous transfer's data
//   act_on_idle      treats IDLE and BUSY as transfers (waits, reads, writes HWDATA); this twin is an
//                    AHB-Lite design without an HWSTRB input, so it writes the lanes HSIZE selects
//   one_cycle_error  answers ERROR in one cycle (HRESP high with HREADYOUT high)
//   ignore_size      writes every lane of the bus word, whatever HSIZE and HWSTRB say
module ahb_mem #(parameter int DATA_W = 32, parameter int DEPTH = 65536) (
  input  logic              hclk,
  input  logic              hresetn,
  input  logic              hsel,
  input  logic [31:0]       haddr,
  input  logic [1:0]        htrans,
  input  logic              hwrite,
  input  logic [2:0]        hsize,
  input  logic [2:0]        hburst,
  input  logic [3:0]        hprot,
  input  logic              hmastlock,
  input  logic [DATA_W-1:0] hwdata,
  input  logic [DATA_W/8-1:0] hwstrb,
  input  logic              hexcl,
  input  logic [3:0]        hmaster,
  input  logic              hready,
  output logic              hreadyout,
  output logic              hresp,
  output logic [DATA_W-1:0] hrdata,
  output logic              hexokay
);
  import ahb_pkg::*;
  localparam int BUS = DATA_W / 8;

  // ---- switches ----
  int waits = 0;
  int waits_at [0:63];
  int unsigned err_above = 32'hffff_ffff;
  bit excl_on = 0, trace = 0;
  bit ignore_hready = 0, wdata_in_addr = 0, act_on_idle = 0, one_cycle_error = 0, ignore_size = 0;

  // ---- the memory ----
  logic [7:0] mem [0:DEPTH-1];
  int cycle = -1;
  int taken = 0;                              // transfers taken so far

  // ---- the data phase in progress ----
  bit              d_valid = 0, d_write = 0, d_err = 0, d_exok = 0, d_xfail = 0;
  int unsigned     d_addr = 0;
  logic [2:0]      d_size = 0;
  logic [1:0]      d_trans = 0;
  logic [DATA_W-1:0] d_wd = 0;                // HWDATA seen in the address phase (the wdata_in_addr twin)
  int              d_cnt = 0;                 // wait states still to insert
  bit              e_two = 0;                 // the ERROR response is in its second cycle

  // ---- exclusive monitors, one per HMASTER ----
  bit          mon_use [0:15];
  int unsigned mon_addr [0:15];
  int          mon_bytes [0:15];

  initial begin
    for (int i = 0; i < DEPTH; i++) mem[i] = 8'h00;
    for (int k = 0; k < 64; k++) waits_at[k] = -1;
    for (int m = 0; m < 16; m++) mon_use[m] = 0;
    hreadyout = 1; hresp = 0; hrdata = 0; hexokay = 0;
  end

  function automatic logic [DATA_W-1:0] read_word(input int unsigned a);
    logic [DATA_W-1:0] w = 0;
    int unsigned word = (a / BUS) * BUS;
    for (int l = 0; l < BUS; l++) w[8*l +: 8] = mem[(word + l) % DEPTH];
    return w;
  endfunction

  // Write the lanes of one transfer: the lanes its address and size select, where the strobe is 1.
  task automatic write_bytes(input int unsigned a, input logic [2:0] size, input logic [DATA_W-1:0] data, input logic [BUS-1:0] strb);
    logic [15:0] lanes = beat_lanes(a, size, BUS);
    int unsigned word = (a / BUS) * BUS;
    int lo = ignore_size ? 0 : lanes[7:0];
    int hi = ignore_size ? BUS - 1 : lanes[15:8];
    for (int l = lo; l <= hi; l++)
      if (ignore_size || act_on_idle || strb[l]) begin
        mem[(word + l) % DEPTH] = data[8*l +: 8];
        if (trace) $display("mem e%0d:   byte 0x%0h <= %02h (lane %0d)", cycle, word + l, data[8*l +: 8], l);
      end
    // any write ends the exclusive monitors that cover one of its bytes
    for (int m = 0; m < 16; m++)
      if (mon_use[m] && a < mon_addr[m] + mon_bytes[m] && mon_addr[m] < a + (1 << size)) mon_use[m] = 0;
  endtask

  always @(posedge hclk) begin
    cycle = cycle + 1;
    if (!hresetn) begin
      d_valid = 0; e_two = 0;
      hreadyout <= 1; hresp <= 0; hexokay <= 0;
    end else begin
      // 1. the data phase that ends or waits at this edge
      if (d_valid) begin
        if (hreadyout && hready) begin
          if (d_write && !d_err && !d_xfail)
            write_bytes(d_addr, d_size, wdata_in_addr ? d_wd : hwdata, hwstrb);
          d_valid = 0;
        end else if (!hreadyout) begin
          if (d_cnt > 0) d_cnt = d_cnt - 1;
          else if (d_err) e_two = 1;
        end
      end
      // 2. the address phase on the wires at this edge
      if (hsel && (htrans[1] || act_on_idle) && (hready || (ignore_hready && !d_valid))) begin
        d_valid = 1; d_addr = haddr; d_write = hwrite; d_size = hsize; d_trans = htrans; d_wd = hwdata;
        d_cnt = (taken < 64 && waits_at[taken] >= 0) ? waits_at[taken] : waits;
        taken = taken + 1;
        d_err = (haddr >= err_above); e_two = 0;
        d_exok = 0; d_xfail = 0;
        if (excl_on && hexcl && htrans[1] && !d_err) begin
          if (!hwrite) begin
            mon_use[hmaster] = 1; mon_addr[hmaster] = haddr; mon_bytes[hmaster] = 1 << hsize; d_exok = 1;
          end else if (mon_use[hmaster] && mon_addr[hmaster] == haddr && mon_bytes[hmaster] == (1 << hsize)) begin
            d_exok = 1; mon_use[hmaster] = 0;
          end else d_xfail = 1;
        end
        if (trace) $display("mem e%0d: %0s %0s 0x%0h size %0d%0s%0s%0s", cycle, trans_name(htrans), hwrite ? "write" : "read", haddr, hsize,
                            opt(!hready, " (taken while HREADY is low)"), opt(d_err, " -> ERROR"),
                            opt(d_xfail, " -> exclusive failed"));
      end
      // 3. the response for the cycle that starts now
      if (d_valid && d_cnt > 0) begin
        hreadyout <= 0; hresp <= 0; hexokay <= 0;
      end else if (d_valid && d_err) begin
        hreadyout <= one_cycle_error ? 1'b1 : e_two; hresp <= 1; hexokay <= 0;
      end else begin
        hreadyout <= 1; hresp <= 0; hexokay <= d_valid && d_exok;
      end
      if (d_valid && !d_write) hrdata <= d_err ? '0 : read_word(d_addr);
    end
  end
endmodule

module release_debug;
// Single-clock bench slice. The host starts in Run-Test/Idle with the lab
// data register selected. Only the direct DR scan path is exercised.
bit tck, tms, tdi, reset_n, authenticated, core_reset = 1;
logic [34:0] shift_dr = 0;
wire tdo = shift_dr[0];
typedef enum {IDLE, SELECT_DR, CAPTURE_DR, SHIFT_DR, EXIT_DR, UPDATE_DR} tap_state;
tap_state tap = IDLE;
logic [31:0] reply = 0, address = 32'h80000000, payload = 0;
logic halt_on_reset = 0, halted = 0, was_reset = 1;
logic [31:0] boot_marker = 32'h00000040;
typedef enum {FREE, ADDRESS, DATA} bus_state;
bus_state bus = FREE;
logic writing = 0;
wire selected = address[31:16] == 16'h8000;
wire ready, error_response;
wire [31:0] read_data;
ahb_mem ram(.hclk(tck), .hresetn(reset_n), .hsel(selected),
  .haddr(address), .htrans(bus == ADDRESS ? 2'b10 : 2'b00),
  .hwrite(writing), .hsize(3'd2), .hburst(3'b0), .hprot(4'b0011),
  .hmastlock(1'b0), .hwdata(payload), .hwstrb(4'hf), .hexcl(1'b0),
  .hmaster(4'd1), .hready(ready), .hreadyout(ready), .hresp(error_response),
  .hrdata(read_data), .hexokay());

always @(posedge tck) begin
  case (tap)
    IDLE: if (tms) tap <= SELECT_DR;
    SELECT_DR: tap <= CAPTURE_DR;
    CAPTURE_DR: begin
      shift_dr <= {authenticated ? reply : 32'b0, 3'b0};
      tap <= SHIFT_DR;
    end
    SHIFT_DR: begin
      shift_dr <= {tdi, shift_dr[34:1]};
      if (tms) tap <= EXIT_DR;
    end
    EXIT_DR: tap <= UPDATE_DR;
    UPDATE_DR: begin
      tap <= IDLE;
      if (authenticated) begin
        case (shift_dr[2:0])
          1: address <= shift_dr[34:3];
          2,3: if (bus == FREE && selected && address[1:0] == 0) begin
            payload <= shift_dr[34:3];
            writing <= shift_dr[2:0] == 2;
            bus <= ADDRESS;
          end
          4: halt_on_reset <= shift_dr[3];
          5: if (halted) reply <= boot_marker;
          default: ;
        endcase
      end
    end
  endcase
  was_reset <= core_reset;
  if (core_reset) halted <= 0;
  else if (was_reset && halt_on_reset) halted <= 1;
  if (bus == ADDRESS && ready) begin
    $display("address %08h write=%b ready=%b", address, writing, ready);
    bus <= DATA;
  end
  if (bus == DATA) begin
    $display("data    write=%b ready=%b response=%b", writing, ready, error_response);
    if (ready) begin
      if (!writing && !error_response) reply <= read_data;
      bus <= FREE;
    end
  end
end

task automatic tick(input bit mode, serial_in);
  tms = mode; tdi = serial_in;
  #2; tck = 1; #2; tck = 0;
endtask

task automatic scan(input logic [2:0] op, input logic [31:0] value,
                    output logic [31:0] returned);
  logic [34:0] outgoing, incoming;
  outgoing = {value, op};
  tick(1,0); tick(0,0); tick(0,0);
  for (int i=0; i<35; i++) begin
    incoming[i] = tdo;
    tick(i == 34, outgoing[i]);
  end
  tick(1,0); tick(0,0);
  returned = incoming[34:3];
endtask

  task automatic witness(input logic [31:0] marker);
    logic [31:0] returned;
    tick(0,0); reset_n=1; authenticated=1; ram.waits=1;
    scan(1,32'h80000010,returned);
    scan(2,marker,returned); repeat(4) tick(0,0);
    scan(3,0,returned); repeat(4) tick(0,0);
    scan(0,0,returned);
    if (returned!==marker || ram.taken!=2) $fatal(1,"debug scratch");
    $display("debug scratch=%08h transfers=%0d",returned,ram.taken);
  endtask
endmodule
Read included file: machine.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  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 = 1;            // 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) 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 (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; bus_path.send_byte(wd);
        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) uart_wait--;
    for (int n = 0; n < rx_planned; n++) if (rx_tick[n] == ticks && rx_count < 4) begin
      rx_queue[rx_count] = rx_plan[n];  rx_count++;
      say($sformatf("UART0 receives %02h \"%c\"", rx_plan[n], rx_plan[n]));
    end
    if (dma_left != 0) 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, 3'b0, 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));
  logic        wdg_write;                      // one write to the watchdog commits at the next rising edge
  logic [11:0] wdg_offset;
  wire         wdg_armed, wdg_reset;
  wire  [3:0]  wdg_left;                       // ticks left before the warning
  wire         wdg_tick = (mtime[4:0] == 5'd31);   // the supervision tick: one in every 32 clock ticks (a lab number)
  watchdog_supervisor wdg (.clk(clk), .reset_n(reset_n), .tick(wdg_tick), .debug_halt(1'b0), .dev_mode(1'b0), .privileged(1'b1),
                           .psel(wdg_write), .penable(wdg_write), .pwrite(wdg_write), .offset(wdg_offset), .pwdata(dev_wdata),
                           .armed(wdg_armed), .irq(wdg_warn), .reset_req(wdg_reset), .remaining(wdg_left));
  bit          wdg_was_armed, wdg_was_warned;
  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;
    visit(ad);
    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 if (wr && (ad == 32'h1000_3000 || ad == 32'h1000_3004 || ad == 32'h1000_3008)) begin   // the watchdog: writes only
      wdg_offset = ad[11:0];  dev_wdata = wd;  wdg_write = 1;
      if (ad[3:0] == 4'h8) say($sformatf("watchdog kick, %0d ticks were left", wdg_left));
    end
    else if ((ad == 'h10002000 || ad == 'h10002004 || ad == 'h10004010 ||
                  ad == 'h10005000 || ad == 'h10005004)) begin
      io_addr = ad; io_data = wd; io_wr = wr; io_sel = 1;
      #1; bus_rdata = spi_data;
    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 && !wdg_armed) 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;
    wdg_write = 0;
    if (wdg_armed && !wdg_was_armed) say($sformatf("watchdog armed, %0d ticks left", wdg_left));
    if (wdg_warn && !wdg_was_warned) say("watchdog early warning: source 6 asks ap_plic");
    if (wdg_reset) say("watchdog reset request: the chip resets here");
    wdg_was_armed = wdg_armed;  wdg_was_warned = wdg_warn;
  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
    wdg_write = 0;  wdg_offset = 0;  wdg_was_armed = 0;  wdg_was_warned = 0;
  endtask
  task automatic run();
    while (!stopped && !wdg_reset && steps + traps + taken < 400) step();
  endtask
  bit supply, osc_ok, lock_ok, button, serviced, io_sel, io_wr;
  logic [31:0] io_addr, io_data;
  wire osc, pll, sampled, strap, fabric, core, ready, pending, gated;
  wire [31:0] spi_data;
  wire pwm, miso, cs_n;
  wire [3:0] pads, oe;
  ap_crg_boot sequencer(clk,supply,osc_ok,lock_ok,1'b0,1'b1,ready,1'b0,osc,pll,sampled,strap,fabric,core);
  boot_rom_port availability(clk,fabric,1'b0,32'b0,ready,,,);
  sleep_clock gate(clk,reset_n,button,gpio_out[0],1'b1,serviced,pending,gated);
  capture_pwm timer(clk,reset_n,io_sel && io_addr[31:12]=='h10002,io_sel,io_wr,1'b0,io_addr[11:0],io_data,,,pwm,);
  serial_slice serial(clk,reset_n,io_sel,io_sel,io_wr,io_addr,io_data,spi_data,1'b0,8'b0,,,,cs_n,,,1'b1);
  pad_slice #(.ROUTES(48'h180)) mux(clk,reset_n,io_sel,io_sel,io_wr,1'b0,io_addr,io_data,,4'b0,4'b0,1'b1,pwm,1'b0,pads,,,,,oe);
  bit tck,tms;
  wire tdo;
  board_tap tap(tck,tms,1'b0,tdo);
  task automatic shift_edge(input bit mode);
    tms=mode; #1; tck=1; #1; tck=0; #1;
  endtask
  logic [31:0] idcode;
  task automatic identify();
    shift_edge(0); shift_edge(1); shift_edge(0); shift_edge(0);
    for (int i=0;i<32;i++) begin idcode[i]=tdo; shift_edge(i==31); end
  endtask
  int aon_edges, core_edges, pad_edges;
  always @(posedge clk) aon_edges++;
  always @(posedge gated) core_edges++;
  always @(posedge pads[0]) if (oe[0]) pad_edges++;
  task automatic pulse();
    #1; clk=1; #1; clk=0; #1;
  endtask
  task automatic boot();
    supply=1;
    repeat(12) begin
      if (osc) osc_ok=1;
      if (pll) lock_ok=1;
      pulse();
      $display("edge=%0d boot osc=%b pll=%b strap_valid=%b fabric=%b ready=%b core=%b",aon_edges,osc,pll,sampled,fabric,ready,core);
      if (core) begin
        reset_n=1;
        pc=strap ? 32'h80000000 : 0;
        if (pc!=0 || kind[0]!=JAL) $fatal(1,"first fetch");
        pulse();
        $display("edge=%0d fetch pc=%08h jump_target=%08h",aon_edges,pc,fc[0]);
        disable boot;
      end
    end
    $fatal(1,"boot timed out");
  endtask

  logic [31:0] issued;
  logic [10:0] visited=0;
  wire [10:0] selected;
  wire miss;
  full_decode decoder(issued,selected,miss);
  release_bridge bus_path();
  release_debug host();
  task automatic visit(input logic [31:0] address);
    issued=address; #1;
    if (miss || !$onehot(selected)) $fatal(1,"release decode");
    visited |= selected;
  endtask

Check Yourself

ConceptWhich port carries the payload of an SRAM copy?
ConceptWhich action consumes input?
ConceptWhat can cause a silent console after a successful transmit store?
ConceptWhich observation distinguishes PWM routing from programming alone?
Predict the outputWith SAMPLE changed to hexadecimal 52, which final application line appears?
// BREAK_PC stops before the instruction. Use -1 for the entire run.
module tb;
  localparam integer BREAK_PC = -1;
  localparam logic [7:0] SAMPLE = 8'h52;
  `include "machine.svh"
  task automatic image();
    i(JAL,   0,  0,  'h4);            // 000: jal x0, 0x4      reset vector: enter start-up
    i(LUI,   2,  0,  'h80010);        // 004: lui x2, 0x80010      sp: first free byte above SRAM
    i(LUI,   8,  0,  'h80000);        // 008: lui x8, 0x80000      SRAM base
    i(LW,    6,  0,  408);            // 00c: lw x6, 408(x0)      load the ROM initializer
    i(SW,    6,  8,  0);              // 010: sw x6, 0(x8)      initialize source word
    i(SW,    0,  8,  4);              // 014: sw x0, 4(x8)      clear destination
    i(ADDI,  5,  0,  384);            // 018: addi x5, x0, 384
    i(CSRW,  5,  0,  MTVEC);          // 01c: csrw mtvec, x5      install vector
    i(LUI,   9,  0,  'hc000);         // 020: lui x9, 0xc000
    i(ADDI,  5,  0,  1);              // 024: addi x5, x0, 1
    i(SW,    5,  9,  4);              // 028: sw x5, 4(x9)      priority for UART0
    i(LUI,   18, 0,  'hc002);         // 02c: lui x18, 0xc002
    i(ADDI,  5,  0,  2);              // 030: addi x5, x0, 2
    i(SW,    5,  18, 0);              // 034: sw x5, 0(x18)      enable source one
    i(LUI,   19, 0,  'hc200);         // 038: lui x19, 0xc200
    i(LUI,   20, 0,  'h10000);        // 03c: lui x20, 0x10000
    i(LUI,   21, 0,  'h10006);        // 040: lui x21, 0x10006
    i(LUI,   22, 0,  'h10001);        // 044: lui x22, 0x10001
    i(LUI,   5,  0,  'h1);            // 048: lui x5, 0x1
    i(ADDI,  5,  5,  -2048);          // 04c: addi x5, x5, -2048
    i(CSRS,  5,  0,  MIE);            // 050: csrs mie, x5
    i(ADDI,  5,  0,  8);              // 054: addi x5, x0, 8
    i(CSRS,  5,  0,  MSTATUS);        // 058: csrs mstatus, x5
    i(ADDI,  6,  30, 0);              // 05c: addi x6, x30, 0
    i(BEQ,   6,  0,  'h5c);           // 060: beq x6, x0, 0x5c      handler sets x30 when the input arrives
    i(SW,    8,  21, 0);              // 064: sw x8, 0(x21)
    i(ADDI,  5,  8,  4);              // 068: addi x5, x8, 4
    i(SW,    5,  21, 4);              // 06c: sw x5, 4(x21)
    i(ADDI,  5,  0,  4);              // 070: addi x5, x0, 4
    i(SW,    5,  21, 8);              // 074: sw x5, 8(x21)
    i(ADDI,  5,  0,  1);              // 078: addi x5, x0, 1
    i(SW,    5,  21, 12);             // 07c: sw x5, 12(x21)      start after all descriptor words
    i(LUI,   18, 0,  'hc001);         // 080: lui x18, 0xc001
    i(LW,    5,  18, 0);              // 084: lw x5, 0(x18)
    i(ANDI,  5,  5,  32);             // 088: andi x5, x5, 32
    i(BEQ,   5,  0,  'h84);           // 08c: beq x5, x0, 0x84
    i(SW,    30, 22, 8);              // 090: sw x30, 8(x22)      ask board to gate the core
    i(SW,    0,  22, 8);              // 094: sw x0, 8(x22)      withdraw sleep request before clearing wake
    i(LW,    10, 8,  4);              // 098: lw x10, 4(x8)      read back the copy after waking
    i(SW,    10, 20, 0);              // 09c: sw x10, 0(x20)      send low byte to console
    i(JAL,   0,  0,  'ha0);           // 0a0: jal x0, 0xa0
    at('h180);
    i(LW,    28, 19, 4);              // 180: lw x28, 4(x19)      claim
    i(LW,    29, 20, 12);             // 184: lw x29, 12(x20)      pop input
    i(SW,    29, 8,  0);              // 188: sw x29, 0(x8)      publish sample
    i(SW,    28, 19, 4);              // 18c: sw x28, 4(x19)      complete
    i(ADDI,  30, 0,  1);              // 190: addi x30, x0, 1
    i(MRET,  0,  0,  0);              // 194: mret
    i(WORD,  0,  0,  32'h00001234);   // 198: .word 0x00001234
  endtask
  int slept, held_pc, held_edges, prior_edges;
  initial begin
    image(); power_on(); reset_n=0; boot();

    board_sends(36,SAMPLE);
    while (!stopped && !traps && ticks<500) begin
      if (pc==BREAK_PC) begin
        $display("break pc=%08h ticks=%0d sp=%08h source=%08h copy=%08h",pc,ticks,x[2],ram[0],ram[1]);
        $finish;
      end
      case(pc)
        'h4: $display("edge=%0d start pc=%08h sp=%08h source=%08h copy=%08h",aon_edges,pc,x[2],ram[0],ram[1]);
        'h20: $display("edge=%0d drivers pc=%08h sp=%08h source=%08h copy=%08h",aon_edges,pc,x[2],ram[0],ram[1]);
        'h64: $display("edge=%0d copy pc=%08h sp=%08h source=%08h copy=%08h",aon_edges,pc,x[2],ram[0],ram[1]);
        'h94: $display("edge=%0d resume pc=%08h sp=%08h source=%08h copy=%08h",aon_edges,pc,x[2],ram[0],ram[1]);
        default: ;
      endcase
      prior_edges=core_edges;
      step(); io_sel=0; #1;
      if (core_edges!=prior_edges+1) $fatal(1,"instruction without core edge");

      if (gpio_out[0] && !slept) begin
        held_edges=core_edges; held_pc=pc;
        $display("edge=%0d sleep pc=%08h",aon_edges,pc);
        repeat(4) pulse();
        button=1;
        while (!pending && aon_edges<600) pulse();
        slept=1;
        $display("edge=%0d wake pending=%b gated_edges=%0d pc=%08h",aon_edges,pending,core_edges-held_edges,pc);
        if (!pending || core_edges!=held_edges || pc!=held_pc) $fatal(1,"sleep boundary");
        serviced=1;
      end
    end

    if (!stopped || !slept || traps || taken!=1 || ram[1]!=={24'b0,SAMPLE} || uart_text!=$sformatf("%c",SAMPLE)) $fatal(1,"application failure");
    $display("copy=%08h console=%s interrupts=%0d exceptions=%0d",ram[1],uart_text,taken,traps);
    $finish;
  end
endmodule
Read included file: slices.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

// 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

// ap_soc teaching policy. Input tick is an enable from the supervision clock.
// A privileged boot writer may arm once. Reset request persists until reset.
module watchdog_supervisor (
  input logic clk, reset_n, tick, debug_halt, dev_mode, privileged,
  input logic psel, penable, pwrite,
  input logic [11:0] offset,
  input logic [31:0] pwdata,
  output logic armed, irq, reset_req,
  output logic [3:0] remaining
);
  localparam KEY = 0, CONTROL = 4, SERVICE = 8;
  localparam RELOAD = 6, OPEN = 3;
  logic first_key, unlocked;
  logic [1:0] grace;
  wire write_word = psel && penable && pwrite;
  wire arm = write_word && privileged && unlocked && offset == CONTROL && pwdata == 1;
  wire kick = write_word && offset == SERVICE && pwdata == 1;

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      first_key <= 0;
      unlocked <= 0;
      armed <= 0;
      remaining <= 0;
      irq <= 0;
      reset_req <= 0;
      grace <= 0;
    end else begin
      if (write_word) begin
        first_key <= privileged && offset == KEY && pwdata == 'h51;
        unlocked <= privileged && first_key && offset == KEY && pwdata == 'ha2;
      end
      if (!armed && arm) begin
        armed <= 1;
        remaining <= RELOAD;
      end else if (armed && !reset_req && !(dev_mode && debug_halt)) begin
        if (irq) begin
          if (tick && grace == 1) reset_req <= 1;
          else if (tick) grace <= grace - 1'b1;
        end else if ((kick && remaining > OPEN) || (tick && remaining == 1 && !kick)) begin
          irq <= 1;
          grace <= 2;
          remaining <= 0;
        end else if (kick) remaining <= RELOAD;
        else if (tick) remaining <= remaining - 1'b1;
      end
    end
  end
endmodule

// 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

// A one-word boot ROM for the startup lab. Unavailable and unmapped reads
// both complete with an error. START_EDGES counts local edges after release.
module boot_rom_port #(
  parameter integer START_EDGES = 4
)(
  input  logic clk, reset_n, req,
  input  logic [31:0] addr,
  output wire ready,
  output logic valid, error,
  output logic [31:0] data
);
  integer warm_edges;
  assign ready = reset_n && warm_edges >= START_EDGES;
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      warm_edges <= 0;
      valid <= 0;
      error <= 0;
      data <= 0;
    end else begin
      if (!ready) warm_edges <= warm_edges + 1;
      valid <= req;
      if (req) begin
        error <= !ready || addr != 0;
        data <= ready && addr == 0 ? 32'h00000013 : 0;
      end
    end
  end
endmodule

// Clock-only sleep slice. The board holds the button until it is serviced.
// Inputs other than button belong to the ungated reference-clock domain.
module sleep_clock(
  input logic ref_clk, reset_n, button, sleep_request, bus_idle, serviced,
  output logic pending, output wire core_clk
);
  logic sample, synced, previous, enabled;
  always_ff @(posedge ref_clk or negedge reset_n) begin
    if (!reset_n) begin
      {sample, synced, previous} <= 0;
      pending <= 0;
    end else begin
      {previous, synced, sample} <= {synced, sample, button};
      if (synced && !previous) pending <= 1;
      else if (serviced) pending <= 0;
    end
  end

  // Model a gate which changes its decision only during the low phase.
  always_ff @(negedge ref_clk or negedge reset_n)
    if (!reset_n) enabled <= 1;
    else enabled <= !sleep_request || !bus_idle || pending;
  assign core_clk = ref_clk && enabled;
endmodule

// Four-slot peripheral timer. The prescaler top is the last count before a step.
// capture is a synchronous event strobe from the input front end.
module capture_pwm (
  input logic clk, reset_n, psel, penable, pwrite, capture,
  input logic [11:0] offset,
  input logic [31:0] pwdata,
  output logic [31:0] prdata,
  output logic [1:0] phase,
  output logic pwm, match
);
  localparam RUN = 0, DUTY = 4, CAPTURED = 8, DIV_TOP = 12, COMPARE = 16;
  logic running;
  logic [7:0] divider, prescale_top;
  logic [2:0] duty;
  logic [1:0] captured, compare_phase;
  wire write_word = psel && penable && pwrite;

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      running <= 0;
      divider <= 0;
      prescale_top <= 0;
      phase <= 0;
      duty <= 0;
      compare_phase <= 0;
      captured <= 0;
    end else begin
      if (write_word && offset == RUN) running <= pwdata[0];
      if (write_word && offset == DUTY) duty <= pwdata[2:0];
      if (write_word && offset == COMPARE) compare_phase <= pwdata[1:0];

      if (write_word && offset == DIV_TOP) begin
        prescale_top <= pwdata[7:0];
        divider <= 0;
      end else if (running) begin
        if (divider == prescale_top) begin
          divider <= 0;
          phase <= phase + 1'b1;
        end else divider <= divider + 1'b1;
      end
      if (capture) captured <= phase;
    end
  end
  assign prdata = offset == CAPTURED ? {30'b0,captured} : 0;
  assign pwm = running && phase < duty;
  assign match = running && phase == compare_phase;
endmodule

// Each 12-bit row holds four three-bit endpoint numbers, indexed by function select.
// The board table is an elaboration parameter. An empty table releases every pad.
module pad_slice #(parameter logic [47:0] ROUTES = 0) (input wire clk,reset_n,psel,penable,pwrite,sample,
  input wire [31:0] paddr,pwdata, output wire [31:0] prdata,
  input wire [3:0] gpio_data,gpio_oe, input wire uart_tx,pwm,spi_clk,
  inout wire [3:0] pad, output logic strap, output wire uart_rx,spi_in,
  output wire [3:0] capture,oe);
  localparam MUX = 32'h10004010;
  logic [7:0] sel;
  wire [3:0] rx_lines, spi_lines;
  assign prdata = paddr == MUX ? {24'b0,sel} : 0;
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      sel <= 0;
      strap <= 0;
    end else begin
      if (sample) strap <= pad[0];
      if (psel && penable && pwrite && paddr == MUX) sel <= pwdata[7:0];
    end
  end
  localparam GPIO=1, UART_TX=2, UART_RX=3, SCLK=4, MISO=5, PWM=6, CAPTURE=7;
  for (genvar p=0; p<4; p++) begin : drivers
    localparam logic [11:0] ROW = ROUTES[12*p +: 12];
    wire [1:0] field = sel[2*p +: 2];
    wire [2:0] endpoint = ROW[3*field +: 3];
    logic data, drive;
    always_comb begin
      case (endpoint)
        GPIO:    {drive,data} = {gpio_oe[p],gpio_data[p]};
        UART_TX: {drive,data} = {1'b1,uart_tx};
        SCLK:    {drive,data} = {1'b1,spi_clk};
        PWM:     {drive,data} = {1'b1,pwm};
        default: {drive,data} = 2'b00;
      endcase
    end
    assign oe[p] = drive;
    assign pad[p] = drive ? data : 1'bz;
    assign rx_lines[p] = endpoint == UART_RX ? pad[p] : 1'b1;
    assign spi_lines[p] = endpoint == MISO ? pad[p] : 1'b0;
    assign capture[p] = endpoint == CAPTURE ? pad[p] : 1'b0;
  end
  // This table assigns at most one source each to UART RX and SPI input.
  assign uart_rx = &rx_lines;
  assign spi_in = |spi_lines;
endmodule

// APB teaching slice. Aligned word transfers, no waits, one system clock.
// UART receives frame-complete bytes from the P6 receiver. SPI uses mode 0.
module serial_slice(
  input wire clk, reset_n, sel, enable, wr,
  input wire [31:0] addr, wdata,
  output logic [31:0] rdata,
  input wire rx_done, input wire [7:0] rx_data,
  output wire tx, irq, dma_req, cs_n, mosi,
  output logic sclk, input wire miso
);
  // UART0: transmit data 0x00 (write), status 0x04 (read), receive data 0x0C (read).
  // Status bits: 0 = room to transmit, 1 = a received byte waits, 2 = the receive queue is full.
  localparam UART_TXDATA = 32'h10000000, UART_STATUS = 32'h10000004, UART_RXDATA = 32'h1000000c,
             SPI_DATA = 32'h10005000, SPI_STATUS = 32'h10005004;
  wire access = sel && enable;
  logic [7:0] fifo [0:1];
  logic head, tail;
  logic [1:0] used;
  wire pop = access && !wr && addr == UART_RXDATA && used != 0;
  wire push = rx_done && (used < 2 || pop);
  assign irq = used != 0;
  assign dma_req = used == 2;
  logic [9:0] frame;
  logic [3:0] bits_left, tick;
  assign tx = frame[0];

  logic [31:0] shift;
  logic [23:0] flash_id;
  logic [5:0] clocks_left;
  logic half_tick;
  assign cs_n = clocks_left == 0;
  assign mosi = shift[31];
  always_comb begin
    case (addr)
      UART_RXDATA: rdata = irq ? fifo[head] : 0;
      UART_STATUS: rdata = {29'b0, dma_req, irq, bits_left == 0};
      SPI_DATA:    rdata = {8'b0, flash_id};
      SPI_STATUS:  rdata = {31'b0, !cs_n};
      default:     rdata = 0;
    endcase
  end
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      used <= 0;
      head <= 0;
      tail <= 0;
      frame <= '1;
      bits_left <= 0;
      tick <= 0;
      clocks_left <= 0;
      half_tick <= 0;
      sclk <= 0;
      shift <= 0;
      flash_id <= 0;
    end else begin
      if (push) begin
        fifo[tail] <= rx_data;
        tail <= !tail;
      end
      if (pop) head <= !head;
      case ({push,pop})
        2'b10: used <= used + 1'b1;
        2'b01: used <= used - 1'b1;
        default: ;
      endcase

      if (bits_left != 0) begin
        tick <= tick + 1'b1;
        if (tick == 15) begin
          frame <= {1'b1, frame[9:1]};
          bits_left <= bits_left - 1'b1;
        end
      end else if (access && wr && addr == UART_TXDATA) begin
        frame <= {1'b1, wdata[7:0], 1'b0};
        bits_left <= 10;
        tick <= 0;
      end

      if (cs_n) begin
        if (access && wr && addr == SPI_DATA) begin
          shift <= {wdata[7:0], 24'b0};
          clocks_left <= 32;
          half_tick <= 0;
        end
      end else begin
        half_tick <= !half_tick;
        if (half_tick) begin
          sclk <= !sclk;
          if (!sclk) flash_id <= {flash_id[22:0], miso};
          else begin
            shift <= shift << 1;
            clocks_left <= clocks_left - 1'b1;
          end
        end
      end
    end
  end
endmodule

// Small board model. DR and IR share the same capture/shift/pause sequencer.
// Only IDCODE and BYPASS have data paths in this fixture.
module board_tap #(parameter logic [31:0] ID = 32'h2a53_10c5) (
  input logic tck, tms, tdi, output logic tdo
);
  typedef enum {RESET, IDLE, SELECT_DR, SELECT_IR, CAPTURE, SHIFT,
                EXIT1, PAUSE_SCAN, EXIT2, UPDATE_SCAN} phase_t;
  phase_t phase = RESET;
  logic ir_branch = 0;
  logic [1:0] opcode = 1, ir_shift;
  logic [31:0] data_shift;
  always @(posedge tck) begin
    case (phase)
      RESET: if (!tms) phase <= IDLE;
      IDLE: if (tms) phase <= SELECT_DR;
      SELECT_DR: if (tms) phase <= SELECT_IR;
                 else begin phase <= CAPTURE; ir_branch <= 0; end
      SELECT_IR: if (tms) phase <= RESET;
                 else begin phase <= CAPTURE; ir_branch <= 1; end
      CAPTURE: begin
        if (ir_branch) ir_shift <= 2'b01;
        else data_shift <= (opcode == 1) ? ID : 0;
        if (tms) phase <= EXIT1; else phase <= SHIFT;
      end
      SHIFT: begin
        if (ir_branch) ir_shift <= {tdi, ir_shift[1]};
        else if (opcode == 1) data_shift <= {tdi, data_shift[31:1]};
        else data_shift[0] <= tdi;
        if (tms) phase <= EXIT1;
      end
      EXIT1: if (tms) phase <= UPDATE_SCAN; else phase <= PAUSE_SCAN;
      PAUSE_SCAN: if (tms) phase <= EXIT2;
      EXIT2: if (tms) phase <= UPDATE_SCAN; else phase <= SHIFT;
      UPDATE_SCAN: if (tms) phase <= SELECT_DR; else phase <= IDLE;
    endcase
  end
  always @(negedge tck) begin
    if (phase == RESET) opcode <= 1;
    if (phase == UPDATE_SCAN && ir_branch) opcode <= ir_shift;
    if (phase == SHIFT) tdo <= ir_branch ? ir_shift[0] : data_shift[0];
    else tdo <= 1'bz;
  end
endmodule
Read included file: machine.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  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 = 1;            // 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) 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 (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;
        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) uart_wait--;
    for (int n = 0; n < rx_planned; n++) if (rx_tick[n] == ticks && rx_count < 4) begin
      rx_queue[rx_count] = rx_plan[n];  rx_count++;
      say($sformatf("UART0 receives %02h \"%c\"", rx_plan[n], rx_plan[n]));
    end
    if (dma_left != 0) 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, 3'b0, 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));
  logic        wdg_write;                      // one write to the watchdog commits at the next rising edge
  logic [11:0] wdg_offset;
  wire         wdg_armed, wdg_reset;
  wire  [3:0]  wdg_left;                       // ticks left before the warning
  wire         wdg_tick = (mtime[4:0] == 5'd31);   // the supervision tick: one in every 32 clock ticks (a lab number)
  watchdog_supervisor wdg (.clk(clk), .reset_n(reset_n), .tick(wdg_tick), .debug_halt(1'b0), .dev_mode(1'b0), .privileged(1'b1),
                           .psel(wdg_write), .penable(wdg_write), .pwrite(wdg_write), .offset(wdg_offset), .pwdata(dev_wdata),
                           .armed(wdg_armed), .irq(wdg_warn), .reset_req(wdg_reset), .remaining(wdg_left));
  bit          wdg_was_armed, wdg_was_warned;
  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 if (wr && (ad == 32'h1000_3000 || ad == 32'h1000_3004 || ad == 32'h1000_3008)) begin   // the watchdog: writes only
      wdg_offset = ad[11:0];  dev_wdata = wd;  wdg_write = 1;
      if (ad[3:0] == 4'h8) say($sformatf("watchdog kick, %0d ticks were left", wdg_left));
    end
    else if ((ad == 'h10002000 || ad == 'h10002004 || ad == 'h10004010 ||
                  ad == 'h10005000 || ad == 'h10005004)) begin
      io_addr = ad; io_data = wd; io_wr = wr; io_sel = 1;
      #1; bus_rdata = spi_data;
    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 && !wdg_armed) 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;
    wdg_write = 0;
    if (wdg_armed && !wdg_was_armed) say($sformatf("watchdog armed, %0d ticks left", wdg_left));
    if (wdg_warn && !wdg_was_warned) say("watchdog early warning: source 6 asks ap_plic");
    if (wdg_reset) say("watchdog reset request: the chip resets here");
    wdg_was_armed = wdg_armed;  wdg_was_warned = wdg_warn;
  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
    wdg_write = 0;  wdg_offset = 0;  wdg_was_armed = 0;  wdg_was_warned = 0;
  endtask
  task automatic run();
    while (!stopped && !wdg_reset && steps + traps + taken < 400) step();
  endtask
  bit supply, osc_ok, lock_ok, button, serviced, io_sel, io_wr;
  logic [31:0] io_addr, io_data;
  wire osc, pll, sampled, strap, fabric, core, ready, pending, gated;
  wire [31:0] spi_data;
  wire pwm, miso, cs_n;
  wire [3:0] pads, oe;
  ap_crg_boot sequencer(clk,supply,osc_ok,lock_ok,1'b0,1'b1,ready,1'b0,osc,pll,sampled,strap,fabric,core);
  boot_rom_port availability(clk,fabric,1'b0,32'b0,ready,,,);
  sleep_clock gate(clk,reset_n,button,gpio_out[0],1'b1,serviced,pending,gated);
  capture_pwm timer(clk,reset_n,io_sel && io_addr[31:12]=='h10002,io_sel,io_wr,1'b0,io_addr[11:0],io_data,,,pwm,);
  serial_slice serial(clk,reset_n,io_sel,io_sel,io_wr,io_addr,io_data,spi_data,1'b0,8'b0,,,,cs_n,,,1'b1);
  pad_slice #(.ROUTES(48'h180)) mux(clk,reset_n,io_sel,io_sel,io_wr,1'b0,io_addr,io_data,,4'b0,4'b0,1'b1,pwm,1'b0,pads,,,,,oe);
  bit tck,tms;
  wire tdo;
  board_tap tap(tck,tms,1'b0,tdo);
  task automatic shift_edge(input bit mode);
    tms=mode; #1; tck=1; #1; tck=0; #1;
  endtask
  logic [31:0] idcode;
  task automatic identify();
    shift_edge(0); shift_edge(1); shift_edge(0); shift_edge(0);
    for (int i=0;i<32;i++) begin idcode[i]=tdo; shift_edge(i==31); end
  endtask
  int aon_edges, core_edges, pad_edges;
  always @(posedge clk) aon_edges++;
  always @(posedge gated) core_edges++;
  always @(posedge pads[0]) if (oe[0]) pad_edges++;
  task automatic pulse();
    #1; clk=1; #1; clk=0; #1;
  endtask
  task automatic boot();
    supply=1;
    repeat(12) begin
      if (osc) osc_ok=1;
      if (pll) lock_ok=1;
      pulse();
      $display("edge=%0d boot osc=%b pll=%b strap_valid=%b fabric=%b ready=%b core=%b",aon_edges,osc,pll,sampled,fabric,ready,core);
      if (core) begin
        reset_n=1;
        pc=strap ? 32'h80000000 : 0;
        if (pc!=0 || kind[0]!=JAL) $fatal(1,"first fetch");
        pulse();
        $display("edge=%0d fetch pc=%08h jump_target=%08h",aon_edges,pc,fc[0]);
        disable boot;
      end
    end
    $fatal(1,"boot timed out");
  endtask

Common Mistakes

Wrong Interpret a source number as an enable mask.

The ID names a bit position.

Fix Shift one left by the source number.

Wrong Use the size as the last offset.

The base byte already belongs to the window.

Fix Subtract one before forming the inclusive upper bound.

Remember

  • Check the window, register and side effect in sequence.
  • Follow both the control and payload paths of DMA.
  • Tie outside observations to their pin functions and clock domains.

Practice

Report a problem with this page