File size: 492,141 Bytes
e6c3ac6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | {"repo": "lowRISC/ibex", "pr_id": 2250, "review_result": {"passed": false, "checks": {"describes_correct_behavior": false, "no_patch_leakage": true, "sufficient_for_diagnosis": true}, "reasoning": "The spec does not use must/shall/should modal verbs to describe correct behavior, but it avoids patch leakage and includes a behavioral assertion about error output when checks disabled."}, "generated_spec": "# Behavioral Design Specification: FPGA Register File\n\n## Overview\n\nThis module implements a RISC‑V register file intended for FPGA synthesis. It contains either 31 or 15 general-purpose registers, each 32‑bits wide. Register `x0` is permanently tied to a constant value (by default zero); writes to it have no effect and reads from it always return that constant value.\n\nThe register file provides two independent read ports and one write port. Read data is available in the same clock cycle the address is presented; there is no forwarding path from the write port to the read ports. Consequently, if a register is both read and written in the same cycle, the read returns the **value present before the write** takes effect.\n\nThe design uses synchronous write and combinational (asynchronous) read semantics, allowing FPGA synthesis tools to infer dedicated RAM primitives (e.g., Xilinx RAM32M). The module supports optional error‑checking features that can detect certain illegal access patterns.\n\n## Functional Interface\n\n- **Clock and Reset**: \n The register file operates on the rising edge of a single clock. The reset signal is present only for compatibility and is **not used** by this implementation; the register file powers‑up with all registers initialized to a known constant value (see *Initialization*).\n\n- **Read Ports** (two ports, denoted R1 and R2): \n Each port receives a 5‑bit read address and outputs the corresponding register’s contents in the same clock cycle. \n - If the address is zero, the output is the constant value `WordZeroVal` (default 0). \n - If the address is non‑zero and points to a valid register, the output is the current value of that register. \n - There is no data dependency between simultaneous reads and writes: a read sees the state **before** any concurrent write completes.\n\n- **Write Port** (one port, denoted W1): \n The write port consists of a write address, write data, and a write enable signal. \n - A write is performed on the rising clock edge only when: \n - the write enable is asserted, **and** \n - the write address is **not** zero. \n - Writes to address zero are always ignored. \n - Data written replaces the content of the addressed register on the clock edge.\n\n- **Error Output**: \n A single error indication is asserted (`1`) when any of the optional error detection checks fails. In the absence of those checks, the error output is always `0`. (See *Error Detection* for the conditions that cause an error.)\n\n## Read Operations\n\n- **Combinational read**: The output value for each read port settles within the same clock cycle after the address is applied. \n- **Zero register**: Reading address 0 does **not** access the internal register array; the output is forced to the value of the `WordZeroVal` parameter. \n- **No forwarding**: Because reads are combinational and writes are synchronous, a read that occurs in the same cycle as a write to the same address obtains the **old** value (the value stored before the write clock edge). This is true regardless of the relative order of the read address and write enable in that cycle.\n\n## Write Operations\n\n- **Synchronous write**: The register file updates only on the rising edge of the clock. \n- **Write enable gating**: An internal write is performed **only** when the write enable signal is asserted and the write address is non‑zero. \n- **Write to register zero**: Even if the write enable is asserted, a write address of zero is silently ignored. No internal state changes.\n\n## Error Detection\n\nThe module can be configured to detect two classes of illegal access conditions via the `WrenCheck` and `RdataMuxCheck` parameters. When enabled, the error output is asserted (`1`) if any of the following conditions occurs:\n\n### 1. Spurious Write Enable Glitch Detection (`WrenCheck` enabled)\n\n- A spurious write enable is defined as a situation where the write enable signal is sampled high at the clock edge **when it should not be active**. \n- The detection logic compares the write enable sampled at the clock edge with the intended write enable. If they differ (i.e., the sampled enable is high but the intended enable is low), an error is flagged.\n\n### 2. Read Address One‑Hot Checking (`RdataMuxCheck` enabled)\n\n- For each read port, the supplied address is checked to ensure it is correctly formed as a one‑hot encoded value (exactly one bit high). \n- Glitches or non‑one‑hot patterns on the read address bus cause the corresponding error flag to be asserted. \n- Additionally, when this check is enabled, the read data multiplexer is implemented using a one‑hot select structure (instead of a binary decoder), which itself can be checked for correct operation.\n\n### Error Aggregation\n\nThe error output is the logical OR of: \n- any read address one‑hot error (per port), \n- any spurious write enable error.\n\nWhen the corresponding check is disabled, the respective error signal is forced to `0`, so the error output only reflects enabled checks.\n\n## Initialization and Reset\n\n- **Power‑up / Initialization**: All registers in the register file are **initialized** to the value of the `WordZeroVal` parameter (default `0`) at the start of simulation or after configuration. This initialization occurs once and does **not** depend on the reset signal. \n- **Reset signal**: The reset input (`rst_ni`) is not used for any functional purpose and is tied off internally. There is no requirement to assert reset for correct operation.\n\n## Parameter Impacts\n\n| Parameter | Values | Effect on Behavior |\n|------------------|--------|-------------------|\n| `RV32E` | 0 or 1 | When `1`, only 15 registers are implemented (address bits [3:0] are used; address bit 4 is ignored). When `0`, all 31 registers are available. Register `x0` is still handled specially. |\n| `DataWidth` | integer (default 32) | Determines the width of all registers and data paths. |\n| `WordZeroVal` | logic vector of `DataWidth` | The constant value returned when reading address 0. Also the initial value loaded into all registers at startup. |\n| `WrenCheck` | 0 or 1 | Enables or disables the spurious write enable detection (see *Error Detection*). |\n| `RdataMuxCheck` | 0 or 1 | Enables or disables the one‑hot read address checking and the one‑hot‑based read multiplexer (see *Error Detection*). |\n| `DummyInstructions` | 0 or 1 | This parameter is present for compatibility with other register file flavors but has **no effect** on the FPGA register file’s behavior. The associated input signals are tied off. |\n\n## Additional Notes\n\n- The module does **not** use the test enable or dummy instruction signals; these are wired to unused logic. \n- The register file is designed to be synthesizable into FPGA block RAM (BRAM) or distributed RAM primitives. Asynchronous reads and synchronous writes are the natural model for such primitives. \n- There is **no write‑to‑read forwarding**; software or hardware must insert appropriate stalls or dependencies to avoid reading the wrong value when a write and read to the same register occur in the same cycle.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2018 ETH Zurich and University of Bologna, see also CREDITS.md.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * RISC-V register file\n *\n * Register file with 31 or 15x 32 bit wide registers. Register 0 is fixed to 0.\n *\n * This register file is designed to make FPGA synthesis tools infer RAM primitives. For Xilinx\n * FPGA architectures, it will produce RAM32M primitives. Other vendors have not yet been tested.\n */\nmodule ibex_register_file_fpga #(\n parameter bit RV32E = 0,\n parameter int unsigned DataWidth = 32,\n parameter bit DummyInstructions = 0,\n parameter bit WrenCheck = 0,\n parameter bit RdataMuxCheck = 0,\n parameter logic [DataWidth-1:0] WordZeroVal = '0\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n input logic test_en_i,\n input logic dummy_instr_id_i,\n input logic dummy_instr_wb_i,\n\n //Read port R1\n input logic [ 4:0] raddr_a_i,\n output logic [DataWidth-1:0] rdata_a_o,\n //Read port R2\n input logic [ 4:0] raddr_b_i,\n output logic [DataWidth-1:0] rdata_b_o,\n // Write port W1\n input logic [ 4:0] waddr_a_i,\n input logic [DataWidth-1:0] wdata_a_i,\n input logic we_a_i,\n\n // This indicates whether spurious WE or non-one-hot encoded raddr are detected.\n output logic err_o\n);\n\n localparam int ADDR_WIDTH = RV32E ? 4 : 5;\n localparam int NUM_WORDS = 2 ** ADDR_WIDTH;\n\n logic [DataWidth-1:0] mem[NUM_WORDS];\n logic we; // write enable if writing to any register other than R0\n\n logic [DataWidth-1:0] mem_o_a, mem_o_b;\n\n // WE strobe and one-hot encoded raddr alert.\n logic oh_raddr_a_err, oh_raddr_b_err, oh_we_err;\n assign err_o = oh_raddr_a_err || oh_raddr_b_err || oh_we_err;\n\n if (RdataMuxCheck) begin : gen_rdata_mux_check\n // Encode raddr_a/b into one-hot encoded signals.\n logic [NUM_WORDS-1:0] raddr_onehot_a, raddr_onehot_b;\n logic [NUM_WORDS-1:0] raddr_onehot_a_buf, raddr_onehot_b_buf;\n prim_onehot_enc #(\n .OneHotWidth(NUM_WORDS)\n ) u_prim_onehot_enc_raddr_a (\n .in_i (raddr_a_i),\n .en_i (1'b1),\n .out_o (raddr_onehot_a)\n );\n\n prim_onehot_enc #(\n .OneHotWidth(NUM_WORDS)\n ) u_prim_onehot_enc_raddr_b (\n .in_i (raddr_b_i),\n .en_i (1'b1),\n .out_o (raddr_onehot_b)\n );\n\n // Buffer the one-hot encoded signals so that the checkers\n // are not optimized.\n prim_buf #(\n .Width(NUM_WORDS)\n ) u_prim_buf_raddr_a (\n .in_i (raddr_onehot_a),\n .out_o(raddr_onehot_a_buf)\n );\n\n prim_buf #(\n .Width(NUM_WORDS)\n ) u_prim_buf_raddr_b (\n .in_i (raddr_onehot_b),\n .out_o(raddr_onehot_b_buf)\n );\n\n // SEC_CM: DATA_REG_SW.GLITCH_DETECT\n // Check the one-hot encoded signals for glitches.\n prim_onehot_check #(\n .AddrWidth(ADDR_WIDTH),\n .OneHotWidth(NUM_WORDS),\n .AddrCheck(1),\n // When AddrCheck=1 also EnableCheck needs to be 1.\n .EnableCheck(1)\n ) u_prim_onehot_check_raddr_a (\n .clk_i,\n .rst_ni,\n .oh_i (raddr_onehot_a_buf),\n .addr_i (raddr_a_i),\n // Set enable=1 as address is always valid.\n .en_i (1'b1),\n .err_o (oh_raddr_a_err)\n );\n\n prim_onehot_check #(\n .AddrWidth(ADDR_WIDTH),\n .OneHotWidth(NUM_WORDS),\n .AddrCheck(1),\n // When AddrCheck=1 also EnableCheck needs to be 1.\n .EnableCheck(1)\n ) u_prim_onehot_check_raddr_b (\n .clk_i,\n .rst_ni,\n .oh_i (raddr_onehot_b_buf),\n .addr_i (raddr_b_i),\n // Set enable=1 as address is always valid.\n .en_i (1'b1),\n .err_o (oh_raddr_b_err)\n );\n\n // MUX register to rdata_a/b_o according to raddr_a/b_onehot.\n prim_onehot_mux #(\n .Width(DataWidth),\n .Inputs(NUM_WORDS)\n ) u_rdata_a_mux (\n .clk_i,\n .rst_ni,\n .in_i (mem),\n .sel_i (raddr_onehot_a),\n .out_o (mem_o_a)\n );\n\n prim_onehot_mux #(\n .Width(DataWidth),\n .Inputs(NUM_WORDS)\n ) u_rdata_b_mux (\n .clk_i,\n .rst_ni,\n .in_i (mem),\n .sel_i (raddr_onehot_b),\n .out_o (mem_o_b)\n );\n\n assign rdata_a_o = (raddr_a_i == '0) ? WordZeroVal : mem_o_a;\n assign rdata_b_o = (raddr_b_i == '0) ? WordZeroVal : mem_o_b;\n end else begin : gen_no_rdata_mux_check\n assign rdata_a_o = (raddr_a_i == '0) ? WordZeroVal : mem[raddr_a_i];\n assign rdata_b_o = (raddr_b_i == '0) ? WordZeroVal : mem[raddr_b_i];\n\n assign oh_raddr_a_err = 1'b0;\n assign oh_raddr_b_err = 1'b0;\n end\n\n // we select\n assign we = (waddr_a_i == '0) ? 1'b0 : we_a_i;\n\n // SEC_CM: DATA_REG_SW.GLITCH_DETECT\n // This checks for spurious WE strobes on the regfile.\n if (WrenCheck) begin : gen_wren_check\n // Since the FPGA uses a memory macro, there is only one write-enable strobe to check.\n assign oh_we_err = we && !we_a_i;\n end else begin : gen_no_wren_check\n assign oh_we_err = 1'b0;\n end\n\n // Note that the SystemVerilog LRM requires variables on the LHS of assignments within\n // \"always_ff\" to not be written to by any other process. However, to enable the initialization\n // of the inferred RAM32M primitives with non-zero values, below \"initial\" procedure is needed.\n // Therefore, we use \"always\" instead of the generally preferred \"always_ff\" for the synchronous\n // write procedure.\n always @(posedge clk_i) begin : sync_write\n if (we == 1'b1) begin\n mem[waddr_a_i] <= wdata_a_i;\n end\n end : sync_write\n\n // Make sure we initialize the BRAM with the correct register reset value.\n initial begin\n for (int k = 0; k < NUM_WORDS; k++) begin\n mem[k] = WordZeroVal;\n end\n end\n\n // Reset not used in this register file version\n logic unused_rst_ni;\n assign unused_rst_ni = rst_ni;\n\n // Dummy instruction changes not relevant for FPGA implementation\n logic unused_dummy_instr;\n assign unused_dummy_instr = dummy_instr_id_i ^ dummy_instr_wb_i;\n // Test enable signal not used in FPGA implementation\n logic unused_test_en;\n assign unused_test_en = test_en_i;\n\nendmodule\n", "pr_title": "[ibex_register_file_fpga] Drop two confusing comments", "pr_body": "These were noticed by someone responding to issue #2230. I think the author's original logic was to point out that there's a path from e.g. raddr_a_i to rdata_a_o which doesn't depend on any clock, so is \"asynchronous\".\r\n\r\nBut that's the same in the other modes and also for the other register file implementations, which don't have analogous comments.\r\n\r\nDrop these ones.", "fix_patch": "diff --git a/rtl/ibex_register_file_fpga.sv b/rtl/ibex_register_file_fpga.sv\nindex 2414d771d5..65698d1c51 100644\n--- a/rtl/ibex_register_file_fpga.sv\n+++ b/rtl/ibex_register_file_fpga.sv\n@@ -150,10 +150,7 @@ module ibex_register_file_fpga #(\n assign rdata_a_o = (raddr_a_i == '0) ? WordZeroVal : mem_o_a;\n assign rdata_b_o = (raddr_b_i == '0) ? WordZeroVal : mem_o_b;\n end else begin : gen_no_rdata_mux_check\n- // async_read a\n assign rdata_a_o = (raddr_a_i == '0) ? WordZeroVal : mem[raddr_a_i];\n-\n- // async_read b\n assign rdata_b_o = (raddr_b_i == '0) ? WordZeroVal : mem[raddr_b_i];\n \n assign oh_raddr_a_err = 1'b0;\n"}
{"repo": "lowRISC/ibex", "pr_id": 2261, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": true, "sufficient_for_diagnosis": false}, "reasoning": "The generated specification correctly describes the core controller behavior without patch details, but it does not include any behavioral assertion about the simulation display message that was fixed by the patch."}, "generated_spec": "# Behavioral Specification for the Ibex Core Controller\n\n## 1. Overview\n\nThe core controller is the central finite-state machine that governs the overall execution flow of the Ibex processor. It coordinates startup from reset, instruction execution, exception and interrupt handling, debug mode entry and exit, sleep/wake‑up, and all changes to the program counter (PC). The controller interacts with the instruction fetch (IF) stage, the instruction decode/execute (ID/EX) stage, and the optional writeback (WB) stage to ensure the pipeline operates correctly under all conditions.\n\nThe controller’s behavior depends on two key parameters:\n\n- **Writeback stage present** – When a third pipeline stage (WB) is instantiated, load/store errors are reported on the instruction in WB and take priority over any exception from the ID/EX stage.\n- **Branch predictor present** – When enabled, the controller handles not‑taken branch mispredictions by requesting a PC correction and flushing the ID/EX stage.\n- **Memory ECC support** – When enabled, a load integrity error generates an internal non‑maskable interrupt (NMI) with a dedicated cause code and address.\n\n## 2. Reset and Boot Sequence\n\nAfter reset, the core must be idle. The controller shall:\n\n1. Request the PC to be set to the boot address (supplied externally).\n2. Perform one additional cycle to propagate the boot address into the fetch stage.\n3. Begin fetching instructions from the boot address.\n4. Transition to normal execution once the first instruction is available in the ID/EX stage.\n\nDuring boot, the controller shall disable all instruction requests until the PC is set.\n\n## 3. Normal Instruction Execution\n\nWhen no special events (exceptions, interrupts, debug requests, or pipeline stalls) are present, the controller shall allow instructions to proceed from IF into ID/EX and be executed.\n\n### 3.1 Branches and Jumps\n\n- When a branch is resolved as taken (branch condition true), the controller **must** request a PC change to the branch target address. \n If the branch predictor is enabled and the branch was *already* predicted taken, no additional PC change is needed – the predictor already redirected the fetch. The controller shall only update the PC if the predictor did not already do so.\n- When a branch is resolved as not taken but was predicted taken (misprediction), the controller **must** request a PC change back to the sequential next instruction and flush the ID/EX stage.\n- When a jump instruction (e.g., `jal` or `jalr`) is executed, the controller **must** always request a PC change to the jump target.\n\n### 3.2 Stalls and Pipeline Control\n\nThe controller shall stall the ID/EX stage whenever:\n\n- The ID/EX stage cannot complete a multi‑cycle instruction (e.g., load, store, multiply, divide, branch, or jump).\n- The writeback stage is not ready to accept a new result.\n\nDuring a stall, the controller shall:\n\n- Prevent the IF stage from supplying a new instruction (halt the IF).\n- Keep the current instruction in the ID/EX stage valid.\n- If the stall is due to a multi‑cycle instruction, retain the instruction’s validity until it finishes.\n\nWhen the stall condition ends, normal flow resumes.\n\n## 4. Exception Handling\n\nThe controller shall handle all synchronous exceptions that occur during instruction execution. Exceptions can arise from:\n\n- Instruction fetch error (access fault).\n- Illegal instruction.\n- Environment call (`ecall`).\n- Breakpoint (`ebreak`).\n- Load access fault.\n- Store access fault.\n\n### 4.1 Exception Priority\n\nWhen multiple exception sources are active in the same cycle, the controller must apply the following priority (highest first). The order differs depending on whether a writeback stage is present.\n\n**With writeback stage (WB present):**\n\n1. Store access fault (from instruction in WB)\n2. Load access fault (from instruction in WB)\n3. Instruction fetch error\n4. Illegal instruction\n5. Environment call (`ecall`)\n6. Breakpoint (`ebreak`)\n\n**Without writeback stage:**\n\n1. Instruction fetch error\n2. Illegal instruction\n3. Environment call (`ecall`)\n4. Breakpoint (`ebreak`)\n5. Store access fault\n6. Load access fault\n\n### 4.2 Exception Processing\n\nWhen a non‑maskable exception is detected and no higher‑priority exception is pending, the controller shall:\n\n- Flush the pipeline: discard the instruction in the ID/EX stage and halt IF.\n- Set the PC to the exception handler address (from `mtvec` CSR).\n- Save the appropriate return PC (from the ID/EX stage, or from the WB stage for load/store faults when WB is present) into `mepc`.\n- Save the exception cause into `mcause`.\n- Save `mstatus.MIE` into `mstatus.MPIE` and clear `mstatus.MIE`.\n- Optionally set `mtval` to the faulting address or instruction encoding, depending on the exception type.\n- Transition back to normal execution after the PC is set and CSRs are updated.\n\nFor an **`ebreak` instruction** that would normally raise a breakpoint exception, the controller shall instead enter debug mode if the core is not yet in debug mode and the appropriate debug CSR bits (`ebreakm` or `ebreaku`) are set. In that case the exception path is overridden by a debug entry (see Section 6).\n\n### 4.3 Handling of `mret` and `dret`\n\n`mret` and `dret` are treated as special instructions that cause a pipeline flush:\n\n- **`mret`** : Restore the PC from `mepc`, restore `mstatus.MIE` from `mstatus.MPIE`, and if the core is currently handling an NMI, exit NMI mode.\n- **`dret`** : Restore the PC from `dpc` and exit debug mode.\n\nBoth instructions flush the ID/EX stage and halt IF before the return address is fetched.\n\n## 5. Interrupt Handling\n\nThe controller shall support the following interrupt sources, ordered by priority (high to low):\n\n1. Non‑maskable interrupt (NMI) – external or internal.\n2. Fast local interrupts (15 sources, `irq_fast[14:0]`).\n3. External interrupt (`irq_external`).\n4. Software interrupt (`irq_software`).\n5. Timer interrupt (`irq_timer`).\n\n### 5.1 Interrupt Enable Conditions\n\nAn interrupt may only be taken when:\n\n- The core is **not** in debug mode.\n- The core is **not** single‑stepping.\n- The core is **not** already handling an NMI (no nesting).\n- The global interrupt enable (`mstatus.MIE`) is set, **or** the core is in User Mode (U‑Mode), where interrupts are always enabled regardless of `MIE` (since `MIE` only applies in M‑Mode).\n\nThe NMI is always enabled and ignores `mstatus.MIE` and `mie` CSR settings.\n\n### 5.2 Interrupt Taking Procedure\n\nWhen an interrupt condition is met and no higher‑priority event (exception or debug) is pending, the controller shall:\n\n- Halt the IF stage to prevent new instructions from being fetched.\n- Wait for any currently executing instruction in ID/EX or WB to complete (including any pending loads or stores) before flushing the pipeline.\n- Set the PC to the interrupt handler address: \n - For NMI: `mtvec` + offset 0x7C. \n - For fast interrupts: `mtvec` + 4 × (16 + interrupt ID). \n - For external, software, or timer interrupts: `mtvec` + 4 × interrupt ID.\n- Save the current PC (from the IF stage) into `mepc`.\n- Save the interrupt cause into `mcause`.\n- Save `mstatus.MIE` into `mstatus.MPIE` and clear `mstatus.MIE`.\n- If an internal NMI (e.g., load integrity error) is taken, set `mtval` to the faulting address.\n- Enter NMI mode when an NMI is taken (both external and internal). In NMI mode, all further interrupts are ignored until NMI mode is exited by `mret`.\n\n### 5.3 Internal Interrupts (Load Integrity Error)\n\nWhen memory ECC protection is enabled, a load response with an integrity error shall set a pending internal NMI. The controller must:\n\n- Record the address of the faulting load.\n- Assert the internal NMI request.\n- The NMI is taken at most one instruction after the faulting load; a subsequent memory operation may execute before the interrupt is taken.\n\nUpon entering the internal NMI handler, the pending flag is automatically cleared. The external NMI has higher priority; if an external NMI arrives while an internal NMI is pending, the external NMI is taken first and the internal NMI remains pending.\n\n## 6. Debug Support\n\nDebug mode entry can be triggered by:\n\n- An external `debug_req` signal.\n- Hardware breakpoint (trigger match) when debug triggers are enabled.\n- Single‑step mode (dcsr.step = 1) after every completed instruction.\n- An `ebreak` instruction when the corresponding debug CSR bit (`ebreakm`/`ebreaku`) is set.\n\n### 6.1 Priority of Debug Entry\n\nDebug entries have the following priority (high to low):\n\n1. `ebreak` with debug entry enabled.\n2. External `debug_req`.\n3. Single‑step.\n4. Trigger match.\n\nA trigger match is only honored if no higher‑priority debug event or exception is pending and the instruction that caused the match is actually executing (i.e., not flushed by a higher‑priority event).\n\n### 6.2 Debug Mode Entry Sequence\n\nWhen the controller decides to enter debug mode, it shall:\n\n- **If entering from a debug event that does not involve an `ebreak` (e.g., debug_req, single‑step, or trigger):** \n - Flush the ID/EX stage. \n - Set the PC to the debug exception address (`DmHaltAddr`). \n - Save the current PC (from IF stage) into `dpc`. \n - Save the debug cause into `dcsr.cause`. \n - Set the debug mode flag. \n - Flush the IF stage.\n\n- **If entering due to an `ebreak` instruction with debug entry enabled (and core not already in debug mode):** \n - Flush the ID/EX stage. \n - Set the PC to the debug exception address. \n - Save the PC of the `ebreak` instruction (from ID stage) into `dpc`. \n - Save the debug cause into `dcsr.cause`. \n - Set the debug mode flag. \n - Do **not** take the breakpoint exception.\n\n- **If an `ebreak` occurs while already in debug mode:** \n - The controller shall re‑enter debug mode by saving the current PC to `dpc` and updating `dcsr.cause`. The core remains in debug mode.\n\nAfter entering debug mode, the controller returns to normal instruction execution, but the core is now in debug mode and reacts as defined by the RISC‑V debug specification.\n\n### 6.3 Debug Mode Exit\n\nDebug mode is exited by executing a `dret` instruction, which restores the PC from `dpc` and clears the debug mode flag.\n\n### 6.4 Interrupts and Exceptions in Debug Mode\n\nWhile in debug mode:\n\n- All interrupts (including NMI) are ignored.\n- Synchronous exceptions that occur inside debug mode are handled using the debug exception address (`DmExceptionAddr`) rather than the normal `mtvec`. The core remains in debug mode.\n\n## 7. WFI and Sleep\n\nThe `wfi` instruction puts the core into a low‑power sleep state. The controller shall:\n\n- Flush the ID/EX stage and halt IF.\n- Enter a sleep state where no instructions are fetched.\n- Remain in sleep until one of the following wake‑up events occurs:\n - Any unmasked interrupt (including NMI) becomes pending.\n - External debug request is asserted.\n - The core was already in debug mode or single‑step mode when `wfi` was executed (in that case `wfi` acts as a NOP and exits sleep immediately).\n- Upon wake‑up, the controller shall restart instruction fetch from the current PC (no interrupt/exception is taken at this point – the core reverts to normal execution unless an interrupt is also pending, in which case the interrupt will be taken in the next cycle).\n\n## 8. Pipeline Flush Behaviors\n\nThe controller must flush the ID/EX stage under the following circumstances:\n\n- A taken branch or jump that was not predicted (or a mispredicted branch).\n- An exception or interrupt is taken.\n- An `mret` or `dret` instruction is executed.\n- A `wfi` instruction is executed (to prevent any previously fetched instruction from executing).\n- A CSR‑related pipeline flush is requested (e.g., after modifying `mstatus` or `mtvec`).\n- When entering or exiting debug mode (pipeline must be empty to ensure consistent debug state).\n\nDuring a flush, the controller:\n\n- Sets a signal to clear the instruction valid flag in the ID/EX stage.\n- Halts the IF stage so no new instruction enters ID/EX.\n- For exceptions and interrupts, the PC is set to the appropriate handler address in the same cycle as the flush.\n\n## 9. Distinction Between WB and ID/EX Exceptions (Writeback Stage)\n\nWhen a writeback (WB) stage is present, load/store faults are detected on the instruction in WB, not in ID/EX. The controller must:\n\n- Prioritize a load/store fault from WB over any exception from ID/EX.\n- When a WB exception is taken, save the return PC from the WB stage into `mepc` (not from ID/EX).\n- Indicate that the instruction in ID/EX must not be executed if a WB exception occurs.\n\nWhen no writeback stage exists, load/store faults occur in ID/EX and are handled like any other ID/EX exception.\n\n## 10. CSR Save and Restore Signals\n\nThe controller shall generate the necessary strobes to save and restore CSR state at the appropriate times:\n\n- **Save IF PC**: when an interrupt or debug entry is taken (save PC from IF stage).\n- **Save ID PC**: when an exception is taken for a non‑load/store fault (save PC from ID/EX stage).\n- **Save WB PC**: when a load/store fault occurs and a WB stage is present (save PC from WB stage).\n- **Save CSR cause**: whenever an exception or interrupt is taken.\n- **Restore on `mret`**: restore `mepc` and `mstatus.MPIE`.\n- **Restore on `dret`**: restore `dpc` and clear debug mode.\n- **Save debug CSR**: when entering debug mode (save cause to `dcsr` and PC to `dpc`).\n\nThese saves and restores are performed in coordination with the PC set and pipeline flush actions.\n\n## 11. Performance Monitoring\n\nThe controller shall provide output flags for performance counters:\n\n- **Jump taken**: asserted when a jump instruction (any variant) resolves as taken.\n- **Taken branch**: asserted when a branch resolves as taken.\n\nThese outputs are used by performance counter logic elsewhere in the core.\n\n## 12. Summary of State Transitions\n\nThe controller proceeds through several major operational phases, though the exact internal states are an implementation detail. The externally visible behavior is:\n\n| Phase | Observable Action |\n|-------|-------------------|\n| Reset | Set PC to boot address, start fetch. |\n| Normal (Decode) | Allow instructions to flow, handle branches/jumps, detect special requests. |\n| Flush | Discard ID/EX instruction, wait for WB ready, then set PC and CSRs for exception/interrupt/special instruction. |\n| Interrupt Taken | Save IF PC, cause, `mstatus`, set PC to handler, enter NMI mode if NMI. |\n| Debug Taken (IF) | Save IF PC, cause, set PC to debug handler, enter debug mode. |\n| Debug Taken (ID) | Save ID PC (from ebreak), cause, set PC to debug handler, enter debug mode. |\n| Sleep | Halt pipeline, wait for wake event, then restart fetch. |\n| Boot Set | Intermediate state during reset to propagate boot address. |\n\nThe controller ensures that only one active special request (exception, interrupt, debug) is handled at a time according to the defined prioritisation rules. After handling, normal execution resumes from the appropriate PC.\n\n--- \n\n*This specification describes the required functional behavior of the Ibex core controller. It does not prescribe internal implementation details such as state encoding or exact timing of internal signals.*", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2018 ETH Zurich and University of Bologna, see also CREDITS.md.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Main controller of the processor\n */\n\n`include \"prim_assert.sv\"\n`include \"dv_fcov_macros.svh\"\n\nmodule ibex_controller #(\n parameter bit WritebackStage = 1'b0,\n parameter bit BranchPredictor = 1'b0,\n parameter bit MemECC = 1'b0\n ) (\n input logic clk_i,\n input logic rst_ni,\n\n output logic ctrl_busy_o, // core is busy processing instrs\n\n // decoder related signals\n input logic illegal_insn_i, // decoder has an invalid instr\n input logic ecall_insn_i, // decoder has ECALL instr\n input logic mret_insn_i, // decoder has MRET instr\n input logic dret_insn_i, // decoder has DRET instr\n input logic wfi_insn_i, // decoder has WFI instr\n input logic ebrk_insn_i, // decoder has EBREAK instr\n input logic csr_pipe_flush_i, // do CSR-related pipeline flush\n\n // instr from IF-ID pipeline stage\n input logic instr_valid_i, // instr is valid\n input logic [31:0] instr_i, // uncompressed instr data for mtval\n input logic [15:0] instr_compressed_i, // instr compressed data for mtval\n input logic instr_is_compressed_i, // instr is compressed\n input logic instr_bp_taken_i, // instr was predicted taken branch\n input logic instr_fetch_err_i, // instr has error\n input logic instr_fetch_err_plus2_i, // instr error is x32\n input logic [31:0] pc_id_i, // instr address\n\n // to IF-ID pipeline stage\n output logic instr_valid_clear_o, // kill instr in IF-ID reg\n output logic id_in_ready_o, // ID stage is ready for new instr\n output logic controller_run_o, // Controller is in standard instruction\n // run mode\n input logic instr_exec_i, // Execution control, when clear ID/EX\n // stage stops accepting instructions from\n // IF\n // to prefetcher\n output logic instr_req_o, // start fetching instructions\n output logic pc_set_o, // jump to address set by pc_mux\n output ibex_pkg::pc_sel_e pc_mux_o, // IF stage fetch address selector\n // (boot, normal, exception...)\n output logic nt_branch_mispredict_o, // Not-taken branch in ID/EX was\n // mispredicted (predicted taken)\n output ibex_pkg::exc_pc_sel_e exc_pc_mux_o, // IF stage selector for exception PC\n output ibex_pkg::exc_cause_t exc_cause_o, // for IF stage, CSRs\n\n // LSU\n input logic [31:0] lsu_addr_last_i, // for mtval\n input logic load_err_i,\n input logic store_err_i,\n input logic mem_resp_intg_err_i,\n output logic wb_exception_o, // Instruction in WB taking an exception\n output logic id_exception_o, // Instruction in ID taking an exception\n\n // jump/branch signals\n input logic branch_set_i, // branch set signal (branch definitely\n // taken)\n input logic branch_not_set_i, // branch is definitely not taken\n input logic jump_set_i, // jump taken set signal\n\n // interrupt signals\n input logic csr_mstatus_mie_i, // M-mode interrupt enable bit\n input logic irq_pending_i, // interrupt request pending\n input ibex_pkg::irqs_t irqs_i, // interrupt requests qualified with\n // mie CSR\n input logic irq_nm_ext_i, // non-maskeable interrupt\n output logic nmi_mode_o, // core executing NMI handler\n\n // debug signals\n input logic debug_req_i,\n output ibex_pkg::dbg_cause_e debug_cause_o,\n output logic debug_csr_save_o,\n output logic debug_mode_o,\n output logic debug_mode_entering_o,\n input logic debug_single_step_i,\n input logic debug_ebreakm_i,\n input logic debug_ebreaku_i,\n input logic trigger_match_i,\n\n output logic csr_save_if_o,\n output logic csr_save_id_o,\n output logic csr_save_wb_o,\n output logic csr_restore_mret_id_o,\n output logic csr_restore_dret_id_o,\n output logic csr_save_cause_o,\n output logic [31:0] csr_mtval_o,\n input ibex_pkg::priv_lvl_e priv_mode_i,\n\n // stall & flush signals\n input logic stall_id_i,\n input logic stall_wb_i,\n output logic flush_id_o,\n input logic ready_wb_i,\n\n // performance monitors\n output logic perf_jump_o, // we are executing a jump\n // instruction (j, jr, jal, jalr)\n output logic perf_tbranch_o // we are executing a taken branch\n // instruction\n);\n import ibex_pkg::*;\n\n ctrl_fsm_e ctrl_fsm_cs, ctrl_fsm_ns;\n\n logic nmi_mode_q, nmi_mode_d;\n logic debug_mode_q, debug_mode_d;\n dbg_cause_e debug_cause_d, debug_cause_q;\n logic load_err_q, load_err_d;\n logic store_err_q, store_err_d;\n logic exc_req_q, exc_req_d;\n logic illegal_insn_q, illegal_insn_d;\n\n // Of the various exception/fault signals, which one takes priority in FLUSH and hence controls\n // what happens next (setting exc_cause, csr_mtval etc)\n logic instr_fetch_err_prio;\n logic illegal_insn_prio;\n logic ecall_insn_prio;\n logic ebrk_insn_prio;\n logic store_err_prio;\n logic load_err_prio;\n\n logic stall;\n logic halt_if;\n logic retain_id;\n logic flush_id;\n logic exc_req_lsu;\n logic special_req;\n logic special_req_pc_change;\n logic special_req_flush_only;\n logic do_single_step_d;\n logic do_single_step_q;\n logic enter_debug_mode_prio_d;\n logic enter_debug_mode_prio_q;\n logic enter_debug_mode;\n logic ebreak_into_debug;\n logic irq_enabled;\n logic handle_irq;\n logic id_wb_pending;\n\n logic irq_nm;\n logic irq_nm_int;\n logic [31:0] irq_nm_int_mtval;\n ibex_pkg::nmi_int_cause_e irq_nm_int_cause;\n\n\n logic [3:0] mfip_id;\n logic unused_irq_timer;\n\n logic ecall_insn;\n logic mret_insn;\n logic dret_insn;\n logic wfi_insn;\n logic ebrk_insn;\n logic csr_pipe_flush;\n logic instr_fetch_err;\n\n`ifndef SYNTHESIS\n // synopsys translate_off\n // make sure we are called later so that we do not generate messages for\n // glitches\n always_ff @(negedge clk_i) begin\n // print warning in case of decoding errors\n if ((ctrl_fsm_cs == DECODE) && instr_valid_i && !instr_fetch_err_i && illegal_insn_d) begin\n $display(\"%t: Illegal instruction (hart %0x) at PC 0x%h: 0x%h\", $time, u_ibex_core.hart_id_i,\n pc_id_i, instr_is_compressed_i ? {16'b0, instr_compressed_i} : instr_i );\n end\n end\n // synopsys translate_on\n`endif\n\n ////////////////\n // Exceptions //\n ////////////////\n\n assign load_err_d = load_err_i;\n assign store_err_d = store_err_i;\n\n // Decoder doesn't take instr_valid into account, factor it in here.\n assign ecall_insn = ecall_insn_i & instr_valid_i;\n assign mret_insn = mret_insn_i & instr_valid_i;\n assign dret_insn = dret_insn_i & instr_valid_i;\n assign wfi_insn = wfi_insn_i & instr_valid_i;\n assign ebrk_insn = ebrk_insn_i & instr_valid_i;\n assign csr_pipe_flush = csr_pipe_flush_i & instr_valid_i;\n assign instr_fetch_err = instr_fetch_err_i & instr_valid_i;\n\n // This is recorded in the illegal_insn_q flop to help timing. Specifically\n // it is needed to break the path from ibex_cs_registers/illegal_csr_insn_o\n // to pc_set_o. Clear when controller is in FLUSH so it won't remain set\n // once illegal instruction is handled.\n // illegal_insn_i only set when instr_valid_i is set.\n assign illegal_insn_d = illegal_insn_i & (ctrl_fsm_cs != FLUSH);\n\n `ASSERT(IllegalInsnOnlyIfInsnValid, illegal_insn_i |-> instr_valid_i)\n\n // exception requests\n // requests are flopped in exc_req_q. This is cleared when controller is in\n // the FLUSH state so the cycle following exc_req_q won't remain set for an\n // exception request that has just been handled.\n // All terms in this expression are qualified by instr_valid_i\n assign exc_req_d = (ecall_insn | ebrk_insn | illegal_insn_d | instr_fetch_err) &\n (ctrl_fsm_cs != FLUSH);\n\n // LSU exception requests\n assign exc_req_lsu = store_err_i | load_err_i;\n\n assign id_exception_o = exc_req_d & ~wb_exception_o;\n\n // special requests: special instructions, pipeline flushes, exceptions...\n // All terms in these expressions are qualified by instr_valid_i except exc_req_lsu which can come\n // from the Writeback stage with no instr_valid_i from the ID stage\n\n // These special requests only cause a pipeline flush and in particular don't cause a PC change\n // that is outside the normal execution flow\n assign special_req_flush_only = wfi_insn | csr_pipe_flush;\n\n // These special requests cause a change in PC\n assign special_req_pc_change = mret_insn | dret_insn | exc_req_d | exc_req_lsu;\n\n // generic special request signal, applies to all instructions\n assign special_req = special_req_pc_change | special_req_flush_only;\n\n // Is there an instruction in ID or WB that has yet to complete?\n assign id_wb_pending = instr_valid_i | ~ready_wb_i;\n\n // Logic to determine which exception takes priority where multiple are possible.\n if (WritebackStage) begin : g_wb_exceptions\n always_comb begin\n instr_fetch_err_prio = 0;\n illegal_insn_prio = 0;\n ecall_insn_prio = 0;\n ebrk_insn_prio = 0;\n store_err_prio = 0;\n load_err_prio = 0;\n\n // Note that with the writeback stage store/load errors occur on the instruction in writeback,\n // all other exception/faults occur on the instruction in ID/EX. The faults from writeback\n // must take priority as that instruction is architecurally ordered before the one in ID/EX.\n if (store_err_q) begin\n store_err_prio = 1'b1;\n end else if (load_err_q) begin\n load_err_prio = 1'b1;\n end else if (instr_fetch_err) begin\n instr_fetch_err_prio = 1'b1;\n end else if (illegal_insn_q) begin\n illegal_insn_prio = 1'b1;\n end else if (ecall_insn) begin\n ecall_insn_prio = 1'b1;\n end else if (ebrk_insn) begin\n ebrk_insn_prio = 1'b1;\n end\n end\n\n // Instruction in writeback is generating an exception so instruction in ID must not execute\n assign wb_exception_o = load_err_q | store_err_q | load_err_i | store_err_i;\n end else begin : g_no_wb_exceptions\n always_comb begin\n instr_fetch_err_prio = 0;\n illegal_insn_prio = 0;\n ecall_insn_prio = 0;\n ebrk_insn_prio = 0;\n store_err_prio = 0;\n load_err_prio = 0;\n\n if (instr_fetch_err) begin\n instr_fetch_err_prio = 1'b1;\n end else if (illegal_insn_q) begin\n illegal_insn_prio = 1'b1;\n end else if (ecall_insn) begin\n ecall_insn_prio = 1'b1;\n end else if (ebrk_insn) begin\n ebrk_insn_prio = 1'b1;\n end else if (store_err_q) begin\n store_err_prio = 1'b1;\n end else if (load_err_q) begin\n load_err_prio = 1'b1;\n end\n end\n assign wb_exception_o = 1'b0;\n end\n\n `ASSERT_IF(IbexExceptionPrioOnehot,\n $onehot({instr_fetch_err_prio,\n illegal_insn_prio,\n ecall_insn_prio,\n ebrk_insn_prio,\n store_err_prio,\n load_err_prio}),\n (ctrl_fsm_cs == FLUSH) & exc_req_q)\n\n ////////////////\n // Interrupts //\n ////////////////\n\n // Internal interrupt control\n // All internal interrupts act as an NMI and go to the NMI vector. mcause is set based upon\n // irq_nm_int_cause.\n\n if (MemECC) begin : g_intg_irq_int\n logic mem_resp_intg_err_irq_pending_q, mem_resp_intg_err_irq_pending_d;\n logic [31:0] mem_resp_intg_err_addr_q, mem_resp_intg_err_addr_d;\n logic mem_resp_intg_err_irq_set, mem_resp_intg_err_irq_clear;\n logic entering_nmi;\n\n assign entering_nmi = nmi_mode_d & ~nmi_mode_q;\n\n // Load integerity error internal interrupt\n always_comb begin\n mem_resp_intg_err_addr_d = mem_resp_intg_err_addr_q;\n mem_resp_intg_err_irq_set = 1'b0;\n mem_resp_intg_err_irq_clear = 1'b0;\n\n if (mem_resp_intg_err_irq_pending_q) begin\n // Clear ECC error interrupt when it is handled. External NMI takes a higher priority so\n // don't clear the ECC error interrupt if an external NMI is present.\n if (entering_nmi & !irq_nm_ext_i) begin\n mem_resp_intg_err_irq_clear = 1'b1;\n end\n end else if (mem_resp_intg_err_i) begin\n // When an ECC error is seen set the ECC error interrupt and capture the address that saw\n // the error. If there is already an ecc error IRQ pending ignore any ECC errors coming in.\n mem_resp_intg_err_addr_d = lsu_addr_last_i;\n mem_resp_intg_err_irq_set = 1'b1;\n end\n end\n\n assign mem_resp_intg_err_irq_pending_d =\n (mem_resp_intg_err_irq_pending_q & ~mem_resp_intg_err_irq_clear) | mem_resp_intg_err_irq_set;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n mem_resp_intg_err_irq_pending_q <= 1'b0;\n mem_resp_intg_err_addr_q <= '0;\n end else begin\n mem_resp_intg_err_irq_pending_q <= mem_resp_intg_err_irq_pending_d;\n mem_resp_intg_err_addr_q <= mem_resp_intg_err_addr_d;\n end\n end\n\n // As integrity error is the only internal interrupt implement, set irq_nm_* signals directly\n // within this generate block.\n assign irq_nm_int = mem_resp_intg_err_irq_pending_q;\n assign irq_nm_int_cause = NMI_INT_CAUSE_ECC;\n assign irq_nm_int_mtval = mem_resp_intg_err_addr_q;\n end else begin : g_no_intg_irq_int\n logic unused_mem_resp_intg_err_i;\n\n assign unused_mem_resp_intg_err_i = mem_resp_intg_err_i;\n\n // No integrity checking on incoming load data so no internal interrupts\n assign irq_nm_int = 1'b0;\n assign irq_nm_int_cause = nmi_int_cause_e'(0);\n assign irq_nm_int_mtval = '0;\n end\n\n\n // Enter debug mode due to an external debug_req_i or because the core is in\n // single step mode (dcsr.step == 1). Single step must be qualified with\n // instruction valid otherwise the core will immediately enter debug mode\n // due to a recently flushed IF (or a delay in an instruction returning from\n // memory) before it has had anything to single step.\n // Also enter debug mode on a trigger match (hardware breakpoint)\n\n // Set `do_single_step_q` when a valid instruction is seen outside of debug mode and core is in\n // single step mode. The first valid instruction on debug mode entry will clear it. Hold its value\n // when there is no valid instruction so `do_single_step_d` remains asserted until debug mode is\n // entered.\n assign do_single_step_d = instr_valid_i ? ~debug_mode_q & debug_single_step_i : do_single_step_q;\n // Enter debug mode due to:\n // * external `debug_req_i`\n // * core in single step mode (dcsr.step == 1).\n // * trigger match (hardware breakpoint)\n //\n // `debug_req_i` and `do_single_step_d` request debug mode with priority. This results in a debug\n // mode entry even if the controller goes to `FLUSH` in preparation for handling an exception or\n // interrupt. `trigger_match_i` is not a priority entry into debug mode as it must be ignored\n // where control flow changes such that the instruction causing the trigger is no longer being\n // executed.\n assign enter_debug_mode_prio_d = (debug_req_i | do_single_step_d) & ~debug_mode_q;\n assign enter_debug_mode = enter_debug_mode_prio_d | (trigger_match_i & ~debug_mode_q);\n\n // Set when an ebreak should enter debug mode rather than jump to exception\n // handler\n assign ebreak_into_debug = priv_mode_i == PRIV_LVL_M ? debug_ebreakm_i :\n priv_mode_i == PRIV_LVL_U ? debug_ebreaku_i :\n 1'b0;\n\n // NMI can be produced from an external (irq_nm_i top level input) or an internal (within\n // ibex_core) source. For internal sources the cause is specified via irq_nm_int_cause.\n assign irq_nm = irq_nm_ext_i | irq_nm_int;\n\n // MIE bit only applies when in M mode\n assign irq_enabled = csr_mstatus_mie_i | (priv_mode_i == PRIV_LVL_U);\n\n // Interrupts including NMI are ignored,\n // - while in debug mode,\n // - while in NMI mode (nested NMIs are not supported, NMI has highest priority and\n // cannot be interrupted by regular interrupts),\n // - while single stepping.\n assign handle_irq = ~debug_mode_q & ~debug_single_step_i & ~nmi_mode_q &\n (irq_nm | (irq_pending_i & irq_enabled));\n\n // generate ID of fast interrupts, highest priority to lowest ID\n always_comb begin : gen_mfip_id\n mfip_id = 4'd0;\n\n for (int i = 14; i >= 0; i--) begin\n if (irqs_i.irq_fast[i]) begin\n mfip_id = i[3:0];\n end\n end\n end\n\n assign unused_irq_timer = irqs_i.irq_timer;\n\n // Record the debug cause outside of the FSM\n // The decision to enter debug_mode and the write of the cause to DCSR happen\n // in seperate steps within the FSM. Hence, there are a small number of cycles\n // where a change in external stimulus can cause the cause to be recorded incorrectly.\n assign debug_cause_d = trigger_match_i ? DBG_CAUSE_TRIGGER :\n ebrk_insn_prio & ebreak_into_debug ? DBG_CAUSE_EBREAK :\n debug_req_i ? DBG_CAUSE_HALTREQ :\n do_single_step_d ? DBG_CAUSE_STEP :\n DBG_CAUSE_NONE ;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n debug_cause_q <= DBG_CAUSE_NONE;\n end else begin\n debug_cause_q <= debug_cause_d;\n end\n end\n\n assign debug_cause_o = debug_cause_q;\n\n /////////////////////\n // Core controller //\n /////////////////////\n\n always_comb begin\n // Default values\n instr_req_o = 1'b1;\n\n csr_save_if_o = 1'b0;\n csr_save_id_o = 1'b0;\n csr_save_wb_o = 1'b0;\n csr_restore_mret_id_o = 1'b0;\n csr_restore_dret_id_o = 1'b0;\n csr_save_cause_o = 1'b0;\n csr_mtval_o = '0;\n\n // The values of pc_mux and exc_pc_mux are only relevant if pc_set is set. Some of the states\n // below always set pc_mux and exc_pc_mux but only set pc_set if certain conditions are met.\n // This avoid having to factor those conditions into the pc_mux and exc_pc_mux select signals\n // helping timing.\n pc_mux_o = PC_BOOT;\n pc_set_o = 1'b0;\n nt_branch_mispredict_o = 1'b0;\n\n exc_pc_mux_o = EXC_PC_IRQ;\n exc_cause_o = ExcCauseInsnAddrMisa; // = 6'h00\n\n ctrl_fsm_ns = ctrl_fsm_cs;\n\n ctrl_busy_o = 1'b1;\n\n halt_if = 1'b0;\n retain_id = 1'b0;\n flush_id = 1'b0;\n\n debug_csr_save_o = 1'b0;\n debug_mode_d = debug_mode_q;\n debug_mode_entering_o = 1'b0;\n nmi_mode_d = nmi_mode_q;\n\n perf_tbranch_o = 1'b0;\n perf_jump_o = 1'b0;\n\n controller_run_o = 1'b0;\n\n unique case (ctrl_fsm_cs)\n RESET: begin\n instr_req_o = 1'b0;\n pc_mux_o = PC_BOOT;\n pc_set_o = 1'b1;\n ctrl_fsm_ns = BOOT_SET;\n end\n\n BOOT_SET: begin\n // copy boot address to instr fetch address\n instr_req_o = 1'b1;\n pc_mux_o = PC_BOOT;\n pc_set_o = 1'b1;\n\n ctrl_fsm_ns = FIRST_FETCH;\n end\n\n WAIT_SLEEP: begin\n ctrl_busy_o = 1'b0;\n instr_req_o = 1'b0;\n halt_if = 1'b1;\n flush_id = 1'b1;\n ctrl_fsm_ns = SLEEP;\n end\n\n SLEEP: begin\n // instruction in IF stage is already valid\n // we begin execution when an interrupt has arrived\n instr_req_o = 1'b0;\n halt_if = 1'b1;\n flush_id = 1'b1;\n\n // normal execution flow\n // in debug mode or single step mode we leave immediately (wfi=nop)\n if (irq_nm || irq_pending_i || debug_req_i || debug_mode_q || debug_single_step_i) begin\n ctrl_fsm_ns = FIRST_FETCH;\n end else begin\n // Make sure clock remains disabled.\n ctrl_busy_o = 1'b0;\n end\n end\n\n FIRST_FETCH: begin\n // Stall because of IF miss\n if (id_in_ready_o) begin\n ctrl_fsm_ns = DECODE;\n end\n\n // handle interrupts\n if (handle_irq) begin\n // We are handling an interrupt. Set halt_if to tell IF not to give\n // us any more instructions before it redirects to the handler, but\n // don't set flush_id: we must allow this instruction to complete\n // (since it might have outstanding loads or stores).\n ctrl_fsm_ns = IRQ_TAKEN;\n halt_if = 1'b1;\n end\n\n // enter debug mode\n if (enter_debug_mode) begin\n ctrl_fsm_ns = DBG_TAKEN_IF;\n // Halt IF only for now, ID will be flushed in DBG_TAKEN_IF as the\n // ID state is needed for correct debug mode entry\n halt_if = 1'b1;\n end\n end\n\n DECODE: begin\n // normal operating mode of the ID stage, in case of debug and interrupt requests,\n // priorities are as follows (lower number == higher priority)\n // 1. currently running (multicycle) instructions and exceptions caused by these\n // 2. debug requests\n // 3. interrupt requests\n\n controller_run_o = 1'b1;\n\n // Set PC mux for branch and jump here to ease timing. Value is only relevant if pc_set_o is\n // also set. Setting the mux value here avoids factoring in special_req and instr_valid_i\n // which helps timing.\n pc_mux_o = PC_JUMP;\n\n\n // Get ready for special instructions, exceptions, pipeline flushes\n if (special_req) begin\n // Halt IF but don't flush ID. This leaves a valid instruction in\n // ID so controller can determine appropriate action in the\n // FLUSH state.\n retain_id = 1'b1;\n\n // Wait for the writeback stage to either be ready for a new instruction or raise its own\n // exception before going to FLUSH. If the instruction in writeback raises an exception it\n // must take priority over any exception from an instruction in ID/EX. Only once the\n // writeback stage is ready can we be certain that won't happen. Without a writeback\n // stage ready_wb_i == 1 so the FSM will always go directly to FLUSH.\n\n if (ready_wb_i | wb_exception_o) begin\n ctrl_fsm_ns = FLUSH;\n end\n end\n\n if (branch_set_i || jump_set_i) begin\n // Only set the PC if the branch predictor hasn't already done the branch for us\n pc_set_o = BranchPredictor ? ~instr_bp_taken_i : 1'b1;\n\n perf_tbranch_o = branch_set_i;\n perf_jump_o = jump_set_i;\n end\n\n if (BranchPredictor) begin\n if (instr_bp_taken_i & branch_not_set_i) begin\n // If the instruction is a branch that was predicted to be taken but was not taken\n // signal a mispredict.\n nt_branch_mispredict_o = 1'b1;\n end\n end\n\n // If entering debug mode or handling an IRQ the core needs to wait until any instruction in\n // ID or WB has finished executing. Stall IF during that time.\n if ((enter_debug_mode || handle_irq) && (stall || id_wb_pending)) begin\n halt_if = 1'b1;\n end\n\n if (!stall && !special_req && !id_wb_pending) begin\n if (enter_debug_mode) begin\n // enter debug mode\n ctrl_fsm_ns = DBG_TAKEN_IF;\n // Halt IF only for now, ID will be flushed in DBG_TAKEN_IF as the\n // ID state is needed for correct debug mode entry\n halt_if = 1'b1;\n end else if (handle_irq) begin\n // handle interrupt (not in debug mode)\n ctrl_fsm_ns = IRQ_TAKEN;\n // We are handling an interrupt (not in debug mode). Set halt_if to\n // tell IF not to give us any more instructions before it redirects\n // to the handler, but don't set flush_id: we must allow this\n // instruction to complete (since it might have outstanding loads\n // or stores).\n halt_if = 1'b1;\n end\n end\n\n end // DECODE\n\n IRQ_TAKEN: begin\n pc_mux_o = PC_EXC;\n exc_pc_mux_o = EXC_PC_IRQ;\n\n if (handle_irq) begin\n pc_set_o = 1'b1;\n\n csr_save_if_o = 1'b1;\n csr_save_cause_o = 1'b1;\n\n // Prioritise interrupts as required by the architecture\n if (irq_nm && !nmi_mode_q) begin\n exc_cause_o =\n irq_nm_ext_i ? ExcCauseIrqNm :\n '{irq_ext: 1'b0, irq_int: 1'b1, lower_cause: irq_nm_int_cause};\n\n if (irq_nm_int & !irq_nm_ext_i) begin\n csr_mtval_o = irq_nm_int_mtval;\n end\n\n nmi_mode_d = 1'b1; // enter NMI mode\n end else if (irqs_i.irq_fast != 15'b0) begin\n // generate exception cause ID from fast interrupt ID:\n // - first bit distinguishes interrupts from exceptions,\n // - second bit adds 16 to fast interrupt ID\n // for example ExcCauseIrqFast0 = {1'b1, 5'd16}\n exc_cause_o = '{irq_ext: 1'b1, irq_int: 1'b0, lower_cause: {1'b1, mfip_id}};\n end else if (irqs_i.irq_external) begin\n exc_cause_o = ExcCauseIrqExternalM;\n end else if (irqs_i.irq_software) begin\n exc_cause_o = ExcCauseIrqSoftwareM;\n end else begin // irqs_i.irq_timer\n exc_cause_o = ExcCauseIrqTimerM;\n end\n end\n\n ctrl_fsm_ns = DECODE;\n end\n\n DBG_TAKEN_IF: begin\n pc_mux_o = PC_EXC;\n exc_pc_mux_o = EXC_PC_DBD;\n\n // enter debug mode and save PC in IF to dpc\n // jump to debug exception handler in debug memory\n flush_id = 1'b1;\n pc_set_o = 1'b1;\n\n csr_save_if_o = 1'b1;\n debug_csr_save_o = 1'b1;\n\n csr_save_cause_o = 1'b1;\n\n // enter debug mode\n debug_mode_d = 1'b1;\n debug_mode_entering_o = 1'b1;\n\n ctrl_fsm_ns = DECODE;\n end\n\n DBG_TAKEN_ID: begin\n // enter debug mode and save PC in ID to dpc, used when encountering\n // 1. EBREAK during debug mode\n // 2. EBREAK with forced entry into debug mode (ebreakm or ebreaku set).\n // regular ebreak's go through FLUSH.\n //\n // for 1. do not update dcsr and dpc, for 2. do so\n // jump to debug exception handler in debug memory\n flush_id = 1'b1;\n pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n exc_pc_mux_o = EXC_PC_DBD;\n\n // update dcsr and dpc\n if (ebreak_into_debug && !debug_mode_q) begin // ebreak with forced entry\n\n // dpc (set to the address of the EBREAK, i.e. set to PC in ID stage)\n csr_save_cause_o = 1'b1;\n csr_save_id_o = 1'b1;\n\n // dcsr\n debug_csr_save_o = 1'b1;\n end\n\n // enter debug mode\n debug_mode_d = 1'b1;\n debug_mode_entering_o = 1'b1;\n\n ctrl_fsm_ns = DECODE;\n end\n\n FLUSH: begin\n // flush the pipeline\n halt_if = 1'b1;\n flush_id = 1'b1;\n ctrl_fsm_ns = DECODE;\n\n // As pc_mux and exc_pc_mux can take various values in this state they aren't set early\n // here.\n\n // exceptions: set exception PC, save PC and exception cause\n // exc_req_lsu is high for one clock cycle only (in DECODE)\n if (exc_req_q || store_err_q || load_err_q) begin\n pc_set_o = 1'b1;\n pc_mux_o = PC_EXC;\n exc_pc_mux_o = debug_mode_q ? EXC_PC_DBG_EXC : EXC_PC_EXC;\n\n if (WritebackStage) begin : g_writeback_mepc_save\n // With the writeback stage present whether an instruction accessing memory will cause\n // an exception is only known when it is in writeback. So when taking such an exception\n // epc must come from writeback.\n csr_save_id_o = ~(store_err_q | load_err_q);\n csr_save_wb_o = store_err_q | load_err_q;\n end else begin : g_no_writeback_mepc_save\n csr_save_id_o = 1'b0;\n end\n\n csr_save_cause_o = 1'b1;\n\n // Exception/fault prioritisation logic will have set exactly 1 X_prio signal\n unique case (1'b1)\n instr_fetch_err_prio: begin\n exc_cause_o = ExcCauseInstrAccessFault;\n csr_mtval_o = instr_fetch_err_plus2_i ? (pc_id_i + 32'd2) : pc_id_i;\n end\n illegal_insn_prio: begin\n exc_cause_o = ExcCauseIllegalInsn;\n csr_mtval_o = instr_is_compressed_i ? {16'b0, instr_compressed_i} : instr_i;\n end\n ecall_insn_prio: begin\n exc_cause_o = (priv_mode_i == PRIV_LVL_M) ? ExcCauseEcallMMode :\n ExcCauseEcallUMode;\n end\n ebrk_insn_prio: begin\n if (debug_mode_q | ebreak_into_debug) begin\n // EBREAK enters debug mode when dcsr.ebreakm or dcsr.ebreaku is set and we're in\n // M or U mode respectively. If we're already in debug mode we re-enter debug mode.\n\n pc_set_o = 1'b0;\n csr_save_id_o = 1'b0;\n csr_save_cause_o = 1'b0;\n ctrl_fsm_ns = DBG_TAKEN_ID;\n flush_id = 1'b0;\n end else begin\n // If EBREAK won't enter debug mode (dcsr.ebreakm/u not set) then raise a breakpoint\n // exception.\n exc_cause_o = ExcCauseBreakpoint;\n end\n end\n store_err_prio: begin\n exc_cause_o = ExcCauseStoreAccessFault;\n csr_mtval_o = lsu_addr_last_i;\n end\n load_err_prio: begin\n exc_cause_o = ExcCauseLoadAccessFault;\n csr_mtval_o = lsu_addr_last_i;\n end\n default: ;\n endcase\n end else begin\n // special instructions and pipeline flushes\n if (mret_insn) begin\n pc_mux_o = PC_ERET;\n pc_set_o = 1'b1;\n csr_restore_mret_id_o = 1'b1;\n if (nmi_mode_q) begin\n nmi_mode_d = 1'b0; // exit NMI mode\n end\n end else if (dret_insn) begin\n pc_mux_o = PC_DRET;\n pc_set_o = 1'b1;\n debug_mode_d = 1'b0;\n csr_restore_dret_id_o = 1'b1;\n end else if (wfi_insn) begin\n ctrl_fsm_ns = WAIT_SLEEP;\n end\n end // exc_req_q\n\n // Entering debug mode due to either single step or debug_req. Ensure\n // registers are set for exception but then enter debug handler rather\n // than exception handler\n // Leave all other signals as is to ensure CSRs and PC get set as if\n // core was entering exception handler, entry to debug mode will then\n // see the appropriate state and setup dpc correctly.\n\n // If an EBREAK instruction is causing us to enter debug mode on the\n // same cycle as a debug_req or single step, honor the EBREAK and\n // proceed to DBG_TAKEN_ID, as it has the highest priority.\n //\n // cause==EBREAK -> prio 3 (highest)\n // cause==debug_req -> prio 2\n // cause==step -> prio 1 (lowest)\n if (enter_debug_mode_prio_q && !(ebrk_insn_prio && ebreak_into_debug)) begin\n ctrl_fsm_ns = DBG_TAKEN_IF;\n end\n end // FLUSH\n\n default: begin\n instr_req_o = 1'b0;\n ctrl_fsm_ns = RESET;\n end\n endcase\n\n if (~instr_exec_i) begin\n // Hold halt_if high when instr_exec_i is low to stop accepting instructions from the IF stage\n halt_if = 1'b1;\n end\n end\n\n assign flush_id_o = flush_id;\n\n // signal to CSR when in debug mode\n assign debug_mode_o = debug_mode_q;\n\n // signal to CSR when in an NMI handler (for nested exception handling)\n assign nmi_mode_o = nmi_mode_q;\n\n ///////////////////\n // Stall control //\n ///////////////////\n\n // If high current instruction cannot complete this cycle. Either because it needs more cycles to\n // finish (stall_id_i) or because the writeback stage cannot accept it yet (stall_wb_i). If there\n // is no writeback stage stall_wb_i is a constant 0.\n assign stall = stall_id_i | stall_wb_i;\n\n // signal to IF stage that ID stage is ready for next instr\n assign id_in_ready_o = ~stall & ~halt_if & ~retain_id;\n\n // kill instr in IF-ID pipeline reg that are done, or if a\n // multicycle instr causes an exception for example\n // retain_id is another kind of stall, where the instr_valid bit must remain\n // set (unless flush_id is set also). It cannot be factored directly into\n // stall as this causes a combinational loop.\n assign instr_valid_clear_o = ~(stall | retain_id) | flush_id;\n\n // update registers\n always_ff @(posedge clk_i or negedge rst_ni) begin : update_regs\n if (!rst_ni) begin\n ctrl_fsm_cs <= RESET;\n nmi_mode_q <= 1'b0;\n do_single_step_q <= 1'b0;\n debug_mode_q <= 1'b0;\n enter_debug_mode_prio_q <= 1'b0;\n load_err_q <= 1'b0;\n store_err_q <= 1'b0;\n exc_req_q <= 1'b0;\n illegal_insn_q <= 1'b0;\n end else begin\n ctrl_fsm_cs <= ctrl_fsm_ns;\n nmi_mode_q <= nmi_mode_d;\n do_single_step_q <= do_single_step_d;\n debug_mode_q <= debug_mode_d;\n enter_debug_mode_prio_q <= enter_debug_mode_prio_d;\n load_err_q <= load_err_d;\n store_err_q <= store_err_d;\n exc_req_q <= exc_req_d;\n illegal_insn_q <= illegal_insn_d;\n end\n end\n\n `ASSERT(PipeEmptyOnIrq, ctrl_fsm_cs != IRQ_TAKEN & ctrl_fsm_ns == IRQ_TAKEN |->\n ~instr_valid_i & ready_wb_i)\n\n //////////\n // FCOV //\n //////////\n\n `DV_FCOV_SIGNAL(logic, all_debug_req, debug_req_i || debug_mode_q || debug_single_step_i)\n `DV_FCOV_SIGNAL(logic, debug_wakeup, (ctrl_fsm_cs == SLEEP) & (ctrl_fsm_ns == FIRST_FETCH) &\n (debug_req_i || debug_mode_q || debug_single_step_i))\n `DV_FCOV_SIGNAL(logic, interrupt_taken, (ctrl_fsm_cs != IRQ_TAKEN) & (ctrl_fsm_ns == IRQ_TAKEN))\n `DV_FCOV_SIGNAL(logic, debug_entry_if,\n (ctrl_fsm_cs != DBG_TAKEN_IF) & (ctrl_fsm_ns == DBG_TAKEN_IF))\n `DV_FCOV_SIGNAL(logic, debug_entry_id,\n (ctrl_fsm_cs != DBG_TAKEN_ID) & (ctrl_fsm_ns == DBG_TAKEN_ID))\n `DV_FCOV_SIGNAL(logic, pipe_flush, (ctrl_fsm_cs != FLUSH) & (ctrl_fsm_ns == FLUSH))\n `DV_FCOV_SIGNAL(logic, debug_req, debug_req_i & ~debug_mode_q)\n `DV_FCOV_SIGNAL(logic, debug_single_step_taken, do_single_step_d & ~do_single_step_q)\n\n ////////////////\n // Assertions //\n ////////////////\n\n `ASSERT(AlwaysInstrClearOnMispredict, nt_branch_mispredict_o |-> instr_valid_clear_o)\n\n // Selectors must be known/valid.\n `ASSERT(IbexCtrlStateValid, ctrl_fsm_cs inside {\n RESET, BOOT_SET, WAIT_SLEEP, SLEEP, FIRST_FETCH, DECODE, FLUSH,\n IRQ_TAKEN, DBG_TAKEN_IF, DBG_TAKEN_ID})\n\n // If entering or exiting debug mode, the pipeline must be flushed. This is because Ibex\n // currently does not support some of the pipeline stages being in debug mode; either all or\n // none of the pipeline stages must be in debug mode. As `flush_id_o` only affects the ID/EX\n // stage but does not prevent a fetched instruction from proceeding to ID/EX the next cycle, the\n // assertion additionally requires `pc_set_o`, which sets the PC in the IF stage to a new value,\n // hence preventing a fetched instruction from proceeding to the ID/EX stage in the next cycle.\n `ASSERT(IbexPipelineFlushOnChangingDebugMode,\n debug_mode_d != debug_mode_q |-> flush_id_o & pc_set_o)\n\n `ifdef RVFI\n // Workaround for internal verilator error when using hierarchical refers to calcuate this\n // directly in ibex_core\n logic rvfi_flush_next;\n\n assign rvfi_flush_next = ctrl_fsm_ns == FLUSH;\n `endif\nendmodule\n", "pr_title": "fix: Illegal instruction display message", "pr_body": "Fix #2236 When encountering certain illegal compressed instructions, incorrect instruction information was displayed. Now, illegal instructions can be printed correctly.", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex 157d05a6e9..1b2666c0bc 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -175,7 +175,7 @@ module ibex_controller #(\n // print warning in case of decoding errors\n if ((ctrl_fsm_cs == DECODE) && instr_valid_i && !instr_fetch_err_i && illegal_insn_d) begin\n $display(\"%t: Illegal instruction (hart %0x) at PC 0x%h: 0x%h\", $time, u_ibex_core.hart_id_i,\n- pc_id_i, id_stage_i.instr_rdata_i);\n+ pc_id_i, instr_is_compressed_i ? {16'b0, instr_compressed_i} : instr_i );\n end\n end\n // synopsys translate_on\n"}
{"repo": "lowRISC/ibex", "pr_id": 1975, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": true, "sufficient_for_diagnosis": false}, "reasoning": "The specification lacks behavioral assertions directly verifying the correct application of the scramble key to icache memory primitives, which is the functional area modified by the patch."}, "generated_spec": "# Behavioral Design Specification for ibex_top (Ibex RISC-V Core)\n\n## 1. Overview\n\n`ibex_top` is the top-level module of the Ibex RISC-V processor core. It implements a 32-bit, in-order, single-issue RISC-V CPU that can execute the RV32I base integer instruction set, optionally extended with:\n\n- **RV32E** (embedded, 16 registers)\n- **RV32M** (multiply/divide)\n- **RV32B** (bit manipulation)\n\nThe core supports configurable physical memory protection (PMP), hardware performance counters, debug triggers, and a set of security features for fault detection and timing‑side‑channel mitigation.\n\n`ibex_top` integrates the CPU pipeline, register file, optional instruction cache (I$), and optional dual‑core lockstep logic. The module provides standard bus interfaces for instruction and data memory, interrupt and debug inputs, alert outputs, and a clock‑gating control signal.\n\n## 2. Configuration Parameters\n\nThe following parameters shall be static (set at synthesis time) and determine the core’s capabilities and behavior.\n\n| Parameter | Effect on Behavior |\n|-------------------------|------------------------------------------------------------------------------------------------------|\n| `PMPEnable` | When 1, physical memory protection (PMP) checking is active on instruction and data accesses. |\n| `PMPGranularity` | Minimum address region size for PMP matching (0 = 4‑byte granularity). |\n| `PMPNumRegions` | Number of PMP configuration regions (1–16). |\n| `MHPMCounterNum` | Number of hardware performance‑monitor counters (0–10). |\n| `MHPMCounterWidth` | Bit width of each performance counter (1–64). |\n| `RV32E` | When 1, only 16 integer registers (x0–x15) are implemented and instructions using x16–x31 are illegal. |\n| `RV32M` | Selects multiplier/divider implementation: none, slow, fast, single‑cycle. |\n| `RV32B` | Selects bit‑manipulation extension: none, balanced, full, or a specific subset. |\n| `RegFile` | Selects register file implementation: flip‑flop, FPGA‑optimised, or latch‑based. |\n| `BranchTargetALU` | When 1, a dedicated branch target ALU is added to remove a stall cycle on taken branches. |\n| `WritebackStage` | When 1, a third pipeline stage (writeback) is added for improved load/store throughput. |\n| `ICache` | When 1, an instruction cache replaces the simple prefetch buffer. |\n| `ICacheECC` | When 1 and `ICache`=1, SECDED ECC protection is added to cache tag and data RAMs. |\n| `ICacheScramble` | When 1 and `ICache`=1, cache RAMs are replaced by scrambling primitives for data confidentiality. |\n| `BranchPredictor` | When 1, static branch prediction is used to reduce taken‑branch stalls. |\n| `DbgTriggerEn` | When 1, a single debug trigger (data‑address match) is supported. |\n| `DbgHwBreakNum` | Number of hardware breakpoints (currently must be ≤ 1). |\n| `SecureIbex` | When 1, all security‑related features are enabled (dummy instructions, bus integrity, register file ECC, glitch detection, shadow CSRs, lockstep). |\n| `RndCnstLfsrSeed` | Initial seed for the LFSR used by dummy instruction generation (only with `SecureIbex`). |\n| `RndCnstLfsrPerm` | Output permutation for the LFSR (only with `SecureIbex`). |\n| `DmHaltAddr` | Address to jump to when entering debug mode (default 0x1A110800). |\n| `DmExceptionAddr` | Address to jump to on exceptions occurring in debug mode (default 0x1A110808). |\n| `RndCnstIbexKey` | Default scramble key for cache scrambling (only with `ICacheScramble`). |\n| `RndCnstIbexNonce` | Default nonce for cache scrambling (only with `ICacheScramble`). |\n\n## 3. Interfaces and Functional Behavior\n\n### 3.1 Clock, Reset, and Test\n\n- **Clock (`clk_i`):** All synchronous logic operates on the rising edge of this clock.\n- **Reset (`rst_ni`):** Active‑low asynchronous reset. When asserted, the core shall be in a known reset state (PC taken from `boot_addr_i`, all CSR state cleared to architectural reset values, pipeline flushed).\n- **Test enable (`test_en_i`):** When asserted, all clock gating shall be disabled to allow full scan testing.\n- **Scan reset (`scan_rst_ni`):** A separate test‑controlled reset. In non‑test operation this must be tied high.\n- **RAM configuration (`ram_cfg_i`):** Provides configuration signals to the internal RAM instances (icache). The exact encoding is defined by the platform’s memory compiler.\n\n### 3.2 Core Identification and Boot\n\n- **Hart ID (`hart_id_i`):** A static 32‑bit identifier for this processor core, readable via the `mhartid` CSR.\n- **Boot address (`boot_addr_i`):** After reset, the core shall start fetching instructions from `boot_addr_i + 0x80` (the reset vector is at `boot_addr_i + 0x80`, following the standard RISC‑V convention; the first eight words are reserved for exception vectors).\n\n### 3.3 Instruction Fetch Interface\n\nThe core fetches instructions through a request‑grant‑response protocol.\n\n- **Request (`instr_req_o`):** When asserted, a new instruction fetch is requested. The core shall hold this signal stable until the memory system asserts `instr_gnt_i`.\n- **Address (`instr_addr_o`):** The word‑aligned address of the instruction to be fetched.\n- **Grant (`instr_gnt_i`):** When asserted, the memory system accepts the request. After grant, the core may change the address in the next cycle.\n- **Response valid (`instr_rvalid_i`):** Asserted for exactly one cycle per accepted request to indicate that `instr_rdata_i` and `instr_err_i` are valid.\n- **Read data (`instr_rdata_i`):** The fetched instruction data (32 bits). The lower two bits determine whether the instruction is compressed (2‑byte) or uncompressed (4‑byte).\n- **Integrity bits (`instr_rdata_intg_i`):** When `SecureIbex`=1, these 7 bits provide error‑detection code for the data. The core shall verify these bits against the data and signal a bus major alert on mismatch.\n- **Error (`instr_err_i`):** When high, the memory access failed (e.g., bus error or PMP violation). The core shall take an instruction‑access exception.\n\n**Protocol:** The core may have multiple outstanding instruction requests (prefetch buffer width). Responses shall be returned in order. The core shall not assert `instr_req_o` again after a PMP error on the same line until a branch occurs.\n\n### 3.4 Data Memory Interface\n\nThe load‑store unit (LSU) uses a similar request‑grant‑response protocol but also includes write control.\n\n- **Request (`data_req_o`):** Asserted to begin a data memory access. Held until `data_gnt_i` is asserted.\n- **Address (`data_addr_o`):** The word‑aligned address of the memory access.\n- **Write enable (`data_we_o`):** High for store operations, low for loads.\n- **Byte enables (`data_be_o`):** 4‑bit mask indicating which bytes of the addressed word are accessed.\n- **Write data (`data_wdata_o`):** Data to be written (32 bits), valid only for stores.\n- **Write data integrity (`data_wdata_intg_o`):** When `SecureIbex`=1, the LU generates integrity bits for write data. These should be transmitted alongside `data_wdata_o` and checked at the memory.\n- **Grant (`data_gnt_i`):** The memory system accepts the request. After grant the core may change address/write data.\n- **Response valid (`data_rvalid_i`):** High for one cycle per request; indicates that `data_rdata_i`, `data_rdata_intg_i`, and `data_err_i` are valid.\n- **Read data (`data_rdata_i`):** Data returned from a load operation (32 bits). For stores, this signal is ignored except for integrity checking.\n- **Read data integrity (`data_rdata_intg_i`):** When `SecureIbex`=1, the core shall check these bits against `data_rdata_i` and signal a bus major alert on mismatch.\n- **Error (`data_err_i`):** High indicates a bus error or PMP violation. The core shall take a data‑access exception.\n\n**Protocol:** The LSU can have up to two outstanding requests (for misaligned accesses). Responses must be returned in order. An error on the first of a pair of misaligned requests does not prevent the second request from being issued, but its response is ignored.\n\n### 3.5 Misaligned Accesses\n\nThe core shall handle misaligned loads and stores (e.g., a 32‑bit load from address 0x3) by performing two word‑aligned bus accesses. Each access follows the standard protocol. If the first access returns an error, the second access is still performed; the core shall take the exception for the first error and discard the second result. The core shall not service a new load/store while waiting for an abandoned second part.\n\n### 3.6 Interrupts\n\nThe core supports the standard RISC‑V interrupt model with configurable delegation and priority.\n\n- **Software interrupt (`irq_software_i`):** Corresponds to `mip.MSIP`.\n- **Timer interrupt (`irq_timer_i`):** Corresponds to `mip.MTIP`.\n- **External interrupt (`irq_external_i`):** Corresponds to `mip.MEIP`.\n- **Fast interrupts (`irq_fast_i[14:0]`):** Up to 15 user‑defined interrupt lines (mapped to `mip` bits 16–30).\n- **Non‑maskable interrupt (`irq_nm_i`):** The highest priority interrupt; taken regardless of `mstatus.MIE` and cannot be masked. The core shall handle it as an NMI, jumping to the `mtvec` address for NMIs (a separate vector from regular exceptions).\n\nAll interrupts are sampled synchronously. The core shall wake from a `WFI` instruction if any interrupt is pending (including NMI). The `irq_pending` internal signal is used for clock gating.\n\n### 3.7 Debug Interface\n\n- **Debug request (`debug_req_i`):** When asserted, the core shall enter debug mode (halt execution) at the next instruction boundary if debug mode is enabled and not already in debug mode. The core jumps to `DmHaltAddr`.\n- **Crash dump (`crash_dump_o`):** A set of registers that can be captured on reset for post‑mortem debugging. It includes the current PC, next PC, last data address, exception PC, and exception address (if any).\n- **Double-fault seen (`double_fault_seen_o`):** This output shall be asserted for one or more cycles when a double fault is detected (i.e., a synchronous exception occurs while already handling a synchronous exception in a context where the handler cannot be re‑entered without a hardware reset or specific CSR bits). The precise conditions are defined by the `SecureIbex` configuration.\n\n### 3.8 Control Signals\n\n- **Fetch enable (`fetch_enable_i`):** A multi‑bit (mubi) signal that gates instruction fetching. When the value is `IbexMuBiOff`, the core shall stop fetching new instructions and float to sleep once any in‑flight instructions complete. When set to `IbexMuBiOn`, normal fetching resumes. Other values are treated as off in non‑secure mode, or as an error in secure mode.\n- **Core sleep (`core_sleep_o`):** High when the core is in a `WFI` sleep state and has no outstanding instruction or data bus transactions. The core shall wake (deassert `core_sleep_o`) upon an interrupt, NMI, or debug request.\n- **Alert outputs:**\n - `alert_minor_o`: A single‑cycle pulse when a recoverable security event is detected (e.g., ECC error in instruction cache).\n - `alert_major_internal_o`: A pulse (possibly multi‑cycle) when an internal, unrecoverable fault is detected (e.g., register file ECC error, lockstep mismatch, hardened PC check failure).\n - `alert_major_bus_o`: A pulse when a bus integrity error is detected (mismatch between data and integrity bits on instruction or data interface).\n\n### 3.9 Scrambling Interface (ICacheScramble)\n\nWhen the instruction cache is configured with scrambling (`ICacheScramble`=1), the core provides a request/acknowledge interface for receiving a fresh encryption key from an external source (e.g., OTP).\n\n- **Key request (`scramble_req_o`):** Asserted when the core needs a new key, typically after a `FENCE.I` instruction that requests key renewal.\n- **Key valid (`scramble_key_valid_i`):** When asserted, `scramble_key_i` and `scramble_nonce_i` carry a valid key and nonce. The core shall latch these values and use them for subsequent cache line encryptions.\n- **Key and nonce (`scramble_key_i`, `scramble_nonce_i`):** The 128‑bit (or configurable‑width) key and nonce used by the scrambling engine.\n\nThe core shall deassert `scramble_req_o` once the key is latched. If a second `FENCE.I` occurs while a request is pending, it shall be ignored (or handled as described in the cache documentation). After a key is received, an automatic cache invalidation shall occur, and all subsequent allocations use the new key.\n\n## 4. Security Features (when `SecureIbex` = 1)\n\n### 4.1 Dummy Instruction Insertion\n\nWhen enabled via a CSR control bit, the core shall insert random dummy instructions into the pipeline at intervals that vary pseudo‑randomly. Dummy instructions write only to register x0 and have no architectural effect. The insertion rate is configurable. This feature requires the `RV32M` parameter to be non‑none.\n\n### 4.2 Data‑Independent Timing\n\nWhen enabled via a CSR control bit, all instructions (including branches, multiplies, and divides) shall execute in the same number of cycles regardless of input data. This prevents timing side‑channels.\n\n### 4.3 Bus Integrity Checking\n\nAs described in the memory interfaces, the core shall generate and check integrity bits (39‑bit inverted Hsaio code) on all data and instruction bus transactions. Mismatches cause a major bus alert and suppress the load register update (for load operations). For stores, the integrity check is done on the response; a mismatch also causes an alert.\n\n### 4.4 Register File ECC and Write‑Enable Glitch Detection\n\nAll reads from the register file shall be checked against an ECC code written at store time. An ECC error (any single or double bit) shall cause an internal major alert. Additionally, the write‑enable signal of the register file shall be tested to ensure it is one‑hot; multiple asserted enables shall trigger an alert.\n\n### 4.5 Shadow CSRs\n\nCritical CSRs (`mstatus`, `mtvec`, `cpuctrl`, `pmpcfg`, `pmpaddr`) shall be duplicated with complemented copies. A continuous comparison shall be made; a mismatch causes an internal major alert. (Note: this feature may be subsumed by lockstep when `SecureIbex` is enabled.)\n\n### 4.6 Hardened PC\n\nA check that the instruction‑fetch PC increments correctly between branches shall be performed. Mismatch triggers an internal major alert.\n\n### 4.7 Dual‑Core Lockstep\n\nWhen `SecureIbex`=1, a second shadow core is instantiated that receives delayed copies of all inputs and compares its outputs against delayed versions of the main core’s outputs. Any difference in outputs (including bus requests, register file addresses, cache control signals, etc.) shall cause an internal major alert. The lockstep logic does not duplicate the register file or cache RAMs; these are protected by ECC.\n\n## 5. Instruction Cache Behavior (when `ICache` = 1)\n\nThe instruction cache acts as a drop‑in replacement for the prefetch buffer. It shall:\n- Cache instructions in a set‑associative structure (number of ways and line size parameterized).\n- On a hit, supply data from the cache in the same cycle as tag lookup (two‑stage pipeline).\n- On a miss, fetch the missing cache line from the instruction memory and allocate it according to the filling policy.\n- Support cache invalidation on `FENCE.I` instruction (or on reset).\n- When `ICacheECC`=1, detect single/double‑bit ECC errors in the tag and data RAMs. On any error, treat it as a cache miss, invalidate the affected line, and signal a minor alert.\n- When `ICacheScramble`=1, all data stored in the cache shall be encrypted using the supplied key/nonce. The encryption is transparent to the rest of the core.\n\nThe cache interface includes a `busy_o` signal that remains high during invalidation or while any external memory request is outstanding.\n\n## 6. Power Management\n\nThe core shall support the `WFI` instruction (wait for interrupt). After executing `WFI`, the core shall deassert `core_sleep_o` only when an enabled interrupt, NMI, or debug request occurs. While sleeping, the internal clocks may be gated; the instruction cache shall also stop fetching. The core shall resume normal operation when a wake event is detected.\n\n## 7. Initialization and Reset\n\nUpon deassertion of `rst_ni`, the core shall:\n- Load the program counter with `boot_addr_i + 0x80`.\n- Clear all CSR state to the architectural reset values (including `mstatus.MIE` = 0, `mtvec` = reset vector, etc.).\n- Invalidate the instruction cache if present.\n- Set any lockstep shadow core to the same reset state.\n- Wait for `fetch_enable_i` to indicate `IbexMuBiOn` before beginning instruction fetching.\n\n## 8. Error Handling\n\n- **Instruction bus errors:** Cause an instruction‑access exception (`mcause` = 1).\n- **Data bus errors:** Cause a load‑access or store‑access exception (`mcause` = 5 or 7).\n- **PMP violations:** Cause the same exceptions as bus errors.\n- **Double faults:** If a synchronous exception occurs while `mstatus.MPRV` is set such that the exception handler cannot be entered, the core shall set `double_fault_seen_o` and may reset itself or enter an infinite loop (implementation‑dependent). The precise behavior is defined by the crash dump and security logic.\n\n## 9. Formal Interface (RVFI)\n\nWhen compiled with `RISCV_FORMAL` define, the core shall output a standard RISC‑V Formal Interface (RVFI) trace of every retired instruction, including register write data, memory access details, and exception status. This interface is used for formal verification and is not required for normal operation.\n\n## 10. Assertion Coverage\n\nThe module includes a suite of SystemVerilog assertions that verify:\n- Output signals are not unknown (X).\n- Instruction and data interfaces follow the described protocol.\n- Maximum outstanding data‑side transactions is never exceeded.\n- Dummy instructions only write to register zero.\n- Crash dump signals are connected to the correct internal signals.\n- Double‑fault detection logic is consistent with the retirement trace (when RVFI is present).\n\nThese assertions are for verification purposes and shall not be synthesized.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2018 ETH Zurich and University of Bologna, see also CREDITS.md.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n`ifdef RISCV_FORMAL\n `define RVFI\n`endif\n\n`include \"prim_assert.sv\"\n\n/**\n * Top level module of the ibex RISC-V core\n */\nmodule ibex_top import ibex_pkg::*; #(\n parameter bit PMPEnable = 1'b0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter int unsigned MHPMCounterNum = 0,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit RV32E = 1'b0,\n parameter rv32m_e RV32M = RV32MFast,\n parameter rv32b_e RV32B = RV32BNone,\n parameter regfile_e RegFile = RegFileFF,\n parameter bit BranchTargetALU = 1'b0,\n parameter bit WritebackStage = 1'b0,\n parameter bit ICache = 1'b0,\n parameter bit ICacheECC = 1'b0,\n parameter bit BranchPredictor = 1'b0,\n parameter bit DbgTriggerEn = 1'b0,\n parameter int unsigned DbgHwBreakNum = 1,\n parameter bit SecureIbex = 1'b0,\n parameter bit ICacheScramble = 1'b0,\n parameter lfsr_seed_t RndCnstLfsrSeed = RndCnstLfsrSeedDefault,\n parameter lfsr_perm_t RndCnstLfsrPerm = RndCnstLfsrPermDefault,\n parameter int unsigned DmHaltAddr = 32'h1A110800,\n parameter int unsigned DmExceptionAddr = 32'h1A110808,\n // Default seed and nonce for scrambling\n parameter logic [SCRAMBLE_KEY_W-1:0] RndCnstIbexKey = RndCnstIbexKeyDefault,\n parameter logic [SCRAMBLE_NONCE_W-1:0] RndCnstIbexNonce = RndCnstIbexNonceDefault\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n input logic test_en_i, // enable all clock gates for testing\n input prim_ram_1p_pkg::ram_1p_cfg_t ram_cfg_i,\n\n input logic [31:0] hart_id_i,\n input logic [31:0] boot_addr_i,\n\n // Instruction memory interface\n output logic instr_req_o,\n input logic instr_gnt_i,\n input logic instr_rvalid_i,\n output logic [31:0] instr_addr_o,\n input logic [31:0] instr_rdata_i,\n input logic [6:0] instr_rdata_intg_i,\n input logic instr_err_i,\n\n // Data memory interface\n output logic data_req_o,\n input logic data_gnt_i,\n input logic data_rvalid_i,\n output logic data_we_o,\n output logic [3:0] data_be_o,\n output logic [31:0] data_addr_o,\n output logic [31:0] data_wdata_o,\n output logic [6:0] data_wdata_intg_o,\n input logic [31:0] data_rdata_i,\n input logic [6:0] data_rdata_intg_i,\n input logic data_err_i,\n\n // Interrupt inputs\n input logic irq_software_i,\n input logic irq_timer_i,\n input logic irq_external_i,\n input logic [14:0] irq_fast_i,\n input logic irq_nm_i, // non-maskeable interrupt\n\n // Scrambling Interface\n input logic scramble_key_valid_i,\n input logic [SCRAMBLE_KEY_W-1:0] scramble_key_i,\n input logic [SCRAMBLE_NONCE_W-1:0] scramble_nonce_i,\n output logic scramble_req_o,\n\n // Debug Interface\n input logic debug_req_i,\n output crash_dump_t crash_dump_o,\n output logic double_fault_seen_o,\n\n // RISC-V Formal Interface\n // Does not comply with the coding standards of _i/_o suffixes, but follows\n // the convention of RISC-V Formal Interface Specification.\n`ifdef RVFI\n output logic rvfi_valid,\n output logic [63:0] rvfi_order,\n output logic [31:0] rvfi_insn,\n output logic rvfi_trap,\n output logic rvfi_halt,\n output logic rvfi_intr,\n output logic [ 1:0] rvfi_mode,\n output logic [ 1:0] rvfi_ixl,\n output logic [ 4:0] rvfi_rs1_addr,\n output logic [ 4:0] rvfi_rs2_addr,\n output logic [ 4:0] rvfi_rs3_addr,\n output logic [31:0] rvfi_rs1_rdata,\n output logic [31:0] rvfi_rs2_rdata,\n output logic [31:0] rvfi_rs3_rdata,\n output logic [ 4:0] rvfi_rd_addr,\n output logic [31:0] rvfi_rd_wdata,\n output logic [31:0] rvfi_pc_rdata,\n output logic [31:0] rvfi_pc_wdata,\n output logic [31:0] rvfi_mem_addr,\n output logic [ 3:0] rvfi_mem_rmask,\n output logic [ 3:0] rvfi_mem_wmask,\n output logic [31:0] rvfi_mem_rdata,\n output logic [31:0] rvfi_mem_wdata,\n output logic [31:0] rvfi_ext_mip,\n output logic rvfi_ext_nmi,\n output logic rvfi_ext_nmi_int,\n output logic rvfi_ext_debug_req,\n output logic rvfi_ext_debug_mode,\n output logic rvfi_ext_rf_wr_suppress,\n output logic [63:0] rvfi_ext_mcycle,\n output logic [31:0] rvfi_ext_mhpmcounters [10],\n output logic [31:0] rvfi_ext_mhpmcountersh [10],\n output logic rvfi_ext_ic_scr_key_valid,\n`endif\n\n // CPU Control Signals\n input ibex_mubi_t fetch_enable_i,\n output logic alert_minor_o,\n output logic alert_major_internal_o,\n output logic alert_major_bus_o,\n output logic core_sleep_o,\n\n // DFT bypass controls\n input logic scan_rst_ni\n);\n\n localparam bit Lockstep = SecureIbex;\n localparam bit ResetAll = Lockstep;\n localparam bit DummyInstructions = SecureIbex;\n localparam bit RegFileECC = SecureIbex;\n localparam bit RegFileWrenCheck = SecureIbex;\n localparam int unsigned RegFileDataWidth = RegFileECC ? 32 + 7 : 32;\n localparam bit MemECC = SecureIbex;\n localparam int unsigned MemDataWidth = MemECC ? 32 + 7 : 32;\n // Icache parameters\n localparam int unsigned BusSizeECC = ICacheECC ? (BUS_SIZE + 7) : BUS_SIZE;\n localparam int unsigned LineSizeECC = BusSizeECC * IC_LINE_BEATS;\n localparam int unsigned TagSizeECC = ICacheECC ? (IC_TAG_SIZE + 6) : IC_TAG_SIZE;\n // Scrambling Parameter\n localparam int unsigned NumAddrScrRounds = ICacheScramble ? 2 : 0;\n localparam int unsigned NumDiffRounds = NumAddrScrRounds;\n\n // Clock signals\n logic clk;\n ibex_mubi_t core_busy_d, core_busy_q;\n logic clock_en;\n logic irq_pending;\n // Core <-> Register file signals\n logic dummy_instr_id;\n logic dummy_instr_wb;\n logic [4:0] rf_raddr_a;\n logic [4:0] rf_raddr_b;\n logic [4:0] rf_waddr_wb;\n logic rf_we_wb;\n logic [RegFileDataWidth-1:0] rf_wdata_wb_ecc;\n logic [RegFileDataWidth-1:0] rf_rdata_a_ecc, rf_rdata_a_ecc_buf;\n logic [RegFileDataWidth-1:0] rf_rdata_b_ecc, rf_rdata_b_ecc_buf;\n\n // Combined data and integrity for data and instruction busses\n logic [MemDataWidth-1:0] data_wdata_core;\n logic [MemDataWidth-1:0] data_rdata_core;\n logic [MemDataWidth-1:0] instr_rdata_core;\n\n // Core <-> RAMs signals\n logic [IC_NUM_WAYS-1:0] ic_tag_req;\n logic ic_tag_write;\n logic [IC_INDEX_W-1:0] ic_tag_addr;\n logic [TagSizeECC-1:0] ic_tag_wdata;\n logic [TagSizeECC-1:0] ic_tag_rdata [IC_NUM_WAYS];\n logic [IC_NUM_WAYS-1:0] ic_data_req;\n logic ic_data_write;\n logic [IC_INDEX_W-1:0] ic_data_addr;\n logic [LineSizeECC-1:0] ic_data_wdata;\n logic [LineSizeECC-1:0] ic_data_rdata [IC_NUM_WAYS];\n logic ic_scr_key_req;\n // Alert signals\n logic core_alert_major_internal, core_alert_major_bus, core_alert_minor;\n logic lockstep_alert_major_internal, lockstep_alert_major_bus;\n logic lockstep_alert_minor;\n // Scramble signals\n logic [SCRAMBLE_KEY_W-1:0] scramble_key_q;\n logic [SCRAMBLE_NONCE_W-1:0] scramble_nonce_q;\n logic scramble_key_valid_d, scramble_key_valid_q;\n logic scramble_req_d, scramble_req_q;\n\n ibex_mubi_t fetch_enable_buf;\n\n /////////////////////\n // Main clock gate //\n /////////////////////\n\n if (SecureIbex) begin : g_clock_en_secure\n // For secure Ibex core_busy_q must be a specific multi-bit pattern to enable the clock.\n prim_flop #(\n .Width($bits(ibex_mubi_t)),\n .ResetValue(IbexMuBiOff)\n ) u_prim_core_busy_flop (\n .clk_i (clk_i),\n .rst_ni(rst_ni),\n .d_i (core_busy_d),\n .q_o (core_busy_q)\n );\n assign clock_en = (core_busy_q != IbexMuBiOff) | debug_req_i | irq_pending | irq_nm_i;\n end else begin : g_clock_en_non_secure\n // For non secure Ibex only the bottom bit of core_busy_q is considered. Other FFs can be\n // optimized away during synthesis.\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n core_busy_q <= IbexMuBiOff;\n end else begin\n core_busy_q <= core_busy_d;\n end\n end\n assign clock_en = core_busy_q[0] | debug_req_i | irq_pending | irq_nm_i;\n\n logic unused_core_busy;\n assign unused_core_busy = ^core_busy_q[$bits(ibex_mubi_t)-1:1];\n end\n\n assign core_sleep_o = ~clock_en;\n\n prim_clock_gating core_clock_gate_i (\n .clk_i (clk_i),\n .en_i (clock_en),\n .test_en_i(test_en_i),\n .clk_o (clk)\n );\n\n ////////////////////////\n // Core instantiation //\n ////////////////////////\n\n // Buffer security critical signals to prevent synthesis optimisation removing them\n prim_buf #(.Width($bits(ibex_mubi_t))) u_fetch_enable_buf (\n .in_i (fetch_enable_i),\n .out_o(fetch_enable_buf)\n );\n\n prim_buf #(.Width(RegFileDataWidth)) u_rf_rdata_a_ecc_buf (\n .in_i (rf_rdata_a_ecc),\n .out_o(rf_rdata_a_ecc_buf)\n );\n\n prim_buf #(.Width(RegFileDataWidth)) u_rf_rdata_b_ecc_buf (\n .in_i (rf_rdata_b_ecc),\n .out_o(rf_rdata_b_ecc_buf)\n );\n\n\n // ibex_core takes integrity and data bits together. Combine the separate integrity and data\n // inputs here.\n assign data_rdata_core[31:0] = data_rdata_i;\n assign instr_rdata_core[31:0] = instr_rdata_i;\n\n if (MemECC) begin : gen_mem_rdata_ecc\n assign data_rdata_core[38:32] = data_rdata_intg_i;\n assign instr_rdata_core[38:32] = instr_rdata_intg_i;\n end else begin : gen_non_mem_rdata_ecc\n logic unused_intg;\n\n assign unused_intg = ^{instr_rdata_intg_i, data_rdata_intg_i};\n end\n\n ibex_core #(\n .PMPEnable (PMPEnable),\n .PMPGranularity (PMPGranularity),\n .PMPNumRegions (PMPNumRegions),\n .MHPMCounterNum (MHPMCounterNum),\n .MHPMCounterWidth (MHPMCounterWidth),\n .RV32E (RV32E),\n .RV32M (RV32M),\n .RV32B (RV32B),\n .BranchTargetALU (BranchTargetALU),\n .ICache (ICache),\n .ICacheECC (ICacheECC),\n .BusSizeECC (BusSizeECC),\n .TagSizeECC (TagSizeECC),\n .LineSizeECC (LineSizeECC),\n .BranchPredictor (BranchPredictor),\n .DbgTriggerEn (DbgTriggerEn),\n .DbgHwBreakNum (DbgHwBreakNum),\n .WritebackStage (WritebackStage),\n .ResetAll (ResetAll),\n .RndCnstLfsrSeed (RndCnstLfsrSeed),\n .RndCnstLfsrPerm (RndCnstLfsrPerm),\n .SecureIbex (SecureIbex),\n .DummyInstructions(DummyInstructions),\n .RegFileECC (RegFileECC),\n .RegFileDataWidth (RegFileDataWidth),\n .MemECC (MemECC),\n .MemDataWidth (MemDataWidth),\n .DmHaltAddr (DmHaltAddr),\n .DmExceptionAddr (DmExceptionAddr)\n ) u_ibex_core (\n .clk_i(clk),\n .rst_ni,\n\n .hart_id_i,\n .boot_addr_i,\n\n .instr_req_o,\n .instr_gnt_i,\n .instr_rvalid_i,\n .instr_addr_o,\n .instr_rdata_i(instr_rdata_core),\n .instr_err_i,\n\n .data_req_o,\n .data_gnt_i,\n .data_rvalid_i,\n .data_we_o,\n .data_be_o,\n .data_addr_o,\n .data_wdata_o(data_wdata_core),\n .data_rdata_i(data_rdata_core),\n .data_err_i,\n\n .dummy_instr_id_o (dummy_instr_id),\n .dummy_instr_wb_o (dummy_instr_wb),\n .rf_raddr_a_o (rf_raddr_a),\n .rf_raddr_b_o (rf_raddr_b),\n .rf_waddr_wb_o (rf_waddr_wb),\n .rf_we_wb_o (rf_we_wb),\n .rf_wdata_wb_ecc_o(rf_wdata_wb_ecc),\n .rf_rdata_a_ecc_i (rf_rdata_a_ecc_buf),\n .rf_rdata_b_ecc_i (rf_rdata_b_ecc_buf),\n\n .ic_tag_req_o (ic_tag_req),\n .ic_tag_write_o (ic_tag_write),\n .ic_tag_addr_o (ic_tag_addr),\n .ic_tag_wdata_o (ic_tag_wdata),\n .ic_tag_rdata_i (ic_tag_rdata),\n .ic_data_req_o (ic_data_req),\n .ic_data_write_o (ic_data_write),\n .ic_data_addr_o (ic_data_addr),\n .ic_data_wdata_o (ic_data_wdata),\n .ic_data_rdata_i (ic_data_rdata),\n .ic_scr_key_valid_i(scramble_key_valid_q),\n .ic_scr_key_req_o (ic_scr_key_req),\n\n .irq_software_i,\n .irq_timer_i,\n .irq_external_i,\n .irq_fast_i,\n .irq_nm_i,\n .irq_pending_o(irq_pending),\n\n .debug_req_i,\n .crash_dump_o,\n .double_fault_seen_o,\n\n`ifdef RVFI\n .rvfi_valid,\n .rvfi_order,\n .rvfi_insn,\n .rvfi_trap,\n .rvfi_halt,\n .rvfi_intr,\n .rvfi_mode,\n .rvfi_ixl,\n .rvfi_rs1_addr,\n .rvfi_rs2_addr,\n .rvfi_rs3_addr,\n .rvfi_rs1_rdata,\n .rvfi_rs2_rdata,\n .rvfi_rs3_rdata,\n .rvfi_rd_addr,\n .rvfi_rd_wdata,\n .rvfi_pc_rdata,\n .rvfi_pc_wdata,\n .rvfi_mem_addr,\n .rvfi_mem_rmask,\n .rvfi_mem_wmask,\n .rvfi_mem_rdata,\n .rvfi_mem_wdata,\n .rvfi_ext_mip,\n .rvfi_ext_nmi,\n .rvfi_ext_nmi_int,\n .rvfi_ext_debug_req,\n .rvfi_ext_debug_mode,\n .rvfi_ext_rf_wr_suppress,\n .rvfi_ext_mcycle,\n .rvfi_ext_mhpmcounters,\n .rvfi_ext_mhpmcountersh,\n .rvfi_ext_ic_scr_key_valid,\n`endif\n\n .fetch_enable_i (fetch_enable_buf),\n .alert_minor_o (core_alert_minor),\n .alert_major_internal_o(core_alert_major_internal),\n .alert_major_bus_o (core_alert_major_bus),\n .core_busy_o (core_busy_d)\n );\n\n /////////////////////////////////\n // Register file Instantiation //\n /////////////////////////////////\n\n logic rf_alert_major_internal;\n if (RegFile == RegFileFF) begin : gen_regfile_ff\n ibex_register_file_ff #(\n .RV32E (RV32E),\n .DataWidth (RegFileDataWidth),\n .DummyInstructions(DummyInstructions),\n // SEC_CM: DATA_REG_SW.GLITCH_DETECT\n .WrenCheck (RegFileWrenCheck),\n .WordZeroVal (RegFileDataWidth'(prim_secded_pkg::SecdedInv3932ZeroWord))\n ) register_file_i (\n .clk_i (clk),\n .rst_ni(rst_ni),\n\n .test_en_i (test_en_i),\n .dummy_instr_id_i(dummy_instr_id),\n .dummy_instr_wb_i(dummy_instr_wb),\n\n .raddr_a_i(rf_raddr_a),\n .rdata_a_o(rf_rdata_a_ecc),\n .raddr_b_i(rf_raddr_b),\n .rdata_b_o(rf_rdata_b_ecc),\n .waddr_a_i(rf_waddr_wb),\n .wdata_a_i(rf_wdata_wb_ecc),\n .we_a_i (rf_we_wb),\n .err_o (rf_alert_major_internal)\n );\n end else if (RegFile == RegFileFPGA) begin : gen_regfile_fpga\n ibex_register_file_fpga #(\n .RV32E (RV32E),\n .DataWidth (RegFileDataWidth),\n .DummyInstructions(DummyInstructions),\n // SEC_CM: DATA_REG_SW.GLITCH_DETECT\n .WrenCheck (RegFileWrenCheck),\n .WordZeroVal (RegFileDataWidth'(prim_secded_pkg::SecdedInv3932ZeroWord))\n ) register_file_i (\n .clk_i (clk),\n .rst_ni(rst_ni),\n\n .test_en_i (test_en_i),\n .dummy_instr_id_i(dummy_instr_id),\n .dummy_instr_wb_i(dummy_instr_wb),\n\n .raddr_a_i(rf_raddr_a),\n .rdata_a_o(rf_rdata_a_ecc),\n .raddr_b_i(rf_raddr_b),\n .rdata_b_o(rf_rdata_b_ecc),\n .waddr_a_i(rf_waddr_wb),\n .wdata_a_i(rf_wdata_wb_ecc),\n .we_a_i (rf_we_wb),\n .err_o (rf_alert_major_internal)\n );\n end else if (RegFile == RegFileLatch) begin : gen_regfile_latch\n ibex_register_file_latch #(\n .RV32E (RV32E),\n .DataWidth (RegFileDataWidth),\n .DummyInstructions(DummyInstructions),\n // SEC_CM: DATA_REG_SW.GLITCH_DETECT\n .WrenCheck (RegFileWrenCheck),\n .WordZeroVal (RegFileDataWidth'(prim_secded_pkg::SecdedInv3932ZeroWord))\n ) register_file_i (\n .clk_i (clk),\n .rst_ni(rst_ni),\n\n .test_en_i (test_en_i),\n .dummy_instr_id_i(dummy_instr_id),\n .dummy_instr_wb_i(dummy_instr_wb),\n\n .raddr_a_i(rf_raddr_a),\n .rdata_a_o(rf_rdata_a_ecc),\n .raddr_b_i(rf_raddr_b),\n .rdata_b_o(rf_rdata_b_ecc),\n .waddr_a_i(rf_waddr_wb),\n .wdata_a_i(rf_wdata_wb_ecc),\n .we_a_i (rf_we_wb),\n .err_o (rf_alert_major_internal)\n );\n end\n\n ///////////////////////////////\n // Scrambling Infrastructure //\n ///////////////////////////////\n\n if (ICacheScramble) begin : gen_scramble\n\n // SEC_CM: ICACHE.MEM.SCRAMBLE\n // Scramble key valid starts with OTP returning new valid key and stays high\n // until we request a new valid key.\n assign scramble_key_valid_d = scramble_req_q ? scramble_key_valid_i :\n ic_scr_key_req ? 1'b0 :\n scramble_key_valid_q;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n scramble_key_q <= RndCnstIbexKey;\n scramble_nonce_q <= RndCnstIbexNonce;\n end else if (scramble_key_valid_i) begin\n scramble_key_q <= scramble_key_i;\n scramble_nonce_q <= scramble_nonce_i;\n end\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n scramble_key_valid_q <= 1'b1;\n scramble_req_q <= '0;\n end else begin\n scramble_key_valid_q <= scramble_key_valid_d;\n scramble_req_q <= scramble_req_d;\n end\n end\n\n // Scramble key request starts with invalidate signal from ICache and stays high\n // until we got a valid key.\n assign scramble_req_d = scramble_req_q ? ~scramble_key_valid_i : ic_scr_key_req;\n assign scramble_req_o = scramble_req_q;\n\n end else begin : gen_noscramble\n\n logic unused_scramble_inputs = scramble_key_valid_i & (|scramble_key_i) & (|RndCnstIbexKey) &\n (|scramble_nonce_i) & (|RndCnstIbexNonce) & scramble_req_q &\n ic_scr_key_req & scramble_key_valid_d & scramble_req_d;\n\n assign scramble_req_d = 1'b0;\n assign scramble_req_q = 1'b0;\n assign scramble_req_o = 1'b0;\n assign scramble_key_q = '0;\n assign scramble_nonce_q = '0;\n assign scramble_key_valid_q = 1'b1;\n assign scramble_key_valid_d = 1'b1;\n end\n\n ////////////////////////\n // Rams Instantiation //\n ////////////////////////\n\n if (ICache) begin : gen_rams\n\n for (genvar way = 0; way < IC_NUM_WAYS; way++) begin : gen_rams_inner\n\n if (ICacheScramble) begin : gen_scramble_rams\n\n // SEC_CM: ICACHE.MEM.SCRAMBLE\n // Tag RAM instantiation\n prim_ram_1p_scr #(\n .Width (TagSizeECC),\n .Depth (IC_NUM_LINES),\n .DataBitsPerMask (TagSizeECC),\n .EnableParity (0),\n .DiffWidth (TagSizeECC),\n .NumAddrScrRounds (NumAddrScrRounds),\n .NumDiffRounds (NumDiffRounds)\n ) tag_bank (\n .clk_i,\n .rst_ni,\n\n .key_valid_i (scramble_key_valid_q),\n .key_i (scramble_key_q),\n .nonce_i (scramble_nonce_q),\n\n .req_i (ic_tag_req[way]),\n\n .gnt_o (),\n .write_i (ic_tag_write),\n .addr_i (ic_tag_addr),\n .wdata_i (ic_tag_wdata),\n .wmask_i ({TagSizeECC{1'b1}}),\n .intg_error_i(1'b0),\n\n .rdata_o (ic_tag_rdata[way]),\n .rvalid_o (),\n .raddr_o (),\n .rerror_o (),\n .cfg_i (ram_cfg_i)\n );\n\n // Data RAM instantiation\n prim_ram_1p_scr #(\n .Width (LineSizeECC),\n .Depth (IC_NUM_LINES),\n .DataBitsPerMask (LineSizeECC),\n .ReplicateKeyStream (1),\n .EnableParity (0),\n .DiffWidth (LineSizeECC),\n .NumAddrScrRounds (NumAddrScrRounds),\n .NumDiffRounds (NumDiffRounds)\n ) data_bank (\n .clk_i,\n .rst_ni,\n\n .key_valid_i (scramble_key_valid_q),\n .key_i (scramble_key_q),\n .nonce_i (scramble_nonce_q),\n\n .req_i (ic_data_req[way]),\n\n .gnt_o (),\n .write_i (ic_data_write),\n .addr_i (ic_data_addr),\n .wdata_i (ic_data_wdata),\n .wmask_i ({LineSizeECC{1'b1}}),\n .intg_error_i(1'b0),\n\n .rdata_o (ic_data_rdata[way]),\n .rvalid_o (),\n .raddr_o (),\n .rerror_o (),\n .cfg_i (ram_cfg_i)\n );\n\n `ifdef INC_ASSERT\n // Sample scramble key whenever it is valid for use in the assertions below. This may be\n // redundant with the sampling performed in the actual design, but that is okay because\n // the assertions exist to check the correct functioning of the design.\n logic [SCRAMBLE_KEY_W-1:0] sampled_scramble_key;\n always_ff @(posedge clk_i, negedge rst_ni) begin\n if (!rst_ni) begin\n sampled_scramble_key <= 'x;\n end else if (scramble_key_valid_i) begin\n sampled_scramble_key <= scramble_key_i;\n end\n end\n\n // Ensure that when a scramble key is received, it is correctly applied to the icache\n // scrambled memory primitives. The upper bound in the cycle ranges below is not exact,\n // but it should not take more than 10 cycles.\n `ASSERT(ScrambleKeyAppliedAtTagBank_A,\n scramble_key_valid_i\n |-> ##[0:10]\n tag_bank.key_valid_i && (tag_bank.key_i == sampled_scramble_key),\n clk_i, !rst_ni\n )\n `ASSERT(ScrambleKeyAppliedAtDataBank_A,\n scramble_key_valid_i\n |-> ##[0:10]\n data_bank.key_valid_i && (data_bank.key_i == sampled_scramble_key),\n clk_i, !rst_ni\n )\n `endif\n\n end else begin : gen_noscramble_rams\n\n // Tag RAM instantiation\n prim_ram_1p #(\n .Width (TagSizeECC),\n .Depth (IC_NUM_LINES),\n .DataBitsPerMask (TagSizeECC)\n ) tag_bank (\n .clk_i,\n\n .req_i (ic_tag_req[way]),\n\n .write_i (ic_tag_write),\n .addr_i (ic_tag_addr),\n .wdata_i (ic_tag_wdata),\n .wmask_i ({TagSizeECC{1'b1}}),\n\n .rdata_o (ic_tag_rdata[way]),\n .cfg_i (ram_cfg_i)\n );\n\n // Data RAM instantiation\n prim_ram_1p #(\n .Width (LineSizeECC),\n .Depth (IC_NUM_LINES),\n .DataBitsPerMask (LineSizeECC)\n ) data_bank (\n .clk_i,\n\n .req_i (ic_data_req[way]),\n\n .write_i (ic_data_write),\n .addr_i (ic_data_addr),\n .wdata_i (ic_data_wdata),\n .wmask_i ({LineSizeECC{1'b1}}),\n\n .rdata_o (ic_data_rdata[way]),\n .cfg_i (ram_cfg_i)\n );\n\n end\n end\n\n end else begin : gen_norams\n\n prim_ram_1p_pkg::ram_1p_cfg_t unused_ram_cfg;\n logic unused_ram_inputs;\n\n assign unused_ram_cfg = ram_cfg_i;\n assign unused_ram_inputs = (|ic_tag_req) & ic_tag_write & (|ic_tag_addr) & (|ic_tag_wdata) &\n (|ic_data_req) & ic_data_write & (|ic_data_addr) & (|ic_data_wdata) &\n (|scramble_key_q) & (|scramble_nonce_q) & scramble_key_valid_q &\n scramble_key_valid_d & (|scramble_nonce_q) &\n (|NumAddrScrRounds);\n\n assign ic_tag_rdata = '{default:'b0};\n assign ic_data_rdata = '{default:'b0};\n\n end\n\n assign data_wdata_o = data_wdata_core[31:0];\n\n if (MemECC) begin : gen_mem_wdata_ecc\n prim_buf #(.Width(7)) u_prim_buf_data_wdata_intg (\n .in_i (data_wdata_core[38:32]),\n .out_o(data_wdata_intg_o)\n );\n end else begin : gen_no_mem_ecc\n assign data_wdata_intg_o = '0;\n end\n\n // Redundant lockstep core implementation\n if (Lockstep) begin : gen_lockstep\n // SEC_CM: LOGIC.SHADOW\n // Note: certain synthesis tools like DC are very smart at optimizing away redundant logic.\n // Hence, we have to insert an optimization barrier at the IOs of the lockstep Ibex.\n // This is achieved by manually buffering each bit using prim_buf.\n // Our Xilinx and DC synthesis flows make sure that these buffers cannot be optimized away\n // using keep attributes (Vivado) and size_only constraints (DC).\n\n localparam int NumBufferBits = $bits({\n hart_id_i,\n boot_addr_i,\n instr_req_o,\n instr_gnt_i,\n instr_rvalid_i,\n instr_addr_o,\n instr_rdata_core,\n instr_err_i,\n data_req_o,\n data_gnt_i,\n data_rvalid_i,\n data_we_o,\n data_be_o,\n data_addr_o,\n data_wdata_core,\n data_rdata_core,\n data_err_i,\n dummy_instr_id,\n dummy_instr_wb,\n rf_raddr_a,\n rf_raddr_b,\n rf_waddr_wb,\n rf_we_wb,\n rf_wdata_wb_ecc,\n rf_rdata_a_ecc,\n rf_rdata_b_ecc,\n ic_tag_req,\n ic_tag_write,\n ic_tag_addr,\n ic_tag_wdata,\n ic_data_req,\n ic_data_write,\n ic_data_addr,\n ic_data_wdata,\n scramble_key_valid_i,\n ic_scr_key_req,\n irq_software_i,\n irq_timer_i,\n irq_external_i,\n irq_fast_i,\n irq_nm_i,\n irq_pending,\n debug_req_i,\n crash_dump_o,\n double_fault_seen_o,\n fetch_enable_i,\n core_busy_d\n });\n\n logic [NumBufferBits-1:0] buf_in, buf_out;\n\n logic [31:0] hart_id_local;\n logic [31:0] boot_addr_local;\n\n logic instr_req_local;\n logic instr_gnt_local;\n logic instr_rvalid_local;\n logic [31:0] instr_addr_local;\n logic [MemDataWidth-1:0] instr_rdata_local;\n logic instr_err_local;\n\n logic data_req_local;\n logic data_gnt_local;\n logic data_rvalid_local;\n logic data_we_local;\n logic [3:0] data_be_local;\n logic [31:0] data_addr_local;\n logic [MemDataWidth-1:0] data_wdata_local;\n logic [MemDataWidth-1:0] data_rdata_local;\n logic data_err_local;\n\n logic dummy_instr_id_local;\n logic dummy_instr_wb_local;\n logic [4:0] rf_raddr_a_local;\n logic [4:0] rf_raddr_b_local;\n logic [4:0] rf_waddr_wb_local;\n logic rf_we_wb_local;\n logic [RegFileDataWidth-1:0] rf_wdata_wb_ecc_local;\n logic [RegFileDataWidth-1:0] rf_rdata_a_ecc_local;\n logic [RegFileDataWidth-1:0] rf_rdata_b_ecc_local;\n\n logic [IC_NUM_WAYS-1:0] ic_tag_req_local;\n logic ic_tag_write_local;\n logic [IC_INDEX_W-1:0] ic_tag_addr_local;\n logic [TagSizeECC-1:0] ic_tag_wdata_local;\n logic [IC_NUM_WAYS-1:0] ic_data_req_local;\n logic ic_data_write_local;\n logic [IC_INDEX_W-1:0] ic_data_addr_local;\n logic [LineSizeECC-1:0] ic_data_wdata_local;\n logic scramble_key_valid_local;\n logic ic_scr_key_req_local;\n\n logic irq_software_local;\n logic irq_timer_local;\n logic irq_external_local;\n logic [14:0] irq_fast_local;\n logic irq_nm_local;\n logic irq_pending_local;\n\n logic debug_req_local;\n crash_dump_t crash_dump_local;\n logic double_fault_seen_local;\n ibex_mubi_t fetch_enable_local;\n\n ibex_mubi_t core_busy_local;\n\n assign buf_in = {\n hart_id_i,\n boot_addr_i,\n instr_req_o,\n instr_gnt_i,\n instr_rvalid_i,\n instr_addr_o,\n instr_rdata_core,\n instr_err_i,\n data_req_o,\n data_gnt_i,\n data_rvalid_i,\n data_we_o,\n data_be_o,\n data_addr_o,\n data_wdata_core,\n data_rdata_core,\n data_err_i,\n dummy_instr_id,\n dummy_instr_wb,\n rf_raddr_a,\n rf_raddr_b,\n rf_waddr_wb,\n rf_we_wb,\n rf_wdata_wb_ecc,\n rf_rdata_a_ecc,\n rf_rdata_b_ecc,\n ic_tag_req,\n ic_tag_write,\n ic_tag_addr,\n ic_tag_wdata,\n ic_data_req,\n ic_data_write,\n ic_data_addr,\n ic_data_wdata,\n scramble_key_valid_q,\n ic_scr_key_req,\n irq_software_i,\n irq_timer_i,\n irq_external_i,\n irq_fast_i,\n irq_nm_i,\n irq_pending,\n debug_req_i,\n crash_dump_o,\n double_fault_seen_o,\n fetch_enable_i,\n core_busy_d\n };\n\n assign {\n hart_id_local,\n boot_addr_local,\n instr_req_local,\n instr_gnt_local,\n instr_rvalid_local,\n instr_addr_local,\n instr_rdata_local,\n instr_err_local,\n data_req_local,\n data_gnt_local,\n data_rvalid_local,\n data_we_local,\n data_be_local,\n data_addr_local,\n data_wdata_local,\n data_rdata_local,\n data_err_local,\n dummy_instr_id_local,\n dummy_instr_wb_local,\n rf_raddr_a_local,\n rf_raddr_b_local,\n rf_waddr_wb_local,\n rf_we_wb_local,\n rf_wdata_wb_ecc_local,\n rf_rdata_a_ecc_local,\n rf_rdata_b_ecc_local,\n ic_tag_req_local,\n ic_tag_write_local,\n ic_tag_addr_local,\n ic_tag_wdata_local,\n ic_data_req_local,\n ic_data_write_local,\n ic_data_addr_local,\n ic_data_wdata_local,\n scramble_key_valid_local,\n ic_scr_key_req_local,\n irq_software_local,\n irq_timer_local,\n irq_external_local,\n irq_fast_local,\n irq_nm_local,\n irq_pending_local,\n debug_req_local,\n crash_dump_local,\n double_fault_seen_local,\n fetch_enable_local,\n core_busy_local\n } = buf_out;\n\n // Manually buffer all input signals.\n prim_buf #(.Width(NumBufferBits)) u_signals_prim_buf (\n .in_i(buf_in),\n .out_o(buf_out)\n );\n\n logic [TagSizeECC-1:0] ic_tag_rdata_local [IC_NUM_WAYS];\n logic [LineSizeECC-1:0] ic_data_rdata_local [IC_NUM_WAYS];\n for (genvar k = 0; k < IC_NUM_WAYS; k++) begin : gen_ways\n prim_buf #(.Width(TagSizeECC)) u_tag_prim_buf (\n .in_i(ic_tag_rdata[k]),\n .out_o(ic_tag_rdata_local[k])\n );\n prim_buf #(.Width(LineSizeECC)) u_data_prim_buf (\n .in_i(ic_data_rdata[k]),\n .out_o(ic_data_rdata_local[k])\n );\n end\n\n logic lockstep_alert_minor_local, lockstep_alert_major_internal_local;\n logic lockstep_alert_major_bus_local;\n\n ibex_lockstep #(\n .PMPEnable (PMPEnable),\n .PMPGranularity (PMPGranularity),\n .PMPNumRegions (PMPNumRegions),\n .MHPMCounterNum (MHPMCounterNum),\n .MHPMCounterWidth (MHPMCounterWidth),\n .RV32E (RV32E),\n .RV32M (RV32M),\n .RV32B (RV32B),\n .BranchTargetALU (BranchTargetALU),\n .ICache (ICache),\n .ICacheECC (ICacheECC),\n .BusSizeECC (BusSizeECC),\n .TagSizeECC (TagSizeECC),\n .LineSizeECC (LineSizeECC),\n .BranchPredictor (BranchPredictor),\n .DbgTriggerEn (DbgTriggerEn),\n .DbgHwBreakNum (DbgHwBreakNum),\n .WritebackStage (WritebackStage),\n .ResetAll (ResetAll),\n .RndCnstLfsrSeed (RndCnstLfsrSeed),\n .RndCnstLfsrPerm (RndCnstLfsrPerm),\n .SecureIbex (SecureIbex),\n .DummyInstructions(DummyInstructions),\n .RegFileECC (RegFileECC),\n .RegFileDataWidth (RegFileDataWidth),\n .MemECC (MemECC),\n .DmHaltAddr (DmHaltAddr),\n .DmExceptionAddr (DmExceptionAddr)\n ) u_ibex_lockstep (\n .clk_i (clk),\n .rst_ni (rst_ni),\n\n .hart_id_i (hart_id_local),\n .boot_addr_i (boot_addr_local),\n\n .instr_req_i (instr_req_local),\n .instr_gnt_i (instr_gnt_local),\n .instr_rvalid_i (instr_rvalid_local),\n .instr_addr_i (instr_addr_local),\n .instr_rdata_i (instr_rdata_local),\n .instr_err_i (instr_err_local),\n\n .data_req_i (data_req_local),\n .data_gnt_i (data_gnt_local),\n .data_rvalid_i (data_rvalid_local),\n .data_we_i (data_we_local),\n .data_be_i (data_be_local),\n .data_addr_i (data_addr_local),\n .data_wdata_i (data_wdata_local),\n .data_rdata_i (data_rdata_local),\n .data_err_i (data_err_local),\n\n .dummy_instr_id_i (dummy_instr_id_local),\n .dummy_instr_wb_i (dummy_instr_wb_local),\n .rf_raddr_a_i (rf_raddr_a_local),\n .rf_raddr_b_i (rf_raddr_b_local),\n .rf_waddr_wb_i (rf_waddr_wb_local),\n .rf_we_wb_i (rf_we_wb_local),\n .rf_wdata_wb_ecc_i (rf_wdata_wb_ecc_local),\n .rf_rdata_a_ecc_i (rf_rdata_a_ecc_local),\n .rf_rdata_b_ecc_i (rf_rdata_b_ecc_local),\n\n .ic_tag_req_i (ic_tag_req_local),\n .ic_tag_write_i (ic_tag_write_local),\n .ic_tag_addr_i (ic_tag_addr_local),\n .ic_tag_wdata_i (ic_tag_wdata_local),\n .ic_tag_rdata_i (ic_tag_rdata_local),\n .ic_data_req_i (ic_data_req_local),\n .ic_data_write_i (ic_data_write_local),\n .ic_data_addr_i (ic_data_addr_local),\n .ic_data_wdata_i (ic_data_wdata_local),\n .ic_data_rdata_i (ic_data_rdata_local),\n .ic_scr_key_valid_i (scramble_key_valid_local),\n .ic_scr_key_req_i (ic_scr_key_req_local),\n\n .irq_software_i (irq_software_local),\n .irq_timer_i (irq_timer_local),\n .irq_external_i (irq_external_local),\n .irq_fast_i (irq_fast_local),\n .irq_nm_i (irq_nm_local),\n .irq_pending_i (irq_pending_local),\n\n .debug_req_i (debug_req_local),\n .crash_dump_i (crash_dump_local),\n .double_fault_seen_i (double_fault_seen_local),\n\n .fetch_enable_i (fetch_enable_local),\n .alert_minor_o (lockstep_alert_minor_local),\n .alert_major_internal_o (lockstep_alert_major_internal_local),\n .alert_major_bus_o (lockstep_alert_major_bus_local),\n .core_busy_i (core_busy_local),\n .test_en_i (test_en_i),\n .scan_rst_ni (scan_rst_ni)\n );\n\n prim_buf u_prim_buf_alert_minor (\n .in_i (lockstep_alert_minor_local),\n .out_o(lockstep_alert_minor)\n );\n\n prim_buf u_prim_buf_alert_major_internal (\n .in_i (lockstep_alert_major_internal_local),\n .out_o(lockstep_alert_major_internal)\n );\n\n prim_buf u_prim_buf_alert_major_bus (\n .in_i (lockstep_alert_major_bus_local),\n .out_o(lockstep_alert_major_bus)\n );\n\n end else begin : gen_no_lockstep\n assign lockstep_alert_major_internal = 1'b0;\n assign lockstep_alert_major_bus = 1'b0;\n assign lockstep_alert_minor = 1'b0;\n logic unused_scan;\n assign unused_scan = scan_rst_ni;\n end\n\n assign alert_major_internal_o = core_alert_major_internal |\n lockstep_alert_major_internal |\n rf_alert_major_internal;\n assign alert_major_bus_o = core_alert_major_bus | lockstep_alert_major_bus;\n assign alert_minor_o = core_alert_minor | lockstep_alert_minor;\n\n // X checks for top-level outputs\n `ASSERT_KNOWN(IbexInstrReqX, instr_req_o)\n `ASSERT_KNOWN_IF(IbexInstrReqPayloadX, instr_addr_o, instr_req_o)\n\n `ASSERT_KNOWN(IbexDataReqX, data_req_o)\n `ASSERT_KNOWN_IF(IbexDataReqPayloadX,\n {data_we_o, data_be_o, data_addr_o, data_wdata_o, data_wdata_intg_o}, data_req_o)\n\n `ASSERT_KNOWN(IbexScrambleReqX, scramble_req_o)\n `ASSERT_KNOWN(IbexDoubleFaultSeenX, double_fault_seen_o)\n `ASSERT_KNOWN(IbexAlertMinorX, alert_minor_o)\n `ASSERT_KNOWN(IbexAlertMajorInternalX, alert_major_internal_o)\n `ASSERT_KNOWN(IbexAlertMajorBusX, alert_major_bus_o)\n `ASSERT_KNOWN(IbexCoreSleepX, core_sleep_o)\n\n // X check for top-level inputs\n `ASSERT_KNOWN(IbexTestEnX, test_en_i)\n `ASSERT_KNOWN(IbexRamCfgX, ram_cfg_i)\n `ASSERT_KNOWN(IbexHartIdX, hart_id_i)\n `ASSERT_KNOWN(IbexBootAddrX, boot_addr_i)\n\n `ASSERT_KNOWN(IbexInstrGntX, instr_gnt_i)\n `ASSERT_KNOWN(IbexInstrRValidX, instr_rvalid_i)\n `ASSERT_KNOWN_IF(IbexInstrRPayloadX,\n {instr_rdata_i, instr_rdata_intg_i, instr_err_i}, instr_rvalid_i)\n\n `ASSERT_KNOWN(IbexDataGntX, data_gnt_i)\n `ASSERT_KNOWN(IbexDataRValidX, data_rvalid_i)\n `ifdef INC_ASSERT\n // Ibex can have a maximum of 2 accesses outstanding on the DSide. This is because it does not\n // speculative data accesses so the only requests that can be in flight must relate to a single\n // ongoing load or store instruction. Due to unaligned access support a single load or store can\n // generate 2 accesses.\n localparam int unsigned MaxOutstandingDSideAccesses = 2;\n\n typedef struct packed {\n logic valid;\n logic is_read;\n } pending_access_t;\n\n pending_access_t pending_dside_accesses_q[MaxOutstandingDSideAccesses];\n pending_access_t pending_dside_accesses_d[MaxOutstandingDSideAccesses];\n pending_access_t pending_dside_accesses_shifted[MaxOutstandingDSideAccesses];\n\n for (genvar i = 0; i < MaxOutstandingDSideAccesses; i++) begin : g_dside_tracker\n always_ff @(posedge clk or negedge rst_ni) begin\n if (!rst_ni) begin\n pending_dside_accesses_q[i] <= '0;\n end else begin\n pending_dside_accesses_q[i] <= pending_dside_accesses_d[i];\n end\n end\n\n always_comb begin\n pending_dside_accesses_shifted[i] = pending_dside_accesses_q[i];\n\n if (data_rvalid_i) begin\n if (i != MaxOutstandingDSideAccesses - 1) begin\n pending_dside_accesses_shifted[i] = pending_dside_accesses_q[i + 1];\n end else begin\n pending_dside_accesses_shifted[i] = '0;\n end\n end\n end\n\n if (i == 0) begin : g_track_first_entry\n always_comb begin\n pending_dside_accesses_d[i] = pending_dside_accesses_shifted[i];\n\n if (data_req_o && data_gnt_i && !pending_dside_accesses_shifted[i].valid) begin\n pending_dside_accesses_d[i].valid = 1'b1;\n pending_dside_accesses_d[i].is_read = ~data_we_o;\n end\n end\n end else begin : g_track_other_entries\n always_comb begin\n pending_dside_accesses_d[i] = pending_dside_accesses_shifted[i];\n\n if (data_req_o && data_gnt_i && pending_dside_accesses_shifted[i - 1].valid &&\n !pending_dside_accesses_shifted[i].valid) begin\n pending_dside_accesses_d[i].valid = 1'b1;\n pending_dside_accesses_d[i].is_read = ~data_we_o;\n end\n end\n end\n end\n\n // We should never start a new data request if we've already got the maximum outstanding. We can\n // start a new request in the same cycle an old one ends, in which case we'll see all pending\n // accesses valid but one will be ending this cycle so the empty slot can be immediately used by\n // the new request.\n `ASSERT(MaxOutstandingDSideAccessesCorrect,\n data_req_o |->\n ~pending_dside_accesses_q[MaxOutstandingDSideAccesses-1].valid | data_rvalid_i)\n\n // Should only see a request response if we're expecting one\n `ASSERT(PendingAccessTrackingCorrect, data_rvalid_i |-> pending_dside_accesses_q[0])\n\n if (SecureIbex) begin : g_secure_ibex_mem_assert\n // For SecureIbex responses to both writes and reads must specify rdata and rdata_intg (for\n // writes rdata is effectively ignored by rdata_intg still checked against rdata)\n `ASSERT_KNOWN_IF(IbexDataRPayloadX, {data_rdata_i, data_rdata_intg_i},\n data_rvalid_i)\n end else begin : g_no_secure_ibex_mem_assert\n // Without SecureIbex data_rdata_i and data_rdata_intg_i are only relevant to reads. Check\n // neither are X on a response to a read.\n `ASSERT_KNOWN_IF(IbexDataRPayloadX, {data_rdata_i, data_rdata_intg_i},\n data_rvalid_i & pending_dside_accesses_q[0].is_read)\n end\n\n // data_err_i relevant to both reads and writes. Check it isn't X on any response.\n `ASSERT_KNOWN_IF(IbexDataRErrPayloadX, data_err_i, data_rvalid_i)\n\n `ifdef RVFI\n // Tracking logic and predictor for double_fault_seen_o output, relies on RVFI so only include\n // it where RVFI is available.\n\n // Returns 1'b1 if the provided instruction decodes to one that would write the sync_exc_bit of\n // the CPUCTRLSTS CSR\n function automatic logic insn_write_sync_exc_seen(logic [31:0] insn_bits);\n return (insn_bits[6:0] == OPCODE_SYSTEM) &&\n (insn_bits[14:12] inside {3'b001, 3'b010, 3'b011, 3'b101}) &&\n (insn_bits[31:20] == CSR_CPUCTRLSTS);\n endfunction\n\n // Given an instruction that writes the sync_exc_bit of the CPUCTRLSTS CSR along with the value\n // of the rs1 register read for that instruction and the current predicted sync_exc_bit bit\n // return the new value of the sync_exc_bit after the instruction is executed.\n function automatic logic new_sync_exc_bit(logic [31:0] insn_bits, logic [31:0] rs1,\n logic cur_bit);\n logic sync_exc_update_bit;\n\n sync_exc_update_bit = insn_bits[14] ? 1'b0 : rs1[6];\n\n case (insn_bits[13:12])\n 2'b01: return sync_exc_update_bit;\n 2'b10: return cur_bit | sync_exc_update_bit;\n 2'b11: return cur_bit & ~sync_exc_update_bit;\n default: return 1'bx;\n endcase\n endfunction\n\n localparam int DoubleFaultSeenLatency = 3;\n logic [DoubleFaultSeenLatency-1:0] double_fault_seen_delay_buffer;\n logic [DoubleFaultSeenLatency-2:0] double_fault_seen_delay_buffer_q;\n logic sync_exc_seen;\n logic new_sync_exc;\n logic double_fault_seen_predicted;\n\n assign new_sync_exc = rvfi_valid & rvfi_trap & ~rvfi_ext_debug_mode;\n assign double_fault_seen_predicted = sync_exc_seen & new_sync_exc;\n\n // Depending on whether the exception comes from the WB or ID/EX stage the precise timing of the\n // double_fault_seen_o output vs the double fault instruction being visible on RVFI differs. At\n // the earliest extreme it can be asserted the same cycle the instruction is visible on the\n // RVFI. Buffer the last few cycles of double_fault_seen_o output for checking. We can\n // guarantee the minimum spacing between double_fault_seen_o assertions (occurring when the\n // first instruction of an exception handler continuously double faults with a single cycle\n // memory access time) is sufficient that we'll only see a single bit set in the delay buffer.\n assign double_fault_seen_delay_buffer = {double_fault_seen_delay_buffer_q, double_fault_seen_o};\n\n always @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n double_fault_seen_delay_buffer_q <= '0;\n sync_exc_seen <= 1'b0;\n end else begin\n double_fault_seen_delay_buffer_q <=\n double_fault_seen_delay_buffer[DoubleFaultSeenLatency-2:0];\n\n if (new_sync_exc) begin\n // Set flag when we see a new synchronous exception\n sync_exc_seen <= 1'b1;\n end else if (rvfi_valid && rvfi_insn == 32'h30200073) begin\n // Clear flag when we see an MRET\n sync_exc_seen <= 1'b0;\n end else if (rvfi_valid && insn_write_sync_exc_seen(rvfi_insn)) begin\n // Update predicted sync_exc_seen when the instruction modifies the relevant CPUCTRLSTS\n // CSR bit.\n sync_exc_seen <= new_sync_exc_bit(rvfi_insn, rvfi_rs1_rdata, sync_exc_seen);\n end\n end\n end\n\n // We should only have a single assertion of double_fault_seen in the delay buffer\n `ASSERT(DoubleFaultSinglePulse, $onehot0(double_fault_seen_delay_buffer))\n // If we predict a double_fault_seen_o we should see one in the delay buffer\n `ASSERT(DoubleFaultPulseSeenOnDoubleFault,\n double_fault_seen_predicted |-> |double_fault_seen_delay_buffer)\n // If double_fault_seen_o is asserted we should see predict one occurring within a bounded time\n `ASSERT(DoubleFaultPulseOnlyOnDoubleFault,\n double_fault_seen_o |-> ##[0:DoubleFaultSeenLatency] double_fault_seen_predicted)\n `endif // RVFI\n `endif\n\n `ASSERT_KNOWN(IbexIrqX, {irq_software_i, irq_timer_i, irq_external_i, irq_fast_i, irq_nm_i})\n\n `ASSERT_KNOWN(IbexScrambleKeyValidX, scramble_key_valid_i)\n `ASSERT_KNOWN_IF(IbexScramblePayloadX, {scramble_key_i, scramble_nonce_i}, scramble_key_valid_i)\n\n `ASSERT_KNOWN(IbexDebugReqX, debug_req_i)\n `ASSERT_KNOWN(IbexFetchEnableX, fetch_enable_i)\n\n // Dummy instructions may only write to register 0, which is a special register when dummy\n // instructions are enabled.\n `ASSERT(WaddrAZeroForDummyInstr, dummy_instr_wb && rf_we_wb |-> rf_waddr_wb == '0)\n\n // Ensure the crash dump is connected to the correct internal signals\n `ASSERT(CrashDumpCurrentPCConn, crash_dump_o.current_pc === u_ibex_core.pc_id)\n `ASSERT(CrashDumpNextPCConn, crash_dump_o.next_pc === u_ibex_core.pc_if)\n `ASSERT(CrashDumpLastDataAddrConn,\n crash_dump_o.last_data_addr === u_ibex_core.load_store_unit_i.addr_last_q)\n `ASSERT(CrashDumpExceptionPCConn,\n crash_dump_o.exception_pc === u_ibex_core.cs_registers_i.mepc_q)\n `ASSERT(CrashDumpExceptionAddrConn,\n crash_dump_o.exception_addr === u_ibex_core.cs_registers_i.mtval_q)\nendmodule\n", "pr_title": "[rtl/dv] Add assertions for icache scramble keys", "pr_body": "This commit adds two assertions in `ibex_top` to ensure that the scramble key is correctly applied to the icache scrambled memory primitives. Those assertions previously existed in the module that instantiated Ibex in OpenTitan, but the reference into the generate loops was problematic for some EDA tools; see lowRISC/opentitan#17155.", "fix_patch": "diff --git a/rtl/ibex_top.sv b/rtl/ibex_top.sv\nindex 92d27cba9b..7621f21daf 100644\n--- a/rtl/ibex_top.sv\n+++ b/rtl/ibex_top.sv\n@@ -620,6 +620,36 @@ module ibex_top import ibex_pkg::*; #(\n .cfg_i (ram_cfg_i)\n );\n \n+ `ifdef INC_ASSERT\n+ // Sample scramble key whenever it is valid for use in the assertions below. This may be\n+ // redundant with the sampling performed in the actual design, but that is okay because\n+ // the assertions exist to check the correct functioning of the design.\n+ logic [SCRAMBLE_KEY_W-1:0] sampled_scramble_key;\n+ always_ff @(posedge clk_i, negedge rst_ni) begin\n+ if (!rst_ni) begin\n+ sampled_scramble_key <= 'x;\n+ end else if (scramble_key_valid_i) begin\n+ sampled_scramble_key <= scramble_key_i;\n+ end\n+ end\n+\n+ // Ensure that when a scramble key is received, it is correctly applied to the icache\n+ // scrambled memory primitives. The upper bound in the cycle ranges below is not exact,\n+ // but it should not take more than 10 cycles.\n+ `ASSERT(ScrambleKeyAppliedAtTagBank_A,\n+ scramble_key_valid_i\n+ |-> ##[0:10]\n+ tag_bank.key_valid_i && (tag_bank.key_i == sampled_scramble_key),\n+ clk_i, !rst_ni\n+ )\n+ `ASSERT(ScrambleKeyAppliedAtDataBank_A,\n+ scramble_key_valid_i\n+ |-> ##[0:10]\n+ data_bank.key_valid_i && (data_bank.key_i == sampled_scramble_key),\n+ clk_i, !rst_ni\n+ )\n+ `endif\n+\n end else begin : gen_noscramble_rams\n \n // Tag RAM instantiation\n"}
{"repo": "lowRISC/ibex", "pr_id": 1699, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": false, "sufficient_for_diagnosis": false}, "reasoning": "The generated specification includes signal name 'ctrl_fsm_cs' from the patch and lacks behavioral assertions related to DRET privilege checking."}, "generated_spec": "# `core_ibex_dut_probe_if` Design Specification\n\n## Overview\n\nThe `core_ibex_dut_probe_if` interface provides a standardized, cycle‑accurate channel for the UVM testbench to observe and control specific internal signals of the Ibex core. It is used within the `core_ibex` UVM environment to enable functional coverage, assertions, and directed stimulus without modifying the core’s external ports. All signals in this interface are synchronous to the provided clock.\n\n## Interface Characteristic\n\n- **Clock**: The interface is driven and sampled on the rising edge of the input clock.\n- **Direction of signals**: \n – Signals that originate from the DUT (inputs to the interface) are sampled by the testbench. \n – Signals that are driven by the testbench (outputs from the interface) are driven into the DUT.\n- **Reset**: The interface does not contain its own reset logic; the `reset` signal from the DUT is made visible for monitoring.\n\n## Signal Description\n\n### Observability Signals (DUT → Interface)\n\nThese signals reflect internal states of the Ibex core. The testbench shall sample them on the rising edge of the clock as defined by the provided clocking block.\n\n| Signal | Description |\n|---------------------|-------------|\n| `reset` | Indicates the core is held in reset. When asserted (high), all core state is initialised. |\n| `illegal_instr` | Asserted for one cycle when the core decodes an illegal instruction. |\n| `ecall` | Asserted for one cycle when an ECALL instruction is executed (environment call). |\n| `wfi` | Asserted for one cycle when a WFI (wait for interrupt) instruction is executed. |\n| `ebreak` | Asserted for one cycle when an EBREAK (breakpoint) instruction is executed. |\n| `dret` | Asserted for one cycle when a DRET (debug return) instruction is executed. |\n| `mret` | Asserted for one cycle when an MRET (machine‑mode return) instruction is executed. |\n| `core_sleep` | Indicates the core is in a low‑power sleep state (after WFI). Remains asserted until an interrupt or debug request wakes the core. |\n| `alert_minor` | Asserted for a configurable number of cycles when a minor security event is detected (e.g., ECC correctable errors). |\n| `alert_major_internal` | Asserted for a configurable number of cycles when a major internal security event is detected (e.g., register file ECC error, PC integrity violation, shadow CSR mismatch). |\n| `alert_major_bus` | Asserted for a configurable number of cycles when a major bus integrity event is detected (e.g., load data check‑bit mismatch). |\n| `priv_mode` | Current privilege level of the core – `PrivLvlM` (Machine) or `PrivLvlU` (User). |\n| `ctrl_fsm_cs` | Current state of the core’s main control finite‑state machine in the ID/EX pipeline stage. |\n\n### Control Signals (Interface → DUT)\n\nThese signals are driven by the testbench to influence core behaviour. They shall be driven on the rising edge of the clock as defined by the clocking block.\n\n| Signal | Description |\n|-----------------|-------------|\n| `fetch_enable` | Controls instruction fetching. When de‑asserted, the core stops fetching new instructions (the pipeline is stalled). Must be initialised to a known value before core operation starts. |\n| `debug_req` | Requests the core to enter Debug Mode (as defined by the RISC‑V Debug Specification). Asserted by the testbench to trigger synchronous debug entry. The testbench must de‑assert this signal after the core acknowledges the request. |\n\n## Clocking Block Behaviour\n\nA clocking block named `dut_cb` is provided for use in testbench components (e.g., drivers, monitors). It defines the timing discipline for all signals.\n\n- **Sampling** (`input` items in clocking block): \n All observability signals (from DUT) are sampled at the **beginning** of each clock cycle (on the rising edge). This ensures that the testbench sees the exact value driven by the core in that cycle.\n\n- **Driving** (`output` items in clocking block): \n The control signals (`fetch_enable`, `debug_req`) are driven **synchronously** on the rising edge of the clock. The testbench must ensure that these signals are stable before the clock edge and held long enough to meet the core’s input setup/hold requirements.\n\n### Clocking Block Signal Listing\n\n| Direction | Signals |\n|-----------|---------|\n| Output (driven by testbench) | `fetch_enable`, `debug_req` |\n| Input (sampled from DUT) | `reset`, `illegal_instr`, `ecall`, `wfi`, `ebreak`, `dret`, `mret`, `core_sleep`, `alert_minor`, `alert_major_internal`, `alert_major_bus`, `priv_mode`, `ctrl_fsm_cs` |\n\n## Initialisation Behaviour\n\nAt the start of simulation (time zero), the interface shall initialise the driven signal `debug_req` to logic `0`. This prevents an inadvertent debug request from being issued before the testbench has configured the core and debug environment.\n\n*Note*: The `fetch_enable` signal is not initialised by the interface; the testbench shall drive it to an appropriate value (typically `1`) before the core starts fetching.\n\n## Usage Rules\n\n1. All transactions between the testbench and the DUT via this interface must be synchronised using the provided clocking block. Direct assignments outside the clocking block are not recommended.\n2. The testbench must ensure that `debug_req` is asserted only when the core is not in Debug Mode and is not already responding to a previous debug request.\n3. The observability signals are **purely for monitoring**; they are inputs to the interface and must not be driven by the testbench.\n4. The interface does **not** perform any override of the DUT’s internal logic – it only samples and drives according to the timing model defined by the clocking block.\n5. The interface shall not be used to drive signals that are not listed in the clocking block’s output list.\n\n## Relationship to Core Functional Behaviour\n\nThe meaning of each observability signal corresponds to the Ibex core’s documented behaviour:\n\n- **Exceptions and Interrupts** (`illegal_instr`, `ecall`, `ebreak`, `mret`, `dret`): \n Refer to the core’s exception/interrupt handling specification. These signals are asserted for exactly one cycle when the corresponding event occurs in the execution pipeline.\n\n- **Security Alerts** (`alert_minor`, `alert_major_internal`, `alert_major_bus`): \n Defined in the core’s security feature documentation. The duration of the pulse may vary depending on the event; typically held for a configurable number of cycles.\n\n- **Debug** (`debug_req`): \n Complies with the RISC‑V Debug Specification v0.13. The testbench should assert this signal when it requires the core to enter Debug Mode. The core will respond by halting at a safe instruction boundary and then asserting its internal debug flag.\n\n- **Core Sleep** (`core_sleep`): \n Asserted when the core has executed a WFI instruction and no interrupt or debug request is pending. Remains asserted until an event wakes the core.\n\n- **Privilege Mode** (`priv_mode`): \n Reflects the current mode (Machine or User) as defined by the `mstatus` CSR. Changed only by MRET, SRET (if supported), or exception entry.\n\n- **Control FSM State** (`ctrl_fsm_cs`): \n Mirrors the state of the ID/EX stage control FSM. Useful for tracking pipeline progress and stalling conditions.\n\nThis interface is purely a testbench observation and control point; it does **not** alter the functional correctness of the core. The testbench shall rely on these signals only for verification purposes and must not assume they affect core behaviour in simulation.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n// Interface to probe DUT internal signal\ninterface core_ibex_dut_probe_if(input logic clk);\n logic reset;\n logic illegal_instr;\n logic ecall;\n logic wfi;\n logic ebreak;\n logic dret;\n logic mret;\n ibex_pkg::fetch_enable_t fetch_enable;\n logic core_sleep;\n logic alert_minor;\n logic alert_major_internal;\n logic alert_major_bus;\n logic debug_req;\n ibex_pkg::priv_lvl_e priv_mode;\n ibex_pkg::ctrl_fsm_e ctrl_fsm_cs;\n\n clocking dut_cb @(posedge clk);\n output fetch_enable;\n output debug_req;\n input reset;\n input illegal_instr;\n input ecall;\n input wfi;\n input ebreak;\n input dret;\n input mret;\n input core_sleep;\n input alert_minor;\n input alert_major_internal;\n input alert_major_bus;\n input priv_mode;\n input ctrl_fsm_cs;\n endclocking\n\n initial begin\n debug_req = 1'b0;\n end\n\nendinterface\n", "pr_title": "[dv] Check privilege correctly after illegal insn", "pr_body": "Timing fix for dret_test and modelling controller behaviour for `FLUSH` transition.\r\n\r\nResolves #1691\r\n\r\nSigned-off-by: Canberk Topal <ctopal@lowrisc.org>", "fix_patch": "diff --git a/dv/uvm/core_ibex/env/core_ibex_dut_probe_if.sv b/dv/uvm/core_ibex/env/core_ibex_dut_probe_if.sv\nindex 43cab77fb9..24a35f93dc 100644\n--- a/dv/uvm/core_ibex/env/core_ibex_dut_probe_if.sv\n+++ b/dv/uvm/core_ibex/env/core_ibex_dut_probe_if.sv\n@@ -18,6 +18,7 @@ interface core_ibex_dut_probe_if(input logic clk);\n logic alert_major_bus;\n logic debug_req;\n ibex_pkg::priv_lvl_e priv_mode;\n+ ibex_pkg::ctrl_fsm_e ctrl_fsm_cs;\n \n clocking dut_cb @(posedge clk);\n output fetch_enable;\n@@ -34,6 +35,7 @@ interface core_ibex_dut_probe_if(input logic clk);\n input alert_major_internal;\n input alert_major_bus;\n input priv_mode;\n+ input ctrl_fsm_cs;\n endclocking\n \n initial begin\n"}
{"repo": "lowRISC/ibex", "pr_id": 903, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": false, "sufficient_for_diagnosis": true}, "reasoning": "The generated specification uses signal names introduced by the patch (region_match_gt, region_match_lt, region_match_eq, region_match_all), violating the no_patch_leakage check."}, "generated_spec": "# Behavioral Specification for Ibex Physical Memory Protection (PMP) Module\n\n## 1. Overview\n\nThe Physical Memory Protection (PMP) module provides region-based access control for memory and I/O transactions in accordance with the RISC-V Privileged Specification (version 1.11). It monitors address requests from multiple independent channels (e.g., instruction fetch and load/store) and checks them against a set of programmable PMP regions. The module asserts an error signal for each channel when the access is not permitted.\n\nThe module is only present in the design when the top‑level `PMPEnable` parameter is set to 1.\n\n## 2. Configuration Parameters\n\n| Parameter | Legal Range | Description |\n|-------------------|-------------|-------------|\n| `PMPGranularity` | 0–31 | Minimum region granularity in bytes: 2^(G+2). Affects address matching and disables NA4 mode when >0. |\n| `PMPNumChan` | ≥1 | Number of independent access check channels (e.g., 1 for I‑side, 1 for D‑side). |\n| `PMPNumRegions` | 1–16 | Number of implemented PMP regions (0 is not allowed when the module is instantiated). |\n\n## 3. Interfaces\n\n### 3.1 Inputs\n- **Clock and reset** (active-low asynchronous reset).\n- **PMP configuration registers** for each region: mode (OFF, NA4, NAPOT, TOR), read/write/execute permissions, and a **lock** bit. The address register for each region is also provided.\n- **Privilege level** for each channel (Machine or User/Supervisor).\n- **Address request** (34‑bit physical address) for each channel.\n- **Access type** for each channel: read, write, or execute.\n\n### 3.2 Outputs\n- **Access error** for each channel: asserted when the access is not permitted; de‑asserted when access is allowed.\n\n## 4. Functional Behavior\n\n### 4.1 Address Matching\n\nEach PMP region defines an address range using its mode and the associated address register(s). The module performs a logical comparison between the incoming request address and each region’s range. A region is said to **match** when the request address falls within its defined range, under the qualifications below:\n\n- **OFF mode**: The region is disabled and never matches.\n- **NA4 mode** (only valid when `PMPGranularity = 0`): The region covers exactly 4 bytes starting at the programmed address (the address must be aligned to 4 bytes). \n If `PMPGranularity > 0`, NA4 mode is not supported and is treated as OFF mode.\n- **NAPOT mode**: The region covers a naturally aligned power‑of‑two size. The size is derived from the least‑significant set of contiguous 1s in the programmed address; matching ignores address bits that fall within the programmed granule. \n The minimum size is **2^(PMPGranularity+2)** bytes when `PMPGranularity > 0`.\n- **TOR mode**: The region covers all addresses from the *previous* region’s address register (or zero for region 0) up to but not including the region’s own address register. The region matches when the request address is greater than or equal to the start address and less than the end address.\n\nAll comparisons use address bits from the most‑significant down to bit (PMPGranularity+2), effectively ignoring the `PMPGranularity+2` least‑significant address bits for matching purposes. This implements the minimum region granularity.\n\n### 4.2 Permission Validation\n\nFor a given channel, each region that matches the request address is checked to see if it **grants** the requested access type. The required permission for an access type is:\n\n| Access Type | Required Permission Bit |\n|-------------|------------------------|\n| Execute | `exec` |\n| Write | `write` |\n| Read | `read` |\n\nA region is considered to permit the access when the corresponding permission bit is set.\n\n### 4.3 Access Fault Determination\n\nThe access fault output for a channel is determined by the following rules:\n\n1. **Base default**: \n - When the privilege level is **User or Supervisor** (i.e., not Machine mode), the default is to **deny** access (fault). \n - When the privilege level is **Machine mode**, the default is to **allow** access (no fault).\n\n2. **Overriding by matching regions** (static priority): \n The regions are evaluated in order from highest index (PMPNumRegions‑1) down to 0. For each matching region, the final fault decision is overridden according to the rules below. Once an override occurs, lower‑index regions are ignored. If multiple regions match, the **lowest‑numbered** (highest priority) region among those that caused an override actually takes effect. (In the implementation, the loop runs from highest to lowest index so that the lowest‑index match wins.)\n\n - **Machine mode access**: \n A matching region *allows* the access (clears the fault) unless the region’s lock bit is set AND the required permission is not granted. \n In other words, if the region is locked and does not grant the required permission, a fault is raised. If the region is unlocked, the access is allowed regardless of the permission bits (Machine mode has unrestricted access to unlocked regions). If the region is locked and does grant the required permission, access is also allowed.\n\n - **User/Supervisor mode access**: \n A matching region *allows* the access only if the required permission is granted. The lock bit has no effect in determining faults for non‑Machine modes. If the required permission is not granted, a fault is raised.\n\n3. **Result**: \n The final fault decision is applied to the corresponding channel’s error output. If a fault is raised, the output is asserted; otherwise it is de‑asserted.\n\n### 4.4 Effects of PMP Granularity\n\nThe `PMPGranularity` parameter reduces the hardware cost by increasing the minimum region size. This parameter affects address matching as described above, and additionally:\n\n- NA4 mode becomes unavailable (treated as OFF) when `PMPGranularity > 0`.\n- All region boundaries (both start and end addresses) are effectively rounded down to a multiple of `2^(PMPGranularity+2)` bytes. The programmer must ensure the programmed addresses respect this alignment; otherwise, the effective range may be larger than intended.\n\n### 4.5 Lock Bit Behavior\n\nThe lock bit (provided in the PMP configuration register for each region) interacts only with Machine‑mode accesses, as described in 4.3. It does not affect fault determination for User/Supervisor mode accesses. The lock bit is not used for any other purpose in the PMP module.\n\n### 4.6 Multiple Channels and Concurrent Checks\n\nEach channel operates independently. The same set of PMP configuration registers is used for all channels. There is no ordering or dependency between channels; the module computes the fault signal for every channel in the same clock cycle.\n\n## 5. Reset Behavior\n\nUpon reset (asynchronous reset asserted, then de‑asserted synchronously), the module’s internal state is initialized. The PMP configuration registers are not part of this module; they are assumed to be reset externally (typically to zero). With all regions in OFF mode and all permission bits cleared, the module’s default fault behavior (see 4.3) applies: Machine mode accesses are allowed; all other accesses are denied until a region is correctly programmed.\n\n## 6. Summary of Observability\n\nThe module’s only observable outputs are the per‑channel error signals. These signals indicate whether the requested access to the given address, by the given privilege level and access type, is permitted according to the programmed PMP policy. There is no internal state that affects future checks beyond the current set of configuration register values.\n\n---\n\n*This specification describes the behavioral requirements of the `ibex_pmp` module as derived from the RTL implementation and the accompanying documentation.*", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\nmodule ibex_pmp #(\n // Granularity of NAPOT access,\n // 0 = No restriction, 1 = 8 byte, 2 = 16 byte, 3 = 32 byte, etc.\n parameter int unsigned PMPGranularity = 0,\n // Number of access channels (e.g. i-side + d-side)\n parameter int unsigned PMPNumChan = 2,\n // Number of implemented regions\n parameter int unsigned PMPNumRegions = 4\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n // Interface to CSRs\n input ibex_pkg::pmp_cfg_t csr_pmp_cfg_i [PMPNumRegions],\n input logic [33:0] csr_pmp_addr_i [PMPNumRegions],\n\n input ibex_pkg::priv_lvl_e priv_mode_i [PMPNumChan],\n // Access checking channels\n input logic [33:0] pmp_req_addr_i [PMPNumChan],\n input ibex_pkg::pmp_req_e pmp_req_type_i [PMPNumChan],\n output logic pmp_req_err_o [PMPNumChan]\n\n);\n\n import ibex_pkg::*;\n\n // Access Checking Signals\n logic [33:0] region_start_addr [PMPNumRegions];\n logic [33:PMPGranularity+2] region_addr_mask [PMPNumRegions];\n logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_gt;\n logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_lt;\n logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_eq;\n logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_all;\n logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_perm_check;\n logic [PMPNumChan-1:0] access_fault;\n\n\n // ---------------\n // Access checking\n // ---------------\n\n for (genvar r = 0; r < PMPNumRegions; r++) begin : g_addr_exp\n // Start address for TOR matching\n if (r == 0) begin : g_entry0\n assign region_start_addr[r] = (csr_pmp_cfg_i[r].mode == PMP_MODE_TOR) ? 34'h000000000 :\n csr_pmp_addr_i[r];\n end else begin : g_oth\n assign region_start_addr[r] = (csr_pmp_cfg_i[r].mode == PMP_MODE_TOR) ? csr_pmp_addr_i[r-1] :\n csr_pmp_addr_i[r];\n end\n // Address mask for NA matching\n for (genvar b = PMPGranularity+2; b < 34; b++) begin : g_bitmask\n if (b == PMPGranularity+2) begin : g_bit0\n // Always mask bit (G+2) for NAPOT\n assign region_addr_mask[r][b] = (csr_pmp_cfg_i[r].mode != PMP_MODE_NAPOT);\n end else begin : g_others\n // We will mask this bit if it is within the programmed granule\n // i.e. addr = yyyy 0111\n // ^\n // | This bit pos is the top of the mask, all lower bits set\n // thus mask = 1111 0000\n assign region_addr_mask[r][b] = (csr_pmp_cfg_i[r].mode != PMP_MODE_NAPOT) |\n ~&csr_pmp_addr_i[r][b-1:PMPGranularity+2];\n end\n end\n end\n\n for (genvar c = 0; c < PMPNumChan; c++) begin : g_access_check\n for (genvar r = 0; r < PMPNumRegions; r++) begin : g_regions\n // Comparators are sized according to granularity\n assign region_match_eq[c][r] = (pmp_req_addr_i[c][33:PMPGranularity+2] &\n region_addr_mask[r]) ==\n (region_start_addr[r][33:PMPGranularity+2] &\n region_addr_mask[r]);\n assign region_match_gt[c][r] = pmp_req_addr_i[c][33:PMPGranularity+2] >\n region_start_addr[r][33:PMPGranularity+2];\n assign region_match_lt[c][r] = pmp_req_addr_i[c][33:PMPGranularity+2] <\n csr_pmp_addr_i[r][33:PMPGranularity+2];\n\n always_comb begin\n region_match_all[c][r] = 1'b0;\n unique case (csr_pmp_cfg_i[r].mode)\n PMP_MODE_OFF : region_match_all[c][r] = 1'b0;\n PMP_MODE_NA4 : region_match_all[c][r] = region_match_eq[c][r];\n PMP_MODE_NAPOT : region_match_all[c][r] = region_match_eq[c][r];\n PMP_MODE_TOR : begin\n region_match_all[c][r] = (region_match_eq[c][r] | region_match_gt[c][r]) &\n region_match_lt[c][r];\n end\n default : region_match_all[c][r] = 1'b0;\n endcase\n end\n\n // Check specific required permissions\n assign region_perm_check[c][r] =\n ((pmp_req_type_i[c] == PMP_ACC_EXEC) & csr_pmp_cfg_i[r].exec) |\n ((pmp_req_type_i[c] == PMP_ACC_WRITE) & csr_pmp_cfg_i[r].write) |\n ((pmp_req_type_i[c] == PMP_ACC_READ) & csr_pmp_cfg_i[r].read);\n end\n\n // Access fault determination / prioritization\n always_comb begin\n // Default is allow for M-mode, deny for other modes\n access_fault[c] = (priv_mode_i[c] != PRIV_LVL_M);\n\n // PMP entries are statically prioritized, from 0 to N-1\n // The lowest-numbered PMP entry which matches an address determines accessability\n for (int r = PMPNumRegions-1; r >= 0; r--) begin\n if (region_match_all[c][r]) begin\n access_fault[c] = (priv_mode_i[c] == PRIV_LVL_M) ?\n // For M-mode, any region which matches with the L-bit clear, or with sufficient\n // access permissions will be allowed\n (csr_pmp_cfg_i[r].lock & ~region_perm_check[c][r]) :\n // For other modes, the lock bit doesn't matter\n ~region_perm_check[c][r];\n end\n end\n end\n\n assign pmp_req_err_o[c] = access_fault[c];\n end\n\nendmodule\n", "pr_title": "[rtl] Fix PMP NA4 address matching", "pr_body": "- Apply address masking to the bottom address bit for NA4 as well as\r\n NAPOT\r\n- Relates to #902\r\n\r\nSigned-off-by: Tom Roberts <tomroberts@lowrisc.org>", "fix_patch": "diff --git a/rtl/ibex_pmp.sv b/rtl/ibex_pmp.sv\nindex 63f84c13ad..1b48693a0a 100644\n--- a/rtl/ibex_pmp.sv\n+++ b/rtl/ibex_pmp.sv\n@@ -32,9 +32,10 @@ module ibex_pmp #(\n // Access Checking Signals\n logic [33:0] region_start_addr [PMPNumRegions];\n logic [33:PMPGranularity+2] region_addr_mask [PMPNumRegions];\n- logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_high;\n- logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_low;\n- logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_both;\n+ logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_gt;\n+ logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_lt;\n+ logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_eq;\n+ logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_match_all;\n logic [PMPNumChan-1:0][PMPNumRegions-1:0] region_perm_check;\n logic [PMPNumChan-1:0] access_fault;\n \n@@ -71,16 +72,30 @@ module ibex_pmp #(\n \n for (genvar c = 0; c < PMPNumChan; c++) begin : g_access_check\n for (genvar r = 0; r < PMPNumRegions; r++) begin : g_regions\n- // TOR Region high/low matching is reused for all match types\n // Comparators are sized according to granularity\n- assign region_match_low[c][r] = pmp_req_addr_i[c][33:PMPGranularity+2] >=\n- (region_start_addr[r][33:PMPGranularity+2] &\n- region_addr_mask[r]);\n- assign region_match_high[c][r] = (pmp_req_addr_i[c][33:PMPGranularity+2] &\n- region_addr_mask[r]) <\n- csr_pmp_addr_i[r][33:PMPGranularity+2];\n- assign region_match_both[c][r] = region_match_low[c][r] & region_match_high[c][r] &\n- (csr_pmp_cfg_i[r].mode != PMP_MODE_OFF);\n+ assign region_match_eq[c][r] = (pmp_req_addr_i[c][33:PMPGranularity+2] &\n+ region_addr_mask[r]) ==\n+ (region_start_addr[r][33:PMPGranularity+2] &\n+ region_addr_mask[r]);\n+ assign region_match_gt[c][r] = pmp_req_addr_i[c][33:PMPGranularity+2] >\n+ region_start_addr[r][33:PMPGranularity+2];\n+ assign region_match_lt[c][r] = pmp_req_addr_i[c][33:PMPGranularity+2] <\n+ csr_pmp_addr_i[r][33:PMPGranularity+2];\n+\n+ always_comb begin\n+ region_match_all[c][r] = 1'b0;\n+ unique case (csr_pmp_cfg_i[r].mode)\n+ PMP_MODE_OFF : region_match_all[c][r] = 1'b0;\n+ PMP_MODE_NA4 : region_match_all[c][r] = region_match_eq[c][r];\n+ PMP_MODE_NAPOT : region_match_all[c][r] = region_match_eq[c][r];\n+ PMP_MODE_TOR : begin\n+ region_match_all[c][r] = (region_match_eq[c][r] | region_match_gt[c][r]) &\n+ region_match_lt[c][r];\n+ end\n+ default : region_match_all[c][r] = 1'b0;\n+ endcase\n+ end\n+\n // Check specific required permissions\n assign region_perm_check[c][r] =\n ((pmp_req_type_i[c] == PMP_ACC_EXEC) & csr_pmp_cfg_i[r].exec) |\n@@ -96,7 +111,7 @@ module ibex_pmp #(\n // PMP entries are statically prioritized, from 0 to N-1\n // The lowest-numbered PMP entry which matches an address determines accessability\n for (int r = PMPNumRegions-1; r >= 0; r--) begin\n- if (region_match_both[c][r]) begin\n+ if (region_match_all[c][r]) begin\n access_fault[c] = (priv_mode_i[c] == PRIV_LVL_M) ?\n // For M-mode, any region which matches with the L-bit clear, or with sufficient\n // access permissions will be allowed\n"}
{"repo": "lowRISC/ibex", "pr_id": 658, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": false, "sufficient_for_diagnosis": true}, "reasoning": "The specification leaks the signal names instr_rdata_i and instr_rdata_alu_i from the patch, violating no_patch_leakage."}, "generated_spec": "# Behavioral Design Specification: ibex_id_stage (Instruction Decode Stage)\n\n## 1. Overview\n\nThe `ibex_id_stage` module implements the instruction decode (ID) stage of the Ibex RISC‑V processor. It receives a fetched instruction from the instruction fetch (IF) stage, decodes it, reads the register file, prepares operands, and forwards control signals to the execution unit (ALU, multiplier/divider), load‑store unit (LSU), CSR block, and the core controller. The stage handles both single‑cycle and multi‑cycle instructions, manages pipeline stalls, and participates in exception, interrupt, and debug handling.\n\nThe ID stage operates in a two‑stage pipeline together with the IF stage. All instructions spend at least one cycle in the ID stage; multi‑cycle instructions stall the ID stage until they complete.\n\n## 2. Interfaces\n\nThe module communicates with the following blocks:\n\n- **Instruction Fetch (IF) stage** – receives a valid instruction, instruction data, compressed instruction indication, fetch errors, and the current program counter (PC). It can kill the IF‑ID pipeline register and signal readiness for a new instruction.\n- **Core Controller** – receives decoded information about illegal instructions, exception causes (ecall, mret, dret, wfi, ebreak), and provides signals for PC updates, exception PCs, interrupt handling, debug entry, and stall indications.\n- **Decoder** – a sub‑block that produces all decoded control signals (ALU operation, operand selection, immediate types, register file addresses, data memory control, CSR access, mult/div control, jump/branch flags).\n- **Register File** – internal to the ID stage; provides two read ports and one write port. Selection of write data comes from the execution stage, LSU result, or CSR read data.\n- **Execution Block (EX)** – receives ALU operands and operation code, multiplier/divider operands and modes, and branch target ALU signals.\n- **Load‑Store Unit (LSU)** – receives data memory request signals (address, write enable, data type, sign extension, write data) and provides responses (load data, address increment requests, last address).\n- **CSR Block** – receives CSR access requests and operation type; supplies CSR read data; provides privilege level and illegal CSR instruction status.\n- **Interrupt/Debug inputs** – interrupt pending, debug requests, single‑step, trigger match, etc.\n- **Write‑back path** – LS unit write data, execution write data, CSR read data are all available for register file write.\n- **Performance counters** – outputs for jump, branch, taken branch, instruction retired events.\n\n## 3. Functional Description\n\n### 3.1 Instruction Decode\n\nThe ID stage decodes an uncompressed 32‑bit instruction (or a compressed instruction expanded to 32 bits by the IF stage). Decoding produces all control signals required for execution, including:\n\n- ALU operation and operand source selection (register a, register b, immediate, current PC, loop‑forwarded address).\n- Immediate values for I, S, B, U, J types and the ZIMM used for CSR immediate.\n- Register file read and write addresses (ports a, b, and write address).\n- Data memory request type (load/store, size, sign extension).\n- Multiplier/divider enable and mode.\n- CSR access and operation.\n- Jump/branch identification.\n\nThe decoding is combinational; all control signals are available in the same cycle the instruction enters the ID stage.\n\n### 3.2 Operand Preparation\n\nOperand A for the ALU can be selected from:\n- Register file port A data.\n- A forwarded address from the LSU (for misaligned access handling).\n- The current PC (PC of the instruction in the ID stage).\n- A zero‑extended immediate (Zimm).\n\nOperand B can be selected from:\n- An immediate value (selected from one of I, S, B, U, J, or a PC increment constant).\n- Register file port B data.\n\nFor the multiplier/divider, operands are taken directly from register file ports A and B.\n\n### 3.3 Register File\n\nThe ID stage contains the processor’s register file. It comprises either 31 or 15 general‑purpose registers (depending on the RV32E configuration), with register x0 statically bound to zero. The register file has two read ports (addresses from decoder) and one write port. Read data is available in the same cycle as the read address is presented.\n\nWrite data comes from one of three sources:\n- Execution unit result (e.g., ALU output).\n- LSU load data.\n- CSR read data.\n\nThe write enable is gated so that:\n- Writes are suppressed when an illegal CSR instruction is detected.\n- Writes are suppressed when the ID stage is not executing an instruction (e.g., stalled).\n- For load, store, and multiply/divide instructions, writes occur only when the data is ready (write‑back stage).\n- Writes are suppressed if a load error is received.\n\nThe register file has no write‑to‑read forwarding; a read of a register being written in the same cycle returns the old value.\n\n### 3.4 ALU Output\n\nThe ALU operation code and the two operands are forwarded to the execution stage. The ALU is used for integer computational instructions, address calculation for loads/stores, branch condition evaluation, branch target computation (if `BranchTargetALU` parameter is disabled), and for multi‑cycle division algorithm support.\n\n### 3.5 Branch Target ALU\n\nWhen the parameter `BranchTargetALU` is enabled, a separate adder in the execution stage computes the branch target in parallel with the main ALU evaluating the branch condition. In this case the ID stage provides a 12‑bit immediate (bits from the B‑type immediate) to the branch target ALU. Otherwise, the handle is not used.\n\n### 3.6 Multi‑Cycle Instruction Handling\n\nSome instructions require more than one cycle in the ID stage. The ID stage contains a small finite‑state machine (FSM) to manage these instructions. The FSM transitions from an **Idle** state to a **Wait** state when the instruction is a multi‑cycle operation, and returns to **Idle** when the operation completes.\n\nThe following instruction classes are multi‑cycle and cause stalling:\n\n- **Load/Store operations** – stall until the LSU returns data (load) or acknowledges completion (store). At least one stall cycle is incurred.\n- **Multiply/Divide operations** – stall until the multiplier/divider block finishes. The number of cycles depends on the multiplier implementation and whether a divide‑by‑zero occurs (see pipeline details).\n- **Branches (taken)** – stall for two cycles without branch target ALU, or one cycle with it. The FSM waits for the branch target computation and the resulting PC request.\n- **Jumps (unconditional)** – stall for at least one cycle to flush the prefetch buffer and issue a new PC request.\n- **Fence.I** – treated as a jump; stalls accordingly.\n\nSingle‑cycle instructions (e.g., integer computational instructions, CSR accesses, branches not taken) complete in the ID stage in one cycle and do not cause stalling.\n\n#### 3.6.1 Stall Generation\n\nThe ID stage generates stall signals for the controller:\n- **Stall LSU**: asserted during load/store operations until `lsu_valid_i` is received.\n- **Stall multiplier/divider**: asserted during multiply/divide operations until the execution stage indicates completion (`ex_valid_i`).\n- **Stall branch**: asserted for taken branches during the second stall cycle.\n- **Stall jump**: asserted during jumps.\n\n#### 3.6.2 Write‑Back Control\n\nFor multi‑cycle instructions, the register file write enable is produced by the FSM when the result is available (`regfile_we_wb`). For single‑cycle instructions, the write enable is directly taken from the decoder (`regfile_we_dec`).\n\n### 3.7 Exception, Interrupt, and Debug Handling\n\nThe ID stage forwards decoded exception‑related signals (illegal instruction, ecall, ebreak, mret, dret, wfi) to the controller. It also receives external status:\n\n- **Illegal instruction** – asserted when the decoder detects an illegal instruction or when an illegal CSR instruction is flagged.\n- **CSR access** – the decoder supplies the CSR operation and address; the ID stage also provides a pipe flush signal used by the controller.\n- **Interrupts** – interrupt pending (including fast interrupts, timer, external, software) and machine status enable bits are received and combined in the controller.\n- **Debug** – debug requests, single‑step, ebreak configuration, trigger match, and privilege‑level specific ebreak behavior are fed to the controller. The ID stage outputs debug mode and debug cause signals.\n\nThe ID stage participates in saving/restoring CSR state for exceptions and debug entry (e.g., CSR save at IF and ID boundaries). It also provides the `mtval` value for exceptions (instruction or address causing the trap).\n\n### 3.8 Misaligned Load/Store Support\n\nWhen the LSU detects a misaligned access, it requests a second address increment (`lsu_addr_incr_req_i`). In response, the ID stage overrides the ALU operand selection to:\n- Operand A: use the forwarded last address from the LSU (`lsu_addr_last_i`).\n- Operand B: use an immediate of 4 (increment).\n- Immediate selection: use the increment immediate.\n\nThis causes the ALU to compute the address for the second part of the misaligned access.\n\n### 3.9 Performance Counters\n\nThe ID stage generates the following performance events:\n- **Jump performed** – active when a jump instruction is executed.\n- **Branch performed** – active for every branch instruction (taken or not taken).\n- **Taken branch performed** – active only for taken branches.\n- **Instruction retired** – active when an instruction completes (including branch instructions, regardless of outcome).\n- **Compressed instruction retired** – active when a retired instruction was compressed.\n\nThese signals are used by the performance counter block to count events.\n\n## 4. Pipeline State Machine (ID/EX/WB FSM)\n\nThe FSM manages instruction progress through the ID stage. It operates in two states:\n\n- **IDLE**: Normal operation. When a new instruction is received (and no fetch error), the machine:\n - For single‑cycle operations: completes the cycle and returns to IDLE.\n - For multi‑cycle operations: enters WAIT_MULTICYCLE and asserts appropriate stall.\n - For taken branches: may directly enter WAIT or return, depending on the FSM logic.\n\n- **WAIT_MULTICYCLE**: The FSM remains here until the multi‑cycle operation finishes. Completion is signaled by:\n - Load/store: when `lsu_valid_i` is asserted.\n - Multiply/divide: when `ex_valid_i` is asserted (since the mul/div block is in the execution stage).\n - Branch/jump: no explicit completion signal; the FSM returns to IDLE based on a combination of `ex_valid_i` and `data_req_dec` (jumps/branches use the ALU for target calculation which is single‑cycle, but the controller manages the PC change; the FSM uses the condition that the operation is no longer a data request and `ex_valid_i` is asserted).\n\nWhen returning to IDLE, the FSM asserts the write‑back enable for loads/stores and multiply/divide results, and activates the instruction retired signal.\n\n## 5. Output Summary\n\nThe ID stage drives the following key outputs (not exhaustive):\n\n- **To IF/Controller**: PC set, PC multiplexer select, exception PC multiplexer select, exception cause, instruction request, kill IF‑ID register, ID ready.\n- **To ALU**: operation code, operand A, operand B.\n- **To Branch Target ALU**: immediate operand.\n- **To Multiplier/Divider**: enable, select, operation, signed mode, operands.\n- **To CSR**: access, operation, save/restore signals, mtval.\n- **To LSU**: request, write enable, data type, sign extension, write data.\n- **To Write‑Back**: register file write data (via the register file’s write port).\n- **Performance counters**: jump, branch, taken branch, instruction retired, compressed retired.\n- **Debug**: debug mode, debug cause, debug CSR save.\n\n## 6. Configuration Parameters\n\nThe module is parameterized by:\n\n- **RV32E**: When set, the register file contains 15 registers instead of 31.\n- **RV32M**: Enables the multiplication/division extension.\n- **BranchTargetALU**: When set, a dedicated adder computes branch targets in parallel with the condition evaluation, reducing branch penalty by one cycle.\n\n## 7. Assertions and Assumptions\n\nThe design assumes that:\n- The input instruction is well‑formed (no X values) when valid and not an error.\n- A branch decision input is stable when a branch instruction is decoded.\n- Only one multi‑cycle operation (load/store, multiply/divide, branch, jump) is active at a time.\n- The duplicate instruction flops (`instr_rdata_i` and `instr_rdata_alu_i`) always match when the instruction is valid.\n- For the latch‑based register file, the clock gating cell ensures the latches capture data correctly.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2018 ETH Zurich and University of Bologna, see also CREDITS.md.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n`ifdef RISCV_FORMAL\n `define RVFI\n`endif\n\n/**\n * Instruction Decode Stage\n *\n * Decode stage of the core. It decodes the instructions and hosts the register\n * file.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_id_stage #(\n parameter bit RV32E = 0,\n parameter bit RV32M = 1,\n parameter bit BranchTargetALU = 0\n) (\n input logic clk_i,\n input logic rst_ni,\n\n input logic test_en_i,\n\n input logic fetch_enable_i,\n output logic ctrl_busy_o,\n output logic illegal_insn_o,\n\n // Interface to IF stage\n input logic instr_valid_i,\n input logic instr_new_i,\n input logic [31:0] instr_rdata_i, // from IF-ID pipeline registers\n input logic [31:0] instr_rdata_alu_i, // from IF-ID pipeline registers\n input logic [15:0] instr_rdata_c_i, // from IF-ID pipeline registers\n input logic instr_is_compressed_i,\n output logic instr_req_o,\n output logic instr_valid_clear_o, // kill instr in IF-ID reg\n output logic id_in_ready_o, // ID stage is ready for next instr\n\n // Jumps and branches\n input logic branch_decision_i,\n\n // IF and ID stage signals\n output logic pc_set_o,\n output ibex_pkg::pc_sel_e pc_mux_o,\n output ibex_pkg::exc_pc_sel_e exc_pc_mux_o,\n output ibex_pkg::exc_cause_e exc_cause_o,\n\n input logic illegal_c_insn_i,\n input logic instr_fetch_err_i,\n\n input logic [31:0] pc_id_i,\n\n // Stalls\n input logic ex_valid_i, // EX stage has valid output\n input logic lsu_valid_i, // LSU has valid output, or is done\n // ALU\n output ibex_pkg::alu_op_e alu_operator_ex_o,\n output logic [31:0] alu_operand_a_ex_o,\n output logic [31:0] alu_operand_b_ex_o,\n\n // Branch target ALU\n output ibex_pkg::jt_mux_sel_e jt_mux_sel_ex_o,\n output logic [11:0] bt_operand_imm_o,\n\n // MUL, DIV\n output logic mult_en_ex_o,\n output logic div_en_ex_o,\n output logic multdiv_sel_ex_o,\n output ibex_pkg::md_op_e multdiv_operator_ex_o,\n output logic [1:0] multdiv_signed_mode_ex_o,\n output logic [31:0] multdiv_operand_a_ex_o,\n output logic [31:0] multdiv_operand_b_ex_o,\n\n // CSR\n output logic csr_access_o,\n output ibex_pkg::csr_op_e csr_op_o,\n output logic csr_save_if_o,\n output logic csr_save_id_o,\n output logic csr_restore_mret_id_o,\n output logic csr_restore_dret_id_o,\n output logic csr_save_cause_o,\n output logic [31:0] csr_mtval_o,\n input ibex_pkg::priv_lvl_e priv_mode_i,\n input logic csr_mstatus_tw_i,\n input logic illegal_csr_insn_i,\n\n // Interface to load store unit\n output logic data_req_ex_o,\n output logic data_we_ex_o,\n output logic [1:0] data_type_ex_o,\n output logic data_sign_ext_ex_o,\n output logic [31:0] data_wdata_ex_o,\n\n input logic lsu_addr_incr_req_i,\n input logic [31:0] lsu_addr_last_i,\n\n // Interrupt signals\n input logic csr_mstatus_mie_i,\n input logic irq_pending_i,\n input ibex_pkg::irqs_t irqs_i,\n input logic irq_nm_i,\n output logic nmi_mode_o,\n\n input logic lsu_load_err_i,\n input logic lsu_store_err_i,\n\n // Debug Signal\n output logic debug_mode_o,\n output ibex_pkg::dbg_cause_e debug_cause_o,\n output logic debug_csr_save_o,\n input logic debug_req_i,\n input logic debug_single_step_i,\n input logic debug_ebreakm_i,\n input logic debug_ebreaku_i,\n input logic trigger_match_i,\n\n // Write back signal\n input logic [31:0] regfile_wdata_lsu_i,\n input logic [31:0] regfile_wdata_ex_i,\n input logic [31:0] csr_rdata_i,\n\n`ifdef RVFI\n output logic [4:0] rfvi_reg_raddr_ra_o,\n output logic [31:0] rfvi_reg_rdata_ra_o,\n output logic [4:0] rfvi_reg_raddr_rb_o,\n output logic [31:0] rfvi_reg_rdata_rb_o,\n output logic [4:0] rfvi_reg_waddr_rd_o,\n output logic [31:0] rfvi_reg_wdata_rd_o,\n output logic rfvi_reg_we_o,\n`endif\n\n // Performance Counters\n output logic perf_jump_o, // executing a jump instr\n output logic perf_branch_o, // executing a branch instr\n output logic perf_tbranch_o, // executing a taken branch instr\n output logic instr_ret_o,\n output logic instr_ret_compressed_o\n);\n\n import ibex_pkg::*;\n\n // Decoder/Controller, ID stage internal signals\n logic illegal_insn_dec;\n logic ebrk_insn;\n logic mret_insn_dec;\n logic dret_insn_dec;\n logic ecall_insn_dec;\n logic wfi_insn_dec;\n\n logic branch_in_dec;\n logic branch_set, branch_set_d;\n logic jump_in_dec;\n logic jump_set;\n\n logic instr_executing;\n logic instr_multicycle;\n logic instr_multicycle_done_n, instr_multicycle_done_q;\n logic stall_lsu;\n logic stall_multdiv;\n logic stall_branch;\n logic stall_jump;\n\n // Immediate decoding and sign extension\n logic [31:0] imm_i_type;\n logic [31:0] imm_s_type;\n logic [31:0] imm_b_type;\n logic [31:0] imm_u_type;\n logic [31:0] imm_j_type;\n logic [31:0] zimm_rs1_type;\n\n logic [31:0] imm_a; // contains the immediate for operand b\n logic [31:0] imm_b; // contains the immediate for operand b\n\n // Register file interface\n logic [4:0] regfile_raddr_a;\n logic [4:0] regfile_raddr_b;\n\n logic [4:0] regfile_waddr;\n\n logic [31:0] regfile_rdata_a;\n logic [31:0] regfile_rdata_b;\n logic [31:0] regfile_wdata;\n\n rf_wd_sel_e regfile_wdata_sel;\n logic regfile_we;\n logic regfile_we_wb, regfile_we_dec;\n\n // ALU Control\n alu_op_e alu_operator;\n op_a_sel_e alu_op_a_mux_sel, alu_op_a_mux_sel_dec;\n op_b_sel_e alu_op_b_mux_sel, alu_op_b_mux_sel_dec;\n\n imm_a_sel_e imm_a_mux_sel;\n imm_b_sel_e imm_b_mux_sel, imm_b_mux_sel_dec;\n\n // Multiplier Control\n logic mult_en_id, mult_en_dec; // use integer multiplier\n logic div_en_id, div_en_dec; // use integer division or reminder\n logic multdiv_sel_dec;\n logic multdiv_en_dec;\n md_op_e multdiv_operator;\n logic [1:0] multdiv_signed_mode;\n\n // Data Memory Control\n logic data_we_id;\n logic [1:0] data_type_id;\n logic data_sign_ext_id;\n logic data_req_id, data_req_dec;\n\n // CSR control\n logic csr_pipe_flush;\n\n logic [31:0] alu_operand_a;\n logic [31:0] alu_operand_b;\n\n /////////////\n // LSU Mux //\n /////////////\n\n // Misaligned loads/stores result in two aligned loads/stores, compute second address\n assign alu_op_a_mux_sel = lsu_addr_incr_req_i ? OP_A_FWD : alu_op_a_mux_sel_dec;\n assign alu_op_b_mux_sel = lsu_addr_incr_req_i ? OP_B_IMM : alu_op_b_mux_sel_dec;\n assign imm_b_mux_sel = lsu_addr_incr_req_i ? IMM_B_INCR_ADDR : imm_b_mux_sel_dec;\n\n ///////////////////\n // Operand A MUX //\n ///////////////////\n\n // Immediate MUX for Operand A\n assign imm_a = (imm_a_mux_sel == IMM_A_Z) ? zimm_rs1_type : '0;\n\n // ALU MUX for Operand A\n always_comb begin : alu_operand_a_mux\n unique case (alu_op_a_mux_sel)\n OP_A_REG_A: alu_operand_a = regfile_rdata_a;\n OP_A_FWD: alu_operand_a = lsu_addr_last_i;\n OP_A_CURRPC: alu_operand_a = pc_id_i;\n OP_A_IMM: alu_operand_a = imm_a;\n default: alu_operand_a = pc_id_i;\n endcase\n end\n\n ///////////////////\n // Operand B MUX //\n ///////////////////\n\n // Immediate MUX for Operand B\n always_comb begin : immediate_b_mux\n unique case (imm_b_mux_sel)\n IMM_B_I: imm_b = imm_i_type;\n IMM_B_S: imm_b = imm_s_type;\n IMM_B_B: imm_b = imm_b_type;\n IMM_B_U: imm_b = imm_u_type;\n IMM_B_J: imm_b = imm_j_type;\n IMM_B_INCR_PC: imm_b = instr_is_compressed_i ? 32'h2 : 32'h4;\n IMM_B_INCR_ADDR: imm_b = 32'h4;\n default: imm_b = 32'h4;\n endcase\n end\n\n // ALU MUX for Operand B\n assign alu_operand_b = (alu_op_b_mux_sel == OP_B_IMM) ? imm_b : regfile_rdata_b;\n\n ///////////////////////\n // Register File MUX //\n ///////////////////////\n\n // Register file write enable mux - do not propagate illegal CSR ops, do not write when idle,\n // for loads/stores and multdiv operations write when the data is ready only\n assign regfile_we = (illegal_csr_insn_i || !instr_executing) ? 1'b0 :\n (data_req_dec || multdiv_en_dec) ? regfile_we_wb : regfile_we_dec;\n\n // Register file write data mux\n always_comb begin : regfile_wdata_mux\n unique case (regfile_wdata_sel)\n RF_WD_EX: regfile_wdata = regfile_wdata_ex_i;\n RF_WD_LSU: regfile_wdata = regfile_wdata_lsu_i;\n RF_WD_CSR: regfile_wdata = csr_rdata_i;\n default: regfile_wdata = regfile_wdata_ex_i;\n endcase\n end\n\n ///////////////////\n // Register File //\n ///////////////////\n\n ibex_register_file #( .RV32E ( RV32E ) ) registers_i (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n .test_en_i ( test_en_i ),\n\n // Read port a\n .raddr_a_i ( regfile_raddr_a ),\n .rdata_a_o ( regfile_rdata_a ),\n // Read port b\n .raddr_b_i ( regfile_raddr_b ),\n .rdata_b_o ( regfile_rdata_b ),\n // write port\n .waddr_a_i ( regfile_waddr ),\n .wdata_a_i ( regfile_wdata ),\n .we_a_i ( regfile_we )\n );\n\n`ifdef RVFI\n assign rfvi_reg_raddr_ra_o = regfile_raddr_a;\n assign rfvi_reg_rdata_ra_o = regfile_rdata_a;\n assign rfvi_reg_raddr_rb_o = regfile_raddr_b;\n assign rfvi_reg_rdata_rb_o = regfile_rdata_b;\n assign rfvi_reg_waddr_rd_o = regfile_waddr;\n assign rfvi_reg_wdata_rd_o = regfile_wdata;\n assign rfvi_reg_we_o = regfile_we;\n`endif\n\n /////////////\n // Decoder //\n /////////////\n\n ibex_decoder #(\n .RV32E ( RV32E ),\n .RV32M ( RV32M ),\n .BranchTargetALU ( BranchTargetALU )\n ) decoder_i (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n // controller\n .illegal_insn_o ( illegal_insn_dec ),\n .ebrk_insn_o ( ebrk_insn ),\n .mret_insn_o ( mret_insn_dec ),\n .dret_insn_o ( dret_insn_dec ),\n .ecall_insn_o ( ecall_insn_dec ),\n .wfi_insn_o ( wfi_insn_dec ),\n .jump_set_o ( jump_set ),\n\n // from IF-ID pipeline register\n .instr_new_i ( instr_new_i ),\n .instr_rdata_i ( instr_rdata_i ),\n .instr_rdata_alu_i ( instr_rdata_alu_i ),\n .illegal_c_insn_i ( illegal_c_insn_i ),\n\n // immediates\n .imm_a_mux_sel_o ( imm_a_mux_sel ),\n .imm_b_mux_sel_o ( imm_b_mux_sel_dec ),\n .jt_mux_sel_o ( jt_mux_sel_ex_o ),\n\n .imm_i_type_o ( imm_i_type ),\n .imm_s_type_o ( imm_s_type ),\n .imm_b_type_o ( imm_b_type ),\n .imm_u_type_o ( imm_u_type ),\n .imm_j_type_o ( imm_j_type ),\n .zimm_rs1_type_o ( zimm_rs1_type ),\n\n // register file\n .regfile_wdata_sel_o ( regfile_wdata_sel ),\n .regfile_we_o ( regfile_we_dec ),\n\n .regfile_raddr_a_o ( regfile_raddr_a ),\n .regfile_raddr_b_o ( regfile_raddr_b ),\n .regfile_waddr_o ( regfile_waddr ),\n\n // ALU\n .alu_operator_o ( alu_operator ),\n .alu_op_a_mux_sel_o ( alu_op_a_mux_sel_dec ),\n .alu_op_b_mux_sel_o ( alu_op_b_mux_sel_dec ),\n\n // MULT & DIV\n .mult_en_o ( mult_en_dec ),\n .div_en_o ( div_en_dec ),\n .multdiv_sel_o ( multdiv_sel_dec ),\n .multdiv_operator_o ( multdiv_operator ),\n .multdiv_signed_mode_o ( multdiv_signed_mode ),\n\n // CSRs\n .csr_access_o ( csr_access_o ),\n .csr_op_o ( csr_op_o ),\n .csr_pipe_flush_o ( csr_pipe_flush ),\n\n // LSU\n .data_req_o ( data_req_dec ),\n .data_we_o ( data_we_id ),\n .data_type_o ( data_type_id ),\n .data_sign_extension_o ( data_sign_ext_id ),\n\n // jump/branches\n .jump_in_dec_o ( jump_in_dec ),\n .branch_in_dec_o ( branch_in_dec )\n );\n\n ////////////////\n // Controller //\n ////////////////\n\n assign illegal_insn_o = instr_valid_i & (illegal_insn_dec | illegal_csr_insn_i);\n\n ibex_controller controller_i (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n .fetch_enable_i ( fetch_enable_i ),\n .ctrl_busy_o ( ctrl_busy_o ),\n\n // decoder related signals\n .illegal_insn_i ( illegal_insn_o ),\n .ecall_insn_i ( ecall_insn_dec ),\n .mret_insn_i ( mret_insn_dec ),\n .dret_insn_i ( dret_insn_dec ),\n .wfi_insn_i ( wfi_insn_dec ),\n .ebrk_insn_i ( ebrk_insn ),\n .csr_pipe_flush_i ( csr_pipe_flush ),\n\n // from IF-ID pipeline\n .instr_valid_i ( instr_valid_i ),\n .instr_i ( instr_rdata_i ),\n .instr_compressed_i ( instr_rdata_c_i ),\n .instr_is_compressed_i ( instr_is_compressed_i ),\n .instr_fetch_err_i ( instr_fetch_err_i ),\n .pc_id_i ( pc_id_i ),\n\n // to IF-ID pipeline\n .instr_valid_clear_o ( instr_valid_clear_o ),\n .id_in_ready_o ( id_in_ready_o ),\n\n // to prefetcher\n .instr_req_o ( instr_req_o ),\n .pc_set_o ( pc_set_o ),\n .pc_mux_o ( pc_mux_o ),\n .exc_pc_mux_o ( exc_pc_mux_o ),\n .exc_cause_o ( exc_cause_o ),\n\n // LSU\n .lsu_addr_last_i ( lsu_addr_last_i ),\n .load_err_i ( lsu_load_err_i ),\n .store_err_i ( lsu_store_err_i ),\n\n // jump/branch control\n .branch_set_i ( branch_set ),\n .jump_set_i ( jump_set ),\n\n // interrupt signals\n .csr_mstatus_mie_i ( csr_mstatus_mie_i ),\n .irq_pending_i ( irq_pending_i ),\n .irqs_i ( irqs_i ),\n .irq_nm_i ( irq_nm_i ),\n .nmi_mode_o ( nmi_mode_o ),\n\n // CSR Controller Signals\n .csr_save_if_o ( csr_save_if_o ),\n .csr_save_id_o ( csr_save_id_o ),\n .csr_restore_mret_id_o ( csr_restore_mret_id_o ),\n .csr_restore_dret_id_o ( csr_restore_dret_id_o ),\n .csr_save_cause_o ( csr_save_cause_o ),\n .csr_mtval_o ( csr_mtval_o ),\n .priv_mode_i ( priv_mode_i ),\n .csr_mstatus_tw_i ( csr_mstatus_tw_i ),\n\n // Debug Signal\n .debug_mode_o ( debug_mode_o ),\n .debug_cause_o ( debug_cause_o ),\n .debug_csr_save_o ( debug_csr_save_o ),\n .debug_req_i ( debug_req_i ),\n .debug_single_step_i ( debug_single_step_i ),\n .debug_ebreakm_i ( debug_ebreakm_i ),\n .debug_ebreaku_i ( debug_ebreaku_i ),\n .trigger_match_i ( trigger_match_i ),\n\n // stall signals\n .stall_lsu_i ( stall_lsu ),\n .stall_multdiv_i ( stall_multdiv ),\n .stall_jump_i ( stall_jump ),\n .stall_branch_i ( stall_branch ),\n\n // Performance Counters\n .perf_jump_o ( perf_jump_o ),\n .perf_tbranch_o ( perf_tbranch_o )\n );\n\n //////////////\n // ID-EX/WB //\n //////////////\n\n assign multdiv_en_dec = mult_en_dec | div_en_dec;\n assign instr_multicycle = data_req_dec | multdiv_en_dec | branch_in_dec | jump_in_dec;\n\n // Forward decoder output to EX, WB and controller only if current instr is still\n // being executed. This is the case if the current instr is either:\n // - a new instr (not yet done)\n // - a multicycle instr that is not yet done\n // An instruction error will suppress any requests or register writes\n assign instr_executing = (instr_new_i | (instr_multicycle & ~instr_multicycle_done_q)) &\n ~instr_fetch_err_i;\n assign data_req_id = instr_executing ? data_req_dec : 1'b0;\n assign mult_en_id = instr_executing ? mult_en_dec : 1'b0;\n assign div_en_id = instr_executing ? div_en_dec : 1'b0;\n\n ///////////\n // ID-EX //\n ///////////\n\n assign data_req_ex_o = data_req_id;\n assign data_we_ex_o = data_we_id;\n assign data_type_ex_o = data_type_id;\n assign data_sign_ext_ex_o = data_sign_ext_id;\n assign data_wdata_ex_o = regfile_rdata_b;\n\n assign alu_operator_ex_o = alu_operator;\n assign alu_operand_a_ex_o = alu_operand_a;\n assign alu_operand_b_ex_o = alu_operand_b;\n\n if (BranchTargetALU) begin : g_bt_operand_imm\n // Branch target ALU sign-extends and inserts bottom 0 bit so only want the\n // 'raw' B-type immediate bits.\n assign bt_operand_imm_o = imm_b_type[12:1];\n end else begin : g_no_bt_operand_imm\n assign bt_operand_imm_o = '0;\n end\n\n assign mult_en_ex_o = mult_en_id;\n assign div_en_ex_o = div_en_id;\n assign multdiv_sel_ex_o = multdiv_sel_dec;\n\n assign multdiv_operator_ex_o = multdiv_operator;\n assign multdiv_signed_mode_ex_o = multdiv_signed_mode;\n assign multdiv_operand_a_ex_o = regfile_rdata_a;\n assign multdiv_operand_b_ex_o = regfile_rdata_b;\n\n typedef enum logic { IDLE, WAIT_MULTICYCLE } id_fsm_e;\n id_fsm_e id_wb_fsm_cs, id_wb_fsm_ns;\n\n ////////////////////////////////\n // ID-EX/WB Pipeline Register //\n ////////////////////////////////\n\n if (BranchTargetALU) begin : g_branch_set_direct\n // Branch set fed straight to controller with branch target ALU\n // (condition pass/fail used same cycle as generated instruction request)\n assign branch_set = branch_set_d;\n end else begin : g_branch_set_flopped\n // Branch set flopped without branch target ALU\n // (condition pass/fail used next cycle where branch target is calculated)\n logic branch_set_q;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n branch_set_q <= 1'b0;\n end else begin\n branch_set_q <= branch_set_d;\n end\n end\n\n assign branch_set = branch_set_q;\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin : id_wb_pipeline_reg\n if (!rst_ni) begin\n id_wb_fsm_cs <= IDLE;\n instr_multicycle_done_q <= 1'b0;\n end else begin\n id_wb_fsm_cs <= id_wb_fsm_ns;\n instr_multicycle_done_q <= instr_multicycle_done_n;\n end\n end\n\n //////////////////\n // ID-EX/WB FSM //\n //////////////////\n\n always_comb begin : id_wb_fsm\n id_wb_fsm_ns = id_wb_fsm_cs;\n instr_multicycle_done_n = instr_multicycle_done_q;\n regfile_we_wb = 1'b0;\n stall_lsu = 1'b0;\n stall_multdiv = 1'b0;\n stall_jump = 1'b0;\n stall_branch = 1'b0;\n branch_set_d = 1'b0;\n perf_branch_o = 1'b0;\n instr_ret_o = 1'b0;\n\n unique case (id_wb_fsm_cs)\n\n IDLE: begin\n // only detect multicycle when instruction is new, do not re-detect after\n // execution (when waiting for next instruction from IF stage)\n if (instr_new_i & ~instr_fetch_err_i) begin\n unique case (1'b1)\n data_req_dec: begin\n // LSU operation\n id_wb_fsm_ns = WAIT_MULTICYCLE;\n stall_lsu = 1'b1;\n instr_multicycle_done_n = 1'b0;\n end\n multdiv_en_dec: begin\n // MUL or DIV operation\n id_wb_fsm_ns = WAIT_MULTICYCLE;\n stall_multdiv = 1'b1;\n instr_multicycle_done_n = 1'b0;\n end\n branch_in_dec: begin\n // cond branch operation\n id_wb_fsm_ns = branch_decision_i ? WAIT_MULTICYCLE : IDLE;\n stall_branch = branch_decision_i;\n instr_multicycle_done_n = ~branch_decision_i;\n branch_set_d = branch_decision_i;\n perf_branch_o = 1'b1;\n instr_ret_o = ~branch_decision_i;\n end\n jump_in_dec: begin\n // uncond branch operation\n id_wb_fsm_ns = WAIT_MULTICYCLE;\n stall_jump = 1'b1;\n instr_multicycle_done_n = 1'b0;\n end\n default: begin\n instr_multicycle_done_n = 1'b0;\n instr_ret_o = 1'b1;\n end\n endcase\n end\n end\n\n WAIT_MULTICYCLE: begin\n if ((data_req_dec & lsu_valid_i) | (~data_req_dec & ex_valid_i)) begin\n id_wb_fsm_ns = IDLE;\n instr_multicycle_done_n = 1'b1;\n regfile_we_wb = regfile_we_dec & ~lsu_load_err_i;\n instr_ret_o = 1'b1;\n end else begin\n stall_lsu = data_req_dec;\n stall_multdiv = multdiv_en_dec;\n stall_branch = branch_in_dec;\n stall_jump = jump_in_dec;\n end\n end\n\n default: begin\n id_wb_fsm_ns = IDLE;\n end\n endcase\n end\n\n assign instr_ret_compressed_o = instr_ret_o & instr_is_compressed_i;\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT_KNOWN(IbexAluOpMuxSelKnown, alu_op_a_mux_sel, clk_i, !rst_ni)\n `ASSERT(IbexImmBMuxSelValid, imm_b_mux_sel inside {\n IMM_B_I,\n IMM_B_S,\n IMM_B_B,\n IMM_B_U,\n IMM_B_J,\n IMM_B_INCR_PC,\n IMM_B_INCR_ADDR})\n `ASSERT(IbexRegfileWdataSelValid, regfile_wdata_sel inside {\n RF_WD_LSU,\n RF_WD_EX,\n RF_WD_CSR})\n `ASSERT_KNOWN(IbexWbStateKnown, id_wb_fsm_cs)\n\n // Branch decision must be valid when jumping.\n `ASSERT(IbexBranchDecisionValid, branch_in_dec |-> !$isunknown(branch_decision_i))\n\n // Instruction delivered to ID stage can not contain X.\n `ASSERT(IbexIdInstrKnown,\n (instr_valid_i && !(illegal_c_insn_i || instr_fetch_err_i)) |-> !$isunknown(instr_rdata_i))\n\n // Instruction delivered to ID stage can not contain X.\n `ASSERT(IbexIdInstrALUKnown,\n (instr_valid_i && !(illegal_c_insn_i || instr_fetch_err_i)) |-> !$isunknown(instr_rdata_alu_i))\n\n // Multicycle enable signals must be unique.\n `ASSERT(IbexMulticycleEnableUnique,\n $onehot0({data_req_dec, multdiv_en_dec, branch_in_dec, jump_in_dec}))\n\n // Duplicated instruction flops must match\n // === as DV environment can produce instructions with Xs in, so must use precise match that\n // includes Xs\n `ASSERT(IbexDuplicateInstrMatch, instr_valid_i |-> instr_rdata_i === instr_rdata_alu_i)\n\n `ifdef CHECK_MISALIGNED\n `ASSERT(IbexMisalignedMemoryAccess, !lsu_addr_incr_req_i)\n `endif\n\nendmodule\n", "pr_title": "Remove stray semicolon", "pr_body": "This seems to cause lint errors with ncsim (see bug #650).", "fix_patch": "diff --git a/rtl/ibex_id_stage.sv b/rtl/ibex_id_stage.sv\nindex c95f19d6f2..572ecaaaf0 100644\n--- a/rtl/ibex_id_stage.sv\n+++ b/rtl/ibex_id_stage.sv\n@@ -684,7 +684,7 @@ module ibex_id_stage #(\n // Duplicated instruction flops must match\n // === as DV environment can produce instructions with Xs in, so must use precise match that\n // includes Xs\n- `ASSERT(IbexDuplicateInstrMatch, instr_valid_i |-> instr_rdata_i === instr_rdata_alu_i);\n+ `ASSERT(IbexDuplicateInstrMatch, instr_valid_i |-> instr_rdata_i === instr_rdata_alu_i)\n \n `ifdef CHECK_MISALIGNED\n `ASSERT(IbexMisalignedMemoryAccess, !lsu_addr_incr_req_i)\n"}
{"repo": "lowRISC/ibex", "pr_id": 560, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": false, "sufficient_for_diagnosis": true}, "reasoning": "The specification includes the variable name 'enable_nested_irq' from the patch, violating the no_patch_leakage requirement."}, "generated_spec": "# Behavioral Specification: `core_ibex_env_cfg`\n\n## Overview\n\nThe `core_ibex_env_cfg` module is a configuration object used within the UVM testbench for the Ibex RISC‑V core. It defines the control knobs that dictate how interrupt and debug stimulus is generated during simulation, as well as the signature address used for the handshaking mechanism between the core and the testbench. This configuration is populated from command‑line plusargs at the start of simulation and is then accessed by the test environment to drive external events.\n\n## Configuration Parameters\n\nThe object contains the following behavioral parameters. Default values are `0` for all bit fields and `0` for the maximum interval, unless explicitly overridden via simulation plusargs.\n\n### `enable_irq_single_seq`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the testbench must generate single interrupt requests to the core. When `0`, no single‑interrupt sequences are produced. This allows selective testing of single vs. multiple interrupt scenarios.\n\n### `enable_irq_multiple_seq`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the testbench must generate sequences that assert multiple interrupts concurrently or in rapid succession. When `0`, multi‑interrupt sequences are not generated.\n\n### `enable_nested_irq`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the test environment must enable scenarios where an interrupt is taken while the core is already servicing another interrupt (i.e., nested interrupt handling). When `0`, nested interrupt scenarios are disabled.\n\n### `enable_debug_seq`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the testbench must generate debug request sequences (via `debug_req_i`) to cause the core to enter Debug Mode. When `0`, debug sequences are not generated.\n\n### `max_interval`\n- **Type**: 32‑bit unsigned integer\n- **Behavior**: Specifies the maximum number of clock cycles or instruction executions (depending on the sequence implementation) between successive interrupt or debug events. This controls the density of external stimulus. A value of `0` may be interpreted as no constraint.\n\n### `require_signature_addr`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the test environment must use the handshaking mechanism based on the signature address. This instructs the core to write status information to that address during runtime, which is then read by the testbench for verification.\n\n### `signature_addr`\n- **Type**: 32‑bit unsigned integer (physical address)\n- **Behavior**: The memory address used for the handshaking protocol. The core writes a signature (status word) to this address. The testbench monitors this location to track core state transitions, such as entry into interrupt handlers or Debug Mode. The default address (if not overridden) is `0x8ffffffc`, as documented in the verification guide.\n\n## Initialization\n\nUpon construction of the `core_ibex_env_cfg` object, the module shall read the following simulation plusargs to set its fields. If a plusarg is not provided, the corresponding field retains its default value (zero for bits, zero for `max_interval`, and an empty string for `signature_addr_str`, which results in `signature_addr` being zero unless explicitly set).\n\n| Plusarg Name | Field Set | Value Interpretation |\n|-----------------------------|-------------------------------|------------------------------------------|\n| `enable_irq_single_seq` | `enable_irq_single_seq` | Decimal integer (0 or 1) |\n| `enable_irq_multiple_seq` | `enable_irq_multiple_seq` | Decimal integer (0 or 1) |\n| `enable_nested_irq` | `enable_nested_irq` | Decimal integer (0 or 1) |\n| `enable_debug_seq` | `enable_debug_seq` | Decimal integer (0 or 1) |\n| `max_interval` | `max_interval` | Decimal integer |\n| `require_signature_addr` | `require_signature_addr` | Decimal integer (0 or 1) |\n| `signature_addr` | `signature_addr` | Hexadecimal string (e.g., `0x8ffffffc`) |\n\nThe string value of the `signature_addr` plusarg is converted to a 32‑bit integer using an `atohex` conversion. If the string is empty or invalid, the resulting address shall be zero.\n\n## Functional Behavior in the Test Environment\n\nThe `core_ibex_env_cfg` object is used by the test environment to configure the behavior of the interrupt agent, debug agent, and the test‑sequence library. Specifically:\n\n- The **interrupt agent** shall generate interrupt requests only for the classes of interrupts that are enabled (single, multiple, nested) and shall respect the `max_interval` constraint when scheduling those events.\n- The **debug agent** shall generate `debug_req_i` assertions only if `enable_debug_seq` is set.\n- The **handshaking mechanism** (used for runtime verification of interrupt and debug scenarios) shall be activated only when `require_signature_addr` is true. In that case, the testbench must configure the core, via the compiled program, to write a signature to the specified `signature_addr`. The testbench then polls that address to detect core state changes and perform correctness checks.\n\nAll configuration fields are accessible after initialization. The testbench shall not modify them during simulation; they remain static for the duration of the test. This ensures deterministic and reproducible stimulus generation per test.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\nclass core_ibex_env_cfg extends uvm_object;\n\n bit enable_irq_single_seq;\n bit enable_irq_multiple_seq;\n bit enable_nested_irq;\n bit enable_debug_seq;\n bit[31:0] max_interval;\n bit require_signature_addr;\n string signature_addr_str;\n bit[31:0] signature_addr;\n\n `uvm_object_utils_begin(core_ibex_env_cfg)\n `uvm_field_int(enable_irq_single_seq, UVM_DEFAULT)\n `uvm_field_int(enable_irq_multiple_seq, UVM_DEFAULT)\n `uvm_field_int(enable_nested_irq, UVM_DEFAULT)\n `uvm_field_int(enable_debug_seq, UVM_DEFAULT)\n `uvm_field_int(max_interval, UVM_DEFAULT)\n `uvm_field_int(require_signature_addr, UVM_DEFAULT)\n `uvm_field_int(signature_addr, UVM_DEFAULT)\n `uvm_object_utils_end\n\n function new(string name = \"\");\n super.new(name);\n void'($value$plusargs(\"enable_irq_single_seq=%0d\", enable_irq_single_seq));\n void'($value$plusargs(\"enable_irq_multiple_seq=%0d\", enable_irq_multiple_seq));\n void'($value$plusargs(\"enable_nested_irq=%0d\", enable_nested_irq));\n void'($value$plusargs(\"enable_debug_seq=%0d\", enable_debug_seq));\n void'($value$plusargs(\"max_interval=%0d\", max_interval));\n void'($value$plusargs(\"require_signature_addr=%0d\", require_signature_addr));\n void'($value$plusargs(\"signature_addr=%s\", signature_addr_str));\n signature_addr = signature_addr_str.atohex();\n endfunction\n\nendclass\n", "pr_title": "[DV] Test nested interrupts", "pr_body": "Tests scenarios where Ibex is executing an interrupt handler and receives a second set of interrupts in the middle of the first handler.\r\nAs per the discussion in #557, I have eliminated nested NMI interrupt test scenarios from this testcase.\r\nThis PR relies on https://github.com/google/riscv-dv/pull/444 to be functionally correct, so will only merge this PR after vendoring the latest riscv-dv copy.\r\n\r\nSigned-off-by: Udi <udij@google.com>", "fix_patch": "diff --git a/dv/uvm/env/core_ibex_env_cfg.sv b/dv/uvm/env/core_ibex_env_cfg.sv\nindex 06f99852cd..4152230ddd 100644\n--- a/dv/uvm/env/core_ibex_env_cfg.sv\n+++ b/dv/uvm/env/core_ibex_env_cfg.sv\n@@ -6,6 +6,7 @@ class core_ibex_env_cfg extends uvm_object;\n \n bit enable_irq_single_seq;\n bit enable_irq_multiple_seq;\n+ bit enable_nested_irq;\n bit enable_debug_seq;\n bit[31:0] max_interval;\n bit require_signature_addr;\n@@ -15,6 +16,7 @@ class core_ibex_env_cfg extends uvm_object;\n `uvm_object_utils_begin(core_ibex_env_cfg)\n `uvm_field_int(enable_irq_single_seq, UVM_DEFAULT)\n `uvm_field_int(enable_irq_multiple_seq, UVM_DEFAULT)\n+ `uvm_field_int(enable_nested_irq, UVM_DEFAULT)\n `uvm_field_int(enable_debug_seq, UVM_DEFAULT)\n `uvm_field_int(max_interval, UVM_DEFAULT)\n `uvm_field_int(require_signature_addr, UVM_DEFAULT)\n@@ -25,6 +27,7 @@ class core_ibex_env_cfg extends uvm_object;\n super.new(name);\n void'($value$plusargs(\"enable_irq_single_seq=%0d\", enable_irq_single_seq));\n void'($value$plusargs(\"enable_irq_multiple_seq=%0d\", enable_irq_multiple_seq));\n+ void'($value$plusargs(\"enable_nested_irq=%0d\", enable_nested_irq));\n void'($value$plusargs(\"enable_debug_seq=%0d\", enable_debug_seq));\n void'($value$plusargs(\"max_interval=%0d\", max_interval));\n void'($value$plusargs(\"require_signature_addr=%0d\", require_signature_addr));\n"}
{"repo": "lowRISC/ibex", "pr_id": 905, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": true, "sufficient_for_diagnosis": false}, "reasoning": "The specification does not mention write mask granularity or the DataBitsPerMask parameter, which is the functional area modified by the patch, so it lacks a behavioral assertion directly related to the change."}, "generated_spec": "# Behavioral Specification: Instruction Cache (ibex_icache)\n\n## Overview\n\nThis module implements an instruction cache (I$) that sits between the processor core and the instruction memory bus. Its primary purpose is to reduce instruction fetch latency by storing recently used instructions and fetching ahead. The cache can be configured in size, associativity, line size, ECC protection, and caching policy.\n\nThe cache communicates with the core via a ready/valid handshake and with the instruction memory using a request/grant/data-valid interface. It supports speculative prefetching, cache invalidation, and error handling (including memory errors and PMP violations).\n\n## Core Interface Behavior\n\n### Instruction Request and Address Tracking\n\nThe core indicates that it will need instructions by asserting a request signal. When this signal is de‑asserted, the cache stops making new memory requests after completing any ongoing line fills.\n\nAn internal address counter tracks the next instruction to deliver. This counter is updated in one of two ways:\n- On a **branch**: when the core asserts a branch signal along with a valid target address, the counter is set to that address. The branch signal must be accompanied by a speculative branch signal (available earlier in the cycle). If the speculative branch is asserted but the actual branch is not, any lookup started that cycle is cancelled.\n- On **sequential execution**: when the core accepts an instruction, the counter increments by 2 or 4 bytes depending on whether the instruction is compressed (bottom two bits not equal to `2'b11`) or uncompressed.\n\nAfter reset (or when `rst_ni` is de‑asserted), the address counter is undefined. The core **must** assert a branch on or before the first cycle that the request signal is asserted after reset, otherwise the cache may fetch from arbitrary addresses.\n\n### Instruction Output\n\nValid instruction data (32 bits, aligned to the address output) is presented along with a `valid` signal. Once `valid` is asserted, all output signals remain stable until the core either accepts the instruction (by asserting `ready`) or the core issues a new branch. The only exception is after an error is reported: after an error, output signals are unconstrained until the next branch.\n\nThe instruction width is determined from the bottom two bits of the returned data:\n- If they equal `2'b11`, the instruction is 32 bits (uncompressed). Otherwise it is 16 bits (compressed).\n- For compressed instructions, the upper 16 bits of the 32‑bit output are unspecified and may change even after valid is asserted.\n\n### Alignment and Skid Buffer\n\nInstructions are always fetched as words (32 bits). To handle misalignment caused by compressed instructions, the cache contains a 16‑bit skid buffer:\n- If the output address is halfword‑aligned and the instruction is compressed, the lower 16 bits are used and the next word’s upper halfword may be buffered.\n- If the output address is word‑aligned and the instruction is uncompressed, both halves are delivered in one cycle.\n- If an uncompressed instruction straddles a word boundary (i.e., address bit 1 is high), the first halfword is buffered and the second halfword is delivered in a subsequent cycle.\n- Branches flush the skid buffer.\n\n### Error Reporting\n\nErrors from the instruction memory (both bus errors and PMP violations) are propagated to the core. An error is signalled on the output when an instruction fetch fails. When an error is reported, the data output is not specified. For uncompressed instructions that span two words, a second error signal indicates whether the second halfword caused the error; this is only meaningful when an error is reported.\n\nAfter the core observes an error on the output, it must issue a branch before accepting the next instruction. The output signals are otherwise unconstrained after an error.\n\n### Ready/Valid Handshake\n\nThe core accepts an instruction by asserting `ready` while `valid` is high. If `valid` is high and `ready` is not asserted, the output must remain stable until either `ready` is asserted or a branch occurs. A correctly behaving core must not assert `ready` while the request signal is de‑asserted.\n\n## Instruction Memory Interface\n\n### Request and Data Transfer\n\nThe cache requests instructions from memory using a standard request/grant/data-valid protocol. The request address is always aligned to the bus width (32 bits). A single request may be granted on the same cycle; after grant, the cache expects a data valid response (with optional error) for that request. Multiple requests can be outstanding.\n\n### Speculative Requests\n\nThe cache may issue speculative requests in parallel with a cache lookup. By default, speculative requests are made only on a branch. When the `SpecRequest` parameter is set, speculative requests are also made on every lookup attempt (even when not branching). This improves performance for workloads that have low cache hit rates, at the cost of extra bus traffic.\n\n### PMP Error Handling\n\nA dedicated PMP error input indicates that the fetch is disallowed by a physical memory protection check. When this signal is asserted together with a grant, the cache treats the request as if it were granted but never expects a data valid response. The entire cache line fetch for that address is aborted, and an error is reported to the core. If both grant and PMP error are asserted, the error takes precedence.\n\n## Cache Operation Modes\n\n### Pass‑Through Mode\n\nWhen the cache enable signal is de‑asserted, the cache operates in pass‑through mode:\n- Every instruction request from the core is fetched directly from memory.\n- No instruction data is stored in the cache RAMs.\n- The prefetch buffer is used only to supply sequential instructions; on a branch the buffer is discarded.\n- The core still receives instructions through the same interface, but no caching takes place.\n\n### Normal Caching (All Misses Allocated)\n\nWhen caching is enabled, every missing fetch that passes through the cache pipeline results in a cache line allocation. The victim way is chosen using a per‑set pseudo‑random round‑robin counter, preferring invalid ways if any exist.\n\n### Branch‑Only Caching\n\nWhen the `BranchCache` parameter is set, the cache only allocates lines for the target of a branch and the two subsequent cache lines. All other misses are not cached. This mode reduces cache pollution for workloads that can be effectively prefetched, while still accelerating branch targets.\n\n### Prefetching\n\nThe cache maintains a prefetch address that advances in cache‑line increments after each granted lookup. On every branch, the prefetch address is set to the branch target. The prefetcher continues to request sequential lines as long as the request signal is high and the fill buffers are not overloaded.\n\n## Cache Invalidation\n\nThe cache is invalidated:\n- **After reset**: a full invalidation of all tag entries is performed automatically.\n- **On request**: when the cache invalidation input is asserted for at least one cycle, an invalidation sequence begins.\n\nDuring invalidation, the cache behaves as if caching is disabled (no new allocations), but existing lookups and instruction fetches can still proceed. The invalidation walks through all cache indices and clears the valid bit in the tag RAM for all ways. Once the walk completes, normal caching resumes. If a second invalidation request is received while an invalidation is in progress, it is ignored (invalidation does not need to restart).\n\n## Cache ECC Protection\n\nIf ECC is enabled, each tag and data RAM entry includes SECDED checkbits. On a cache read (at the end of the pipeline), the ECC logic checks both tag and data for errors:\n- Any single‑ or double‑bit error in a tag or data RAM is detected.\n- When an error is detected, the cache treats the current lookup as a miss: the request is served from the instruction memory, and the erroneous line(s) are invalidated (valid bit cleared) in the following cycle.\n- No inline correction is performed; the corrupted data is always discarded.\n- Lookups are blocked while the invalidation write for the erroneous way is in progress.\n\n## Fill Buffers\n\nThe cache contains a set of fill buffers (at least 2) that manage the lifecycle of each cache line fetch. Every lookup request (whether it hits or misses) acquires a fill buffer. The fill buffer tracks:\n\n- **External requests**: multiple bus requests to fetch all beats of the cache line.\n- **Received data**: counting returning beats.\n- **Output data**: supplying beats to the core as they become available.\n- **Cache allocation**: once all beats have been received, if the line is to be cached (and no error occurred), it is written into the data and tag RAMs.\n- **Cancellation**: fill buffers are cancelled on a branch if no external requests have been issued. If requests have already been issued, they complete and the line may still be allocated (unless the cache is disabled or an invalidation is in progress).\n\nFill buffers are age‑ordered; the oldest buffer that has data available supplies the next beat to the core. Data can come from three sources: a cache hit (data from the data RAM), buffered data in the fill buffer, or directly from the bus (rvalid data). Hitting lines supply the first word immediately from the RAMs; subsequent words are buffered and supplied on demand.\n\n## Busy Signal\n\nThe cache asserts a busy signal when it is performing any operation that prevents clock gating:\n- While an invalidation is in progress.\n- While any fill buffer has an outstanding external request that has not yet received its data (i.e., it is still waiting for bus responses).\n\nWhen the busy signal is de‑asserted, the cache has no pending bus transactions and is not invalidating; it is safe to gate the clock.\n\n## Configuration Parameter Effects\n\nThe following parameters alter the observable behavior:\n\n| Parameter | Effect |\n|-----------|--------|\n| `BusWidth` | Fixed at 32 bits for the current Ibex system. |\n| `CacheSizeBytes` | Total cache capacity (all ways combined). |\n| `LineSize` | Width of each cache line in bits. Must be greater than 32. Larger lines increase area efficiency but can cause higher latency on misaligned branches. |\n| `NumWays` | Associativity (number of ways per set). |\n| `ICacheECC` | When set, SECDED ECC is added to tag and data RAMs; error detection and invalidation on error are enabled. |\n| `SpecRequest` | When set, speculative bus requests are made on every lookup; otherwise only on branches. |\n| `BranchCache` | When set, only branch targets (and two following lines) are cached; all other misses bypass the cache. |\n\n## Behavioral Assumptions and Constraints\n\n- The core must ensure that `branch_spec_i` is asserted whenever `branch_i` is asserted.\n- The core must not assert `ready` when the request signal is de‑asserted.\n- After an error is reported, the core must issue a branch before accepting further instructions.\n- The cache does not perform any write‑back or coherence; invalidations are global and unconditional.\n- The cache is designed for a single‑core system with no snooping or DMA.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Instruction cache\n *\n * Provides an instruction cache along with cache management, instruction buffering and prefetching\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_icache #(\n // Cache arrangement parameters\n parameter int unsigned BusWidth = 32,\n parameter int unsigned CacheSizeBytes = 4*1024,\n parameter bit ICacheECC = 1'b0,\n parameter int unsigned LineSize = 64,\n parameter int unsigned NumWays = 2,\n // Always make speculative bus requests in parallel with lookups\n parameter bit SpecRequest = 1'b0,\n // Only cache branch targets\n parameter bit BranchCache = 1'b0\n) (\n // Clock and reset\n input logic clk_i,\n input logic rst_ni,\n\n // Signal that the core would like instructions\n input logic req_i,\n\n // Set the cache's address counter\n input logic branch_i,\n input logic branch_spec_i,\n input logic [31:0] addr_i,\n\n // IF stage interface: Pass fetched instructions to the core\n input logic ready_i,\n output logic valid_o,\n output logic [31:0] rdata_o,\n output logic [31:0] addr_o,\n output logic err_o,\n output logic err_plus2_o,\n\n // Instruction memory / interconnect interface: Fetch instruction data from memory\n output logic instr_req_o,\n input logic instr_gnt_i,\n output logic [31:0] instr_addr_o,\n input logic [BusWidth-1:0] instr_rdata_i,\n input logic instr_err_i,\n input logic instr_pmp_err_i,\n input logic instr_rvalid_i,\n\n // Cache status\n input logic icache_enable_i,\n input logic icache_inval_i,\n output logic busy_o\n);\n\n // NOTE RTL IS DRAFT\n\n // Local constants\n localparam int unsigned ADDR_W = 32;\n // Number of fill buffers (must be >= 2)\n localparam int unsigned NUM_FB = 4;\n // Request throttling threshold\n localparam int unsigned FB_THRESHOLD = NUM_FB - 2;\n // Derived parameters\n localparam int unsigned LINE_SIZE_ECC = ICacheECC ? (LineSize + 8) : LineSize;\n localparam int unsigned LINE_SIZE_BYTES = LineSize/8;\n localparam int unsigned LINE_W = $clog2(LINE_SIZE_BYTES);\n localparam int unsigned BUS_BYTES = BusWidth/8;\n localparam int unsigned BUS_W = $clog2(BUS_BYTES);\n localparam int unsigned LINE_BEATS = LINE_SIZE_BYTES / BUS_BYTES;\n localparam int unsigned LINE_BEATS_W = $clog2(LINE_BEATS);\n localparam int unsigned NUM_LINES = CacheSizeBytes / NumWays / LINE_SIZE_BYTES;\n localparam int unsigned INDEX_W = $clog2(NUM_LINES);\n localparam int unsigned INDEX_HI = INDEX_W + LINE_W - 1;\n localparam int unsigned TAG_SIZE = ADDR_W - INDEX_W - LINE_W + 1; // 1 valid bit\n localparam int unsigned TAG_SIZE_ECC = ICacheECC ? (TAG_SIZE + 6) : TAG_SIZE;\n localparam int unsigned OUTPUT_BEATS = (BUS_BYTES / 2); // number of halfwords\n\n // Prefetch signals\n logic [ADDR_W-1:0] lookup_addr_aligned;\n logic [ADDR_W-1:0] prefetch_addr_d, prefetch_addr_q;\n logic prefetch_addr_en;\n // Cache pipelipe IC0 signals\n logic branch_suppress;\n logic lookup_throttle;\n logic lookup_req_ic0;\n logic [ADDR_W-1:0] lookup_addr_ic0;\n logic [INDEX_W-1:0] lookup_index_ic0;\n logic fill_req_ic0;\n logic [INDEX_W-1:0] fill_index_ic0;\n logic [TAG_SIZE-1:0] fill_tag_ic0;\n logic [LineSize-1:0] fill_wdata_ic0;\n logic lookup_grant_ic0;\n logic lookup_actual_ic0;\n logic fill_grant_ic0;\n logic tag_req_ic0;\n logic [INDEX_W-1:0] tag_index_ic0;\n logic [NumWays-1:0] tag_banks_ic0;\n logic tag_write_ic0;\n logic [TAG_SIZE_ECC-1:0] tag_wdata_ic0;\n logic data_req_ic0;\n logic [INDEX_W-1:0] data_index_ic0;\n logic [NumWays-1:0] data_banks_ic0;\n logic data_write_ic0;\n logic [LINE_SIZE_ECC-1:0] data_wdata_ic0;\n // Cache pipelipe IC1 signals\n logic [TAG_SIZE_ECC-1:0] tag_rdata_ic1 [NumWays];\n logic [LINE_SIZE_ECC-1:0] data_rdata_ic1 [NumWays];\n logic [LINE_SIZE_ECC-1:0] hit_data_ic1;\n logic lookup_valid_ic1;\n logic [ADDR_W-1:INDEX_HI+1] lookup_addr_ic1;\n logic [NumWays-1:0] tag_match_ic1;\n logic tag_hit_ic1;\n logic [NumWays-1:0] tag_invalid_ic1;\n logic [NumWays-1:0] lowest_invalid_way_ic1;\n logic [NumWays-1:0] round_robin_way_ic1, round_robin_way_q;\n logic [NumWays-1:0] sel_way_ic1;\n logic ecc_err_ic1;\n logic ecc_write_req;\n logic [NumWays-1:0] ecc_write_ways;\n logic [INDEX_W-1:0] ecc_write_index;\n // Fill buffer signals\n logic gnt_or_pmp_err, gnt_not_pmp_err;\n logic [$clog2(NUM_FB)-1:0] fb_fill_level;\n logic fill_cache_new;\n logic fill_new_alloc;\n logic fill_spec_req, fill_spec_done, fill_spec_hold;\n logic [NUM_FB-1:0][NUM_FB-1:0] fill_older_d, fill_older_q;\n logic [NUM_FB-1:0] fill_alloc_sel, fill_alloc;\n logic [NUM_FB-1:0] fill_busy_d, fill_busy_q;\n logic [NUM_FB-1:0] fill_done;\n logic [NUM_FB-1:0] fill_in_ic1;\n logic [NUM_FB-1:0] fill_stale_d, fill_stale_q;\n logic [NUM_FB-1:0] fill_cache_d, fill_cache_q;\n logic [NUM_FB-1:0] fill_hit_ic1, fill_hit_d, fill_hit_q;\n logic [NUM_FB-1:0][LINE_BEATS_W:0] fill_ext_cnt_d, fill_ext_cnt_q;\n logic [NUM_FB-1:0] fill_ext_hold_d, fill_ext_hold_q;\n logic [NUM_FB-1:0] fill_ext_done;\n logic [NUM_FB-1:0][LINE_BEATS_W:0] fill_rvd_cnt_d, fill_rvd_cnt_q;\n logic [NUM_FB-1:0] fill_rvd_done;\n logic [NUM_FB-1:0] fill_ram_done_d, fill_ram_done_q;\n logic [NUM_FB-1:0] fill_out_grant;\n logic [NUM_FB-1:0][LINE_BEATS_W:0] fill_out_cnt_d, fill_out_cnt_q;\n logic [NUM_FB-1:0] fill_out_done;\n logic [NUM_FB-1:0] fill_ext_req, fill_rvd_exp, fill_ram_req, fill_out_req;\n logic [NUM_FB-1:0] fill_data_sel, fill_data_reg, fill_data_hit, fill_data_rvd;\n logic [NUM_FB-1:0][LINE_BEATS_W-1:0] fill_ext_off, fill_rvd_off;\n logic [NUM_FB-1:0][LINE_BEATS_W:0] fill_rvd_beat;\n logic [NUM_FB-1:0] fill_ext_arb, fill_ram_arb, fill_out_arb;\n logic [NUM_FB-1:0] fill_rvd_arb;\n logic [NUM_FB-1:0] fill_entry_en;\n logic [NUM_FB-1:0] fill_addr_en;\n logic [NUM_FB-1:0] fill_way_en;\n logic [NUM_FB-1:0][LINE_BEATS-1:0] fill_data_en;\n logic [NUM_FB-1:0][LINE_BEATS-1:0] fill_err_d, fill_err_q;\n logic [ADDR_W-1:0] fill_addr_q [NUM_FB];\n logic [NumWays-1:0] fill_way_q [NUM_FB];\n logic [LineSize-1:0] fill_data_d [NUM_FB];\n logic [LineSize-1:0] fill_data_q [NUM_FB];\n logic [ADDR_W-1:BUS_W] fill_ext_req_addr;\n logic [ADDR_W-1:0] fill_ram_req_addr;\n logic [NumWays-1:0] fill_ram_req_way;\n logic [LineSize-1:0] fill_ram_req_data;\n logic [LineSize-1:0] fill_out_data;\n logic [LINE_BEATS-1:0] fill_out_err;\n // External req signals\n logic instr_req;\n logic [ADDR_W-1:BUS_W] instr_addr;\n // Data output signals\n logic skid_complete_instr;\n logic skid_ready;\n logic output_compressed;\n logic skid_valid_d, skid_valid_q, skid_en;\n logic [15:0] skid_data_d, skid_data_q;\n logic skid_err_q;\n logic output_valid;\n logic addr_incr_two;\n logic output_addr_en;\n logic [ADDR_W-1:1] output_addr_d, output_addr_q;\n logic [15:0] output_data_lo, output_data_hi;\n logic data_valid, output_ready;\n logic [LineSize-1:0] line_data;\n logic [LINE_BEATS-1:0] line_err;\n logic [31:0] line_data_muxed;\n logic line_err_muxed;\n logic [31:0] output_data;\n logic output_err;\n // Invalidations\n logic start_inval, inval_done;\n logic reset_inval_q;\n logic inval_prog_d, inval_prog_q;\n logic [INDEX_W-1:0] inval_index_d, inval_index_q;\n\n //////////////////////////\n // Instruction prefetch //\n //////////////////////////\n\n assign lookup_addr_aligned = {lookup_addr_ic0[ADDR_W-1:LINE_W],{LINE_W{1'b0}}};\n\n // The prefetch address increments by one cache line for each granted request.\n // This address is also updated if there is a branch that is not granted, since the target\n // address (addr_i) is only valid for one cycle while branch_i is high.\n\n // The captured branch target address is not forced to be aligned since the offset in the cache\n // line must also be recorded for later use by the fill buffers.\n assign prefetch_addr_d =\n lookup_grant_ic0 ? (lookup_addr_aligned + {{ADDR_W-LINE_W-1{1'b0}},1'b1,{LINE_W{1'b0}}}) :\n addr_i;\n\n assign prefetch_addr_en = branch_i | lookup_grant_ic0;\n\n always_ff @(posedge clk_i) begin\n if (prefetch_addr_en) begin\n prefetch_addr_q <= prefetch_addr_d;\n end\n end\n\n ////////////////////////\n // Pipeline stage IC0 //\n ////////////////////////\n\n // Cache lookup\n assign lookup_throttle = (fb_fill_level > FB_THRESHOLD[$clog2(NUM_FB)-1:0]);\n\n assign lookup_req_ic0 = req_i & ~&fill_busy_q & (branch_i | ~lookup_throttle) & ~ecc_write_req;\n assign lookup_addr_ic0 = branch_spec_i ? addr_i :\n prefetch_addr_q;\n assign lookup_index_ic0 = lookup_addr_ic0[INDEX_HI:LINE_W];\n\n // Cache write\n assign fill_req_ic0 = (|fill_ram_req);\n assign fill_index_ic0 = fill_ram_req_addr[INDEX_HI:LINE_W];\n assign fill_tag_ic0 = {(~inval_prog_q & ~ecc_write_req),fill_ram_req_addr[ADDR_W-1:INDEX_HI+1]};\n assign fill_wdata_ic0 = fill_ram_req_data;\n\n // Suppress a new lookup on a not-taken branch (as the address will be incorrect)\n assign branch_suppress = branch_spec_i & ~branch_i;\n\n // Arbitrated signals - lookups have highest priority\n assign lookup_grant_ic0 = lookup_req_ic0 & ~branch_suppress;\n assign fill_grant_ic0 = fill_req_ic0 & (~lookup_req_ic0 | branch_suppress) & ~inval_prog_q &\n ~ecc_write_req;\n // Qualified lookup grant to mask ram signals in IC1 if access was not made\n assign lookup_actual_ic0 = lookup_grant_ic0 & icache_enable_i & ~inval_prog_q & ~start_inval;\n\n // Tagram\n assign tag_req_ic0 = lookup_req_ic0 | fill_req_ic0 | inval_prog_q | ecc_write_req;\n assign tag_index_ic0 = inval_prog_q ? inval_index_q :\n ecc_write_req ? ecc_write_index :\n fill_grant_ic0 ? fill_index_ic0 :\n lookup_index_ic0;\n assign tag_banks_ic0 = ecc_write_req ? ecc_write_ways :\n fill_grant_ic0 ? fill_ram_req_way :\n {NumWays{1'b1}};\n assign tag_write_ic0 = fill_grant_ic0 | inval_prog_q | ecc_write_req;\n\n // Dataram\n assign data_req_ic0 = lookup_req_ic0 | fill_req_ic0;\n assign data_index_ic0 = tag_index_ic0;\n assign data_banks_ic0 = tag_banks_ic0;\n assign data_write_ic0 = tag_write_ic0;\n\n // Append ECC checkbits to write data if required\n if (ICacheECC) begin : gen_ecc_wdata\n\n // Tagram ECC\n // Reuse the same ecc encoding module for larger cache sizes by padding with zeros\n logic [21:0] tag_ecc_input_padded;\n logic [27:0] tag_ecc_output_padded;\n logic [22-TAG_SIZE:0] tag_ecc_output_unused;\n\n assign tag_ecc_input_padded = {{22-TAG_SIZE{1'b0}},fill_tag_ic0};\n assign tag_ecc_output_unused = tag_ecc_output_padded[21:TAG_SIZE-1];\n\n prim_secded_28_22_enc tag_ecc_enc (\n .in (tag_ecc_input_padded),\n .out (tag_ecc_output_padded)\n );\n\n assign tag_wdata_ic0 = {tag_ecc_output_padded[27:22],tag_ecc_output_padded[TAG_SIZE-1:0]};\n\n // Dataram ECC\n prim_secded_72_64_enc data_ecc_enc (\n .in (fill_wdata_ic0),\n .out (data_wdata_ic0)\n );\n\n end else begin : gen_noecc_wdata\n assign tag_wdata_ic0 = fill_tag_ic0;\n assign data_wdata_ic0 = fill_wdata_ic0;\n end\n\n ////////////////\n // IC0 -> IC1 //\n ////////////////\n\n for (genvar way = 0; way < NumWays; way++) begin : gen_rams\n // Tag RAM instantiation\n prim_ram_1p #(\n .Width (TAG_SIZE_ECC),\n .Depth (NUM_LINES),\n .DataBitsPerMask (TAG_SIZE_ECC)\n ) tag_bank (\n .clk_i (clk_i),\n .req_i (tag_req_ic0 & tag_banks_ic0[way]),\n .write_i (tag_write_ic0),\n .wmask_i ({TAG_SIZE_ECC{1'b1}}),\n .addr_i (tag_index_ic0),\n .wdata_i (tag_wdata_ic0),\n .rdata_o (tag_rdata_ic1[way])\n );\n // Data RAM instantiation\n prim_ram_1p #(\n .Width (LINE_SIZE_ECC),\n .Depth (NUM_LINES),\n .DataBitsPerMask (LINE_SIZE_ECC)\n ) data_bank (\n .clk_i (clk_i),\n .req_i (data_req_ic0 & data_banks_ic0[way]),\n .write_i (data_write_ic0),\n .wmask_i ({LINE_SIZE_ECC{1'b1}}),\n .addr_i (data_index_ic0),\n .wdata_i (data_wdata_ic0),\n .rdata_o (data_rdata_ic1[way])\n );\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n lookup_valid_ic1 <= 1'b0;\n end else begin\n lookup_valid_ic1 <= lookup_actual_ic0;\n end\n end\n\n always_ff @(posedge clk_i) begin\n if (lookup_grant_ic0) begin\n lookup_addr_ic1 <= lookup_addr_ic0[ADDR_W-1:INDEX_HI+1];\n fill_in_ic1 <= fill_alloc_sel;\n end\n end\n\n ////////////////////////\n // Pipeline stage IC1 //\n ////////////////////////\n\n // Tag matching\n for (genvar way = 0; way < NumWays; way++) begin : gen_tag_match\n assign tag_match_ic1[way] = (tag_rdata_ic1[way][TAG_SIZE-1:0] ==\n {1'b1,lookup_addr_ic1[ADDR_W-1:INDEX_HI+1]});\n assign tag_invalid_ic1[way] = ~tag_rdata_ic1[way][TAG_SIZE-1];\n end\n\n assign tag_hit_ic1 = |tag_match_ic1;\n\n // Hit data mux\n always_comb begin\n hit_data_ic1 = 'b0;\n for (int way = 0; way < NumWays; way++) begin\n if (tag_match_ic1[way]) begin\n hit_data_ic1 |= data_rdata_ic1[way];\n end\n end\n end\n\n // Way selection for allocations to the cache (onehot signals)\n // 1 first invalid way\n // 2 global round-robin (pseudorandom) way\n assign lowest_invalid_way_ic1[0] = tag_invalid_ic1[0];\n assign round_robin_way_ic1[0] = round_robin_way_q[NumWays-1];\n for (genvar way = 1; way < NumWays; way++) begin : gen_lowest_way\n assign lowest_invalid_way_ic1[way] = tag_invalid_ic1[way] & ~|tag_invalid_ic1[way-1:0];\n assign round_robin_way_ic1[way] = round_robin_way_q[way-1];\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n round_robin_way_q <= {{NumWays-1{1'b0}},1'b1};\n end else if (lookup_valid_ic1) begin\n round_robin_way_q <= round_robin_way_ic1;\n end\n end\n\n assign sel_way_ic1 = |tag_invalid_ic1 ? lowest_invalid_way_ic1 :\n round_robin_way_q;\n\n // ECC checking logic\n if (ICacheECC) begin : gen_data_ecc_checking\n logic [NumWays-1:0] tag_err_ic1;\n logic [1:0] data_err_ic1;\n logic ecc_correction_write_d, ecc_correction_write_q;\n logic [NumWays-1:0] ecc_correction_ways_d, ecc_correction_ways_q;\n logic [INDEX_W-1:0] lookup_index_ic1, ecc_correction_index_q;\n\n // Tag ECC checking\n for (genvar way = 0; way < NumWays; way++) begin : gen_tag_ecc\n logic [1:0] tag_err_bank_ic1;\n logic [27:0] tag_rdata_padded_ic1;\n\n // Expand the tag rdata with extra padding if the tag size is less than the maximum\n assign tag_rdata_padded_ic1 = {tag_rdata_ic1[way][TAG_SIZE_ECC-1-:6],\n {22-TAG_SIZE{1'b0}},\n tag_rdata_ic1[way][TAG_SIZE-1:0]};\n\n prim_secded_28_22_dec data_ecc_dec (\n .in (tag_rdata_padded_ic1),\n .d_o (),\n .syndrome_o (),\n .err_o (tag_err_bank_ic1)\n );\n assign tag_err_ic1[way] = |tag_err_bank_ic1;\n end\n\n // Data ECC checking\n // Note - could generate for all ways and mux after\n prim_secded_72_64_dec data_ecc_dec (\n .in (hit_data_ic1),\n .d_o (),\n .syndrome_o (),\n .err_o (data_err_ic1)\n );\n\n assign ecc_err_ic1 = lookup_valid_ic1 & ((|data_err_ic1) | (|tag_err_ic1));\n\n // Error correction\n // The way(s) producing the error will be invalidated in the next cycle.\n assign ecc_correction_ways_d = tag_err_ic1 | (tag_match_ic1 & {NumWays{|data_err_ic1}});\n assign ecc_correction_write_d = ecc_err_ic1;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n ecc_correction_write_q <= 1'b0;\n end else begin\n ecc_correction_write_q <= ecc_correction_write_d;\n end\n end\n\n // The index is required in IC1 only when ECC is configured so is registered here\n always_ff @(posedge clk_i) begin\n if (lookup_grant_ic0) begin\n lookup_index_ic1 <= lookup_addr_ic0[INDEX_HI-:INDEX_W];\n end\n end\n\n // Store the ways with errors to be invalidated\n always_ff @(posedge clk_i) begin\n if (ecc_err_ic1) begin\n ecc_correction_ways_q <= ecc_correction_ways_d;\n ecc_correction_index_q <= lookup_index_ic1;\n end\n end\n\n assign ecc_write_req = ecc_correction_write_q;\n assign ecc_write_ways = ecc_correction_ways_q;\n assign ecc_write_index = ecc_correction_index_q;\n\n end else begin : gen_no_data_ecc\n assign ecc_err_ic1 = 1'b0;\n assign ecc_write_req = 1'b0;\n assign ecc_write_ways = '0;\n assign ecc_write_index = '0;\n end\n\n ///////////////////////////////\n // Cache allocation decision //\n ///////////////////////////////\n\n if (BranchCache) begin : gen_caching_logic\n\n // Cache branch target + a number of subsequent lines\n localparam int unsigned CACHE_AHEAD = 2;\n localparam int unsigned CACHE_CNT_W = (CACHE_AHEAD == 1) ? 1 : $clog2(CACHE_AHEAD) + 1;\n logic cache_cnt_dec;\n logic [CACHE_CNT_W-1:0] cache_cnt_d, cache_cnt_q;\n\n assign cache_cnt_dec = lookup_grant_ic0 & (|cache_cnt_q);\n assign cache_cnt_d = branch_i ? CACHE_AHEAD[CACHE_CNT_W-1:0] :\n (cache_cnt_q - {{CACHE_CNT_W-1{1'b0}},cache_cnt_dec});\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n cache_cnt_q <= '0;\n end else begin\n cache_cnt_q <= cache_cnt_d;\n end\n end\n\n assign fill_cache_new = (branch_i | (|cache_cnt_q)) & icache_enable_i &\n ~icache_inval_i & ~inval_prog_q;\n\n end else begin : gen_cache_all\n\n // Cache all missing fetches\n assign fill_cache_new = icache_enable_i & ~start_inval & ~inval_prog_q;\n end\n\n //////////////////////////\n // Fill buffer tracking //\n //////////////////////////\n\n always_comb begin\n fb_fill_level = '0;\n for (int i = 0; i < NUM_FB; i++) begin\n if (fill_busy_q[i] & ~fill_stale_q[i]) begin\n fb_fill_level += {{$clog2(NUM_FB)-1{1'b0}},1'b1};\n end\n end\n end\n\n // PMP errors might not / don't need to be granted (since the external request is masked)\n assign gnt_or_pmp_err = instr_gnt_i | instr_pmp_err_i;\n assign gnt_not_pmp_err = instr_gnt_i & ~instr_pmp_err_i;\n // Allocate a new buffer for every granted lookup\n assign fill_new_alloc = lookup_grant_ic0;\n // Track whether a speculative external request was made from IC0, and whether it was granted\n assign fill_spec_req = (SpecRequest | branch_i) & ~|fill_ext_req;\n assign fill_spec_done = fill_spec_req & gnt_not_pmp_err;\n assign fill_spec_hold = fill_spec_req & ~gnt_or_pmp_err;\n\n for (genvar fb = 0; fb < NUM_FB; fb++) begin : gen_fbs\n\n /////////////////////////////\n // Fill buffer allocations //\n /////////////////////////////\n\n // Allocate the lowest available buffer\n if (fb == 0) begin : gen_fb_zero\n assign fill_alloc_sel[fb] = ~fill_busy_q[fb];\n end else begin : gen_fb_rest\n assign fill_alloc_sel[fb] = ~fill_busy_q[fb] & (&fill_busy_q[fb-1:0]);\n end\n\n assign fill_alloc[fb] = fill_alloc_sel[fb] & fill_new_alloc;\n assign fill_busy_d[fb] = fill_alloc[fb] | (fill_busy_q[fb] & ~fill_done[fb]);\n\n // Track which other fill buffers are older than this one (for age-based arbitration)\n // TODO sparsify\n assign fill_older_d[fb] = (fill_alloc[fb] ? fill_busy_q : fill_older_q[fb]) & ~fill_done;\n\n // A fill buffer can release once all its actions are completed\n // all data written to the cache (unless hit or error)\n assign fill_done[fb] = (fill_ram_done_q[fb] | fill_hit_q[fb] | ~fill_cache_q[fb] |\n (|fill_err_q[fb])) &\n // all data output unless stale due to intervening branch\n (fill_out_done[fb] | fill_stale_q[fb] | branch_i) &\n // all external requests completed\n fill_rvd_done[fb];\n\n /////////////////////////////////\n // Fill buffer status tracking //\n /////////////////////////////////\n\n // Track staleness (requests become stale when a branch intervenes)\n assign fill_stale_d[fb] = fill_busy_q[fb] & (branch_i | fill_stale_q[fb]);\n // Track whether or not this request should allocate to the cache\n // Any invalidation or disabling of the cache while the buffer is busy will stop allocation\n assign fill_cache_d[fb] = (fill_alloc[fb] & fill_cache_new) |\n (fill_cache_q[fb] & fill_busy_q[fb] &\n icache_enable_i & ~icache_inval_i);\n // Record whether the request hit in the cache\n assign fill_hit_ic1[fb] = lookup_valid_ic1 & fill_in_ic1[fb] & tag_hit_ic1;\n assign fill_hit_d[fb] = (fill_hit_ic1[fb] & ~ecc_err_ic1) |\n (fill_hit_q[fb] & fill_busy_q[fb]);\n\n ///////////////////////////////////////////\n // Fill buffer external request tracking //\n ///////////////////////////////////////////\n\n // Make an external request\n assign fill_ext_req[fb] = fill_busy_q[fb] & ~fill_ext_done[fb];\n\n // Count the number of completed external requests (each line requires LINE_BEATS requests)\n // Don't count fake PMP error grants here since they will never receive an rvalid response\n assign fill_ext_cnt_d[fb] = fill_alloc[fb] ?\n {{LINE_BEATS_W{1'b0}},fill_spec_done} :\n (fill_ext_cnt_q[fb] + {{LINE_BEATS_W{1'b0}},\n fill_ext_arb[fb] & gnt_not_pmp_err});\n // External request must be held until granted\n assign fill_ext_hold_d[fb] = (fill_alloc[fb] & fill_spec_hold) |\n (fill_ext_arb[fb] & ~gnt_or_pmp_err);\n // External requests are completed when the counter is filled or when the request is cancelled\n assign fill_ext_done[fb] = (fill_ext_cnt_q[fb][LINE_BEATS_W] |\n // external requests are considered complete if the request hit\n (fill_hit_ic1[fb] & ~ecc_err_ic1) | fill_hit_q[fb] |\n // external requests will stop once any PMP error is received\n fill_err_q[fb][fill_ext_off[fb]] |\n // cancel if the line is stale and won't be cached\n (~fill_cache_q[fb] & (branch_i | fill_stale_q[fb]))) &\n // can't cancel while we are waiting for a grant on the bus\n ~fill_ext_hold_q[fb];\n // Track whether this fill buffer expects to receive beats of data\n assign fill_rvd_exp[fb] = fill_busy_q[fb] & ~fill_rvd_done[fb];\n // Count the number of rvalid beats received\n assign fill_rvd_cnt_d[fb] = fill_alloc[fb] ? '0 :\n (fill_rvd_cnt_q[fb] +\n {{LINE_BEATS_W{1'b0}},fill_rvd_arb[fb]});\n // External data is complete when all issued external requests have received their data\n assign fill_rvd_done[fb] = fill_ext_done[fb] & (fill_rvd_cnt_q[fb] == fill_ext_cnt_q[fb]);\n\n //////////////////////////////////////\n // Fill buffer data output tracking //\n //////////////////////////////////////\n\n // Send data to the IF stage for requests that are not stale, have not completed their\n // data output, and have data available to send.\n // Data is available if:\n // - The request hit in the cache\n // - The current beat is an error (since a PMP error might not actually receive any data)\n // - Buffered data is available (fill_rvd_cnt_q is ahead of fill_out_cnt_q)\n // - Data is available from the bus this cycle (fill_rvd_arb)\n assign fill_out_req[fb] = fill_busy_q[fb] & ~fill_stale_q[fb] & ~fill_out_done[fb] &\n (fill_hit_ic1[fb] | fill_hit_q[fb] |\n (fill_err_q[fb][fill_out_cnt_q[fb][LINE_BEATS_W-1:0]]) |\n (fill_rvd_beat[fb] > fill_out_cnt_q[fb]) | fill_rvd_arb[fb]);\n\n // Calculate when a beat of data is output. Any ECC error squashes the output that cycle.\n assign fill_out_grant[fb] = fill_out_arb[fb] & output_ready & ~ecc_err_ic1;\n\n // Count the beats of data output to the IF stage\n assign fill_out_cnt_d[fb] = fill_alloc[fb] ? {1'b0,lookup_addr_ic0[LINE_W-1:BUS_W]} :\n (fill_out_cnt_q[fb] +\n {{LINE_BEATS_W{1'b0}},fill_out_grant[fb]});\n // Data output complete when the counter fills\n assign fill_out_done[fb] = fill_out_cnt_q[fb][LINE_BEATS_W];\n\n //////////////////////////////////////\n // Fill buffer ram request tracking //\n //////////////////////////////////////\n\n // make a fill request once all data beats received\n assign fill_ram_req[fb] = fill_busy_q[fb] & fill_rvd_cnt_q[fb][LINE_BEATS_W] &\n // unless the request hit, was non-allocating or got an error\n ~fill_hit_q[fb] & fill_cache_q[fb] & ~|fill_err_q[fb] &\n // or the request was already completed\n ~fill_ram_done_q[fb];\n\n // Record when a cache allocation request has been completed\n assign fill_ram_done_d[fb] = fill_ram_arb[fb] | (fill_ram_done_q[fb] & fill_busy_q[fb]);\n\n //////////////////////////////\n // Fill buffer line offsets //\n //////////////////////////////\n\n // When we branch into the middle of a line, the output count will not start from zero. This\n // beat count is used to know which incoming rdata beats are relevant.\n assign fill_rvd_beat[fb] = {1'b0,fill_addr_q[fb][LINE_W-1:BUS_W]} +\n fill_rvd_cnt_q[fb][LINE_BEATS_W:0];\n assign fill_ext_off[fb] = fill_addr_q[fb][LINE_W-1:BUS_W] +\n fill_ext_cnt_q[fb][LINE_BEATS_W-1:0];\n assign fill_rvd_off[fb] = fill_rvd_beat[fb][LINE_BEATS_W-1:0];\n\n /////////////////////////////\n // Fill buffer arbitration //\n /////////////////////////////\n\n // Age based arbitration - all these signals are one-hot\n assign fill_ext_arb[fb] = fill_ext_req[fb] & ~|(fill_ext_req & fill_older_q[fb]);\n assign fill_ram_arb[fb] = fill_ram_req[fb] & fill_grant_ic0 & ~|(fill_ram_req & fill_older_q[fb]);\n // Calculate which fill buffer is the oldest one which still needs to output data to IF\n assign fill_data_sel[fb] = ~|(fill_busy_q & ~fill_out_done & ~fill_stale_q &\n fill_older_q[fb]);\n // Arbitrate the request which has data available to send, and is the oldest outstanding\n assign fill_out_arb[fb] = fill_out_req[fb] & fill_data_sel[fb];\n // Assign incoming rvalid data to the oldest fill buffer expecting it\n assign fill_rvd_arb[fb] = instr_rvalid_i & fill_rvd_exp[fb] & ~|(fill_rvd_exp & fill_older_q[fb]);\n\n /////////////////////////////\n // Fill buffer data muxing //\n /////////////////////////////\n\n // Output data muxing controls\n // 1. Select data from the fill buffer data register\n assign fill_data_reg[fb] = fill_busy_q[fb] & ~fill_stale_q[fb] &\n ~fill_out_done[fb] & fill_data_sel[fb] &\n // The incoming data is already ahead of the output count\n ((fill_rvd_beat[fb] > fill_out_cnt_q[fb]) | fill_hit_q[fb] |\n (|fill_err_q[fb]));\n // 2. Select IC1 hit data\n assign fill_data_hit[fb] = fill_busy_q[fb] & fill_hit_ic1[fb] & fill_data_sel[fb];\n // 3. Select incoming instr_rdata_i\n assign fill_data_rvd[fb] = fill_busy_q[fb] & fill_rvd_arb[fb] & ~fill_hit_q[fb] &\n ~fill_hit_ic1[fb] & ~fill_stale_q[fb] & ~fill_out_done[fb] &\n // The incoming data lines up with the output count\n (fill_rvd_beat[fb] == fill_out_cnt_q[fb]) & fill_data_sel[fb];\n\n\n ///////////////////////////\n // Fill buffer registers //\n ///////////////////////////\n\n // Fill buffer general enable\n assign fill_entry_en[fb] = fill_alloc[fb] | fill_busy_q[fb];\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n fill_busy_q[fb] <= 1'b0;\n fill_older_q[fb] <= '0;\n fill_stale_q[fb] <= 1'b0;\n fill_cache_q[fb] <= 1'b0;\n fill_hit_q[fb] <= 1'b0;\n fill_ext_cnt_q[fb] <= '0;\n fill_ext_hold_q[fb] <= 1'b0;\n fill_rvd_cnt_q[fb] <= '0;\n fill_ram_done_q[fb] <= 1'b0;\n fill_out_cnt_q[fb] <= '0;\n end else if (fill_entry_en[fb]) begin\n fill_busy_q[fb] <= fill_busy_d[fb];\n fill_older_q[fb] <= fill_older_d[fb];\n fill_stale_q[fb] <= fill_stale_d[fb];\n fill_cache_q[fb] <= fill_cache_d[fb];\n fill_hit_q[fb] <= fill_hit_d[fb];\n fill_ext_cnt_q[fb] <= fill_ext_cnt_d[fb];\n fill_ext_hold_q[fb] <= fill_ext_hold_d[fb];\n fill_rvd_cnt_q[fb] <= fill_rvd_cnt_d[fb];\n fill_ram_done_q[fb] <= fill_ram_done_d[fb];\n fill_out_cnt_q[fb] <= fill_out_cnt_d[fb];\n end\n end\n\n ////////////////////////////////////////\n // Fill buffer address / data storage //\n ////////////////////////////////////////\n\n assign fill_addr_en[fb] = fill_alloc[fb];\n assign fill_way_en[fb] = (lookup_valid_ic1 & fill_in_ic1[fb]);\n\n always_ff @(posedge clk_i) begin\n if (fill_addr_en[fb]) begin\n fill_addr_q[fb] <= lookup_addr_ic0;\n end\n end\n\n always_ff @(posedge clk_i) begin\n if (fill_way_en[fb]) begin\n fill_way_q[fb] <= sel_way_ic1;\n end\n end\n\n // Data either comes from the cache or the bus. If there was an ECC error, we must take\n // the incoming bus data since the cache hit data is corrupted.\n assign fill_data_d[fb] = (fill_hit_ic1[fb] & ~ecc_err_ic1) ? hit_data_ic1[LineSize-1:0] :\n {LINE_BEATS{instr_rdata_i}};\n\n for (genvar b = 0; b < LINE_BEATS; b++) begin : gen_data_buf\n // Error tracking (per beat)\n // Either a PMP error on a speculative request,\n assign fill_err_d[fb][b] = (instr_pmp_err_i & fill_alloc[fb] & fill_spec_req &\n (lookup_addr_ic0[LINE_W-1:BUS_W] == b[LINE_BEATS_W-1:0])) |\n // a PMP error on a fill buffer ext req\n (instr_pmp_err_i & fill_ext_arb[fb] &\n (fill_ext_off[fb] == b[LINE_BEATS_W-1:0])) |\n // Or a data error with instr_rvalid_i\n (fill_rvd_arb[fb] & instr_err_i &\n (fill_rvd_off[fb] == b[LINE_BEATS_W-1:0])) |\n // Hold the error once recorded\n (fill_busy_q[fb] & fill_err_q[fb][b]);\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n fill_err_q[fb][b] <= '0;\n end else if (fill_entry_en[fb]) begin\n fill_err_q[fb][b] <= fill_err_d[fb][b];\n end\n end\n\n // Enable the relevant part of the data register (or all for cache hits)\n // Ignore incoming rvalid data when we already have cache hit data\n assign fill_data_en[fb][b] = fill_hit_ic1[fb] |\n (fill_rvd_arb[fb] & ~fill_hit_q[fb] &\n (fill_rvd_off[fb] == b[LINE_BEATS_W-1:0]));\n\n always_ff @(posedge clk_i) begin\n if (fill_data_en[fb][b]) begin\n fill_data_q[fb][b*BusWidth+:BusWidth] <= fill_data_d[fb][b*BusWidth+:BusWidth];\n end\n end\n\n end\n end\n\n ////////////////////////////////\n // Fill buffer one-hot muxing //\n ////////////////////////////////\n\n // External req info\n always_comb begin\n fill_ext_req_addr = '0;\n for (int i = 0; i < NUM_FB; i++) begin\n if (fill_ext_arb[i]) begin\n fill_ext_req_addr |= {fill_addr_q[i][ADDR_W-1:LINE_W], fill_ext_off[i]};\n end\n end\n end\n\n // Cache req info\n always_comb begin\n fill_ram_req_addr = '0;\n fill_ram_req_way = '0;\n fill_ram_req_data = '0;\n for (int i = 0; i < NUM_FB; i++) begin\n if (fill_ram_arb[i]) begin\n fill_ram_req_addr |= fill_addr_q[i];\n fill_ram_req_way |= fill_way_q[i];\n fill_ram_req_data |= fill_data_q[i];\n end\n end\n end\n\n // IF stage output data\n always_comb begin\n fill_out_data = '0;\n fill_out_err = '0;\n for (int i = 0; i < NUM_FB; i++) begin\n if (fill_data_reg[i]) begin\n fill_out_data |= fill_data_q[i];\n // Ignore any speculative errors accumulated on cache hits\n fill_out_err |= (fill_err_q[i] & ~{LINE_BEATS{fill_hit_q[i]}});\n end\n end\n end\n\n ///////////////////////\n // External requests //\n ///////////////////////\n\n assign instr_req = ((SpecRequest | branch_i) & lookup_grant_ic0) |\n |fill_ext_req;\n\n assign instr_addr = |fill_ext_req ? fill_ext_req_addr :\n lookup_addr_ic0[ADDR_W-1:BUS_W];\n\n assign instr_req_o = instr_req;\n assign instr_addr_o = {instr_addr[ADDR_W-1:BUS_W],{BUS_W{1'b0}}};\n\n ////////////////////////\n // Output data muxing //\n ////////////////////////\n\n // Mux between line-width data sources\n assign line_data = |fill_data_hit ? hit_data_ic1[LineSize-1:0] : fill_out_data;\n assign line_err = |fill_data_hit ? {LINE_BEATS{1'b0}} : fill_out_err;\n\n // Mux the relevant beat of line data, based on the output address\n always_comb begin\n line_data_muxed = '0;\n line_err_muxed = 1'b0;\n for (int i = 0; i < LINE_BEATS; i++) begin\n // When data has been skidded, the output address is behind by one\n if ((output_addr_q[LINE_W-1:BUS_W] + {{LINE_BEATS_W-1{1'b0}},skid_valid_q}) ==\n i[LINE_BEATS_W-1:0]) begin\n line_data_muxed |= line_data[i*32+:32];\n line_err_muxed |= line_err[i];\n end\n end\n end\n\n // Mux between incoming rdata and the muxed line data\n assign output_data = |fill_data_rvd ? instr_rdata_i : line_data_muxed;\n assign output_err = |fill_data_rvd ? instr_err_i : line_err_muxed;\n\n // Output data is valid (from any of the three possible sources). Note that fill_out_arb\n // must be used here rather than fill_out_req because data can become valid out of order\n // (e.g. cache hit data can become available ahead of an older outstanding miss).\n // Any ECC error suppresses the output that cycle.\n assign data_valid = |fill_out_arb & ~ecc_err_ic1;\n\n // Skid buffer data\n assign skid_data_d = output_data[31:16];\n\n assign skid_en = data_valid & (ready_i | skid_ready);\n\n always_ff @(posedge clk_i) begin\n if (skid_en) begin\n skid_data_q <= skid_data_d;\n skid_err_q <= output_err;\n end\n end\n\n // The data in the skid buffer is ready if it's a complete compressed instruction or if there's\n // an error (no need to wait for the second half)\n assign skid_complete_instr = skid_valid_q & ((skid_data_q[1:0] != 2'b11) | skid_err_q);\n\n // Data can be loaded into the skid buffer for an unaligned uncompressed instruction\n assign skid_ready = output_addr_q[1] & ~skid_valid_q & (~output_compressed | output_err);\n\n assign output_ready = (ready_i | skid_ready) & ~skid_complete_instr;\n\n assign output_compressed = (rdata_o[1:0] != 2'b11);\n\n assign skid_valid_d =\n // Branches invalidate the skid buffer\n branch_i ? 1'b0 :\n // Once valid, the skid buffer stays valid until a compressed instruction realigns the stream\n (skid_valid_q ? ~(ready_i & ((skid_data_q[1:0] != 2'b11) | skid_err_q)) :\n // The skid buffer becomes valid when:\n // - we branch to an unaligned uncompressed instruction\n (((output_addr_q[1] & (~output_compressed | output_err)) |\n // - a compressed instruction misaligns the stream\n (~output_addr_q[1] & output_compressed & ~output_err & ready_i)) & data_valid));\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n skid_valid_q <= 1'b0;\n end else begin\n skid_valid_q <= skid_valid_d;\n end\n end\n\n // Signal that valid data is available to the IF stage\n // Note that if the first half of an unaligned instruction reports an error, we do not need\n // to wait for the second half (and for PMP errors we might not have fetched the second half)\n // Compressed instruction completely satisfied by skid buffer\n assign output_valid = skid_complete_instr |\n // Output data available and, output stream aligned, or skid data available,\n (data_valid & (~output_addr_q[1] | skid_valid_q |\n // or this is an error or an unaligned compressed instruction\n output_err | (output_data[17:16] != 2'b11)));\n\n // Update the address on branches and every time an instruction is driven\n assign output_addr_en = branch_i | (ready_i & valid_o);\n\n // Increment the address by two every time a compressed instruction is popped\n assign addr_incr_two = output_compressed & ~err_o;\n\n assign output_addr_d = branch_i ? addr_i[31:1] :\n (output_addr_q[31:1] +\n // Increment address by 4 or 2\n {29'd0, ~addr_incr_two, addr_incr_two});\n\n always_ff @(posedge clk_i) begin\n if (output_addr_en) begin\n output_addr_q <= output_addr_d;\n end\n end\n\n // Mux the data from BusWidth to halfword\n // This muxing realigns data when instruction words are split across BUS_W e.g.\n // word 1 |----|*h1*|\n // word 0 |*h0*|----| --> |*h1*|*h0*|\n // 31 15 0 31 15 0\n always_comb begin\n output_data_lo = '0;\n for (int i = 0; i < OUTPUT_BEATS; i++) begin\n if (output_addr_q[BUS_W-1:1] == i[BUS_W-2:0]) begin\n output_data_lo |= output_data[i*16+:16];\n end\n end\n end\n\n always_comb begin\n output_data_hi = '0;\n for (int i = 0; i < OUTPUT_BEATS-1; i++) begin\n if (output_addr_q[BUS_W-1:1] == i[BUS_W-2:0]) begin\n output_data_hi |= output_data[(i+1)*16+:16];\n end\n end\n if (&output_addr_q[BUS_W-1:1]) begin\n output_data_hi |= output_data[15:0];\n end\n end\n\n assign valid_o = output_valid;\n assign rdata_o = {output_data_hi, (skid_valid_q ? skid_data_q : output_data_lo)};\n assign addr_o = {output_addr_q, 1'b0};\n assign err_o = (skid_valid_q & skid_err_q) | (~skid_complete_instr & output_err);\n // Error caused by the second half of a misaligned uncompressed instruction\n // (only relevant when err_o is set)\n assign err_plus2_o = skid_valid_q & ~skid_err_q;\n\n ///////////////////\n // Invalidations //\n ///////////////////\n\n // Invalidate on reset, or when instructed. If an invalidation request is received while a\n // previous invalidation is ongoing, it does not need to be restarted.\n assign start_inval = (~reset_inval_q | icache_inval_i) & ~inval_prog_q;\n assign inval_prog_d = start_inval | (inval_prog_q & ~inval_done);\n assign inval_done = &inval_index_q;\n assign inval_index_d = start_inval ? '0 :\n (inval_index_q + {{INDEX_W-1{1'b0}},1'b1});\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n inval_prog_q <= 1'b0;\n reset_inval_q <= 1'b0;\n end else begin\n inval_prog_q <= inval_prog_d;\n reset_inval_q <= 1'b1;\n end\n end\n\n always_ff @(posedge clk_i) begin\n if (inval_prog_d) begin\n inval_index_q <= inval_index_d;\n end\n end\n\n /////////////////\n // Busy status //\n /////////////////\n\n // Only busy (for WFI purposes) while an invalidation is in-progress, or external requests are\n // outstanding.\n assign busy_o = inval_prog_q | (|(fill_busy_q & ~fill_rvd_done));\n\n ////////////////\n // Assertions //\n ////////////////\n\n `ASSERT_INIT(size_param_legal, (LineSize > 32))\n\n // ECC primitives will need to be changed for different sizes\n `ASSERT_INIT(ecc_tag_param_legal, (TAG_SIZE <= 27))\n `ASSERT_INIT(ecc_data_param_legal, (LineSize <= 121))\n\nendmodule\n", "pr_title": "Optimize use of RAM primitive in icache", "pr_body": "The RAM primitive provides a way to specify the granularity of the write\nmask (wmask) signal, which can be used to select an appropriate\nimplementation (e.g. a SRAM with only byte selects, or no subselects at\nall).\n\n---\nEven though this change should be safe, I've seen X asserts fire on this one previously in icache UVM DV. I cannot test right now until #904 is fixed.", "fix_patch": "diff --git a/rtl/ibex_icache.sv b/rtl/ibex_icache.sv\nindex 086b27ddaf..f65725becb 100644\n--- a/rtl/ibex_icache.sv\n+++ b/rtl/ibex_icache.sv\n@@ -301,8 +301,9 @@ module ibex_icache #(\n for (genvar way = 0; way < NumWays; way++) begin : gen_rams\n // Tag RAM instantiation\n prim_ram_1p #(\n- .Width (TAG_SIZE_ECC),\n- .Depth (NUM_LINES)\n+ .Width (TAG_SIZE_ECC),\n+ .Depth (NUM_LINES),\n+ .DataBitsPerMask (TAG_SIZE_ECC)\n ) tag_bank (\n .clk_i (clk_i),\n .req_i (tag_req_ic0 & tag_banks_ic0[way]),\n@@ -314,8 +315,9 @@ module ibex_icache #(\n );\n // Data RAM instantiation\n prim_ram_1p #(\n- .Width (LINE_SIZE_ECC),\n- .Depth (NUM_LINES)\n+ .Width (LINE_SIZE_ECC),\n+ .Depth (NUM_LINES),\n+ .DataBitsPerMask (LINE_SIZE_ECC)\n ) data_bank (\n .clk_i (clk_i),\n .req_i (data_req_ic0 & data_banks_ic0[way]),\n"}
{"repo": "lowRISC/ibex", "pr_id": 813, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": true, "sufficient_for_diagnosis": false}, "reasoning": "Specification uses correct behavioral language but lacks explicit assertion that PMP error must be cleared when LSU returns to IDLE, which is the functional area modified by the patch."}, "generated_spec": "# Load-Store Unit (LSU) Specification\n\n## Overview\nThe Load-Store Unit (LSU) is responsible for executing all load and store memory operations issued by the processor core. It handles word (32-bit), halfword (16-bit), and byte (8-bit) accesses, including misaligned accesses that cross word boundaries. The LSU manages the data memory interface, performs byte-enable generation, data alignment, sign extension, and error reporting. It operates as a finite state machine that coordinates memory request/response handshaking, supports split transactions for misaligned accesses, and ensures correct ordering and completion of operations.\n\n## Interface Description\nThe LSU connects to the processor pipeline (ID/EX stage) and to an external data memory or bus system.\n\n### Signals from the Pipeline\n- Load/Store type (word, halfword, byte).\n- Write enable (indicates store vs. load).\n- Data to be written (for stores).\n- Sign extension flag (for loads, indicates signed vs. unsigned extension).\n- Request valid (indicates a new load or store operation is pending).\n- Memory address (computed by the ALU, provided as a 32‑bit value).\n\n### Signals to the Pipeline\n- Read data (aligned and sign‑extended to 32 bits).\n- Read data valid (asserted when read data is available).\n- Address increment request (asserted during misaligned accesses to request the next transaction’s address).\n- Last address (for exception handling and misaligned address generation).\n- Request done (asserted when the current operation is fully completed, i.e., the LSU has received the final response and is ready for a new request).\n- Response valid (asserted when a transaction response – load data or store acknowledgement – is available).\n- Load error / Store error (asserted when an error is detected on a load or store, respectively).\n- Busy (asserted while the LSU is processing an outstanding transaction).\n\n### Signals to the Data Memory\n- Request valid (stays high until granted).\n- Address (word‑aligned, 32 bits).\n- Write enable (high for stores, low for loads).\n- Byte enables (4‑bit mask indicating which bytes to read/write).\n- Write data (32 bits, aligned for the target byte lanes).\n- Grant input (acknowledges the request; the address and control signals may change in the next cycle).\n- Read data valid (asserted for one cycle when response is available).\n- Read data (32 bits of read data, valid when read data valid is high).\n- Error input (asserted with read data valid to indicate a bus or memory error).\n\n## Functional Description\n\n### Access Types\nThe LSU supports three access sizes:\n- **Word**: 4 bytes, natural alignment at 4‑byte boundary.\n- **Halfword**: 2 bytes, natural alignment at 2‑byte boundary.\n- **Byte**: 1 byte, any address.\n\nFor loads, the data is sign‑extended (or zero‑extended) to 32 bits according to the sign extension flag. For stores, the write data is aligned and masked appropriately.\n\n### Normal (Aligned) Accesses\nWhen an access address is naturally aligned for the given size, the LSU performs a single word‑aligned memory transaction. The byte enables are set to cover the exact bytes of the access. For example:\n- Word at offset 0: all four byte enables active.\n- Halfword at offset 0: enables for bytes 0 and 1.\n- Halfword at offset 2: enables for bytes 2 and 3.\n- Byte at any offset: enables only the corresponding byte lane.\n\nThe write data is rotated so that the least‑significant byte of the data is placed in the byte lane addressed by the lower two address bits.\n\nFor loads, the returned 32‑bit read data is shifted and sign‑extracted to produce the final value. The LSU internally captures the offset of the original access to correctly reconstruct the result.\n\n### Misaligned Accesses\nAccesses that cross a word boundary are automatically split into two separate word‑aligned transactions. A misaligned access is defined as:\n- **Word access** when the lower two address bits are not `00`.\n- **Halfword access** when the lower two address bits are `11` (address ends in `0b11`).\n\nByte accesses are never misaligned.\n\nThe LSU handles misaligned accesses in the following manner:\n1. The first transaction uses the original (misaligned) address, but the address sent to the memory is forced word‑aligned (lower two bits set to `00`). The byte enables and write data are generated to cover only the bytes that belong to the first part of the access.\n2. The LSU outputs an address increment request to the pipeline, instructing it to increment the original address by 4 for the second part. The pipeline updates the address and presents it to the LSU.\n3. The second transaction uses the incremented, word‑aligned address. The byte enables and write data are generated to cover the remaining bytes.\n4. For loads, the data from the two read responses is combined internally. The bytes from the first response are stored in a temporary register; the bytes from the second response are merged with the stored bytes to form the complete 32‑bit value, which is then sign‑extracted according to the access type.\n\nThe LSU asserts the address increment request during the entire time it is waiting for the second transaction to complete, ensuring the pipeline does not change the address prematurely.\n\n### Byte Enable Generation\nByte enables are a 4‑bit mask indicating which byte lanes in the 32‑bit word are accessed. They are generated based on:\n- Access type (word, halfword, byte).\n- Lower two bits of the original address (byte offset).\n- Whether this is the first or second part of a misaligned access.\n\nFor the first part of a misaligned word access, the byte enables cover the bytes from the offset to the end of the word (e.g., offset `01` → enables `1110`). For the second part, enables cover the bytes from the beginning of the next word up to just before the offset (e.g., offset `01` → enables `0001`). The same logic applies for halfword accesses: the first part covers bytes from offset to the end (or part of the halfword) and the second part covers the remaining byte(s) at the start of the next word.\n\n### Data Alignment\n\n#### Write Data\nFor store operations, the write data is rotated so that the least‑significant byte of the data appears on the byte lane addressed by the lower two address bits. This rotation is performed irrespective of whether the access is aligned or misaligned (the byte enables ensure only the correct bytes are written).\n\n#### Read Data (Loads)\nFor load operations, the LSU performs sign extension after reconstructing the final data. The read data is processed as follows:\n- **Word load**: The 32‑bit value is taken directly from the memory response. For misaligned word loads, the value is reconstructed from two memory responses using the temporarily stored upper bytes from the first response.\n- **Halfword load**: The relevant 16‑bit halfword is extracted from the word (aligned according to the original address offset) and then sign‑extended (or zero‑extended) to 32 bits.\n- **Byte load**: The relevant byte is extracted and sign‑extended (or zero‑extended) to 32 bits.\n\nThe sign extension flag determines whether the MSB of the extracted halfword or byte is extended (signed) or a zero is extended (unsigned).\n\n### Error Handling\nThe memory system can signal an error for any transaction via the error input, which is valid only when the read data valid signal is asserted. Additionally, a physical memory protection (PMP) error input is provided; it is considered valid only during the address phase (when a request is issued and accepted).\n\n- **Store error**: Asserted when the final response of a store transaction indicates an error (either data error or PMP error).\n- **Load error**: Asserted when the final response of a load transaction indicates an error.\n\nIf an error occurs on the first part of a misaligned access, the LSU does not cancel the second part; it still issues the second transaction and waits for its response. However, the data/response from the second part is ignored, and the error from the first part is reported as the final outcome. The address presented to the memory for the second part is still generated, but the pipeline is not required to provide a new address update if the first part already failed (though the LSU may still request the address increment – the pipeline must still respond appropriately).\n\nThe LSU stores the last transaction address for exception handling (`mtval`) and for generating the second address in misaligned accesses. The stored address is updated only when a transaction completes without error. If an error occurs, the address is not updated, thus preserving the faulting address.\n\n### Protocol Timing\nThe LSU follows a request‑grant‑response protocol with the data memory:\n\n1. **Request phase**: The LSU asserts a request, provides the address, write enable, byte enables, and write data (for stores). The request stays high until the memory asserts a grant.\n2. **Grant**: The memory may assert the grant in the same cycle as the request or any later cycle. After receiving the grant, the LSU may change the address and control signals in the next cycle for a subsequent transaction.\n3. **Response phase**: After one or more cycles following the grant, the memory asserts read data valid for exactly one cycle. At that time, the error flag and read data (if any) are valid. The LSU expects responses in the same order as the transactions were granted.\n\nThe LSU can have multiple outstanding transactions (e.g., both parts of a misaligned access). The memory system must return responses in‑order.\n\n### Finite State Machine\nThe LSU operates as a finite state machine with the following states:\n\n- **IDLE**: No transaction pending. When a new request arrives, the LSU issues the first request and moves to either a wait state for a misaligned access or directly to IDLE if the request is granted immediately for an aligned access.\n- **WAIT_GNT_MIS**: Waiting for a grant for the first part of a misaligned access.\n- **WAIT_RVALID_MIS**: Waiting for the read data valid for the first part of a misaligned access. During this state, the LSU also issues the second request (if the first part has not yet been granted) or waits for the second part’s grant/rvalid.\n- **WAIT_GNT**: Waiting for a grant for the second part of a misaligned access (or for a non‑misaligned access if the first grant was delayed).\n- **WAIT_RVALID_MIS_GNTS_DONE**: The second part of a misaligned access has already been granted, and the LSU is waiting for the first part’s read data valid. Once received, it will then wait for the second part’s response.\n\nThe state machine transitions back to IDLE when the final response is received and the transaction is complete.\n\n### Performance Monitoring\nThe LSU outputs performance counter pulses:\n- A pulse for a load operation when the request is first issued.\n- A pulse for a store operation when the request is first issued.\n\nThese pulses are independent of misaligned splits; only one pulse is generated per pipeline load or store operation.\n\n## Constraints and Assumptions\n- The address from the pipeline is a 32‑bit value. The LSU always outputs a word‑aligned address (lower two bits zero) to the memory.\n- The LSU does not handle atomic operations or cache coherency.\n- Error responses are assumed to be persistent: if an error is received, the LSU will report it and not retry.\n- The memory system is assumed to process requests in‑order and return responses in‑order.\n- The pipeline must provide a new address when the address increment request is asserted, and must not issue a new load/store request until the previous one is complete (as indicated by the request done signal).\n- The PMP error signal is valid only during an address phase; it is sampled when a grant is received or when a new request is issued (depending on the state). The LSU may use a registered version of the PMP error to avoid losing it before the corresponding response.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2018 ETH Zurich and University of Bologna, see also CREDITS.md.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n\n/**\n * Load Store Unit\n *\n * Load Store Unit, used to eliminate multiple access during processor stalls,\n * and to align bytes and halfwords.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_load_store_unit\n(\n input logic clk_i,\n input logic rst_ni,\n\n // data interface\n output logic data_req_o,\n input logic data_gnt_i,\n input logic data_rvalid_i,\n input logic data_err_i,\n input logic data_pmp_err_i,\n\n output logic [31:0] data_addr_o,\n output logic data_we_o,\n output logic [3:0] data_be_o,\n output logic [31:0] data_wdata_o,\n input logic [31:0] data_rdata_i,\n\n // signals to/from ID/EX stage\n input logic lsu_we_i, // write enable -> from ID/EX\n input logic [1:0] lsu_type_i, // data type: word, half word, byte -> from ID/EX\n input logic [31:0] lsu_wdata_i, // data to write to memory -> from ID/EX\n input logic lsu_sign_ext_i, // sign extension -> from ID/EX\n\n output logic [31:0] lsu_rdata_o, // requested data -> to ID/EX\n output logic lsu_rdata_valid_o,\n input logic lsu_req_i, // data request -> from ID/EX\n\n input logic [31:0] adder_result_ex_i, // address computed in ALU -> from ID/EX\n\n output logic addr_incr_req_o, // request address increment for\n // misaligned accesses -> to ID/EX\n output logic [31:0] addr_last_o, // address of last transaction -> to controller\n // -> mtval\n // -> AGU for misaligned accesses\n\n output logic lsu_req_done_o, // Signals that data request is complete\n // (only need to await final data\n // response) -> to ID/EX\n\n output logic lsu_resp_valid_o, // LSU has response from transaction -> to ID/EX\n\n // exception signals\n output logic load_err_o,\n output logic store_err_o,\n\n output logic load_o,\n output logic busy_o,\n\n output logic perf_load_o,\n output logic perf_store_o,\n\n // used for assertions only\n input logic illegal_insn_id_i, // illegal instruciton -> from ID/EX\n input logic instr_valid_id_i // valid instruction -> from ID/EX\n);\n\n logic [31:0] data_addr;\n logic [31:0] data_addr_w_aligned;\n logic [31:0] addr_last_q;\n\n logic addr_update;\n logic ctrl_update;\n logic rdata_update;\n logic [31:8] rdata_q;\n logic [1:0] rdata_offset_q;\n logic [1:0] data_type_q;\n logic data_sign_ext_q;\n logic data_we_q;\n\n logic [1:0] data_offset; // mux control for data to be written to memory\n\n logic [3:0] data_be;\n logic [31:0] data_wdata;\n\n logic [31:0] data_rdata_ext;\n\n logic [31:0] rdata_w_ext; // word realignment for misaligned loads\n logic [31:0] rdata_h_ext; // sign extension for half words\n logic [31:0] rdata_b_ext; // sign extension for bytes\n\n logic split_misaligned_access;\n logic handle_misaligned_q, handle_misaligned_d; // high after receiving grant for first\n // part of a misaligned access\n logic pmp_err_q, pmp_err_d;\n logic lsu_err_q, lsu_err_d;\n logic data_or_pmp_err;\n\n typedef enum logic [2:0] {\n IDLE, WAIT_GNT_MIS, WAIT_RVALID_MIS, WAIT_GNT,\n WAIT_RVALID_MIS_GNTS_DONE\n } ls_fsm_e;\n\n ls_fsm_e ls_fsm_cs, ls_fsm_ns;\n\n assign data_addr = adder_result_ex_i;\n assign data_offset = data_addr[1:0];\n\n ///////////////////\n // BE generation //\n ///////////////////\n\n always_comb begin\n unique case (lsu_type_i) // Data type 00 Word, 01 Half word, 11,10 byte\n 2'b00: begin // Writing a word\n if (!handle_misaligned_q) begin // first part of potentially misaligned transaction\n unique case (data_offset)\n 2'b00: data_be = 4'b1111;\n 2'b01: data_be = 4'b1110;\n 2'b10: data_be = 4'b1100;\n 2'b11: data_be = 4'b1000;\n default: data_be = 4'b1111;\n endcase // case (data_offset)\n end else begin // second part of misaligned transaction\n unique case (data_offset)\n 2'b00: data_be = 4'b0000; // this is not used, but included for completeness\n 2'b01: data_be = 4'b0001;\n 2'b10: data_be = 4'b0011;\n 2'b11: data_be = 4'b0111;\n default: data_be = 4'b1111;\n endcase // case (data_offset)\n end\n end\n\n 2'b01: begin // Writing a half word\n if (!handle_misaligned_q) begin // first part of potentially misaligned transaction\n unique case (data_offset)\n 2'b00: data_be = 4'b0011;\n 2'b01: data_be = 4'b0110;\n 2'b10: data_be = 4'b1100;\n 2'b11: data_be = 4'b1000;\n default: data_be = 4'b1111;\n endcase // case (data_offset)\n end else begin // second part of misaligned transaction\n data_be = 4'b0001;\n end\n end\n\n 2'b10,\n 2'b11: begin // Writing a byte\n unique case (data_offset)\n 2'b00: data_be = 4'b0001;\n 2'b01: data_be = 4'b0010;\n 2'b10: data_be = 4'b0100;\n 2'b11: data_be = 4'b1000;\n default: data_be = 4'b1111;\n endcase // case (data_offset)\n end\n\n default: data_be = 4'b1111;\n endcase // case (lsu_type_i)\n end\n\n /////////////////////\n // WData alignment //\n /////////////////////\n\n // prepare data to be written to the memory\n // we handle misaligned accesses, half word and byte accesses here\n always_comb begin\n unique case (data_offset)\n 2'b00: data_wdata = lsu_wdata_i[31:0];\n 2'b01: data_wdata = {lsu_wdata_i[23:0], lsu_wdata_i[31:24]};\n 2'b10: data_wdata = {lsu_wdata_i[15:0], lsu_wdata_i[31:16]};\n 2'b11: data_wdata = {lsu_wdata_i[ 7:0], lsu_wdata_i[31: 8]};\n default: data_wdata = lsu_wdata_i[31:0];\n endcase // case (data_offset)\n end\n\n /////////////////////\n // RData alignment //\n /////////////////////\n\n // register for unaligned rdata\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rdata_q <= '0;\n end else if (rdata_update) begin\n rdata_q <= data_rdata_i[31:8];\n end\n end\n\n // registers for transaction control\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rdata_offset_q <= 2'h0;\n data_type_q <= 2'h0;\n data_sign_ext_q <= 1'b0;\n data_we_q <= 1'b0;\n end else if (ctrl_update) begin\n rdata_offset_q <= data_offset;\n data_type_q <= lsu_type_i;\n data_sign_ext_q <= lsu_sign_ext_i;\n data_we_q <= lsu_we_i;\n end\n end\n\n // Store last address for mtval + AGU for misaligned transactions.\n // Do not update in case of errors, mtval needs the (first) failing address\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n addr_last_q <= '0;\n end else if (addr_update) begin\n addr_last_q <= data_addr;\n end\n end\n\n // take care of misaligned words\n always_comb begin\n unique case (rdata_offset_q)\n 2'b00: rdata_w_ext = data_rdata_i[31:0];\n 2'b01: rdata_w_ext = {data_rdata_i[ 7:0], rdata_q[31:8]};\n 2'b10: rdata_w_ext = {data_rdata_i[15:0], rdata_q[31:16]};\n 2'b11: rdata_w_ext = {data_rdata_i[23:0], rdata_q[31:24]};\n default: rdata_w_ext = data_rdata_i[31:0];\n endcase\n end\n\n ////////////////////\n // Sign extension //\n ////////////////////\n\n // sign extension for half words\n always_comb begin\n unique case (rdata_offset_q)\n 2'b00: begin\n if (!data_sign_ext_q) begin\n rdata_h_ext = {16'h0000, data_rdata_i[15:0]};\n end else begin\n rdata_h_ext = {{16{data_rdata_i[15]}}, data_rdata_i[15:0]};\n end\n end\n\n 2'b01: begin\n if (!data_sign_ext_q) begin\n rdata_h_ext = {16'h0000, data_rdata_i[23:8]};\n end else begin\n rdata_h_ext = {{16{data_rdata_i[23]}}, data_rdata_i[23:8]};\n end\n end\n\n 2'b10: begin\n if (!data_sign_ext_q) begin\n rdata_h_ext = {16'h0000, data_rdata_i[31:16]};\n end else begin\n rdata_h_ext = {{16{data_rdata_i[31]}}, data_rdata_i[31:16]};\n end\n end\n\n 2'b11: begin\n if (!data_sign_ext_q) begin\n rdata_h_ext = {16'h0000, data_rdata_i[7:0], rdata_q[31:24]};\n end else begin\n rdata_h_ext = {{16{data_rdata_i[7]}}, data_rdata_i[7:0], rdata_q[31:24]};\n end\n end\n\n default: rdata_h_ext = {16'h0000, data_rdata_i[15:0]};\n endcase // case (rdata_offset_q)\n end\n\n // sign extension for bytes\n always_comb begin\n unique case (rdata_offset_q)\n 2'b00: begin\n if (!data_sign_ext_q) begin\n rdata_b_ext = {24'h00_0000, data_rdata_i[7:0]};\n end else begin\n rdata_b_ext = {{24{data_rdata_i[7]}}, data_rdata_i[7:0]};\n end\n end\n\n 2'b01: begin\n if (!data_sign_ext_q) begin\n rdata_b_ext = {24'h00_0000, data_rdata_i[15:8]};\n end else begin\n rdata_b_ext = {{24{data_rdata_i[15]}}, data_rdata_i[15:8]};\n end\n end\n\n 2'b10: begin\n if (!data_sign_ext_q) begin\n rdata_b_ext = {24'h00_0000, data_rdata_i[23:16]};\n end else begin\n rdata_b_ext = {{24{data_rdata_i[23]}}, data_rdata_i[23:16]};\n end\n end\n\n 2'b11: begin\n if (!data_sign_ext_q) begin\n rdata_b_ext = {24'h00_0000, data_rdata_i[31:24]};\n end else begin\n rdata_b_ext = {{24{data_rdata_i[31]}}, data_rdata_i[31:24]};\n end\n end\n\n default: rdata_b_ext = {24'h00_0000, data_rdata_i[7:0]};\n endcase // case (rdata_offset_q)\n end\n\n // select word, half word or byte sign extended version\n always_comb begin\n unique case (data_type_q)\n 2'b00: data_rdata_ext = rdata_w_ext;\n 2'b01: data_rdata_ext = rdata_h_ext;\n 2'b10,2'b11: data_rdata_ext = rdata_b_ext;\n default: data_rdata_ext = rdata_w_ext;\n endcase // case (data_type_q)\n end\n\n /////////////\n // LSU FSM //\n /////////////\n\n // check for misaligned accesses that need to be split into two word-aligned accesses\n assign split_misaligned_access =\n ((lsu_type_i == 2'b00) && (data_offset != 2'b00)) || // misaligned word access\n ((lsu_type_i == 2'b01) && (data_offset == 2'b11)); // misaligned half-word access\n\n // FSM\n always_comb begin\n ls_fsm_ns = ls_fsm_cs;\n\n data_req_o = 1'b0;\n addr_incr_req_o = 1'b0;\n handle_misaligned_d = handle_misaligned_q;\n pmp_err_d = pmp_err_q;\n lsu_err_d = lsu_err_q;\n\n addr_update = 1'b0;\n ctrl_update = 1'b0;\n rdata_update = 1'b0;\n\n perf_load_o = 1'b0;\n perf_store_o = 1'b0;\n\n unique case (ls_fsm_cs)\n\n IDLE: begin\n pmp_err_d = 1'b0;\n if (lsu_req_i) begin\n data_req_o = 1'b1;\n pmp_err_d = data_pmp_err_i;\n lsu_err_d = 1'b0;\n perf_load_o = ~lsu_we_i;\n perf_store_o = lsu_we_i;\n\n if (data_gnt_i) begin\n ctrl_update = 1'b1;\n addr_update = 1'b1;\n handle_misaligned_d = split_misaligned_access;\n ls_fsm_ns = split_misaligned_access ? WAIT_RVALID_MIS : IDLE;\n end else begin\n ls_fsm_ns = split_misaligned_access ? WAIT_GNT_MIS : WAIT_GNT;\n end\n end\n end\n\n WAIT_GNT_MIS: begin\n data_req_o = 1'b1;\n // data_pmp_err_i is valid during the address phase of a request. An error will block the\n // external request and so a data_gnt_i might never be signalled. The registered version\n // pmp_err_q is only updated for new address phases and so can be used in WAIT_GNT* and\n // WAIT_RVALID* states\n if (data_gnt_i || pmp_err_q) begin\n addr_update = 1'b1;\n ctrl_update = 1'b1;\n handle_misaligned_d = 1'b1;\n ls_fsm_ns = WAIT_RVALID_MIS;\n end\n end\n\n WAIT_RVALID_MIS: begin\n // push out second request\n data_req_o = 1'b1;\n // tell ID/EX stage to update the address\n addr_incr_req_o = 1'b1;\n\n // first part rvalid is received, or gets a PMP error\n if (data_rvalid_i || pmp_err_q) begin\n // Update the PMP error for the second part\n pmp_err_d = data_pmp_err_i;\n // Record the error status of the first part\n lsu_err_d = data_err_i | pmp_err_q;\n // Capture the first rdata for loads\n rdata_update = ~data_we_q;\n // If already granted, wait for second rvalid\n ls_fsm_ns = data_gnt_i ? IDLE : WAIT_GNT;\n // Update the address for the second part, if no error\n addr_update = data_gnt_i & ~(data_err_i | pmp_err_q);\n // clear handle_misaligned if second request is granted\n handle_misaligned_d = ~data_gnt_i;\n end else begin\n // first part rvalid is NOT received\n if (data_gnt_i) begin\n // second grant is received\n ls_fsm_ns = WAIT_RVALID_MIS_GNTS_DONE;\n handle_misaligned_d = 1'b0;\n end\n end\n end\n\n WAIT_GNT: begin\n // tell ID/EX stage to update the address\n addr_incr_req_o = handle_misaligned_q;\n data_req_o = 1'b1;\n if (data_gnt_i || pmp_err_q) begin\n ctrl_update = 1'b1;\n // Update the address, unless there was an error\n addr_update = ~lsu_err_q;\n ls_fsm_ns = IDLE;\n handle_misaligned_d = 1'b0;\n end\n end\n\n WAIT_RVALID_MIS_GNTS_DONE: begin\n // tell ID/EX stage to update the address (to make sure the\n // second address can be captured correctly for mtval and PMP checking)\n addr_incr_req_o = 1'b1;\n // Wait for the first rvalid, second request is already granted\n if (data_rvalid_i) begin\n // Update the pmp error for the second part\n pmp_err_d = data_pmp_err_i;\n // The first part cannot see a PMP error in this state\n lsu_err_d = data_err_i;\n // Now we can update the address for the second part if no error\n addr_update = ~data_err_i;\n // Capture the first rdata for loads\n rdata_update = ~data_we_q;\n // Wait for second rvalid\n ls_fsm_ns = IDLE;\n end\n end\n\n default: begin\n ls_fsm_ns = IDLE;\n end\n endcase\n end\n\n assign lsu_req_done_o = (lsu_req_i | (ls_fsm_cs != IDLE)) & (ls_fsm_ns == IDLE);\n\n // registers for FSM\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n ls_fsm_cs <= IDLE;\n handle_misaligned_q <= '0;\n pmp_err_q <= '0;\n lsu_err_q <= '0;\n end else begin\n ls_fsm_cs <= ls_fsm_ns;\n handle_misaligned_q <= handle_misaligned_d;\n pmp_err_q <= pmp_err_d;\n lsu_err_q <= lsu_err_d;\n end\n end\n\n /////////////\n // Outputs //\n /////////////\n\n assign data_or_pmp_err = lsu_err_q | data_err_i | pmp_err_q;\n assign lsu_resp_valid_o = (data_rvalid_i | pmp_err_q) & (ls_fsm_cs == IDLE);\n assign lsu_rdata_valid_o = lsu_resp_valid_o & ~data_we_q;\n\n // output to register file\n assign lsu_rdata_o = data_rdata_ext;\n\n // output data address must be word aligned\n assign data_addr_w_aligned = {data_addr[31:2], 2'b00};\n\n // output to data interface\n assign data_addr_o = data_addr_w_aligned;\n assign data_wdata_o = data_wdata;\n assign data_we_o = lsu_we_i;\n assign data_be_o = data_be;\n\n // output to ID stage: mtval + AGU for misaligned transactions\n assign addr_last_o = addr_last_q;\n\n // Signal a load or store error depending on the transaction type outstanding\n assign load_err_o = data_or_pmp_err & ~data_we_q & lsu_resp_valid_o;\n assign store_err_o = data_or_pmp_err & data_we_q & lsu_resp_valid_o;\n\n assign busy_o = (ls_fsm_cs != IDLE);\n assign load_o = ~data_we_q;\n\n ////////////////\n // Assertions //\n ////////////////\n\n logic unused_instr_valid_id;\n logic unused_illegal_insn_id;\n\n // Inputs only used for assertions\n assign unused_instr_valid_id = instr_valid_id_i;\n assign unused_illegal_insn_id = illegal_insn_id_i;\n\n // Selectors must be known/valid.\n `ASSERT(IbexDataTypeKnown, (instr_valid_id_i & ~illegal_insn_id_i) |-> !$isunknown(lsu_type_i))\n `ASSERT(IbexDataOffsetKnown, (instr_valid_id_i & ~illegal_insn_id_i) |-> !$isunknown(data_offset))\n `ASSERT_KNOWN(IbexRDataOffsetQKnown, rdata_offset_q)\n `ASSERT_KNOWN(IbexDataTypeQKnown, data_type_q)\n `ASSERT(IbexLsuStateValid, ls_fsm_cs inside {\n IDLE, WAIT_GNT_MIS, WAIT_RVALID_MIS, WAIT_GNT,\n WAIT_RVALID_MIS_GNTS_DONE})\n\n // Errors must only be sent together with rvalid.\n `ASSERT(IbexDataErrWithoutRvalid, data_err_i |-> data_rvalid_i)\n\n // Address must not contain X when request is sent.\n `ASSERT(IbexDataAddrUnknown, data_req_o |-> !$isunknown(data_addr_o))\n\n // Address must be word aligned when request is sent.\n `ASSERT(IbexDataAddrUnaligned, data_req_o |-> (data_addr_o[1:0] == 2'b00))\n\nendmodule\n", "pr_title": "[rtl/lsu] Fix bug in pmp error clearing", "pr_body": "- pmp_err_q needs to clear once the LSU state machine returns to idle,\r\n otherwise it will remain set indefinely.\r\n- Relates to #808\r\n\r\nSigned-off-by: Tom Roberts <tomroberts@lowrisc.org>", "fix_patch": "diff --git a/rtl/ibex_load_store_unit.sv b/rtl/ibex_load_store_unit.sv\nindex 689297b8f0..ec69a3a033 100644\n--- a/rtl/ibex_load_store_unit.sv\n+++ b/rtl/ibex_load_store_unit.sv\n@@ -352,6 +352,7 @@ module ibex_load_store_unit\n unique case (ls_fsm_cs)\n \n IDLE: begin\n+ pmp_err_d = 1'b0;\n if (lsu_req_i) begin\n data_req_o = 1'b1;\n pmp_err_d = data_pmp_err_i;\n"}
{"repo": "lowRISC/ibex", "pr_id": 693, "review_result": {"passed": false, "checks": {"describes_correct_behavior": false, "no_patch_leakage": true, "sufficient_for_diagnosis": true}, "reasoning": "The specification does not use must/shall/should to describe correct behavior, but it accurately covers the reset behavior modified by the patch and avoids any patch-specific identifiers."}, "generated_spec": "# Behavioral Design Specification: `ibex_counters`\n\n## Overview\n\nThe `ibex_counters` module implements a bank of programmable up-counters used for performance monitoring in the Ibex RISC‑V processor. Each counter is a 64‑bit accumulator that can be incremented by one per clock cycle, loaded with a 32‑bit value (into either the lower or upper half), or left unchanged. The number of active counters, their bit width, and the maximum number of counters are all parametrizable at synthesis time. The module provides a read‑only view of all counter values as a 64‑bit vector per counter.\n\n## Behavior\n\n### Counter Array\n\n- The module maintains up to `MaxNumCounters` independent 64‑bit counters. However, only the first `NumCounters` counters are physically implemented; all other counter outputs are fixed to zero.\n- Each implemented counter has a configurable width `CounterWidth` (1 to 64 bits). The counter behaves as if it were an unsigned integer of that width. Any overflow beyond the configured width is discarded.\n- The value of each counter is presented on a dedicated 64‑bit output port. For counters with `CounterWidth < 64`, the upper (most significant) bits above the configured width are always zero.\n\n### Counter Update\n\nEvery cycle, each active counter updates its value based on three control signals:\n\n1. **Increment** – When asserted, the counter is incremented by one. Increment is independent of any write operation and only takes effect when no write is performed during the same cycle (see priority below).\n2. **Write** – When asserted, the counter is loaded with an externally supplied 32‑bit value. The write operation can target either:\n - the lower 32 bits of the counter, or\n - the upper 32 bits of the counter.\n \n The selection between lower‑half and upper‑half write is made by a dedicated per‑counter control signal. When writing the upper half, the lower half retains its current value; when writing the lower half, the upper half retains its current value.\n3. **No operation** – If neither increment nor write is asserted, the counter holds its current value.\n\n**Priority**: If a write is asserted for a counter in the same cycle as an increment, the write takes precedence. The increment is ignored for that counter during that cycle.\n\n### Reset\n\n- On reset, every implemented counter is cleared to zero.\n- The reset polarity is active low (`rst_ni`). The reset itself is either asynchronous or synchronous with respect to the clock, depending on the synthesis target (see FPGA considerations).\n\n### Outputs\n\n- All counter values are continuously available on a 64‑bit output bus. The outputs reflect the state of the counters after the most recent clock edge.\n- Unused counter positions (i.e., indices ≥ `NumCounters`) output constant zero.\n\n## Configuration Parameters\n\n| Parameter | Description | Default |\n|-----------------|-----------------------------------------------------------------------------|---------|\n| `MaxNumCounters`| Maximum number of counter slots (the size of the internal array and output bus). | 29 |\n| `NumCounters` | Number of counters that are actually instantiated. Must be ≤ `MaxNumCounters`. | 0 |\n| `CounterWidth` | Bit width of each implemented counter (1 to 64). Overflow bits are truncated. | 32 |\n\n- Setting `NumCounters = 0` disables all counters; all outputs are zero.\n- The performance counters in Ibex (see `doc/performance_counters.rst`) map directly to the first 29 counter slots: `mcycle` and `minstret` occupy slots 0 and 2, while `mhpmcounter3` through `mhpmcounter31` occupy slots 3–31. However, this module is a generic counter bank and does not enforce any specific event mapping or CSR interface.\n\n## FPGA Considerations\n\n- For Xilinx FPGA targets, the module may optionally infer DSP slices (DSP48E1 or similar) to implement the counter logic. This inference is enabled by defining the preprocessor macro `FPGA_XILINX` before synthesis.\n- When DSP inference is active, the counter width is limited to 48 bits for efficient DSP usage. Counters of width 32 or 48 bits can be implemented using a single DSP slice, reducing logic and flip‑flop utilization.\n- The reset behavior changes when DSP slices are used: the counter register becomes synchronous-reset only (i.e., reset is sampled on the rising edge of the clock). Without DSP inference, the counter register uses an asynchronous reset (sensitive to both clock and reset falling edge).\n\n## Functional Summary\n\n| Condition | Counter Behavior |\n|---------------------------------------------------|---------------------------------------------------------|\n| Reset active (low) | Counter becomes zero |\n| Write asserted (any half) | Counter loaded with supplied 32‑bit value at selected half; other half unchanged |\n| Increment asserted, no write | Counter increments by 1 |\n| Neither increment nor write asserted | Counter holds its current value |\n| Write and increment simultaneously asserted | Write takes priority; increment is ignored |\n| Counter index ≥ `NumCounters` | Output is permanently zero |\n| Counter width < 64 | Upper bits (above `CounterWidth-1`) are forced to zero |\n\n## Signal Interface (Behavioral Description)\n\n- **Clock**: Rising‑edge clock drives all counter updates.\n- **Reset**: Active‑low reset clears all counters.\n- **Increment enables**: One bit per counter slot. When high, the corresponding counter is incremented (unless a write occurs).\n- **Write enables**: Two sets of one‑bit enables per counter slot:\n - Lower‑half write enable – when high, the 32‑bit input value is written to bits [31:0] of the counter.\n - Upper‑half write enable – when high, the 32‑bit input value is written to bits [63:32] of the counter.\n- **Write data**: A single 32‑bit value driven to all counter slots. Each counter uses its own write‑enable signals to determine whether to capture this value.\n- **Counter outputs**: A 64‑bit vector per counter slot, representing the current counter value (or zero for unused slots).\n\n> Note: While the RTL uses specific port names, the behavior described here is independent of those names and should be considered the functional contract of the module.", "fixed_rtl_code": "module ibex_counters #(\n parameter int MaxNumCounters = 29,\n parameter int NumCounters = 0,\n parameter int CounterWidth = 32\n) (\n input clk_i,\n input rst_ni,\n\n input logic [MaxNumCounters-1:0] counter_inc_i,\n input logic [MaxNumCounters-1:0] counterh_we_i,\n input logic [MaxNumCounters-1:0] counter_we_i,\n input logic [31:0] counter_val_i,\n output logic [63:0] counter_val_o [MaxNumCounters]\n);\n logic [63:0] counter [MaxNumCounters];\n\n assign counter_val_o = counter;\n\n for (genvar i = 0; i < MaxNumCounters; i++) begin : g_counter\n // Only elaborate flops that are needed from the given CounterWidth and NumCounters.\n if (i < NumCounters) begin : g_counter_exists\n\n logic [63:0] counter_upd;\n logic [63:0] counter_load;\n logic we;\n logic [CounterWidth-1:0] counter_d;\n\n // Update\n always_comb begin\n\n // Write\n we = counter_we_i[i] | counterh_we_i[i];\n counter_load[63:32] = counter[i][63:32];\n counter_load[31:0] = counter_val_i;\n if (counterh_we_i[i]) begin\n counter_load[63:32] = counter_val_i;\n counter_load[31:0] = counter[i][31:0];\n end\n\n // Increment\n counter_upd = counter[i] + 64'h1;\n\n // Next value logic\n if (we) begin\n counter_d = counter_load[CounterWidth-1:0];\n end else if (counter_inc_i[i])begin\n counter_d = counter_upd[CounterWidth-1:0];\n end else begin\n counter_d = counter[i][CounterWidth-1:0];\n end\n end\n\n`ifdef FPGA_XILINX\n // Set DSP pragma for supported xilinx FPGAs\n localparam dsp_pragma = CounterWidth < 49 ? \"yes\" : \"no\";\n (* use_dsp = dsp_pragma *) logic [CounterWidth-1:0] counter_q;\n\n // DSP output register requires synchronous reset.\n `define COUNTER_FLOP_RST posedge clk_i\n`else\n logic [CounterWidth-1:0] counter_q;\n\n `define COUNTER_FLOP_RST posedge clk_i or negedge rst_ni\n`endif\n\n // Counter flop\n always @(`COUNTER_FLOP_RST) begin\n if (!rst_ni) begin\n counter_q <= '0;\n end else begin\n counter_q <= counter_d;\n end\n end\n\n if (CounterWidth < 64) begin : g_counter_narrow\n assign counter[i][CounterWidth-1:0] = counter_q;\n assign counter[i][63:CounterWidth] = '0;\n end else begin : g_counter_full\n assign counter[i] = counter_q;\n end\n end else begin : g_no_counter\n assign counter[i] = '0;\n end\n end\n\nendmodule\n\n// Keep helper defines file-local.\n`undef COUNTER_FLOP_RST\n", "pr_title": "Use a syntax compatible with Verible", "pr_body": "Verible doesn't do real pre-processing currently, and fails to parse\ncode if define sections span across headers of blocks, as we did.\n\nUse another syntax instead for the one case where we did that to work\naround this limitation. The code isn't less readable as result, making\nthis an acceptable trade-off.\n\nWorks around https://github.com/google/verible/issues/228", "fix_patch": "diff --git a/rtl/ibex_counters.sv b/rtl/ibex_counters.sv\nindex 9a28b9a98a..2d9a4ef43d 100644\n--- a/rtl/ibex_counters.sv\n+++ b/rtl/ibex_counters.sv\n@@ -54,17 +54,17 @@ module ibex_counters #(\n // Set DSP pragma for supported xilinx FPGAs\n localparam dsp_pragma = CounterWidth < 49 ? \"yes\" : \"no\";\n (* use_dsp = dsp_pragma *) logic [CounterWidth-1:0] counter_q;\n+\n+ // DSP output register requires synchronous reset.\n+ `define COUNTER_FLOP_RST posedge clk_i\n `else\n logic [CounterWidth-1:0] counter_q;\n+\n+ `define COUNTER_FLOP_RST posedge clk_i or negedge rst_ni\n `endif\n \n // Counter flop\n-`ifdef FPGA_XILINX\n- // DSP output register requires synchronous reset.\n- always @(posedge clk_i) begin\n-`else\n- always @(posedge clk_i or negedge rst_ni) begin\n-`endif\n+ always @(`COUNTER_FLOP_RST) begin\n if (!rst_ni) begin\n counter_q <= '0;\n end else begin\n@@ -84,3 +84,6 @@ module ibex_counters #(\n end\n \n endmodule\n+\n+// Keep helper defines file-local.\n+`undef COUNTER_FLOP_RST\n"}
{"repo": "lowRISC/ibex", "pr_id": 272, "review_result": {"passed": false, "checks": {"describes_correct_behavior": false, "no_patch_leakage": true, "sufficient_for_diagnosis": false}, "reasoning": "The specification fails to assert that DRET outside debug mode causes an illegal instruction exception, which is the core fix; thus it does not fully describe correct behavior and is insufficient for diagnosing the patch."}, "generated_spec": "# Ibex Controller Behavioral Specification\n\n## Overview\n\nThe Ibex controller is the central FSM that governs the flow of instructions through the Ibex RISC-V core pipeline. It orchestrates the fetch, decode, exception handling, interrupt processing, debug entry, and sleep/wake transitions. The controller reacts to the processor state and external inputs (interrupts, debug requests, load‑store unit errors, etc.) to adjust the pipeline and the instruction fetch address.\n\nThe controller must:\n\n- Manage the core’s reset and boot sequence.\n- Direct the fetch unit (prefetcher) to request instructions from the instruction memory.\n- Coordinate start/stop of instruction decoding based on stalls, exceptions, interrupts, and debug events.\n- Generate control signals to save/restore architectural state (CSRs) on trap handling and return from traps.\n- Generate signals to invalidate pipeline registers when necessary.\n- Provide performance monitoring outputs for taken branches and jumps.\n\n## States and Basic Operation\n\nThe controller implements a finite state machine with the following logical phases:\n\n- **Reset / Boot**\n- **Decode (normal execution)**\n- **First Fetch (after reset or wake)**\n- **Flush (on exceptions, special instructions, or CSR pipeline flushes)**\n- **Interrupt Taken**\n- **Debug Taken (from IF or ID)**\n- **Wait for Sleep / Sleep**\n\nThe controller must transition between these phases according to the rules below.\n\n### Reset and Boot\n\nUpon assertion of the core’s reset signal, the controller must:\n\n- Disable instruction fetch requests.\n- Cause the fetch address to be set to the boot address.\n- Wait for the `fetch_enable` input to be asserted.\n\nWhen `fetch_enable` is asserted, the controller must ensure that the first instruction request is made to the boot address, and then transition to fetching and decoding instructions.\n\n### Normal Instruction Execution – Decode Phase\n\nIn the decode phase, the controller must direct the fetch unit to continue requesting instructions. It must monitor the `instruction_valid` signal from the IF‑ID pipeline register.\n\nWhile an instruction is valid in the ID stage, the controller must consider:\n\n- **Branch or jump signals**: If the instruction is a taken branch or jump, the controller must immediately cause the fetch address to be updated to the branch/jump target (via the `pc_set` and `pc_mux` signals). It must also assert performance counter outputs for the corresponding event.\n\n- **Special instructions and exceptions**: If the instruction is an `ECALL`, `EBREAK`, `MRET`, `DRET`, `WFI`, causes an illegal instruction exception, triggers a pipeline flush through a CSR write, or any instruction fetch error, the controller must transition to the flush phase (see below).\n\n- **Stall conditions**: If the instruction requires multiple cycles (e.g., load/store, multiply/divide) the controller must stall the IF stage until the instruction completes. During this stall, debug and interrupt requests may be held pending but not serviced until the instruction finishes.\n\n- **Debug single-stepping**: When single‑step mode is active (outside debug mode), the controller must halt the IF stage after the current instruction completes and then enter debug mode (unless an exception or special instruction prevents immediate entry).\n\n- **Debug requests and interrupts**: If a debug request or an interrupt (maskable or NMI) is pending and the pipeline is not stalled, the controller must halt the IF/ID stages and transition to the appropriate handling state (debug or interrupt taken) as soon as the current instruction finishes.\n\n> **Note on priority**: While instructions are being decoded, the controller must give the highest priority to executing the current instruction (including its side effects, such as exceptions it might cause). After the instruction is complete, it may service debug requests (higher priority than interrupts) or interrupts.\n\n### First Fetch Phase\n\nImmediately after reset and before the first instruction is fetched, the controller must enter a special “first fetch” phase. During this phase it must:\n\n- Indicate that the core is in the first fetch state.\n- Wait until the IF‑ID stage signals it is ready to accept a new instruction.\n- Upon ready, transition to normal decode.\n\nInterrupts and debug requests must still be serviced during this phase (i.e., if a request is pending, the controller may skip the first fetch and directly enter the interrupt/debug handling state).\n\n### Flush Phase\n\nThe flush phase is entered when an exception, a special instruction (`MRET`, `DRET`, `WFI`), or a CSR‑related pipeline flush is recognized during decode.\n\nDuring the flush phase, the controller must:\n\n- Halt both the IF and ID stages (prevent new instructions from entering the pipeline).\n- For true **exceptions** (including instruction fetch errors, illegal instructions, `ECALL`, `EBREAK`, load/store errors) the controller must:\n - Set the fetch address to the appropriate exception vector (based on whether the core is in debug mode).\n - Save the program counter (from the ID stage) into the `mepc` CSR.\n - Set the exception cause (`mcause`) according to the exception type.\n - Optionally write exception‑specific information to `mtval` (e.g., faulting address for load/store errors, faulting instruction for illegal instructions).\n - For `EBREAK` occurring in debug mode, the controller must not save state again; instead, it must transition to the debug‑taken (ID) phase.\n- For **MRET**: restore `mstatus.MIE` from `mstatus.MPIE`, exit NMI mode if active, and set the fetch address to the value in `mepc`.\n- For **DRET**: exit debug mode and set the fetch address to the value in `dpc`.\n- For **WFI**: transition to the sleep state (see below).\n- For **CSR pipeline flushes** that occur while an interrupt is pending and enabled, the controller may skip the normal flush and instead go directly to interrupt‑taken state.\n- If **debug single‑stepping** is active (outside debug mode), the exception state must be saved in the CSR registers but the fetch address must **not** be updated; instead, the controller must go to debug‑taken (IF) state.\n\n### Interrupt Handling\n\nInterrupts are taken only if:\n\n- The core is **not** in debug mode.\n- The interrupt is pending (for maskable interrupts, the global interrupt enable `MIE` in `mstatus` must be asserted, except for NMI which is always enabled independent of `MIE`).\n- The current instruction has completed (flush phase not needed; if in decode while stalled, the interrupt is delayed until the stall ends).\n\nWhen an interrupt is taken, the controller must:\n\n- Override the fetch address to the interrupt vector (base address from `mtvec` plus 4× interrupt ID).\n- Save the program counter (from the IF stage by default) into `mepc`.\n- Save the interrupt cause (`mcause`) with interrupt bit set.\n- For NMI, set the NMI‑mode flag (so that subsequent NMIs are not nested).\n- After saving state, the controller returns to the decode phase to begin executing the interrupt handler.\n\nInterrupt priority (highest priority first):\n\n1. Non‑maskable interrupt (NMI, ID=31)\n2. Fast interrupts (IDs 30–16)\n3. External interrupt (ID=11)\n4. Software interrupt (ID=3)\n5. Timer interrupt (ID=7)\n\n### Debug Mode\n\nThe core enters debug mode under three conditions:\n\n1. **Debug request** (`debug_req` asserted while not already in debug mode).\n2. **Single‑step** (when the instruction just retired with single‑step enabled).\n3. **EBREAK instruction** when the `ebreakm` parameter is set (or when already in debug mode).\n\nWhile in debug mode:\n\n- All interrupts (including NMI) are ignored.\n- Single‑step behavior is suppressed.\n- Exceptions (other than EBREAK) are handled normally but use the debug exception address (`DmExceptionAddr`) instead of the normal exception vector.\n\n**Entering debug mode from IF (debug request, single‑step):**\n\n- The controller must save the program counter from the IF stage into `dpc`.\n- Set the fetch address to the debug halt address (`DmHaltAddr`).\n- Set the debug cause (`dcsr.cause`) to “halt request” (for `debug_req`) or “single step” (for single‑step).\n- Enter debug mode.\n\n**Entering debug mode from ID (EBREAK handling):**\n\n- For an EBREAK that triggers debug entry (either already in debug mode or with `ebreakm` set), the controller must:\n - If not already in debug mode and `ebreakm` is set: save the program counter from the ID stage into `dpc`, save the debug cause as “EBREAK”, and set the fetch address to the debug halt address.\n - If already in debug mode: do **not** update `dpc` or `dcsr`; simply redirect to the debug halt address.\n- In both cases enter debug mode.\n\n**Exiting debug mode:** The `DRET` instruction must exit debug mode and set the fetch address to the value in `dpc`.\n\n### Sleep State\n\nWhen a `WFI` instruction is executed, the controller must:\n\n- Suspend instruction fetch.\n- Halt both IF and ID stages.\n- Indicate that the core is not busy (e.g., for power management).\n- Wait in the sleep state until any of the following occurs:\n - An interrupt (maskable or NMI) or a debug request is asserted.\n - The core was already in debug mode or single‑step mode (the controller immediately wakes up; `WFI` is treated as a NOP).\n- Upon wake, transition to the first fetch phase to resume instruction execution.\n\n### Stall Control\n\nThe controller must aggregate stall signals from multiple sources:\n\n- Load‑store unit (LSU)\n- Multiplier/divider unit\n- Branch execution unit\n- Jump execution unit\n\nIf any stall source is asserted, the controller must prevent the IF‑ID pipeline register from accepting a new instruction. The ID stage must continue executing the current instruction until the stall is deasserted. The controller must also signal the IF stage that the ID stage is not ready for new instructions.\n\nDuring a stall, the controller must maintain the ability to handle exceptions or debug/interrupt requests only **after** the stall ends. It must not let new instructions advance into the ID stage while the stall is active.\n\n### Pipeline Flush and Invalidations\n\nThe controller must generate signals to:\n\n- Clear the IF‑ID pipeline register when the current instruction is ready to be retired (i.e., when not stalled, or when an exception/special instruction forces a flush).\n- Kill the IF‑ID register on certain conditions (e.g., when a multicycle instruction causes an exception, or when the controller itself decides to flush).\n\n### Performance Monitor Outputs\n\nThe controller must produce two performance counter events:\n\n- **Taken branch**: When a branch taken signal is asserted.\n- **Jump**: When a jump taken signal is asserted (including `JAL`, `JALR`, etc.).\n\nThese outputs must be valid for exactly one cycle per event.\n\n## Behavior Under Reset\n\nWhen reset is active (low):\n\n- All internal state (FSM, debug mode flag, NMI mode flag, LSU error flags) must be cleared.\n- The core must be in the reset / boot phase, waiting for `fetch_enable`.\n- No instruction requests shall be made.\n\n## Timing / Protocol Requirements\n\n- The controller must produce all control signals (e.g., fetch address mux, PC set, CSR save/restore, pipeline stalls) combinatorially from the current state and inputs, meeting the pipeline timing closure requirements.\n- The instruction fetch address and related controls must be updated as soon as a branch, jump, exception, or interrupt is recognized, so that the prefetcher can start fetching from the new address in the next cycle.\n- The controller must not introduce any bubble in the pipeline beyond those required by stalls or hazards; it shall keep the IF stage active whenever possible.\n\n## Summary of Key External Interactions\n\n- **Instruction fetch**: The controller commands the prefetcher to request instructions, sets the fetch target address, and indicates when the ID stage is ready.\n- **Decoder**: The controller uses decoder outputs (type of instruction, illegal/ecall/ebrk etc.) to decide actions.\n- **CSR logic**: The controller initiates saving of `mepc`, `mcause`, `mtval`, debug registers, restores on `MRET`/`DRET`, and updates NMI and debug mode flags.\n- **Load‑store unit**: The controller samples load/store error signals to generate exceptions and records the faulting address.\n- **Interrupt controller**: The controller evaluates interrupt pending signals and the global enable to decide whether to take an interrupt.\n- **Debug module**: The controller responds to debug requests and implements single‑step behavior according to the RISC‑V Debug Specification v0.13.\n\nThe controller must adhere to all the priorities and rules described in the sections above to guarantee correct RISC‑V trap handling and debug support.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2018 ETH Zurich and University of Bologna, see also CREDITS.md.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Main controller of the processor\n */\nmodule ibex_controller (\n input logic clk_i,\n input logic rst_ni,\n\n input logic fetch_enable_i, // start decoding\n output logic ctrl_busy_o, // core is busy processing instrs\n output logic first_fetch_o, // core is at the FIRST FETCH stage\n\n // decoder related signals\n input logic illegal_insn_i, // decoder has an invalid instr\n input logic ecall_insn_i, // decoder has ECALL instr\n input logic mret_insn_i, // decoder has MRET instr\n input logic dret_insn_i, // decoder has DRET instr\n input logic wfi_insn_i, // decoder has WFI instr\n input logic ebrk_insn_i, // decoder has EBREAK instr\n input logic csr_pipe_flush_i, // do CSR-related pipeline flush\n\n // from IF-ID pipeline stage\n input logic instr_valid_i, // instr from IF-ID reg is valid\n input logic [31:0] instr_i, // instr from IF-ID reg, for mtval\n input logic [15:0] instr_compressed_i, // instr from IF-ID reg, for mtval\n input logic instr_is_compressed_i, // instr from IF-ID reg is compressed\n input logic instr_fetch_err_i, // instr from IF-ID reg has error\n input logic [31:0] pc_id_i, // instr from IF-ID reg address\n\n // to IF-ID pipeline stage\n output logic instr_valid_clear_o, // kill instr in IF-ID reg\n output logic id_in_ready_o, // ID stage is ready for new instr\n\n // to prefetcher\n output logic instr_req_o, // start fetching instructions\n output logic pc_set_o, // jump to address set by pc_mux\n output ibex_pkg::pc_sel_e pc_mux_o, // IF stage fetch address selector\n // (boot, normal, exception...)\n output ibex_pkg::exc_pc_sel_e exc_pc_mux_o, // IF stage selector for exception PC\n output ibex_pkg::exc_cause_e exc_cause_o, // for IF stage, CSRs\n\n // LSU\n input logic [31:0] lsu_addr_last_i, // for mtval\n input logic load_err_i,\n input logic store_err_i,\n\n // jump/branch signals\n input logic branch_set_i, // branch taken set signal\n input logic jump_set_i, // jump taken set signal\n\n // interrupt signals\n input logic csr_mstatus_mie_i, // M-mode interrupt enable bit\n input logic csr_msip_i, // software interrupt pending\n input logic csr_mtip_i, // timer interrupt pending\n input logic csr_meip_i, // external interrupt pending\n input logic [14:0] csr_mfip_i, // fast interrupt pending\n input logic irq_pending_i, // interrupt request pending\n input logic irq_nm_i, // non-maskeable interrupt\n\n // debug signals\n input logic debug_req_i,\n output ibex_pkg::dbg_cause_e debug_cause_o,\n output logic debug_csr_save_o,\n input logic debug_single_step_i,\n input logic debug_ebreakm_i,\n\n output logic csr_save_if_o,\n output logic csr_save_id_o,\n output logic csr_restore_mret_id_o,\n output logic csr_save_cause_o,\n output logic [31:0] csr_mtval_o,\n\n // stall signals\n input logic stall_lsu_i,\n input logic stall_multdiv_i,\n input logic stall_jump_i,\n input logic stall_branch_i,\n\n // performance monitors\n output logic perf_jump_o, // we are executing a jump\n // instruction (j, jr, jal, jalr)\n output logic perf_tbranch_o // we are executing a taken branch\n // instruction\n);\n import ibex_pkg::*;\n\n // FSM state encoding\n typedef enum logic [3:0] {\n RESET, BOOT_SET, WAIT_SLEEP, SLEEP, FIRST_FETCH, DECODE, FLUSH,\n IRQ_TAKEN, DBG_TAKEN_IF, DBG_TAKEN_ID\n } ctrl_fsm_e;\n\n ctrl_fsm_e ctrl_fsm_cs, ctrl_fsm_ns;\n\n logic nmi_mode_q, nmi_mode_d;\n logic debug_mode_q, debug_mode_d;\n logic load_err_q, load_err_d;\n logic store_err_q, store_err_d;\n\n logic stall;\n logic halt_if;\n logic halt_id;\n logic illegal_dret;\n logic illegal_insn;\n logic exc_req;\n logic exc_req_lsu;\n logic special_req;\n logic enter_debug_mode;\n logic handle_irq;\n\n logic [4:0] mfip_id;\n logic unused_csr_mtip;\n\n`ifndef SYNTHESIS\n // synopsys translate_off\n // make sure we are called later so that we do not generate messages for\n // glitches\n always_ff @(negedge clk_i) begin\n // print warning in case of decoding errors\n if ((ctrl_fsm_cs == DECODE) && instr_valid_i && illegal_insn) begin\n $display(\"%t: Illegal instruction (core %0d) at PC 0x%h: 0x%h\", $time, ibex_core.core_id_i,\n ibex_id_stage.pc_id_i, ibex_id_stage.instr_rdata_i);\n end\n end\n // synopsys translate_on\n`endif\n\n ////////////////\n // Exceptions //\n ////////////////\n\n assign load_err_d = load_err_i;\n assign store_err_d = store_err_i;\n\n // \"Executing DRET outside of Debug Mode causes an illegal instruction exception.\"\n // [Debug Spec v0.13.2, p.41]\n assign illegal_dret = dret_insn_i & ~debug_mode_q;\n assign illegal_insn = illegal_insn_i | illegal_dret;\n\n // exception requests\n assign exc_req = ecall_insn_i | ebrk_insn_i | illegal_insn | instr_fetch_err_i;\n\n // LSU exception requests\n assign exc_req_lsu = store_err_i | load_err_i;\n\n // special requests: special instructions, pipeline flushes, exceptions...\n assign special_req = mret_insn_i | dret_insn_i | wfi_insn_i | csr_pipe_flush_i |\n exc_req | exc_req_lsu;\n\n ////////////////\n // Interrupts //\n ////////////////\n\n assign enter_debug_mode = debug_req_i & ~debug_mode_q;\n\n // interrupts including NMI are ignored while in debug mode [Debug Spec v0.13.2, p.39]\n assign handle_irq = ~debug_mode_q &\n ((irq_nm_i & ~nmi_mode_q) | (irq_pending_i & csr_mstatus_mie_i));\n\n // generate ID of fast interrupts, highest priority to highest ID\n always_comb begin : gen_mfip_id\n if (csr_mfip_i[14]) mfip_id = 5'd14;\n else if (csr_mfip_i[13]) mfip_id = 5'd13;\n else if (csr_mfip_i[12]) mfip_id = 5'd12;\n else if (csr_mfip_i[11]) mfip_id = 5'd11;\n else if (csr_mfip_i[10]) mfip_id = 5'd10;\n else if (csr_mfip_i[ 9]) mfip_id = 5'd9;\n else if (csr_mfip_i[ 8]) mfip_id = 5'd8;\n else if (csr_mfip_i[ 7]) mfip_id = 5'd7;\n else if (csr_mfip_i[ 6]) mfip_id = 5'd6;\n else if (csr_mfip_i[ 5]) mfip_id = 5'd5;\n else if (csr_mfip_i[ 5]) mfip_id = 5'd5;\n else if (csr_mfip_i[ 4]) mfip_id = 5'd4;\n else if (csr_mfip_i[ 3]) mfip_id = 5'd3;\n else if (csr_mfip_i[ 2]) mfip_id = 5'd2;\n else if (csr_mfip_i[ 1]) mfip_id = 5'd1;\n else mfip_id = 5'd0;\n end\n\n assign unused_csr_mtip = csr_mtip_i;\n\n /////////////////////\n // Core controller //\n /////////////////////\n\n always_comb begin\n // Default values\n instr_req_o = 1'b1;\n\n csr_save_if_o = 1'b0;\n csr_save_id_o = 1'b0;\n csr_restore_mret_id_o = 1'b0;\n csr_save_cause_o = 1'b0;\n csr_mtval_o = '0;\n\n pc_mux_o = PC_BOOT;\n pc_set_o = 1'b0;\n\n exc_pc_mux_o = EXC_PC_IRQ;\n exc_cause_o = EXC_CAUSE_INSN_ADDR_MISA; // = 6'h00\n\n ctrl_fsm_ns = ctrl_fsm_cs;\n\n ctrl_busy_o = 1'b1;\n first_fetch_o = 1'b0;\n\n halt_if = 1'b0;\n halt_id = 1'b0;\n\n debug_csr_save_o = 1'b0;\n debug_cause_o = DBG_CAUSE_EBREAK;\n debug_mode_d = debug_mode_q;\n nmi_mode_d = 1'b0;\n\n perf_tbranch_o = 1'b0;\n perf_jump_o = 1'b0;\n\n unique case (ctrl_fsm_cs)\n RESET: begin\n // just wait for fetch_enable\n instr_req_o = 1'b0;\n pc_mux_o = PC_BOOT;\n pc_set_o = 1'b1;\n if (fetch_enable_i) begin\n ctrl_fsm_ns = BOOT_SET;\n end\n end\n\n BOOT_SET: begin\n // copy boot address to instr fetch address\n instr_req_o = 1'b1;\n pc_mux_o = PC_BOOT;\n pc_set_o = 1'b1;\n\n ctrl_fsm_ns = FIRST_FETCH;\n end\n\n WAIT_SLEEP: begin\n ctrl_busy_o = 1'b0;\n instr_req_o = 1'b0;\n halt_if = 1'b1;\n halt_id = 1'b1;\n ctrl_fsm_ns = SLEEP;\n end\n\n SLEEP: begin\n // instruction in IF stage is already valid\n // we begin execution when an interrupt has arrived\n ctrl_busy_o = 1'b0;\n instr_req_o = 1'b0;\n halt_if = 1'b1;\n halt_id = 1'b1;\n\n // normal execution flow\n // in debug mode or single step mode we leave immediately (wfi=nop)\n if (irq_nm_i || irq_pending_i || debug_req_i || debug_mode_q || debug_single_step_i) begin\n ctrl_fsm_ns = FIRST_FETCH;\n end\n end\n\n FIRST_FETCH: begin\n first_fetch_o = 1'b1;\n // Stall because of IF miss\n if (id_in_ready_o) begin\n ctrl_fsm_ns = DECODE;\n end\n\n // handle interrupts\n if (handle_irq) begin\n // This assumes that the pipeline is always flushed before\n // going to sleep.\n ctrl_fsm_ns = IRQ_TAKEN;\n halt_if = 1'b1;\n halt_id = 1'b1;\n end\n\n // enter debug mode\n if (enter_debug_mode) begin\n ctrl_fsm_ns = DBG_TAKEN_IF;\n halt_if = 1'b1;\n halt_id = 1'b1;\n end\n end\n\n DECODE: begin\n // normal operating mode of the ID stage, in case of debug and interrupt requests,\n // priorities are as follows (lower number == higher priority)\n // 1. currently running (multicycle) instructions and exceptions caused by these\n // 2. debug requests\n // 3. interrupt requests\n\n if (instr_valid_i) begin\n\n // set PC in IF stage to branch or jump target\n if (branch_set_i || jump_set_i) begin\n pc_mux_o = PC_JUMP;\n pc_set_o = 1'b1;\n\n perf_tbranch_o = branch_set_i;\n perf_jump_o = jump_set_i;\n\n // get ready for special instructions, exceptions, pipeline flushes\n end else if (special_req) begin\n ctrl_fsm_ns = FLUSH;\n halt_if = 1'b1;\n halt_id = 1'b1;\n end\n\n // stall IF stage to not starve debug and interrupt requests, these just\n // need to wait until after the current (multicycle) instruction\n if ((enter_debug_mode || handle_irq) && stall) begin\n halt_if = 1'b1;\n end\n\n // single stepping:\n // execute a single instruction and then enter debug mode, in case of exceptions,\n // set registers but do not jump into handler [Debug Spec v0.13.2, p.44]\n if (debug_single_step_i && !debug_mode_q) begin\n halt_if = 1'b1;\n\n if (!special_req && !stall) begin\n ctrl_fsm_ns = DBG_TAKEN_IF;\n end\n end\n end // instr_valid_i\n\n if (!stall && !special_req) begin\n if (enter_debug_mode) begin\n // enter debug mode\n ctrl_fsm_ns = DBG_TAKEN_IF;\n halt_if = 1'b1;\n halt_id = 1'b1;\n\n end else if (handle_irq) begin\n // handle interrupt (not in debug mode)\n ctrl_fsm_ns = IRQ_TAKEN;\n halt_if = 1'b1;\n halt_id = 1'b1;\n end\n end\n\n end // DECODE\n\n IRQ_TAKEN: begin\n if (handle_irq) begin\n pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n exc_pc_mux_o = EXC_PC_IRQ;\n\n csr_save_if_o = 1'b1;\n csr_save_cause_o = 1'b1;\n\n // interrupt priorities according to Privileged Spec v1.11 p.31\n if (irq_nm_i && !nmi_mode_q) begin\n exc_cause_o = EXC_CAUSE_IRQ_NM;\n nmi_mode_d = 1'b1; // enter NMI mode\n end else if (csr_mfip_i != 15'b0) begin\n exc_cause_o = exc_cause_e'({1'b1, mfip_id});\n end else if (csr_meip_i) begin\n exc_cause_o = EXC_CAUSE_IRQ_EXTERNAL_M;\n end else if (csr_msip_i) begin\n exc_cause_o = EXC_CAUSE_IRQ_SOFTWARE_M;\n end else begin // csr_mtip_i\n exc_cause_o = EXC_CAUSE_IRQ_TIMER_M;\n end\n end\n\n ctrl_fsm_ns = DECODE;\n end\n\n DBG_TAKEN_IF: begin\n // enter debug mode and save PC in IF to dpc\n // jump to debug exception handler in debug memory\n if (debug_single_step_i || debug_req_i) begin\n pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n exc_pc_mux_o = EXC_PC_DBD;\n\n csr_save_if_o = 1'b1;\n debug_csr_save_o = 1'b1;\n\n csr_save_cause_o = 1'b1;\n if (debug_single_step_i) begin\n debug_cause_o = DBG_CAUSE_STEP;\n end else begin\n debug_cause_o = DBG_CAUSE_HALTREQ;\n end\n\n // enter debug mode\n debug_mode_d = 1'b1;\n end\n\n ctrl_fsm_ns = DECODE;\n end\n\n DBG_TAKEN_ID: begin\n // enter debug mode and save PC in ID to dpc, used when encountering\n // 1. EBREAK during debug mode\n // 2. EBREAK with forced entry into debug mode (ebreakm or ebreaku set).\n // regular ebreak's go through FLUSH.\n //\n // for 1. do not update dcsr and dpc, for 2. do so [Debug Spec v0.13.2, p.39]\n // jump to debug exception handler in debug memory\n if (ebrk_insn_i) begin\n pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n exc_pc_mux_o = EXC_PC_DBD;\n\n // update dcsr and dpc\n if (debug_ebreakm_i && !debug_mode_q) begin // ebreak with forced entry\n\n // dpc (set to the address of the EBREAK, i.e. set to PC in ID stage)\n csr_save_cause_o = 1'b1;\n csr_save_id_o = 1'b1;\n\n // dcsr\n debug_csr_save_o = 1'b1;\n debug_cause_o = DBG_CAUSE_EBREAK;\n end\n\n // enter debug mode\n debug_mode_d = 1'b1;\n end\n\n ctrl_fsm_ns = DECODE;\n end\n\n FLUSH: begin\n // flush the pipeline\n halt_if = 1'b1;\n halt_id = 1'b1;\n ctrl_fsm_ns = DECODE;\n\n // exceptions: set exception PC, save PC and exception cause\n // exc_req_lsu is high for one clock cycle only (in DECODE)\n if (exc_req || store_err_q || load_err_q) begin\n pc_set_o = 1'b1;\n pc_mux_o = PC_EXC;\n exc_pc_mux_o = debug_mode_q ? EXC_PC_DBG_EXC : EXC_PC_EXC;\n csr_save_id_o = 1'b1;\n csr_save_cause_o = 1'b1;\n\n // set exception registers, priorities according to Table 3.7 of Privileged Spec v1.11\n if (instr_fetch_err_i) begin\n exc_cause_o = EXC_CAUSE_INSTR_ACCESS_FAULT;\n csr_mtval_o = pc_id_i;\n\n end else if (illegal_insn) begin\n exc_cause_o = EXC_CAUSE_ILLEGAL_INSN;\n csr_mtval_o = instr_is_compressed_i ? {16'b0, instr_compressed_i} : instr_i;\n\n end else if (ecall_insn_i) begin\n exc_cause_o = EXC_CAUSE_ECALL_MMODE;\n\n end else if (ebrk_insn_i) begin\n if (debug_mode_q) begin\n /*\n * EBREAK in debug mode re-enters debug mode\n *\n * \"The only exception is EBREAK. When that is executed in Debug\n * Mode, it halts the hart again but without updating dpc or\n * dcsr.\" [Debug Spec v0.13.2, p.39]\n */\n pc_set_o = 1'b0;\n csr_save_id_o = 1'b0;\n csr_save_cause_o = 1'b0;\n ctrl_fsm_ns = DBG_TAKEN_ID;\n end else if (debug_ebreakm_i) begin\n /*\n * dcsr.ebreakm == 1:\n * \"EBREAK instructions in M-mode enter Debug Mode.\"\n * [Debug Spec v0.13.2, p.42]\n */\n pc_set_o = 1'b0;\n csr_save_id_o = 1'b0;\n csr_save_cause_o = 1'b0;\n ctrl_fsm_ns = DBG_TAKEN_ID;\n end else begin\n /*\n * \"The EBREAK instruction is used by debuggers to cause control\n * to be transferred back to a debugging environment. It\n * generates a breakpoint exception and performs no other\n * operation. [...] ECALL and EBREAK cause the receiving\n * privilege mode’s epc register to be set to the address of the\n * ECALL or EBREAK instruction itself, not the address of the\n * following instruction.\" [Privileged Spec v1.11, p.40]\n */\n exc_cause_o = EXC_CAUSE_BREAKPOINT;\n end\n\n end else if (store_err_q) begin\n exc_cause_o = EXC_CAUSE_STORE_ACCESS_FAULT;\n csr_mtval_o = lsu_addr_last_i;\n\n end else if (load_err_q) begin\n exc_cause_o = EXC_CAUSE_LOAD_ACCESS_FAULT;\n csr_mtval_o = lsu_addr_last_i;\n end\n\n end else begin\n // special instructions and pipeline flushes\n if (mret_insn_i) begin\n pc_mux_o = PC_ERET;\n pc_set_o = 1'b1;\n csr_restore_mret_id_o = 1'b1;\n if (nmi_mode_q) begin\n nmi_mode_d = 1'b0; // exit NMI mode\n end\n end else if (dret_insn_i) begin\n pc_mux_o = PC_DRET;\n pc_set_o = 1'b1;\n debug_mode_d = 1'b0;\n end else if (wfi_insn_i) begin\n ctrl_fsm_ns = WAIT_SLEEP;\n end else if (csr_pipe_flush_i && handle_irq) begin\n // start handling IRQs when doing CSR-related pipeline flushes\n ctrl_fsm_ns = IRQ_TAKEN;\n end\n end // exc_req\n\n // single stepping\n // set exception registers, but do not jump into handler [Debug Spec v0.13.2, p.44]\n if (debug_single_step_i && !debug_mode_q) begin\n pc_set_o = 1'b0;\n ctrl_fsm_ns = DBG_TAKEN_IF;\n end\n end // FLUSH\n\n default: begin\n instr_req_o = 1'b0;\n ctrl_fsm_ns = ctrl_fsm_e'(1'bX);\n end\n endcase\n end\n\n ///////////////////\n // Stall control //\n ///////////////////\n\n // if high, current instr needs at least one more cycle to finish after the current cycle\n // if low, current instr finishes in current cycle\n // multicycle instructions have this set except during the last cycle\n assign stall = stall_lsu_i | stall_multdiv_i | stall_jump_i | stall_branch_i;\n\n // signal to IF stage that ID stage is ready for next instr\n assign id_in_ready_o = ~stall & ~halt_if;\n\n // kill instr in IF-ID pipeline reg that are done, or if a\n // multicycle instr causes an exception for example\n assign instr_valid_clear_o = ~stall | halt_id;\n\n // update registers\n always_ff @(posedge clk_i or negedge rst_ni) begin : update_regs\n if (!rst_ni) begin\n ctrl_fsm_cs <= RESET;\n nmi_mode_q <= 1'b0;\n debug_mode_q <= 1'b0;\n load_err_q <= 1'b0;\n store_err_q <= 1'b0;\n end else begin\n ctrl_fsm_cs <= ctrl_fsm_ns;\n nmi_mode_q <= nmi_mode_d;\n debug_mode_q <= debug_mode_d;\n load_err_q <= load_err_d;\n store_err_q <= store_err_d;\n end\n end\n\nendmodule\n", "pr_title": "Fix behavior of DRET executed outside debug mode", "pr_body": "Executing a DRET instruction outside of debug mode now causes an illegal instruction exception as mandated by the Debug Spec v0.13.2 p.41.\r\n\r\nThis resolves lowRISC/ibex#270.", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex a59633c771..c7ef3e0b9c 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -104,6 +104,8 @@ module ibex_controller (\n logic stall;\n logic halt_if;\n logic halt_id;\n+ logic illegal_dret;\n+ logic illegal_insn;\n logic exc_req;\n logic exc_req_lsu;\n logic special_req;\n@@ -119,7 +121,7 @@ module ibex_controller (\n // glitches\n always_ff @(negedge clk_i) begin\n // print warning in case of decoding errors\n- if ((ctrl_fsm_cs == DECODE) && instr_valid_i && illegal_insn_i) begin\n+ if ((ctrl_fsm_cs == DECODE) && instr_valid_i && illegal_insn) begin\n $display(\"%t: Illegal instruction (core %0d) at PC 0x%h: 0x%h\", $time, ibex_core.core_id_i,\n ibex_id_stage.pc_id_i, ibex_id_stage.instr_rdata_i);\n end\n@@ -134,8 +136,13 @@ module ibex_controller (\n assign load_err_d = load_err_i;\n assign store_err_d = store_err_i;\n \n+ // \"Executing DRET outside of Debug Mode causes an illegal instruction exception.\"\n+ // [Debug Spec v0.13.2, p.41]\n+ assign illegal_dret = dret_insn_i & ~debug_mode_q;\n+ assign illegal_insn = illegal_insn_i | illegal_dret;\n+\n // exception requests\n- assign exc_req = ecall_insn_i | ebrk_insn_i | illegal_insn_i | instr_fetch_err_i;\n+ assign exc_req = ecall_insn_i | ebrk_insn_i | illegal_insn | instr_fetch_err_i;\n \n // LSU exception requests\n assign exc_req_lsu = store_err_i | load_err_i;\n@@ -442,7 +449,7 @@ module ibex_controller (\n exc_cause_o = EXC_CAUSE_INSTR_ACCESS_FAULT;\n csr_mtval_o = pc_id_i;\n \n- end else if (illegal_insn_i) begin\n+ end else if (illegal_insn) begin\n exc_cause_o = EXC_CAUSE_ILLEGAL_INSN;\n csr_mtval_o = instr_is_compressed_i ? {16'b0, instr_compressed_i} : instr_i;\n \n"}
{"repo": "lowRISC/ibex", "pr_id": 401, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": false, "sufficient_for_diagnosis": true}, "reasoning": "The generated specification uses signal names from the patch (e.g., pc_set_o, DBG_TAKEN_IF), which constitutes patch leakage."}, "generated_spec": "# Behavioral Design Specification: ibex_controller\n\n## Overview\n\nThe controller is the main state machine that governs the overall execution of the RISC-V processor. It manages the transition of the processor through its operational phases: reset, boot, instruction fetch, decode/execute, exception handling, interrupt handling, debug mode entry/exit, and sleep (WFI). The controller interacts with the instruction fetch stage, the decode/execute stage, the load-store unit (LSU), the CSR block, and the debug module to ensure correct sequencing of operations.\n\nThe controller is responsible for:\n\n- Starting the processor from reset and performing the initial boot sequence.\n- Directing the instruction fetch stage to the correct program counter (PC) for normal fetching, jumps, branches, exceptions, and debug entries.\n- Coordinating pipeline stalls, halts, and flushes to ensure architectural correctness.\n- Recognizing exception conditions (illegal instructions, ecall, ebreak, fetch errors, load/store errors) and initiating appropriate trap handling.\n- Recognizing interrupt requests (including NMI, fast interrupts, external, timer, software) and initiating interrupt handling.\n- Supporting entry into debug mode via external request, single-step, or ebreak instruction.\n- Controlling the sleep state entered by the WFI instruction and waking up on interrupts or debug requests.\n- Generating performance monitoring signals for jumps and taken branches.\n\n## Reset and Boot\n\nUpon system reset, the controller must hold the processor in a reset state until the `fetch_enable` signal is asserted. During reset, the instruction fetch stage must be held inactive (no requests). Once `fetch_enable` is asserted, the controller must transition to a boot set state. In the boot set state, the controller must set the program counter to the boot address and force the instruction fetch stage to request an instruction from that address. Immediately after boot set, the controller enters the first fetch state, which fetches the first instruction. After the first fetch completes (the decode stage indicates readiness), the controller transitions to the decode state for normal operation.\n\nThe boot address is provided externally (typically via a CSR or other configuration). The controller ensures that the first instruction fetch starts from that address.\n\n## Normal Instruction Flow\n\nIn normal operation (decode state), the controller monitors the validity of the instruction in the decode stage (`instr_valid`). While an instruction is valid and no special conditions occur, the controller allows the pipeline to proceed:\n\n- If a taken branch or jump is detected, the controller must set the program counter to the target address (via PC_JUMP) and issue a PC set request. The instruction fetch stage will begin fetching from that address on the next cycle. A taken branch also triggers a performance event (taken branch), and a jump triggers a performance event (jump).\n- If no branch or jump occurs, the controller simply allows the current instruction to complete and the next instruction to enter the decode stage.\n\nThe controller must handle pipeline stalls caused by multi-cycle instructions (loads, stores, multiplications, divisions, jumps, branches). When a stall is asserted by the LSU, multiplier/divider, jump, or branch logic, the controller must:\n\n- Halt the instruction fetch stage (prevent new instructions from entering the IF/ID pipeline register).\n- Keep the decode stage valid until the stall is released.\n\nWhen the stall is released, the controller must allow the next instruction to enter the decode stage.\n\nThe controller must also support a \"halt IF\" signal, which stops the fetch stage while keeping the decode stage valid. This is used during certain exception handling sequences where the current instruction remains in the decode stage for analysis.\n\nIf a pipeline flush is needed (e.g., due to an exception, interrupt, or debug entry), the controller must clear the instruction in the IF/ID pipeline register by asserting an invalidate signal (`instr_valid_clear`). The flush signal is distinct from a stall: a flush immediately invalidates the current instruction, whereas a stall preserves it.\n\n## Exceptions\n\nThe controller must detect and handle the following exception sources:\n\n- Illegal instruction (including illegal DRET in non-debug mode and illegal instructions in user mode that require machine mode)\n- Environment call (ECALL) from either machine or user mode\n- Breakpoint (EBREAK) instruction\n- Instruction fetch error (access fault during instruction fetch)\n- Load access fault (error response from LSU during a load)\n- Store access fault (error response from LSU during a store)\n\nThese exceptions are registered and latched on the cycle they are detected, then serviced on the following cycle when the controller enters a flush state.\n\nWhen an exception is recognized, the controller must:\n\n1. Halt the instruction fetch stage (no new instructions fetched).\n2. Flush the pipeline (invalidate the instruction in the decode stage and the IF/ID register).\n3. Set the program counter to the exception handler address. The handler address is selected based on the current privilege mode and whether the core is in debug mode (debug mode uses the debug exception address).\n4. Save necessary CSR state: save the current PC to `mepc` (or `dpc` if in debug mode), record the exception cause in `mcause` (or `dcause`), and optionally set `mtval` with additional information (instruction bits, faulting address, etc.).\n5. After the flush, the controller returns to the decode state, and the first instruction of the exception handler will be fetched.\n\nException priorities follow the RISC-V Privileged Specification (v1.11). Within the flush state, the controller must evaluate which exception has highest priority and set the appropriate cause and CSR values. The order of priority (highest first) is:\n\n- Instruction fetch error\n- Illegal instruction\n- ECALL\n- EBREAK (breakpoint) - note that EBREAK may lead to debug mode entry instead of an exception (see Debug section)\n- Store access fault\n- Load access fault\n\nThe `mtval` CSR must be set with the relevant information: for instruction fetch errors, the PC of the faulting instruction; for illegal instructions, the instruction encoding (compressed or full); for load/store faults, the last accessed address.\n\n## Interrupts\n\nThe controller must support the following interrupt sources:\n\n- Non-maskable interrupt (NMI) – highest priority, enabled even when interrupts are globally disabled, and not visible in `mip` CSR.\n- Fast interrupts (15 local interrupts, IDs 16–30)\n- External interrupt (ID 11)\n- Timer interrupt (ID 7)\n- Software interrupt (ID 3)\n\nAll interrupts except NMI are controlled by the global interrupt enable (`mstatus.MIE`) and per-interrupt enable bits in `mie`. Interrupts are ignored when the core is in debug mode, regardless of MIE.\n\nThe controller must evaluate interrupts in the decode state, but only when the current instruction completes (i.e., no stall and no special instruction pending). Interrupts have lower priority than debug requests but higher than normal instruction execution after the current instruction finishes.\n\nWhen an interrupt is taken, the controller must:\n\n1. Halt the instruction fetch stage.\n2. Flush the pipeline.\n3. Set the program counter to the vector table base address (from `mtvec`) plus four times the interrupt ID (vectored mode). For NMI, the offset is 0x7C (ID 31 * 4).\n4. Save the current PC to `mepc`, save the current interrupt enable state to `mstatus.MPIE`, and clear `mstatus.MIE`.\n5. Record the interrupt cause in `mcause`. The cause encoding follows RISC-V conventions: cause bit 31 is set for interrupts, and the lower bits contain the interrupt ID (with fast interrupts mapped to IDs 16-30).\n6. Enter NMI mode if the interrupt is an NMI. This mode records that an NMI is being serviced; subsequent NMIs are ignored until the NMI handler returns (signalled by MRET). The NMI mode is implemented via a dedicated flip-flop.\n\nAfter the interrupt handling sequence, the controller returns to the decode state and the first instruction of the interrupt handler is fetched.\n\n## Debug\n\nThe controller implements debug support as defined in the RISC-V Debug Specification v0.13. The debug entry can be triggered by:\n\n- Assertion of the external debug request (`debug_req`).\n- Single-step mode (when `debug_single_step` is set) – the core enters debug mode after executing each instruction.\n- Execution of an EBREAK instruction when the respective `ebreakm` or `ebreaku` CSR bit is set to force debug entry.\n\nDebug requests have higher priority than interrupts but lower priority than exceptions (exceptions in progress will complete and then debug entry may occur).\n\nWhen entering debug mode:\n\n1. The controller must save the appropriate PC to `dpc`. If debug entry occurs while a valid instruction is in the decode stage (e.g., after ebreak or single-step), the PC saved is the address of that instruction. If entry occurs in the fetch stage (e.g., from external debug request or single-step before a new instruction), the PC saved is the address of the next instruction to be fetched.\n2. The controller must set `dcsr` with the cause of debug entry (halt request, single-step, or ebreak).\n3. The controller must set the program counter to the debug halt address (`DmHaltAddr`).\n4. The controller must flush the pipeline and inhibit new instruction fetches until the PC is set.\n5. After debug entry, the core is in debug mode. All interrupts (including NMI) are ignored while in debug mode.\n6. Debug mode is exited by executing a DRET instruction (see below).\n\nSpecial handling for EBREAK:\n\n- If the core is already in debug mode and executes an EBREAK, it re-enters debug mode without updating `dpc` or `dcsr`. This allows the debugger to re-enter.\n- If the core is not in debug mode but `ebreakm` or `ebreaku` is set, the EBREAK causes debug entry (with `dpc` and `dcsr` updated) rather than an exception.\n- Otherwise, EBREAK causes a breakpoint exception as described in the Exceptions section.\n\nThe controller must also support single-step: after each instruction execution (when `debug_single_step` is set), the core enters debug mode. The instruction that just completed is the one that was single-stepped; its PC is saved to `dpc`.\n\nThe DRET instruction:\n\n- When executed, the controller must set the program counter to the value stored in `dpc` (using PC_DRET) and exit debug mode (clear the debug mode internal state).\n\n## Sleep (WFI)\n\nWhen a WFI instruction is decoded, the controller must:\n\n1. Halt the instruction fetch stage.\n2. Flush the pipeline.\n3. Transition to a sleep state where the core is not busy (`ctrl_busy` deasserted).\n4. Remain in sleep until a wake-up event occurs.\n\nWake-up events include:\n\n- Any pending interrupt (NMI or regular interrupt that would be taken if interrupts were enabled – i.e., if `mstatus.MIE` is set and individual enable matches).\n- Debug request (external or single-step).\n- The core is already in debug mode or single-step mode (WFI is treated as NOP and the core immediately resumes).\n\nThe `mstatus.TW` bit can cause a trap to machine mode when WFI is executed in user mode. In that case, the WFI instruction is treated as illegal for user mode, and an illegal instruction exception is raised instead of entering sleep.\n\n## CSR Pipeline Flush\n\nSome CSR writes require a pipeline flush to ensure correct behavior of subsequent instructions that depend on the updated CSR state. When the decoder asserts a CSR pipeline flush request, the controller must treat it similarly to a special instruction: halt IF, flush ID in the next cycle, and then continue normal execution. This ensures that any stale pipeline state is cleared.\n\n## Performance Monitoring\n\nThe controller must provide two performance event outputs:\n\n- Jump performed: asserted when a jump instruction (JAL, JALR) is executed and the jump is taken.\n- Taken branch: asserted when a branch instruction is executed and the branch condition is taken.\n\nThese events are generated in the decode state when the respective signals from the decoder indicate a branch or jump. The outputs are valid only for the cycle in which the instruction is executed.\n\n## Pipeline Control Summary\n\nThe controller manages three main pipeline control signals:\n\n- **Stall**: The controller must hold the current instruction in the decode stage while external units (LSU, multiplier/divider, jump, branch) are busy. During a stall, instruction fetch is halted, and the decode stage state is preserved.\n- **Halt IF**: The controller must prevent new instructions from being fetched while allowing the current instruction in decode to remain valid. This is used when the controller needs to inspect the current instruction before deciding the next action (e.g., during exception evaluation).\n- **Flush ID**: The controller must invalidate the instruction in the decode stage and the IF/ID pipeline register. This is used when the controller decides to discard the current instruction (e.g., after an exception or interrupt).\n\nThe decode stage readiness signal indicates when the controller is ready to accept a new instruction: it is asserted when there is no stall and no halt condition. The instruction valid clear signal is asserted when the controller is not stalling or halting, or when a flush is requested.\n\nThe controller outputs a busy signal that indicates the core is actively processing instructions. It is deasserted only during the sleep state (after WFI) when the core is idle and waiting for wake-up.\n\n## State Machine Summary\n\nThe controller implements a finite state machine with the following states (the exact encoding is implementation-specific, but the behavior must follow):\n\n- **Reset**: Waiting for fetch enable.\n- **Boot Set**: Set PC to boot address and request first fetch.\n- **First Fetch**: Waiting for first instruction to be fetched.\n- **Decode**: Normal operation, executing instructions.\n- **Flush**: Handling exceptions, interrupts, debug entry, or special instructions (MRET, DRET, WFI, CSR flush). Performs PC set and CSR save/restore as needed, then returns to decode.\n- **Irq Taken**: Saving state for an interrupt and setting PC to the handler.\n- **Debug Taken IF**: Saving state for debug entry from the fetch stage (external request or single-step).\n- **Debug Taken ID**: Saving state for debug entry from the decode stage (EBREAK re-entry or forced debug entry).\n- **Wait Sleep**: Transition to sleep after WFI.\n- **Sleep**: Idle, waiting for wake-up event.\n\nThe state machine must handle all transitions correctly, ensuring that no architectural state is lost or corrupted. For example, when an exception occurs while a debug request is pending, the exception is handled first, then debug entry may occur on the next cycle after returning to decode.\n\n## Summary of Requirements\n\n- The controller must correctly sequence the core from reset to normal operation.\n- It must properly handle all exceptions and interrupts according to the RISC-V Privileged Specification v1.11 and Debug Specification v0.13.\n- It must support debug mode entry via external request, single-step, and ebreak.\n- It must manage pipeline stalls, halts, and flushes without introducing data hazards or losing state.\n- It must generate correct exception cause and trap values for `mcause`, `mtval`, `mepc`, and corresponding debug CSRs.\n- It must support WFI sleep and wake-up.\n- It must provide performance signals for jumps and taken branches.\n- It must not rely on any specific internal signal names or implementation choices; the described behavior is the required functional contract.\n\nThis specification defines the expected behavior of the controller as seen from the rest of the core and external debugger interfaces.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2018 ETH Zurich and University of Bologna, see also CREDITS.md.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Main controller of the processor\n */\nmodule ibex_controller (\n input logic clk_i,\n input logic rst_ni,\n\n input logic fetch_enable_i, // start decoding\n output logic ctrl_busy_o, // core is busy processing instrs\n output logic first_fetch_o, // core is at the FIRST FETCH stage\n\n // decoder related signals\n input logic illegal_insn_i, // decoder has an invalid instr\n input logic ecall_insn_i, // decoder has ECALL instr\n input logic mret_insn_i, // decoder has MRET instr\n input logic dret_insn_i, // decoder has DRET instr\n input logic wfi_insn_i, // decoder has WFI instr\n input logic ebrk_insn_i, // decoder has EBREAK instr\n input logic csr_pipe_flush_i, // do CSR-related pipeline flush\n\n // from IF-ID pipeline stage\n input logic instr_valid_i, // instr from IF-ID reg is valid\n input logic [31:0] instr_i, // instr from IF-ID reg, for mtval\n input logic [15:0] instr_compressed_i, // instr from IF-ID reg, for mtval\n input logic instr_is_compressed_i, // instr from IF-ID reg is compressed\n input logic instr_fetch_err_i, // instr from IF-ID reg has error\n input logic [31:0] pc_id_i, // instr from IF-ID reg address\n\n // to IF-ID pipeline stage\n output logic instr_valid_clear_o, // kill instr in IF-ID reg\n output logic id_in_ready_o, // ID stage is ready for new instr\n\n // to prefetcher\n output logic instr_req_o, // start fetching instructions\n output logic pc_set_o, // jump to address set by pc_mux\n output ibex_pkg::pc_sel_e pc_mux_o, // IF stage fetch address selector\n // (boot, normal, exception...)\n output ibex_pkg::exc_pc_sel_e exc_pc_mux_o, // IF stage selector for exception PC\n output ibex_pkg::exc_cause_e exc_cause_o, // for IF stage, CSRs\n\n // LSU\n input logic [31:0] lsu_addr_last_i, // for mtval\n input logic load_err_i,\n input logic store_err_i,\n\n // jump/branch signals\n input logic branch_set_i, // branch taken set signal\n input logic jump_set_i, // jump taken set signal\n\n // interrupt signals\n input logic csr_mstatus_mie_i, // M-mode interrupt enable bit\n input logic csr_msip_i, // software interrupt pending\n input logic csr_mtip_i, // timer interrupt pending\n input logic csr_meip_i, // external interrupt pending\n input logic [14:0] csr_mfip_i, // fast interrupt pending\n input logic irq_pending_i, // interrupt request pending\n input logic irq_nm_i, // non-maskeable interrupt\n\n // debug signals\n input logic debug_req_i,\n output ibex_pkg::dbg_cause_e debug_cause_o,\n output logic debug_csr_save_o,\n output logic debug_mode_o,\n input logic debug_single_step_i,\n input logic debug_ebreakm_i,\n input logic debug_ebreaku_i,\n\n output logic csr_save_if_o,\n output logic csr_save_id_o,\n output logic csr_restore_mret_id_o,\n output logic csr_save_cause_o,\n output logic [31:0] csr_mtval_o,\n input ibex_pkg::priv_lvl_e priv_mode_i,\n input logic csr_mstatus_tw_i,\n\n // stall signals\n input logic stall_lsu_i,\n input logic stall_multdiv_i,\n input logic stall_jump_i,\n input logic stall_branch_i,\n\n // performance monitors\n output logic perf_jump_o, // we are executing a jump\n // instruction (j, jr, jal, jalr)\n output logic perf_tbranch_o // we are executing a taken branch\n // instruction\n);\n import ibex_pkg::*;\n\n // FSM state encoding\n typedef enum logic [3:0] {\n RESET, BOOT_SET, WAIT_SLEEP, SLEEP, FIRST_FETCH, DECODE, FLUSH,\n IRQ_TAKEN, DBG_TAKEN_IF, DBG_TAKEN_ID\n } ctrl_fsm_e;\n\n ctrl_fsm_e ctrl_fsm_cs, ctrl_fsm_ns;\n\n logic nmi_mode_q, nmi_mode_d;\n logic debug_mode_q, debug_mode_d;\n logic load_err_q, load_err_d;\n logic store_err_q, store_err_d;\n logic exc_req_q, exc_req_d;\n logic illegal_insn_q, illegal_insn_d;\n\n logic stall;\n logic halt_if;\n logic flush_id;\n logic illegal_dret;\n logic illegal_umode;\n logic exc_req_lsu;\n logic special_req;\n logic enter_debug_mode;\n logic ebreak_into_debug;\n logic handle_irq;\n\n logic [3:0] mfip_id;\n logic unused_csr_mtip;\n\n logic ecall_insn;\n logic mret_insn;\n logic dret_insn;\n logic wfi_insn;\n logic ebrk_insn;\n logic csr_pipe_flush;\n logic instr_fetch_err;\n\n`ifndef SYNTHESIS\n // synopsys translate_off\n // make sure we are called later so that we do not generate messages for\n // glitches\n always_ff @(negedge clk_i) begin\n // print warning in case of decoding errors\n if ((ctrl_fsm_cs == DECODE) && instr_valid_i && !instr_fetch_err_i && illegal_insn_d) begin\n $display(\"%t: Illegal instruction (hart %0x) at PC 0x%h: 0x%h\", $time, ibex_core.hart_id_i,\n ibex_id_stage.pc_id_i, ibex_id_stage.instr_rdata_i);\n end\n end\n // synopsys translate_on\n`endif\n\n ////////////////\n // Exceptions //\n ////////////////\n\n assign load_err_d = load_err_i;\n assign store_err_d = store_err_i;\n\n // Decoder doesn't take instr_valid into account, factor it in here.\n assign ecall_insn = ecall_insn_i & instr_valid_i;\n assign mret_insn = mret_insn_i & instr_valid_i;\n assign dret_insn = dret_insn_i & instr_valid_i;\n assign wfi_insn = wfi_insn_i & instr_valid_i;\n assign ebrk_insn = ebrk_insn_i & instr_valid_i;\n assign csr_pipe_flush = csr_pipe_flush_i & instr_valid_i;\n assign instr_fetch_err = instr_fetch_err_i & instr_valid_i;\n\n // \"Executing DRET outside of Debug Mode causes an illegal instruction exception.\"\n // [Debug Spec v0.13.2, p.41]\n assign illegal_dret = dret_insn & ~debug_mode_q;\n\n // Some instructions can only be executed in M-Mode\n assign illegal_umode = (priv_mode_i != PRIV_LVL_M) &\n // MRET must be in M-Mode. TW means trap WFI to M-Mode.\n (mret_insn | (csr_mstatus_tw_i & wfi_insn));\n\n // This is recorded in the illegal_insn_q flop to help timing. Specifically\n // it is needed to break the path from ibex_cs_registers/illegal_csr_insn_o\n // to pc_set_o. Clear when controller is in FLUSH so it won't remain set\n // once illegal instruction is handled.\n assign illegal_insn_d = (illegal_insn_i | illegal_dret | illegal_umode) & (ctrl_fsm_cs != FLUSH);\n\n // exception requests\n // requests are flopped in exc_req_q. This is cleared when controller is in\n // the FLUSH state so the cycle following exc_req_q won't remain set for an\n // exception request that has just been handled.\n assign exc_req_d = (ecall_insn | ebrk_insn | illegal_insn_d | instr_fetch_err) &\n (ctrl_fsm_cs != FLUSH);\n\n // LSU exception requests\n assign exc_req_lsu = store_err_i | load_err_i;\n\n // special requests: special instructions, pipeline flushes, exceptions...\n assign special_req = mret_insn | dret_insn | wfi_insn | csr_pipe_flush |\n exc_req_d | exc_req_lsu;\n\n ////////////////\n // Interrupts //\n ////////////////\n\n // Enter debug mode due to an external debug_req_i or because the core is in\n // single step mode (dcsr.step == 1). Single step must be qualified with\n // instruction valid otherwise the core will immediately enter debug mode\n // due to a recently flushed IF (or a delay in an instruction returning from\n // memory) before it has had anything to single step.\n assign enter_debug_mode = (debug_req_i | (debug_single_step_i & instr_valid_i)) & ~debug_mode_q;\n\n // Set when an ebreak should enter debug mode rather than jump to exception\n // handler\n assign ebreak_into_debug = priv_mode_i == PRIV_LVL_M ? debug_ebreakm_i :\n priv_mode_i == PRIV_LVL_U ? debug_ebreaku_i :\n 1'b0;\n\n // interrupts including NMI are ignored while in debug mode [Debug Spec v0.13.2, p.39]\n assign handle_irq = ~debug_mode_q &\n ((irq_nm_i & ~nmi_mode_q) | (irq_pending_i & csr_mstatus_mie_i));\n\n // generate ID of fast interrupts, highest priority to highest ID\n always_comb begin : gen_mfip_id\n if (csr_mfip_i[14]) mfip_id = 4'd14;\n else if (csr_mfip_i[13]) mfip_id = 4'd13;\n else if (csr_mfip_i[12]) mfip_id = 4'd12;\n else if (csr_mfip_i[11]) mfip_id = 4'd11;\n else if (csr_mfip_i[10]) mfip_id = 4'd10;\n else if (csr_mfip_i[ 9]) mfip_id = 4'd9;\n else if (csr_mfip_i[ 8]) mfip_id = 4'd8;\n else if (csr_mfip_i[ 7]) mfip_id = 4'd7;\n else if (csr_mfip_i[ 6]) mfip_id = 4'd6;\n else if (csr_mfip_i[ 5]) mfip_id = 4'd5;\n else if (csr_mfip_i[ 5]) mfip_id = 4'd5;\n else if (csr_mfip_i[ 4]) mfip_id = 4'd4;\n else if (csr_mfip_i[ 3]) mfip_id = 4'd3;\n else if (csr_mfip_i[ 2]) mfip_id = 4'd2;\n else if (csr_mfip_i[ 1]) mfip_id = 4'd1;\n else mfip_id = 4'd0;\n end\n\n assign unused_csr_mtip = csr_mtip_i;\n\n /////////////////////\n // Core controller //\n /////////////////////\n\n always_comb begin\n // Default values\n instr_req_o = 1'b1;\n\n csr_save_if_o = 1'b0;\n csr_save_id_o = 1'b0;\n csr_restore_mret_id_o = 1'b0;\n csr_save_cause_o = 1'b0;\n csr_mtval_o = '0;\n\n pc_mux_o = PC_BOOT;\n pc_set_o = 1'b0;\n\n exc_pc_mux_o = EXC_PC_IRQ;\n exc_cause_o = EXC_CAUSE_INSN_ADDR_MISA; // = 6'h00\n\n ctrl_fsm_ns = ctrl_fsm_cs;\n\n ctrl_busy_o = 1'b1;\n first_fetch_o = 1'b0;\n\n halt_if = 1'b0;\n flush_id = 1'b0;\n\n debug_csr_save_o = 1'b0;\n debug_cause_o = DBG_CAUSE_EBREAK;\n debug_mode_d = debug_mode_q;\n nmi_mode_d = nmi_mode_q;\n\n perf_tbranch_o = 1'b0;\n perf_jump_o = 1'b0;\n\n unique case (ctrl_fsm_cs)\n RESET: begin\n // just wait for fetch_enable\n instr_req_o = 1'b0;\n pc_mux_o = PC_BOOT;\n pc_set_o = 1'b1;\n if (fetch_enable_i) begin\n ctrl_fsm_ns = BOOT_SET;\n end\n end\n\n BOOT_SET: begin\n // copy boot address to instr fetch address\n instr_req_o = 1'b1;\n pc_mux_o = PC_BOOT;\n pc_set_o = 1'b1;\n\n ctrl_fsm_ns = FIRST_FETCH;\n end\n\n WAIT_SLEEP: begin\n ctrl_busy_o = 1'b0;\n instr_req_o = 1'b0;\n halt_if = 1'b1;\n flush_id = 1'b1;\n ctrl_fsm_ns = SLEEP;\n end\n\n SLEEP: begin\n // instruction in IF stage is already valid\n // we begin execution when an interrupt has arrived\n ctrl_busy_o = 1'b0;\n instr_req_o = 1'b0;\n halt_if = 1'b1;\n flush_id = 1'b1;\n\n // normal execution flow\n // in debug mode or single step mode we leave immediately (wfi=nop)\n if (irq_nm_i || irq_pending_i || debug_req_i || debug_mode_q || debug_single_step_i) begin\n ctrl_fsm_ns = FIRST_FETCH;\n end\n end\n\n FIRST_FETCH: begin\n first_fetch_o = 1'b1;\n // Stall because of IF miss\n if (id_in_ready_o) begin\n ctrl_fsm_ns = DECODE;\n end\n\n // handle interrupts\n if (handle_irq) begin\n // This assumes that the pipeline is always flushed before\n // going to sleep.\n ctrl_fsm_ns = IRQ_TAKEN;\n halt_if = 1'b1;\n flush_id = 1'b1;\n end\n\n // enter debug mode\n if (enter_debug_mode) begin\n ctrl_fsm_ns = DBG_TAKEN_IF;\n // Halt IF only for now, ID will be flushed in DBG_TAKEN_IF as the\n // ID state is needed for correct debug mode entry\n halt_if = 1'b1;\n end\n end\n\n DECODE: begin\n // normal operating mode of the ID stage, in case of debug and interrupt requests,\n // priorities are as follows (lower number == higher priority)\n // 1. currently running (multicycle) instructions and exceptions caused by these\n // 2. debug requests\n // 3. interrupt requests\n\n if (instr_valid_i) begin\n\n // get ready for special instructions, exceptions, pipeline flushes\n if (special_req) begin\n // Halt IF but don't flush ID. This leaves a valid instruction in\n // ID so controller can determine appropriate action in the\n // FLUSH state.\n ctrl_fsm_ns = FLUSH;\n halt_if = 1'b1;\n // set PC in IF stage to branch or jump target\n end else if (branch_set_i || jump_set_i) begin\n pc_mux_o = PC_JUMP;\n pc_set_o = 1'b1;\n\n perf_tbranch_o = branch_set_i;\n perf_jump_o = jump_set_i;\n end\n\n // If entering debug mode or handling an IRQ the core needs to wait\n // until the current instruction has finished executing. Stall IF\n // during that time.\n if ((enter_debug_mode || handle_irq) && stall) begin\n halt_if = 1'b1;\n end\n end // instr_valid_i\n\n if (!stall && !special_req) begin\n if (enter_debug_mode) begin\n // enter debug mode\n ctrl_fsm_ns = DBG_TAKEN_IF;\n // Halt IF only for now, ID will be flushed in DBG_TAKEN_IF as the\n // ID state is needed for correct debug mode entry\n halt_if = 1'b1;\n end else if (handle_irq) begin\n // handle interrupt (not in debug mode)\n ctrl_fsm_ns = IRQ_TAKEN;\n halt_if = 1'b1;\n flush_id = 1'b1;\n end\n end\n\n end // DECODE\n\n IRQ_TAKEN: begin\n if (handle_irq) begin\n pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n exc_pc_mux_o = EXC_PC_IRQ;\n\n csr_save_if_o = 1'b1;\n csr_save_cause_o = 1'b1;\n\n // interrupt priorities according to Privileged Spec v1.11 p.31\n if (irq_nm_i && !nmi_mode_q) begin\n exc_cause_o = EXC_CAUSE_IRQ_NM;\n nmi_mode_d = 1'b1; // enter NMI mode\n end else if (csr_mfip_i != 15'b0) begin\n // generate exception cause ID from fast interrupt ID:\n // - first bit distinguishes interrupts from exceptions,\n // - second bit adds 16 to fast interrupt ID\n // for example EXC_CAUSE_IRQ_FAST_0 = {1'b1, 5'd16}\n exc_cause_o = exc_cause_e'({2'b11, mfip_id});\n end else if (csr_meip_i) begin\n exc_cause_o = EXC_CAUSE_IRQ_EXTERNAL_M;\n end else if (csr_msip_i) begin\n exc_cause_o = EXC_CAUSE_IRQ_SOFTWARE_M;\n end else begin // csr_mtip_i\n exc_cause_o = EXC_CAUSE_IRQ_TIMER_M;\n end\n end\n\n ctrl_fsm_ns = DECODE;\n end\n\n DBG_TAKEN_IF: begin\n // enter debug mode and save PC in IF to dpc\n // jump to debug exception handler in debug memory\n if (debug_single_step_i || debug_req_i) begin\n flush_id = 1'b1;\n pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n exc_pc_mux_o = EXC_PC_DBD;\n\n csr_save_if_o = 1'b1;\n debug_csr_save_o = 1'b1;\n\n csr_save_cause_o = 1'b1;\n if (debug_single_step_i) begin\n debug_cause_o = DBG_CAUSE_STEP;\n end else begin\n debug_cause_o = DBG_CAUSE_HALTREQ;\n end\n\n // enter debug mode\n debug_mode_d = 1'b1;\n end\n\n ctrl_fsm_ns = DECODE;\n end\n\n DBG_TAKEN_ID: begin\n // enter debug mode and save PC in ID to dpc, used when encountering\n // 1. EBREAK during debug mode\n // 2. EBREAK with forced entry into debug mode (ebreakm or ebreaku set).\n // regular ebreak's go through FLUSH.\n //\n // for 1. do not update dcsr and dpc, for 2. do so [Debug Spec v0.13.2, p.39]\n // jump to debug exception handler in debug memory\n if (ebrk_insn) begin\n flush_id = 1'b1;\n pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n exc_pc_mux_o = EXC_PC_DBD;\n\n // update dcsr and dpc\n if (ebreak_into_debug && !debug_mode_q) begin // ebreak with forced entry\n\n // dpc (set to the address of the EBREAK, i.e. set to PC in ID stage)\n csr_save_cause_o = 1'b1;\n csr_save_id_o = 1'b1;\n\n // dcsr\n debug_csr_save_o = 1'b1;\n debug_cause_o = DBG_CAUSE_EBREAK;\n end\n\n // enter debug mode\n debug_mode_d = 1'b1;\n end\n\n ctrl_fsm_ns = DECODE;\n end\n\n FLUSH: begin\n // flush the pipeline\n halt_if = 1'b1;\n flush_id = 1'b1;\n ctrl_fsm_ns = DECODE;\n\n // exceptions: set exception PC, save PC and exception cause\n // exc_req_lsu is high for one clock cycle only (in DECODE)\n if (exc_req_q || store_err_q || load_err_q) begin\n pc_set_o = 1'b1;\n pc_mux_o = PC_EXC;\n exc_pc_mux_o = debug_mode_q ? EXC_PC_DBG_EXC : EXC_PC_EXC;\n csr_save_id_o = 1'b1;\n csr_save_cause_o = 1'b1;\n\n // set exception registers, priorities according to Table 3.7 of Privileged Spec v1.11\n if (instr_fetch_err) begin\n exc_cause_o = EXC_CAUSE_INSTR_ACCESS_FAULT;\n csr_mtval_o = pc_id_i;\n\n end else if (illegal_insn_q) begin\n exc_cause_o = EXC_CAUSE_ILLEGAL_INSN;\n csr_mtval_o = instr_is_compressed_i ? {16'b0, instr_compressed_i} : instr_i;\n\n end else if (ecall_insn) begin\n exc_cause_o = (priv_mode_i == PRIV_LVL_M) ? EXC_CAUSE_ECALL_MMODE :\n EXC_CAUSE_ECALL_UMODE;\n\n end else if (ebrk_insn) begin\n if (debug_mode_q | ebreak_into_debug) begin\n /*\n * EBREAK in debug mode re-enters debug mode\n *\n * \"The only exception is EBREAK. When that is executed in Debug\n * Mode, it halts the hart again but without updating dpc or\n * dcsr.\" [Debug Spec v0.13.2, p.39]\n */\n\n /*\n * dcsr.ebreakm == 1:\n * \"EBREAK instructions in M-mode enter Debug Mode.\"\n * [Debug Spec v0.13.2, p.42]\n */\n pc_set_o = 1'b0;\n csr_save_id_o = 1'b0;\n csr_save_cause_o = 1'b0;\n ctrl_fsm_ns = DBG_TAKEN_ID;\n flush_id = 1'b0;\n end else begin\n /*\n * \"The EBREAK instruction is used by debuggers to cause control\n * to be transferred back to a debugging environment. It\n * generates a breakpoint exception and performs no other\n * operation. [...] ECALL and EBREAK cause the receiving\n * privilege mode's epc register to be set to the address of the\n * ECALL or EBREAK instruction itself, not the address of the\n * following instruction.\" [Privileged Spec v1.11, p.40]\n */\n exc_cause_o = EXC_CAUSE_BREAKPOINT;\n end\n\n end else if (store_err_q) begin\n exc_cause_o = EXC_CAUSE_STORE_ACCESS_FAULT;\n csr_mtval_o = lsu_addr_last_i;\n\n end else if (load_err_q) begin\n exc_cause_o = EXC_CAUSE_LOAD_ACCESS_FAULT;\n csr_mtval_o = lsu_addr_last_i;\n end\n\n end else begin\n // special instructions and pipeline flushes\n if (mret_insn) begin\n pc_mux_o = PC_ERET;\n pc_set_o = 1'b1;\n csr_restore_mret_id_o = 1'b1;\n if (nmi_mode_q) begin\n nmi_mode_d = 1'b0; // exit NMI mode\n end\n end else if (dret_insn) begin\n pc_mux_o = PC_DRET;\n pc_set_o = 1'b1;\n debug_mode_d = 1'b0;\n end else if (wfi_insn) begin\n ctrl_fsm_ns = WAIT_SLEEP;\n end else if (csr_pipe_flush && handle_irq) begin\n // start handling IRQs when doing CSR-related pipeline flushes\n ctrl_fsm_ns = IRQ_TAKEN;\n end\n end // exc_req_q\n\n // Entering debug mode due to either single step or debug_req. Ensure\n // registers are set for exception but then enter debug handler rather\n // than exception handler [Debug Spec v0.13.2, p.44]\n // Leave all other signals as is to ensure CSRs and PC get set as if\n // core was entering exception handler, entry to debug mode will then\n // see the appropriate state and setup dpc correctly.\n if (enter_debug_mode) begin\n ctrl_fsm_ns = DBG_TAKEN_IF;\n end\n end // FLUSH\n\n default: begin\n instr_req_o = 1'b0;\n ctrl_fsm_ns = ctrl_fsm_e'(1'bX);\n end\n endcase\n end\n\n // signal to CSR when in debug mode\n assign debug_mode_o = debug_mode_q;\n\n ///////////////////\n // Stall control //\n ///////////////////\n\n // if high, current instr needs at least one more cycle to finish after the current cycle\n // if low, current instr finishes in current cycle\n // multicycle instructions have this set except during the last cycle\n assign stall = stall_lsu_i | stall_multdiv_i | stall_jump_i | stall_branch_i;\n\n // signal to IF stage that ID stage is ready for next instr\n assign id_in_ready_o = ~stall & ~halt_if;\n\n // kill instr in IF-ID pipeline reg that are done, or if a\n // multicycle instr causes an exception for example\n // halt_if is another kind of stall, where the instr_valid bit must remain\n // set (unless flush_id is set also). It cannot be factored directly into\n // stall as this causes a combinational loop.\n assign instr_valid_clear_o = ~(stall | halt_if) | flush_id;\n\n // update registers\n always_ff @(posedge clk_i or negedge rst_ni) begin : update_regs\n if (!rst_ni) begin\n ctrl_fsm_cs <= RESET;\n nmi_mode_q <= 1'b0;\n debug_mode_q <= 1'b0;\n load_err_q <= 1'b0;\n store_err_q <= 1'b0;\n exc_req_q <= 1'b0;\n illegal_insn_q <= 1'b0;\n end else begin\n ctrl_fsm_cs <= ctrl_fsm_ns;\n nmi_mode_q <= nmi_mode_d;\n debug_mode_q <= debug_mode_d;\n load_err_q <= load_err_d;\n store_err_q <= store_err_d;\n exc_req_q <= exc_req_d;\n illegal_insn_q <= illegal_insn_d;\n end\n end\n\nendmodule\n", "pr_title": "[RTL] Fix single stepping on exceptions", "pr_body": "When we single step over an instruction that causes an exception DPC\r\nshould be set to point to the exception handler (where we would have\r\ngone were we not single stepping).\r\n\r\nAs discussed on Zulip this looks to be the correct behaviour, see response to issue on riscv-debug-spec here https://github.com/riscv/riscv-debug-spec/issues/497", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex 08530b1b63..07b64e35ef 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -566,10 +566,13 @@ module ibex_controller (\n end\n end // exc_req_q\n \n- // single stepping\n- // set exception registers, but do not jump into handler [Debug Spec v0.13.2, p.44]\n+ // Entering debug mode due to either single step or debug_req. Ensure\n+ // registers are set for exception but then enter debug handler rather\n+ // than exception handler [Debug Spec v0.13.2, p.44]\n+ // Leave all other signals as is to ensure CSRs and PC get set as if\n+ // core was entering exception handler, entry to debug mode will then\n+ // see the appropriate state and setup dpc correctly.\n if (enter_debug_mode) begin\n- pc_set_o = 1'b0;\n ctrl_fsm_ns = DBG_TAKEN_IF;\n end\n end // FLUSH\n"}
{"repo": "lowRISC/ibex", "pr_id": 113, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": true, "sufficient_for_diagnosis": false}, "reasoning": "The generated specification describes core behavior using normative language but lacks any mention of the tracer or its signal connections, which is the area modified by the patch."}, "generated_spec": "# Behavioral Design Specification for ibex_core (RISC-V Processor Core)\n\n## 1. Introduction\n\nThe `ibex_core` module implements a 32-bit RISC-V processor core that executes the RV32I base instruction set. It supports the optional extensions RV32E (embedded, 16 registers) and RV32M (multiply/divide). The core is designed as a three-stage in-order pipeline (Instruction Fetch, Instruction Decode, Execute) with a separate load-store unit (LSU). It provides separate instruction and data memory interfaces, a simple interrupt controller, and debug support.\n\nThe core shall be fully compliant with the RISC-V Unprivileged Specification (version 2.1 or later) for the implemented instruction set variants, and with the RISC-V Privileged Architecture (version 1.10) for machine-level CSRs and interrupt handling.\n\n## 2. Configuration Parameters\n\nThe core’s behavior is configurable through the following parameters at instantiation time:\n\n- **MHPMCounterNum** (integer, 0…8): Number of hardware performance monitor counters (machine-level). Zero disables all custom counters.\n- **MHPMCounterWidth** (integer, 1…64): Bit width of each performance monitor counter. The counters wrap naturally on overflow.\n- **RV32E** (bit): When set to 1, the core operates in RV32E mode: only the lower 16 registers (x0–x15) are implemented, and all instructions referring to registers x16–x31 cause an illegal instruction exception.\n- **RV32M** (bit): When set to 1, the M extension is enabled (multiply, divide, remainder instructions). When set to 0, those instructions raise an illegal instruction exception.\n- **DmHaltAddr** (32-bit, default 0x1A110800): The program counter to jump to when entering debug mode.\n- **DmExceptionAddr** (32-bit, default 0x1A110808): The program counter to jump to when an exception occurs while the core is already in debug mode.\n\nAll parameters are static; changing them during operation is not permitted.\n\n## 3. Interfaces\n\n### 3.1 Clock and Reset\n- **clk_i**: Main clock input. All synchronous logic is clocked on the rising edge.\n- **rst_ni**: Active-low synchronous reset. When low, the core must be fully reset. The reset must be deasserted synchronously.\n- **test_en_i**: Test enable input. When high, it un-gates all clock gates for test purposes. During normal operation it must be low.\n\n### 3.2 Core Identification and Boot\n- **core_id_i[3:0]**: Static core identifier. It is readable via the `mhartid` CSR.\n- **cluster_id_i[5:0]**: Static cluster identifier. Readable via a custom CSR (not defined in RISC-V spec but provided for system integration).\n- **boot_addr_i[31:0]**: Address from which the core starts fetching instructions after reset.\n\n### 3.3 Instruction Memory Interface\nThe core fetches instructions from a separate instruction memory using a simple handshake protocol. The interface consists of:\n- **Request (output)**: Signal `instr_req_o` must be asserted to start a fetch. It may remain high across multiple cycles until a grant is received.\n- **Address (output)**: `instr_addr_o[31:0]` gives the word-aligned address (the two LSBs are zero). The address may change while the request is active (e.g., after a branch), but the memory must return data corresponding to the address at grant time.\n- **Grant (input)**: The memory asserts `instr_gnt_i` to accept the request. After grant, the core may change the address for the next request.\n- **Data valid (input)**: `instr_rvalid_i` is asserted for exactly one cycle to indicate that `instr_rdata_i` holds valid instruction data.\n- **Data (input)**: `instr_rdata_i[31:0]` contains the 32-bit instruction or the upper/lower half of a compressed instruction pair.\n\nThe protocol is request-grant with a separate response. The core must handle wait states: the grant may come any number of cycles after request, and the response may come any number of cycles after grant.\n\n### 3.4 Data Memory Interface (Load-Store Unit)\nThe LSU accesses data memory with a request-grant‑response protocol, similar to the instruction interface but with additional control signals:\n- **Request (output)**: `data_req_o` asserted to start a data transaction.\n- **Write enable (output)**: `data_we_o` high for stores, low for loads.\n- **Byte enables (output)**: `data_be_o[3:0]` specifies which bytes are accessed. For a word load, all four bytes are enabled; for halfword, two bytes; for byte, one byte. During stores, only the enabled bytes are written.\n- **Address (output)**: `data_addr_o[31:0]` – typically word-aligned, but may be misaligned (handled internally by the LSU by performing multiple aligned accesses).\n- **Write data (output)**: `data_wdata_o[31:0]` – data to be written during a store, aligned to byte lanes according to `data_be_o`.\n- **Grant (input)**: `data_gnt_i` – the memory accepts the request. After grant, the core may change all outputs for the next request.\n- **Response valid (input)**: `data_rvalid_i` – asserted for one cycle when `data_rdata_i` and `data_err_i` are valid.\n- **Read data (input)**: `data_rdata_i[31:0]` – data returned for loads.\n- **Error (input)**: `data_err_i` – asserted with response to signal an error. The core must take an exception for such requests.\n\nThe LSU must handle misaligned accesses transparently. For a load or store to a misaligned address, the core performs two or more aligned transactions, but from the outside no extra signals are needed. The response (including error) for the original access is only given when all sub‑transactions complete.\n\n### 3.5 Interrupt Interface\nThe core supports one interrupt input:\n- **irq_i**: Level-sensitive interrupt request. Must be held high until the core acknowledges it.\n- **irq_id_i[4:0]**: Interrupt identifier (interrupt cause value). Used to set the `mcause` CSR when the interrupt is taken.\n- **irq_ack_o**: Acknowledgment signal. The core asserts this for one cycle when it takes the interrupt (starts the trap handler).\n- **irq_id_o[4:0]**: Interrupt identifier output at the time of acknowledgment, reflecting the interrupt that was taken.\n\nThe core must take an interrupt only when the machine-level interrupt enable (`MIE`) bit in `mstatus` is set. The interrupt causes the core to save PC to `mepc`, set `mcause` to the value of `irq_id_i`, and jump to `mtvec`. After the interrupt handler completes with an `MRET` instruction, execution resumes at the address saved in `mepc`.\n\n### 3.6 Debug Interface\n- **debug_req_i**: Debug request input. When asserted, the core will enter debug mode after completing the current instruction (or immediately if halted). The core must set the appropriate debug cause and jump to `DmHaltAddr`. While in debug mode, the core executes a separate code sequence. Exceptions in debug mode jump to `DmExceptionAddr`. The debug mode behavior follows the RISC-V Debug Specification (version 0.13).\n\n### 3.7 Core Control\n- **fetch_enable_i**: Core enable. When low, the core must stop fetching new instructions and eventually become idle. The core must not execute any new instructions. When high, the core resumes normal operation.\n\n## 4. Functional Requirements\n\n### 4.1 Reset Behavior\nUpon deassertion of `rst_ni`, the core must:\n- Reset all architectural registers (including x0 which always reads 0).\n- Initialize program counter to the value of `boot_addr_i`.\n- Set `mstatus` with `MIE` cleared (interrupts disabled).\n- Clear all CSRs, including `mepc`, `mcause`, `mtvec`, `mtval`, and performance counters.\n- Set `mhartid` to `core_id_i`.\n- Begin fetching instructions from `boot_addr_i` only when `fetch_enable_i` is high.\n\n### 4.2 Instruction Fetch (IF) Behavior\nThe IF stage must:\n- Continuously fetch instructions from the instruction memory as long as `fetch_enable_i` is high and the pipeline is not stalled.\n- Support compressed instructions (RVC) by internally handling halfword-aligned addresses. The external interface always uses word-aligned addresses; the core internally selects the correct halfword.\n- Detect illegal compressed instructions and forward them as illegal instructions to the ID stage.\n- Accept branch and jump target addresses from the execute stage and update the program counter accordingly.\n- Support single-step and debug entry via the IF stage's interaction with the CSR block.\n\n### 4.3 Instruction Decode (ID) Behavior\nThe ID stage must:\n- Decode all supported RISC‑V instructions.\n- Read the register file (either 16 or 32 registers depending on RV32E).\n- Detect illegal instructions (including unsupported opcodes, illegal CSR accesses, and RV32E register references to registers x16–x31). When an illegal instruction is detected, the core must raise an illegal instruction exception (cause 2) and not commit any side effects.\n- Generate control signals for the execute stage and LSU.\n- Handle pipeline stalls caused by data hazards (load-use) or structural hazards (busy LSU, busy IF).\n- Detect interrupt requests, debug requests, and exception conditions (from IF, ID, or LSU) and initiate the appropriate trap or debug entry sequence.\n\n### 4.4 Execute Stage Behavior\nThe execute stage must:\n- Perform arithmetic and logical operations (ALU) as required by the instruction.\n- Execute multiply, divide, and remainder operations if the RV32M parameter is enabled, else these instructions are illegal.\n- Compute branch and jump target addresses.\n- Generate the branch decision signal (taken/not taken) forwarded back to ID for PC update.\n- Forward arithmetic results to the register file write port (bypass for register writes) and to the LSU for store data and address computation.\n\n### 4.5 Load-Store Unit (LSU) Behavior\nThe LSU must:\n- Perform load and store operations of size byte, halfword, or word.\n- Handle misaligned accesses by performing multiple aligned bus transactions, keeping the entire access atomic from the programmer’s perspective.\n- Provide the loaded data for register write-back after the response is received.\n- Report memory errors to the ID stage, which then raises an appropriate exception (load access fault or store access fault).\n- Indicate busy status so that the pipeline stalls until the LSU is free.\n\n### 4.6 Exception and Interrupt Handling\nThe core must support the following synchronous exceptions and asynchronous interrupts:\n\n- **Instruction access fault** (cause 1): raised by the instruction memory interface if the fetch fails (not shown on the interface, but can be triggered by the system).\n- **Illegal instruction** (cause 2): as described above.\n- **Load address misaligned** (cause 4): generated by the LSU when a load address is misaligned and cannot be handled (only if the system requires alignment; by default the LSU handles misalignment, so this exception should not occur unless the system declares load misaligned as an error).\n- **Load access fault** (cause 5): raised when the data memory returns an error for a load.\n- **Store address misaligned** (cause 6): similar to load misaligned.\n- **Store access fault** (cause 7): raised when the data memory returns an error for a store.\n- **Environment call from M-mode** (cause 11): generated by the `ECALL` instruction.\n- **Breakpoint** (cause 3): generated by `EBREAK` instruction (unless in debug mode, where it is handled by the debug module).\n\n- **Machine external interrupt** (cause 0x80000000 | irq_id): taken when `irq_i` is high and `mstatus.MIE` is set.\n\nFor any trap (exception or interrupt), the core must:\n1. Set `mepc` to the PC of the instruction that caused the trap (or for interrupts, the PC of the next instruction to resume).\n2. Set `mcause` to the appropriate cause value.\n3. Optionally set `mtval` to an exception-specific value (e.g., address for access faults, zero otherwise).\n4. Disable interrupts by clearing `mstatus.MIE`.\n5. Set the PC to `mtvec` (address of trap handler).\n\nReturn from handler is done via `MRET`, which restores `mstatus.MIE` and PC from `mepc`.\n\n### 4.7 Debug Mode Behavior\nWhen `debug_req_i` is asserted, the core shall enter debug mode after the current instruction completes. In debug mode:\n- The core jumps to `DmHaltAddr`.\n- Additional debug CSRs (like `dcsr`, `dpc`) are used to store the return address and control debug behavior.\n- The core can single-step (`dscsr.singlestep` set) or respond to `EBREAK` depending on `dcsr` configuration.\n- An exception in debug mode causes a jump to `DmExceptionAddr` (instead of `mtvec`).\n- The core exits debug mode upon executing a `DRET` instruction.\n\n### 4.8 Performance Counters\nIf `MHPMCounterNum > 0`, the core includes that many 64‑bit (or `MHPMCounterWidth`‑bit) counters that count events such as:\n- Retired instructions\n- Instruction cache misses\n- Jumps (unconditional branches)\n- Branches (conditional)\n- Taken branches\n- Loads\n- Stores\n\nThese counters are accessible via the `mhpmcounter` CSRs and can be configured to count arbitrary events via `mhpmevent` CSRs (if implemented). The counters saturate or wrap at their maximum width (the implementer may choose). The core must increment the counters on the appropriate cycle when the event occurs.\n\n### 4.9 Core Busy and Clock Gating\nThe core shall automatically gate its main clock (except the debug unit) when it is idle. Idle means:\n- No instruction fetch pending or in progress.\n- No instructions in the pipeline.\n- No outstanding LSU transaction.\n- No interrupt or debug request waiting.\n\nWhen the core is idle, the clock enable output (internal) is deasserted to the clock gate. The core must wake up on any interrupt, debug request, or when `fetch_enable_i` is asserted after being low.\n\n### 4.10 RISC-V Formal Interface (Optional)\nWhen compiled with `RISCV_FORMAL` define, the core shall provide the `rvfi_*` output signals conforming to the RISC-V Formal Interface (RVFI) specification. These outputs capture the retirement of each instruction, including PC, instruction word, register reads and writes, memory access details, and trap information. The formal interface must be cycle-accurate for verification.\n\n## 5. Constraints and Assumptions\n\n- The instruction and data memory systems must be coherent (i.e., a store to a location that is also used for instruction fetch is not automatically visible; the core does not implement hardware coherence or store-to-load forwarding for instructions).\n- The interrupt input `irq_i` is level‑sensitive; after acknowledgment the system must deassert it; failure to do so may cause repeated interrupts.\n- The debug request `debug_req_i` should remain asserted until the core acknowledges it via the debug logic (no external handshake).\n- The `test_en_i` shall only be used for ATPG; during functional operation it must be low.\n- The reset signal `rst_ni` must be synchronous to the clock.\n\n## 6. Summary of Supported Instructions\n\n- **RV32I**: All base integer instructions (including `FENCE`, `ECALL`, `EBREAK`, `CSRRW`, etc.).\n- **RV32C** (implicit if not disabled): All compressed instructions as per the C extension, automatically detected and decoded. The core supports both aligned and halfword-aligned instructions.\n- **RV32M** (optional): `MUL`, `MULH`, `MULHSU`, `MULHU`, `DIV`, `DIVU`, `REM`, `REMU`.\n- **RV32E** (optional): Restricts register file to 16 registers; otherwise instruction behavior is identical to RV32I.\n\n## 7. Reference\n\nThis specification is based on the lowRISC/ibex RTL source (version as provided) and the official documentation for integration, instruction fetch, and load-store unit. The core’s behavior is intended to comply with the RISC-V Privileged and Unprivileged Specifications as of version 1.10 and 2.1, respectively.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2018 ETH Zurich and University of Bologna.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n////////////////////////////////////////////////////////////////////////////////\n// Engineer: Matthias Baer - baermatt@student.ethz.ch //\n// //\n// Additional contributions by: //\n// Igor Loi - igor.loi@unibo.it //\n// Andreas Traber - atraber@student.ethz.ch //\n// Sven Stucki - svstucki@student.ethz.ch //\n// Markus Wegmann - markus.wegmann@technokrat.ch //\n// Davide Schiavone - pschiavo@iis.ee.ethz.ch //\n// //\n// Design Name: Top level module //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Top level module of the RISC-V core. //\n// //\n////////////////////////////////////////////////////////////////////////////////\n\n`ifdef RISCV_FORMAL\n `define RVFI\n`endif\n\n/**\n * Top level module of the ibex RISC-V core\n */\nmodule ibex_core #(\n parameter int unsigned MHPMCounterNum = 0,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit RV32E = 0,\n parameter bit RV32M = 1,\n parameter int unsigned DmHaltAddr = 32'h1A110800,\n parameter int unsigned DmExceptionAddr = 32'h1A110808\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n input logic test_en_i, // enable all clock gates for testing\n\n // Core ID, Cluster ID and boot address are considered more or less static\n input logic [ 3:0] core_id_i,\n input logic [ 5:0] cluster_id_i,\n input logic [31:0] boot_addr_i,\n\n // Instruction memory interface\n output logic instr_req_o,\n input logic instr_gnt_i,\n input logic instr_rvalid_i,\n output logic [31:0] instr_addr_o,\n input logic [31:0] instr_rdata_i,\n\n // Data memory interface\n output logic data_req_o,\n input logic data_gnt_i,\n input logic data_rvalid_i,\n output logic data_we_o,\n output logic [3:0] data_be_o,\n output logic [31:0] data_addr_o,\n output logic [31:0] data_wdata_o,\n input logic [31:0] data_rdata_i,\n input logic data_err_i,\n\n // Interrupt inputs\n input logic irq_i, // level sensitive IR lines\n input logic [4:0] irq_id_i,\n output logic irq_ack_o, // irq ack\n output logic [4:0] irq_id_o,\n\n // Debug Interface\n input logic debug_req_i,\n\n // RISC-V Formal Interface\n // Does not comply with the coding standards of _i/_o suffixes, but follows\n // the convention of RISC-V Formal Interface Specification.\n`ifdef RVFI\n output logic rvfi_valid,\n output logic [63:0] rvfi_order,\n output logic [31:0] rvfi_insn,\n output logic rvfi_trap,\n output logic rvfi_halt,\n output logic rvfi_intr,\n output logic [ 1:0] rvfi_mode,\n output logic [ 4:0] rvfi_rs1_addr,\n output logic [ 4:0] rvfi_rs2_addr,\n output logic [31:0] rvfi_rs1_rdata,\n output logic [31:0] rvfi_rs2_rdata,\n output logic [ 4:0] rvfi_rd_addr,\n output logic [31:0] rvfi_rd_wdata,\n output logic [31:0] rvfi_pc_rdata,\n output logic [31:0] rvfi_pc_wdata,\n output logic [31:0] rvfi_mem_addr,\n output logic [ 3:0] rvfi_mem_rmask,\n output logic [ 3:0] rvfi_mem_wmask,\n output logic [31:0] rvfi_mem_rdata,\n output logic [31:0] rvfi_mem_wdata,\n`endif\n\n // CPU Control Signals\n input logic fetch_enable_i\n\n);\n\n import ibex_defines::*;\n\n // IF/ID signals\n logic instr_valid_id;\n logic [31:0] instr_rdata_id; // Instruction sampled inside IF stage\n logic [15:0] instr_rdata_c_id; // Compressed instruction sampled inside IF stage\n logic instr_is_compressed_id;\n logic illegal_c_insn_id; // Illegal compressed instruction sent to ID stage\n logic illegal_insn_id; // ID stage sees an illegal instruction\n logic [31:0] pc_if; // Program counter in IF stage\n logic [31:0] pc_id; // Program counter in ID stage\n\n logic clear_instr_valid;\n logic pc_set;\n pc_sel_e pc_mux_id; // Mux selector for next PC\n exc_pc_sel_e exc_pc_mux_id; // Mux selector for exception PC\n exc_cause_e exc_cause; // Exception cause\n\n logic lsu_load_err;\n logic lsu_store_err;\n\n // ID performance counter signals\n logic is_decoding;\n\n logic data_misaligned;\n logic [31:0] lsu_addr_last;\n\n // Jump and branch target and decision (EX->IF)\n logic [31:0] jump_target_ex;\n logic branch_decision;\n\n logic ctrl_busy;\n logic if_busy;\n logic lsu_busy;\n //core busy signals\n logic core_busy;\n logic core_ctrl_firstfetch, core_busy_int, core_busy_q;\n\n // ALU Control\n alu_op_e alu_operator_ex;\n logic [31:0] alu_operand_a_ex;\n logic [31:0] alu_operand_b_ex;\n\n logic [31:0] alu_adder_result_ex; // Used to forward computed address to LSU\n logic [31:0] regfile_wdata_ex;\n\n // Multiplier Control\n logic mult_en_ex;\n logic div_en_ex;\n md_op_e multdiv_operator_ex;\n logic [1:0] multdiv_signed_mode_ex;\n logic [31:0] multdiv_operand_a_ex;\n logic [31:0] multdiv_operand_b_ex;\n\n // CSR control\n logic csr_access_ex;\n csr_op_e csr_op_ex;\n\n logic csr_access;\n csr_op_e csr_op;\n csr_num_e csr_addr;\n logic [31:0] csr_rdata;\n logic [31:0] csr_wdata;\n logic illegal_csr_insn_id; // CSR access to non-existent register,\n // with wrong priviledge level,\n // or missing write permissions\n\n // Data Memory Control\n logic data_we_ex;\n logic [1:0] data_type_ex;\n logic data_sign_ext_ex;\n logic [1:0] data_reg_offset_ex;\n logic data_req_ex;\n logic [31:0] data_wdata_ex;\n logic [31:0] regfile_wdata_lsu;\n\n // stall control\n logic halt_if;\n logic id_ready;\n logic ex_ready;\n\n logic if_valid;\n logic id_valid;\n\n logic data_valid_lsu;\n\n // Signals between instruction core interface and pipe (if and id stages)\n logic instr_req_int; // Id stage asserts a req to instruction core interface\n\n // Interrupts\n logic m_irq_enable;\n logic [31:0] csr_mepc, csr_depc;\n\n logic csr_save_if;\n logic csr_save_id;\n logic csr_restore_mret_id;\n logic csr_restore_dret_id;\n logic csr_save_cause;\n logic [31:0] csr_mtvec;\n logic [31:0] csr_mtval;\n\n // debug mode and dcsr configuration\n dbg_cause_e debug_cause;\n logic debug_csr_save;\n logic debug_single_step;\n logic debug_ebreakm;\n\n // performance counter related signals\n logic insn_ret;\n logic perf_imiss;\n logic perf_jump;\n logic perf_branch;\n logic perf_tbranch;\n logic perf_load;\n logic perf_store;\n\n // RISC-V Formal Interface signals\n`ifdef RVFI\n logic [31:0] rvfi_insn_opcode;\n logic rvfi_valid_int;\n logic [4:0] rvfi_rs1_addr_id;\n logic [4:0] rvfi_rs2_addr_id;\n logic [31:0] rvfi_rs1_data_d;\n logic [31:0] rvfi_rs1_data_id;\n logic [31:0] rvfi_rs1_data_q;\n logic [31:0] rvfi_rs2_data_d;\n logic [31:0] rvfi_rs2_data_id;\n logic [31:0] rvfi_rs2_data_q;\n logic [4:0] rvfi_rd_addr_id;\n logic [4:0] rvfi_rd_addr_q;\n logic [4:0] rvfi_rd_addr_d;\n logic [31:0] rvfi_rd_wdata_id;\n logic [31:0] rvfi_rd_wdata_d;\n logic [31:0] rvfi_rd_wdata_q;\n logic rvfi_rd_we_id;\n logic rvfi_insn_new_d;\n logic rvfi_insn_new_q;\n logic rvfi_insn_clear_d;\n logic rvfi_insn_clear_q;\n logic rvfi_changed_insn;\n logic rvfi_changed_pc;\n logic [31:0] rvfi_pc_id_q;\n logic [3:0] rvfi_mem_mask_int;\n logic [31:0] rvfi_mem_rdata_d;\n logic [31:0] rvfi_mem_rdata_q;\n logic [31:0] rvfi_mem_wdata_d;\n logic [31:0] rvfi_mem_wdata_q;\n logic [31:0] rvfi_mem_addr_d;\n logic [31:0] rvfi_mem_addr_q;\n`endif\n\n //////////////////////\n // Clock management //\n //////////////////////\n\n logic clk;\n\n logic clock_en;\n\n // if we are sleeping on a barrier let's just wait on the instruction\n // interface to finish loading instructions\n assign core_busy_int = if_busy | ctrl_busy | lsu_busy;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n core_busy_q <= 1'b0;\n end else begin\n core_busy_q <= core_busy_int;\n end\n end\n\n assign core_busy = core_ctrl_firstfetch ? 1'b1 : core_busy_q;\n\n assign clock_en = core_busy | irq_i | debug_req_i;\n\n // main clock gate of the core\n // generates all clocks except the one for the debug unit which is\n // independent\n prim_clock_gating core_clock_gate_i (\n .clk_i ( clk_i ),\n .en_i ( clock_en ),\n .test_en_i ( test_en_i ),\n .clk_o ( clk )\n );\n\n //////////////\n // IF stage //\n //////////////\n\n ibex_if_stage #(\n .DmHaltAddr ( DmHaltAddr ),\n .DmExceptionAddr ( DmExceptionAddr )\n ) if_stage_i (\n .clk_i ( clk ),\n .rst_ni ( rst_ni ),\n\n .boot_addr_i ( boot_addr_i ),\n .req_i ( instr_req_int ), // instruction request control\n\n // instruction cache interface\n .instr_req_o ( instr_req_o ),\n .instr_addr_o ( instr_addr_o ),\n .instr_gnt_i ( instr_gnt_i ),\n .instr_rvalid_i ( instr_rvalid_i ),\n .instr_rdata_i ( instr_rdata_i ),\n\n // outputs to ID stage\n .instr_valid_id_o ( instr_valid_id ),\n .instr_rdata_id_o ( instr_rdata_id ),\n .instr_rdata_c_id_o ( instr_rdata_c_id ),\n .instr_is_compressed_id_o ( instr_is_compressed_id ),\n .illegal_c_insn_id_o ( illegal_c_insn_id ),\n .pc_if_o ( pc_if ),\n .pc_id_o ( pc_id ),\n\n // control signals\n .clear_instr_valid_i ( clear_instr_valid ),\n .pc_set_i ( pc_set ),\n .pc_mux_i ( pc_mux_id ),\n .exc_pc_mux_i ( exc_pc_mux_id ),\n .exc_cause ( exc_cause ),\n\n // jump targets\n .jump_target_ex_i ( jump_target_ex ),\n\n // CSRs\n .csr_mepc_i ( csr_mepc ), // exception return address\n .csr_depc_i ( csr_depc ), // debug return address\n .csr_mtvec_o ( csr_mtvec ), // trap-vector base address\n\n // pipeline stalls\n .halt_if_i ( halt_if ),\n .id_ready_i ( id_ready ),\n .if_valid_o ( if_valid ),\n\n .if_busy_o ( if_busy ),\n .perf_imiss_o ( perf_imiss )\n );\n\n\n //////////////\n // ID stage //\n //////////////\n\n ibex_id_stage #(\n .RV32E ( RV32E ),\n .RV32M ( RV32M )\n ) id_stage_i (\n .clk_i ( clk ),\n .rst_ni ( rst_ni ),\n\n .test_en_i ( test_en_i ),\n\n // Processor Enable\n .fetch_enable_i ( fetch_enable_i ),\n .ctrl_busy_o ( ctrl_busy ),\n .core_ctrl_firstfetch_o ( core_ctrl_firstfetch ),\n .is_decoding_o ( is_decoding ),\n .illegal_insn_o ( illegal_insn_id ),\n\n // Interface to instruction memory\n .instr_valid_i ( instr_valid_id ),\n .instr_rdata_i ( instr_rdata_id ),\n .instr_rdata_c_i ( instr_rdata_c_id ),\n .instr_is_compressed_i ( instr_is_compressed_id ),\n .instr_req_o ( instr_req_int ),\n\n // Jumps and branches\n .branch_decision_i ( branch_decision ),\n\n // IF and ID control signals\n .clear_instr_valid_o ( clear_instr_valid ),\n .pc_set_o ( pc_set ),\n .pc_mux_o ( pc_mux_id ),\n .exc_pc_mux_o ( exc_pc_mux_id ),\n .exc_cause_o ( exc_cause ),\n\n .illegal_c_insn_i ( illegal_c_insn_id ),\n\n .pc_id_i ( pc_id ),\n\n // Stalls\n .halt_if_o ( halt_if ),\n\n .id_ready_o ( id_ready ),\n .ex_ready_i ( ex_ready ),\n\n .id_valid_o ( id_valid ),\n\n .alu_operator_ex_o ( alu_operator_ex ),\n .alu_operand_a_ex_o ( alu_operand_a_ex ),\n .alu_operand_b_ex_o ( alu_operand_b_ex ),\n\n .mult_en_ex_o ( mult_en_ex ),\n .div_en_ex_o ( div_en_ex ),\n .multdiv_operator_ex_o ( multdiv_operator_ex ),\n .multdiv_signed_mode_ex_o ( multdiv_signed_mode_ex ),\n .multdiv_operand_a_ex_o ( multdiv_operand_a_ex ),\n .multdiv_operand_b_ex_o ( multdiv_operand_b_ex ),\n\n // CSR ID/EX\n .csr_access_ex_o ( csr_access_ex ),\n .csr_op_ex_o ( csr_op_ex ),\n .csr_save_if_o ( csr_save_if ), // control signal to save pc\n .csr_save_id_o ( csr_save_id ), // control signal to save pc\n .csr_restore_mret_id_o ( csr_restore_mret_id ), // control signal to restore pc\n .csr_restore_dret_id_o ( csr_restore_dret_id ), // control signal to restore pc\n .csr_save_cause_o ( csr_save_cause ),\n .csr_mtval_o ( csr_mtval ),\n .illegal_csr_insn_i ( illegal_csr_insn_id ),\n\n // LSU\n .data_req_ex_o ( data_req_ex ), // to load store unit\n .data_we_ex_o ( data_we_ex ), // to load store unit\n .data_type_ex_o ( data_type_ex ), // to load store unit\n .data_sign_ext_ex_o ( data_sign_ext_ex ), // to load store unit\n .data_reg_offset_ex_o ( data_reg_offset_ex ), // to load store unit\n .data_wdata_ex_o ( data_wdata_ex ), // to load store unit\n\n .data_misaligned_i ( data_misaligned ),\n .lsu_addr_last_i ( lsu_addr_last ),\n\n .lsu_load_err_i ( lsu_load_err ),\n .lsu_store_err_i ( lsu_store_err ),\n\n // Interrupt Signals\n .irq_i ( irq_i ), // incoming interrupts\n .irq_id_i ( irq_id_i ),\n .m_irq_enable_i ( m_irq_enable ),\n .irq_ack_o ( irq_ack_o ),\n .irq_id_o ( irq_id_o ),\n\n // Debug Signal\n .debug_cause_o ( debug_cause ),\n .debug_csr_save_o ( debug_csr_save ),\n .debug_req_i ( debug_req_i ),\n .debug_single_step_i ( debug_single_step ),\n .debug_ebreakm_i ( debug_ebreakm ),\n\n // write data to commit in the register file\n .regfile_wdata_lsu_i ( regfile_wdata_lsu ),\n .regfile_wdata_ex_i ( regfile_wdata_ex ),\n .csr_rdata_i ( csr_rdata ),\n\n`ifdef RVFI\n .rfvi_reg_raddr_ra_o ( rvfi_rs1_addr_id ),\n .rfvi_reg_rdata_ra_o ( rvfi_rs1_data_id ),\n .rfvi_reg_raddr_rb_o ( rvfi_rs2_addr_id ),\n .rfvi_reg_rdata_rb_o ( rvfi_rs2_data_id ),\n .rfvi_reg_waddr_rd_o ( rvfi_rd_addr_id ),\n .rfvi_reg_wdata_rd_o ( rvfi_rd_wdata_id ),\n .rfvi_reg_we_o ( rvfi_rd_we_id ),\n`endif\n\n // Performance Counters\n .perf_jump_o ( perf_jump ),\n .perf_branch_o ( perf_branch ),\n .perf_tbranch_o ( perf_tbranch )\n );\n\n\n ibex_ex_block #(\n .RV32M ( RV32M )\n ) ex_block_i (\n .clk_i ( clk ),\n .rst_ni ( rst_ni ),\n // Alu signals from ID stage\n //TODO: hot encoding\n .alu_operator_i ( alu_operator_ex ),\n .multdiv_operator_i ( multdiv_operator_ex ),\n .alu_operand_a_i ( alu_operand_a_ex ),\n .alu_operand_b_i ( alu_operand_b_ex ),\n\n // Multipler\n .mult_en_i ( mult_en_ex ),\n .div_en_i ( div_en_ex ),\n .multdiv_signed_mode_i ( multdiv_signed_mode_ex),\n .multdiv_operand_a_i ( multdiv_operand_a_ex ),\n .multdiv_operand_b_i ( multdiv_operand_b_ex ),\n .alu_adder_result_ex_o ( alu_adder_result_ex ), // from ALU to LSU\n .regfile_wdata_ex_o ( regfile_wdata_ex ),\n\n // To IF: Jump and branch target and decision\n .jump_target_o ( jump_target_ex ),\n .branch_decision_o ( branch_decision ),\n\n .lsu_en_i ( data_req_ex ),\n .lsu_ready_ex_i ( data_valid_lsu ),\n .ex_ready_o ( ex_ready )\n );\n\n /////////////////////\n // Load/store unit //\n /////////////////////\n\n ibex_load_store_unit load_store_unit_i (\n .clk_i ( clk ),\n .rst_ni ( rst_ni ),\n\n //output to data memory\n .data_req_o ( data_req_o ),\n .data_gnt_i ( data_gnt_i ),\n .data_rvalid_i ( data_rvalid_i ),\n .data_err_i ( data_err_i ),\n\n .data_addr_o ( data_addr_o ),\n .data_we_o ( data_we_o ),\n .data_be_o ( data_be_o ),\n .data_wdata_o ( data_wdata_o ),\n .data_rdata_i ( data_rdata_i ),\n\n // signal from ex stage\n .data_we_ex_i ( data_we_ex ),\n .data_type_ex_i ( data_type_ex ),\n .data_wdata_ex_i ( data_wdata_ex ),\n .data_reg_offset_ex_i ( data_reg_offset_ex ),\n .data_sign_ext_ex_i ( data_sign_ext_ex ),\n\n .data_rdata_ex_o ( regfile_wdata_lsu ),\n .data_req_ex_i ( data_req_ex ),\n\n .adder_result_ex_i ( alu_adder_result_ex),\n\n .data_misaligned_o ( data_misaligned ),\n .addr_last_o ( lsu_addr_last ),\n\n // exception signals\n .load_err_o ( lsu_load_err ),\n .store_err_o ( lsu_store_err ),\n\n // control signals\n .data_valid_o ( data_valid_lsu ),\n .lsu_update_addr_o ( ),\n .busy_o ( lsu_busy )\n );\n\n\n /////////////////////////////////////////\n // CSRs (Control and Status Registers) //\n /////////////////////////////////////////\n\n assign csr_access = csr_access_ex;\n assign csr_wdata = alu_operand_a_ex;\n assign csr_op = csr_op_ex;\n assign csr_addr = csr_num_e'(csr_access_ex ? alu_operand_b_ex[11:0] : 12'b0);\n\n assign perf_load = data_req_o & data_gnt_i & (~data_we_o);\n assign perf_store = data_req_o & data_gnt_i & data_we_o;\n\n // An instruction has been executed and retired if the ID stage gets a new instruction and\n // the previously seen instruction was valid.\n assign insn_ret = if_valid & ~illegal_insn_id;\n\n ibex_cs_registers #(\n .MHPMCounterNum ( MHPMCounterNum ),\n .MHPMCounterWidth ( MHPMCounterWidth ),\n .RV32E ( RV32E ),\n .RV32M ( RV32M )\n ) cs_registers_i (\n .clk_i ( clk ),\n .rst_ni ( rst_ni ),\n\n // Core and Cluster ID from outside\n .core_id_i ( core_id_i ),\n .cluster_id_i ( cluster_id_i ),\n\n\n // Interface to CSRs (SRAM like)\n .csr_access_i ( csr_access ),\n .csr_addr_i ( csr_addr ),\n .csr_wdata_i ( csr_wdata ),\n .csr_op_i ( csr_op ),\n .csr_rdata_o ( csr_rdata ),\n\n // Interrupt related control signals\n .m_irq_enable_o ( m_irq_enable ),\n .csr_mepc_o ( csr_mepc ),\n\n // debug\n .csr_depc_o ( csr_depc ),\n .debug_cause_i ( debug_cause ),\n .debug_csr_save_i ( debug_csr_save ),\n .debug_single_step_o ( debug_single_step ),\n .debug_ebreakm_o ( debug_ebreakm ),\n\n .pc_if_i ( pc_if ),\n .pc_id_i ( pc_id ),\n\n .csr_save_if_i ( csr_save_if ),\n .csr_save_id_i ( csr_save_id ),\n .csr_restore_mret_i ( csr_restore_mret_id ),\n .csr_restore_dret_i ( csr_restore_dret_id ),\n .csr_save_cause_i ( csr_save_cause ),\n .csr_mtvec_i ( csr_mtvec ),\n .csr_mcause_i ( exc_cause ),\n .csr_mtval_i ( csr_mtval ),\n .illegal_csr_insn_o ( illegal_csr_insn_id ),\n\n // performance counter related signals\n .insn_ret_i ( insn_ret ),\n .id_valid_i ( id_valid ),\n .instr_is_compressed_i ( instr_is_compressed_id ),\n .is_decoding_i ( is_decoding ),\n\n .imiss_i ( perf_imiss ),\n .pc_set_i ( pc_set ),\n .jump_i ( perf_jump ),\n .branch_i ( perf_branch ),\n .branch_taken_i ( perf_tbranch ),\n .mem_load_i ( perf_load ),\n .mem_store_i ( perf_store ),\n .lsu_busy_i ( lsu_busy )\n );\n\n`ifdef RVFI\n always_ff @(posedge clk) begin\n rvfi_halt <= '0;\n rvfi_trap <= '0;\n rvfi_intr <= irq_ack_o;\n rvfi_order <= rst_ni ? rvfi_order + rvfi_valid : '0;\n rvfi_insn <= rvfi_insn_opcode;\n rvfi_mode <= PRIV_LVL_M;\n rvfi_rs1_addr <= rvfi_rs1_addr_id;\n rvfi_rs2_addr <= rvfi_rs2_addr_id;\n rvfi_pc_rdata <= pc_id;\n rvfi_mem_rmask <= rvfi_mem_mask_int;\n rvfi_mem_wmask <= data_we_o ? rvfi_mem_mask_int : 4'b0000;\n rvfi_valid <= rvfi_valid_int;\n rvfi_rs1_rdata <= rvfi_rs1_data_d;\n rvfi_rs2_rdata <= rvfi_rs2_data_d;\n end\n\n assign rvfi_pc_wdata = pc_id;\n assign rvfi_rd_wdata = rvfi_rd_wdata_q;\n assign rvfi_rd_addr = rvfi_rd_addr_q;\n assign rvfi_mem_rdata = rvfi_mem_rdata_q;\n assign rvfi_mem_wdata = rvfi_mem_wdata_q;\n assign rvfi_mem_addr = rvfi_mem_addr_q;\n\n // Keep the mem data stable for each instruction cycle\n always_comb begin\n if (rvfi_insn_new_d) begin\n rvfi_mem_addr_d = alu_adder_result_ex;\n rvfi_mem_rdata_d = regfile_wdata_lsu;\n rvfi_mem_wdata_d = data_wdata_ex;\n end else begin\n rvfi_mem_addr_d = rvfi_mem_addr_q;\n rvfi_mem_rdata_d = rvfi_mem_rdata_q;\n rvfi_mem_wdata_d = rvfi_mem_wdata_q;\n end\n end\n always_ff @(posedge clk) begin\n rvfi_mem_addr_q <= rvfi_mem_addr_d;\n rvfi_mem_rdata_q <= rvfi_mem_rdata_d;\n rvfi_mem_wdata_q <= rvfi_mem_wdata_d;\n end\n // Byte enable based on data type\n always_comb begin\n unique case (data_type_ex)\n 2'b00: rvfi_mem_mask_int = 4'b1111;\n 2'b01: rvfi_mem_mask_int = 4'b0011;\n 2'b10: rvfi_mem_mask_int = 4'b0001;\n default: rvfi_mem_mask_int = 4'b0000;\n endcase\n end\n\n assign rvfi_valid_int = id_valid && if_valid && !illegal_c_insn_id;\n\n always_comb begin\n if (instr_is_compressed_id) begin\n rvfi_insn_opcode = {16'b0, instr_rdata_c_id};\n end else begin\n rvfi_insn_opcode = instr_rdata_id;\n end\n end\n\n // Source register data are kept stable for each instruction cycle\n always_comb begin\n if (rvfi_insn_new_d) begin\n rvfi_rs1_data_d = rvfi_rs1_data_id;\n rvfi_rs2_data_d = rvfi_rs2_data_id;\n end else begin\n rvfi_rs1_data_d = rvfi_rs1_data_q;\n rvfi_rs2_data_d = rvfi_rs2_data_q;\n end\n end\n always_ff @(posedge clk) begin\n rvfi_rs1_data_q <= rvfi_rs1_data_d;\n rvfi_rs2_data_q <= rvfi_rs2_data_d;\n end\n\n // RD write register is refreshed only once per cycle and\n // then it is kept stable for the cycle.\n always_comb begin\n if (rvfi_insn_new_d) begin\n if (!rvfi_rd_we_id) begin\n rvfi_rd_addr_d = '0;\n rvfi_rd_wdata_d = '0;\n rvfi_insn_clear_d = 1'b0;\n end else begin\n rvfi_rd_addr_d = rvfi_rd_addr_id;\n if (!rvfi_rd_addr_id) begin\n rvfi_rd_wdata_d = '0;\n end else begin\n rvfi_rd_wdata_d = rvfi_rd_wdata_id;\n end\n rvfi_insn_clear_d = 1'b1;\n end\n end else begin\n rvfi_rd_addr_d = rvfi_rd_addr_q;\n rvfi_rd_wdata_d = rvfi_rd_wdata_q;\n rvfi_insn_clear_d = 1'b0;\n end\n end\n always_ff @(posedge clk) begin\n rvfi_insn_clear_q <= rvfi_insn_clear_d;\n rvfi_rd_addr_q <= rvfi_rd_addr_d;\n rvfi_rd_wdata_q <= rvfi_rd_wdata_d;\n end\n\n // New instruction signalling based on changes of\n // instruction data, program counter and valid signal\n always_comb begin\n if (rvfi_changed_insn || rvfi_changed_pc || rvfi_valid ) begin\n rvfi_insn_new_d = 1'b1;\n end else if (rvfi_insn_clear_q) begin\n rvfi_insn_new_d = 1'b0;\n end else begin\n rvfi_insn_new_d = rvfi_insn_new_q;\n end\n end\n always_ff @(posedge clk) begin\n rvfi_insn_new_q <= rvfi_insn_new_d;\n end\n\n // Change in instruction code\n assign rvfi_changed_insn = rvfi_insn != rvfi_insn_opcode;\n\n // Change in program counter\n always_ff @(posedge clk) begin\n rvfi_pc_id_q <= pc_id;\n end\n assign rvfi_changed_pc = rvfi_pc_id_q != pc_id;\n`endif\n\n\n`ifndef VERILATOR\n`ifdef TRACE_EXECUTION\n ibex_tracer ibex_tracer_i (\n .clk_i ( clk_i ), // always-on clk for tracer\n .rst_ni ( rst_ni ),\n\n .fetch_enable_i ( fetch_enable_i ),\n .core_id_i ( core_id_i ),\n .cluster_id_i ( cluster_id_i ),\n\n .pc_i ( id_stage_i.pc_id_i ),\n .instr_i ( id_stage_i.instr ),\n .compressed_i ( id_stage_i.instr_is_compressed_i ),\n .id_valid_i ( id_stage_i.id_valid_o ),\n .is_decoding_i ( id_stage_i.is_decoding_o ),\n .is_branch_i ( id_stage_i.branch_in_id ),\n .branch_taken_i ( id_stage_i.branch_set_q ),\n .pipe_flush_i ( id_stage_i.controller_i.pipe_flush_i ),\n .mret_insn_i ( id_stage_i.controller_i.mret_insn_i ),\n .dret_insn_i ( id_stage_i.controller_i.dret_insn_i ),\n .ecall_insn_i ( id_stage_i.controller_i.ecall_insn_i ),\n .ebrk_insn_i ( id_stage_i.controller_i.ebrk_insn_i ),\n .csr_status_i ( id_stage_i.controller_i.csr_status_i ),\n .rs1_value_i ( id_stage_i.operand_a_fw_id ),\n .rs2_value_i ( id_stage_i.operand_b_fw_id ),\n\n .lsu_value_i ( data_wdata_ex ),\n\n .ex_reg_addr_i ( id_stage_i.regfile_waddr_mux ),\n .ex_reg_we_i ( id_stage_i.regfile_we_mux ),\n .ex_reg_wdata_i ( id_stage_i.regfile_wdata_mux ),\n .data_valid_lsu_i ( data_valid_lsu ),\n .ex_data_addr_i ( data_addr_o ),\n .ex_data_req_i ( data_req_o ),\n .ex_data_gnt_i ( data_gnt_i ),\n .ex_data_we_i ( data_we_o ),\n\n .ex_data_wdata_i ( data_wdata_o ),\n\n .lsu_reg_wdata_i ( regfile_wdata_lsu ),\n\n .imm_i_type_i ( id_stage_i.imm_i_type ),\n .imm_s_type_i ( id_stage_i.imm_s_type ),\n .imm_b_type_i ( id_stage_i.imm_b_type ),\n .imm_u_type_i ( id_stage_i.imm_u_type ),\n .imm_j_type_i ( id_stage_i.imm_j_type ),\n .zimm_rs1_type_i ( id_stage_i.zimm_rs1_type )\n );\n`endif\n`endif\n\nendmodule\n", "pr_title": "Switch to new signal name in tracer instantiation", "pr_body": "This got forgotten when renaming the signal inside ID stage in\r\ncommit b22a6a10defc7bad31dda7d8a33c7145d1a79a3b.\r\n\r\nThis fixes #112 .", "fix_patch": "diff --git a/rtl/ibex_core.sv b/rtl/ibex_core.sv\nindex c4a5acb925..450b5c8859 100644\n--- a/rtl/ibex_core.sv\n+++ b/rtl/ibex_core.sv\n@@ -763,7 +763,7 @@ module ibex_core #(\n \n .pc_i ( id_stage_i.pc_id_i ),\n .instr_i ( id_stage_i.instr ),\n- .compressed_i ( id_stage_i.is_compressed_i ),\n+ .compressed_i ( id_stage_i.instr_is_compressed_i ),\n .id_valid_i ( id_stage_i.id_valid_o ),\n .is_decoding_i ( id_stage_i.is_decoding_o ),\n .is_branch_i ( id_stage_i.branch_in_id ),\n"}
{"repo": "lowRISC/ibex", "pr_id": 166, "review_result": {"passed": false, "checks": {"describes_correct_behavior": true, "no_patch_leakage": true, "sufficient_for_diagnosis": false}, "reasoning": "The generated specification does not include explicit behavioral assertions for the perpetual illegal branch condition detection and the illegal detection when instr[28] is set for register-register ALU operations, which are the key fixes in the patch."}, "generated_spec": "# Behavioral Design Specification: ibex_decoder\n\n## Overview\nThe decoder module is the instruction decoder for the Ibex RISC-V core. It takes a 32-bit instruction word from the IF/ID pipeline register and generates all control signals required by subsequent pipeline stages (ALU, load/store unit, register file, CSR unit, multiply/divide unit, branch/jump logic). It also identifies illegal instructions and outputs exception triggers for `ecall`, `ebreak`, `mret`, `dret`, and `wfi`.\n\nThe decoder supports:\n- RV32I base instruction set\n- RV32M extension (multiply/divide) – enabled by a parameter\n- RV32E embedded extension (reduced register file) – enabled by a parameter\n- RISC-V privilege level 1.11 CSRs\n- Compressed instruction extension (via an external illegal compressed instruction indicator)\n\nThe decoder must operate in a single combinatorial block; all outputs are valid within the same cycle as the input instruction.\n\n## Inputs\n- **Instruction word** (32 bits) from the IF/ID pipeline register.\n- **Instruction new** indication: asserts when a new instruction enters the decode stage. Used to differentiate the first (address calculation) and second (result write-back) cycles for jumps (JAL/JALR) and branches.\n- **Illegal compressed instruction**: external flag indicating that a compressed instruction (16‑bit) failed its own decode. When asserted, the decoder must treat the instruction as illegal regardless of its own decoding.\n\n## Outputs\nThe decoder produces the following categories of outputs:\n\n### Register File Control\n- Read addresses for two source registers (rs1, rs2).\n- Write address for destination register (rd).\n- Write enable for the register file.\n- Selection of the data to be written back: from ALU result (EX), from load data (LSU), or from CSR read data.\n\n### Immediate Generation\n- Five sign- or zero-extended immediates for I‑type, S‑type, B‑type, U‑type, and J‑type instructions.\n- A zero-extended immediate from the rs1 field for CSR immediate operations (zimm).\n- Selection muxes for operand A and B of the ALU: these choose between a register value, the current PC, an immediate, or zero.\n\n### ALU Control\n- ALU operation (add, sub, slt, sltu, xor, or, and, sll, srl, sra, eq, ne, lt, ge, ltu, geu).\n- Selection muxes for ALU operand A and operand B.\n\n### Multiply/Divide Control\n- Enable signals for multiply and divide.\n- Operation type (MUL, MULH, DIV, REM, etc.).\n- Signed mode indication (both signed, both unsigned, mixed).\n\n### Load/Store Control\n- Data request enable.\n- Write enable (load vs store).\n- Data size (byte, halfword, word).\n- Sign extension flag for loads.\n- Byte offset within the register for stores.\n\n### Branch/Jump Control\n- Branch in decode indicator (tells the pipeline that a branch is being evaluated).\n- Jump in decode indicator (tells the pipeline that a jump is being calculated).\n- Jump set signal (used to redirect the PC in the first cycle of a jump).\n\n### CSR Control\n- CSR access enable.\n- CSR operation (read, write, set, clear).\n- CSR status flush indicator for accesses to `mstatus`, `dcsr`, `dpc`, `dscratch0`, `dscratch1`.\n\n### Exception / Trap Flags\n- Illegal instruction flag.\n- `ecall` instruction detected.\n- `ebreak` instruction detected.\n- `mret` instruction detected.\n- `dret` instruction detected.\n- `wfi` instruction detected.\n\n## Functional Behavior\n\n### 1. Immediate Extraction\nFor every instruction, the decoder must extract the appropriate immediate fields from the instruction word and sign-extend or zero-extend them to 32 bits. The following immediates are always produced:\n\n- **I-type**: 12‑bit signed immediate (bits 31:20 sign-extended).\n- **S-type**: 12‑bit signed immediate (bits 31:25 and 11:7 concatenated, sign-extended).\n- **B-type**: 13‑bit signed immediate (bits 31, 7, 30:25, 11:8 concatenated with a trailing 0, sign-extended).\n- **U-type**: 20‑bit unsigned immediate (bits 31:12 placed in the upper 20 bits, lower 12 bits zero).\n- **J-type**: 21‑bit signed immediate (bits 19:12, 20, 30:21 concatenated with a trailing 0, sign-extended).\n- **zimm**: 5‑bit zero‑extended immediate from the rs1 field (bits 19:15 zero‑extended).\n\nThe usage of these immediates is selected by the `imm_a_mux_sel` and `imm_b_mux_sel` mux controls. The decoder must route the appropriate immediate to the ALU operand B mux (IMM_B_I, IMM_B_S, IMM_B_B, IMM_B_U, IMM_B_J, IMM_B_INCR_PC) and to the operand A mux (IMM_A_ZERO, IMM_A_Z).\n\n### 2. Register File Access\nThe decoder must extract the three register fields from the instruction:\n\n- Source register 1 address (rs1) from bits 19:15.\n- Source register 2 address (rs2) from bits 24:20.\n- Destination register address (rd) from bits 11:7.\n\nThe register file write enable and write address are determined by the decoded instruction type. For instructions that write to the register file (e.g., ALU ops, loads, LUI, AUIPC, JAL, JALR, CSR reads), write enable must be asserted. For jumps, the write enable is **deasserted in the first cycle** (address calculation) and **asserted in the second cycle** (PC+4 write‑back). The decoder must also enforce that CSR‑related instructions that write a value of zero to the CSR (via immediate or x0) are treated as reads only (CSR write‑enable is suppressed).\n\n### 3. ALU Operations\nThe decoder selects the ALU operation based on the opcode and funct3/funct7 fields.\n\n- **LUI**: ALU adds zero to the U‑type immediate (effectively passes the immediate forward).\n- **AUIPC**: ALU adds U‑type immediate to the current PC.\n- **OP_IMM**: ALU performs the operation specified by funct3 (ADD, SLT, SLTU, XOR, OR, AND). For shifts (SLL, SRL, SRA) the funct7 field must be checked: only shift operations with funct7 == 0x00 (SLL, SRL) or 0x20 (SRA) are legal; otherwise the instruction is illegal.\n- **OP**: For RV32I, the ALU operation is determined by funct7 and funct3 (ADD, SUB, SLT, SLTU, XOR, OR, AND, SLL, SRL, SRA). Any instruction with bit 31 set (indicating an invalid funct7) must be illegal. The ALU operation is also used for branches (EQ, NE, LT, GE, LTU, GEU) and jumps (ADD for target calculation).\n- **Load/Store**: ALU must perform ADD to compute the effective address using either an immediate offset (I‑type for loads, S‑type for stores) or a register offset (for the “reg‑reg” load encoding).\n- **Branches**: ALU first evaluates the branch condition (comparison between rs1 and rs2) and then later calculates the target address (PC + B‑immediate). The ALU operation for condition evaluation is selected based on funct3.\n- **JAL/JALR**: In the first cycle, ALU adds the relevant immediate to PC (JAL) or rs1 (JALR) to compute the jump target. In the second cycle, ALU adds 4 to the current PC to produce the return address.\n\n### 4. Branch and Jump Control\n- **Branches**: When a branch instruction (opcode = OPCODE_BRANCH) is decoded, `branch_in_dec` must be asserted. In the cycle when `instr_new` is asserted, the ALU evaluates the branch condition (comparison of rs1 and rs2). In the following cycle (when `instr_new` is deasserted), the ALU calculates the target address.\n- **JAL**: `jump_in_dec` is asserted. In the first cycle (`instr_new` asserted), the ALU calculates the jump target (PC + J‑imm) and `jump_set` is asserted to redirect the fetch. In the second cycle, the ALU calculates PC+4 for writing back to rd. Register write enable is asserted only in the second cycle.\n- **JALR**: Similar to JAL, but the jump target is computed as (rs1 + I‑imm). The low‑order bit of the calculated target must be forced to 0 (as per the RISC‑V specification). Any funct3 value other than 0x0 is illegal.\n\n### 5. Load and Store Instructions\n- **Store**: The decoder must enable `data_req` and set `data_we` to 1. The ALU computes the store address (rs1 + offset). The offset can be either an S‑type immediate (when bit 14 of the instruction is 0) or a register offset (when bit 14 is 1 – note: this is not supported and must be treated as illegal). The data size is encoded in bits 13:12: 00 → byte (SB), 01 → halfword (SH), 10 → word (SW). Bits 13:12 == 11 is illegal. The decoder must also output the byte offset (`data_reg_offset`) for partial‑width stores (derived from the two least‑significant address bits).\n- **Load**: The decoder must enable `data_req` and set `regfile_we` to 1. The ALU computes the load address (rs1 + offset). By default the offset is an I‑type immediate. A second encoding (funct3 == 111) uses rs2 as the offset (register‑register load). For that encoding, the sign/zero extension and size are determined by a different instruction field (bits 31:25). The size encoding for both standard and reg‑reg loads: 00 → word (LW), 01 → halfword (LH/LHU), 10 → byte (LB/LBU). Sign extension is controlled by the highest order bit of the funct3 field (bit 14 for standard loads, bit 30 for reg‑reg loads); a 0 indicates signed, a 1 indicates unsigned (zero extension). Any load with funct3 == 011 (LD) must be illegal on RV32.\n\n### 6. Multiply/Divide Instructions (RV32M)\nWhen the RV32M parameter is enabled, the decoder must recognize the 8 multiply/divide instructions within the OP opcode (funct7 = 0x01). For each, it must set `mult_en` or `div_en` accordingly and select the appropriate operation and signed mode. When RV32M is disabled, these instructions must cause an illegal instruction exception.\n\n- MUL: signed x signed, lower 32 bits → `MD_OP_MULL`, signed_mode = 00.\n- MULH: signed x signed, upper 32 bits → `MD_OP_MULH`, signed_mode = 11.\n- MULHSU: signed x unsigned, upper 32 bits → `MD_OP_MULH`, signed_mode = 01.\n- MULHU: unsigned x unsigned, upper 32 bits → `MD_OP_MULH`, signed_mode = 00.\n- DIV: signed division → `MD_OP_DIV`, signed_mode = 11.\n- DIVU: unsigned division → `MD_OP_DIV`, signed_mode = 00.\n- REM: signed remainder → `MD_OP_REM`, signed_mode = 11.\n- REMU: unsigned remainder → `MD_OP_REM`, signed_mode = 00.\n\n### 7. CSR Instructions\nInstructions with opcode = SYSTEM and funct3 != 0 are CSR accesses. The decoder must:\n- Enable `csr_access`.\n- Set `regfile_wdata_sel` to RF_WD_CSR so the CSR read value is written to the register file.\n- Use the I‑type immediate for the CSR address (bits 31:20). The CSR value to write comes from either the rs1 register field (if funct3 bit 14 == 0) or from the zero‑extended zimm immediate (if funct3 bit 14 == 1).\n- Set the CSR operation according to funct3[1:0]: 01 → CSR_OP_WRITE, 10 → CSR_OP_SET, 11 → CSR_OP_CLEAR. Any other value (00) is illegal.\n- Override the CSR operation to CSR_OP_READ when the write data is zero: for SET/CLEAR operations, if the source (rs1 or zimm) is zero, then the instruction behaves as a read only (no write to the CSR).\n- Assert `csr_status` (flush pipeline) when the accessed CSR address matches `mstatus` (0x300), `dcsr` (0x7B0), `dpc` (0x7B1), `dscratch0` (0x7B2), or `dscratch1` (0x7B3). This flag indicates that subsequent instructions may be affected by the CSR change.\n\n### 8. System Instructions (non‑CSR)\nFunct3 == 0 of the SYSTEM opcode encodes special instructions. The decoder must detect:\n\n- `ecall` (bits 31:20 = 0x000) → trigger `ecall_insn`.\n- `ebreak` (bits 31:20 = 0x001) → trigger `ebreak_insn`.\n- `mret` (bits 31:20 = 0x302) → trigger `mret_insn`.\n- `dret` (bits 31:20 = 0x7B2) → trigger `dret_insn`.\n- `wfi` (bits 31:20 = 0x105) → trigger `wfi_insn`.\n- All other values → illegal instruction.\n- Additionally, the rs1 and rd fields must both be zero; otherwise the instruction is illegal.\n\n### 9. Other Instructions\n- **Fence instructions** (opcode = MISC‑MEM, funct3 = 000): must be treated as a NOP – all control signals remain at their safe defaults (register file not written, no data request). Any other funct3 value (e.g., fence.i) must be treated as illegal.\n\n### 10. Illegal Instruction Detection\nThe decoder must detect illegal instructions based on:\n- Unrecognized opcode (including reserved opcodes).\n- Invalid funct3, funct7, or register fields within a recognized opcode.\n- Instructions that require unimplemented extensions (e.g., RV64 loads when parameter RV32 is selected, register‑offset stores when not supported).\n- Use of registers x16–x31 when the RV32E parameter is enabled and the register is actually read/written (see Section 12).\n- The external `illegal_c_insn` input, which forces the instruction to be considered illegal regardless of decode.\n\nWhen an illegal instruction is detected, the decoder must:\n- Set `illegal_insn` to 1.\n- Suppress all side effects by forcing:\n - Register file write enable to 0.\n - Data request and data write enable to 0.\n - Multiply/divide enable to 0.\n - Jump in decode and branch in decode to 0.\n - CSR access to 0.\n\nThe illegal instruction status is combined with the RV32E register violation check to produce the final `illegal_insn` output.\n\n### 11. Defaults for Unused or Invalid Scenarios\nThe decoder must provide safe default values for all outputs. Typical defaults are chosen so that an illegal instruction does not cause unintended actions:\n- ALU operation: SLTU (arbitrary, but must not cause writeback to be enabled).\n- Operand mux selections: immediate and zero.\n- Immediate mux selections: I‑type and zero.\n- All enables (regfile, data, mult, div, CSR) are low.\n- All exception flags are low.\n\n### 12. Parameter‑Dependent Behavior\n#### RV32E (Embedded)\nWhen the RV32E parameter is set, only registers x0–x15 are available (5‑bit address space with MSB = 1 illegal). The decoder must check:\n- If rs1 is read (i.e., the ALU operand A mux selects `OP_A_REG_A` and the instruction actually uses a register read) and the rs1 address has bit 4 = 1, the instruction is illegal.\n- If rs2 is read (operand B mux selects `OP_B_REG_B` and a register read is used) and the rs2 address has bit 4 = 1, the instruction is illegal.\n- If the destination register write is enabled and the rd address has bit 4 = 1, the instruction is illegal.\n\nWhen any such violation occurs, the `illegal_reg_rv32e` signal is asserted, which is ORed with the internal `illegal_insn` to produce the final `illegal_insn`. The register file write enable is also suppressed.\n\n#### RV32M (Multiply/Divide)\nWhen the RV32M parameter is set to 0, any multiplication or division instruction (funct7 = 0x01) must be treated as illegal. When RV32M is 1, those instructions are legal and produce the corresponding enable signals.\n\n### 13. Wiring and Outputs\nAll outputs must be driven combinatorially from the input instruction and the `instr_new` flag. The decoder does not contain state; the pipeline handshake is managed externally. The immediate values (imm_*_type_o) and register addresses are always produced, even for illegal instructions, but they may be ignored by downstream logic due to the suppression of enables.", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2018 ETH Zurich and University of Bologna.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\n////////////////////////////////////////////////////////////////////////////////\n// Engineer Andreas Traber - atraber@iis.ee.ethz.ch //\n// //\n// Additional contributions by: //\n// Matthias Baer - baermatt@student.ethz.ch //\n// Igor Loi - igor.loi@unibo.it //\n// Sven Stucki - svstucki@student.ethz.ch //\n// Davide Schiavone - pschiavo@iis.ee.ethz.ch //\n// Markus Wegmann - markus.wegmann@technokrat.ch //\n// //\n// Design Name: Decoder //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Decoder //\n// //\n////////////////////////////////////////////////////////////////////////////////\n\n// Source/Destination register instruction index\n`define REG_S1 19:15\n`define REG_S2 24:20\n`define REG_D 11:07\n\n/**\n * Instruction decoder\n */\nmodule ibex_decoder #(\n parameter bit RV32E = 0,\n parameter bit RV32M = 1\n) (\n // to/from controller\n output logic illegal_insn_o, // illegal instr encountered\n output logic ebrk_insn_o, // trap instr encountered\n output logic mret_insn_o, // return from exception instr\n // encountered\n output logic dret_insn_o, // return from debug instr encountered\n output logic ecall_insn_o, // syscall instr encountered\n output logic wfi_insn_o, // wait for interrupt instr encountered\n output logic jump_set_o, // jump taken set signal\n\n // from IF-ID pipeline register\n input logic instr_new_i, // instruction read is new\n input logic [31:0] instr_rdata_i, // instruction read from memory/cache\n input logic illegal_c_insn_i, // compressed instruction decode failed\n\n // immediates\n output ibex_defines::imm_a_sel_e imm_a_mux_sel_o, // immediate selection for operand a\n output ibex_defines::imm_b_sel_e imm_b_mux_sel_o, // immediate selection for operand b\n output logic [31:0] imm_i_type_o,\n output logic [31:0] imm_s_type_o,\n output logic [31:0] imm_b_type_o,\n output logic [31:0] imm_u_type_o,\n output logic [31:0] imm_j_type_o,\n output logic [31:0] zimm_rs1_type_o,\n\n // register file\n output ibex_defines::rf_wd_sel_e regfile_wdata_sel_o, // RF write data selection\n output logic regfile_we_o, // write enable for regfile\n output logic [4:0] regfile_raddr_a_o,\n output logic [4:0] regfile_raddr_b_o,\n output logic [4:0] regfile_waddr_o,\n\n // ALU\n output ibex_defines::alu_op_e alu_operator_o, // ALU operation selection\n output ibex_defines::op_a_sel_e alu_op_a_mux_sel_o, // operand a selection: reg value, PC,\n // immediate or zero\n output ibex_defines::op_b_sel_e alu_op_b_mux_sel_o, // operand b selection: reg value or\n // immediate\n\n // MULT & DIV\n output logic mult_en_o, // perform integer multiplication\n output logic div_en_o, // perform integer division or\n // remainder\n output ibex_defines::md_op_e multdiv_operator_o,\n output logic [1:0] multdiv_signed_mode_o,\n\n // CSRs\n output logic csr_access_o, // access to CSR\n output ibex_defines::csr_op_e csr_op_o, // operation to perform on CSR\n output logic csr_status_o, // access to xstatus CSR\n\n // LSU\n output logic data_req_o, // start transaction to data memory\n output logic data_we_o, // write enable\n output logic [1:0] data_type_o, // size of transaction: byte, half\n // word or word\n output logic data_sign_extension_o, // sign extension for data read from\n // memory\n output logic [1:0] data_reg_offset_o, // register byte offset for stores\n\n // jump/branches\n output logic jump_in_dec_o, // jump is being calculated in ALU\n output logic branch_in_dec_o\n);\n\n import ibex_defines::*;\n\n logic illegal_insn;\n logic illegal_reg_rv32e;\n logic csr_illegal;\n logic regfile_we;\n\n logic [31:0] instr;\n\n csr_op_e csr_op;\n\n opcode_e opcode;\n\n assign instr = instr_rdata_i;\n\n //////////////////////////////////////\n // Register and immediate selection //\n //////////////////////////////////////\n\n // immediate extraction and sign extension\n assign imm_i_type_o = { {20{instr[31]}}, instr[31:20] };\n assign imm_s_type_o = { {20{instr[31]}}, instr[31:25], instr[11:7] };\n assign imm_b_type_o = { {19{instr[31]}}, instr[31], instr[7], instr[30:25], instr[11:8], 1'b0 };\n assign imm_u_type_o = { instr[31:12], 12'b0 };\n assign imm_j_type_o = { {12{instr[31]}}, instr[19:12], instr[20], instr[30:21], 1'b0 };\n\n // immediate for CSR manipulation (zero extended)\n assign zimm_rs1_type_o = { 27'b0, instr[`REG_S1] }; // rs1\n\n // source registers\n assign regfile_raddr_a_o = instr[`REG_S1]; // rs1\n assign regfile_raddr_b_o = instr[`REG_S2]; // rs2\n\n // destination register\n assign regfile_waddr_o = instr[`REG_D]; // rd\n\n ////////////////////\n // Register check //\n ////////////////////\n if (RV32E) begin\n assign illegal_reg_rv32e = ((regfile_raddr_a_o[4] && (alu_op_a_mux_sel_o == OP_A_REG_A)) ||\n (regfile_raddr_b_o[4] && (alu_op_b_mux_sel_o == OP_B_REG_B)) ||\n (regfile_waddr_o[4] & regfile_we));\n end else begin\n assign illegal_reg_rv32e = 1'b0;\n end\n\n ///////////////////////\n // CSR operand check //\n ///////////////////////\n always_comb begin : csr_operand_check\n csr_op_o = csr_op;\n\n // CSRRSI/CSRRCI must not write 0 to CSRs (uimm[4:0]=='0)\n // CSRRS/CSRRC must not write from x0 to CSRs (rs1=='0)\n if ((csr_op == CSR_OP_SET || csr_op == CSR_OP_CLEAR) &&\n instr[`REG_S1] == '0) begin\n csr_op_o = CSR_OP_READ;\n end\n end\n\n /////////////\n // Decoder //\n /////////////\n\n always_comb begin\n jump_in_dec_o = 1'b0;\n jump_set_o = 1'b0;\n branch_in_dec_o = 1'b0;\n alu_operator_o = ALU_SLTU;\n alu_op_a_mux_sel_o = OP_A_IMM;\n alu_op_b_mux_sel_o = OP_B_IMM;\n\n imm_a_mux_sel_o = IMM_A_ZERO;\n imm_b_mux_sel_o = IMM_B_I;\n\n mult_en_o = 1'b0;\n div_en_o = 1'b0;\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n\n regfile_wdata_sel_o = RF_WD_EX;\n regfile_we = 1'b0;\n\n csr_access_o = 1'b0;\n csr_status_o = 1'b0;\n csr_illegal = 1'b0;\n csr_op = CSR_OP_READ;\n\n data_we_o = 1'b0;\n data_type_o = 2'b00;\n data_sign_extension_o = 1'b0;\n data_reg_offset_o = 2'b00;\n data_req_o = 1'b0;\n\n illegal_insn = 1'b0;\n ebrk_insn_o = 1'b0;\n mret_insn_o = 1'b0;\n dret_insn_o = 1'b0;\n ecall_insn_o = 1'b0;\n wfi_insn_o = 1'b0;\n\n opcode = opcode_e'(instr[6:0]);\n\n unique case (opcode)\n\n ///////////\n // Jumps //\n ///////////\n\n OPCODE_JAL: begin // Jump and Link\n jump_in_dec_o = 1'b1;\n if (instr_new_i) begin\n // Calculate jump target\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_b_mux_sel_o = IMM_B_J;\n alu_operator_o = ALU_ADD;\n regfile_we = 1'b0;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_b_mux_sel_o = IMM_B_INCR_PC;\n alu_operator_o = ALU_ADD;\n regfile_we = 1'b1;\n end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n jump_in_dec_o = 1'b1;\n if (instr_new_i) begin\n // Calculate jump target\n alu_op_a_mux_sel_o = OP_A_REG_A;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_b_mux_sel_o = IMM_B_I;\n alu_operator_o = ALU_ADD;\n regfile_we = 1'b0;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_b_mux_sel_o = IMM_B_INCR_PC;\n alu_operator_o = ALU_ADD;\n regfile_we = 1'b1;\n end\n if (instr[14:12] != 3'b0) begin\n illegal_insn = 1'b1;\n end\n end\n\n OPCODE_BRANCH: begin // Branch\n branch_in_dec_o = 1'b1;\n // Check branch condition selection\n unique case (instr[14:12])\n 3'b000: alu_operator_o = ALU_EQ;\n 3'b001: alu_operator_o = ALU_NE;\n 3'b100: alu_operator_o = ALU_LT;\n 3'b101: alu_operator_o = ALU_GE;\n 3'b110: alu_operator_o = ALU_LTU;\n 3'b111: alu_operator_o = ALU_GEU;\n default: illegal_insn = 1'b1;\n endcase\n if (instr_new_i) begin\n // Evaluate branch condition\n alu_op_a_mux_sel_o = OP_A_REG_A;\n alu_op_b_mux_sel_o = OP_B_REG_B;\n end else begin\n // Calculate jump target in EX\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_b_mux_sel_o = IMM_B_B;\n alu_operator_o = ALU_ADD;\n regfile_we = 1'b0;\n end\n end\n\n ////////////////\n // Load/store //\n ////////////////\n\n OPCODE_STORE: begin\n alu_op_a_mux_sel_o = OP_A_REG_A;\n alu_op_b_mux_sel_o = OP_B_REG_B;\n data_req_o = 1'b1;\n data_we_o = 1'b1;\n alu_operator_o = ALU_ADD;\n\n if (!instr[14]) begin\n // offset from immediate\n imm_b_mux_sel_o = IMM_B_S;\n alu_op_b_mux_sel_o = OP_B_IMM;\n end else begin\n // Register offset is illegal since no register c available\n illegal_insn = 1'b1;\n end\n\n // store size\n unique case (instr[13:12])\n 2'b00: data_type_o = 2'b10; // SB\n 2'b01: data_type_o = 2'b01; // SH\n 2'b10: data_type_o = 2'b00; // SW\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n OPCODE_LOAD: begin\n alu_op_a_mux_sel_o = OP_A_REG_A;\n data_req_o = 1'b1;\n regfile_wdata_sel_o = RF_WD_LSU;\n regfile_we = 1'b1;\n data_type_o = 2'b00;\n\n // offset from immediate\n alu_operator_o = ALU_ADD;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_b_mux_sel_o = IMM_B_I;\n\n // sign/zero extension\n data_sign_extension_o = ~instr[14];\n\n // load size\n unique case (instr[13:12])\n 2'b00: data_type_o = 2'b10; // LB\n 2'b01: data_type_o = 2'b01; // LH\n 2'b10: data_type_o = 2'b00; // LW\n default: data_type_o = 2'b00; // illegal or reg-reg\n endcase\n\n // reg-reg load (different encoding)\n if (instr[14:12] == 3'b111) begin\n // offset from RS2\n alu_op_b_mux_sel_o = OP_B_REG_B;\n\n // sign/zero extension\n data_sign_extension_o = ~instr[30];\n\n // load size\n unique case (instr[31:25])\n 7'b0000_000,\n 7'b0100_000: data_type_o = 2'b10; // LB, LBU\n 7'b0001_000,\n 7'b0101_000: data_type_o = 2'b01; // LH, LHU\n 7'b0010_000: data_type_o = 2'b00; // LW\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n if (instr[14:12] == 3'b011) begin\n // LD -> RV64 only\n illegal_insn = 1'b1;\n end\n end\n\n /////////\n // ALU //\n /////////\n\n OPCODE_LUI: begin // Load Upper Immediate\n alu_op_a_mux_sel_o = OP_A_IMM;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_a_mux_sel_o = IMM_A_ZERO;\n imm_b_mux_sel_o = IMM_B_U;\n alu_operator_o = ALU_ADD;\n regfile_we = 1'b1;\n end\n\n OPCODE_AUIPC: begin // Add Upper Immediate to PC\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_b_mux_sel_o = IMM_B_U;\n alu_operator_o = ALU_ADD;\n regfile_we = 1'b1;\n end\n\n OPCODE_OP_IMM: begin // Register-Immediate ALU Operations\n alu_op_a_mux_sel_o = OP_A_REG_A;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_b_mux_sel_o = IMM_B_I;\n regfile_we = 1'b1;\n\n unique case (instr[14:12])\n 3'b000: alu_operator_o = ALU_ADD; // Add Immediate\n 3'b010: alu_operator_o = ALU_SLT; // Set to one if Lower Than Immediate\n 3'b011: alu_operator_o = ALU_SLTU; // Set to one if Lower Than Immediate Unsigned\n 3'b100: alu_operator_o = ALU_XOR; // Exclusive Or with Immediate\n 3'b110: alu_operator_o = ALU_OR; // Or with Immediate\n 3'b111: alu_operator_o = ALU_AND; // And with Immediate\n\n 3'b001: begin\n alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n if (instr[31:25] != 7'b0) begin\n illegal_insn = 1'b1;\n end\n end\n\n 3'b101: begin\n if (instr[31:25] == 7'b0) begin\n alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n end else if (instr[31:25] == 7'b010_0000) begin\n alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n end else begin\n illegal_insn = 1'b1;\n end\n end\n\n default: begin\n alu_operator_o = alu_op_e'({$bits(alu_op_e){1'bX}});\n end\n endcase\n end\n\n OPCODE_OP: begin // Register-Register ALU operation\n alu_op_a_mux_sel_o = OP_A_REG_A;\n alu_op_b_mux_sel_o = OP_B_REG_B;\n regfile_we = 1'b1;\n\n if (instr[31]) begin\n illegal_insn = 1'b1;\n end else begin\n unique case ({instr[30:25], instr[14:12]})\n // RV32I ALU operations\n {6'b00_0000, 3'b000}: alu_operator_o = ALU_ADD; // Add\n {6'b10_0000, 3'b000}: alu_operator_o = ALU_SUB; // Sub\n {6'b00_0000, 3'b010}: alu_operator_o = ALU_SLT; // Set Lower Than\n {6'b00_0000, 3'b011}: alu_operator_o = ALU_SLTU; // Set Lower Than Unsigned\n {6'b00_0000, 3'b100}: alu_operator_o = ALU_XOR; // Xor\n {6'b00_0000, 3'b110}: alu_operator_o = ALU_OR; // Or\n {6'b00_0000, 3'b111}: alu_operator_o = ALU_AND; // And\n {6'b00_0000, 3'b001}: alu_operator_o = ALU_SLL; // Shift Left Logical\n {6'b00_0000, 3'b101}: alu_operator_o = ALU_SRL; // Shift Right Logical\n {6'b10_0000, 3'b101}: alu_operator_o = ALU_SRA; // Shift Right Arithmetic\n\n // supported RV32M instructions\n {6'b00_0001, 3'b000}: begin // mul\n alu_operator_o = ALU_ADD;\n multdiv_operator_o = MD_OP_MULL;\n mult_en_o = RV32M ? 1'b1 : 1'b0;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {6'b00_0001, 3'b001}: begin // mulh\n alu_operator_o = ALU_ADD;\n multdiv_operator_o = MD_OP_MULH;\n mult_en_o = RV32M ? 1'b1 : 1'b0;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {6'b00_0001, 3'b010}: begin // mulhsu\n alu_operator_o = ALU_ADD;\n multdiv_operator_o = MD_OP_MULH;\n mult_en_o = RV32M ? 1'b1 : 1'b0;\n multdiv_signed_mode_o = 2'b01;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {6'b00_0001, 3'b011}: begin // mulhu\n alu_operator_o = ALU_ADD;\n multdiv_operator_o = MD_OP_MULH;\n mult_en_o = RV32M ? 1'b1 : 1'b0;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {6'b00_0001, 3'b100}: begin // div\n alu_operator_o = ALU_ADD;\n multdiv_operator_o = MD_OP_DIV;\n div_en_o = RV32M ? 1'b1 : 1'b0;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {6'b00_0001, 3'b101}: begin // divu\n alu_operator_o = ALU_ADD;\n multdiv_operator_o = MD_OP_DIV;\n div_en_o = RV32M ? 1'b1 : 1'b0;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {6'b00_0001, 3'b110}: begin // rem\n alu_operator_o = ALU_ADD;\n multdiv_operator_o = MD_OP_REM;\n div_en_o = RV32M ? 1'b1 : 1'b0;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {6'b00_0001, 3'b111}: begin // remu\n alu_operator_o = ALU_ADD;\n multdiv_operator_o = MD_OP_REM;\n div_en_o = RV32M ? 1'b1 : 1'b0;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n end\n\n /////////////\n // Special //\n /////////////\n\n OPCODE_MISC_MEM: begin\n // For now, treat the fence (funct3 == 000) instruction as a nop.\n // This may not be correct in a system with caches and should be\n // revisited.\n // fence.i (funct3 == 001) was moved to a separate Zifencei extension\n // in the RISC-V ISA spec proposed for ratification, so we treat it as\n // an illegal instruction.\n if (instr[14:12] == 3'b000) begin\n alu_operator_o = ALU_ADD; // nop\n alu_op_a_mux_sel_o = OP_A_REG_A;\n alu_op_b_mux_sel_o = OP_B_IMM;\n regfile_we = 1'b0;\n end else begin\n illegal_insn = 1'b1;\n end\n end\n\n OPCODE_SYSTEM: begin\n if (instr[14:12] == 3'b000) begin\n // non CSR related SYSTEM instructions\n alu_op_a_mux_sel_o = OP_A_REG_A;\n alu_op_b_mux_sel_o = OP_B_IMM;\n unique case (instr[31:20])\n 12'h000: // ECALL\n // environment (system) call\n ecall_insn_o = 1'b1;\n\n 12'h001: // ebreak\n // debugger trap\n ebrk_insn_o = 1'b1;\n\n 12'h302: // mret\n mret_insn_o = 1'b1;\n\n 12'h7b2: // dret\n dret_insn_o = 1'b1;\n\n 12'h105: // wfi\n wfi_insn_o = 1'b1;\n\n default:\n illegal_insn = 1'b1;\n endcase\n\n // rs1 and rd must be 0\n if (instr[`REG_S1] || instr[`REG_D]) begin\n illegal_insn = 1'b1;\n end\n end else begin\n // instruction to read/modify CSR\n csr_access_o = 1'b1;\n regfile_wdata_sel_o = RF_WD_CSR;\n regfile_we = 1'b1;\n alu_op_b_mux_sel_o = OP_B_IMM;\n imm_a_mux_sel_o = IMM_A_Z;\n imm_b_mux_sel_o = IMM_B_I; // CSR address is encoded in I imm\n\n if (instr[14]) begin\n // rs1 field is used as immediate\n alu_op_a_mux_sel_o = OP_A_IMM;\n end else begin\n alu_op_a_mux_sel_o = OP_A_REG_A;\n end\n\n unique case (instr[13:12])\n 2'b01: csr_op = CSR_OP_WRITE;\n 2'b10: csr_op = CSR_OP_SET;\n 2'b11: csr_op = CSR_OP_CLEAR;\n default: csr_illegal = 1'b1;\n endcase\n\n if (!csr_illegal) begin\n // flush pipeline on access to mstatus or debug CSRs\n if (csr_num_e'(instr[31:20]) == CSR_MSTATUS ||\n csr_num_e'(instr[31:20]) == CSR_DCSR ||\n csr_num_e'(instr[31:20]) == CSR_DPC ||\n csr_num_e'(instr[31:20]) == CSR_DSCRATCH0 ||\n csr_num_e'(instr[31:20]) == CSR_DSCRATCH1) begin\n csr_status_o = 1'b1;\n end\n end\n\n illegal_insn = csr_illegal;\n end\n\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n\n // make sure illegal compressed instructions cause illegal instruction exceptions\n if (illegal_c_insn_i) begin\n illegal_insn = 1'b1;\n end\n\n // make sure illegal instructions detected in the decoder do not propagate from decoder\n // into register file, LSU, EX, WB, CSRs\n // NOTE: instructions can also be detected to be illegal inside the CSRs (upon accesses with\n // insufficient privileges), in ID stage (when accessing Reg 16 or higher in RV32E config),\n // these cases are not handled here\n if (illegal_insn) begin\n regfile_we = 1'b0;\n data_req_o = 1'b0;\n data_we_o = 1'b0;\n mult_en_o = 1'b0;\n div_en_o = 1'b0;\n jump_in_dec_o = 1'b0;\n branch_in_dec_o = 1'b0;\n csr_access_o = 1'b0;\n end\n end\n\n // make sure instructions accessing non-available registers in RV32E cause illegal\n // instruction exceptions\n assign illegal_insn_o = illegal_insn | illegal_reg_rv32e;\n\n // do not propgate regfile write enable if non-available registers are accessed in RV32E\n assign regfile_we_o = regfile_we & ~illegal_reg_rv32e;\n\nendmodule // controller\n", "pr_title": "Decoder: fix signaling and detection of illegal instructions", "pr_body": "This commit fixes two bugs in the decoder:\r\n\r\n1. For illegal branch condition selections, the illegal instruction\r\ncondition must be signaled as long as the instruction is being executed\r\nand not just during the first cycle, as the controller cannot interrupt\r\nmulticycle instructions.\r\n\r\n2. Illegal instructions should also be signaled when `instr[28]` is set\r\nfor register-register ALU operations. Previously, these were not\r\nsignaled as the original design used `instr[28]` to encode custom bit-\r\nmanipulation instructions.\r\n\r\nThese bugs were discovered by @taoliug. This resolves issue #163.", "fix_patch": "diff --git a/rtl/ibex_decoder.sv b/rtl/ibex_decoder.sv\nindex 468f9ffba3..03910af64c 100644\n--- a/rtl/ibex_decoder.sv\n+++ b/rtl/ibex_decoder.sv\n@@ -253,19 +253,20 @@ module ibex_decoder #(\n \n OPCODE_BRANCH: begin // Branch\n branch_in_dec_o = 1'b1;\n+ // Check branch condition selection\n+ unique case (instr[14:12])\n+ 3'b000: alu_operator_o = ALU_EQ;\n+ 3'b001: alu_operator_o = ALU_NE;\n+ 3'b100: alu_operator_o = ALU_LT;\n+ 3'b101: alu_operator_o = ALU_GE;\n+ 3'b110: alu_operator_o = ALU_LTU;\n+ 3'b111: alu_operator_o = ALU_GEU;\n+ default: illegal_insn = 1'b1;\n+ endcase\n if (instr_new_i) begin\n // Evaluate branch condition\n alu_op_a_mux_sel_o = OP_A_REG_A;\n alu_op_b_mux_sel_o = OP_B_REG_B;\n- unique case (instr[14:12])\n- 3'b000: alu_operator_o = ALU_EQ;\n- 3'b001: alu_operator_o = ALU_NE;\n- 3'b100: alu_operator_o = ALU_LT;\n- 3'b101: alu_operator_o = ALU_GE;\n- 3'b110: alu_operator_o = ALU_LTU;\n- 3'b111: alu_operator_o = ALU_GEU;\n- default: illegal_insn = 1'b1;\n- endcase\n end else begin\n // Calculate jump target in EX\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n@@ -422,7 +423,7 @@ module ibex_decoder #(\n \n if (instr[31]) begin\n illegal_insn = 1'b1;\n- end else if (!instr[28]) begin // non bit-manipulation instructions\n+ end else begin\n unique case ({instr[30:25], instr[14:12]})\n // RV32I ALU operations\n {6'b00_0000, 3'b000}: alu_operator_o = ALU_ADD; // Add\n"}
|