diff --git "a/s2/lowRISC__ibex/lowRISC__ibex_s02_inputs.jsonl" "b/s2/lowRISC__ibex/lowRISC__ibex_s02_inputs.jsonl" new file mode 100644--- /dev/null +++ "b/s2/lowRISC__ibex/lowRISC__ibex_s02_inputs.jsonl" @@ -0,0 +1,75 @@ +{"input": {"repo": "lowRISC/ibex", "pr_id": 2241, "lang": "sv", "rtl_files": ["rtl/ibex_register_file_fpga.sv"], "spec": "# Behavioral Specification for FPGA Register File Module\n\n## Overview\n\nThis module implements a RISC‑V register file intended for FPGA synthesis. It contains either 31 or 15 registers of configurable width (default 32 bits). Register `x0` is permanently tied to a configured zero value (`WordZeroVal`, default all‑zero) and ignores all writes. The register file provides two independent read ports and one write port. Reads are asynchronous (data available in the same cycle the address is presented), and writes are synchronous (performed on the rising edge of the clock). The module includes optional error detection for glitch‑susceptible read addresses and spurious write enable signals.\n\n## Parameters\n\nThe following parameters control the instance behaviour:\n\n- **RV32E** (0 or 1): When 1, the register file contains only 15 registers (addresses 0‑14). When 0, it contains 31 registers (addresses 0‑30). Address 0 is always the fixed‑zero register.\n- **DataWidth** (positive integer, default 32): Width of each register in bits. All read and write data paths use this width.\n- **DummyInstructions** (0 or 1): Not used in the FPGA implementation. The input signals related to dummy instructions are ignored.\n- **WrenCheck** (0 or 1): When 1, the module enables detection of spurious write enable strobes (e.g., glitches on the write enable input). When 0, no write enable check is performed.\n- **RdataMuxCheck** (0 or 1): When 1, the module enables one‑hot encoding of read addresses and checks each read address for valid one‑hot representation. The read data multiplexers are also implemented using one‑hot selection for glitch robustness. When 0, read addresses are used directly to index the register file.\n- **WordZeroVal** (bit vector of `DataWidth`, default all‑zero): The constant value returned when reading register x0. This value also initializes every register at power‑up (or upon global reset of the FPGA fabric). If a non‑zero value is used, writes to any register that set it to zero will be visible.\n\n## Interface Behaviour\n\n### Clock and Reset\n- **Clock**: All write operations occur on the rising edge of the clock. The module does not require a reset signal; the reset input is ignored.\n- **Reset Input**: The reset pin is tied off and has no functional effect. Power‑up initialisation is done through an `initial` procedure (common in FPGA flows) that sets every internal register to `WordZeroVal`.\n\n### Read Ports (A and B)\n- Two independent read ports are provided. Each port has a read address input and a read data output.\n- **Read address**: A 5‑bit value (4 bits when RV32E is enabled). Any address value is accepted.\n- **Read data**: Outputs the current value of the addressed register. For address 0, the output is always `WordZeroVal`, regardless of any writes to that address. For any other valid register address, the output is the value last written (or the initial `WordZeroVal` if never written).\n- Reads are asynchronous: the output data becomes valid combinatorial logic after the address stabilises. There is no pipeline delay or write‑to‑read forwarding – a read that occurs in the same cycle as a write to the same address sees the **old** value (the value before the write takes effect).\n\n### Write Port (W)\n- One write port is provided with a write address, write data, and write enable signal.\n- **Write address**: 5‑bit (or 4‑bit with RV32E). Writing to address 0 is silently ignored; the write enable is internally suppressed.\n- **Write data**: Data to be stored in the addressed register.\n- **Write enable**: When asserted high, the write data is sampled on the rising edge of the clock and stored in the addressed register (unless the address is zero). The write enable must be stable around the clock edge for correct operation.\n- **Timing**: Writes are synchronous to the clock rising edge. The written value becomes available for reads in the next clock cycle (before the next rising edge, due to asynchronous reads).\n\n### Unused Inputs\n- **Test enable**: Not used in the FPGA implementation; tied off.\n- **Dummy instruction signals** (ID and WB stages): Not used in the FPGA implementation; tied off.\n\n**Note**: The module does **not** provide any forwarding paths. A sequence that reads a register in the same cycle it is written will observe the register’s pre‑write value.\n\n## Error Detection\n\nThe module provides a single error output that indicates when certain glitch conditions are detected. This output is a combination of three potential error sources:\n\n### 1. Read Address One‑Hot Check (when `RdataMuxCheck = 1`)\nFor each read port, the read address is decoded into a one‑hot vector and checked for validity:\n- The one‑hot vector must have **exactly one** bit high. If more than one bit is active, or if no bit is active (all zeros), an error is generated.\n- The built‑in one‑hot check also verifies that the one‑hot vector matches the original address value. This provides protection against single‑event upsets or routing glitches that might modify the address before decoding.\n- Errors are detected continuously (combinatorial) and will appear on the error output as soon as an invalid address is sampled. The error is not latched – it persists as long as the invalid address is present.\n\n### 2. Write Enable Glitch Check (when `WrenCheck = 1`)\n- The module monitors the write enable strobe for spurious assertions that do not come from the external write enable input. Such glitches could occur due to clock domain crossing or transient logic hazards.\n- If a write enable event is detected that is inconsistent with the expected external write enable, an error is flagged. (In the typical functional case, when the write enable signal is clean, no error occurs.)\n- The error is combinatorial and follows the glitch event.\n\n### Error Output\n- The error output is the logical OR of the three error sources described above. It is asserted high when any of the checks fails.\n- The error output is **informational only**; it does **not** alter the functional behaviour of the register file. Writes and reads proceed normally even when an error is indicated.\n\nWhen `RdataMuxCheck = 0`, the read address one‑hot checks and corresponding multiplexers are removed, and the error sources for both read ports are forced to zero. Similarly, when `WrenCheck = 0`, the write enable glitch check is removed and its error source forced to zero.\n\n## Power‑Up and Initialisation\n\n- The module uses an FPGA‑compatible `initial` block to set every internal storage cell to `WordZeroVal`. This matches the expected FPGA behaviour where initial blocks are synthesised into configuration stream initialisation.\n- The reset input is **not** used for register initialisation; it is ignored.\n- After power‑up, before any clock edge, all registers (including those that are not x0) contain `WordZeroVal`. The first write to any register changes that value.\n\n## Summary of Behavioural Requirements\n\n| Condition | Observable Behaviour |\n|-----------|----------------------|\n| Read address = 0 | Read data output = `WordZeroVal` |\n| Read address ≠ 0 | Read data output = value last written to that address (or initial `WordZeroVal`) |\n| Write enable = 1 and address ≠ 0 | On rising clock edge, write data is stored into addressed register |\n| Write enable = 1 and address = 0 | Write is ignored (internal write enable masked) |\n| Write enable = 0 | No write operation |\n| `RdataMuxCheck` = 1 and a read address is not one‑hot | Error output asserted |\n| `WrenCheck` = 1 and a spurious write enable strobe occurs | Error output asserted |\n| No error conditions | Error output = 0 |\n| Same register read and written in same cycle | Read returns value before write (no forwarding) |\n| Reset input | Ignored |\n| Dummy instruction or test enable inputs | Ignored |\n\nThis specification defines the module’s required behaviour without prescribing internal implementation details. All aspects described here shall be met by any implementation claiming compliance.", "commit_id": "8f4c75c5e43e61b994248307c814e01860303056", "timestamp": "2025-01-07T10:01:03+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "4d722d3308f5b2bafd4f1264d4163031752a0a93", "pr_title": "[rtl] Drive oh_raddr_*_err if RdataMuxCheck=0", "pr_body": "These errors aren't detected or reported if the mux is disabled, but the RTL didn't actually drive them at all.\r\n\r\nFixes #2239.", "issue_title": "Undriven signal in ibex_register_file_fpga.sv", "issue_body": "## Observed Behavior\n\n\nOn the following line, `oh_raddr_a_err` is undriven if `RdataMuxCheck` is zero.\n\nhttps://github.com/lowRISC/ibex/blob/master/rtl/ibex_register_file_fpga.sv#L54\n\nThis was seen in Verilator linting when trying to integrate Ibex into my design. I've searched the VLT files for any relevant waivers but can't see any relating to this level of hierarchy.\n\n```\nERROR: %Warning-UNDRIVEN: src/lowrisc_export_ibex_top_0/rtl/ibex_register_file_fpga.sv:54:9: Signal is not driven: 'oh_raddr_a_err'\n : ... note: In instance 'ibex_wb.u_top..gen_regfile_fpga.register_file_i'\n 54 | logic oh_raddr_a_err, oh_raddr_b_err, oh_we_err;\n | ^~~~~~~~~~~~~~\n ... For warning description see https://verilator.org/warn/UNDRIVEN?v=5.024\n ... Use \"/* verilator lint_off UNDRIVEN */\" and lint_on around source to disable this message.\n%Warning-UNDRIVEN: src/lowrisc_export_ibex_top_0/rtl/ibex_register_file_fpga.sv:54:25: Signal is not driven: 'oh_raddr_b_err'\n : ... note: In instance 'ibex_wb.u_top..gen_regfile_fpga.register_file_i'\n 54 | logic oh_raddr_a_err, oh_raddr_b_err, oh_we_err;\n | ^~~~~~~~~~~~~~\n%Error: Exiting due to 2 warning(s)\nmake: *** [Makefile:23: lint-only] Error 1\n\nERROR: Failed to build nq:ip:ibex_wb:0 : '['make', 'lint-only']' exited with an error: 2\n```\n\n## Expected Behavior\n\nTis lint clean please.\n\n## Steps to reproduce the issue\n\n\nI'm trying to export the Ibex RTL source code to get around the fact that you are using a custom version of Fusesoc. I'm instantiating Ibex with the following parameters:\n\n```\n ibex_top #(\n .RV32M (ibex_pkg::RV32MSlow),\n .RV32B (ibex_pkg::RV32BNone),\n .RegFile(ibex_pkg::RegFileFPGA)\n ) u_top (\n\n```\n\nand then running a Verilator lint using the standard Fusesoc/Edalize flow.\n\n## My Environment\n\n\n\n**EDA tool and version:**\nVerilator 5.024 2024-04-05 rev v5.024\n\n\n**Operating system:**\nRocky 9.4\n\n\n**Version of the Ibex source code:**\n8f4c75c5e43e61b994248307c814e01860303056\n\n", "commit_message": "[rtl] Drive oh_raddr_*_err if RdataMuxCheck=0\n\nThese errors aren't detected or reported if the mux is disabled, but\nthe RTL didn't actually drive them at all.", "fix_patch": "diff --git a/rtl/ibex_register_file_fpga.sv b/rtl/ibex_register_file_fpga.sv\nindex 73e0afab2f..2414d771d5 100644\n--- a/rtl/ibex_register_file_fpga.sv\n+++ b/rtl/ibex_register_file_fpga.sv\n@@ -155,6 +155,9 @@ module ibex_register_file_fpga #(\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+ assign oh_raddr_b_err = 1'b0;\n end\n \n // we select\n", "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 // 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 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", "selected_doc_paths": ["doc/03_reference/register_file.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 2449, "lang": "sv", "rtl_files": ["examples/simple_system/rtl/ibex_simple_system.sv"], "spec": "# Behavioral Design Specification: `ibex_simple_system`\n\n## Overview\n\nThe `ibex_simple_system` module provides a minimal, simulation‑targeted system around the lowRISC Ibex RISC‑V core. It integrates a single‑ported instruction/data RAM, a memory‑mapped timer, and a memory‑mapped simulator control peripheral. The system is configured entirely through compile‑time parameters and is designed to work with Verilator as the primary simulator, with support for other simulators.\n\nThe primary purpose of this system is to allow software binaries to be executed against Ibex RTL in simulation, producing instruction traces, wave forms, and ASCII console output via the simulator control module.\n\n## Clock and Reset\n\n- The module expects a single clock input and a single active‑low asynchronous reset input.\n- When not using Verilator (`VERILATOR` not defined), the module shall internally generate its own clock (running at 1 time unit period) and a delayed release of reset (reset asserted for 8 time units after start of simulation).\n- All internal logic shall operate synchronously to the system clock and be reset by the system reset. The core’s internal reset is the same system reset.\n- The core’s `test_en_i` and `scan_rst_ni` inputs are tied to fixed values (test disabled, scan reset inactive). These may be overridden in a custom integration but are not used in this simple system.\n\n## Processor Core (Ibex)\n\nThe system instantiates a configurable Ibex core (`ibex_top`). All parameters of the core are exposed as top‑level parameters of the simple system. The following behaviors are defined:\n\n- **Instruction Fetch**: The core issues fetch requests to the instruction memory interface. The simple system guarantees that every fetch request is immediately granted (`instr_gnt` same as `instr_req`). No error is ever signalled on the instruction bus.\n- **Data Access**: The core issues data read/write requests to the system bus. Data access errors are not generated by any peripheral (they are tied to zero).\n- **Interrupts**: The core receives a single timer interrupt input from the timer peripheral. Software, external, and fast interrupts are tied to zero.\n- **Boot**: After reset, the core fetches the first instruction from address `boot_addr_i + 0x80`. In the simple system, the boot address is set to `0x00100000`, so the first instruction resides at `0x00100080`.\n- **Debug**: Debug is not activated; the core’s debug request input is tied low. The debug module base address parameters (`DmBaseAddr, DmAddrMask, DmHaltAddr, DmExceptionAddr`) are set to `0x00100000` (overlapping the RAM), but because debug is disabled via `debug_req_i=0`, they have no functional effect.\n\n### Configuration Parameters\n\nThe system accepts all parameters of the Ibex core, including:\n- `SecureIbex, LockstepOffset, ICacheScramble` – security and lockstep features (default disabled).\n- `PMPEnable, PMPGranularity, PMPNumRegions` – physical memory protection.\n- `MHPMCounterNum, MHPMCounterWidth` – performance monitoring counters.\n- `RV32E` – selects 16‑register RV32E mode.\n- `RV32M, RV32B, RV32ZC` – selects multiply, bit‑manipulation, and code‑size extensions.\n- `RegFile` – selects register file implementation (flip‑flop, latch, FPGA).\n- `BranchTargetALU, WritebackStage, ICache, ICacheECC, BranchPredictor` – pipeline options.\n- `DbgTriggerEn` – debug trigger support.\n- `SRAMInitFile` – optional initialisation file for the internal RAM.\n\nWhen `SecureIbex` is enabled, the system includes ECC generation for data and instruction return data (39‑bit SECDED codes). The generated ECC bits are passed to the core; error injection is not used.\n\n## System Bus and Address Decoding\n\nThe system implements a single‑host, three‑device bus. The Ibex core is the only bus host. Devices are selected by address decoding with fixed base and mask values:\n\n| Device | Address Base | Size | Description |\n|----------|--------------|--------|--------------------------------------------|\n| RAM | `0x00100000` | 1 MiB | Instruction and data storage |\n| SimCtrl | `0x00020000` | 1 KiB | Simulation control and ASCII output |\n| Timer | `0x00030000` | 1 KiB | Timer with interrupt generation |\n\nAll accesses outside these ranges (or to unmapped addresses) shall be silently ignored; the bus does not generate error responses. The bus grants all host requests immediately. Read accesses to a device return data on the next cycle (pipelined). Write accesses complete in one cycle.\n\n## Memory Subsystem (RAM)\n\nThe RAM is a dual‑ported memory with a total capacity of 1 MiB (256 k × 32 bits).\n\n- **Port A**: Connected to the system bus (data accesses from the core). Supports reads and writes with byte enable signals (`be`). Write enables are decoded to allow byte, half‑word, or word writes.\n- **Port B**: Connected directly to the core’s instruction fetch interface. This port is read‑only; any write attempt is ignored.\n- Both ports operate synchronously to the system clock.\n- The RAM may be initialised from a file at the start of simulation if the `SRAMInitFile` parameter is non‑empty. The format of the file is determined by the `ram_2p` implementation (typically an Intel‑HEX or binary file).\n- An optional extra delay (`INSTR_CYCLE_DELAY`) can be added to port B read responses to model slower instruction memory. When set to 0 (default), read data is returned in the cycle following a request.\n\n## Timer Peripheral\n\nThe timer is a memory‑mapped device with a 32‑bit wide register interface. The following functionality shall be provided (based on the `timer` module):\n\n- The timer contains a configurable counter that can be started, stopped, and reloaded by software writes.\n- It generates a timer interrupt (`timer_irq`) when the counter reaches zero (or an equivalent condition, depending on the implementation).\n- The interrupt output is connected directly to the Ibex core’s timer interrupt input (`irq_timer_i`).\n- The timer operates on the system clock and is reset by system reset.\n- The device responds to read/write accesses at its base address (`0x00030000`) within a 1 KiB region. Unimplemented addresses within that range shall either return zero or be ignored.\n\n## Simulator Control Peripheral\n\nThe simulator control peripheral (`simulator_ctrl`) provides a mechanism for software running on Ibex to interact with the simulation environment:\n\n- **ASCII Output**: Writing to a specific memory‑mapped location (e.g., a “print” register) shall cause the simulator to output the written byte (or word) as an ASCII character to the simulation console or a log file. The log file name is configurable via the `LogName` parameter (default: `ibex_simple_system.log`).\n- **Simulation Halt**: Writing a specific value to a control register shall cause the simulation to stop (e.g., `$finish` in Verilog). The precise encoding is defined by the `simulator_ctrl` implementation.\n- The peripheral responds to read and write accesses at its base address (`0x00020000`) within a 1 KiB region.\n- No error is signalled from this peripheral.\n- The peripheral is intended for simulation only; it has no effect in an actual FPGA or ASIC implementation.\n\n## Interrupts\n\n- The only interrupt source in the system is the timer.\n- Software, external, and fast interrupts are all tied to zero and shall never be asserted.\n- The non‑maskable interrupt (`irq_nm_i`) is tied low.\n\n## Simulation‑Specific Behaviour\n\n- When `VERILATOR` is defined at compile time, the clock and reset inputs are passed directly from the top‑level ports. No internal clock generation occurs.\n- When `VERILATOR` is not defined, the module internally generates a free‑running clock with a period of 2 time units and releases reset after 8 time units. This ensures the system is self‑starting in any simulator that does not provide an external clock.\n- The `instr_err` signal is permanently de‑asserted; the core never sees an error on an instruction fetch.\n- All bus‑related error signals from devices are tied to zero.\n\n## DPI Functions\n\nTwo DPI‑exported functions are provided for use by simulation testbenches:\n\n1. **`mhpmcounter_num()`** – Returns the number of implemented machine performance monitoring counters (`MHPMCounterNum`). This allows a testbench to query the counter configuration without parsing parameters.\n2. **`mhpmcounter_get(index)`** – Returns the current 64‑bit value of a specified hardware performance monitor counter. The index shall be between 0 and `mhpmcounter_num() - 1`. Out‑of‑range indices may return zero or an undefined value.\n\nThese functions are intended to be called from C/C++ code (e.g., Verilator’s DPI) to inspect performance counters during simulation.\n\n## Behaviour Under Reset\n\n- When reset is asserted (`rst_n` low), all registers in the core, bus, RAM, timer, and simulator control shall be initialised to their reset states.\n- The core’s program counter shall be set to the reset vector (`boot_addr_i + 0x80 = 0x00100080`).\n- The timer interrupt shall be de‑asserted.\n- The RAM content shall retain its initialisation file data if provided; otherwise it is undefined until first written.\n- The bus interface shall be idle.\n\n## Unused Signals and Tie‑offs\n\n- All shadow‑core outputs (required for lockstep) are left unconnected.\n- All scrambling key inputs are tied to zero and the scrambling request output is unused.\n- The `crash_dump`, `double_fault_seen`, and alert outputs are not used in this system.\n\n## Summary of Configuration‑Dependent Behaviour\n\n- **`SecureIbex`**: When enabled, ECC check bits are generated for both instruction and data read data using a SECDED (39,32) encoder. The core receives these check bits as part of its interface.\n- **`ICache`**: When enabled, the core uses an instruction cache instead of a prefetch buffer. The system does not modify the cache RAM configuration; default RAM configuration is provided.\n- **`ICacheScramble`**: When both `ICache` and `SecureIbex` are enabled, the cache RAMs are replaced with scrambling primitives. The system ties the key and nonce inputs to zero.\n- **`BranchPredictor`**: When enabled, the core performs static branch prediction. The system does not affect this behaviour.\n\nAll other Ibex parameters directly influence the core’s instruction set, pipeline, and resource count without any additional system‑level effect.", "commit_id": "57d37bf9008640415532d23ad59018b795c642aa", "timestamp": "2026-06-09T14:34:00+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "b58952d7f72d03b083e7de6309b4492ad3f374f1", "pr_title": "[simple_system] Fix initial assignment of `clk_sys`", "pr_body": "Remove the in-line initialization of the clock from the simple system, and handle the clock generation in a separate `initial` block instead.\r\n\r\nFixes https://github.com/lowRISC/ibex/issues/2447", "issue_title": "Fix ifdef VERILATOR breaking sv-tests ibex", "issue_body": "## Observed Behavior\n\nThe Ibex test that runs on Verilator as part of sv-tests at https://chipsalliance.github.io/sv-tests-results/?v=verilator+ibex+ibex\n\nfails with:\n\n```\n%Error-CONTASSINIT: build/lowrisc_ibex_ibex_simple_system_0/sim-verilator/../src/lowrisc_ibex_ibex_simple_system_core_0/rtl/ibex_simple_system.sv:68:19: Continuous assignment to variable with initial value: 'clk_sys'\n : ... note: In instance 'ibex_simple_system'\n : ... Location of variable initialization\n build/lowrisc_ibex_ibex_simple_system_0/sim-verilator/../src/lowrisc_ibex_ibex_simple_system_core_0/rtl/ibex_simple_system.sv:132:12: ... Location of continuous assignment\n ... For error description see https://verilator.org/warn/CONTASSINIT?v=5.049\n```\n\n## Expected Behavior\n\nDoes not fail.\n\n## Steps to reproduce the issue\n\nSee sv-tests for their command line.\n\n## Notes\n\nI believe this is because Verilator recently added/updated the continuous assignment error, previously this was (incorrectly) not an error. I believe that the error is correct, and is due to the `ifdef VERILATOR code around here:\n\nhttps://github.com/lowRISC/ibex/blob/2cf450db5133f6215c32d8463e65f8733e7323a3/examples/simple_system/rtl/ibex_simple_system.sv#L131\n\nit should be updated to be an always or otherwise not create IEEE-illegal code when VERILATOR is defined. Thanks.\n", "commit_message": "[simple_system] Fix initial assignment of `clk_sys`", "fix_patch": "diff --git a/examples/simple_system/rtl/ibex_simple_system.sv b/examples/simple_system/rtl/ibex_simple_system.sv\nindex 1f5e08602..fa2f6016f 100644\n--- a/examples/simple_system/rtl/ibex_simple_system.sv\n+++ b/examples/simple_system/rtl/ibex_simple_system.sv\n@@ -65,7 +65,7 @@ module ibex_simple_system (\n parameter bit BranchPredictor = 1'b0;\n parameter SRAMInitFile = \"\";\n \n- logic clk_sys = 1'b0, rst_sys_n;\n+ logic clk_sys, rst_sys_n;\n \n typedef enum logic {\n CoreD\n@@ -137,9 +137,12 @@ module ibex_simple_system (\n #8\n rst_sys_n = 1'b1;\n end\n- always begin\n- #1 clk_sys = 1'b0;\n- #1 clk_sys = 1'b1;\n+ initial begin\n+ clk_sys = 1'b0;\n+ forever begin\n+ #1 clk_sys = 1'b0;\n+ #1 clk_sys = 1'b1;\n+ end\n end\n `endif\n \n", "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// VCS does not support overriding enum and string parameters via command line. Instead, a `define\n// is used that can be set from the command line. If no value has been specified, this gives a\n// default. Other simulators don't take the detour via `define and can override the corresponding\n// parameters directly.\n`ifndef RV32M\n `define RV32M ibex_pkg::RV32MFast\n`endif\n\n`ifndef RV32B\n `define RV32B ibex_pkg::RV32BNone\n`endif\n\n`ifndef RV32ZC\n `define RV32ZC ibex_pkg::RV32ZcaZcbZcmp\n`endif\n\n`ifndef RegFile\n `define RegFile ibex_pkg::RegFileFF\n`endif\n\n`ifndef INSTR_CYCLE_DELAY\n `define INSTR_CYCLE_DELAY 0\n`endif\n\n/**\n * Ibex simple system\n *\n * This is a basic system consisting of an ibex, a 1 MB sram for instruction/data\n * and a small memory mapped control module for outputting ASCII text and\n * controlling/halting the simulation from the software running on the ibex.\n *\n * It is designed to be used with verilator but should work with other\n * simulators, a small amount of work may be required to support the\n * simulator_ctrl module.\n */\n\nmodule ibex_simple_system (\n input IO_CLK,\n input IO_RST_N\n);\n\n parameter bit SecureIbex = 1'b0;\n parameter int unsigned LockstepOffset = 1;\n parameter bit ICacheScramble = 1'b0;\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 ibex_pkg::rv32m_e RV32M = `RV32M;\n parameter ibex_pkg::rv32b_e RV32B = `RV32B;\n parameter ibex_pkg::rv32zc_e RV32ZC = `RV32ZC;\n parameter ibex_pkg::regfile_e RegFile = `RegFile;\n parameter bit BranchTargetALU = 1'b0;\n parameter bit WritebackStage = 1'b0;\n parameter bit ICache = 1'b0;\n parameter bit DbgTriggerEn = 1'b0;\n parameter bit ICacheECC = 1'b0;\n parameter bit ICacheTweakInfection = 1'b0;\n parameter bit BranchPredictor = 1'b0;\n parameter SRAMInitFile = \"\";\n\n logic clk_sys, rst_sys_n;\n\n typedef enum logic {\n CoreD\n } bus_host_e;\n\n typedef enum logic[1:0] {\n Ram,\n SimCtrl,\n Timer\n } bus_device_e;\n\n localparam int NrDevices = 3;\n localparam int NrHosts = 1;\n\n // interrupts\n logic timer_irq;\n\n // host and device signals\n logic host_req [NrHosts];\n logic host_gnt [NrHosts];\n logic [31:0] host_addr [NrHosts];\n logic host_we [NrHosts];\n logic [ 3:0] host_be [NrHosts];\n logic [31:0] host_wdata [NrHosts];\n logic host_rvalid [NrHosts];\n logic [31:0] host_rdata [NrHosts];\n logic host_err [NrHosts];\n\n logic [6:0] data_rdata_intg;\n logic [6:0] instr_rdata_intg;\n\n // devices (slaves)\n logic device_req [NrDevices];\n logic [31:0] device_addr [NrDevices];\n logic device_we [NrDevices];\n logic [ 3:0] device_be [NrDevices];\n logic [31:0] device_wdata [NrDevices];\n logic device_rvalid [NrDevices];\n logic [31:0] device_rdata [NrDevices];\n logic device_err [NrDevices];\n\n // Device address mapping\n logic [31:0] cfg_device_addr_base [NrDevices];\n logic [31:0] cfg_device_addr_mask [NrDevices];\n assign cfg_device_addr_base[Ram] = 32'h100000;\n assign cfg_device_addr_mask[Ram] = ~32'hFFFFF; // 1 MB\n assign cfg_device_addr_base[SimCtrl] = 32'h20000;\n assign cfg_device_addr_mask[SimCtrl] = ~32'h3FF; // 1 kB\n assign cfg_device_addr_base[Timer] = 32'h30000;\n assign cfg_device_addr_mask[Timer] = ~32'h3FF; // 1 kB\n\n // Instruction fetch signals\n logic instr_req;\n logic instr_gnt;\n logic instr_rvalid;\n logic [31:0] instr_addr;\n logic [31:0] instr_rdata;\n logic instr_err;\n\n assign instr_gnt = instr_req;\n assign instr_err = '0;\n\n `ifdef VERILATOR\n assign clk_sys = IO_CLK;\n assign rst_sys_n = IO_RST_N;\n `else\n initial begin\n rst_sys_n = 1'b0;\n #8\n rst_sys_n = 1'b1;\n end\n initial begin\n clk_sys = 1'b0;\n forever begin\n #1 clk_sys = 1'b0;\n #1 clk_sys = 1'b1;\n end\n end\n `endif\n\n // Tie-off unused error signals\n assign device_err[Ram] = 1'b0;\n assign device_err[SimCtrl] = 1'b0;\n\n bus #(\n .NrDevices ( NrDevices ),\n .NrHosts ( NrHosts ),\n .DataWidth ( 32 ),\n .AddressWidth ( 32 )\n ) u_bus (\n .clk_i (clk_sys),\n .rst_ni (rst_sys_n),\n\n .host_req_i (host_req ),\n .host_gnt_o (host_gnt ),\n .host_addr_i (host_addr ),\n .host_we_i (host_we ),\n .host_be_i (host_be ),\n .host_wdata_i (host_wdata ),\n .host_rvalid_o (host_rvalid ),\n .host_rdata_o (host_rdata ),\n .host_err_o (host_err ),\n\n .device_req_o (device_req ),\n .device_addr_o (device_addr ),\n .device_we_o (device_we ),\n .device_be_o (device_be ),\n .device_wdata_o (device_wdata ),\n .device_rvalid_i (device_rvalid),\n .device_rdata_i (device_rdata ),\n .device_err_i (device_err ),\n\n .cfg_device_addr_base,\n .cfg_device_addr_mask\n );\n\n if (SecureIbex) begin : g_mem_rdata_ecc\n logic [31:0] unused_data_rdata;\n logic [31:0] unused_instr_rdata;\n\n prim_secded_inv_39_32_enc u_data_rdata_intg_gen (\n .data_i (host_rdata[CoreD]),\n .data_o ({data_rdata_intg, unused_data_rdata})\n );\n\n prim_secded_inv_39_32_enc u_instr_rdata_intg_gen (\n .data_i (instr_rdata),\n .data_o ({instr_rdata_intg, unused_instr_rdata})\n );\n end else begin : g_no_mem_rdata_ecc\n assign data_rdata_intg = '0;\n assign instr_rdata_intg = '0;\n end\n\n ibex_top_tracing #(\n .SecureIbex ( SecureIbex ),\n .LockstepOffset ( LockstepOffset ),\n .ICacheScramble ( ICacheScramble ),\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 .RV32ZC ( RV32ZC ),\n .RegFile ( RegFile ),\n .BranchTargetALU ( BranchTargetALU ),\n .ICache ( ICache ),\n .ICacheECC ( ICacheECC ),\n .ICacheTweakInfection ( ICacheTweakInfection ),\n .WritebackStage ( WritebackStage ),\n .BranchPredictor ( BranchPredictor ),\n .DbgTriggerEn ( DbgTriggerEn ),\n .DmBaseAddr ( 32'h00100000 ),\n .DmAddrMask ( 32'h00000003 ),\n .DmHaltAddr ( 32'h00100000 ),\n .DmExceptionAddr ( 32'h00100000 )\n ) u_top (\n .clk_i (clk_sys),\n .rst_ni (rst_sys_n),\n\n .test_en_i (1'b0),\n .scan_rst_ni (1'b1),\n .ram_cfg_icache_tag_i (prim_ram_1p_pkg::RAM_1P_CFG_DEFAULT),\n .ram_cfg_rsp_icache_tag_o (),\n .ram_cfg_icache_data_i (prim_ram_1p_pkg::RAM_1P_CFG_DEFAULT),\n .ram_cfg_rsp_icache_data_o (),\n\n .hart_id_i (32'b0),\n // First instruction executed is at 0x0 + 0x80\n .boot_addr_i (32'h00100000),\n\n .instr_req_o (instr_req),\n .instr_gnt_i (instr_gnt),\n .instr_rvalid_i (instr_rvalid),\n .instr_addr_o (instr_addr),\n .instr_rdata_i (instr_rdata),\n .instr_rdata_intg_i (instr_rdata_intg),\n .instr_err_i (instr_err),\n\n .data_req_o (host_req[CoreD]),\n .data_gnt_i (host_gnt[CoreD]),\n .data_rvalid_i (host_rvalid[CoreD]),\n .data_we_o (host_we[CoreD]),\n .data_be_o (host_be[CoreD]),\n .data_addr_o (host_addr[CoreD]),\n .data_wdata_o (host_wdata[CoreD]),\n .data_wdata_intg_o (),\n .data_rdata_i (host_rdata[CoreD]),\n .data_rdata_intg_i (data_rdata_intg),\n .data_err_i (host_err[CoreD]),\n\n .irq_software_i (1'b0),\n .irq_timer_i (timer_irq),\n .irq_external_i (1'b0),\n .irq_fast_i (15'b0),\n .irq_nm_i (1'b0),\n\n .scramble_key_valid_i ('0),\n .scramble_key_i ('0),\n .scramble_nonce_i ('0),\n .scramble_req_o (),\n\n .debug_req_i (1'b0),\n .crash_dump_o (),\n .double_fault_seen_o (),\n\n .fetch_enable_i (ibex_pkg::IbexMuBiOn),\n .alert_minor_o (),\n .alert_major_internal_o (),\n .alert_major_bus_o (),\n .core_sleep_o (),\n\n .lockstep_cmp_en_o (),\n\n .data_req_shadow_o (),\n .data_we_shadow_o (),\n .data_be_shadow_o (),\n .data_addr_shadow_o (),\n .data_wdata_shadow_o (),\n .data_wdata_intg_shadow_o (),\n\n .instr_req_shadow_o (),\n .instr_addr_shadow_o ()\n );\n\n // SRAM block for instruction and data storage\n ram_2p #(\n .Depth(1024*1024/4),\n .BExtraDelay(`INSTR_CYCLE_DELAY),\n .MemInitFile(SRAMInitFile)\n ) u_ram (\n .clk_i (clk_sys),\n .rst_ni (rst_sys_n),\n\n .a_req_i (device_req[Ram]),\n .a_we_i (device_we[Ram]),\n .a_be_i (device_be[Ram]),\n .a_addr_i (device_addr[Ram]),\n .a_wdata_i (device_wdata[Ram]),\n .a_rvalid_o (device_rvalid[Ram]),\n .a_rdata_o (device_rdata[Ram]),\n\n .b_req_i (instr_req),\n .b_we_i (1'b0),\n .b_be_i (4'b0),\n .b_addr_i (instr_addr),\n .b_wdata_i (32'b0),\n .b_rvalid_o (instr_rvalid),\n .b_rdata_o (instr_rdata)\n );\n\n simulator_ctrl #(\n .LogName(\"ibex_simple_system.log\")\n ) u_simulator_ctrl (\n .clk_i (clk_sys),\n .rst_ni (rst_sys_n),\n\n .req_i (device_req[SimCtrl]),\n .we_i (device_we[SimCtrl]),\n .be_i (device_be[SimCtrl]),\n .addr_i (device_addr[SimCtrl]),\n .wdata_i (device_wdata[SimCtrl]),\n .rvalid_o (device_rvalid[SimCtrl]),\n .rdata_o (device_rdata[SimCtrl])\n );\n\n timer #(\n .DataWidth (32),\n .AddressWidth (32)\n ) u_timer (\n .clk_i (clk_sys),\n .rst_ni (rst_sys_n),\n\n .timer_req_i (device_req[Timer]),\n .timer_we_i (device_we[Timer]),\n .timer_be_i (device_be[Timer]),\n .timer_addr_i (device_addr[Timer]),\n .timer_wdata_i (device_wdata[Timer]),\n .timer_rvalid_o (device_rvalid[Timer]),\n .timer_rdata_o (device_rdata[Timer]),\n .timer_err_o (device_err[Timer]),\n .timer_intr_o (timer_irq)\n );\n\n export \"DPI-C\" function mhpmcounter_num;\n\n function automatic int unsigned mhpmcounter_num();\n return u_top.u_ibex_top.u_ibex_core.cs_registers_i.MHPMCounterNum;\n endfunction\n\n export \"DPI-C\" function mhpmcounter_get;\n\n function automatic longint unsigned mhpmcounter_get(int index);\n return u_top.u_ibex_top.u_ibex_core.cs_registers_i.mhpmcounter[index];\n endfunction\n\nendmodule\n", "selected_doc_paths": ["doc/02_user/examples.rst", "doc/02_user/integration.rst", "doc/02_user/configuration.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 2269, "lang": "sv", "rtl_files": ["rtl/ibex_decoder.sv"], "spec": "# Behavioral Design Specification: Ibex Instruction Decoder\n\n## Overview\n\nThe instruction decoder is a purely combinational block within the Ibex processor’s instruction decode and execute (ID/EX) stage. It receives a 32-bit uncompressed instruction (after any compressed-to-uncompressed conversion performed earlier) and generates all control signals required to execute that instruction in the same cycle. The decoder is responsible for:\n\n- Identifying the instruction type and checking its legality.\n- Generating immediates in all RISC-V formats (I, S, B, U, J, Z).\n- Selecting the source operands for the ALU, branch target calculation, and register file writes.\n- Controlling the multiplier/divider, load-store unit (LSU), and CSR block.\n- Flagging special instructions (ECALL, EBREAK, MRET, DRET, WFI) and handling instruction fence.\n\nThe decoder’s behavior is parameterized by the core configuration (RV32E, RV32M, RV32B, and BranchTargetALU). It does **not** contain any state; all outputs are determined directly from the current instruction and a few external qualifier signals (instruction first‑cycle indicator, branch taken decision, and a compressed‑instruction illegal flag).\n\n## Inputs and Outputs (Conceptual)\n\nThe decoder receives:\n\n- **Instruction data** (32 bits uncompressed) – the opcode, register specifiers, and immediate fields.\n- **Instruction first‑cycle indicator** – a flag that is asserted when the instruction is newly entering the ID/EX stage.\n- **Branch taken decision** – the registered outcome of a previous branch condition evaluation.\n- **Compressed‑instruction illegal flag** – asserted if a compressed instruction could not be decoded into a valid uncompressed form.\n\nThe decoder produces:\n\n- **Register file controls** – read addresses for operand A and B, write address, write enable, read enables, and write‑data source selection.\n- **ALU controls** – operation select, operand A and B mux selects, and a multi‑cycle indicator.\n- **Immediate outputs** – six different immediate values: I‑type, S‑type, B‑type, U‑type, J‑type, and Z‑type (zero‑extended rs1 for CSR immediates).\n- **ALU immediate mux selects** – for the ALU’s operand A and B, and separate mux selects for the branch target calculation path.\n- **Multiplier/divider controls** – operation select, signed mode, enable signals (mult, div), and static selection signals for data muxes.\n- **LSU controls** – data request, write enable, data size, sign extension.\n- **CSR controls** – access request, operation type (read, write, set, clear), and address.\n- **Jump/branch controls** – jump‑in‑decoder indication, jump set signal, branch‑in‑decoder indication, and instruction cache invalidate.\n- **Special instruction flags** – illegal instruction, EBREAK, MRET, DRET, ECALL, WFI.\n\n## Functional Behavior\n\n### Instruction Decoding and Illegal Detection\n\nThe decoder examines the opcode field (bits 6:0) to determine the instruction category. For each opcode, further fields (funct3, funct7, rs1, rs2, rd, etc.) are checked for validity. Any invalid combination of opcode, funct3, funct7, rs1, or immediate fields shall cause the illegal instruction flag to be asserted. The following rules apply:\n\n- **Jumps (JAL, JALR):** JALR requires funct3 == 0; otherwise illegal.\n- **Branches (BRANCH):** Only funct3 values 000, 001, 100, 101, 110, 111 are legal. Any other funct3 value is illegal.\n- **Loads (LOAD):** Only funct3 values 000, 001, 010 are legal for standard loads (lb, lh, lw). The combination funct3=110 (lwu) is illegal. All other funct3 values are illegal.\n- **Stores (STORE):** The high bit of funct3 (bit 14 of the instruction) must be 0. Only funct3 values 000, 001, 010 are legal (sb, sh, sw).\n- **Immediate ALU (OP‑IMM):** For funct3=001 and funct3=101, the legality of the instruction depends on the upper bits of the instruction (func7) and the configured bit‑manipulation extension (RV32B). Many shift and bit‑manipulation operations are guarded by configuration parameters. Any combination not explicitly listed in the decoder’s internal tables is illegal.\n- **Register‑register ALU (OP):** The decoder defines a large set of allowed combinations of funct7 and funct3. For RV32M instructions (mul, div, rem variants) the illegal flag is deasserted only when the RV32M parameter is not set to “None”. For RV32B instructions, the illegal flag is asserted unless the specific sub‑extension is enabled according to the RV32B parameter (RV32BNone, RV32BBalanced, RV32BOTEarlGrey, or RV32BFull). All other combinations are illegal.\n- **System instructions (SYSTEM):** For funct3=000, only specific immediate values (ECALL, EBREAK, MRET, DRET, WFI) are legal. Additionally, rs1 and rd must both be zero; otherwise the instruction is illegal.\n- **MISC‑MEM (FENCE, FENCE.I):** Only funct3=000 and funct3=001 are legal. Any other funct3 value is illegal.\n- **All other opcodes** (LUI, AUIPC) are always legal.\n\nIf the compressed‑instruction illegal flag is asserted, the decoder shall force the illegal instruction output regardless of the uncompressed instruction content.\n\n### RV32E Register File Check\n\nWhen the RV32E parameter is enabled, the decoder shall check that any register file access (read addresses or write address) does not use register indices with the most significant bit set (i.e., registers 16–31 are illegal). If such an access is attempted and the corresponding operand mux selects a register value, the illegal instruction output shall be asserted and the register file write enable shall be suppressed.\n\n### Immediate Generation\n\nThe decoder shall produce the following immediate values by extracting and sign‑extending the appropriate instruction fields:\n\n- **I‑type:** 12‑bit signed immediate from bits [31:20], sign‑extended to 32 bits.\n- **S‑type:** 12‑bit signed immediate constructed from bits [31:25] and [11:7], sign‑extended.\n- **B‑type:** 13‑bit signed immediate constructed from bits [31], [7], [30:25], [11:8], with a trailing zero, sign‑extended to 32 bits.\n- **U‑type:** 20‑bit unsigned immediate from bits [31:12], shifted left by 12 bits.\n- **J‑type:** 21‑bit signed immediate constructed from bits [31], [19:12], [20], [30:21], with a trailing zero, sign‑extended.\n- **Z‑type:** Zero‑extended 5‑bit immediate from the rs1 field (bits [19:15]).\n\n### Register File Controls\n\nThe decoder shall provide the following register file controls:\n\n- **Read addresses:** Two read addresses are produced. The first read address (for operand A) is normally the rs1 field; for certain multi‑cycle bit‑manipulation instructions that use rs3 (funct3 field), the address shall be switched to the rs3 field during the second cycle of the instruction. The switch is controlled by an internal flop that records the need for rs3 during the first cycle. The second read address (for operand B) is always the rs2 field.\n- **Write address:** Taken from the rd field (bits [11:7]).\n- **Read enables:** Asserted whenever the instruction requires reading from the corresponding register. For JALR, loads, stores, immediate ALU operations, register‑register ALU operations, and CSR operations that use rs1, the read enable for operand A is asserted. For branches and register‑register ALU operations, read enables for both operand A and operand B are asserted.\n- **Write enable:** Asserted for instructions that write a result to the register file: JAL and JALR (in the second cycle, and also in the first cycle if BranchTargetALU is configured), LUI, AUIPC, immediate ALU, register‑register ALU, CSR reads/writes. Write enable shall be suppressed if the instruction is detected as illegal (including RV32E register violations).\n- **Write‑data source:** Selects one of several sources: ALU result, load data, CSR read data, or (for the second cycle of jumps) PC+4.\n\n### ALU Control\n\nThe decoder shall produce the ALU operation and operand mux selects. The ALU is used for integer computation, branch condition evaluation, address calculation, and PC‑relative calculations. Two separate mux select signals exist: one for the main ALU and one for the branch target ALU (when BranchTargetALU is enabled). The behavior differs based on instruction type and the first‑cycle indicator.\n\n- **Operand A mux select:** Chooses between register value (rs1), current PC, immediate, or zero. For example, LUI uses zero; AUIPC uses PC; immediate ALU and loads use register value; CSR operations may use register value or immediate depending on funct3[2].\n- **Operand B mux select:** Chooses between register value (rs2) or an immediate. The immediate type is further selected by the immediate B mux select (I, S, B, U, J, or increment‑PC).\n- **ALU operation:** The operation is selected according to the instruction’s function codes (funct3 and funct7). Standard RV32I operations (add, sub, slt, sltu, xor, or, and, sll, srl, sra) are unconditionally supported. Bit‑manipulation operations (e.g., rol, ror, pack, clmul, etc.) are only available when the corresponding sub‑extension is enabled via RV32B. Multiplier/divider operations set the ALU operation to add and simultaneously assert a separate multiplier or divider enable signal.\n\nFor **jumps** (JAL, JALR), the decoder uses the ALU to calculate the jump target (PC+offset or reg+offset) in the first cycle if BranchTargetALU is disabled; in the second cycle it calculates PC+4 for the link. If BranchTargetALU is enabled, the first cycle calculates PC+4 and the jump target is computed by a separate branch‑target ALU (not controlled by these muxes).\n\nFor **branches**, the decoder evaluates the branch condition in the first cycle (using the main ALU with operands A=rs1, B=rs2) and then in the second cycle (if BranchTargetALU is disabled) calculates the branch target using the main ALU. If BranchTargetALU is enabled, the branch target is computed in parallel with the condition evaluation.\n\nFor **loads and stores**, the ALU computes the memory address (base register + immediate offset). The address calculation uses the I‑type or S‑type immediate as appropriate.\n\nFor **FENCE.I**, the decoder behaves like a jump to the next PC (PC+4) to flush the instruction pipeline and prefetch buffer. If an instruction cache is present, the cache is invalidated.\n\n### Multi‑Cycle Indicator\n\nCertain bit‑manipulation instructions require more than one cycle in the ALU but do not involve the multiplier/divider. Examples include CRC operations (Zbr), funnel shifts (Zbt), rotate, compress/decompress (Zbe), and general reverse (GORC/GREV). The decoder shall assert a multi‑cycle indicator for these instructions, which causes the ID/EX stage to stall until the operation completes.\n\n### Multiplier/Divider Control\n\nFor RV32M instructions (mul, mulh, mulhsu, mulhu, div, divu, rem, remu), the decoder shall:\n\n- Assert the multiplier or divider enable signal, depending on the instruction.\n- Set the static selection signals (`mult_sel`, `div_sel`) to route the appropriate result from the multiplier/divider block to the write‑data mux.\n- Set the operation (`multdiv_operator`) to the correct one (MULL, MULH, DIV, REM).\n- Set the signed mode to control signed/unsigned interpretation of the operands.\n\nThese enables shall be suppressed if the instruction is illegal.\n\n### Load‑Store Unit Control\n\nFor **loads**: The decoder shall assert the data request, set the data type (byte, halfword, word), and set the sign‑extension control (0 for zero‑extension, 1 for sign‑extension). Loads with funct3=110 (lwu) are illegal. For **stores**: The decoder shall assert data request and write enable, and set the data type. The ALU is configured to compute the store address using the S‑type immediate.\n\n### CSR Control\n\nFor CSR instructions (opcode SYSTEM with funct3 ≠ 0), the decoder shall:\n\n- Assert the CSR access request.\n- Select the CSR operation type (read, write, set, clear) based on funct3.\n- Forward the CSR address (from the immediate field) to the CSR block.\n- Set the register file write‑data source to the CSR read data.\n- Enable reading from rs1 when the immediate‑based variant (CSRRSI/CSRRCI) is not used.\n- If the operation is SET or CLEAR and the rs1 field is zero, the operation shall be downgraded to a read (to prevent unwanted CSR modification).\n\nFor non‑CSR system instructions (ECALL, EBREAK, MRET, DRET, WFI), the decoder shall set the corresponding output flags and suppress all other actions (register file writes, data requests, etc.).\n\n### Jump, Branch, and Fence Control\n\n- **Jump (JAL, JALR):** The decoder shall assert `jump_in_dec` and, in the first cycle, assert `jump_set` (to signal the controller to begin fetching from the new PC). In the second cycle, a link address (PC+4) is written to the register file.\n- **Branch:** The decoder shall assert `branch_in_dec`. The ALU condition evaluation is performed in the first cycle. In the second cycle (or in parallel with BranchTargetALU), the branch target is computed. The target may be the not‑taken path (PC+4) for secure mode operation if the branch is not taken.\n- **FENCE.I:** Treated as a jump to PC+4. The decoder shall assert `jump_in_dec`, `jump_set` (in the first cycle), and also assert `icache_inval` if an instruction cache is present.\n\nAll jump and branch control signals shall be suppressed if the instruction is illegal.\n\n### Handling of Illegal, Compressed, and RV32E Violations\n\nWhen the illegal instruction flag is asserted (due to any reason: illegal opcode, invalid funct fields, illegal compressed instruction, or RV32E register violations), the decoder shall:\n\n- Suppress the register file write enable.\n- Suppress all LSU control signals (data request, write enable).\n- Suppress all jump and branch control signals.\n- Suppress the CSR access request.\n- Suppress the multiplier/divider enables.\n\nThe illegal instruction output shall be the logical OR of the decoder‑detected illegal signal and the RV32E register‑check result. The register file write enable output shall be the write enable ANDed with the inverse of the RV32E register violation (so that an illegal register access does not cause a write).\n\n## Parameterization\n\n- **RV32E (bit):** When set to 1, the decoder shall enforce that register indices 16–31 are not used (except for immediate selections that do not access the register file). When set to 0, no such check is performed.\n- **RV32M (enum):** Determines which, if any, multiply/divide instructions are legal and enabled. Values: None, SingleCycle, Fast, Slow.\n- **RV32B (enum):** Determines which bit‑manipulation sub‑extensions are supported. Values: None, Balanced, OTEarlGrey, Full. The decoder shall assert the illegal flag for any bit‑manipulation instruction that is not included in the selected configuration.\n- **BranchTargetALU (bit):** When set to 1, a separate branch‑target ALU is available. This changes the timing of jump and branch target calculations: jump targets are computed in the first cycle, and only PC+4 remains for the second cycle; branch targets are computed in parallel with the condition, allowing a one‑cycle reduction in taken branch latency.\n\n## Combinational Nature\n\nAll outputs are combinatorial functions of the inputs. The decoder does not contain any registered state except for a small one‑bit flop used to remember the need for rs3 in the second cycle of certain bit‑manipulation instructions (rs3 is known one cycle ahead). This flop is present only when RV32B is not set to None. In all other respects, the decoder is fully combinational and shall produce outputs within one clock cycle of the instruction being presented.", "commit_id": "594ea976c9dad793f87edf91ec1c4c1df447e6dc", "timestamp": "2025-04-25T12:57:41+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "0199c03ea4b9d1c9a9178a9ed209b3a5b68ae33a", "pr_title": "[rtl] Minor tweak to decoder to avoid dead code", "pr_body": "The \"else\" part of the if/else check here wasn't possible because the surrounding else branch (starting at line 406) is already in the case where instr[26] is zero.\r\n\r\nFixes #2268.", "issue_title": "[bug][ibex_decoder] Report a bug in Ibex", "issue_body": "Hi all!\n\nI am using a static analysis to found a various bugs in open source RTL designs.\n\nIt was founded that in `ibex_decoder.sv` RTL file dead code is exists [here](https://github.com/lowRISC/ibex/blob/master/rtl/ibex_decoder.sv#L439).\n\nThis assignment under `else` statement is never executed due to [this](https://github.com/lowRISC/ibex/blob/master/rtl/ibex_decoder.sv#L406) external `else` branch with `!instr[26]` condition.", "commit_message": "[rtl] Minor tweak to decoder to avoid dead code\n\nThe \"else\" part of the if/else check here wasn't possible because the\nsurrounding else branch (starting at line 406) is already in the case\nwhere instr[26] is zero.", "fix_patch": "diff --git a/rtl/ibex_decoder.sv b/rtl/ibex_decoder.sv\nindex 6e925f5651..880885575f 100644\n--- a/rtl/ibex_decoder.sv\n+++ b/rtl/ibex_decoder.sv\n@@ -433,11 +433,10 @@ module ibex_decoder #(\n end\n end\n 5'b0_0001: begin\n- if (instr[26] == 1'b0) begin // unshfl\n- illegal_insn = (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) ? 1'b0 : 1'b1;\n- end else begin\n- illegal_insn = 1'b1;\n- end\n+ // Since instr[26] is known to be 0, this must be the \"unshfl\" instruction, which\n+ // is part of the RISC-V bitmanip extension. This is supported for the\n+ // RV32BOTEarlGrey and RV32BFull bitmanip configurations.\n+ illegal_insn = (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) ? 1'b0 : 1'b1;\n end\n \n default: illegal_insn = 1'b1;\n", "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 * Instruction decoder\n *\n * This module is fully combinatorial, clock and reset are used for\n * assertions only.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_decoder #(\n parameter bit RV32E = 0,\n parameter ibex_pkg::rv32m_e RV32M = ibex_pkg::RV32MFast,\n parameter ibex_pkg::rv32b_e RV32B = ibex_pkg::RV32BNone,\n parameter bit BranchTargetALU = 0\n) (\n input logic clk_i,\n input logic rst_ni,\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 input logic branch_taken_i, // registered branch decision\n output logic icache_inval_o,\n\n // from IF-ID pipeline register\n input logic instr_first_cycle_i, // instruction read is in its first cycle\n input logic [31:0] instr_rdata_i, // instruction read from memory/cache\n input logic [31:0] instr_rdata_alu_i, // instruction read from memory/cache\n // replicated to ease fan-out)\n\n input logic illegal_c_insn_i, // compressed instruction decode failed\n\n // immediates\n output ibex_pkg::imm_a_sel_e imm_a_mux_sel_o, // immediate selection for operand a\n output ibex_pkg::imm_b_sel_e imm_b_mux_sel_o, // immediate selection for operand b\n output ibex_pkg::op_a_sel_e bt_a_mux_sel_o, // branch target selection operand a\n output ibex_pkg::imm_b_sel_e bt_b_mux_sel_o, // branch target selection 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_pkg::rf_wd_sel_e rf_wdata_sel_o, // RF write data selection\n output logic rf_we_o, // write enable for regfile\n output logic [4:0] rf_raddr_a_o,\n output logic [4:0] rf_raddr_b_o,\n output logic [4:0] rf_waddr_o,\n output logic rf_ren_a_o, // Instruction reads from RF addr A\n output logic rf_ren_b_o, // Instruction reads from RF addr B\n\n // ALU\n output ibex_pkg::alu_op_e alu_operator_o, // ALU operation selection\n output ibex_pkg::op_a_sel_e alu_op_a_mux_sel_o, // operand a selection: reg value, PC,\n // immediate or zero\n output ibex_pkg::op_b_sel_e alu_op_b_mux_sel_o, // operand b selection: reg value or\n // immediate\n output logic alu_multicycle_o, // ternary bitmanip instruction\n\n // MULT & DIV\n output logic mult_en_o, // perform integer multiplication\n output logic div_en_o, // perform integer division or remainder\n output logic mult_sel_o, // as above but static, for data muxes\n output logic div_sel_o, // as above but static, for data muxes\n\n output ibex_pkg::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_pkg::csr_op_e csr_op_o, // operation to perform on CSR\n output ibex_pkg::csr_num_e csr_addr_o, // CSR address\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\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_pkg::*;\n\n logic illegal_insn;\n logic illegal_reg_rv32e;\n logic csr_illegal;\n logic rf_we;\n\n logic [31:0] instr;\n logic [31:0] instr_alu;\n logic [9:0] unused_instr_alu;\n // Source/Destination register instruction index\n logic [4:0] instr_rs1;\n logic [4:0] instr_rs2;\n logic [4:0] instr_rs3;\n logic [4:0] instr_rd;\n\n logic use_rs3_d;\n logic use_rs3_q;\n\n csr_op_e csr_op;\n\n opcode_e opcode;\n opcode_e opcode_alu;\n\n // To help timing the flops containing the current instruction are replicated to reduce fan-out.\n // instr_alu is used to determine the ALU control logic and associated operand/imm select signals\n // as the ALU is often on the more critical timing paths. instr is used for everything else.\n assign instr = instr_rdata_i;\n assign instr_alu = instr_rdata_alu_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 assign csr_addr_o = csr_num_e'(instr[31:20]);\n\n // immediate for CSR manipulation (zero extended)\n assign zimm_rs1_type_o = { 27'b0, instr_rs1 }; // rs1\n\n if (RV32B != RV32BNone) begin : gen_rs3_flop\n // the use of rs3 is known one cycle ahead.\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n use_rs3_q <= 1'b0;\n end else begin\n use_rs3_q <= use_rs3_d;\n end\n end\n end else begin : gen_no_rs3_flop\n logic unused_clk;\n logic unused_rst_n;\n\n // Clock and reset unused when there's no rs3 flop\n assign unused_clk = clk_i;\n assign unused_rst_n = rst_ni;\n\n // always zero\n assign use_rs3_q = use_rs3_d;\n end\n\n // source registers\n assign instr_rs1 = instr[19:15];\n assign instr_rs2 = instr[24:20];\n assign instr_rs3 = instr[31:27];\n assign rf_raddr_a_o = (use_rs3_q & ~instr_first_cycle_i) ? instr_rs3 : instr_rs1; // rs3 / rs1\n assign rf_raddr_b_o = instr_rs2; // rs2\n\n // destination register\n assign instr_rd = instr[11:7];\n assign rf_waddr_o = instr_rd; // rd\n\n ////////////////////\n // Register check //\n ////////////////////\n if (RV32E) begin : gen_rv32e_reg_check_active\n assign illegal_reg_rv32e = ((rf_raddr_a_o[4] & (alu_op_a_mux_sel_o == OP_A_REG_A)) |\n (rf_raddr_b_o[4] & (alu_op_b_mux_sel_o == OP_B_REG_B)) |\n (rf_waddr_o[4] & rf_we));\n end else begin : gen_rv32e_reg_check_inactive\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_rs1 == '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 icache_inval_o = 1'b0;\n\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n\n rf_wdata_sel_o = RF_WD_EX;\n rf_we = 1'b0;\n rf_ren_a_o = 1'b0;\n rf_ren_b_o = 1'b0;\n\n csr_access_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_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\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n jump_in_dec_o = 1'b1;\n\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n if (instr[14:12] != 3'b0) begin\n illegal_insn = 1'b1;\n end\n\n rf_ren_a_o = 1'b1;\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,\n 3'b001,\n 3'b100,\n 3'b101,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n default: illegal_insn = 1'b1;\n endcase\n\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n end\n\n ////////////////\n // Load/store //\n ////////////////\n\n OPCODE_STORE: begin\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n data_req_o = 1'b1;\n data_we_o = 1'b1;\n\n if (instr[14]) begin\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: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_LOAD: begin\n rf_ren_a_o = 1'b1;\n data_req_o = 1'b1;\n data_type_o = 2'b00;\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(u)\n 2'b01: data_type_o = 2'b01; // lh(u)\n 2'b10: begin\n data_type_o = 2'b00; // lw\n if (instr[14]) begin\n illegal_insn = 1'b1; // lwu does not exist\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n /////////\n // ALU //\n /////////\n\n OPCODE_LUI: begin // Load Upper Immediate\n rf_we = 1'b1;\n end\n\n OPCODE_AUIPC: begin // Add Upper Immediate to PC\n rf_we = 1'b1;\n end\n\n OPCODE_OP_IMM: begin // Register-Immediate ALU Operations\n rf_ren_a_o = 1'b1;\n rf_we = 1'b1;\n\n unique case (instr[14:12])\n 3'b000,\n 3'b010,\n 3'b011,\n 3'b100,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n\n 3'b001: begin\n unique case (instr[31:27])\n 5'b0_0000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // slli\n 5'b0_0100: begin // sloi\n illegal_insn = (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) ? 1'b0 : 1'b1;\n end\n 5'b0_1001, // bclri\n 5'b0_0101, // bseti\n 5'b0_1101: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // binvi\n 5'b0_0001: begin\n if (instr[26] == 1'b0) begin // shfl\n illegal_insn = (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) ? 1'b0 : 1'b1;\n end else begin\n illegal_insn = 1'b1;\n end\n end\n 5'b0_1100: begin\n unique case(instr[26:20])\n 7'b000_0000, // clz\n 7'b000_0001, // ctz\n 7'b000_0010, // cpop\n 7'b000_0100, // sext.b\n 7'b000_0101: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sext.h\n 7'b001_0000, // crc32.b\n 7'b001_0001, // crc32.h\n 7'b001_0010, // crc32.w\n 7'b001_1000, // crc32c.b\n 7'b001_1001, // crc32c.h\n 7'b001_1010: begin // crc32c.w\n illegal_insn = (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) ? 1'b0 : 1'b1;\n end\n default: illegal_insn = 1'b1;\n endcase\n end\n default : illegal_insn = 1'b1;\n endcase\n end\n\n 3'b101: begin\n if (instr[26]) begin\n illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // fsri\n end else begin\n unique case (instr[31:27])\n 5'b0_0000, // srli\n 5'b0_1000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // srai\n\n 5'b0_0100: begin // sroi\n illegal_insn = (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) ? 1'b0 : 1'b1;\n end\n 5'b0_1100, // rori\n 5'b0_1001: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // bexti\n\n 5'b0_1101: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) begin\n illegal_insn = 1'b0; // grevi\n end else if (RV32B == RV32BBalanced) begin\n illegal_insn = (instr[24:20] == 5'b11000) ? 1'b0 : 1'b1; // rev8\n end else begin\n illegal_insn = 1'b1;\n end\n end\n 5'b0_0101: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) begin\n illegal_insn = 1'b0; // gorci\n end else if (instr[24:20] == 5'b00111) begin\n illegal_insn = (RV32B == RV32BBalanced) ? 1'b0 : 1'b1; // orc.b\n end else begin\n illegal_insn = 1'b1;\n end\n end\n 5'b0_0001: begin\n // Since instr[26] is known to be 0, this must be the \"unshfl\" instruction, which\n // is part of the RISC-V bitmanip extension. This is supported for the\n // RV32BOTEarlGrey and RV32BFull bitmanip configurations.\n illegal_insn = (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) ? 1'b0 : 1'b1;\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_OP: begin // Register-Register ALU operation\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n rf_we = 1'b1;\n if ({instr[26], instr[13:12]} == {1'b1, 2'b01}) begin\n illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // cmix / cmov / fsl / fsr\n end else begin\n unique case ({instr[31:25], instr[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000},\n {7'b010_0000, 3'b000},\n {7'b000_0000, 3'b010},\n {7'b000_0000, 3'b011},\n {7'b000_0000, 3'b100},\n {7'b000_0000, 3'b110},\n {7'b000_0000, 3'b111},\n {7'b000_0000, 3'b001},\n {7'b000_0000, 3'b101},\n {7'b010_0000, 3'b101}: illegal_insn = 1'b0;\n\n // RV32B zba\n {7'b001_0000, 3'b010}, // sh1add\n {7'b001_0000, 3'b100}, // sh2add\n {7'b001_0000, 3'b110}, // sh3add\n // RV32B zbb\n {7'b010_0000, 3'b111}, // andn\n {7'b010_0000, 3'b110}, // orn\n {7'b010_0000, 3'b100}, // xnor\n {7'b011_0000, 3'b001}, // rol\n {7'b011_0000, 3'b101}, // ror\n {7'b000_0101, 3'b100}, // min\n {7'b000_0101, 3'b110}, // max\n {7'b000_0101, 3'b101}, // minu\n {7'b000_0101, 3'b111}, // maxu\n {7'b000_0100, 3'b100}, // pack\n {7'b010_0100, 3'b100}, // packu\n {7'b000_0100, 3'b111}, // packh\n // RV32B zbs\n {7'b010_0100, 3'b001}, // bclr\n {7'b001_0100, 3'b001}, // bset\n {7'b011_0100, 3'b001}, // binv\n {7'b010_0100, 3'b101}, // bext\n // RV32B zbf\n {7'b010_0100, 3'b111}: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // bfp\n // RV32B zbp\n {7'b011_0100, 3'b101}, // grev\n {7'b001_0100, 3'b101}, // gorc\n {7'b000_0100, 3'b001}, // shfl\n {7'b000_0100, 3'b101}, // unshfl\n {7'b001_0100, 3'b010}, // xperm.n\n {7'b001_0100, 3'b100}, // xperm.b\n {7'b001_0100, 3'b110}, // xperm.h\n {7'b001_0000, 3'b001}, // slo\n {7'b001_0000, 3'b101}, // sro\n // RV32B zbc\n {7'b000_0101, 3'b001}, // clmul\n {7'b000_0101, 3'b010}, // clmulr\n {7'b000_0101, 3'b011}: begin // clmulh\n illegal_insn = (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) ? 1'b0 : 1'b1;\n end\n // RV32B zbe\n {7'b010_0100, 3'b110}, // bdecompress\n {7'b000_0100, 3'b110}: illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // bcompress\n\n // RV32M instructions\n {7'b000_0001, 3'b000}: begin // mul\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b01;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b100}: begin // div\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b101}: begin // divu\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b110}: begin // rem\n multdiv_operator_o = MD_OP_REM;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b111}: begin // remu\n multdiv_operator_o = MD_OP_REM;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\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 unique case (instr[14:12])\n 3'b000: begin\n // FENCE is treated as a NOP since all memory operations are already strictly ordered.\n rf_we = 1'b0;\n end\n 3'b001: begin\n // FENCE.I is implemented as a jump to the next PC, this gives the required flushing\n // behaviour (iside prefetch buffer flushed and response to any outstanding iside\n // requests will be ignored).\n // If present, the ICache will also be flushed.\n jump_in_dec_o = 1'b1;\n\n rf_we = 1'b0;\n\n if (instr_first_cycle_i) begin\n jump_set_o = 1'b1;\n icache_inval_o = 1'b1;\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr[14:12] == 3'b000) begin\n // non CSR related SYSTEM instructions\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_rs1 != 5'b0 || instr_rd != 5'b0) 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 rf_wdata_sel_o = RF_WD_CSR;\n rf_we = 1'b1;\n\n if (~instr[14]) begin\n rf_ren_a_o = 1'b1;\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 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, PC\n // NOTE: instructions can also be detected to be illegal inside the CSRs (upon accesses with\n // insufficient privileges), or when accessing non-available registers in RV32E,\n // these cases are not handled here\n if (illegal_insn) begin\n rf_we = 1'b0;\n data_req_o = 1'b0;\n data_we_o = 1'b0;\n jump_in_dec_o = 1'b0;\n jump_set_o = 1'b0;\n branch_in_dec_o = 1'b0;\n csr_access_o = 1'b0;\n end\n end\n\n /////////////////////////////\n // Decoder for ALU control //\n /////////////////////////////\n\n always_comb begin\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 bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_I;\n\n\n opcode_alu = opcode_e'(instr_alu[6:0]);\n\n use_rs3_d = 1'b0;\n alu_multicycle_o = 1'b0;\n mult_sel_o = 1'b0;\n div_sel_o = 1'b0;\n\n unique case (opcode_alu)\n\n ///////////\n // Jumps //\n ///////////\n\n OPCODE_JAL: begin // Jump and Link\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_J;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_REG_A;\n bt_b_mux_sel_o = IMM_B_I;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_BRANCH: begin // Branch\n // Check branch condition selection\n unique case (instr_alu[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: ;\n endcase\n\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n // Not-taken branch will jump to next instruction (used in secure mode)\n bt_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n end\n\n // Without branch target ALU, a branch is a two-stage operation using the Main ALU in both\n // stages\n if (instr_first_cycle_i) begin\n // First evaluate the 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 if (!BranchTargetALU) begin\n // Then calculate jump target\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n // Not-taken branch will jump to next instruction (used in secure mode)\n imm_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n alu_operator_o = ALU_ADD;\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 alu_operator_o = ALU_ADD;\n\n if (!instr_alu[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\n end\n\n OPCODE_LOAD: begin\n alu_op_a_mux_sel_o = OP_A_REG_A;\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 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 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 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\n unique case (instr_alu[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 if (RV32B != RV32BNone) begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n // Shift Left Ones by Immediate\n 5'b0_0100: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_SLO;\n end\n 5'b0_1001: alu_operator_o = ALU_BCLR; // Clear bit specified by immediate\n 5'b0_0101: alu_operator_o = ALU_BSET; // Set bit specified by immediate\n 5'b0_1101: alu_operator_o = ALU_BINV; // Invert bit specified by immediate.\n // Shuffle with Immediate Control Value\n 5'b0_0001: if (instr_alu[26] == 0) alu_operator_o = ALU_SHFL;\n 5'b0_1100: begin\n unique case (instr_alu[26:20])\n 7'b000_0000: alu_operator_o = ALU_CLZ; // clz\n 7'b000_0001: alu_operator_o = ALU_CTZ; // ctz\n 7'b000_0010: alu_operator_o = ALU_CPOP; // cpop\n 7'b000_0100: alu_operator_o = ALU_SEXTB; // sext.b\n 7'b000_0101: alu_operator_o = ALU_SEXTH; // sext.h\n 7'b001_0000: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_B; // crc32.b\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_0001: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_H; // crc32.h\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_0010: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_W; // crc32.w\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1000: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_B; // crc32c.b\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1001: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_H; // crc32c.h\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1010: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_W; // crc32c.w\n alu_multicycle_o = 1'b1;\n end\n end\n default: ;\n endcase\n end\n\n default: ;\n endcase\n end else begin\n alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n end\n end\n\n 3'b101: begin\n if (RV32B != RV32BNone) begin\n if (instr_alu[26] == 1'b1) begin\n alu_operator_o = ALU_FSR;\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end else begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n 5'b0_1000: alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n // Shift Right Ones by Immediate\n 5'b0_0100: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_SRO;\n end\n 5'b0_1001: alu_operator_o = ALU_BEXT; // Extract bit specified by immediate.\n 5'b0_1100: begin\n alu_operator_o = ALU_ROR; // Rotate Right by Immediate\n alu_multicycle_o = 1'b1;\n end\n 5'b0_1101: alu_operator_o = ALU_GREV; // General Reverse with Imm Control Val\n 5'b0_0101: alu_operator_o = ALU_GORC; // General Or-combine with Imm Control Val\n // Unshuffle with Immediate Control Value\n 5'b0_0001: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) begin\n if (instr_alu[26] == 1'b0) alu_operator_o = ALU_UNSHFL;\n end\n end\n default: ;\n endcase\n end\n\n end else begin\n if (instr_alu[31:27] == 5'b0_0000) begin\n alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n end else if (instr_alu[31:27] == 5'b0_1000) begin\n alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n end\n end\n end\n\n default: ;\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\n if (instr_alu[26]) begin\n if (RV32B != RV32BNone) begin\n unique case ({instr_alu[26:25], instr_alu[14:12]})\n {2'b11, 3'b001}: begin\n alu_operator_o = ALU_CMIX; // cmix\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b11, 3'b101}: begin\n alu_operator_o = ALU_CMOV; // cmov\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b10, 3'b001}: begin\n alu_operator_o = ALU_FSL; // fsl\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b10, 3'b101}: begin\n alu_operator_o = ALU_FSR; // fsr\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n default: ;\n endcase\n end\n end else begin\n unique case ({instr_alu[31:25], instr_alu[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000}: alu_operator_o = ALU_ADD; // Add\n {7'b010_0000, 3'b000}: alu_operator_o = ALU_SUB; // Sub\n {7'b000_0000, 3'b010}: alu_operator_o = ALU_SLT; // Set Lower Than\n {7'b000_0000, 3'b011}: alu_operator_o = ALU_SLTU; // Set Lower Than Unsigned\n {7'b000_0000, 3'b100}: alu_operator_o = ALU_XOR; // Xor\n {7'b000_0000, 3'b110}: alu_operator_o = ALU_OR; // Or\n {7'b000_0000, 3'b111}: alu_operator_o = ALU_AND; // And\n {7'b000_0000, 3'b001}: alu_operator_o = ALU_SLL; // Shift Left Logical\n {7'b000_0000, 3'b101}: alu_operator_o = ALU_SRL; // Shift Right Logical\n {7'b010_0000, 3'b101}: alu_operator_o = ALU_SRA; // Shift Right Arithmetic\n\n // RV32B ALU Operations\n {7'b011_0000, 3'b001}: begin\n if (RV32B != RV32BNone) begin\n alu_operator_o = ALU_ROL;\n alu_multicycle_o = 1'b1;\n end\n end\n {7'b011_0000, 3'b101}: begin\n if (RV32B != RV32BNone) begin\n alu_operator_o = ALU_ROR;\n alu_multicycle_o = 1'b1;\n end\n end\n\n {7'b000_0101, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_MIN;\n {7'b000_0101, 3'b110}: if (RV32B != RV32BNone) alu_operator_o = ALU_MAX;\n {7'b000_0101, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_MINU;\n {7'b000_0101, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_MAXU;\n\n {7'b000_0100, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACK;\n {7'b010_0100, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACKU;\n {7'b000_0100, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACKH;\n\n {7'b010_0000, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_XNOR;\n {7'b010_0000, 3'b110}: if (RV32B != RV32BNone) alu_operator_o = ALU_ORN;\n {7'b010_0000, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_ANDN;\n\n // RV32B zba\n {7'b001_0000, 3'b010}: if (RV32B != RV32BNone) alu_operator_o = ALU_SH1ADD;\n {7'b001_0000, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_SH2ADD;\n {7'b001_0000, 3'b110}: if (RV32B != RV32BNone) alu_operator_o = ALU_SH3ADD;\n\n // RV32B zbs\n {7'b010_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_BCLR;\n {7'b001_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_BSET;\n {7'b011_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_BINV;\n {7'b010_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_BEXT;\n\n // RV32B zbf\n {7'b010_0100, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_BFP;\n\n // RV32B zbp\n {7'b011_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_GREV;\n {7'b001_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_GORC;\n {7'b000_0100, 3'b001}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_SHFL;\n end\n {7'b000_0100, 3'b101}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_UNSHFL;\n end\n {7'b001_0100, 3'b010}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_XPERM_N;\n end\n {7'b001_0100, 3'b100}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_XPERM_B;\n end\n {7'b001_0100, 3'b110}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_XPERM_H;\n end\n {7'b001_0000, 3'b001}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_SLO;\n end\n {7'b001_0000, 3'b101}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_SRO;\n end\n\n // RV32B zbc\n {7'b000_0101, 3'b001}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_CLMUL;\n end\n {7'b000_0101, 3'b010}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_CLMULR;\n end\n {7'b000_0101, 3'b011}: begin\n if (RV32B == RV32BOTEarlGrey || RV32B == RV32BFull) alu_operator_o = ALU_CLMULH;\n end\n\n // RV32B zbe\n {7'b010_0100, 3'b110}: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_BDECOMPRESS;\n alu_multicycle_o = 1'b1;\n end\n end\n {7'b000_0100, 3'b110}: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_BCOMPRESS;\n alu_multicycle_o = 1'b1;\n end\n end\n\n // RV32M instructions, all use the same ALU operation\n {7'b000_0001, 3'b000}: begin // mul\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b100}: begin // div\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b101}: begin // divu\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b110}: begin // rem\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b111}: begin // remu\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n\n default: ;\n endcase\n end\n end\n\n /////////////\n // Special //\n /////////////\n\n OPCODE_MISC_MEM: begin\n unique case (instr_alu[14:12])\n 3'b000: begin\n // FENCE is treated as a NOP since all memory operations are already strictly ordered.\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 end\n 3'b001: begin\n // FENCE.I will flush the IF stage, prefetch buffer and ICache if present.\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_INCR_PC;\n end else begin\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 end\n end\n default: ;\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr_alu[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 end else begin\n // instruction to read/modify CSR\n imm_a_mux_sel_o = IMM_A_Z;\n\n // No need for operand/immediate B mux selection. The CSR address is fed out as csr_addr_o\n // as the CSR address always comes from the same field in the instruction.\n\n if (instr_alu[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 end\n\n end\n default: ;\n endcase\n end\n\n // do not enable multdiv in case of illegal instruction exceptions\n assign mult_en_o = illegal_insn ? 1'b0 : mult_sel_o;\n assign div_en_o = illegal_insn ? 1'b0 : div_sel_o;\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 rf_we_o = rf_we & ~illegal_reg_rv32e;\n\n // Not all bits are used\n assign unused_instr_alu = {instr_alu[19:15],instr_alu[11:7]};\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT(IbexRegImmAluOpKnown, (opcode == OPCODE_OP_IMM) |->\n !$isunknown(instr[14:12]))\nendmodule // controller\n", "selected_doc_paths": ["doc/03_reference/instruction_decode_execute.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/cs_registers.rst", "doc/02_user/configuration.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 2229, "lang": "sv", "rtl_files": ["rtl/ibex_counter.sv"], "spec": "# Design Specification: Ibex Counter (`ibex_counter`)\n\n## Overview\n\nThe `ibex_counter` module implements a synchronous, resettable binary counter with configurable width (up to 64 bits). It is used as a building block for performance counters in the Ibex processor, such as `mcycle`, `minstret`, and `mhpmcounter` registers. The counter supports:\n\n- Increment by 1 on each clock cycle when enabled.\n- Independent write to the low 32 bits or high 32 bits of the counter (for 64‑bit access via CSR write).\n- Full synchronous reset to zero.\n- A configurable output that provides either the incremented value of the counter’s lower bits (for Xilinx DSP inference) or a constant zero.\n\nThe module is fully synchronous and uses a single clock domain. Its width and the behavior of the “updated value” output are controlled by parameters at synthesis time.\n\n## Interface\n\nThe module interacts with the outside world through the following functional interfaces:\n\n- **Clock** – The rising edge of the clock triggers all state updates.\n- **Reset** – An active‑low asynchronous reset (synchronous on some targets) that forces the counter to zero.\n- **Increment Enable** – A single‑bit command. When asserted (high), the counter shall increase its value by 1 on the next clock edge.\n- **Write Enables** – Two separate signals, one for the low 32 bits and one for the high 32 bits of a 64‑bit representation. If either write enable is asserted, the counter shall load a new value instead of incrementing.\n- **Write Data** – A 32‑bit value. When writing, the module uses this data to update either the low 32 bits or the high 32 bits of the counter, depending on which write enable is active. If both write enables are active, the low half of the write data updates the high 32 bits of the counter (see *Write Behavior*).\n- **Current Value Output** – A 64‑bit bus that always reflects the present counter value.\n- **Updated Value Output** – A 64‑bit bus that provides either the incremented lower part of the counter (function of the current counter and the increment enable) or all zeros, as determined by a synthesis‑time parameter.\n\n## Functional Behavior\n\n### Reset\n\nWhen reset is asserted (low), the counter shall hold a value of all zeros. After reset is de‑asserted, the counter remains at zero until a write or increment operation is performed.\n\n### Normal Operation (no write, no increment)\n\nIf neither increment enable nor any write enable is asserted, the counter shall retain its current value.\n\n### Increment\n\nWhen the increment enable is asserted and no write is requested simultaneously, the counter shall, on the next rising clock edge, advance by one. The increment is performed on the least‑significant bits of the counter (up to the configured width). Overflow beyond the counter width is discarded; the counter wraps around.\n\n### Write\n\nA write operation takes precedence over an increment. When at least one of the write enables is asserted:\n\n- **Write to low 32 bits** (`counter_we_i` active): The 32‑bit write data shall be loaded into the low 32 bits of the counter. The high 32 bits shall remain unchanged.\n- **Write to high 32 bits** (`counterh_we_i` active): The 32‑bit write data shall be loaded into the high 32 bits of the counter. The low 32 bits shall remain unchanged.\n- **Both write enables active simultaneously**: The write data shall be loaded into the high 32 bits of the counter, while the low 32 bits retain their current value. (This is a simplification that allows efficient CSR write of the “high” half of the counter.)\n\nThe counter loads only the bits that fall within its configured width. Bits outside the configured width shall be forced to zero in the current value output.\n\n### Counter Width\n\nThe counter supports any width from 1 to 64 bits, configurable via a synthesis parameter. If the counter width is less than 64 bits, the unused most‑significant bits of the current value output shall be zero. Similarly, the updated value output’s unused high bits shall be zero.\n\n### Updated Value Output\n\nThe second output bus provides an “incremented” version of the counter’s lower bits. Its behavior depends on a synthesis parameter:\n\n- **When `ProvideValUpd` is set to 1**: The lower bits of this output shall be equal to the lower bits of the counter plus one (i.e., the value the counter would take if an increment were performed). This output is updated combinatorially (immediately when the counter value changes). Its width matches the counter width; the remaining bits (if any) are zero.\n- **When `ProvideValUpd` is set to 0**: The entire updated value output shall be all zeros.\n\nThis output is provided to enable Xilinx DSP inference – the DSP48E1 block can absorb the increment logic and its internal pipeline register when this output is used. If not required, it is hard‑wired to zero to avoid unnecessary logic.\n\n### Target‑Specific Reset Behavior\n\nFor designs targeting Xilinx FPGAs (identified by the `FPGA_XILINX` preprocessor definition), the counter’s flip‑flop reset is synchronous. For all other targets, the reset is asynchronous. The functional behavior at the module boundary is identical: after reset de‑assertion the counter is zero.\n\n## Synthesis Parameters\n\n| Parameter | Type | Default | Description |\n|----------------|--------|---------|-------------|\n| `CounterWidth` | int | 32 | Width of the counter in bits (1 to 64). |\n| `ProvideValUpd`| bit | 0 | When 1, the updated value output provides the incremented lower part of the counter. When 0, that output is constant zero. |\n\nThese parameters shall be static at synthesis time and shall not change during operation.\n\n## Usage Context\n\nThis module is instantiated multiple times in the Ibex performance counter subsystem. It is generic enough to serve as the storage element for any 32‑ or 64‑bit counter that supports both an increment-by‑1 operation and CSR writes to the low or high half.\n\n## Summary of Requirements\n\n1. **Reset**: After reset, the counter must be zero.\n2. **No operation**: Counter must hold its value.\n3. **Increment**: When increment enable is high (and no write occurs), the counter must increase by 1 on the next clock edge.\n4. **Write**: When a write enable is active, the counter must update the appropriate half with the 32‑bit write data. If both write enables are high, the write data is applied to the high half only.\n5. **Current value output**: Must always show the full counter value, with upper unused bits zero.\n6. **Updated value output**: Must be either the incremented lower bits (if parameter set) or all zeros.\n7. **Width**: Must support any integer width from 1 to 64, with zero extension to 64 bits.\n8. **Reset type**: Must be functionally correct regardless of target (synchronous or asynchronous reset), with the same post‑reset state.", "commit_id": "54985d21b055967c39d0a77b45ae0d573b55b0f7", "timestamp": "2024-12-04T00:34:00+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "0945aa84c635a1756311c076a6a7a5b5c239532f", "pr_title": "Revert \"[rtl] Fix counter reset value on FPGA\"", "pr_body": "Reverts lowRISC/ibex#2226 because the scope for counter_q is incorrect resulting in synthesis failure for Xilinx targets.", "issue_title": "[rtl] Fix counter reset value on FPGA", "issue_body": "If the counter width is >= 49, we do not use a DSP on the FPGA. Then, we should use an asynchronous reset to initialize the counter.\r\n\r\nThis bug was detected when enabling the lockstep for the CW340. A lockstep mismatch happend as the mcycle counters of the main and shadow core did not match due to this bug.", "commit_message": "Revert \"[rtl] Fix counter reset value on FPGA\"\n\nThis reverts commit 54985d21b055967c39d0a77b45ae0d573b55b0f7.", "fix_patch": "diff --git a/rtl/ibex_counter.sv b/rtl/ibex_counter.sv\nindex d3ca14ca02..c78e510ee4 100644\n--- a/rtl/ibex_counter.sv\n+++ b/rtl/ibex_counter.sv\n@@ -51,17 +51,12 @@ module ibex_counter #(\n end\n \n `ifdef FPGA_XILINX\n- // On Xilinx FPGAs, 48-bit DSPs are available that can be used for the\n- // counter.\n- if (CounterWidth < 49) begin : g_dsp_counter\n- // Set DSP pragma for supported xilinx FPGAs\n- (* use_dsp = \"yes\" *) logic [CounterWidth-1:0] counter_q;\n- // DSP output register requires synchronous reset.\n- `define COUNTER_FLOP_RST posedge clk_i\n- end else begin : g_no_dsp_counter\n- (* use_dsp = \"no\" *) logic [CounterWidth-1:0] counter_q;\n- `define COUNTER_FLOP_RST posedge clk_i or negedge rst_ni\n- end\n+ // Set DSP pragma for supported xilinx FPGAs\n+ localparam int DspPragma = CounterWidth < 49 ? \"yes\" : \"no\";\n+ (* use_dsp = DspPragma *) 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@@ -70,7 +65,6 @@ module ibex_counter #(\n \n // Counter flop\n always_ff @(`COUNTER_FLOP_RST) begin\n- `undef COUNTER_FLOP_RST\n if (!rst_ni) begin\n counter_q <= '0;\n end else begin\n@@ -104,3 +98,6 @@ module ibex_counter #(\n assign counter_val_o = counter;\n \n endmodule\n+\n+// Keep helper defines file-local.\n+`undef COUNTER_FLOP_RST\n", "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_counter #(\n parameter int CounterWidth = 32,\n // When set `counter_val_upd_o` provides an incremented version of the counter value, otherwise\n // the output is hard-wired to 0. This is required to allow Xilinx DSP inference to work\n // correctly. When `ProvideValUpd` is set no DSPs are inferred.\n parameter bit ProvideValUpd = 0\n) (\n input logic clk_i,\n input logic rst_ni,\n\n input logic counter_inc_i,\n input logic counterh_we_i,\n input logic counter_we_i,\n input logic [31:0] counter_val_i,\n output logic [63:0] counter_val_o,\n output logic [63:0] counter_val_upd_o\n);\n\n logic [63:0] counter;\n logic [CounterWidth-1:0] counter_upd;\n logic [63:0] counter_load;\n logic we;\n logic [CounterWidth-1:0] counter_d;\n\n // Increment\n assign counter_upd = counter[CounterWidth-1:0] + {{CounterWidth - 1{1'b0}}, 1'b1};\n\n // Update\n always_comb begin\n // Write\n we = counter_we_i | counterh_we_i;\n counter_load[63:32] = counter[63:32];\n counter_load[31:0] = counter_val_i;\n if (counterh_we_i) begin\n counter_load[63:32] = counter_val_i;\n counter_load[31:0] = counter[31:0];\n end\n\n // Next value logic\n if (we) begin\n counter_d = counter_load[CounterWidth-1:0];\n end else if (counter_inc_i) begin\n counter_d = counter_upd[CounterWidth-1:0];\n end else begin\n counter_d = counter[CounterWidth-1:0];\n end\n end\n\n`ifdef FPGA_XILINX\n // Set DSP pragma for supported xilinx FPGAs\n localparam int DspPragma = CounterWidth < 49 ? \"yes\" : \"no\";\n (* use_dsp = DspPragma *) 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_ff @(`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 logic [63:CounterWidth] unused_counter_load;\n\n assign counter[CounterWidth-1:0] = counter_q;\n assign counter[63:CounterWidth] = '0;\n\n if (ProvideValUpd) begin : g_counter_val_upd_o\n assign counter_val_upd_o[CounterWidth-1:0] = counter_upd;\n end else begin : g_no_counter_val_upd_o\n assign counter_val_upd_o[CounterWidth-1:0] = '0;\n end\n assign counter_val_upd_o[63:CounterWidth] = '0;\n assign unused_counter_load = counter_load[63:CounterWidth];\n end else begin : g_counter_full\n assign counter = counter_q;\n\n if (ProvideValUpd) begin : g_counter_val_upd_o\n assign counter_val_upd_o = counter_upd;\n end else begin : g_no_counter_val_upd_o\n assign counter_val_upd_o = '0;\n end\n end\n\n assign counter_val_o = counter;\n\nendmodule\n\n// Keep helper defines file-local.\n`undef COUNTER_FLOP_RST\n", "selected_doc_paths": ["doc/03_reference/performance_counters.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 2224, "lang": "sv", "rtl_files": ["rtl/ibex_register_file_fpga.sv"], "spec": "# Behavioral Specification: FPGA Register File (ibex_register_file_fpga)\n\n## Overview\n\nThe FPGA register file implements the RISC-V general‑purpose register file (x0–x31 or x0–x15) with two read ports and one write port. It is intended for FPGA targets where synchronous‑write, asynchronous‑read RAM primitives are available. The module provides a purely behavioral contract – the exact internal storage technology is invisible to the rest of the processor.\n\n## Register Configuration\n\n- The register file holds either **31** (if the RV32E extension is **disabled**) or **15** (if RV32E is **enabled**) writable registers.\n- Register **x0** is statically bound to a constant value. It does not contain any state and cannot be written; any attempt to write x0 must be ignored.\n- The constant value returned when reading x0 is configurable at design time, but is **zero by default**.\n\n## Port Behavior\n\n### Write Port (W1)\n\n- A single write port accepts an address, data, and a write‑enable signal.\n- A write occurs only on the rising edge of the clock when the write enable is asserted **and** the write address does **not** refer to register x0.\n- Writes to x0 are silently ignored – no state changes, regardless of the write enable value.\n- The written data is available for reading in the same clock cycle **only** if the read address differs from the write address (no write‑to‑read forwarding is performed). If a read and a write target the same register in the same cycle, the read returns the **previous** value, not the value being written.\n\n### Read Ports (R1 and R2)\n\n- Two independent read ports, each with an address input, provide combinatorial (asynchronous) read data outputs.\n- When a read address refers to a writable register (x1–x31 or x1–x15), the output is the current content of that register.\n- When a read address refers to **x0**, the output is the configured constant zero value.\n- Both read outputs are always valid once the address is stable; no enable signal is required.\n\n## Error Detection\n\nThe module contains built‑in integrity checks that generate a single error output. An error is asserted under the following conditions:\n\n1. **Spurious write‑enable strobe** – if the write‑enable signal toggles (e.g., due to a glitch) while the write address is not x0, the error output is asserted.\n2. **Non‑one‑hot read addresses** – if either read address, when decoded into a one‑hot vector, does not contain exactly one asserted bit, the error output is asserted. This includes the case where multiple bits are high or no bits are high.\n3. **Address parity / illegal encoding** – the detection logic verifies that the binary address encodes a valid one‑hot representation; any mismatch (including metastable or glitched addresses) will raise the error.\n\nThe error output is a combinational OR of all detected conditions. It does not affect data outputs – the register file continues to operate, but the system is notified of a potential integrity violation.\n\n## Initialization\n\n- At simulation start (time zero), **all** registers (including all addresses, including those representing x0) are initialized to the same constant zero value. Note that x0’s read output is permanently forced to the constant value, so its internal initial state has no effect on reads.\n- No reset signal is required for normal operation. The reset input is present only for compatibility with other register file flavors and is ignored.\n\n## Constraints and Excluded Features\n\n- The module does **not** use any test enable or dummy instruction signals. These inputs may be tied off or left unconnected.\n- There is no internal write‑to‑read forwarding logic; software (or a hazard unit) must handle read‑after‑write hazards.\n- The register file does **not** perform any clock gating. Writes happen on every rising clock edge when the write conditions are met.\n\n## Parameter Summary\n\n| Parameter | Effect |\n|-----------|--------|\n| RV32E | Selects 31 (0) or 15 (1) writable registers. |\n| DataWidth | Width of each register and data paths (default 32 bits). |\n| DummyInstructions | Not used; must be tied to a constant value. |\n| WrenCheck | Enables (1) or disables (0) the spurious write‑enable check. |\n| RdataMuxCheck | Enables (1) or disables (0) the one‑hot read address check. When enabled, read data is also processed through one‑hot muxes; otherwise a direct array read is used. |\n| WordZeroVal | The constant value returned when reading address 0 (default all zeros). |\n\n---\n\nThis specification defines the **observable behavior** of the FPGA register file. The internal architecture (RAM primitives, synchronous write, asynchronous read) is an implementation detail and shall not affect the functional contract described above.", "commit_id": "f0f6bfd79a18d676eb565b04b8235133f0f9eedf", "timestamp": "2024-11-18T14:12:06+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "84232a5bfa8b020cd05718b2ae21d8584c942df8", "pr_title": "[rtl] Fix zero value in FPGA RF", "pr_body": "We should use `WordZeroVal` instead of `0` for reads from register `x0` in the FPGA register file.\r\n\r\nThis bug was discovered when enabling the `RegFileECC` parameter. When this is enabled, the core performs ECC checks, expecting that `WordZeroVal` is returned for `x0`. Else, we get a major alert.\r\n\r\nFixes lowRISC/opentitan#25146", "issue_title": "", "issue_body": "", "commit_message": "[rtl] Fix zero value in FPGA RF\n\nWe should use `WordZeroVal` instead of `0` for reads from register `x0` in the\nFPGA register file.\n\nThis bug was discovered when enabling the `RegFileECC` parameter. When this is\nenabled, the core performs ECC checks, expecting that `WordZeroVal` is returned\nfor `x0`. Else, we get a major alert.\n\nFixes lowRISC/opentitan#25146\n\nSigned-off-by: Pascal Nasahl ", "fix_patch": "diff --git a/rtl/ibex_register_file_fpga.sv b/rtl/ibex_register_file_fpga.sv\nindex 7a0ae34b15..73e0afab2f 100644\n--- a/rtl/ibex_register_file_fpga.sv\n+++ b/rtl/ibex_register_file_fpga.sv\n@@ -147,14 +147,14 @@ module ibex_register_file_fpga #(\n .out_o (mem_o_b)\n );\n \n- assign rdata_a_o = (raddr_a_i == '0) ? '0 : mem_o_a;\n- assign rdata_b_o = (raddr_b_i == '0) ? '0 : mem_o_b;\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) ? '0 : mem[raddr_a_i];\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) ? '0 : mem[raddr_b_i];\n+ assign rdata_b_o = (raddr_b_i == '0) ? WordZeroVal : mem[raddr_b_i];\n end\n \n // we select\n", "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 // 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 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", "selected_doc_paths": ["doc/03_reference/register_file.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1879, "lang": "sv", "rtl_files": ["dv/uvm/core_ibex/env/core_ibex_dut_probe_if.sv"], "spec": "# Behavioral Design Specification: `core_ibex_dut_probe_if` (Probe Interface)\n\n## 1. Overview\n\nThe `core_ibex_dut_probe_if` is a verification‑focused interface that connects to a simulation model of the lowRISC Ibex core. Its primary purpose is to expose a curated set of internal signals of the core to a UVM testbench, and to allow the testbench to drive a small number of control signals synchronously.\n\nThe interface provides:\n\n- A **clocking block** that defines synchronous, clock‑edge‑based communication with the DUT.\n- **Input** signals (from the DUT) that reflect the current state of key internal registers, state machines, and status flags.\n- **Output** signals (to the DUT) that the testbench can drive to influence core behaviour in a controlled way.\n- **Probe functions** (generated by macros) that give UVM components a convenient handle to read specific signals without direct hierarchical path references.\n\n## 2. Functional Behaviour\n\n### 2.1 Clocking Block\n\nThe interface defines a clocking block **dut_cb** that clocks on the **positive edge** of the supplied `clk` signal.\n\n- All **outputs** (signals driven by the testbench toward the DUT) are driven in the clocking block’s output direction. They shall be sampled by the DUT on the positive clock edge.\n- All **inputs** (signals driven by the DUT toward the interface) are sampled on the positive clock edge when used in clocking block expressions.\n\nThe testbench must use the clocking block to synchronise all interactions with the DUT.\n\n### 2.2 Output Signals (Driven from Testbench)\n\nThese signals are driven by the testbench and are declared with **output** direction in the clocking block. They must be initialised to known values after reset.\n\n| Signal | Behaviour |\n|---------------------|-----------|\n| `fetch_enable` | Controls whether the core is allowed to fetch instructions. When de‑asserted, the core shall enter a suspended state (halted fetch). This signal is of type `ibex_pkg::ibex_mubi_t` (multi‑bit uni‑value), and must be driven to one of the valid encoding values as defined in the core’s package. |\n| `debug_req` | Requests the core to enter Debug Mode. The core shall respond by transitioning to debug state as described in the debug specification. This signal must be held high until the core acknowledges the request (visible via the `debug_mode` input). The initial value of `debug_req` after simulation start shall be logic `0`. |\n\n### 2.3 Input Signals (Probed from DUT)\n\nThese signals convey the state of internal logic of the Ibex core. They are declared with **input** direction in the clocking block and are sampled on each positive clock edge.\n\n| Signal | Behaviour |\n|--------|-----------|\n| `reset` | Asynchronous reset status of the core (active‑high). When asserted, the core is held in reset state. |\n| `illegal_instr` | Asserted for one clock cycle when the core detects an illegal instruction in the ID/EX stage. |\n| `ecall` | Asserted for one clock cycle when an `ECALL` instruction is executed. |\n| `wfi` | Asserted when the core has executed a `WFI` instruction and is in sleep‑wait state. |\n| `ebreak` | Asserted for one clock cycle when an `EBREAK` instruction is executed. |\n| `dret` | Asserted for one clock cycle when a `DRET` instruction (return from Debug Mode) is executed. |\n| `mret` | Asserted for one clock cycle when an `MRET` instruction (return from Machine Mode) is executed. |\n| `core_sleep` | Indicates that the core is in a sleep state (after `WFI`), with its clock potentially gated. |\n| `alert_minor` | A minor security alert output. Asserted for at least one cycle when a non‑critical security event (e.g., ICache ECC error) is detected. |\n| `alert_major_internal` | A major internal security alert. Asserted when an unrecoverable security condition (e.g., register file ECC error, PC integrity failure) is detected internally. |\n| `alert_major_bus` | A major bus‑integrity alert. Asserted when an unrecoverable check‑bit mismatch is detected on the instruction or data bus. |\n| `ic_tag_req` | Indicates a tag RAM read request for the instruction cache (one bit per way). |\n| `ic_tag_write` | Indicates a tag RAM write operation (one bit per way). |\n| `ic_tag_addr` | Address bus for the tag RAM of the instruction cache. |\n| `ic_data_req` | Indicates a data RAM read request for the instruction cache (one bit per way). |\n| `ic_data_write` | Indicates a data RAM write for the instruction cache (one bit per way). |\n| `ic_data_addr` | Address bus for the data RAM of the instruction cache. |\n| `priv_mode` | Current privilege level of the core (`Machine` or `User`). |\n| `ctrl_fsm_cs` | Current state of the core’s main control finite‑state machine. |\n| `debug_mode` | Asserted when the core is in Debug Mode. |\n| `double_fault_seen` | Asserted for one cycle when a double fault is detected (a synchronous exception occurs while handling a previous synchronous exception). |\n| `rf_ren_a` | Register file read enable for port A (one per instruction). |\n| `rf_ren_b` | Register file read enable for port B. |\n| `rf_rd_a_wb_match` | Asserted when the address read on port A matches the write‑back address of a previous write, indicating a possible read‑after‑write hazard. |\n| `rf_rd_b_wb_match` | Same as `rf_rd_a_wb_match`, but for port B. |\n\n### 2.4 Probe Functions\n\nThe interface implements a set of macros (`DV_CREATE_SIGNAL_PROBE_FUNCTION`) that create a function named `signal_probe_` for each of the following signals:\n\n- `rf_ren_a`\n- `rf_ren_b`\n- `rf_rd_a_wb_match`\n- `rf_rd_b_wb_match`\n- `alert_minor`\n- `ic_tag_req`\n- `ic_tag_write`\n- `ic_tag_addr`\n- `ic_data_req`\n- `ic_data_write`\n- `ic_data_addr`\n\nEach probe function returns the current value of the corresponding signal. The functions are intended to be called from UVM components (e.g., scoreboards, coverage collectors) to read the signal value without needing a hierarchical reference. The behaviour of these functions shall be identical to reading the signal directly; they must return the value sampled on the last positive clock edge.\n\n## 3. Initialisation and Reset Behaviour\n\n- **Output signal initialisation**: At time zero, before the first clock edge, `debug_req` shall be set to `1'b0`. Other outputs (specifically `fetch_enable`) are not initialised by this interface; their initial state must be set by the testbench via the clocking block at the appropriate time.\n- **Reset handling**: When the `reset` input is asserted, all core state machines are reset. The interface itself does not reset its sampling; it continues to reflect the values of the DUT signals. The testbench is responsible for aligning its driving of outputs with the DUT reset.\n\n## 4. Timing Requirements\n\n- All signal transitions on outputs shall be aligned to the positive edge of `clk`.\n- Input signals are sampled on the positive edge of `clk` inside the clocking block. The testbench may assume that the values seen in the clocking block are stable at that edge.\n- The output `debug_req` must be driven synchronously to the core’s debug request input.\n\n## 5. Usage Constraints\n\n- This interface is intended **only for simulation** and shall not be synthesised. It is part of the UVM verification environment for Ibex.\n- The probe functions shall be used only after the DUT is out of reset and the clock is running.\n- The clocking block must be used in a UVM monitor or driver to ensure proper synchronous timing.\n\n## 6. Dependencies\n\nThe interface relies on the package `ibex_pkg` for type definitions (`ibex_mubi_t`, `priv_lvl_e`, `ctrl_fsm_e`, `IC_NUM_WAYS`, `IC_INDEX_W`). The behaviour of the probed signals is fully described in the Ibex core documentation (exception/interrupt handling, debug, ICache, register file, pipeline, and security features). This specification does not repeat those details but assumes that the observed signals conform to the respective functional specifications.", "commit_id": "66b3ed1ac1df79cc6d285e586135fd1e68ab198f", "timestamp": "2022-11-04T15:28:09+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "7b0921e14cca9bcba02e9492b22f9a185dbfdc7a", "pr_title": "[dv] Add test glitching data/tag of icache", "pr_body": "This PR addresses the integrity part of https://github.com/lowRISC/ibex/issues/1759 by verifying that a glitch on the data or tag response from the instruction cache raises a minor alert by the core (if the data/tag returned from the cache is used by the core).\r\n\r\nThe **last** commit implements the actual test. The commits before that are prerequisites as follows:\r\n1. ~~[dv] Add assert control for `NoAlertsTriggered`: duplicate from #1873, will be dropped once that PR is merged.~~\r\n2. ~~[wip] Extend vendored-in `clk_rst_if`: adds two functions to that IF -- if we agree that this is appropriate and necessary, these functions should be upstreamed.~~\r\n3. ~~[wip] Locally import `DV_CREATE_SIGNAL_PROBE_FUNCTION`: adds a macro recently added in OpenTitan (I wanted to properly vendor it in, but the update failed). If we agree that this macro should be used here, we need to fix the vendor-update problems.~~\r\n4. [dv] Add icache signals to `core_ibex_dut_probe_if`: should be fairly uncontroversial.\r\n5. [dv] Create signal probe functions in `core_ibex_dut_probe_if`: these functions have benefits over `uvm_hdl_read()`; see the commit message.\r\n\r\nPass rate is currently 100% (I tried 20 seeds) -- that is, alerts are produced and checked as expected. Every test corrupts a used data/tag of the icache, but not in every test the data/tag is valid (even when not corrupted). The test takes this into account when checking for an alert.\r\n\r\n~~Note: This test currently only works correctly if waves are being logged. Otherwise, the simulator complains that it does not have access to the icache data/tag to glitch it.~~", "issue_title": "[dv] Add test glitching PC of Ibex", "issue_body": "This PR addresses #1755 by verifying that a glitch on the PC of Ibex raises an internal major alert in the core.", "commit_message": "[dv] Add test glitching icache data or tag\n\nThis commit addresses the integrity part of #1759 by verifying that a\nglitch on the data or tag response from the instruction cache raises a\nminor alert by the core (if the data/tag returned from the cache is used\nby the core).\n\nSigned-off-by: Andreas Kurth ", "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 7dec52c584..fdf40cce98 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@@ -7,27 +7,33 @@ interface core_ibex_dut_probe_if(input logic clk);\n \n import uvm_pkg::*;\n \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::ibex_mubi_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- logic debug_mode;\n- logic double_fault_seen;\n- logic rf_ren_a;\n- logic rf_ren_b;\n- logic rf_rd_a_wb_match;\n- logic rf_rd_b_wb_match;\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::ibex_mubi_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+ logic [ibex_pkg::IC_NUM_WAYS-1:0] ic_tag_req;\n+ logic ic_tag_write;\n+ logic [ibex_pkg::IC_INDEX_W-1:0] ic_tag_addr;\n+ logic [ibex_pkg::IC_NUM_WAYS-1:0] ic_data_req;\n+ logic ic_data_write;\n+ logic [ibex_pkg::IC_INDEX_W-1:0] ic_data_addr;\n+ ibex_pkg::priv_lvl_e priv_mode;\n+ ibex_pkg::ctrl_fsm_e ctrl_fsm_cs;\n+ logic debug_mode;\n+ logic double_fault_seen;\n+ logic rf_ren_a;\n+ logic rf_ren_b;\n+ logic rf_rd_a_wb_match;\n+ logic rf_rd_b_wb_match;\n \n clocking dut_cb @(posedge clk);\n output fetch_enable;\n@@ -43,6 +49,12 @@ interface core_ibex_dut_probe_if(input logic clk);\n input alert_minor;\n input alert_major_internal;\n input alert_major_bus;\n+ input ic_tag_req;\n+ input ic_tag_write;\n+ input ic_tag_addr;\n+ input ic_data_req;\n+ input ic_data_write;\n+ input ic_data_addr;\n input priv_mode;\n input ctrl_fsm_cs;\n input debug_mode;\n@@ -61,5 +73,12 @@ interface core_ibex_dut_probe_if(input logic clk);\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_ren_b, rf_ren_b)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_rd_a_wb_match, rf_rd_a_wb_match)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_rd_b_wb_match, rf_rd_b_wb_match)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_alert_minor, alert_minor)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_tag_req, ic_tag_req)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_tag_write, ic_tag_write)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_tag_addr, ic_tag_addr)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_data_req, ic_data_req)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_data_write, ic_data_write)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_data_addr, ic_data_addr)\n \n endinterface\n", "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\n import uvm_pkg::*;\n\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::ibex_mubi_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 logic [ibex_pkg::IC_NUM_WAYS-1:0] ic_tag_req;\n logic ic_tag_write;\n logic [ibex_pkg::IC_INDEX_W-1:0] ic_tag_addr;\n logic [ibex_pkg::IC_NUM_WAYS-1:0] ic_data_req;\n logic ic_data_write;\n logic [ibex_pkg::IC_INDEX_W-1:0] ic_data_addr;\n ibex_pkg::priv_lvl_e priv_mode;\n ibex_pkg::ctrl_fsm_e ctrl_fsm_cs;\n logic debug_mode;\n logic double_fault_seen;\n logic rf_ren_a;\n logic rf_ren_b;\n logic rf_rd_a_wb_match;\n logic rf_rd_b_wb_match;\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 ic_tag_req;\n input ic_tag_write;\n input ic_tag_addr;\n input ic_data_req;\n input ic_data_write;\n input ic_data_addr;\n input priv_mode;\n input ctrl_fsm_cs;\n input debug_mode;\n input double_fault_seen;\n input rf_ren_a;\n input rf_ren_b;\n input rf_rd_a_wb_match;\n input rf_rd_b_wb_match;\n endclocking\n\n initial begin\n debug_req = 1'b0;\n end\n\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_ren_a, rf_ren_a)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_ren_b, rf_ren_b)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_rd_a_wb_match, rf_rd_a_wb_match)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_rd_b_wb_match, rf_rd_b_wb_match)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_alert_minor, alert_minor)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_tag_req, ic_tag_req)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_tag_write, ic_tag_write)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_tag_addr, ic_tag_addr)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_data_req, ic_data_req)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_data_write, ic_data_write)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_ic_data_addr, ic_data_addr)\n\nendinterface\n", "selected_doc_paths": ["doc/03_reference/exception_interrupts.rst", "doc/03_reference/debug.rst", "doc/03_reference/icache.rst", "doc/03_reference/register_file.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/security.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1881, "lang": "sv", "rtl_files": ["dv/uvm/core_ibex/env/core_ibex_dut_probe_if.sv"], "spec": "# Behavioral Design Specification: core_ibex_dut_probe_if\n\n## Overview\n\nThis module defines a UVM verification interface that provides testbench access to key internal signals of the Ibex processor core. It is used exclusively in simulation environments to observe and control core behavior during verification. The interface is synchronous to the core clock and exposes a set of signals that capture core state at the end of each clock cycle.\n\nThe interface serves two primary purposes:\n- **Observation**: Allows the testbench to monitor internal core signals (e.g., exception indications, alert outputs, debug mode, pipeline state, register file activity).\n- **Control**: Allows the testbench to drive two critical inputs to the core – `fetch_enable` and `debug_req` – enabling controlled start/stop of instruction fetch and debug entry.\n\n## Clocking Behavior\n\nAll signal sampling and driving is performed on the positive edge of the core clock. The interface defines a clocking block that synchronizes signal transitions to this edge. The testbench must use this clocking block when interacting with the interface to ensure proper setup and hold timing.\n\n## Exposed Signals (Observable)\n\nThe following groups of internal core signals are made available for monitoring:\n\n### Reset and Basic Status\n- **Reset state**: Indicates whether the core is in reset.\n- **Core sleep**: Indicates the core is in a low‑power idle state (WFI executed).\n\n### Exception and Trap Indicators\n- **Illegal instruction**: Asserted when an illegal instruction is decoded.\n- **Environment call (ECALL)**: Asserted when an ECALL instruction is executed.\n- **Wait‑for‑interrupt (WFI)**: Asserted when the WFI instruction is executed.\n- **Breakpoint (EBREAK)**: Asserted when an EBREAK instruction is executed.\n- **Debug return (DRET)**: Asserted when a DRET instruction is executed.\n- **Machine return (MRET)**: Asserted when an MRET instruction is executed.\n\n### Privilege and Debug State\n- **Privilege mode**: Current privilege level (Machine or User mode), encoded as an enumerated type.\n- **Debug mode**: Indicates the core is executing in Debug Mode.\n- **Control FSM state**: Current state of the main control finite state machine, encoded as an enumerated type.\n\n### Security Alerts\n- **Minor alert**: Asserted for non‑critical security events (e.g., potential timing anomalies or ECC warnings).\n- **Major internal alert**: Asserted for critical internal security events (e.g., register file ECC error or glitch detection).\n- **Major bus alert**: Asserted for critical security events detected on incoming bus data (e.g., integrity check failure).\n\n### Register File Read Activity\n- **Read enable for port A**: Indicates the register file’s read port A is being accessed in the current cycle.\n- **Read enable for port B**: Indicates the register file’s read port B is being accessed in the current cycle.\n- **Write‑back match for port A**: Indicates that the register requested on read port A matches the destination register of an in‑flight write‑back operation.\n- **Write‑back match for port B**: Similar match indication for read port B.\n\n### Double Fault Detection\n- **Double fault seen**: Asserted for one cycle when a double fault (synchronous exception while already handling a synchronous exception) is detected.\n\n### Fetch Enable\n- **Fetch enable**: A multi‑bit (MUBI) signal indicating whether instruction fetching is enabled. This signal is observed by the interface, but the testbench can also drive it (see “Controllable Signals” below).\n\n## Controllable Signals\n\nTwo signals can be driven by the testbench through the interface:\n\n- **Fetch enable**: The testbench can assert or deassert this multi‑bit signal to enable or disable instruction fetch. This allows simulation‑level control of core execution.\n- **Debug request**: The testbench can assert this signal to request the core to enter Debug Mode. The interface initializes this signal to inactive (0) at the start of simulation. The testbench must drive it through the clocking block.\n\n## Probe Functions\n\nThe interface provides functions that allow the testbench to directly probe the current value of specific register file read signals. These functions are useful for scoreboard or coverage tasks that need immediate access to these values without referencing the interface signals directly. The following signals have associated probe functions:\n\n- Register file read enable for port A\n- Register file read enable for port B\n- Write‑back match for port A\n- Write‑back match for port B\n\n## Initialization and Reset Behavior\n\nAt the start of simulation (initial block), the interface sets the driven `debug_req` output to logic zero. The other outputs (`fetch_enable`) are not initialized by the interface; the testbench must provide an initial value via the clocking block if required.\n\nAll sampled inputs are available immediately after the first positive clock edge following reset deassertion.\n\n## Usage Constraints\n\n- The interface is intended solely for use in UVM‑based simulation environments. It must not be instantiated in synthesis targets.\n- The testbench must adhere to the clocking block timing to avoid race conditions.\n- The `fetch_enable` and `debug_req` outputs must be driven only through the clocking block; direct assignment outside the clocking block may produce invalid behavior.\n- The interface imports the `ibex_pkg` package, which defines the multi‑bit (MUBI) type and privilege/enum types used in the signals.\n\n## Summary\n\nThe `core_ibex_dut_probe_if` module provides a comprehensive window into the Ibex core’s internal state for verification purposes. It enables the testbench to observe critical control, exception, debug, security, and register file signals, and to drive fetch enable and debug request inputs in a controlled, cycle‑accurate manner. The interface is a key component of the UVM verification environment for Ibex.", "commit_id": "e9a866ef55997f05a62c4c3af9dd60586697e197", "timestamp": "2022-11-04T15:00:44+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "66b3ed1ac1df79cc6d285e586135fd1e68ab198f", "pr_title": "[dv] Add test glitching register file read ports", "pr_body": "This PR addresses the integrity checking part of https://github.com/lowRISC/ibex/issues/1756 by verifying that a glitch on the data read from the register file raises a major alert by the core (if the data read from the register file is used by the core).\r\n\r\nThe **last** commit implements the actual test. The commits before that are prerequisites as follows:\r\n1. ~~duplicate from #1873, will be dropped once that PR is merged.~~\r\n2. ~~duplicate from #1879, will be dropped once that PR is merged.~~\r\n3. [dv] Add RF signals to `core_ibex_dut_probe_if` and\r\n4. [dv] Create signal probe functions in `core_ibex_dut_probe_if`: same approach as in #1879.\r\n\r\nPass rate is currently 100% (I tried 20 seeds) -- that is, alerts are produced and checked as expected ~~-- however the DV environment misinterprets passing tests as failures (probably due to the call to `dv_test_status_pkg::dv_test_status(1)` at the end of a successful test). Hints on how to fix this would be appreciated.~~", "issue_title": "[dv] Add test glitching PC of Ibex", "issue_body": "This PR addresses #1755 by verifying that a glitch on the PC of Ibex raises an internal major alert in the core.", "commit_message": "[dv] Add test glitching register file read data\n\nThis commit addresses the integrity checking part of #1756 by verifying\nthat a glitch on the data read from the register file raises a major\nalert by the core (if the data read from the register file is used by\nthe core).\n\nSigned-off-by: Andreas Kurth ", "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 06bb441112..7dec52c584 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@@ -4,6 +4,9 @@\n \n // Interface to probe DUT internal signal\n interface core_ibex_dut_probe_if(input logic clk);\n+\n+ import uvm_pkg::*;\n+\n logic reset;\n logic illegal_instr;\n logic ecall;\n@@ -21,6 +24,10 @@ interface core_ibex_dut_probe_if(input logic clk);\n ibex_pkg::ctrl_fsm_e ctrl_fsm_cs;\n logic debug_mode;\n logic double_fault_seen;\n+ logic rf_ren_a;\n+ logic rf_ren_b;\n+ logic rf_rd_a_wb_match;\n+ logic rf_rd_b_wb_match;\n \n clocking dut_cb @(posedge clk);\n output fetch_enable;\n@@ -40,10 +47,19 @@ interface core_ibex_dut_probe_if(input logic clk);\n input ctrl_fsm_cs;\n input debug_mode;\n input double_fault_seen;\n+ input rf_ren_a;\n+ input rf_ren_b;\n+ input rf_rd_a_wb_match;\n+ input rf_rd_b_wb_match;\n endclocking\n \n initial begin\n debug_req = 1'b0;\n end\n \n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_ren_a, rf_ren_a)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_ren_b, rf_ren_b)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_rd_a_wb_match, rf_rd_a_wb_match)\n+ `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_rd_b_wb_match, rf_rd_b_wb_match)\n+\n endinterface\n", "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\n import uvm_pkg::*;\n\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::ibex_mubi_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 logic debug_mode;\n logic double_fault_seen;\n logic rf_ren_a;\n logic rf_ren_b;\n logic rf_rd_a_wb_match;\n logic rf_rd_b_wb_match;\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 input debug_mode;\n input double_fault_seen;\n input rf_ren_a;\n input rf_ren_b;\n input rf_rd_a_wb_match;\n input rf_rd_b_wb_match;\n endclocking\n\n initial begin\n debug_req = 1'b0;\n end\n\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_ren_a, rf_ren_a)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_ren_b, rf_ren_b)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_rd_a_wb_match, rf_rd_a_wb_match)\n `DV_CREATE_SIGNAL_PROBE_FUNCTION(signal_probe_rf_rd_b_wb_match, rf_rd_b_wb_match)\n\nendinterface\n", "selected_doc_paths": ["doc/03_reference/exception_interrupts.rst", "doc/03_reference/debug.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/register_file.rst", "doc/03_reference/instruction_fetch.rst", "doc/03_reference/security.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 2307, "lang": "sv", "rtl_files": ["dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_request_driver.sv"], "spec": "# Behavioral Design Specification: `ibex_mem_intf_request_driver`\n\n## Overview\n\nThe `ibex_mem_intf_request_driver` is a UVM driver component that controls the request side of the memory interface agent used for the Ibex core's data memory (LSU) bus. It operates as a reactive master: it receives memory transaction requests (read or write) from the UVM sequencer and drives the corresponding bus signals to initiate the transfer on the memory interface. The driver also collects the response (read data or completion status) and returns it to the sequencer.\n\nThis driver is designed to work with the memory interface protocol defined for the Ibex core’s load-store unit (LSU), which supports single‑cycle and multi‑cycle back‑to‑back transfers, arbitrary request‑to‑grant delays, and response timing that may be multiple cycles after grant.\n\n## Functional Behavior\n\n### Reset Behavior\n\nUpon any assertion of the global reset signal (positive edge), the driver shall immediately:\n\n- De‑assert the request signal.\n- Place all address, write data, write integrity, byte‑enable, and write‑enable signals into a high‑impedance (idle) state.\n- The driver shall maintain these signals in the idle state for as long as reset is asserted.\n\nWhen reset is negated (negative edge), the driver shall wait for one clock cycle and then begin the normal transaction processing loop.\n\n### Transaction Driving (Request Phase)\n\nThe driver accepts `ibex_mem_intf_seq_item` objects one at a time from the UVM sequencer. Each item specifies:\n\n- A read/write indicator (read or write).\n- An address.\n- Byte enables.\n- Write data (for writes).\n- Write integrity bits (for systems that use integrity checking).\n- A required delay (`req_delay`) between the request being accepted and the driver actually asserting the bus request.\n\nThe driver shall:\n\n1. Wait for the number of clock cycles specified by `req_delay` (if greater than zero) before driving the request.\n2. On the chosen cycle, assert the request signal and simultaneously place on the bus:\n\n - The address.\n - The byte‑enables.\n - The write‑enable (driven high for a write, low for a read).\n - The write data and write integrity bits (for writes; for reads these signals may be ignored or driven to a defined state – the driver drives them to the values from the item).\n\n3. Hold these signals stable until the bus asserts the grant signal. The grant may occur in the same cycle as the request or any number of cycles later, in accordance with the LSU protocol.\n4. Once grant is observed asserted, the driver shall wait one clock cycle and then de‑assert the request signal and return the address, wdata, wintg, byte‑enable, and write‑enable signals to their idle high‑impedance state.\n5. Immediately after completing the drive, the driver shall enqueue the transaction for response collection.\n\nThe driver shall drive only one request at a time. It shall not issue a new request until the previous request has been granted and the response for that request has been collected (or the driver is ready to accept a new item from the sequencer). This ensures in‑order processing as required by the LSU protocol.\n\n### Response Collection\n\nThe driver maintains an internal queue of transactions for which the request has been completed (grant received) but the response (read data or write completion) has not yet been collected.\n\nFor each queued transaction, the driver shall:\n\n1. Wait until the bus asserts the response valid signal (`rvalid`). The driver shall ignore any clock cycle in which the bus also asserts a spurious response indicator; it shall continue waiting for a `rvalid` that is not accompanied by a spurious indication. This prevents the driver from consuming a response that is not intended for this request.\n2. Once a valid `rvalid` is observed, the driver shall:\n\n - If the original transaction was a **read**: capture the read data and read integrity bits from the bus.\n - If the original transaction was a **write**: the response data and integrity bits are not used by the core for write responses, but the driver shall still capture them (they may be used for checking or logging). The driver expects the bus to provide a valid response (data + integrity) for every write, as required by the LSU protocol.\n\n3. The driver shall then return a response object to the UVM sequencer via the response port. The response object shall be a clone of the original request item, updated with any captured read data and integrity bits. The response ID information shall be carried forward from the original request to allow the sequencer to correlate the response.\n\nThe driver shall process responses in the same order as the requests were enqueued.\n\n### Handling of Delays\n\nThe driver supports a configurable `req_delay` that specifies the number of clock cycles the driver shall wait after getting the next item from the sequencer before driving the request onto the bus. This delay is applied before the request is asserted, allowing simulation of variable pipeline depth or back‑pressure. A `req_delay` of zero means the request shall be driven immediately on the next clock cycle after receiving the item.\n\n### Interaction with Reset\n\nWhen reset is asserted at any time, the driver shall:\n\n- Abort any in‑progress request drive (the request signal shall be de‑asserted immediately, and the bus signals placed in high impedance).\n- Flush the internal response queue.\n- Discard any partially processed sequence item; the driver shall not return a response for an item that was interrupted by reset.\n- Resume the normal operating loop only after reset is de‑asserted (as described above).\n\nAll sequence items obtained before reset that were not yet fully processed are considered lost; the sequencer should be prepared to re‑issue them if necessary.\n\n### Error and Spurious Response Handling\n\nThe LSU protocol allows the bus to assert a spurious response indicator simultaneously with `rvalid`. The driver shall treat a cycle where the spurious indicator is high as if no valid response is present, and shall continue waiting for a future `rvalid` without the spurious indicator. This prevents the driver from incorrectly consuming a response that is not intended for the request it tracks.\n\nThe driver does not differentiate between error and success responses at the bus level; it captures the response data and integrity regardless of whether the bus error signal is asserted. Error handling (e.g., raising an exception) is performed by the core and is outside the scope of this driver.\n\n## Sequencing and Parallelism\n\nThe driver’s main operation comprises three parallel tasks:\n\n- **Get and drive**: As described above: obtains items, applies delays, drives request, and enqueues the item.\n- **Reset monitoring**: Continuously monitors the reset signal and, upon assertion, immediately forces the bus signals to idle and resets internal state.\n- **Response collection**: Continuously dequeues items from the internal queue, waits for valid `rvalid`, captures data, and sends responses.\n\nThese tasks run concurrently. Reset takes priority; if reset is asserted, the driving and response collection tasks shall be suspended until reset de‑asserts. The driver must handle the case where a request is in the middle of being driven when reset occurs – the request signals shall be released to idle without waiting for the grant or completing the transfer.\n\n## Requirements Summary\n\n- The driver shall comply with the Ibex LSU memory protocol (request/grant handshake, in‑order response delivery).\n- The driver shall correctly handle arbitrary request‑to‑grant latency and arbitrary response‑valid timing.\n- The driver shall properly handle reset at any point, placing the bus in a benign idle state.\n- The driver shall delay request assertion by the number of clock cycles specified in each transaction item.\n- The driver shall ignore spurious response indications and only consume valid `rvalid` signals.\n- The driver shall preserve transaction ordering: responses shall be returned to the sequencer in the same order as the corresponding requests were issued.\n- The driver shall pass read data and integrity bits back to the sequencer; for write transactions, it may still capture the response data for verification purposes.\n- The driver shall not drive a new request until the previous request has been granted, ensuring that only one outstanding request is present at a time.\n\n## Dependencies\n\nThis driver is intended to be used with the `ibex_mem_intf_vif` virtual interface and the `ibex_mem_intf_seq_item` sequence item class. It is independent of the memory model; the backing memory is handled by the agent’s monitor and other components.", "commit_id": "29f932486eb436d4b088c5c87794eaa057640e3f", "timestamp": "2025-08-17T19:50:55+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "587e9fe47ddf54a387b7976f6f720455f5a0b95d", "pr_title": "Fix #2302", "pr_body": "", "issue_title": "Verilator flags indentation warning that looks like a testbench bug", "issue_body": "I was trying to run Verilator lint on the full Ibex source code, including the testbench. I found that there was a lint warning about indentation. It actually looks like it's flagging a real bug:\n\n```\n%Warning-MISINDENT: ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_request_driver.sv:87:17: Misleading indentation\n 87 | tr.intg = vif.request_driver_cb.rintg;\n | ^\n ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_agent_pkg.sv:24:1: ... note: In file included from 'ibex_mem_intf_agent_pkg.sv'\n ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_request_driver.sv:85:7: ... Expected indentation matching this earlier statement's line:\n 85 | if(tr.read_write == READ)\n | ^~\n ... For warning description see https://verilator.org/warn/MISINDENT?v=5.037\n ... Use \"/* verilator lint_off MISINDENT */\" and lint_on around source to disable this message.\n```\n\n## Observed Source Code Issue\n\nIn `ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_request_driver.sv:87:17`:\n\n```\n if(tr.read_write == READ)\n tr.data = vif.request_driver_cb.rdata;\n tr.intg = vif.request_driver_cb.rintg;\n seq_item_port.put_response(tr);\n```\n\nThe two lines starting with `tr.` should probably both be under the if clause.\n\n## Expected Source Code\n\nThe driver should probably be fixed to have a `begin` and `end` to encapsulate these.\n\nIn `ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_request_driver.sv:87:17`:\n\n```\n if(tr.read_write == READ) begin\n tr.data = vif.request_driver_cb.rdata;\n tr.intg = vif.request_driver_cb.rintg;\n end\n seq_item_port.put_response(tr);\n```\n\n## My Environment\n\n**EDA tool and version:** Verilator 5.037 devel\n\n**Operating system:** macOS 15.5 arm64\n\n**Version of the Ibex source code:** 479750353fdf2a74d507ec436028349ded1b951a\n", "commit_message": "Fix #2302", "fix_patch": "diff --git a/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_request_driver.sv b/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_request_driver.sv\nindex 6ad0a2679a..5bf7a290fe 100644\n--- a/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_request_driver.sv\n+++ b/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_request_driver.sv\n@@ -82,9 +82,10 @@ class ibex_mem_intf_request_driver extends uvm_driver #(ibex_mem_intf_seq_item);\n rdata_queue.get(tr);\n vif.wait_clks(1);\n while((vif.rvalid !== 1'b1 || vif.spurious_response === 1'b1)) vif.wait_clks(1);\n- if(tr.read_write == READ)\n+ if (tr.read_write == READ) begin\n tr.data = vif.request_driver_cb.rdata;\n tr.intg = vif.request_driver_cb.rintg;\n+ end\n seq_item_port.put_response(tr);\n end\n endtask : collect_response\n", "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// CLASS: ibex_mem_intf_request_driver\n//------------------------------------------------------------------------------\n\nclass ibex_mem_intf_request_driver extends uvm_driver #(ibex_mem_intf_seq_item);\n\n protected virtual ibex_mem_intf vif;\n\n `uvm_component_utils(ibex_mem_intf_request_driver)\n `uvm_component_new\n\n mailbox #(ibex_mem_intf_seq_item) rdata_queue;\n\n function void build_phase(uvm_phase phase);\n super.build_phase(phase);\n rdata_queue = new();\n if(!uvm_config_db#(virtual ibex_mem_intf)::get(this, \"\", \"vif\", vif))\n `uvm_fatal(\"NOVIF\",{\"virtual interface must be set for: \",get_full_name(),\".vif\"});\n endfunction: build_phase\n\n virtual task run_phase(uvm_phase phase);\n fork\n get_and_drive();\n reset_signals();\n collect_response();\n join\n endtask : run_phase\n\n virtual protected task get_and_drive();\n @(negedge vif.request_driver_cb.reset);\n forever begin\n vif.wait_clks(1);\n seq_item_port.get_next_item(req);\n vif.wait_clks(req.req_delay);\n $cast(rsp, req.clone());\n rsp.set_id_info(req);\n drive_transfer(rsp);\n seq_item_port.item_done();\n end\n endtask : get_and_drive\n\n virtual protected task reset_signals();\n forever begin\n @(posedge vif.request_driver_cb.reset);\n vif.request_driver_cb.request <= 'h0;\n vif.request_driver_cb.addr <= 'hz;\n vif.request_driver_cb.wdata <= 'hz;\n vif.request_driver_cb.wintg <= 'hz;\n vif.request_driver_cb.be <= 'bz;\n vif.request_driver_cb.we <= 'bz;\n end\n endtask : reset_signals\n\n virtual protected task drive_transfer (ibex_mem_intf_seq_item trans);\n if (trans.req_delay > 0) begin\n vif.wait_clks(trans.req_delay);\n end\n vif.request_driver_cb.request <= 1'b1;\n vif.request_driver_cb.addr <= trans.addr;\n vif.request_driver_cb.be <= trans.be;\n vif.request_driver_cb.we <= trans.read_write;\n vif.request_driver_cb.wdata <= trans.data;\n vif.request_driver_cb.wintg <= trans.intg;\n wait (vif.request_driver_cb.grant === 1'b1);\n vif.wait_clks(1);\n vif.request_driver_cb.request <= 'h0;\n vif.request_driver_cb.addr <= 'hz;\n vif.request_driver_cb.wdata <= 'hz;\n vif.request_driver_cb.wintg <= 'hz;\n vif.request_driver_cb.be <= 'bz;\n vif.request_driver_cb.we <= 'bz;\n rdata_queue.put(trans);\n endtask : drive_transfer\n\n virtual protected task collect_response();\n ibex_mem_intf_seq_item tr;\n forever begin\n rdata_queue.get(tr);\n vif.wait_clks(1);\n while((vif.rvalid !== 1'b1 || vif.spurious_response === 1'b1)) vif.wait_clks(1);\n if (tr.read_write == READ) begin\n tr.data = vif.request_driver_cb.rdata;\n tr.intg = vif.request_driver_cb.rintg;\n end\n seq_item_port.put_response(tr);\n end\n endtask : collect_response\n\nendclass : ibex_mem_intf_request_driver\n", "selected_doc_paths": ["doc/03_reference/load_store_unit.rst", "doc/03_reference/verification.rst", "doc/03_reference/testplan.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1816, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# Ibex Controller Behavioral Specification\n\n## 1. Overview\n\nThe Ibex controller is the central control unit of the processor pipeline. It orchestrates the flow of instructions through the fetch, decode/execute, and optional writeback pipeline stages. The controller is responsible for:\n\n- Initializing the processor from reset and booting to the correct address.\n- Managing normal instruction execution, including branch and jump redirection.\n- Handling all exception and interrupt events, including precise trap reporting and pipeline flushing.\n- Supporting debug mode entry and exit.\n- Controlling pipeline stalls and flushes caused by multi-cycle instructions or exceptional events.\n- Providing signals that influence the instruction fetch stage (e.g., new program counter selection) and the decode/execute stage (e.g., instruction validation).\n\nThe controller observes status signals from the decoder, load-store unit, interrupt inputs, debug request, and stall/flush controls. It reacts deterministically according to a fixed priority scheme among events.\n\n---\n\n## 2. Reset and Boot\n\nUpon reset deassertion, the controller shall:\n\n1. Assert a reset-initiated fetch request to the instruction fetch stage. \n2. Direct the fetch stage to load the processor’s boot address. \n3. After one cycle, begin fetching the first instruction from that boot address. \n4. The boot address is implicitly the vector table base (mtvec) initial value; the core’s first instruction is assumed to be at `mtvec` base plus offset 0x80, per the RISC‑V privileged specification.\n\nThe controller remains in a booting sequence until a valid instruction enters the decode stage, after which normal execution starts.\n\n---\n\n## 3. Normal Instruction Execution\n\n### 3.1 Fetch and Decode Flow\n\nAfter boot, the controller continuously requests instructions from the fetch stage. Whenever the decode stage is ready (i.e., no stall condition and no pending exception/debug/interrupt), the controller enables the pipeline to accept a new instruction. Instructions move from fetch to decode each cycle unless stalled or flushed.\n\n### 3.2 Branches and Jumps\n\nWhen a branch or jump instruction is decoded:\n\n- The controller must redirect the instruction fetch to the computed target address **immediately** (no later than the decode cycle for jumps, or after condition evaluation for branches).\n- The controller also flushes any instructions that may have been fetched after the branch/jump but before the target is resolved.\n- If the branch predictor is enabled, the controller handles taken/not-taken mispredictions:\n - If a branch was predicted taken but is actually not taken, the controller reports a mispredict and flushes the incorrectly fetched target instruction(s).\n - If a branch was predicted not taken but is actually taken, the controller redirects fetch and flushes as normal.\n\n### 3.3 Stalls and Pipeline Hold\n\nThe controller stalls the pipeline under the following conditions:\n\n- **Data dependency stall**: The decode stage signals that the current instruction requires more cycles (e.g., multi-cycle multiplier, load/store waiting for memory).\n- **Writeback stall**: When the writeback stage is not ready to accept a completing instruction (only applicable if the writeback stage is present).\n- **Retain ID** (temporary hold): The controller may hold the instruction in decode when a special request (exception, interrupt, debug, or instruction fence) is pending but not yet fully resolved.\n\nWhile stalled:\n\n- No new instruction enters the decode stage.\n- The fetch stage may continue fetching unless told to halt (e.g., during an exception handling transition).\n\n### 3.4 Performance Monitoring\n\nThe controller must provide one‑cycle indicator pulses when:\n\n- A jump instruction is executed (any unconditional jump or jump‑and‑link).\n- A taken branch instruction is executed.\n\nThese signals are used by performance counters.\n\n---\n\n## 4. Exception Handling\n\n### 4.1 Exception Sources\n\nThe controller handles the following synchronous exception types when the corresponding instruction is in the decode stage (or writeback stage if present):\n\n- **Instruction access fault**: Fetch stage reported an error for this instruction.\n- **Illegal instruction**: Decoder detected an invalid opcode or privileged violation.\n- **Environment call (ECALL)**: System call from U‑ or M‑mode.\n- **Breakpoint (EBREAK)**: Breakpoint instruction.\n- **Load access fault**: Load instruction caused an error (known in writeback stage if present, otherwise in decode).\n- **Store access fault**: Store instruction caused an error (known in writeback stage if present, otherwise in decode).\n\n### 4.2 Exception Priority\n\nWhen multiple exceptions occur simultaneously (e.g., a fault in the writeback stage and a different fault in decode), the controller must give priority to the **architecturally older** instruction. The required ordering (highest priority first) is:\n\n1. Store access fault (writeback)\n2. Load access fault (writeback)\n3. Instruction access fault (decode)\n4. Illegal instruction (decode)\n5. ECALL (decode)\n6. EBREAK (decode)\n\nIf the writeback stage is not present, load/store faults are handled in the decode stage and are lower priority than instruction faults.\n\n### 4.3 Exception Flow\n\nUpon detecting an exception (after resolving priority and ensuring no pending events from the older instruction):\n\n1. The controller must **halt instruction fetch** immediately.\n2. The pipeline is **flushed**: all instructions in the fetch and decode stages are invalidated. Instructions in the writeback stage (if present) are allowed to complete normally before the flush.\n3. The controller saves the **return PC** to the `mepc` CSR:\n - For exceptions from the decode stage, the PC of the faulting instruction is saved.\n - For exceptions from the writeback stage (load/store faults), the PC of the instruction in writeback is saved instead.\n4. The **exception cause** is written to the `mcause` CSR.\n5. The **mtval** CSR is updated with the faulting address or instruction encoding, as appropriate for the exception type.\n6. The `mstatus` register’s MIE bit is saved to MPIE, and MIE is cleared.\n7. The controller directs the fetch stage to jump to the exception handler address. The handler address is:\n - If not in debug mode: `mtvec` base + 0×00 (all exceptions use the same base).\n - If in debug mode: `dm_exception_addr` (the debug exception address), so the core stays within the debug handler.\n\nAfter the fetch redirection, the controller returns to normal fetching at the handler address, and instruction flow resumes.\n\n### 4.4 MRET and DRET\n\nThe `mret` instruction causes the controller to:\n\n- Restore `mstatus` from the saved MPIE and MPP fields.\n- Return to the PC stored in `mepc`.\n- Exit NMI mode if currently active (see section 5.4).\n\nThe `dret` instruction causes the controller to:\n\n- Exit debug mode.\n- Restore the return PC from `dpc`.\n\nBoth MRET and DRET require a pipeline flush and a jump to the restored address.\n\n### 4.5 WFI (Wait for Interrupt)\n\nWhen a WFI instruction is decoded:\n\n- The controller puts the pipeline into a low‑power sleep state.\n- Instruction fetch is stopped, and no new instructions enter decode.\n- The core remains asleep until an enabled interrupt, debug request, or a condition that would cause immediate wake‑up (e.g., already in debug mode or single‑stepping) occurs.\n- Upon wake, the controller resumes fetch and decode normally.\n\n### 4.6 CSR Pipeline Flush\n\nSome CSR writes (e.g., to `mstatus` or `mtvec`) require a pipeline flush to ensure subsequent instructions see the new state. When such a flush is indicated, the controller:\n\n- Flushes the decode and fetch stages.\n- Does **not** take an exception (no PC redirection).\n- After the flush, resume fetching from the current PC.\n\n---\n\n## 5. Interrupt Handling\n\n### 5.1 Interrupt Types\n\nThe controller supports these interrupt sources:\n\n- **External NMI** (`irq_nm`, highest priority, always enabled).\n- **Internal NMI**: Generated by internal events (e.g., load integrity error – only when parameter `MemECC` is set). Uses the same vector as the external NMI.\n- **Fast interrupts** (15 lines, IDs 16–30).\n- **External interrupt** (ID 11).\n- **Timer interrupt** (ID 7).\n- **Software interrupt** (ID 3).\n\nAll interrupts except NMI can be masked via `mstatus.MIE` and `mie` CSR.\n\n### 5.2 Interrupt Enable Conditions\n\nAn interrupt is considered **pending** and will be taken only when:\n\n- The core is **not** in debug mode.\n- The core is **not** in single‑step mode (single stepping defers interrupts).\n- The core is **not** in NMI mode (NMIs are not nestable).\n- The global interrupt enable (`mstatus.MIE`) is set, **or** the core is in User Mode (U‑mode always has interrupts enabled).\n- The individual interrupt bit in `mie` is set (applies only to maskable interrupts, not NMI).\n\nInterrupts are also ignored while the core is in debug mode, even if `mstatus.MIE` is set.\n\n### 5.3 Interrupt Priority\n\nWhen multiple interrupts are pending, the controller selects the one with the highest architectural priority:\n\n1. Non‑maskable interrupt (NMI) – external or internal (ID 31).\n2. Fast interrupts – priority by lowest ID (fast[0] highest among fast).\n3. External interrupt.\n4. Software interrupt.\n5. Timer interrupt.\n\n### 5.4 NMI Mode\n\nWhen an NMI (external or internal) is taken:\n\n- The controller enters **NMI mode** (`nmi_mode` active). While in NMI mode, all further interrupts (including NMIs) are ignored.\n- The NMI handler vector is `mtvec` + 0×7C.\n- The cause for internal NMIs is reflected in `mcause` with a special encoding (e.g., 0xFFFFFFE0 for load integrity error) and `mtval` captures the faulting address.\n- External NMIs set `mcause` to the standard NMI code (0x8000001F).\n- The controller automatically exits NMI mode when an `mret` instruction is executed.\n\n### 5.5 Interrupt Flow\n\nWhen an interrupt is determined to be pending and taken (priority higher than any ongoing exception or debug event):\n\n1. If an instruction is currently in the decode stage and is **not** a multi‑cycle instruction that will still cause an exception, the controller waits for that instruction to complete.\n2. Once no instruction is in flight (including any load/store in writeback), the controller:\n - Halts fetch.\n - Redirects fetch to the appropriate interrupt handler vector (base + 4 × interrupt ID).\n - Saves the return PC (from the instruction that would have been the next to execute) into `mepc`.\n - Saves `mstatus.MIE` into `mstatus.MPIE` and clears `mstatus.MIE`.\n - Records the interrupt cause in `mcause`.\n3. The pipeline is **not flushed**; the instructions behind the interrupt point are simply discarded by the redirect.\n4. After the handler address is fetched, normal execution resumes.\n\n---\n\n## 6. Debug Support\n\n### 6.1 Debug Mode Entry\n\nThe controller shall enter debug mode upon any of the following events:\n\n- **External debug request** (`debug_req_i` asserted).\n- **Single‑step**: The `dcsr.step` bit is set and a valid instruction completes execution.\n- **Trigger match**: A hardware breakpoint (trigger) matches on the instruction in decode (if debug triggers are configured).\n- **EBREAK instruction**: When the corresponding `dcsr.ebreakm` or `dcsr.ebreaku` bit is set for the current privilege mode, or if the core is already in debug mode.\n\nDebug mode entry is **priority‑based** over normal interrupt handling, but an ongoing exception that takes priority (e.g., a load/store fault in writeback) is handled first.\n\n### 6.2 Debug Mode Entry Flow\n\nDepending on the cause, the controller enters debug mode through one of two paths:\n\n- **Debug entry from IF**: Used for external request, single‑step, or trigger match.\n 1. The controller saves the PC of the **next** instruction (the one that would have been executed) to `dpc`.\n 2. The debug cause is written to `dcsr.cause` (e.g., haltreq, step, trigger).\n 3. The controller jumps to the debug handler address `dm_halt_addr`.\n 4. The core enters debug mode.\n\n- **Debug entry from ID (EBREAK)**: Used when an EBREAK instruction must enter debug mode.\n 1. The controller saves the PC of the EBREAK instruction itself to `dpc`.\n 2. The debug cause is set to `ebreak`.\n 3. If the core was already in debug mode (e.g., an EBREAK encountered in debug mode), `dpc` and `dcsr` are **not** updated – the core re-enters debug mode at the same handler.\n 4. The controller jumps to the debug handler address.\n\nIn both cases, during the transition:\n\n- The pipeline is flushed.\n- The fetch stage is redirected.\n- The core remains in debug mode until a `dret` instruction is executed.\n\n### 6.3 Behavior in Debug Mode\n\nWhile in debug mode:\n\n- All interrupts (including NMI) are ignored.\n- Debug requests are ignored (already in debug mode).\n- Single‑stepping is ignored.\n- Exceptional events (like instruction faults or load/store errors) cause the core to jump to the **debug exception address** (`dm_exception_addr`) instead of the normal exception handler. The cause and `mepc` are saved as for a normal exception, but the core stays in debug mode.\n\n### 6.4 Debug CSR Save Signals\n\nThe controller provides signals to the CSR module to indicate when to save the PC to `dpc` and when to update `dcsr`. These saves happen exactly once per debug mode entry.\n\n---\n\n## 7. Pipeline Control Signals\n\n### 7.1 Fetch Halt and Flush\n\nThe controller generates the following control outputs to the pipeline stages:\n\n- **Instruction fetch halt**: When active, the fetch stage shall stop presenting new instructions to the decode stage. This is used during exception/interrupt/debug entry, and during WFI sleep.\n- **Instruction valid clear**: When active, the instruction currently in the decode stage shall be invalidated. This occurs on pipeline flushes (e.g., branch mispredict, exception) and when a branch/jump redirect occurs.\n- **ID ready**: Indicates to the decode stage that it may accept a new instruction from fetch. This is the inverse of stall, halt, and retain conditions.\n\n### 7.2 Stall Sources\n\nThe controller combines stall signals from:\n\n- **Decode stall**: The current instruction in decode needs more cycles (multi‑cycle operation).\n- **Writeback stall**: The writeback stage cannot accept the result of a completing instruction.\n\nWhile stalled, the instruction in decode remains valid, and fetch is prevented from advancing.\n\n### 7.3 Pipeline Flush\n\nA full pipeline flush (invalidate fetch and decode) occurs on:\n\n- Exception entry.\n- Interrupt entry (logical flush; the fetch is redirected but decode may be allowed to complete the current instruction first).\n- Debug entry.\n- MRET, DRET, FENCE.I.\n- CSR pipeline flush due to certain CSR writes.\n\nDuring a flush, any pending load/store operations in the memory system are **not** affected; they are allowed to complete in the background.\n\n---\n\n## 8. Configuration Parameters\n\nThe controller’s behavior is adjusted by the following parameters:\n\n- **WritebackStage**: If set (1’b1), the pipeline includes a third stage (writeback). The controller then expects the writeback stage to report load/store faults and to provide the return PC for those faults. The controller also waits for the writeback stage to be ready before handling exceptions and interrupts.\n- **BranchPredictor**: If set, the controller uses a static branch predictor. It assumes all branches with negative offset are taken. The controller must detect mispredictions and signal a not‑taken branch mispredict.\n- **MemECC**: If set, the controller includes logic for an internal NMI caused by a memory response integrity error (e.g., ECC error). The controller latches the faulty address and generates an internal interrupt at the next opportunity.\n\n---\n\n## 9. Double Fault Detection\n\nThe controller supports a double fault detection mechanism:\n\n- When a synchronous exception occurs, a flag (`sync_exception_seen`) is set internally.\n- This flag is cleared when an MRET instruction is executed.\n- If a second synchronous exception occurs while the flag is set, the controller asserts a one‑cycle **double fault seen** output and records the event in a custom CSR (`cpuctrl.double_fault_seen`).\n- The controller does not modify its normal exception handling flow upon detecting a double fault; the indication is merely a status signal.\n\n---\n\n## 10. Interaction with the CSR Module\n\nThe controller emits several signals to cause the CSR module to:\n\n- Save PC and interrupt/exception cause (`mepc`, `mcause`, `mtval`).\n- Save debug PC and cause (`dpc`, `dcsr`).\n- Restore PC and status on MRET/DRET (`mepc`, `mstatus`, `dpc`, `dcsr`).\n- Signal entry into NMI mode or debug mode to the CSR logic.\n\nThe controller does **not** directly compute any of these CSR values; it only indicates when and from which pipeline stage the values must be captured.\n\n---\n\n## 11. Summary of Priority Ordering\n\nWhen multiple events compete for control of the pipeline, they are resolved in the following order (highest priority first):\n\n1. **Multi‑cycle instruction completion / writeback exception** (load/store faults in writeback stage, if present).\n2. **Synchronous exception** from decode (priority among exceptions as listed in §4.2).\n3. **Debug mode entry** (trigger match, single‑step, external debug request, or EBREAK that must enter debug).\n4. **Interrupt** (any pending interrupt, with NMI highest, then fast, etc.).\n5. **Normal branch/jump** redirection.\n\nThe controller ensures that once a decision is made to handle a higher‑priority event, lower‑priority events are deferred until the handler completes (or the controller returns to normal execution).", "commit_id": "7b1be3354d650bc5b23dff6f439459c353288e4f", "timestamp": "2022-10-14T17:44:02+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "75a93dbed0dbe340b637c82e2a8e3ba1b841ecc3", "pr_title": "[rtl] Change how we record debug causes", "pr_body": "This commit changes when we catch the debug causes. Since `debug_cause_o` only gets saved when `csr_save_cause_o` is high, it would work if we change the cause with a mux that is connected to the input signals.\r\n\r\nResolves #1772\r\n\r\nSigned-off-by: Canberk Topal ", "issue_title": "Cosim mismatch when reading DCSR.cause", "issue_body": "## Observed Behavior\r\nTest failures with the following error : \r\n```\r\nUVM_FATAL ibex_cosim_scoreboard.sv(138) @ 4049807: Cosim mismatch Register write data mismatch to x22 DUT: 40000100 expected: 400000c0\r\n```\r\n\r\nThis fails upon reading from `DCSR.cause`\r\nIn this case : \r\n\r\n![image](https://user-images.githubusercontent.com/102029880/184605611-4f106a6b-a987-4952-b636-760647e12afe.png)\r\n(IBEX)\r\n\r\n![image](https://user-images.githubusercontent.com/102029880/184605563-b1bd1eb8-b8c3-47c2-b263-3c84427153f3.png)\r\n(SPIKE)\r\n\r\nObserving the waveform below, we can see that `debug_req_i` is de-asserted shortly after `debug_mode_i` goes low due to leaving debug mode from a dret. We do re-enter debug mode, but the cause can be seen to be recorded as `DBG_CAUSE_STEP`. In spike, we read back `DBG_CAUSE_HALTREQ` at the same instruction, hence the mismatch.\r\n\r\n## Expected Behavior\r\n\r\nIbex should record `DCSR.cause` as DBG_CAUSE_HALTREQ.\r\n\r\nI think this might be due to the [ibex_controller.sv ](https://github.com/lowRISC/ibex/blob/2f8dfa9dfe2d938228118ed8ab6a543804d0c9ae/rtl/ibex_controller.sv#L662)state machine sampling the `debug_req_i` signal to determine the correct `cause` one cycle later than the decision to enter debug_mode.\r\n\r\n## Steps to reproduce the issue\r\n```\r\ncd dv/uvm/core_ibex/\r\nmake TEST=riscv_debug_basic_test ITERATIONS=1 WAVES=1 SEED=9892 -j12 -ik\r\n```\r\n![image](https://user-images.githubusercontent.com/102029880/184603232-ef1a9397-1cd2-4a0b-828b-1b2eb4e1745a.png)\r\n\r\n> estimate 8\r\n> remaining 2022-09-27 4\r\n> remaining 2022-10-12 1", "commit_message": "Fixup signal used when checking for ebreak cause", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex 3673967a00..ecaf64fb84 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -114,6 +114,7 @@ module ibex_controller #(\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@@ -417,6 +418,26 @@ module ibex_controller #(\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 ? 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@@ -453,7 +474,6 @@ module ibex_controller #(\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@@ -657,13 +677,6 @@ module ibex_controller #(\n debug_csr_save_o = 1'b1;\n \n csr_save_cause_o = 1'b1;\n- if (trigger_match_i) begin\n- debug_cause_o = DBG_CAUSE_TRIGGER; // (priority 4)\n- end else if (debug_req_i) begin\n- debug_cause_o = DBG_CAUSE_HALTREQ; // (priority 1)\n- end else begin\n- debug_cause_o = DBG_CAUSE_STEP; // (priority 0, lowest)\n- end\n \n // enter debug mode\n debug_mode_d = 1'b1;\n@@ -693,7 +706,6 @@ module ibex_controller #(\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", "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\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, 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 // 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;\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_set | 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 ? 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 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\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 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 //////////\n // FCOV //\n //////////\n\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 `ifdef INC_ASSERT\n // If something that causes a jump into an exception handler is seen that jump must occur before\n // the next instruction executes. The logic tracks whether a jump into an exception handler is\n // expected. Assertions check the jump occurs.\n\n logic exception_req, exception_req_pending, exception_req_accepted, exception_req_done;\n logic exception_pc_set, seen_exception_pc_set, expect_exception_pc_set;\n logic exception_req_needs_pc_set;\n\n assign exception_req = (special_req | enter_debug_mode | handle_irq);\n // Any exception rquest will cause a transition out of DECODE, once the controller transitions\n // back into DECODE we're done handling the request.\n assign exception_req_done =\n exception_req_pending & (ctrl_fsm_cs != DECODE) & (ctrl_fsm_ns == DECODE);\n\n assign exception_req_needs_pc_set = enter_debug_mode | handle_irq | special_req_pc_change;\n\n // An exception PC set uses specific PC types\n assign exception_pc_set =\n exception_req_pending & (pc_set_o & (pc_mux_o inside {PC_EXC, PC_ERET, PC_DRET}));\n\n always @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n exception_req_pending <= 1'b0;\n exception_req_accepted <= 1'b0;\n expect_exception_pc_set <= 1'b0;\n seen_exception_pc_set <= 1'b0;\n end else begin\n // Keep `exception_req_pending` asserted once an exception_req is seen until it is done\n exception_req_pending <= (exception_req_pending | exception_req) & ~exception_req_done;\n\n // The exception req has been accepted once the controller transitions out of decode\n exception_req_accepted <= (exception_req_accepted & ~exception_req_done) |\n (exception_req & ctrl_fsm_ns != DECODE);\n\n // Set `expect_exception_pc_set` if exception req needs one and keep it asserted until\n // exception req is done\n expect_exception_pc_set <= (expect_exception_pc_set | exception_req_needs_pc_set) &\n ~exception_req_done;\n\n // Keep `seen_exception_pc_set` asserted once an exception PC set is seen until the\n // exception req is done\n seen_exception_pc_set <= (seen_exception_pc_set | exception_pc_set) & ~exception_req_done;\n end\n end\n\n // Once an exception request has been accepted it must be handled before controller goes back to\n // DECODE\n `ASSERT(IbexNoDoubleExceptionReq, exception_req_accepted |-> ctrl_fsm_cs != DECODE)\n\n // Only signal ready, allowing a new instruction into ID, if there is no exception request\n // pending or it is done this cycle.\n `ASSERT(IbexDontSkipExceptionReq,\n id_in_ready_o |-> !exception_req_pending || exception_req_done)\n\n // Once a PC set has been performed for an exception request there must not be any other\n // excepting those to move into debug mode.\n `ASSERT(IbexNoDoubleSpecialReqPCSet,\n seen_exception_pc_set &&\n !((ctrl_fsm_cs inside {DBG_TAKEN_IF, DBG_TAKEN_ID}) &&\n (pc_mux_o == PC_EXC) && (exc_pc_mux_o == EXC_PC_DBD))\n |-> !pc_set_o)\n\n // When an exception request is done there must have been an appropriate PC set (either this\n // cycle or a previous one).\n `ASSERT(IbexSetExceptionPCOnSpecialReqIfExpected,\n exception_req_pending && expect_exception_pc_set && exception_req_done |->\n seen_exception_pc_set || exception_pc_set)\n\n // If there's a pending exception req that doesn't need a PC set we must not see one\n `ASSERT(IbexNoPCSetOnSpecialReqIfNotExpected,\n exception_req_pending && !expect_exception_pc_set |-> ~pc_set_o)\n `endif\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", "selected_doc_paths": ["doc/03_reference/exception_interrupts.rst", "doc/03_reference/debug.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/instruction_fetch.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1488, "lang": "sv", "rtl_files": ["rtl/ibex_register_file_fpga.sv"], "spec": "# Behavioral Specification: ibex_register_file_fpga\n\n## Overview\n\nThe `ibex_register_file_fpga` module implements a general‑purpose register file as required by the RISC‑V architecture. It provides storage for either 31 or 15 writable registers (plus the hardwired‑zero register `x0`), with two independent asynchronous read ports and one synchronous write port. The design is optimized for FPGA synthesis, typically inferring block RAM or LUT‑based memory primitives.\n\n## Register Organization\n\n- **Number of registers** \n The register file contains either 31 or 15 writable registers, depending on whether the RV32E extension is enabled.\n - When RV32E is **disabled**: 32 addressable entries (addresses 0 through 31). Entry 0 is the zero register (`x0`) and always reads as 0.\n - When RV32E is **enabled**: 16 addressable entries (addresses 0 through 15). Entry 0 is likewise hardwired to 0.\n All writable registers are 32 bits wide.\n\n## Initial State\n\nUpon power‑on (or after the device configuration in an FPGA), every register (except entry 0) is initialized to a constant value. This value is controllable via a parameter and defaults to all‑zeros. The register file has **no dynamic reset** – the `rst_ni` input is unused and has no effect on the stored values.\n\n## Read Ports\n\nTwo independent read ports are provided. For each port:\n\n- **Address input**: a 5‑bit address (only bits needed for the selected depth are used; higher bits are ignored in practice when RV32E is enabled).\n- **Data output**: the current content of the addressed register is presented on the output **in the same cycle** as the address (asynchronous read).\n- **Hardwired zero**: if the read address is 0, the output is forced to all‑zeros, regardless of any stored value.\n\n## Write Port\n\nA single synchronous write port operates as follows:\n\n- **Write enable**: when the write enable input is asserted and the write address is **not** 0, the data on the write data bus is stored into the addressed register.\n- **Write to register 0 is ignored**: a write to address 0 has no effect on the register file; the value of the zero register remains unchanged.\n- **Timing**: the write takes effect on the **rising edge of the clock**. Data must be stable before the rising edge and is sampled at that edge.\n\n## Write‑to‑Read Forwarding\n\n**No write‑to‑read forwarding** is implemented. If a write and a read target the same register in the same cycle, the read returns the **previous** value of that register, not the value being written. The new value becomes available to subsequent reads starting one clock cycle later.\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|--------------------|---------|---------|-------------------------------------------------------------------------------------------------------------|\n| `RV32E` | bit | 0 | When set to 1, the register file is reduced to 16 entries (15 writable) as per the RV32E extension. |\n| `DataWidth` | integer | 32 | Width of each register (fixed to 32 in practice). |\n| `DummyInstructions`| bit | 0 | **Not used** in this module. The signal `dummy_instr_id_i` is connected but ignored. |\n| `WordZeroVal` | logic | 0 | The value with which **all registers (except entry 0)** are initialized at power‑on. |\n\n## Inputs and Outputs (Functional View)\n\n- **Clock** (`clk_i`): All state changes (writes) occur on the rising edge of this clock.\n- **Reset** (`rst_ni`): **Unused**. The register file does not react to this signal.\n- **Test Enable** (`test_en_i`): **Unused** in the FPGA implementation. The signal is accepted but ignored.\n- **Dummy Instruction ID** (`dummy_instr_id_i`): **Unused**. It has no effect on register file operation.\n- **Read Port A**: Address input, data output (combinatorial).\n- **Read Port B**: Address input, data output (combinatorial).\n- **Write Port**: Address input, data input, write enable input (active high). Write occurs on the rising clock edge if enable is asserted and address is not zero.\n\n## Clock and Reset Behavior\n\n- The module is fully synchronous for writes. Set‑up/hold times relative to the clock apply as per standard flip‑flop or RAM primitive timing.\n- No reset or clear sequence is required; the initial state is established during FPGA configuration (or simulation initialization) as described above.\n\n## Summary of Observability\n\n- Any read to address 0 always returns `0`.\n- Any read to a non‑zero address returns the value stored in that register, reflecting the most recent completed write (including writes from previous cycles).\n- A write to a non‑zero address updates the stored value one clock cycle later.\n- A write to address 0 is silently discarded.\n\nThis specification defines only the externally visible behavior of the `ibex_register_file_fpga` module. Internal implementation choices (such as the use of RAM primitives, initial‑block initialization, or clock gating) are not part of this behavioral description.", "commit_id": "fa3df3b8ee1f6c7fc71f2d429f16b0015413f075", "timestamp": "2021-12-09T15:35:31+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "fccdd63992991c65458c94f330a1c7428b7ee6db", "pr_title": "[rtl] Replace always_ff with always @(posedge .. in FPGA regfile", "pr_body": "This resolves lowRISC/Ibex#1485.\r\n\r\nNote: I've tested that these changes don't impact the Vivado's capability to infer LUTRAM for the FPGA regfile.", "issue_title": "Wrong SV code - compilation error occurs", "issue_body": "\r\n\r\n## Observed Behavior\r\n\r\nAfter https://github.com/lowRISC/ibex/commit/169785d0711335c94561a93146e069766eec138c commit the \"ibex_simple_system\" and UVM tests cannot be compiled because of the error:\r\n\r\n`ALOG: Error: VCP2675 /ibex/build/lowrisc_ibex_ibex_simple_system_0/src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_register_file_fpga.sv : (63, 1): Cannot write to a variable 'mem[k]' that is also driven by an always_comb/always_latch/always_ff procedural block. `\r\n\r\n\r\nThe problem is caused by wrong SV code:\r\nhttps://github.com/lowRISC/ibex/blob/c78acac8cc381293900f3648e365ddd136784789/rtl/ibex_register_file_fpga.sv#L54-L65\r\n\r\nIn this case the mem[] variable is written in always_ff and initial block what is prohibited by SV LRM:\r\n\r\n> \"The always_ff procedure imposes the restriction that it contains one and only one event control and no\r\n> blocking timing controls. Variables on the left-hand side of assignments within an always_ff procedure,\r\n> including variables from the contents of a called function, shall not be written to by any other process.\"\r\n\r\n## Expected Behavior\r\n\r\n\r\nThe code should compile without errors.\r\n\r\n## Steps to reproduce the issue\r\n\r\n\r\n## My Environment\r\n\r\n\r\n\r\n**EDA tool and version:**\r\n\r\nAldec Riviera-PRO\r\n\r\n**Operating system:**\r\n\r\nLinux, Ubuntu 20.04\r\n\r\n**Version of the Ibex source code:**\r\n\r\n", "commit_message": "[rtl] Replace always_ff with always @(posedge .. in FPGA regfile\n\nThis resolves lowRISC/Ibex#1485.\n\nSigned-off-by: Pirmin Vogel ", "fix_patch": "diff --git a/rtl/ibex_register_file_fpga.sv b/rtl/ibex_register_file_fpga.sv\nindex 3a5d425afe..678549aba6 100644\n--- a/rtl/ibex_register_file_fpga.sv\n+++ b/rtl/ibex_register_file_fpga.sv\n@@ -51,7 +51,12 @@ module ibex_register_file_fpga #(\n // we select\n assign we = (waddr_a_i == '0) ? 1'b0 : we_a_i;\n \n- always_ff @(posedge clk_i) begin : sync_write\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", "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 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\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\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 // async_read a\n assign rdata_a_o = (raddr_a_i == '0) ? '0 : mem[raddr_a_i];\n\n // async_read b\n assign rdata_b_o = (raddr_b_i == '0) ? '0 : mem[raddr_b_i];\n\n // we select\n assign we = (waddr_a_i == '0) ? 1'b0 : we_a_i;\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;\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", "selected_doc_paths": ["doc/03_reference/register_file.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1839, "lang": "sv", "rtl_files": ["rtl/ibex_if_stage.sv"], "spec": "# Behavioral Specification: Instruction Fetch (IF) Stage\n\n## Overview\n\nThe Instruction Fetch (IF) stage is the first stage of the Ibex processor pipeline. Its primary responsibility is to supply one instruction per cycle to the Instruction Decode and Execute (ID/EX) stage. It manages the program counter (PC), fetches instructions from memory (either through a prefetch buffer or an optional instruction cache), decompresses compressed instructions, and handles errors, dummy instructions, and branch prediction.\n\nThe IF stage interfaces with:\n\n- The instruction-side memory system (bus or cache).\n- The ID/EX stage, providing instructions, PC, and status flags.\n- The control unit, receiving PC‑set requests, stalls, and exceptions.\n- The PMP (Physical Memory Protection) unit.\n- The CSR (Control and Status Register) unit for exception handling and debug.\n\n## Behavior\n\n### 1. PC Selection\n\nWhen a new PC must be set (e.g., on reset, taken branch, exception, interrupt, debug entry, or return), the IF stage must select the correct new PC from one of the following sources, in priority order:\n\n- **Boot address** – Used at reset and whenever the core is told to boot.\n- **Jump target** – From the ID/EX stage (calculated branch or jump address).\n- **Exception/interrupt vector** – Determined by the exception cause. For synchronous exceptions, the PC is taken from `mtvec` (aligned to 256‑byte boundary). For interrupts, the PC is `mtvec` base plus an offset based on the interrupt ID. For NMI, the offset points to the NMI handler. For debug exceptions, the PC is the fixed debug exception address. For debug entry (single‑step or breakpoint), the PC is the debug halt address.\n- **Return addresses** – From `mepc` (exception return) or `depc` (debug return).\n- **Branch prediction target** – If the optional branch predictor signals a taken branch, the PC is set to the predicted target address. The IF stage must honour the predicted PC only if no other PC‑set request is active.\n\nThe IF stage must ignore the branch predictor when any of the above higher‑priority PC‑set events occurs.\n\n### 2. Instruction Fetch Flow\n\nAfter the PC is set, the IF stage fetches instructions linearly, incrementing the PC by 2 or 4 bytes depending on whether the fetched instruction is compressed or not. Fetches are performed through one of two sub‑modules:\n\n- **Prefetch buffer** (default) – Buffers a small number of instructions to improve performance and timing.\n- **Instruction cache (I$)** (optional) – A fully‑associative cache that reduces memory latency.\n\nThe IF stage requests instructions from the memory system using a simple request/grant/valid protocol. The address sent to memory must be word‑aligned (aligned to 4 bytes). If the internal PC is half‑word aligned (due to a compressed instruction), the IF stage must still make a word‑aligned request and select the correct half‑word internally.\n\nWhen a branch or jump occurs, the IF stage must flush its prefetch buffer (or I$ pipeline) and begin fetching from the new PC. The prefetch buffer or I$ must be flushed on any PC‑set event (including exceptions, interrupts, and debug entries).\n\n### 3. Ready/Valid Handshake with ID/EX Stage\n\nThe IF stage supplies instructions to ID/EX via a ready/valid handshake:\n\n- `valid` – Indicates that a new instruction (and its associated PC and status) is available.\n- `ready` – Driven by ID/EX to indicate it can accept the instruction.\n\nA transfer occurs when both valid and ready are high simultaneously. Once valid is asserted, the stage must keep it asserted (and all associated output signals stable) until the transfer completes or until a PC‑set event (including branch mispredict) invalidates the instruction.\n\nThe IF stage must hold its output pipeline registers (the IF‑ID registers) stable when ID/EX is not ready. Only when a transfer occurs (valid and ready high) are the registers updated.\n\n### 4. Instruction Compression and Decompression\n\nThe IF stage must decompress compressed (16‑bit) instructions into 32‑bit equivalents before passing them to the ID/EX stage. The decompression is performed on the fetched instruction data. The following information must be forwarded to ID/EX:\n\n- The full 32‑bit decompressed instruction.\n- A replica of the decompressed instruction (for timing).\n- The original 16‑bit instruction (for the `mtval` CSR in case of an illegal instruction exception).\n- A flag indicating whether the original instruction is compressed.\n- A flag indicating whether the compressed decoder considers the instruction illegal (for illegal instruction exceptions).\n\n### 5. Error Handling\n\nErrors can occur during instruction fetch:\n\n- **Bus error** – Signaled by the memory system (e.g., access to non‑existent memory).\n- **PMP error** – Signaled by the PMP unit (access to a protected region).\n- **ECC error** – If the instruction bus includes ECC (optional), an integrity error from the bus is treated as a bus error.\n- **I$ ECC error** – If the instruction cache is present and has ECC, an ECC error in the cache’s tag or data RAMs must cause the cache to treat that fetch as a miss and fetch from main memory. The cache must signal an ECC error alert. The I$ must never correct errors; any correctable or uncorrectable ECC error results in a refetch.\n\nWhen an error occurs, the IF stage must set an error flag for that instruction and pass it to ID/EX. The IF stage must also provide a “plus‑2” error flag that indicates the error applies to the second half of an unaligned, uncompressed instruction (used to record the correct address in `mtval`). PMP errors can arise from either the instruction’s own address or the next address when the instruction spans two word‑aligned fetches.\n\nFor misaligned uncompressed instructions (half‑word aligned), the IF stage must request two separate word‑aligned memory accesses. If the second access causes an error, the “plus‑2” flag must be set.\n\n### 6. Dummy Instructions (Optional)\n\nFor security hardening, the IF stage can insert dummy instructions into the pipeline. This feature is controlled by an enable and a mask. Dummy instructions are generated by a linear‑feedback shift register (LFSR) seeded from a CSR. When a dummy instruction is inserted:\n\n- The IF stage must stall the pipeline (prevent the next real instruction from entering ID/EX) for one cycle.\n- The dummy instruction is presented to ID/EX with a dedicated flag (`dummy_instr_id_o`).\n- The dummy instruction has no effect on architectural state (it is executed but its results are discarded). The PC of the dummy instruction equals the PC of the next real instruction.\n\nDummy instruction insertion must be suppressed while a bus or PMP error is being reported for the real instruction.\n\n### 7. Branch Prediction (Optional)\n\nWhen the optional branch predictor is enabled, the IF stage uses static prediction: any branch instruction whose immediate offset is negative is predicted taken; others are predicted not taken.\n\n- **Predicted taken** – The IF stage sets the PC to the predicted target address (calculated from the branch instruction’s immediate). The next instruction fetched is the target instruction.\n- **Predicted not taken** – The IF stage continues sequential fetch.\n\nThe predictor operates on the instruction currently being fetched. If that instruction is predicted taken, the IF stage must provide a “branch taken” flag to ID/EX so that the execute stage can verify whether the branch was actually taken.\n\n#### Skid Buffer\n\nWhen a predicted‑taken instruction cannot be immediately accepted by ID/EX (ID/EX not ready), the IF stage must buffer the instruction and its predicted status in a skid buffer. The skid buffer holds exactly one instruction. While the skid buffer holds a valid instruction, the IF stage must not make new branch predictions (the instruction in the skid is the one that produced the prediction). The skid buffer must release its contents to ID/EX when ID/EX becomes ready.\n\nIf a branch mispredict occurs (ID/EX detects that a branch predicted taken was actually not taken), the IF stage must:\n\n- Cancel the current fetch (as if a branch had occurred) and resume fetching from the not‑taken address.\n- Ignore any instruction that was in the skid buffer or fetched under the prediction.\n- Not generate a new branch prediction until the misprediction is processed.\n\nThe mispredict can arrive on the same cycle as a new fetch valid; in that case the new fetch is considered valid (it is the not‑taken side) and no further squashing is needed.\n\n#### Assertion Checks (for verification)\n\nThe design must ensure that mispredict is only signalled when a predicted branch is still live (i.e., instructions from the predicted path have not yet been accepted by ID/EX). If the core signals mispredict, the prefetch buffer or I$ must provide the correct not‑taken PC.\n\n### 8. PC Increment Consistency Check (Optional)\n\nFor security, the IF stage can optionally check that every sequential PC increment matches the expected value (previous PC + 2 or +4, depending on the instruction size). This check is enabled by a parameter and operates on the PC values in the IF and ID stages. If a mismatch is detected (i.e., the IF stage’s current PC is not equal to the previous ID stage PC plus the known instruction size), the IF stage must raise an alert.\n\nThe check must be bypassed after any PC‑set event (branch, jump, exception, interrupt, debug) and after reset, and also for dummy instructions. It must also be bypassed for the first instruction fetched after a PC‑set event.\n\n### 9. Power Management and Busy Status\n\nThe IF stage must provide a `busy` signal that is high whenever the prefetch buffer or I$ is actively fetching instructions or performing cache invalidation. This signal can be used to prevent clock gating while the stage is doing useful work.\n\nWhen the core asserts a request enable signal (`req_i`), the prefetch buffer or I$ begins fetching. If the request enable goes low (e.g., during `WFI`), the stage must stop making new memory requests as soon as possible (after completing any outstanding cache line fill).\n\n### 10. Instruction Cache (I$) Specific Behavior\n\nIf the I$ is present (parameter `ICache = 1`), the following additional behaviors must be implemented:\n\n- **Cache enable** – Controlled by a CSR. When disabled, the I$ operates in pass‑through mode: every instruction is fetched from memory and no data is stored in the cache.\n- **Cache invalidation** – Triggered by an external signal (from `FENCE.I`). While invalidation is in progress, the I$ behaves as if disabled (no allocations). After invalidation completes, caching resumes.\n- **ECC errors** – As described in Section 5, ECC errors cause a refetch and an alert. The cache must invalidate the line (or tag) where the error occurred.\n- **Scrambling** – If scrambling is enabled, the I$ uses a scrambling key that can be renewed via a request/acknowledge protocol. A new key is requested on a reset or `FENCE.I`. While a key request is pending, the I$ must operate in pass‑through mode (or continue with the old key until the new one arrives). The I$ must invalidate its contents after the key is updated.\n\n### 11. Reset Behavior\n\nAt system reset:\n\n- The IF stage must set its PC to the boot address.\n- The prefetch buffer or I$ must be flushed.\n- The IF‑ID pipeline registers must be cleared to a known state (if parameter `ResetAll` is set).\n- The instruction valid flag for the ID stage must be de‑asserted.\n- All internal state (including branch predictor, dummy instruction logic, and PC consistency checker) must be initialized.\n\n### 12. Interface Summary\n\nThe IF stage must expose the following logical interfaces (signal names are omitted, only functional descriptions):\n\n- **PC selection inputs**: boot address, jump target, exception PC, return addresses, branch prediction target.\n- **Instruction memory interface**: request, address, grant, valid, data, error (bus and PMP).\n- **I$ memory interface**: tag and data RAM ports, enable, invalidate, ECC error output.\n- **Outputs to ID/EX**: valid flag, new instruction flag, decompressed instruction, its replica, original compressed instruction (for mtval), compressed flag, illegal‑compressed flag, error flags (bus, plus‑2, and combined), branch predicted taken flag, dummy instruction flag, PC of the instruction.\n- **Control inputs**: request enable (from core), PC‑set signal, PC mux selector, exception PC selector, exception cause, not‑taken branch mispredict signal and address, dummy instruction enable/mask/seed, I$ enable/invalidate.\n- **CSR inputs**: `mepc`, `depc`, `mtvec`.\n- **Outputs**: mtvec initialization signal, PC mismatch alert, busy status, I$ ECC error alert.\n\nAll interfaces must operate correctly under the timing constraints of a single‑cycle, 2‑stage pipeline with support for stalls, branches, exceptions, and optional features.\n\n## Summary of Key Requirements\n\n1. **PC management**: Must correctly select the next PC from multiple sources with fixed priority.\n2. **Instruction fetch**: Must fetch word‑aligned instructions linearly, handle misalignment internally, and flush the fetch pipeline on any PC change.\n3. **Handshake**: Must implement a ready/valid interface with backpressure and hold semantics.\n4. **Decompression**: Must decompress compressed instructions and forward appropriate flags.\n5. **Error handling**: Must combine bus and PMP errors, handle plus‑2 errors, and pass error information to ID/EX.\n6. **Dummy instructions (optional)**: Must insert dummy instructions, stall the pipeline, and mark them.\n7. **Branch prediction (optional)**: Must predict static branches, handle skid buffer, and support misprediction with correct not‑taken address.\n8. **PC consistency check (optional)**: Must raise alert on unexpected PC increments.\n9. **I$ (optional)**: Must support enable, invalidate, ECC, and scrambling.\n10. **Reset**: Must initialize all state appropriately.\n\nThe IF stage must meet all functional requirements under the assumption of a single‑clock, synchronous design with an asynchronous reset.", "commit_id": "0e396d594435c0acca9df785ac40309c76576cc3", "timestamp": "2022-10-06T09:23:01+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "7ab2571bea0daca3f14155d82f0124fb0b118799", "pr_title": "[if,pmp] Check second bit instead of third for instruction alignment", "pr_body": "Ibex was checking the wrong bit when looking at PMP errors and when to count the error it received from instruction fetch +2.\r\n\r\nCloses: https://github.com/lowRISC/ibex/issues/1837", "issue_title": "[pmp] Instruction straddling two TOR regions cosim mismatch", "issue_body": "When running the following test:\r\n`make -j1 --keep-going IBEX_CONFIG=opentitan ITERATIONS=1 TEST=riscv_epmp_mml_test WAVES=0 COV=0 SEED=30325`\r\n\r\nIbex and Spike have different behavior. Spike throws an instruction access fault exception for the address `0x80005cc4`. The TOR region ends at `0x80005cc4`, which is the expected behavior.\r\n\r\nI think Ibex somehow does not perform the check for fetched instructions properly. In this test case there is a branch instruction that straddles two PMP entries, so Ibex must do two requests.\r\n\r\nIbex commit: 0e396d594435c0acca9df785ac40309c76576cc3\r\nSpike commit: 0dc2de5d76add7b218b31053792a676973034b9e\r\n\r\n> estimate 4", "commit_message": "[if,pmp] Check second bit instead of third for instruction alignment\n\nSigned-off-by: Marno van der Maas ", "fix_patch": "diff --git a/rtl/ibex_if_stage.sv b/rtl/ibex_if_stage.sv\nindex 392980d8ad..1bf21ced1f 100644\n--- a/rtl/ibex_if_stage.sv\n+++ b/rtl/ibex_if_stage.sv\n@@ -386,13 +386,13 @@ module ibex_if_stage import ibex_pkg::*; #(\n // An error can come from the instruction address, or the next instruction address for unaligned,\n // uncompressed instructions.\n assign if_instr_pmp_err = pmp_err_if_i |\n- (if_instr_addr[2] & ~instr_is_compressed & pmp_err_if_plus2_i);\n+ (if_instr_addr[1] & ~instr_is_compressed & pmp_err_if_plus2_i);\n \n // Combine bus errors and pmp errors\n assign if_instr_err = if_instr_bus_err | if_instr_pmp_err;\n \n // Capture the second half of the address for errors on the second part of an instruction\n- assign if_instr_err_plus2 = ((if_instr_addr[2] & ~instr_is_compressed & pmp_err_if_plus2_i) |\n+ assign if_instr_err_plus2 = ((if_instr_addr[1] & ~instr_is_compressed & pmp_err_if_plus2_i) |\n fetch_err_plus2) & ~pmp_err_if_i;\n \n // compressed instruction decoding, or more precisely compressed instruction\n", "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 * Instruction Fetch Stage\n *\n * Instruction fetch unit: Selection of the next PC, and buffering (sampling) of\n * the read instruction.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_if_stage import ibex_pkg::*; #(\n parameter int unsigned DmHaltAddr = 32'h1A110800,\n parameter int unsigned DmExceptionAddr = 32'h1A110808,\n parameter bit DummyInstructions = 1'b0,\n parameter bit ICache = 1'b0,\n parameter bit ICacheECC = 1'b0,\n parameter int unsigned BusSizeECC = BUS_SIZE,\n parameter int unsigned TagSizeECC = IC_TAG_SIZE,\n parameter int unsigned LineSizeECC = IC_LINE_SIZE,\n parameter bit PCIncrCheck = 1'b0,\n parameter bit ResetAll = 1'b0,\n parameter lfsr_seed_t RndCnstLfsrSeed = RndCnstLfsrSeedDefault,\n parameter lfsr_perm_t RndCnstLfsrPerm = RndCnstLfsrPermDefault,\n parameter bit BranchPredictor = 1'b0,\n parameter bit MemECC = 1'b0,\n parameter int unsigned MemDataWidth = MemECC ? 32 + 7 : 32\n) (\n input logic clk_i,\n input logic rst_ni,\n\n input logic [31:0] boot_addr_i, // also used for mtvec\n input logic req_i, // instruction request control\n\n // instruction cache interface\n output logic instr_req_o,\n output logic [31:0] instr_addr_o,\n input logic instr_gnt_i,\n input logic instr_rvalid_i,\n input logic [MemDataWidth-1:0] instr_rdata_i,\n input logic instr_bus_err_i,\n output logic instr_intg_err_o,\n\n // ICache RAM IO\n output logic [IC_NUM_WAYS-1:0] ic_tag_req_o,\n output logic ic_tag_write_o,\n output logic [IC_INDEX_W-1:0] ic_tag_addr_o,\n output logic [TagSizeECC-1:0] ic_tag_wdata_o,\n input logic [TagSizeECC-1:0] ic_tag_rdata_i [IC_NUM_WAYS],\n output logic [IC_NUM_WAYS-1:0] ic_data_req_o,\n output logic ic_data_write_o,\n output logic [IC_INDEX_W-1:0] ic_data_addr_o,\n output logic [LineSizeECC-1:0] ic_data_wdata_o,\n input logic [LineSizeECC-1:0] ic_data_rdata_i [IC_NUM_WAYS],\n input logic ic_scr_key_valid_i,\n output logic ic_scr_key_req_o,\n\n // output of ID stage\n output logic instr_valid_id_o, // instr in IF-ID is valid\n output logic instr_new_id_o, // instr in IF-ID is new\n output logic [31:0] instr_rdata_id_o, // instr for ID stage\n output logic [31:0] instr_rdata_alu_id_o, // replicated instr for ID stage\n // to reduce fan-out\n output logic [15:0] instr_rdata_c_id_o, // compressed instr for ID stage\n // (mtval), meaningful only if\n // instr_is_compressed_id_o = 1'b1\n output logic instr_is_compressed_id_o, // compressed decoder thinks this\n // is a compressed instr\n output logic instr_bp_taken_o, // instruction was predicted to be\n // a taken branch\n output logic instr_fetch_err_o, // bus error on fetch\n output logic instr_fetch_err_plus2_o, // bus error misaligned\n output logic illegal_c_insn_id_o, // compressed decoder thinks this\n // is an invalid instr\n output logic dummy_instr_id_o, // Instruction is a dummy\n output logic [31:0] pc_if_o,\n output logic [31:0] pc_id_o,\n input logic pmp_err_if_i,\n input logic pmp_err_if_plus2_i,\n\n // control signals\n input logic instr_valid_clear_i, // clear instr valid bit in IF-ID\n input logic pc_set_i, // set the PC to a new value\n input pc_sel_e pc_mux_i, // selector for PC multiplexer\n input logic nt_branch_mispredict_i, // Not-taken branch in ID/EX was\n // mispredicted (predicted taken)\n input logic [31:0] nt_branch_addr_i, // Not-taken branch address in ID/EX\n input exc_pc_sel_e exc_pc_mux_i, // selects ISR address\n input exc_cause_t exc_cause, // selects ISR address for\n // vectorized interrupt lines\n input logic dummy_instr_en_i,\n input logic [2:0] dummy_instr_mask_i,\n input logic dummy_instr_seed_en_i,\n input logic [31:0] dummy_instr_seed_i,\n input logic icache_enable_i,\n input logic icache_inval_i,\n output logic icache_ecc_error_o,\n\n // jump and branch target\n input logic [31:0] branch_target_ex_i, // branch/jump target address\n\n // CSRs\n input logic [31:0] csr_mepc_i, // PC to restore after handling\n // the interrupt/exception\n input logic [31:0] csr_depc_i, // PC to restore after handling\n // the debug request\n input logic [31:0] csr_mtvec_i, // base PC to jump to on exception\n output logic csr_mtvec_init_o, // tell CS regfile to init mtvec\n\n // pipeline stall\n input logic id_in_ready_i, // ID stage is ready for new instr\n\n // misc signals\n output logic pc_mismatch_alert_o,\n output logic if_busy_o // IF stage is busy fetching instr\n);\n\n logic instr_valid_id_d, instr_valid_id_q;\n logic instr_new_id_d, instr_new_id_q;\n\n logic instr_err, instr_intg_err;\n\n // prefetch buffer related signals\n logic prefetch_busy;\n logic branch_req;\n logic [31:0] fetch_addr_n;\n logic unused_fetch_addr_n0;\n\n logic prefetch_branch;\n logic [31:0] prefetch_addr;\n\n logic fetch_valid_raw;\n logic fetch_valid;\n logic fetch_ready;\n logic [31:0] fetch_rdata;\n logic [31:0] fetch_addr;\n logic fetch_err;\n logic fetch_err_plus2;\n\n logic [31:0] instr_decompressed;\n logic illegal_c_insn;\n logic instr_is_compressed;\n\n logic if_instr_valid;\n logic [31:0] if_instr_rdata;\n logic [31:0] if_instr_addr;\n logic if_instr_bus_err;\n logic if_instr_pmp_err;\n logic if_instr_err;\n logic if_instr_err_plus2;\n\n logic [31:0] exc_pc;\n\n logic if_id_pipe_reg_we; // IF-ID pipeline reg write enable\n\n // Dummy instruction signals\n logic stall_dummy_instr;\n logic [31:0] instr_out;\n logic instr_is_compressed_out;\n logic illegal_c_instr_out;\n logic instr_err_out;\n\n logic predict_branch_taken;\n logic [31:0] predict_branch_pc;\n\n logic [4:0] irq_vec;\n\n ibex_pkg::pc_sel_e pc_mux_internal;\n\n logic [7:0] unused_boot_addr;\n logic [7:0] unused_csr_mtvec;\n logic unused_exc_cause;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n assign unused_csr_mtvec = csr_mtvec_i[7:0];\n\n assign unused_exc_cause = |{exc_cause.irq_ext, exc_cause.irq_int};\n\n // exception PC selection mux\n always_comb begin : exc_pc_mux\n irq_vec = exc_cause.lower_cause;\n\n if (exc_cause.irq_int) begin\n // All internal interrupts go to the NMI vector\n irq_vec = ExcCauseIrqNm.lower_cause;\n end\n\n unique case (exc_pc_mux_i)\n EXC_PC_EXC: exc_pc = { csr_mtvec_i[31:8], 8'h00 };\n EXC_PC_IRQ: exc_pc = { csr_mtvec_i[31:8], 1'b0, irq_vec, 2'b00 };\n EXC_PC_DBD: exc_pc = DmHaltAddr;\n EXC_PC_DBG_EXC: exc_pc = DmExceptionAddr;\n default: exc_pc = { csr_mtvec_i[31:8], 8'h00 };\n endcase\n end\n\n // The Branch predictor can provide a new PC which is internal to if_stage. Only override the mux\n // select to choose this if the core isn't already trying to set a PC.\n assign pc_mux_internal =\n (BranchPredictor && predict_branch_taken && !pc_set_i) ? PC_BP : pc_mux_i;\n\n // fetch address selection mux\n always_comb begin : fetch_addr_mux\n unique case (pc_mux_internal)\n PC_BOOT: fetch_addr_n = { boot_addr_i[31:8], 8'h80 };\n PC_JUMP: fetch_addr_n = branch_target_ex_i;\n PC_EXC: fetch_addr_n = exc_pc; // set PC to exception handler\n PC_ERET: fetch_addr_n = csr_mepc_i; // restore PC when returning from EXC\n PC_DRET: fetch_addr_n = csr_depc_i;\n // Without branch predictor will never get pc_mux_internal == PC_BP. We still handle no branch\n // predictor case here to ensure redundant mux logic isn't synthesised.\n PC_BP: fetch_addr_n = BranchPredictor ? predict_branch_pc : { boot_addr_i[31:8], 8'h80 };\n default: fetch_addr_n = { boot_addr_i[31:8], 8'h80 };\n endcase\n end\n\n // tell CS register file to initialize mtvec on boot\n assign csr_mtvec_init_o = (pc_mux_i == PC_BOOT) & pc_set_i;\n\n // SEC_CM: BUS.INTEGRITY\n if (MemECC) begin : g_mem_ecc\n logic [1:0] ecc_err;\n logic [MemDataWidth-1:0] instr_rdata_buf;\n\n prim_buf #(.Width(MemDataWidth)) u_prim_buf_instr_rdata (\n .in_i (instr_rdata_i),\n .out_o(instr_rdata_buf)\n );\n\n prim_secded_inv_39_32_dec u_instr_intg_dec (\n .data_i (instr_rdata_buf),\n .data_o (),\n .syndrome_o (),\n .err_o (ecc_err)\n );\n\n // Don't care if error is correctable or not, they're all treated the same\n assign instr_intg_err = |ecc_err;\n end else begin : g_no_mem_ecc\n assign instr_intg_err = 1'b0;\n end\n\n assign instr_err = instr_intg_err | instr_bus_err_i;\n assign instr_intg_err_o = instr_intg_err & instr_rvalid_i;\n\n // There are two possible \"branch please\" signals that are computed in the IF stage: branch_req\n // and nt_branch_mispredict_i. These should be mutually exclusive (see the NoMispredBranch\n // assertion), so we can just OR the signals together.\n assign prefetch_branch = branch_req | nt_branch_mispredict_i;\n assign prefetch_addr = branch_req ? {fetch_addr_n[31:1], 1'b0} : nt_branch_addr_i;\n\n // The fetch_valid signal that comes out of the icache or prefetch buffer should be squashed if we\n // had a misprediction.\n assign fetch_valid = fetch_valid_raw & ~nt_branch_mispredict_i;\n\n // We should never see a mispredict and an incoming branch on the same cycle. The mispredict also\n // cancels any predicted branch so overall branch_req must be low.\n `ASSERT(NoMispredBranch, nt_branch_mispredict_i |-> ~branch_req)\n\n if (ICache) begin : gen_icache\n // Full I-Cache option\n ibex_icache #(\n .ICacheECC (ICacheECC),\n .ResetAll (ResetAll),\n .BusSizeECC (BusSizeECC),\n .TagSizeECC (TagSizeECC),\n .LineSizeECC (LineSizeECC)\n ) icache_i (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n .req_i ( req_i ),\n\n .branch_i ( prefetch_branch ),\n .addr_i ( prefetch_addr ),\n\n .ready_i ( fetch_ready ),\n .valid_o ( fetch_valid_raw ),\n .rdata_o ( fetch_rdata ),\n .addr_o ( fetch_addr ),\n .err_o ( fetch_err ),\n .err_plus2_o ( fetch_err_plus2 ),\n\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[31:0] ),\n .instr_err_i ( instr_err ),\n\n .ic_tag_req_o ( ic_tag_req_o ),\n .ic_tag_write_o ( ic_tag_write_o ),\n .ic_tag_addr_o ( ic_tag_addr_o ),\n .ic_tag_wdata_o ( ic_tag_wdata_o ),\n .ic_tag_rdata_i ( ic_tag_rdata_i ),\n .ic_data_req_o ( ic_data_req_o ),\n .ic_data_write_o ( ic_data_write_o ),\n .ic_data_addr_o ( ic_data_addr_o ),\n .ic_data_wdata_o ( ic_data_wdata_o ),\n .ic_data_rdata_i ( ic_data_rdata_i ),\n .ic_scr_key_valid_i ( ic_scr_key_valid_i ),\n .ic_scr_key_req_o ( ic_scr_key_req_o ),\n\n .icache_enable_i ( icache_enable_i ),\n .icache_inval_i ( icache_inval_i ),\n .busy_o ( prefetch_busy ),\n .ecc_error_o ( icache_ecc_error_o )\n );\n end else begin : gen_prefetch_buffer\n // prefetch buffer, caches a fixed number of instructions\n ibex_prefetch_buffer #(\n .ResetAll (ResetAll)\n ) prefetch_buffer_i (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n .req_i ( req_i ),\n\n .branch_i ( prefetch_branch ),\n .addr_i ( prefetch_addr ),\n\n .ready_i ( fetch_ready ),\n .valid_o ( fetch_valid_raw ),\n .rdata_o ( fetch_rdata ),\n .addr_o ( fetch_addr ),\n .err_o ( fetch_err ),\n .err_plus2_o ( fetch_err_plus2 ),\n\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[31:0] ),\n .instr_err_i ( instr_err ),\n\n .busy_o ( prefetch_busy )\n );\n // ICache tieoffs\n logic unused_icen, unused_icinv, unused_scr_key_valid;\n logic [TagSizeECC-1:0] unused_tag_ram_input [IC_NUM_WAYS];\n logic [LineSizeECC-1:0] unused_data_ram_input [IC_NUM_WAYS];\n assign unused_icen = icache_enable_i;\n assign unused_icinv = icache_inval_i;\n assign unused_tag_ram_input = ic_tag_rdata_i;\n assign unused_data_ram_input = ic_data_rdata_i;\n assign unused_scr_key_valid = ic_scr_key_valid_i;\n assign ic_tag_req_o = 'b0;\n assign ic_tag_write_o = 'b0;\n assign ic_tag_addr_o = 'b0;\n assign ic_tag_wdata_o = 'b0;\n assign ic_data_req_o = 'b0;\n assign ic_data_write_o = 'b0;\n assign ic_data_addr_o = 'b0;\n assign ic_data_wdata_o = 'b0;\n assign ic_scr_key_req_o = 'b0;\n assign icache_ecc_error_o = 'b0;\n\n`ifndef SYNTHESIS\n // If we don't instantiate an icache and this is a simulation then we have a problem because the\n // simulator might discard the icache module entirely, including some DPI exports that it\n // implies. This then causes problems for linking against C++ testbench code that expected them.\n // As a slightly ugly hack, let's define the DPI functions here (the real versions are defined\n // in prim_util_get_scramble_params.svh)\n export \"DPI-C\" function simutil_get_scramble_key;\n export \"DPI-C\" function simutil_get_scramble_nonce;\n function automatic int simutil_get_scramble_key(output bit [127:0] val);\n return 0;\n endfunction\n function automatic int simutil_get_scramble_nonce(output bit [319:0] nonce);\n return 0;\n endfunction\n`endif\n end\n\n assign unused_fetch_addr_n0 = fetch_addr_n[0];\n\n assign branch_req = pc_set_i | predict_branch_taken;\n\n assign pc_if_o = if_instr_addr;\n assign if_busy_o = prefetch_busy;\n\n // PMP errors\n // An error can come from the instruction address, or the next instruction address for unaligned,\n // uncompressed instructions.\n assign if_instr_pmp_err = pmp_err_if_i |\n (if_instr_addr[1] & ~instr_is_compressed & pmp_err_if_plus2_i);\n\n // Combine bus errors and pmp errors\n assign if_instr_err = if_instr_bus_err | if_instr_pmp_err;\n\n // Capture the second half of the address for errors on the second part of an instruction\n assign if_instr_err_plus2 = ((if_instr_addr[1] & ~instr_is_compressed & pmp_err_if_plus2_i) |\n fetch_err_plus2) & ~pmp_err_if_i;\n\n // compressed instruction decoding, or more precisely compressed instruction\n // expander\n //\n // since it does not matter where we decompress instructions, we do it here\n // to ease timing closure\n ibex_compressed_decoder compressed_decoder_i (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .valid_i (fetch_valid & ~fetch_err),\n .instr_i (if_instr_rdata),\n .instr_o (instr_decompressed),\n .is_compressed_o(instr_is_compressed),\n .illegal_instr_o(illegal_c_insn)\n );\n\n // Dummy instruction insertion\n if (DummyInstructions) begin : gen_dummy_instr\n // SEC_CM: CTRL_FLOW.UNPREDICTABLE\n logic insert_dummy_instr;\n logic [31:0] dummy_instr_data;\n\n ibex_dummy_instr #(\n .RndCnstLfsrSeed (RndCnstLfsrSeed),\n .RndCnstLfsrPerm (RndCnstLfsrPerm)\n ) dummy_instr_i (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .dummy_instr_en_i (dummy_instr_en_i),\n .dummy_instr_mask_i (dummy_instr_mask_i),\n .dummy_instr_seed_en_i(dummy_instr_seed_en_i),\n .dummy_instr_seed_i (dummy_instr_seed_i),\n .fetch_valid_i (fetch_valid),\n .id_in_ready_i (id_in_ready_i),\n .insert_dummy_instr_o (insert_dummy_instr),\n .dummy_instr_data_o (dummy_instr_data)\n );\n\n // Mux between actual instructions and dummy instructions\n assign instr_out = insert_dummy_instr ? dummy_instr_data : instr_decompressed;\n assign instr_is_compressed_out = insert_dummy_instr ? 1'b0 : instr_is_compressed;\n assign illegal_c_instr_out = insert_dummy_instr ? 1'b0 : illegal_c_insn;\n assign instr_err_out = insert_dummy_instr ? 1'b0 : if_instr_err;\n\n // Stall the IF stage if we insert a dummy instruction. The dummy will execute between whatever\n // is currently in the ID stage and whatever is valid from the prefetch buffer this cycle. The\n // PC of the dummy instruction will match whatever is next from the prefetch buffer.\n assign stall_dummy_instr = insert_dummy_instr;\n\n // Register the dummy instruction indication into the ID stage\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n dummy_instr_id_o <= 1'b0;\n end else if (if_id_pipe_reg_we) begin\n dummy_instr_id_o <= insert_dummy_instr;\n end\n end\n\n end else begin : gen_no_dummy_instr\n logic unused_dummy_en;\n logic [2:0] unused_dummy_mask;\n logic unused_dummy_seed_en;\n logic [31:0] unused_dummy_seed;\n\n assign unused_dummy_en = dummy_instr_en_i;\n assign unused_dummy_mask = dummy_instr_mask_i;\n assign unused_dummy_seed_en = dummy_instr_seed_en_i;\n assign unused_dummy_seed = dummy_instr_seed_i;\n assign instr_out = instr_decompressed;\n assign instr_is_compressed_out = instr_is_compressed;\n assign illegal_c_instr_out = illegal_c_insn;\n assign instr_err_out = if_instr_err;\n assign stall_dummy_instr = 1'b0;\n assign dummy_instr_id_o = 1'b0;\n end\n\n // The ID stage becomes valid as soon as any instruction is registered in the ID stage flops.\n // Note that the current instruction is squashed by the incoming pc_set_i signal.\n // Valid is held until it is explicitly cleared (due to an instruction completing or an exception)\n assign instr_valid_id_d = (if_instr_valid & id_in_ready_i & ~pc_set_i) |\n (instr_valid_id_q & ~instr_valid_clear_i);\n assign instr_new_id_d = if_instr_valid & id_in_ready_i;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_valid_id_q <= 1'b0;\n instr_new_id_q <= 1'b0;\n end else begin\n instr_valid_id_q <= instr_valid_id_d;\n instr_new_id_q <= instr_new_id_d;\n end\n end\n\n assign instr_valid_id_o = instr_valid_id_q;\n // Signal when a new instruction enters the ID stage (only used for RVFI signalling).\n assign instr_new_id_o = instr_new_id_q;\n\n // IF-ID pipeline registers, frozen when the ID stage is stalled\n assign if_id_pipe_reg_we = instr_new_id_d;\n\n if (ResetAll) begin : g_instr_rdata_ra\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_rdata_id_o <= '0;\n instr_rdata_alu_id_o <= '0;\n instr_fetch_err_o <= '0;\n instr_fetch_err_plus2_o <= '0;\n instr_rdata_c_id_o <= '0;\n instr_is_compressed_id_o <= '0;\n illegal_c_insn_id_o <= '0;\n pc_id_o <= '0;\n end else if (if_id_pipe_reg_we) begin\n instr_rdata_id_o <= instr_out;\n // To reduce fan-out and help timing from the instr_rdata_id flops they are replicated.\n instr_rdata_alu_id_o <= instr_out;\n instr_fetch_err_o <= instr_err_out;\n instr_fetch_err_plus2_o <= if_instr_err_plus2;\n instr_rdata_c_id_o <= if_instr_rdata[15:0];\n instr_is_compressed_id_o <= instr_is_compressed_out;\n illegal_c_insn_id_o <= illegal_c_instr_out;\n pc_id_o <= pc_if_o;\n end\n end\n end else begin : g_instr_rdata_nr\n always_ff @(posedge clk_i) begin\n if (if_id_pipe_reg_we) begin\n instr_rdata_id_o <= instr_out;\n // To reduce fan-out and help timing from the instr_rdata_id flops they are replicated.\n instr_rdata_alu_id_o <= instr_out;\n instr_fetch_err_o <= instr_err_out;\n instr_fetch_err_plus2_o <= if_instr_err_plus2;\n instr_rdata_c_id_o <= if_instr_rdata[15:0];\n instr_is_compressed_id_o <= instr_is_compressed_out;\n illegal_c_insn_id_o <= illegal_c_instr_out;\n pc_id_o <= pc_if_o;\n end\n end\n end\n\n // Check for expected increments of the PC when security hardening enabled\n if (PCIncrCheck) begin : g_secure_pc\n // SEC_CM: PC.CTRL_FLOW.CONSISTENCY\n logic [31:0] prev_instr_addr_incr, prev_instr_addr_incr_buf;\n logic prev_instr_seq_q, prev_instr_seq_d;\n\n // Do not check for sequential increase after a branch, jump, exception, interrupt or debug\n // request, all of which will set branch_req. Also do not check after reset or for dummys.\n assign prev_instr_seq_d = (prev_instr_seq_q | instr_new_id_d) &\n ~branch_req & ~if_instr_err & ~stall_dummy_instr;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n prev_instr_seq_q <= 1'b0;\n end else begin\n prev_instr_seq_q <= prev_instr_seq_d;\n end\n end\n\n assign prev_instr_addr_incr = pc_id_o + (instr_is_compressed_id_o ? 32'd2 : 32'd4);\n\n // Buffer anticipated next PC address to ensure optimiser cannot remove the check.\n prim_buf #(.Width(32)) u_prev_instr_addr_incr_buf (\n .in_i (prev_instr_addr_incr),\n .out_o(prev_instr_addr_incr_buf)\n );\n\n // Check that the address equals the previous address +2/+4\n assign pc_mismatch_alert_o = prev_instr_seq_q & (pc_if_o != prev_instr_addr_incr_buf);\n\n end else begin : g_no_secure_pc\n assign pc_mismatch_alert_o = 1'b0;\n end\n\n if (BranchPredictor) begin : g_branch_predictor\n logic [31:0] instr_skid_data_q;\n logic [31:0] instr_skid_addr_q;\n logic instr_skid_bp_taken_q;\n logic instr_skid_valid_q, instr_skid_valid_d;\n logic instr_skid_en;\n logic instr_bp_taken_q, instr_bp_taken_d;\n\n logic predict_branch_taken_raw;\n\n // ID stages needs to know if branch was predicted taken so it can signal mispredicts\n if (ResetAll) begin : g_bp_taken_ra\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_bp_taken_q <= '0;\n end else if (if_id_pipe_reg_we) begin\n instr_bp_taken_q <= instr_bp_taken_d;\n end\n end\n end else begin : g_bp_taken_nr\n always_ff @(posedge clk_i) begin\n if (if_id_pipe_reg_we) begin\n instr_bp_taken_q <= instr_bp_taken_d;\n end\n end\n end\n\n // When branch prediction is enabled a skid buffer between the IF and ID/EX stage is introduced.\n // If an instruction in IF is predicted to be a taken branch and ID/EX is not ready the\n // instruction in IF is moved to the skid buffer which becomes the output of the IF stage until\n // the ID/EX stage accepts the instruction. The skid buffer is required as otherwise the ID/EX\n // ready signal is coupled to the instr_req_o output which produces a feedthrough path from\n // data_gnt_i -> instr_req_o (which needs to be avoided as for some interconnects this will\n // result in a combinational loop).\n\n assign instr_skid_en = predict_branch_taken & ~pc_set_i & ~id_in_ready_i & ~instr_skid_valid_q;\n\n assign instr_skid_valid_d = (instr_skid_valid_q & ~id_in_ready_i & ~stall_dummy_instr) |\n instr_skid_en;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_skid_valid_q <= 1'b0;\n end else begin\n instr_skid_valid_q <= instr_skid_valid_d;\n end\n end\n\n if (ResetAll) begin : g_instr_skid_ra\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_skid_bp_taken_q <= '0;\n instr_skid_data_q <= '0;\n instr_skid_addr_q <= '0;\n end else if (instr_skid_en) begin\n instr_skid_bp_taken_q <= predict_branch_taken;\n instr_skid_data_q <= fetch_rdata;\n instr_skid_addr_q <= fetch_addr;\n end\n end\n end else begin : g_instr_skid_nr\n always_ff @(posedge clk_i) begin\n if (instr_skid_en) begin\n instr_skid_bp_taken_q <= predict_branch_taken;\n instr_skid_data_q <= fetch_rdata;\n instr_skid_addr_q <= fetch_addr;\n end\n end\n end\n\n ibex_branch_predict branch_predict_i (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .fetch_rdata_i(fetch_rdata),\n .fetch_pc_i (fetch_addr),\n .fetch_valid_i(fetch_valid),\n\n .predict_branch_taken_o(predict_branch_taken_raw),\n .predict_branch_pc_o (predict_branch_pc)\n );\n\n // If there is an instruction in the skid buffer there must be no branch prediction.\n // Instructions are only placed in the skid after they have been predicted to be a taken branch\n // so with the skid valid any prediction has already occurred.\n // Do not branch predict on instruction errors.\n assign predict_branch_taken = predict_branch_taken_raw & ~instr_skid_valid_q & ~fetch_err;\n\n assign if_instr_valid = fetch_valid | (instr_skid_valid_q & ~nt_branch_mispredict_i);\n assign if_instr_rdata = instr_skid_valid_q ? instr_skid_data_q : fetch_rdata;\n assign if_instr_addr = instr_skid_valid_q ? instr_skid_addr_q : fetch_addr;\n\n // Don't branch predict on instruction error so only instructions without errors end up in the\n // skid buffer.\n assign if_instr_bus_err = ~instr_skid_valid_q & fetch_err;\n assign instr_bp_taken_d = instr_skid_valid_q ? instr_skid_bp_taken_q : predict_branch_taken;\n\n assign fetch_ready = id_in_ready_i & ~stall_dummy_instr & ~instr_skid_valid_q;\n\n assign instr_bp_taken_o = instr_bp_taken_q;\n\n `ASSERT(NoPredictSkid, instr_skid_valid_q |-> ~predict_branch_taken)\n `ASSERT(NoPredictIllegal, predict_branch_taken |-> ~illegal_c_insn)\n end else begin : g_no_branch_predictor\n assign instr_bp_taken_o = 1'b0;\n assign predict_branch_taken = 1'b0;\n assign predict_branch_pc = 32'b0;\n\n assign if_instr_valid = fetch_valid;\n assign if_instr_rdata = fetch_rdata;\n assign if_instr_addr = fetch_addr;\n assign if_instr_bus_err = fetch_err;\n assign fetch_ready = id_in_ready_i & ~stall_dummy_instr;\n end\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT_KNOWN(IbexExcPcMuxKnown, exc_pc_mux_i)\n\n if (BranchPredictor) begin : g_branch_predictor_asserts\n `ASSERT_IF(IbexPcMuxValid, pc_mux_internal inside {\n PC_BOOT,\n PC_JUMP,\n PC_EXC,\n PC_ERET,\n PC_DRET,\n PC_BP},\n pc_set_i)\n\n`ifdef INC_ASSERT\n /**\n * Checks for branch prediction interface to fetch_fifo/icache\n *\n * The interface has two signals:\n * - predicted_branch_i: When set with a branch (branch_i) indicates the branch is a predicted\n * one, it should be ignored when a branch_i isn't set.\n * - branch_mispredict_i: Indicates the previously predicted branch was mis-predicted and\n * execution should resume with the not-taken side of the branch (i.e. continue with the PC\n * that followed the predicted branch). This must be raised before the instruction that is\n * made available following a predicted branch is accepted (Following a cycle with branch_i\n * & predicted_branch_i, branch_mispredict_i can only be asserted before or on the same cycle\n * as seeing fetch_valid & fetch_ready). When branch_mispredict_i is asserted, fetch_valid may\n * be asserted in response. If fetch_valid is asserted on the same cycle as\n * branch_mispredict_i this indicates the fetch_fifo/icache has the not-taken side of the\n * branch immediately ready for use\n */\n logic predicted_branch_live_q, predicted_branch_live_d;\n logic [31:0] predicted_branch_nt_pc_q, predicted_branch_nt_pc_d;\n logic [31:0] awaiting_instr_after_mispredict_q, awaiting_instr_after_mispredict_d;\n logic [31:0] next_pc;\n\n logic mispredicted, mispredicted_d, mispredicted_q;\n\n assign next_pc = fetch_addr + (instr_is_compressed_out ? 32'd2 : 32'd4);\n\n logic predicted_branch;\n\n // pc_set_i takes precendence over branch prediction\n assign predicted_branch = predict_branch_taken & ~pc_set_i;\n\n always_comb begin\n predicted_branch_live_d = predicted_branch_live_q;\n mispredicted_d = mispredicted_q;\n\n if (branch_req & predicted_branch) begin\n predicted_branch_live_d = 1'b1;\n mispredicted_d = 1'b0;\n end else if (predicted_branch_live_q) begin\n if (fetch_valid & fetch_ready) begin\n predicted_branch_live_d = 1'b0;\n end else if (nt_branch_mispredict_i) begin\n mispredicted_d = 1'b1;\n end\n end\n end\n\n always @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n predicted_branch_live_q <= 1'b0;\n mispredicted_q <= 1'b0;\n end else begin\n predicted_branch_live_q <= predicted_branch_live_d;\n mispredicted_q <= mispredicted_d;\n end\n end\n\n always @(posedge clk_i) begin\n if (branch_req & predicted_branch) begin\n predicted_branch_nt_pc_q <= next_pc;\n end\n end\n\n // Must only see mispredict after we've performed a predicted branch but before we've accepted\n // any instruction (with fetch_ready & fetch_valid) that follows that predicted branch.\n `ASSERT(MispredictOnlyImmediatelyAfterPredictedBranch,\n nt_branch_mispredict_i |-> predicted_branch_live_q)\n // Check that on mispredict we get the correct PC for the non-taken side of the branch when\n // prefetch buffer/icache makes that PC available.\n `ASSERT(CorrectPCOnMispredict,\n predicted_branch_live_q & mispredicted_d & fetch_valid |->\n fetch_addr == predicted_branch_nt_pc_q)\n // Must not signal mispredict over multiple cycles but it's possible to have back to back\n // mispredicts for different branches (core signals mispredict, prefetch buffer/icache immediate\n // has not-taken side of the mispredicted branch ready, which itself is a predicted branch,\n // following cycle core signal that that branch has mispredicted).\n `ASSERT(MispredictSingleCycle,\n nt_branch_mispredict_i & ~(fetch_valid & fetch_ready) |=> ~nt_branch_mispredict_i)\n`endif\n\n end else begin : g_no_branch_predictor_asserts\n `ASSERT_IF(IbexPcMuxValid, pc_mux_internal inside {\n PC_BOOT,\n PC_JUMP,\n PC_EXC,\n PC_ERET,\n PC_DRET},\n pc_set_i)\n end\n\n // Boot address must be aligned to 256 bytes.\n `ASSERT(IbexBootAddrUnaligned, boot_addr_i[7:0] == 8'h00)\n\n // Address must not contain X when request is sent.\n `ASSERT(IbexInstrAddrUnknown, instr_req_o |-> !$isunknown(instr_addr_o))\n\n // Address must be word aligned when request is sent.\n `ASSERT(IbexInstrAddrUnaligned, instr_req_o |-> (instr_addr_o[1:0] == 2'b00))\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/instruction_fetch.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/icache.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1744, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# Behavioral Design Specification for ibex_controller\n\n## Overview\n\nThe **ibex_controller** is the central control unit of the Ibex processor. It governs the instruction execution pipeline, determines the processor’s response to exceptions, interrupts, debug requests, and special instructions, and manages the program counter (PC) flow. The controller interacts with the instruction fetch stage, the decode/execute stage, and the writeback stage (if present) to coordinate the correct architectural state transitions as defined by the RISC-V Privileged Specification (v1.11) and the RISC-V Debug Specification (v0.13.2).\n\n## Functional Behavior\n\n### 1. Reset and Initialization\n\n- Upon reset, the controller must initialize the processor to fetch from the boot address. It asserts a PC update to the boot address and then transitions to the first instruction fetch cycle.\n- After booting, the processor continues normal instruction fetching until a condition (exception, interrupt, debug, or special instruction) requires a change of flow.\n\n### 2. Normal Instruction Execution Flow\n\n- The controller manages two pipeline stages: instruction fetch (IF) and instruction decode/execute (ID/EX). An optional third writeback stage may be present.\n- In the normal decode state, the controller:\n - Allows new instructions to enter the ID/EX stage unless stalled.\n - Monitors for branch and jump instructions; upon their completion, it updates the PC to the target address (if taken).\n - Handles branch prediction: if the branch predictor has already set the PC to a taken target, the controller avoids redundant PC updates; otherwise, it sets the PC.\n - For branches predicted taken but not actually taken, it signals a misprediction and initiates a pipeline flush.\n\n### 3. Pipeline Stall, Halt, and Flush\n\n- The controller must stall the ID/EX stage when:\n - A multi-cycle instruction (e.g., load, store, multiplication) is still completing.\n - The writeback stage cannot accept a new result (when the writeback stage is present).\n- The controller can halt the instruction fetch:\n - When a special instruction, exception, or interrupt is pending and the ID/EX stage is not yet ready.\n - During sleep (WFI) while waiting for an interrupt or debug event.\n- The controller flushes the ID/EX pipeline stage:\n - When an exception or interrupt is taken.\n - When a jump or taken branch changes the PC.\n - When a CSR pipeline flush is required.\n - When a mispredicted branch is corrected.\n- Flushing invalidates the current instruction in the ID/EX stage and forces the core to refetch from the new PC.\n\n### 4. Exception Handling\n\nThe controller must detect and prioritize exceptions according to the RISC-V Privileged Specification (Table 3.7). The following exceptions are supported:\n\n- **Instruction access fault** (during instruction fetch)\n- **Illegal instruction**\n- **Breakpoint** (EBREAK)\n- **Load access fault** (when Writeback stage present, this comes from the writeback stage; without Writeback, from ID/EX)\n- **Store access fault** (same as load)\n- **Environment call from M-mode or U-mode** (ECALL)\n\n**Prioritization (highest to lowest):**\n\n1. Store access fault (if writeback stage present)\n2. Load access fault (if writeback stage present)\n3. Instruction access fault\n4. Illegal instruction\n5. ECALL\n6. EBREAK\n7. (Without writeback stage, load/store faults have lower priority than EBREAK)\n\n- Only one exception is taken; the controller must save the appropriate architectural state (`mepc`, `mcause`, `mtval`, `mstatus.MPIE`, `mstatus.MPP`) and redirect the PC to the exception vector (base address in `mtvec`).\n- For breakpoints (EBREAK), if the core is already in debug mode or if the `dcsr.ebreakm`/`ebreaku` bit is set, the controller must enter debug mode instead of taking an exception (see Debug section).\n- The controller asserts a signal indicating that the instruction in the ID/EX stage is taking an exception (used for CSR save in that stage).\n- When the writeback stage is present, the instruction in writeback may also cause an exception; the controller must prevent the ID/EX instruction from executing if the writeback instruction is taking an exception.\n\n### 5. Interrupt Handling\n\n- The controller supports the following interrupts:\n - Non-maskable interrupt (NMI) – highest priority.\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- Interrupt handling is only enabled when:\n - The core is not in debug mode.\n - The core is not already in NMI mode.\n - Global interrupt enable (`mstatus.MIE`) is set and the corresponding interrupt is enabled in `mie` CSR.\n- NMI is always enabled, ignoring `mie` and `mstatus.MIE`.\n- Internal interrupts (e.g., from load integrity errors) generate an NMI with a specific cause code.\n- Upon taking an interrupt, the controller:\n - Saves the PC (`mepc`), cause (`mcause`), and the previous interrupt enable state (`mstatus`).\n - For NMI, enters NMI mode (which blocks further interrupts until MRET).\n - Sets the PC to the vector table base address plus four times the interrupt ID (vectored mode). For NMI, the offset is 0x7C (ID 31).\n - Does not flush the ID/EX stage if there is an outstanding instruction that needs to complete (e.g., a pending load/store).\n- Interrupts are only taken after the current instruction completes; if a special instruction (e.g., MRET, DRET, WFI) or exception is pending, the interrupt is deferred until the FLUSH state handling.\n\n### 6. Debug Support\n\nThe controller implements debug mode entry as specified by the RISC-V Debug Specification v0.13.2.\n\n**Debug entry sources (in priority order):**\n\n- **EBREAK instruction** (if it causes debug entry – see below)\n- **External debug request** (`debug_req_i`)\n- **Single-step** (when `dcsr.step` is set)\n- **Trigger match** (hardware breakpoint)\n\n**Behavior:**\n\n- Debug mode can be entered from any state except when the controller is already in debug mode.\n- **EBREAK**: If the core is already in debug mode, EBREAK re-enters debug mode without updating `dpc` or `dcsr`. If the core is not in debug mode, EBREAK causes a breakpoint exception unless `dcsr.ebreakm` (M-mode) or `dcsr.ebreaku` (U-mode) is set, in which case it enters debug mode and saves the PC to `dpc`.\n- **External debug request**: The controller must enter debug mode as soon as the current instruction (if any) completes. It saves the next PC to `dpc` and causes a debug entry via the `DBG_TAKEN_IF` state.\n- **Single-step**: After executing a single instruction (outside debug mode), the controller immediately enters debug mode (via `DBG_TAKEN_IF`). Single-step is only active when `dcsr.step=1` and the core is not in debug mode.\n- **Trigger match**: On a match, the controller enters debug mode before executing the matched instruction (via `DBG_TAKEN_IF`). If the controller is already processing a flush for another reason (exception or interrupt), the trigger match is ignored.\n- When entering debug mode, the controller must save the PC (from the appropriate stage) to `dpc` and set `dcsr.cause` accordingly. It also flushes the ID/EX stage and jumps to the debug entry address (`DmHaltAddr`).\n- While in debug mode, all interrupts (including NMI) are ignored.\n\n### 7. Special Instructions\n\nThe controller handles the following special instructions:\n\n- **MRET**: Returns from M-mode exception handling. Restores `mepc` to PC, restores `mstatus` from the saved state, and exits NMI mode if active.\n- **DRET**: Returns from debug mode. Restores `dpc` to PC, clears debug mode.\n- **WFI**: Waits for interrupt. The controller enters a sleep state where no instructions are fetched and the pipeline is flushed. The core wakes when any interrupt (including NMI) is pending, or when a debug request or single-step condition is present. If the core is already in debug mode or single-step is active, WFI behaves as a NOP and returns immediately to fetch.\n- **CSR pipeline flush**: Triggered by certain CSR writes (e.g., `mtvec` change). This flushes the ID/EX stage and may also cause an immediate interrupt entry if an interrupt is pending.\n\n### 8. NMI Mode\n\n- When an NMI is taken, the controller enters NMI mode. While in NMI mode, all interrupts (including further NMIs) are ignored.\n- NMI mode is cleared when the controller executes an `MRET` instruction.\n- The controller supports internal interrupts (e.g., load integrity error) that use the NMI vector. These are treated as NMIs and also set NMI mode.\n\n### 9. Performance Monitoring\n\nThe controller must generate pulse signals indicating:\n\n- A taken branch instruction (for counting taken branches).\n- A jump instruction (for counting jumps).\n\nThese pulses are output for performance counters.\n\n### 10. Busy Indication\n\nThe controller asserts a busy signal whenever the core is actively processing instructions. This signal is de-asserted only in the sleep state (WFI) when waiting for an interrupt.\n\n## Interface Overview (Conceptual)\n\n- **Clock and reset**: Synchronous logic with active-low reset.\n- **To/from decoder**: Receives decoded instruction types (ECALL, MRET, etc.), illegal instruction, and compressed instruction information. Provides instruction valid clear and ready signals.\n- **To prefetcher**: Controls instruction fetch requests and PC updates (set, mux selection).\n- **To/from LSU**: Receives load/store error signals; provides exception indication for writeback stage.\n- **To/from CSRs**: Receives interrupt enables and pending status, privilege level, and debug configuration. Provides save/restore requests and cause/value registers.\n- **To/from debug**: Receives debug request, single-step, trigger match; outputs debug mode, cause, and save signals.\n- **Stall and flush**: Receives stall signals from ID/EX and writeback; generates flush signal to ID/EX.\n- **Performance counters**: Outputs jump and taken branch pulses.\n\n## State Machine Summary\n\nThe controller implements a finite state machine with the following states:\n\n- **RESET**: Initialization, sets PC to boot address.\n- **BOOT_SET**: Issues first fetch from boot address.\n- **FIRST_FETCH**: Waits for first instruction to be ready, then transitions to DECODE. May take interrupts or debug entries.\n- **DECODE**: Normal operation; handles branches, jumps, exceptions, interrupts, debug. May transition to FLUSH, IRQ_TAKEN, DBG_TAKEN_IF.\n- **FLUSH**: Pipeline flush; determines whether to handle an exception, special instruction, or debug entry.\n- **IRQ_TAKEN**: Handles interrupt; saves state, sets PC to vector.\n- **DBG_TAKEN_IF**: Handles debug entry from IF stage (external request, single-step, trigger). Saves PC from IF, sets PC to debug vector.\n- **DBG_TAKEN_ID**: Handles debug re-entry from ID stage (EBREAK in debug mode or ebreak into debug). Saves PC from ID.\n- **WAIT_SLEEP**: Prepares to enter sleep (WFI).\n- **SLEEP**: Idle; wakes on interrupts, debug requests, or single-step.\n\n## Key Behavioral Rules\n\n- The controller must never fetch a new instruction while a previous instruction is pending in the writeback stage that may take an exception.\n- The controller must ensure that only one exception or interrupt is handled at a time; nested interrupts are supported only via software enabling (hardware does not support hardware nesting).\n- The controller must enforce the priority order described for exceptions and interrupts.\n- When multiple sources of debug entry are active, the controller must select the correct cause code according to the debug specification priority.\n- The controller must not flush the instruction currently being executed if it is a load/store that has not yet completed; it must wait for completion before handling an interrupt or debug request.\n\nThis specification describes the required external behavior of the ibex_controller module. Any implementation that satisfies these functional requirements is acceptable.", "commit_id": "c4a97e05f5853b25e40fa1ea5b4edcfafba9a370", "timestamp": "2022-08-05T11:03:36+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "23806e2ad7d0d6fab429ae227d9a45cbd42f0fb3", "pr_title": "Fix incorrect debug_cause priority against riscv-debug 1.0.0-STABLE", "pr_body": "The relevant page [Debug Spec v1.0.0-STABLE, p.53] gives the following\r\npriorities for resolving multiple concurrent reasons for entering debug mode....\r\n\r\n> DCSR.cause : Explains why Debug Mode was entered.\r\n> \r\n> When there are multiple reasons to enter Debug Mode in a single cycle,\r\n> hardware should set cause to the cause with the highest priority.\r\n> 1: An ebreak instruction was executed. (priority 3)\r\n> 2: A Trigger Module trigger fired with action=1. (priority 4)\r\n> 3: The debugger requested entry to Debug Mode using haltreq. (priority 1)\r\n> 4: The hart single stepped because step was set. (priority 0, lowest)\r\n> 5: The hart halted directly out of reset due to resethaltreq. (priority 2)\r\n> It is also acceptable to report 3 when this happens.\r\n> 6: The hart halted because it’s part of a halt group. (priority 5, highest)\r\n> Harts may report 3 for this cause instead.\r\n> \r\n> Other values are reserved for future use.\r\n\r\nFixes #1743 ", "issue_title": "Ibex DCSR.cause priority encoding does not match debug-spec 0.13.2 or 1.0.0-STABLE", "issue_body": "\r\n\r\n## Observed Behavior\r\n\r\nWhile testing single-step behaviour, a cosimulation-mismatch was encountered when reading DCSR.cause. It was tracked down to a simultaneous assertion of DCSR.step and debug_req_i when entering debug_mode, and I believe that the spike behaviour is correct in this case.\r\nAccording to both debug specifications [0.13.2](https://riscv.org/wp-content/uploads/2019/03/riscv-debug-release.pdf) and [1.0.0-STABLE](https://raw.githubusercontent.com/riscv/riscv-debug-spec/master/riscv-debug-stable.pdf), the priority among reporting DCSR.cause has **step** (0) as a lower priority than **haltreq** (1). Ibex [currently reports](https://ibex-core.readthedocs.io/en/latest/03_reference/debug.html#debug-support) debug support in compliance with the RISCV Debug Specification Version 0.13.\r\nCurrent ibex behaviour is a priority-encoder [which places **step** above **haltreq**](https://github.com/lowRISC/ibex/blob/c4a97e05f5853b25e40fa1ea5b4edcfafba9a370/rtl/ibex_controller.sv#L662).\r\n\r\n\r\n## Expected Behavior\r\n\r\nIbex should prioritize reporting DCSR.cause as **haltreq** above **step** when entering debug_mode with both stimulus present.\r\n", "commit_message": "Fix incorrect debug_cause priority against riscv-debug 1.0.0-STABLE\n\nThe relevant page [Debug Spec v1.0.0-STABLE, p.53] gives the following\npriorities for resolving multiple concurrent reasons for entering debug mode....\n\nDCSR.cause : Explains why Debug Mode was entered.\n\nWhen there are multiple reasons to enter Debug Mode in a single cycle,\nhardware should set cause to the cause with the highest priority.\n1: An ebreak instruction was executed. (priority 3)\n2: A Trigger Module trigger fired with action=1. (priority 4)\n3: The debugger requested entry to Debug Mode using haltreq. (priority 1)\n4: The hart single stepped because step was set. (priority 0, lowest)\n5: The hart halted directly out of reset due to resethaltreq. (priority 2)\n It is also acceptable to report 3 when this happens.\n6: The hart halted because it’s part of a halt group. (priority 5, highest)\n Harts may report 3 for this cause instead.\n\nOther values are reserved for future use.", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex f017b3a851..5ee3a6ed7c 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -658,11 +658,11 @@ module ibex_controller #(\n \n csr_save_cause_o = 1'b1;\n if (trigger_match_i) begin\n- debug_cause_o = DBG_CAUSE_TRIGGER;\n- end else if (debug_single_step_i) begin\n- debug_cause_o = DBG_CAUSE_STEP;\n+ debug_cause_o = DBG_CAUSE_TRIGGER; // (priority 4)\n+ end else if (debug_req_i) begin\n+ debug_cause_o = DBG_CAUSE_HALTREQ; // (priority 1)\n end else begin\n- debug_cause_o = DBG_CAUSE_HALTREQ;\n+ debug_cause_o = DBG_CAUSE_STEP; // (priority 0, lowest)\n end\n \n // enter debug mode\n@@ -815,9 +815,14 @@ module ibex_controller #(\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.\n+ // proceed to DBG_TAKEN_ID, as it has the highest priority.\n+ // [Debug Spec v1.0.0-STABLE, p.53]\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", "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\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 load_intg_err_i,\n input logic store_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 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 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 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, 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 // 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;\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 // Exception/fault prioritisation is taken from Table 3.7 of Priviledged Spec v1.11\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 load_intg_err_irq_pending_q, load_intg_err_irq_pending_d;\n logic [31:0] load_intg_err_addr_q, load_intg_err_addr_d;\n logic load_intg_err_irq_set, load_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 load_intg_err_addr_d = load_intg_err_addr_q;\n load_intg_err_irq_set = 1'b0;\n load_intg_err_irq_clear = 1'b0;\n\n if (load_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 load_intg_err_irq_clear = 1'b1;\n end\n end else if (load_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 load_intg_err_addr_d = lsu_addr_last_i;\n load_intg_err_irq_set = 1'b1;\n end\n end\n\n assign load_intg_err_irq_pending_d =\n (load_intg_err_irq_pending_q & ~load_intg_err_irq_clear) | load_intg_err_irq_set;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n load_intg_err_irq_pending_q <= 1'b0;\n load_intg_err_addr_q <= '0;\n end else begin\n load_intg_err_irq_pending_q <= load_intg_err_irq_pending_d;\n load_intg_err_addr_q <= load_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 = load_intg_err_irq_set | load_intg_err_irq_pending_q;\n assign irq_nm_int_cause = NMI_INT_CAUSE_ECC;\n assign irq_nm_int_mtval = load_intg_err_addr_q;\n end else begin : g_no_intg_irq_int\n logic unused_load_intg_err_i;\n\n assign unused_load_intg_err_i = load_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 // Interrupts including NMI are ignored,\n // - while in debug mode [Debug Spec v0.13.2, p.39],\n // - while in NMI mode (nested NMIs are not supported, NMI has highest priority and\n // cannot be interrupted by regular interrupts).\n assign handle_irq = ~debug_mode_q & ~nmi_mode_q &\n (irq_nm | (irq_pending_i & csr_mstatus_mie_i));\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 /////////////////////\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_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 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 // interrupt priorities according to Privileged Spec v1.11 p.31\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 if (trigger_match_i) begin\n debug_cause_o = DBG_CAUSE_TRIGGER; // (priority 4)\n end else if (debug_req_i) begin\n debug_cause_o = DBG_CAUSE_HALTREQ; // (priority 1)\n end else begin\n debug_cause_o = DBG_CAUSE_STEP; // (priority 0, lowest)\n end\n\n // enter debug mode\n debug_mode_d = 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 [Debug Spec v0.13.2, p.39]\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 debug_cause_o = DBG_CAUSE_EBREAK;\n end\n\n // enter debug mode\n debug_mode_d = 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 /*\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 = 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 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\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 // [Debug Spec v1.0.0-STABLE, p.53]\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 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 //////////\n // FCOV //\n //////////\n\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 `ifdef INC_ASSERT\n // If something that causes a jump into an exception handler is seen that jump must occur before\n // the next instruction executes. The logic tracks whether a jump into an exception handler is\n // expected. Assertions check the jump occurs.\n\n logic exception_req, exception_req_pending, exception_req_accepted, exception_req_done;\n logic exception_pc_set, seen_exception_pc_set, expect_exception_pc_set;\n logic exception_req_needs_pc_set;\n\n assign exception_req = (special_req | enter_debug_mode | handle_irq);\n // Any exception rquest will cause a transition out of DECODE, once the controller transitions\n // back into DECODE we're done handling the request.\n assign exception_req_done =\n exception_req_pending & (ctrl_fsm_cs != DECODE) & (ctrl_fsm_ns == DECODE);\n\n assign exception_req_needs_pc_set = enter_debug_mode | handle_irq | special_req_pc_change;\n\n // An exception PC set uses specific PC types\n assign exception_pc_set =\n exception_req_pending & (pc_set_o & (pc_mux_o inside {PC_EXC, PC_ERET, PC_DRET}));\n\n always @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n exception_req_pending <= 1'b0;\n exception_req_accepted <= 1'b0;\n expect_exception_pc_set <= 1'b0;\n seen_exception_pc_set <= 1'b0;\n end else begin\n // Keep `exception_req_pending` asserted once an exception_req is seen until it is done\n exception_req_pending <= (exception_req_pending | exception_req) & ~exception_req_done;\n\n // The exception req has been accepted once the controller transitions out of decode\n exception_req_accepted <= (exception_req_accepted & ~exception_req_done) |\n (exception_req & ctrl_fsm_ns != DECODE);\n\n // Set `expect_exception_pc_set` if exception req needs one and keep it asserted until\n // exception req is done\n expect_exception_pc_set <= (expect_exception_pc_set | exception_req_needs_pc_set) &\n ~exception_req_done;\n\n // Keep `seen_exception_pc_set` asserted once an exception PC set is seen until the\n // exception req is done\n seen_exception_pc_set <= (seen_exception_pc_set | exception_pc_set) & ~exception_req_done;\n end\n end\n\n // Once an exception request has been accepted it must be handled before controller goes back to\n // DECODE\n `ASSERT(IbexNoDoubleExceptionReq, exception_req_accepted |-> ctrl_fsm_cs != DECODE)\n\n // Only signal ready, allowing a new instruction into ID, if there is no exception request\n // pending or it is done this cycle.\n `ASSERT(IbexDontSkipExceptionReq,\n id_in_ready_o |-> !exception_req_pending || exception_req_done)\n\n // Once a PC set has been performed for an exception request there must not be any other\n // excepting those to move into debug mode.\n `ASSERT(IbexNoDoubleSpecialReqPCSet,\n seen_exception_pc_set &&\n !((ctrl_fsm_cs inside {DBG_TAKEN_IF, DBG_TAKEN_ID}) &&\n (pc_mux_o == PC_EXC) && (exc_pc_mux_o == EXC_PC_DBD))\n |-> !pc_set_o)\n\n // When an exception request is done there must have been an appropriate PC set (either this\n // cycle or a previous one).\n `ASSERT(IbexSetExceptionPCOnSpecialReqIfExpected,\n exception_req_pending && expect_exception_pc_set && exception_req_done |->\n seen_exception_pc_set || exception_pc_set)\n\n // If there's a pending exception req that doesn't need a PC set we must not see one\n `ASSERT(IbexNoPCSetOnSpecialReqIfNotExpected,\n exception_req_pending && !expect_exception_pc_set |-> ~pc_set_o)\n `endif\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", "selected_doc_paths": ["doc/03_reference/exception_interrupts.rst", "doc/03_reference/debug.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/cs_registers.rst", "doc/03_reference/instruction_fetch.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1780, "lang": "sv", "rtl_files": ["rtl/ibex_cs_registers.sv"], "spec": "# Behavioral Design Specification: `ibex_cs_registers`\n\n## 1. Overview\n\nThe `ibex_cs_registers` module implements the RISC‑V Control and Status Registers (CSRs) as required by the Privileged Specification version 1.11, together with custom CSRs for CPU control, debug support, and security features. The module is responsible for storing all machine‑level CSRs, providing read‑only access to read‑only registers, treating most writable registers as WARL (Write‑Anything Read‑Legal), and updating exception‑related CSRs automatically when a trap or debug entry occurs.\n\nThe module integrates with the core’s pipeline stages to:\n\n- Supply the current privilege level and interrupt enable status to the decode and load‑store units.\n- Provide the trap vector base address, exception program counter, trap value, and exception cause to the exception controller.\n- Generate the qualified interrupt request bus by masking incoming interrupt lines with the enabled bits in `mie`.\n- Drive the PMP configuration and address outputs to the physical memory protection unit.\n- Drive debug control signals (single‑step, EBREAK behavior, trigger match) based on the debug CSRs.\n- Expose CPU control bits for data‑independent timing, dummy instruction insertion, and instruction cache enable.\n- Host the performance‑monitoring counters and their inhibit/event‑selection registers.\n\n## 2. Interfaces\n\nThe module interacts with:\n\n- **Pipeline stages** – receives signals indicating that a trap must be taken (save), that an MRET or DRET instruction is being executed (restore), and the program counters from the IF, ID, and WB stages.\n- **CSR instruction execution** – receives the CSR address, operation type (read, write, set, clear), write data, and an operation‑enable flag; returns read data and asserts an illegal‑CSR indication when appropriate.\n- **Interrupt sources** – receives the five groups of interrupt requests (software, timer, external, 15 fast interrupts, and a non‑maskable interrupt line).\n- **Hart ID** – receives a 32‑bit hart identifier presented read‑only to the `mhartid` CSR.\n- **Boot address** – used to initialize the trap‑vector base address (`mtvec`) at reset.\n- **Debug module** – receives entry cause and a save signal for debug entry; returns `depc`, single‑step enable, EBREAK mode bits, and a trigger match indication.\n- **Exception data** – receives the exception cause and trap value when a synchronous exception or interrupt causes a trap.\n- **Performance monitor inputs** – receives events (instruction retired, loads, stores, branch, jump, waits, etc.) for counting.\n- **CPU control outputs** – provides signals to the rest of the core for data‑independent timing, dummy instruction insertion, instruction cache enable, and a shadow error summary.\n- **PMP unit** – outputs per‑region PMP configuration, address, and the machine security configuration register (`mseccfg`).\n\n## 3. Reset and Initialization\n\nOn power‑on reset the module shall:\n\n- Set the current privilege level to Machine Mode (`M‑Mode`).\n- Initialize `mstatus` with MIE=0, MPIE=1, MPP=U‑Mode, MPRV=0, TW=0.\n- Initialize `mtvec` to the value `{boot_addr[31:8], 6'b0, 2'b01}` – that is, the base address taken from the boot address, forced to 256‑byte alignment, and the MODE field set to “vectored” (01).\n- Zero all interrupt enable bits (`mie`).\n- Zero the machine cause, exception PC, trap value, scratch, debug CSRs (`dcsr`, `dpc`, `dscratch0`, `dscratch1`), and all PMP configuration/address registers.\n- Zero the performance counter inhibit register and all counter flip‑flops.\n- Zero the custom CPU control register (`cpuctrl`) and the seed register storage (which is not readable).\n- Set `misa` to a hard‑wired value reflecting the configured ISA extensions (I, M, C, U, E, etc.) and the MXLEN field.\n\nThe module shall not depend on software writing to any CSR before normal operation; the reset values are sufficient for the core to begin fetching instructions.\n\n## 4. CSR Access Control\n\nThe module shall:\n\n- **Privilege level check:** A CSR is accessible only if the address’s high two bits (bits 9:8) are less than or equal to the current privilege level. Address bits 9:8 encode the required privilege: 0b11 → Machine only, 0b10 → Supervisor (not implemented), 0b01 → User and above, 0b00 → User only. Because Ibex implements only M‑Mode and U‑Mode, access to any CSR with bits 9:8 > current privilege level shall cause an illegal instruction trap.\n- **Write permission check:** CSRs whose addresses have bits 11:10 = 2’b11 are read‑only. A write attempt (any of CSR_OP_WRITE, SET, CLEAR) to such an address shall be rejected and shall assert the illegal CSR signal.\n- **Debug CSR access:** Debug‑only CSRs (`dcsr`, `dpc`, `dscratch0`, `dscratch1`) and debug‑trigger CSRs (`tselect`, `tdata1`, `tdata2`, `tdata3`, `mcontext`, `scontext`) shall be accessible only when the core is in Debug Mode. An attempt to access them from M‑Mode or U‑Mode shall be treated as an illegal instruction.\n- **Non‑existent CSR:** Any CSR address not listed in the module’s decode table shall be treated as illegal.\n- **PMP CSRs without PMP:** If the PMP feature is disabled, all `pmpcfg*` and `pmpaddr*` registers, as well as `mseccfg` and `mseccfgh`, shall be inaccessible and any read or write to them shall raise an illegal instruction.\n- **WARL behavior:** Most writable CSRs are WARL. The module shall update them with the supplied write data, but may adjust fields to legal values (e.g., `mstatus.MPP` bits that decode to unsupported privilege levels shall be forced to U‑Mode; `mtvec.BASE` bits 7:2 are forced to zero; `dcsr.prv` unsupported values are forced to U‑Mode). Writes to read‑only fields of a register shall have no effect.\n- **`misa` write:** `misa` is hard‑wired; any write shall be silently ignored.\n\n## 5. Interrupt and Exception Handling\n\n### 5.1 Trap Save (Entering a Handler)\n\nWhen the core is in a non‑debug mode and a trap (synchronous exception or interrupt) is to be taken, the module shall:\n\n1. Capture the program counter from the pipeline stage indicated by the save request (IF, ID, or WB) into `mepc`.\n2. Store the current privilege level into `mstatus.MPP`.\n3. Save the current `mstatus.MIE` into `mstatus.MPIE`.\n4. Disable interrupts by clearing `mstatus.MIE`.\n5. Set `mcause` and `mtval` from the inputs provided by the exception controller.\n6. Update the current privilege level to M‑Mode.\n\nFor debug entry (when `debug_csr_save_i` is asserted), the module shall:\n\n- Save the current privilege level into `dcsr.prv`.\n- Record the debug cause (`dcsr.cause`).\n- Save the program counter into `dpc`.\n- Update the current privilege level to M‑Mode (since the core enters Debug Mode from M‑Mode).\n- Not modify `mcause`, `mepc`, `mtval`, or `mstatus`.\n\n### 5.2 Trap Restore (MRET)\n\nOn execution of an MRET instruction (`csr_restore_mret_i`), the module shall:\n\n- Restore the privilege level from `mstatus.MPP`.\n- Set `mstatus.MIE` to the value of `mstatus.MPIE`.\n- Set `mstatus.MPIE` to 1 and `mstatus.MPP` to U‑Mode (unless an NMI return is in progress, see 5.4).\n- Clear the synchronous‑exception‑seen flag in the CPU control register (`cpuctrl`).\n\n### 5.3 Interrupt Qualification and Priority\n\nThe module shall generate:\n\n- A qualified interrupt pending vector `irqs_o` as the bitwise AND of the incoming `mip` signals (software, timer, external, fast) with the `mie` register.\n- A single-pulse `irq_pending_o` output whenever any qualified interrupt is pending.\n\nInterrupts are only considered when the core is not in Debug Mode and when `mstatus.MIE` is set (except for NMIs). The priority order follows the RISC‑V specification: fast interrupts (ID 16–30) have the highest priority among maskable interrupts, with lower ID having higher priority, followed by external, timer, then software.\n\n### 5.4 Non‑Maskable Interrupt (NMI)\n\nThe NMI (interrupt ID 31) is enabled regardless of `mstatus.MIE` or `mie`. It is not visible in the `mip` CSR.\n\nWhen an NMI is taken, the module behaves as a normal interrupt save but additionally:\n\n- Stores the previous `mstatus.MPIE` and `mstatus.MPP` into the non‑standard `mstack` CSR.\n- Saves `mepc` and `mcause` into `mstack_epc` and `mstack_cause`.\n- Upon returning from the NMI handler (MRET while in NMI mode), the module restores `mstatus.MPIE` and `mstatus.MPP` from the `mstack` CSR, and loads `mepc` and `mcause` from the saved copies, effectively undoing the NMI save to support a recoverable NMI.\n\nDuring NMI handling all interrupts (including further NMIs) are ignored.\n\n### 5.5 Double Fault Detection\n\nThe module shall maintain a non‑architectural `cpu_ctrl` field `sync_exc_seen`. This field is:\n\n- Set to 1 when a synchronous exception occurs.\n- Cleared to 0 on MRET.\n- If a synchronous exception is taken while `sync_exc_seen` is already 1, the module shall assert the `double_fault_seen_o` output for one cycle and set the `double_fault_seen` field in `cpuctrl`. This field must be manually cleared by software.\n\n## 6. Debug Support\n\n### 6.1 Debug CSRs\n\nThe module implements four core debug CSRs (accessible only in Debug Mode):\n\n- **`dcsr` (Debug Control and Status):** Contains the xdebugver (read‑only 4), ebreakm, ebreaku, cause (read‑only), step, and prv fields. The `step` bit controls single‑stepping; when set, the core executes one instruction and re‑enters Debug Mode. The `cause` field records the reason for entering Debug Mode (1=EBREAK, 2=trigger, 3=halt request, 4=step). Writes to read‑only fields (xdebugver, cause, stopcount, stoptime, mprven, nmip) shall be ignored.\n- **`dpc` (Debug PC):** Stores the return address for resume.\n- **`dscratch0/1` (Debug Scratch):** General‑purpose storage for debug software.\n\n### 6.2 Debug Triggers\n\nWhen enabled by the `DbgTriggerEn` parameter, the module instantiates `DbgHwBreakNum` hardware breakpoint trigger registers:\n\n- **`tselect` (Trigger Select):** WARL register selecting which of the implemented triggers is accessed by `tdata1/2/3`. Writes beyond the number of implemented triggers are clamped to the highest valid index.\n- **`tdata1` (Trigger Data 1):** Returns a fixed value indicating a single address‑match trigger (type=2), accessible only in Debug Mode. The `execute` bit is writable; all other fields are hard‑wired.\n- **`tdata2` (Trigger Data 2):** Stores the instruction address to match.\n- **`tdata3`, `mcontext`, `scontext`:** Read as zero; writes are ignored.\n\nThe module shall compare the instruction fetch program counter against all active trigger values and assert `trigger_match_o` if any match occurs. Matching is enabled only for the currently selected trigger’s `execute` bit.\n\n## 7. Physical Memory Protection (PMP) Support\n\nWhen the `PMPEnable` parameter is 1, the module shall:\n\n- Implement the number of PMP regions specified by `PMPNumRegions` (1–16).\n- Provide four configuration registers (`pmpcfg0`–`pmpcfg3`), each containing four 8‑bit PMP configuration fields. The NA4 mode is not available when `PMPGranularity > 0`; in that case a write of NA4 is treated as OFF.\n- Provide 16 address registers (`pmpaddr0`–`pmpaddr15`), each holding `PMPAddrWidth` bits (derived from PMPGranularity).\n- Implement the Machine Security Configuration register `mseccfg` with three bits: MML, MMWP, RLB. The `mseccfgh` is read‑only zero.\n- Support the lock bit: once the lock bit is set in a PMP configuration, further writes to that configuration and its associated address are ignored unless the MSECCFG.RLB bit is set.\n- Support the enhanced PMP behavior (Smepmp): when MSECCFG.MML is set, the meaning of the R/W/X bits changes per the Smepmp proposal. The module shall prevent writing new M‑mode‑executable configurations that would violate lockdown unless RLB is set.\n- Output per‑region PMP configuration, expanded address (with low‑bit masking per granularity), and the `mseccfg` value to the PMP checker.\n\nWhen PMP is disabled, all PMP‑related outputs are zero.\n\n## 8. Performance Counters\n\n### 8.1 Standard Counters\n\n- **`mcycle` (0xB00/0xB80):** 64‑bit cycle counter, incremented every clock cycle unless inhibited by `mcountinhibit[0]`.\n- **`minstret` (0xB02/0xB82):** 64‑bit instruction‑retired counter, incremented on each retired instruction unless inhibited by `mcountinhibit[2]`. The module shall adjust the counter value to account for an instruction in the write‑back stage when read speculatively (timing optimization), but the architectural value is stable after write‑back commits.\n\n### 8.2 Event Counters\n\nUp to 29 optional event counters (`mhpmcounter3`–`mhpmcounter31`, each with lower and upper halves) are instantiated based on the `MHPMCounterNum` parameter. Their width is configurable via `MHPMCounterWidth`. Each event counter increments on a hard‑wired event as defined in the table below. The event selector CSRs (`mhpmevent3`–`mhpmevent31`) are read‑only and permanently enable the corresponding single event. Unused counters decode to zero and ignore writes.\n\n| Counter | Event Mnemonic | Description |\n|-------------|-----------------------|--------------------------------------------------|\n| 3 | NumCyclesLSU | Cycles waiting for data memory |\n| 4 | NumCyclesIF | Cycles waiting for instruction fetch |\n| 5 | NumLoads | Number of load operations |\n| 6 | NumStores | Number of store operations |\n| 7 | NumJumps | Number of unconditional jumps |\n| 8 | NumBranches | Number of conditional branches |\n| 9 | NumBranchesTaken | Number of taken branches |\n| 10 | NumInstrRetC | Number of compressed instructions retired |\n| 11 | NumCyclesMulWait | Cycles waiting for multiply |\n| 12 | NumCyclesDivWait | Cycles waiting for divide |\n\nCounters 1, 13..31 are unused and always read as zero.\n\n### 8.3 Counter Control\n\n- `mcountinhibit` (0x320) controls which counters are enabled. Bits 0 (mcycle), 2 (minstret), and bits 3–31 (mhpmcounter3–31) are implemented. Bit 1 is reserved and forced to 0. Writing a 1 to a bit inhibits the corresponding counter increment.\n- All counters are freely writable by software (lower and upper halves) and non‑destructive to read.\n\n## 9. Custom CPU Control Register (`cpuctrl`)\n\nAddress 0x7C0, accessible in M‑Mode only, WARL. The register is a packed structure with the following fields:\n\n- **`double_fault_seen` (bit 7):** Set only by hardware when a double fault is detected. Software may clear it by writing 0. Writing 1 has no effect on this bit.\n- **`sync_exc_seen` (bit 6):** Set by hardware on any synchronous exception; cleared by hardware on MRET. Software may also write it.\n- **`dummy_instr_mask` (bits 5:3):** Controls the frequency of dummy instruction insertion. Only writable when `DummyInstructions` parameter is 1; otherwise hardwired to 0.\n- **`dummy_instr_en` (bit 2):** Enables dummy instruction insertion. Writable only when `DummyInstructions=1`; otherwise 0.\n- **`data_ind_timing` (bit 1):** Enables data‑independent timing. Writable only when `DataIndTiming=1`; otherwise 0.\n- **`icache_enable` (bit 0):** Enables the instruction cache. Writable only when `ICache=1`; otherwise 0.\n\nThe module shall output the decoded fields to the corresponding core control signals. Writing to this CSR shall only occur when the core is in M‑Mode and no illegal access condition exists.\n\n## 10. Security Seed Register (`secureseed`)\n\nAddress 0x7C1, accessible in M‑Mode only. A write to this CSR causes the module to pulse the `dummy_instr_seed_en_o` output and present the write data on `dummy_instr_seed_o`, allowing software to reseed security‑related pseudo‑random generators. Reads always return zero; writes are WARL but the value is not stored.\n\n## 11. Shadow Error Output\n\nThe module shall combine the error outputs from all sub‑CSR instances that support shadow copies (based on the `ShadowCSR` parameter). The `csr_shadow_err_o` output must be asserted if any of those CSRs experiences a shadow‑copy integrity error.\n\n## 12. Assumptions and Constraints\n\n- The CSR address encoding follows the RISC‑V standard (bits 11:10 for read‑only, bits 9:8 for privilege).\n- The `csr_access_i` signal must be asserted whenever `csr_op_en_i` is asserted (assertion in source).\n- The `mtvec` CSR is always forced to vectored mode (MODE=01); the `BASE` field is always 256‑byte aligned.\n- The `mvendorid`, `marchid`, and `mimpid` CSRs are parameterizable via constants in a package file, but their values are fixed at synthesis time.\n- The “time” CSRs (0xC01/0xC81) are not implemented; any access traps to M‑Mode.\n- Privilege level transitions on MRET and DRET respect the stored CSR values; no other transition mechanism exists.\n\n## 13. Summary of Outputs\n\n| Output | Derivation / Purpose |\n|----------------------------------|-----------------------------------------------------------------------------------------------------------------|\n| `priv_mode_id_o` | Current privilege level (used by decoder). |\n| `priv_mode_lsu_o` | Privilege level for load‑store operations (takes `mstatus.MPRV` into account). |\n| `csr_mtvec_o` | Trap vector base address (for jump target computation). |\n| `csr_mepc_o`, `csr_mtval_o` | Exception PC and trap value (for immediate use by exception controller). |\n| `irqs_o`, `irq_pending_o` | Qualified interrupt requests and pending indication. |\n| `csr_mstatus_mie_o` | Global interrupt enable status. |\n| `csr_mstatus_tw_o` | Timeout‑wait bit (for WFI handling in U‑Mode). |\n| `csr_depc_o` | Debug PC (used by debug resume). |\n| `debug_single_step_o` | Single‑step enable (from `dcsr.step`). |\n| `debug_ebreakm_o`, `debug_ebreaku_o` | EBREAK behavior in M‑Mode and U‑Mode. |\n| `trigger_match_o` | OR of all active hardware breakpoint matches. |\n| `data_ind_timing_o` | Data‑independent timing enable for LSU. |\n| `dummy_instr_en_o`, `dummy_instr_mask_o` | Dummy instruction insertion control. |\n| `dummy_instr_seed_en_o`, `dummy_instr_seed_o` | Seed update pulse and data for LFSR reseeding. |\n| `icache_enable_o` | Instruction cache enable. |\n| `csr_shadow_err_o` | Combined error from shadow‑copied CSR instances. |\n| `illegal_csr_insn_o` | Strobe indicating a CSR access is illegal. |\n| `double_fault_seen_o` | Strobe indicating a double fault has just been detected. |\n| PMP outputs | Per‑region configuration, address, and machine security configuration. |", "commit_id": "1affeff5278d5b2d84984cd3bf173f72d9f024da", "timestamp": "2022-08-18T14:45:28+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "a646737d4d7a210ba6292ad0c825dfd194d8623a", "pr_title": "[rtl] Cannot add M mode executable PMP regions when MML = 1", "pr_body": "A rule that allows M mode execution (either M mode only or shared M/U\r\nmode) cannot be added when MML is set, unless RLB is also set.\r\n\r\nFixes #1740", "issue_title": "[rtl,epmp] Prevent addition of executable regions as required by the specification", "issue_body": "The Smepmp specification states:\r\n\r\n> Adding a rule with executable privileges that either is M-mode-only or a locked Shared-Region is not possible and such pmpcfg writes are ignored, leaving pmpcfg unchanged. This restriction can be temporarily lifted e.g. during the boot process, by setting mseccfg.RLB.****\r\n\r\nThis was overlooked during the original epmp implementation and must be added.\r\n\r\n> estimate 2\r\n> remaining 2022-18-08 1", "commit_message": "[rtl] Cannot add M mode executable PMP regions when MML = 1\n\nA rule that allows M mode execution (either M mode only or shared M/U\nmode) cannot be added when MML is set, unless RLB is also set.\n\nFixes #1740", "fix_patch": "diff --git a/rtl/ibex_cs_registers.sv b/rtl/ibex_cs_registers.sv\nindex d1d791ae69..5b2f6a28b6 100644\n--- a/rtl/ibex_cs_registers.sv\n+++ b/rtl/ibex_cs_registers.sv\n@@ -124,6 +124,22 @@ module ibex_cs_registers #(\n \n import ibex_pkg::*;\n \n+ // Is a PMP config a locked one that allows M-mode execution when MSECCFG.MML is set (either\n+ // M mode alone or shared M/U mode execution)?\n+ function automatic logic is_mml_m_exec_cfg(ibex_pkg::pmp_cfg_t pmp_cfg);\n+ logic unused_cfg;\n+ unused_cfg = ^{pmp_cfg.mode};\n+\n+ if (pmp_cfg.lock) begin\n+ case ({pmp_cfg.read, pmp_cfg.write, pmp_cfg.exec})\n+ 3'b001, 3'b010, 3'b011, 3'b101: return 1'b1;\n+ default: return 1'b0;\n+ endcase\n+ end\n+\n+ return 1'b0;\n+ endfunction\n+\n localparam int unsigned RV32BExtra = (RV32B == RV32BOTEarlGrey) || (RV32B == RV32BFull) ? 1 : 0;\n localparam int unsigned RV32MEnabled = (RV32M == RV32MNone) ? 0 : 1;\n localparam int unsigned PMPAddrWidth = (PMPGranularity > 0) ? 33 - PMPGranularity : 32;\n@@ -1045,6 +1061,7 @@ module ibex_cs_registers #(\n logic pmp_mseccfg_err;\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_locked;\n+ logic [PMPNumRegions-1:0] pmp_cfg_wr_suppress;\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n logic [PMPAddrWidth-1:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n@@ -1100,7 +1117,9 @@ module ibex_cs_registers #(\n // -------------------------\n // Instantiate cfg registers\n // -------------------------\n- assign pmp_cfg_we[i] = csr_we_int & ~pmp_cfg_locked[i] &\n+ assign pmp_cfg_we[i] = csr_we_int &\n+ ~pmp_cfg_locked[i] &\n+ ~pmp_cfg_wr_suppress[i] &\n (csr_addr == (CSR_OFF_PMP_CFG + (i[11:0] >> 2)));\n \n // Select the correct WDATA (each CSR contains 4 CFG fields, each with 2 RES bits)\n@@ -1140,6 +1159,12 @@ module ibex_cs_registers #(\n // set).\n assign pmp_cfg_locked[i] = pmp_cfg[i].lock & ~pmp_mseccfg_q.rlb;\n \n+ // When MSECCFG.MML is set cannot add new regions allowing M mode execution unless MSECCFG.RLB\n+ // is set\n+ assign pmp_cfg_wr_suppress[i] = pmp_mseccfg_q.mml &\n+ ~pmp_mseccfg.rlb &\n+ is_mml_m_exec_cfg(pmp_cfg_wdata[i]);\n+\n // --------------------------\n // Instantiate addr registers\n // --------------------------\n", "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 * Control and Status Registers\n *\n * Control and Status Registers (CSRs) following the RISC-V Privileged\n * Specification, draft version 1.11\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_cs_registers #(\n parameter bit DbgTriggerEn = 0,\n parameter int unsigned DbgHwBreakNum = 1,\n parameter bit DataIndTiming = 1'b0,\n parameter bit DummyInstructions = 1'b0,\n parameter bit ShadowCSR = 1'b0,\n parameter bit ICache = 1'b0,\n parameter int unsigned MHPMCounterNum = 10,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit PMPEnable = 0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter bit RV32E = 0,\n parameter ibex_pkg::rv32m_e RV32M = ibex_pkg::RV32MFast,\n parameter ibex_pkg::rv32b_e RV32B = ibex_pkg::RV32BNone\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n // Hart ID\n input logic [31:0] hart_id_i,\n\n // Privilege mode\n output ibex_pkg::priv_lvl_e priv_mode_id_o,\n output ibex_pkg::priv_lvl_e priv_mode_lsu_o,\n output logic csr_mstatus_tw_o,\n\n // mtvec\n output logic [31:0] csr_mtvec_o,\n input logic csr_mtvec_init_i,\n input logic [31:0] boot_addr_i,\n\n // Interface to registers (SRAM like)\n input logic csr_access_i,\n input ibex_pkg::csr_num_e csr_addr_i,\n input logic [31:0] csr_wdata_i,\n input ibex_pkg::csr_op_e csr_op_i,\n input csr_op_en_i,\n output logic [31:0] csr_rdata_o,\n\n // interrupts\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 nmi_mode_i,\n output logic irq_pending_o, // interrupt request pending\n output ibex_pkg::irqs_t irqs_o, // interrupt requests qualified with mie\n output logic csr_mstatus_mie_o,\n output logic [31:0] csr_mepc_o,\n output logic [31:0] csr_mtval_o,\n\n // PMP\n output ibex_pkg::pmp_cfg_t csr_pmp_cfg_o [PMPNumRegions],\n output logic [33:0] csr_pmp_addr_o [PMPNumRegions],\n output ibex_pkg::pmp_mseccfg_t csr_pmp_mseccfg_o,\n\n // debug\n input logic debug_mode_i,\n input ibex_pkg::dbg_cause_e debug_cause_i,\n input logic debug_csr_save_i,\n output logic [31:0] csr_depc_o,\n output logic debug_single_step_o,\n output logic debug_ebreakm_o,\n output logic debug_ebreaku_o,\n output logic trigger_match_o,\n\n input logic [31:0] pc_if_i,\n input logic [31:0] pc_id_i,\n input logic [31:0] pc_wb_i,\n\n // CPU control bits\n output logic data_ind_timing_o,\n output logic dummy_instr_en_o,\n output logic [2:0] dummy_instr_mask_o,\n output logic dummy_instr_seed_en_o,\n output logic [31:0] dummy_instr_seed_o,\n output logic icache_enable_o,\n output logic csr_shadow_err_o,\n\n // Exception save/restore\n input logic csr_save_if_i,\n input logic csr_save_id_i,\n input logic csr_save_wb_i,\n input logic csr_restore_mret_i,\n input logic csr_restore_dret_i,\n input logic csr_save_cause_i,\n input ibex_pkg::exc_cause_t csr_mcause_i,\n input logic [31:0] csr_mtval_i,\n output logic illegal_csr_insn_o, // access to non-existent CSR,\n // with wrong priviledge level, or\n // missing write permissions\n output logic double_fault_seen_o,\n // Performance Counters\n input logic instr_ret_i, // instr retired in ID/EX stage\n input logic instr_ret_compressed_i, // compressed instr retired\n input logic instr_ret_spec_i, // speculative instr_ret_i\n input logic instr_ret_compressed_spec_i, // speculative instr_ret_compressed_i\n input logic iside_wait_i, // core waiting for the iside\n input logic jump_i, // jump instr seen (j, jr, jal, jalr)\n input logic branch_i, // branch instr seen (bf, bnf)\n input logic branch_taken_i, // branch was taken\n input logic mem_load_i, // load from memory in this cycle\n input logic mem_store_i, // store to memory in this cycle\n input logic dside_wait_i, // core waiting for the dside\n input logic mul_wait_i, // core waiting for multiply\n input logic div_wait_i // core waiting for divide\n);\n\n import ibex_pkg::*;\n\n // Is a PMP config a locked one that allows M-mode execution when MSECCFG.MML is set (either\n // M mode alone or shared M/U mode execution)?\n function automatic logic is_mml_m_exec_cfg(ibex_pkg::pmp_cfg_t pmp_cfg);\n logic unused_cfg;\n unused_cfg = ^{pmp_cfg.mode};\n\n if (pmp_cfg.lock) begin\n case ({pmp_cfg.read, pmp_cfg.write, pmp_cfg.exec})\n 3'b001, 3'b010, 3'b011, 3'b101: return 1'b1;\n default: return 1'b0;\n endcase\n end\n\n return 1'b0;\n endfunction\n\n localparam int unsigned RV32BExtra = (RV32B == RV32BOTEarlGrey) || (RV32B == RV32BFull) ? 1 : 0;\n localparam int unsigned RV32MEnabled = (RV32M == RV32MNone) ? 0 : 1;\n localparam int unsigned PMPAddrWidth = (PMPGranularity > 0) ? 33 - PMPGranularity : 32;\n\n // misa\n localparam logic [31:0] MISA_VALUE =\n (0 << 0) // A - Atomic Instructions extension\n | (0 << 1) // B - Bit-Manipulation extension\n | (1 << 2) // C - Compressed extension\n | (0 << 3) // D - Double precision floating-point extension\n | (32'(RV32E) << 4) // E - RV32E base ISA\n | (0 << 5) // F - Single precision floating-point extension\n | (32'(!RV32E) << 8) // I - RV32I/64I/128I base ISA\n | (RV32MEnabled << 12) // M - Integer Multiply/Divide extension\n | (0 << 13) // N - User level interrupts supported\n | (0 << 18) // S - Supervisor mode implemented\n | (1 << 20) // U - User mode implemented\n | (RV32BExtra << 23) // X - Non-standard extensions present\n | (32'(CSR_MISA_MXL) << 30); // M-XLEN\n\n typedef struct packed {\n logic mie;\n logic mpie;\n priv_lvl_e mpp;\n logic mprv;\n logic tw;\n } status_t;\n\n typedef struct packed {\n logic mpie;\n priv_lvl_e mpp;\n } status_stk_t;\n\n typedef struct packed {\n x_debug_ver_e xdebugver;\n logic [11:0] zero2;\n logic ebreakm;\n logic zero1;\n logic ebreaks;\n logic ebreaku;\n logic stepie;\n logic stopcount;\n logic stoptime;\n dbg_cause_e cause;\n logic zero0;\n logic mprven;\n logic nmip;\n logic step;\n priv_lvl_e prv;\n } dcsr_t;\n\n // CPU control register fields\n typedef struct packed {\n logic double_fault_seen;\n logic sync_exc_seen;\n logic [2:0] dummy_instr_mask;\n logic dummy_instr_en;\n logic data_ind_timing;\n logic icache_enable;\n } cpu_ctrl_t;\n\n // Interrupt and exception control signals\n logic [31:0] exception_pc;\n\n // CSRs\n priv_lvl_e priv_lvl_q, priv_lvl_d;\n status_t mstatus_q, mstatus_d;\n logic mstatus_err;\n logic mstatus_en;\n irqs_t mie_q, mie_d;\n logic mie_en;\n logic [31:0] mscratch_q;\n logic mscratch_en;\n logic [31:0] mepc_q, mepc_d;\n logic mepc_en;\n exc_cause_t mcause_q, mcause_d;\n logic mcause_en;\n logic [31:0] mtval_q, mtval_d;\n logic mtval_en;\n logic [31:0] mtvec_q, mtvec_d;\n logic mtvec_err;\n logic mtvec_en;\n irqs_t mip;\n dcsr_t dcsr_q, dcsr_d;\n logic dcsr_en;\n logic [31:0] depc_q, depc_d;\n logic depc_en;\n logic [31:0] dscratch0_q;\n logic [31:0] dscratch1_q;\n logic dscratch0_en, dscratch1_en;\n\n // CSRs for recoverable NMIs\n // NOTE: these CSRS are nonstandard, see https://github.com/riscv/riscv-isa-manual/issues/261\n status_stk_t mstack_q, mstack_d;\n logic mstack_en;\n logic [31:0] mstack_epc_q, mstack_epc_d;\n exc_cause_t mstack_cause_q, mstack_cause_d;\n\n // PMP Signals\n logic [31:0] pmp_addr_rdata [PMP_MAX_REGIONS];\n logic [PMP_CFG_W-1:0] pmp_cfg_rdata [PMP_MAX_REGIONS];\n logic pmp_csr_err;\n pmp_mseccfg_t pmp_mseccfg;\n\n // Hardware performance monitor signals\n logic [31:0] mcountinhibit;\n // Only have mcountinhibit flops for counters that actually exist\n logic [MHPMCounterNum+3-1:0] mcountinhibit_d, mcountinhibit_q;\n logic mcountinhibit_we;\n\n // mhpmcounter flops are elaborated below providing only the precise number that is required based\n // on MHPMCounterNum/MHPMCounterWidth. This signal connects to the Q output of these flops\n // where they exist and is otherwise 0.\n logic [63:0] mhpmcounter [32];\n logic [31:0] mhpmcounter_we;\n logic [31:0] mhpmcounterh_we;\n logic [31:0] mhpmcounter_incr;\n logic [31:0] mhpmevent [32];\n logic [4:0] mhpmcounter_idx;\n logic unused_mhpmcounter_we_1;\n logic unused_mhpmcounterh_we_1;\n logic unused_mhpmcounter_incr_1;\n\n logic [63:0] minstret_next, minstret_raw;\n\n // Debug / trigger registers\n logic [31:0] tselect_rdata;\n logic [31:0] tmatch_control_rdata;\n logic [31:0] tmatch_value_rdata;\n\n // CPU control bits\n cpu_ctrl_t cpuctrl_q, cpuctrl_d, cpuctrl_wdata_raw, cpuctrl_wdata;\n logic cpuctrl_we;\n logic cpuctrl_err;\n\n // CSR update logic\n logic [31:0] csr_wdata_int;\n logic [31:0] csr_rdata_int;\n logic csr_we_int;\n logic csr_wr;\n\n // Access violation signals\n logic dbg_csr;\n logic illegal_csr;\n logic illegal_csr_priv;\n logic illegal_csr_dbg;\n logic illegal_csr_write;\n\n logic [7:0] unused_boot_addr;\n logic [2:0] unused_csr_addr;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n\n /////////////\n // CSR reg //\n /////////////\n\n logic [$bits(csr_num_e)-1:0] csr_addr;\n assign csr_addr = {csr_addr_i};\n assign unused_csr_addr = csr_addr[7:5];\n assign mhpmcounter_idx = csr_addr[4:0];\n\n assign illegal_csr_dbg = dbg_csr & ~debug_mode_i;\n // See RISC-V Privileged Specification, version 1.11, Section 2.1\n assign illegal_csr_priv = (csr_addr[9:8] > {priv_lvl_q});\n assign illegal_csr_write = (csr_addr[11:10] == 2'b11) && csr_wr;\n assign illegal_csr_insn_o = csr_access_i & (illegal_csr | illegal_csr_write | illegal_csr_priv |\n illegal_csr_dbg);\n\n // mip CSR is purely combinational - must be able to re-enable the clock upon WFI\n assign mip.irq_software = irq_software_i;\n assign mip.irq_timer = irq_timer_i;\n assign mip.irq_external = irq_external_i;\n assign mip.irq_fast = irq_fast_i;\n\n // read logic\n always_comb begin\n csr_rdata_int = '0;\n illegal_csr = 1'b0;\n dbg_csr = 1'b0;\n\n unique case (csr_addr_i)\n // mvendorid: encoding of manufacturer/provider\n CSR_MVENDORID: csr_rdata_int = CSR_MVENDORID_VALUE;\n // marchid: encoding of base microarchitecture\n CSR_MARCHID: csr_rdata_int = CSR_MARCHID_VALUE;\n // mimpid: encoding of processor implementation version\n CSR_MIMPID: csr_rdata_int = CSR_MIMPID_VALUE;\n // mhartid: unique hardware thread id\n CSR_MHARTID: csr_rdata_int = hart_id_i;\n\n // mstatus: always M-mode, contains IE bit\n CSR_MSTATUS: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSTATUS_MIE_BIT] = mstatus_q.mie;\n csr_rdata_int[CSR_MSTATUS_MPIE_BIT] = mstatus_q.mpie;\n csr_rdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW] = mstatus_q.mpp;\n csr_rdata_int[CSR_MSTATUS_MPRV_BIT] = mstatus_q.mprv;\n csr_rdata_int[CSR_MSTATUS_TW_BIT] = mstatus_q.tw;\n end\n\n // misa\n CSR_MISA: csr_rdata_int = MISA_VALUE;\n\n // interrupt enable\n CSR_MIE: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mie_q.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mie_q.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mie_q.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mie_q.irq_fast;\n end\n\n // mcounteren: machine counter enable\n CSR_MCOUNTEREN: begin\n csr_rdata_int = '0;\n end\n\n CSR_MSCRATCH: csr_rdata_int = mscratch_q;\n\n // mtvec: trap-vector base address\n CSR_MTVEC: csr_rdata_int = mtvec_q;\n\n // mepc: exception program counter\n CSR_MEPC: csr_rdata_int = mepc_q;\n\n // mcause: exception cause\n CSR_MCAUSE: csr_rdata_int = {mcause_q.irq_ext | mcause_q.irq_int,\n mcause_q.irq_int ? {26{1'b1}} : 26'b0,\n mcause_q.lower_cause[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: csr_rdata_int = mtval_q;\n\n // mip: interrupt pending\n CSR_MIP: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mip.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mip.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mip.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mip.irq_fast;\n end\n\n CSR_MSECCFG: begin\n if (PMPEnable) begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSECCFG_MML_BIT] = pmp_mseccfg.mml;\n csr_rdata_int[CSR_MSECCFG_MMWP_BIT] = pmp_mseccfg.mmwp;\n csr_rdata_int[CSR_MSECCFG_RLB_BIT] = pmp_mseccfg.rlb;\n end else begin\n illegal_csr = 1'b1;\n end\n end\n\n CSR_MSECCFGH: begin\n if (PMPEnable) begin\n csr_rdata_int = '0;\n end else begin\n illegal_csr = 1'b1;\n end\n end\n\n // PMP registers\n CSR_PMPCFG0: csr_rdata_int = {pmp_cfg_rdata[3], pmp_cfg_rdata[2],\n pmp_cfg_rdata[1], pmp_cfg_rdata[0]};\n CSR_PMPCFG1: csr_rdata_int = {pmp_cfg_rdata[7], pmp_cfg_rdata[6],\n pmp_cfg_rdata[5], pmp_cfg_rdata[4]};\n CSR_PMPCFG2: csr_rdata_int = {pmp_cfg_rdata[11], pmp_cfg_rdata[10],\n pmp_cfg_rdata[9], pmp_cfg_rdata[8]};\n CSR_PMPCFG3: csr_rdata_int = {pmp_cfg_rdata[15], pmp_cfg_rdata[14],\n pmp_cfg_rdata[13], pmp_cfg_rdata[12]};\n CSR_PMPADDR0: csr_rdata_int = pmp_addr_rdata[0];\n CSR_PMPADDR1: csr_rdata_int = pmp_addr_rdata[1];\n CSR_PMPADDR2: csr_rdata_int = pmp_addr_rdata[2];\n CSR_PMPADDR3: csr_rdata_int = pmp_addr_rdata[3];\n CSR_PMPADDR4: csr_rdata_int = pmp_addr_rdata[4];\n CSR_PMPADDR5: csr_rdata_int = pmp_addr_rdata[5];\n CSR_PMPADDR6: csr_rdata_int = pmp_addr_rdata[6];\n CSR_PMPADDR7: csr_rdata_int = pmp_addr_rdata[7];\n CSR_PMPADDR8: csr_rdata_int = pmp_addr_rdata[8];\n CSR_PMPADDR9: csr_rdata_int = pmp_addr_rdata[9];\n CSR_PMPADDR10: csr_rdata_int = pmp_addr_rdata[10];\n CSR_PMPADDR11: csr_rdata_int = pmp_addr_rdata[11];\n CSR_PMPADDR12: csr_rdata_int = pmp_addr_rdata[12];\n CSR_PMPADDR13: csr_rdata_int = pmp_addr_rdata[13];\n CSR_PMPADDR14: csr_rdata_int = pmp_addr_rdata[14];\n CSR_PMPADDR15: csr_rdata_int = pmp_addr_rdata[15];\n\n CSR_DCSR: begin\n csr_rdata_int = dcsr_q;\n dbg_csr = 1'b1;\n end\n CSR_DPC: begin\n csr_rdata_int = depc_q;\n dbg_csr = 1'b1;\n end\n CSR_DSCRATCH0: begin\n csr_rdata_int = dscratch0_q;\n dbg_csr = 1'b1;\n end\n CSR_DSCRATCH1: begin\n csr_rdata_int = dscratch1_q;\n dbg_csr = 1'b1;\n end\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: csr_rdata_int = mcountinhibit;\n CSR_MHPMEVENT3,\n CSR_MHPMEVENT4, CSR_MHPMEVENT5, CSR_MHPMEVENT6, CSR_MHPMEVENT7,\n CSR_MHPMEVENT8, CSR_MHPMEVENT9, CSR_MHPMEVENT10, CSR_MHPMEVENT11,\n CSR_MHPMEVENT12, CSR_MHPMEVENT13, CSR_MHPMEVENT14, CSR_MHPMEVENT15,\n CSR_MHPMEVENT16, CSR_MHPMEVENT17, CSR_MHPMEVENT18, CSR_MHPMEVENT19,\n CSR_MHPMEVENT20, CSR_MHPMEVENT21, CSR_MHPMEVENT22, CSR_MHPMEVENT23,\n CSR_MHPMEVENT24, CSR_MHPMEVENT25, CSR_MHPMEVENT26, CSR_MHPMEVENT27,\n CSR_MHPMEVENT28, CSR_MHPMEVENT29, CSR_MHPMEVENT30, CSR_MHPMEVENT31: begin\n csr_rdata_int = mhpmevent[mhpmcounter_idx];\n end\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][31:0];\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][63:32];\n end\n\n // Debug triggers\n CSR_TSELECT: begin\n csr_rdata_int = tselect_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA1: begin\n csr_rdata_int = tmatch_control_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA2: begin\n csr_rdata_int = tmatch_value_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA3: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_MCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_SCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n\n // Custom CSR for controlling CPU features\n CSR_CPUCTRL: begin\n csr_rdata_int = {{32 - $bits(cpu_ctrl_t) {1'b0}}, cpuctrl_q};\n end\n\n // Custom CSR for LFSR re-seeding (cannot be read)\n CSR_SECURESEED: begin\n csr_rdata_int = '0;\n end\n\n default: begin\n illegal_csr = 1'b1;\n end\n endcase\n\n if (!PMPEnable) begin\n if (csr_addr inside {CSR_PMPCFG0, CSR_PMPCFG1, CSR_PMPCFG2, CSR_PMPCFG3,\n CSR_PMPADDR0, CSR_PMPADDR1, CSR_PMPADDR2, CSR_PMPADDR3,\n CSR_PMPADDR4, CSR_PMPADDR5, CSR_PMPADDR6, CSR_PMPADDR7,\n CSR_PMPADDR8, CSR_PMPADDR9, CSR_PMPADDR10, CSR_PMPADDR11,\n CSR_PMPADDR12, CSR_PMPADDR13, CSR_PMPADDR14, CSR_PMPADDR15}) begin\n illegal_csr = 1'b1;\n end\n end\n end\n\n // write logic\n always_comb begin\n exception_pc = pc_id_i;\n\n priv_lvl_d = priv_lvl_q;\n mstatus_en = 1'b0;\n mstatus_d = mstatus_q;\n mie_en = 1'b0;\n mscratch_en = 1'b0;\n mepc_en = 1'b0;\n mepc_d = {csr_wdata_int[31:1], 1'b0};\n mcause_en = 1'b0;\n mcause_d = '{irq_ext : csr_wdata_int[31:30] == 2'b10,\n irq_int : csr_wdata_int[31:30] == 2'b11,\n lower_cause: csr_wdata_int[4:0]};\n mtval_en = 1'b0;\n mtval_d = csr_wdata_int;\n mtvec_en = csr_mtvec_init_i;\n // mtvec.MODE set to vectored\n // mtvec.BASE must be 256-byte aligned\n mtvec_d = csr_mtvec_init_i ? {boot_addr_i[31:8], 6'b0, 2'b01} :\n {csr_wdata_int[31:8], 6'b0, 2'b01};\n dcsr_en = 1'b0;\n dcsr_d = dcsr_q;\n depc_d = {csr_wdata_int[31:1], 1'b0};\n depc_en = 1'b0;\n dscratch0_en = 1'b0;\n dscratch1_en = 1'b0;\n\n mstack_en = 1'b0;\n mstack_d.mpie = mstatus_q.mpie;\n mstack_d.mpp = mstatus_q.mpp;\n mstack_epc_d = mepc_q;\n mstack_cause_d = mcause_q;\n\n mcountinhibit_we = 1'b0;\n mhpmcounter_we = '0;\n mhpmcounterh_we = '0;\n\n cpuctrl_we = 1'b0;\n cpuctrl_d = cpuctrl_q;\n\n double_fault_seen_o = 1'b0;\n\n if (csr_we_int) begin\n unique case (csr_addr_i)\n // mstatus: IE bit\n CSR_MSTATUS: begin\n mstatus_en = 1'b1;\n mstatus_d = '{\n mie: csr_wdata_int[CSR_MSTATUS_MIE_BIT],\n mpie: csr_wdata_int[CSR_MSTATUS_MPIE_BIT],\n mpp: priv_lvl_e'(csr_wdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW]),\n mprv: csr_wdata_int[CSR_MSTATUS_MPRV_BIT],\n tw: csr_wdata_int[CSR_MSTATUS_TW_BIT]\n };\n // Convert illegal values to U-mode\n if ((mstatus_d.mpp != PRIV_LVL_M) && (mstatus_d.mpp != PRIV_LVL_U)) begin\n mstatus_d.mpp = PRIV_LVL_U;\n end\n end\n\n // interrupt enable\n CSR_MIE: mie_en = 1'b1;\n\n CSR_MSCRATCH: mscratch_en = 1'b1;\n\n // mepc: exception program counter\n CSR_MEPC: mepc_en = 1'b1;\n\n // mcause\n CSR_MCAUSE: mcause_en = 1'b1;\n\n // mtval: trap value\n CSR_MTVAL: mtval_en = 1'b1;\n\n // mtvec\n CSR_MTVEC: mtvec_en = 1'b1;\n\n CSR_DCSR: begin\n dcsr_d = csr_wdata_int;\n dcsr_d.xdebugver = XDEBUGVER_STD;\n // Change to PRIV_LVL_U if software writes an unsupported value\n if ((dcsr_d.prv != PRIV_LVL_M) && (dcsr_d.prv != PRIV_LVL_U)) begin\n dcsr_d.prv = PRIV_LVL_U;\n end\n\n // Read-only for SW\n dcsr_d.cause = dcsr_q.cause;\n\n // Interrupts always disabled during single stepping\n dcsr_d.stepie = 1'b0;\n\n // currently not supported:\n dcsr_d.nmip = 1'b0;\n dcsr_d.mprven = 1'b0;\n dcsr_d.stopcount = 1'b0;\n dcsr_d.stoptime = 1'b0;\n\n // forced to be zero\n dcsr_d.zero0 = 1'b0;\n dcsr_d.zero1 = 1'b0;\n dcsr_d.zero2 = 12'h0;\n dcsr_en = 1'b1;\n end\n\n // dpc: debug program counter\n CSR_DPC: depc_en = 1'b1;\n\n CSR_DSCRATCH0: dscratch0_en = 1'b1;\n CSR_DSCRATCH1: dscratch1_en = 1'b1;\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: mcountinhibit_we = 1'b1;\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n mhpmcounter_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n mhpmcounterh_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_CPUCTRL: begin\n cpuctrl_d = cpuctrl_wdata;\n cpuctrl_we = 1'b1;\n end\n\n default:;\n endcase\n end\n\n // exception controller gets priority over other writes\n unique case (1'b1)\n\n csr_save_cause_i: begin\n unique case (1'b1)\n csr_save_if_i: begin\n exception_pc = pc_if_i;\n end\n csr_save_id_i: begin\n exception_pc = pc_id_i;\n end\n csr_save_wb_i: begin\n exception_pc = pc_wb_i;\n end\n default:;\n endcase\n\n // Any exception, including debug mode, causes a switch to M-mode\n priv_lvl_d = PRIV_LVL_M;\n\n if (debug_csr_save_i) begin\n // all interrupts are masked\n // do not update cause, epc, tval, epc and status\n dcsr_d.prv = priv_lvl_q;\n dcsr_d.cause = debug_cause_i;\n dcsr_en = 1'b1;\n depc_d = exception_pc;\n depc_en = 1'b1;\n end else if (!debug_mode_i) begin\n // In debug mode, \"exceptions do not update any registers. That\n // includes cause, epc, tval, dpc and mstatus.\" [Debug Spec v0.13.2, p.39]\n mtval_en = 1'b1;\n mtval_d = csr_mtval_i;\n mstatus_en = 1'b1;\n mstatus_d.mie = 1'b0; // disable interrupts\n // save current status\n mstatus_d.mpie = mstatus_q.mie;\n mstatus_d.mpp = priv_lvl_q;\n mepc_en = 1'b1;\n mepc_d = exception_pc;\n mcause_en = 1'b1;\n mcause_d = csr_mcause_i;\n // save previous status for recoverable NMI\n mstack_en = 1'b1;\n\n if (!(mcause_d.irq_ext || mcause_d.irq_int)) begin\n // SEC_CM: EXCEPTION.CTRL_FLOW.LOCAL_ESC\n // SEC_CM: EXCEPTION.CTRL_FLOW.GLOBAL_ESC\n cpuctrl_we = 1'b1;\n\n cpuctrl_d.sync_exc_seen = 1'b1;\n if (cpuctrl_q.sync_exc_seen) begin\n double_fault_seen_o = 1'b1;\n cpuctrl_d.double_fault_seen = 1'b1;\n end\n end\n end\n end // csr_save_cause_i\n\n csr_restore_dret_i: begin // DRET\n priv_lvl_d = dcsr_q.prv;\n end // csr_restore_dret_i\n\n csr_restore_mret_i: begin // MRET\n priv_lvl_d = mstatus_q.mpp;\n mstatus_en = 1'b1;\n mstatus_d.mie = mstatus_q.mpie; // re-enable interrupts\n\n // SEC_CM: EXCEPTION.CTRL_FLOW.LOCAL_ESC\n // SEC_CM: EXCEPTION.CTRL_FLOW.GLOBAL_ESC\n cpuctrl_we = 1'b1;\n cpuctrl_d.sync_exc_seen = 1'b0;\n\n if (nmi_mode_i) begin\n // when returning from an NMI restore state from mstack CSR\n mstatus_d.mpie = mstack_q.mpie;\n mstatus_d.mpp = mstack_q.mpp;\n mepc_en = 1'b1;\n mepc_d = mstack_epc_q;\n mcause_en = 1'b1;\n mcause_d = mstack_cause_q;\n end else begin\n // otherwise just set mstatus.MPIE/MPP\n // See RISC-V Privileged Specification, version 1.11, Section 3.1.6.1\n mstatus_d.mpie = 1'b1;\n mstatus_d.mpp = PRIV_LVL_U;\n end\n end // csr_restore_mret_i\n\n default:;\n endcase\n end\n\n // Update current priv level\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n priv_lvl_q <= PRIV_LVL_M;\n end else begin\n priv_lvl_q <= priv_lvl_d;\n end\n end\n\n // Send current priv level to the decoder\n assign priv_mode_id_o = priv_lvl_q;\n // Load/store instructions must factor in MPRV for PMP checking\n assign priv_mode_lsu_o = mstatus_q.mprv ? mstatus_q.mpp : priv_lvl_q;\n\n // CSR operation logic\n always_comb begin\n unique case (csr_op_i)\n CSR_OP_WRITE: csr_wdata_int = csr_wdata_i;\n CSR_OP_SET: csr_wdata_int = csr_wdata_i | csr_rdata_o;\n CSR_OP_CLEAR: csr_wdata_int = ~csr_wdata_i & csr_rdata_o;\n CSR_OP_READ: csr_wdata_int = csr_wdata_i;\n default: csr_wdata_int = csr_wdata_i;\n endcase\n end\n\n assign csr_wr = (csr_op_i inside {CSR_OP_WRITE, CSR_OP_SET, CSR_OP_CLEAR});\n\n // only write CSRs during one clock cycle\n assign csr_we_int = csr_wr & csr_op_en_i & ~illegal_csr_insn_o;\n\n assign csr_rdata_o = csr_rdata_int;\n\n // directly output some registers\n assign csr_mepc_o = mepc_q;\n assign csr_depc_o = depc_q;\n assign csr_mtvec_o = mtvec_q;\n assign csr_mtval_o = mtval_q;\n\n assign csr_mstatus_mie_o = mstatus_q.mie;\n assign csr_mstatus_tw_o = mstatus_q.tw;\n assign debug_single_step_o = dcsr_q.step;\n assign debug_ebreakm_o = dcsr_q.ebreakm;\n assign debug_ebreaku_o = dcsr_q.ebreaku;\n\n // Qualify incoming interrupt requests in mip CSR with mie CSR for controller and to re-enable\n // clock upon WFI (must be purely combinational).\n assign irqs_o = mip & mie_q;\n assign irq_pending_o = |irqs_o;\n\n ////////////////////////\n // CSR instantiations //\n ////////////////////////\n\n // MSTATUS\n localparam status_t MSTATUS_RST_VAL = '{mie: 1'b0,\n mpie: 1'b1,\n mpp: PRIV_LVL_U,\n mprv: 1'b0,\n tw: 1'b0};\n ibex_csr #(\n .Width ($bits(status_t)),\n .ShadowCopy(ShadowCSR),\n .ResetValue({MSTATUS_RST_VAL})\n ) u_mstatus_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mstatus_d}),\n .wr_en_i (mstatus_en),\n .rd_data_o (mstatus_q),\n .rd_error_o(mstatus_err)\n );\n\n // MEPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_mepc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mepc_d),\n .wr_en_i (mepc_en),\n .rd_data_o (mepc_q),\n .rd_error_o()\n );\n\n // MIE\n assign mie_d.irq_software = csr_wdata_int[CSR_MSIX_BIT];\n assign mie_d.irq_timer = csr_wdata_int[CSR_MTIX_BIT];\n assign mie_d.irq_external = csr_wdata_int[CSR_MEIX_BIT];\n assign mie_d.irq_fast = csr_wdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW];\n ibex_csr #(\n .Width ($bits(irqs_t)),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_mie_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mie_d}),\n .wr_en_i (mie_en),\n .rd_data_o (mie_q),\n .rd_error_o()\n );\n\n // MSCRATCH\n ibex_csr #(\n .Width (32),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_mscratch_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (mscratch_en),\n .rd_data_o (mscratch_q),\n .rd_error_o()\n );\n\n // MCAUSE\n ibex_csr #(\n .Width ($bits(exc_cause_t)),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_mcause_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mcause_d}),\n .wr_en_i (mcause_en),\n .rd_data_o (mcause_q),\n .rd_error_o()\n );\n\n // MTVAL\n ibex_csr #(\n .Width (32),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_mtval_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mtval_d),\n .wr_en_i (mtval_en),\n .rd_data_o (mtval_q),\n .rd_error_o()\n );\n\n // MTVEC\n ibex_csr #(\n .Width (32),\n .ShadowCopy(ShadowCSR),\n .ResetValue(32'd1)\n ) u_mtvec_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mtvec_d),\n .wr_en_i (mtvec_en),\n .rd_data_o (mtvec_q),\n .rd_error_o(mtvec_err)\n );\n\n // DCSR\n localparam dcsr_t DCSR_RESET_VAL = '{\n xdebugver: XDEBUGVER_STD,\n cause: DBG_CAUSE_NONE, // 3'h0\n prv: PRIV_LVL_M,\n default: '0\n };\n ibex_csr #(\n .Width ($bits(dcsr_t)),\n .ShadowCopy(1'b0),\n .ResetValue({DCSR_RESET_VAL})\n ) u_dcsr_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({dcsr_d}),\n .wr_en_i (dcsr_en),\n .rd_data_o (dcsr_q),\n .rd_error_o()\n );\n\n // DEPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_depc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (depc_d),\n .wr_en_i (depc_en),\n .rd_data_o (depc_q),\n .rd_error_o()\n );\n\n // DSCRATCH0\n ibex_csr #(\n .Width (32),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_dscratch0_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (dscratch0_en),\n .rd_data_o (dscratch0_q),\n .rd_error_o()\n );\n\n // DSCRATCH1\n ibex_csr #(\n .Width (32),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_dscratch1_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (dscratch1_en),\n .rd_data_o (dscratch1_q),\n .rd_error_o()\n );\n\n // MSTACK\n localparam status_stk_t MSTACK_RESET_VAL = '{mpie: 1'b1, mpp: PRIV_LVL_U};\n ibex_csr #(\n .Width ($bits(status_stk_t)),\n .ShadowCopy(1'b0),\n .ResetValue({MSTACK_RESET_VAL})\n ) u_mstack_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mstack_d}),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_q),\n .rd_error_o()\n );\n\n // MSTACK_EPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_mstack_epc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mstack_epc_d),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_epc_q),\n .rd_error_o()\n );\n\n // MSTACK_CAUSE\n ibex_csr #(\n .Width ($bits(exc_cause_t)),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_mstack_cause_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mstack_cause_d),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_cause_q),\n .rd_error_o()\n );\n\n // -----------------\n // PMP registers\n // -----------------\n\n if (PMPEnable) begin : g_pmp_registers\n // PMP reset values\n `ifdef IBEX_CUSTOM_PMP_RESET_VALUES\n `include \"ibex_pmp_reset.svh\"\n `else\n `include \"ibex_pmp_reset_default.svh\"\n `endif\n\n pmp_mseccfg_t pmp_mseccfg_q, pmp_mseccfg_d;\n logic pmp_mseccfg_we;\n logic pmp_mseccfg_err;\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_locked;\n logic [PMPNumRegions-1:0] pmp_cfg_wr_suppress;\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n logic [PMPAddrWidth-1:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n logic [PMPNumRegions-1:0] pmp_cfg_err;\n logic [PMPNumRegions-1:0] pmp_addr_we;\n logic [PMPNumRegions-1:0] pmp_addr_err;\n logic any_pmp_entry_locked;\n\n // Expanded / qualified register read data\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_exp_rd_data\n if (i < PMPNumRegions) begin : g_implemented_regions\n // Add in zero padding for reserved fields\n assign pmp_cfg_rdata[i] = {pmp_cfg[i].lock, 2'b00, pmp_cfg[i].mode,\n pmp_cfg[i].exec, pmp_cfg[i].write, pmp_cfg[i].read};\n\n // Address field read data depends on the current programmed mode and the granularity\n // See RISC-V Privileged Specification, version 1.11, Section 3.6.1\n if (PMPGranularity == 0) begin : g_pmp_g0\n // If G == 0, read data is unmodified\n assign pmp_addr_rdata[i] = pmp_addr[i];\n\n end else if (PMPGranularity == 1) begin : g_pmp_g1\n // If G == 1, bit [G-1] reads as zero in TOR or OFF mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n\n end else begin : g_pmp_g2\n // For G >= 2, bits are masked to one or zero depending on the mode\n always_comb begin\n // In NAPOT mode, bits [G-2:0] must read as one\n pmp_addr_rdata[i] = {pmp_addr[i], {PMPGranularity - 1{1'b1}}};\n\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n // In TOR or OFF mode, bits [G-1:0] must read as zero\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n end\n\n end else begin : g_other_regions\n // Non-implemented regions read as zero\n assign pmp_cfg_rdata[i] = '0;\n assign pmp_addr_rdata[i] = '0;\n end\n end\n\n // Write data calculation\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_pmp_csrs\n // -------------------------\n // Instantiate cfg registers\n // -------------------------\n assign pmp_cfg_we[i] = csr_we_int &\n ~pmp_cfg_locked[i] &\n ~pmp_cfg_wr_suppress[i] &\n (csr_addr == (CSR_OFF_PMP_CFG + (i[11:0] >> 2)));\n\n // Select the correct WDATA (each CSR contains 4 CFG fields, each with 2 RES bits)\n assign pmp_cfg_wdata[i].lock = csr_wdata_int[(i%4)*PMP_CFG_W+7];\n // NA4 mode is not selectable when G > 0, mode is treated as OFF\n always_comb begin\n unique case (csr_wdata_int[(i%4)*PMP_CFG_W+3+:2])\n 2'b00 : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n 2'b01 : pmp_cfg_wdata[i].mode = PMP_MODE_TOR;\n 2'b10 : pmp_cfg_wdata[i].mode = (PMPGranularity == 0) ? PMP_MODE_NA4:\n PMP_MODE_OFF;\n 2'b11 : pmp_cfg_wdata[i].mode = PMP_MODE_NAPOT;\n default : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n endcase\n end\n assign pmp_cfg_wdata[i].exec = csr_wdata_int[(i%4)*PMP_CFG_W+2];\n // When MSECCFG.MML is unset, W = 1, R = 0 is a reserved combination, so force W to 0 if R ==\n // 0. Otherwise allow all possible values to be written.\n assign pmp_cfg_wdata[i].write = pmp_mseccfg_q.mml ? csr_wdata_int[(i%4)*PMP_CFG_W+1] :\n &csr_wdata_int[(i%4)*PMP_CFG_W+:2];\n assign pmp_cfg_wdata[i].read = csr_wdata_int[(i%4)*PMP_CFG_W];\n\n ibex_csr #(\n .Width ($bits(pmp_cfg_t)),\n .ShadowCopy(ShadowCSR),\n .ResetValue(pmp_cfg_rst[i])\n ) u_pmp_cfg_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({pmp_cfg_wdata[i]}),\n .wr_en_i (pmp_cfg_we[i]),\n .rd_data_o (pmp_cfg[i]),\n .rd_error_o(pmp_cfg_err[i])\n );\n\n // MSECCFG.RLB allows the lock bit to be bypassed (allowing cfg writes when MSECCFG.RLB is\n // set).\n assign pmp_cfg_locked[i] = pmp_cfg[i].lock & ~pmp_mseccfg_q.rlb;\n\n // When MSECCFG.MML is set cannot add new regions allowing M mode execution unless MSECCFG.RLB\n // is set\n assign pmp_cfg_wr_suppress[i] = pmp_mseccfg_q.mml &\n ~pmp_mseccfg.rlb &\n is_mml_m_exec_cfg(pmp_cfg_wdata[i]);\n\n // --------------------------\n // Instantiate addr registers\n // --------------------------\n if (i < PMPNumRegions - 1) begin : g_lower\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg_locked[i] &\n (~pmp_cfg_locked[i+1] | (pmp_cfg[i+1].mode != PMP_MODE_TOR)) &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end else begin : g_upper\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg_locked[i] &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end\n\n ibex_csr #(\n .Width (PMPAddrWidth),\n .ShadowCopy(ShadowCSR),\n .ResetValue(pmp_addr_rst[i][33-:PMPAddrWidth])\n ) u_pmp_addr_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int[31-:PMPAddrWidth]),\n .wr_en_i (pmp_addr_we[i]),\n .rd_data_o (pmp_addr[i]),\n .rd_error_o(pmp_addr_err[i])\n );\n\n `ASSERT_INIT(PMPAddrRstLowBitsZero_A, pmp_addr_rst[i][33-PMPAddrWidth:0] == '0)\n\n assign csr_pmp_cfg_o[i] = pmp_cfg[i];\n assign csr_pmp_addr_o[i] = {pmp_addr_rdata[i], 2'b00};\n end\n\n assign pmp_mseccfg_we = csr_we_int & (csr_addr == CSR_MSECCFG);\n\n // MSECCFG.MML/MSECCFG.MMWP cannot be unset once set\n assign pmp_mseccfg_d.mml = pmp_mseccfg_q.mml ? 1'b1 : csr_wdata_int[CSR_MSECCFG_MML_BIT];\n assign pmp_mseccfg_d.mmwp = pmp_mseccfg_q.mmwp ? 1'b1 : csr_wdata_int[CSR_MSECCFG_MMWP_BIT];\n\n // pmp_cfg_locked factors in MSECCFG.RLB so any_pmp_entry_locked will only be set if MSECCFG.RLB\n // is unset\n assign any_pmp_entry_locked = |pmp_cfg_locked;\n\n // When any PMP entry is locked (A PMP entry has the L bit set and MSECCFG.RLB is unset),\n // MSECCFG.RLB cannot be set again\n assign pmp_mseccfg_d.rlb = any_pmp_entry_locked ? 1'b0 : csr_wdata_int[CSR_MSECCFG_RLB_BIT];\n\n ibex_csr #(\n .Width ($bits(pmp_mseccfg_t)),\n .ShadowCopy(ShadowCSR),\n .ResetValue(pmp_mseccfg_rst)\n ) u_pmp_mseccfg (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (pmp_mseccfg_d),\n .wr_en_i (pmp_mseccfg_we),\n .rd_data_o (pmp_mseccfg_q),\n .rd_error_o(pmp_mseccfg_err)\n );\n\n assign pmp_csr_err = (|pmp_cfg_err) | (|pmp_addr_err) | pmp_mseccfg_err;\n assign pmp_mseccfg = pmp_mseccfg_q;\n\n end else begin : g_no_pmp_tieoffs\n // Generate tieoffs when PMP is not configured\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_rdata\n assign pmp_addr_rdata[i] = '0;\n assign pmp_cfg_rdata[i] = '0;\n end\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_outputs\n assign csr_pmp_cfg_o[i] = pmp_cfg_t'(1'b0);\n assign csr_pmp_addr_o[i] = '0;\n end\n assign pmp_csr_err = 1'b0;\n assign pmp_mseccfg = '0;\n end\n\n assign csr_pmp_mseccfg_o = pmp_mseccfg;\n\n //////////////////////////\n // Performance monitor //\n //////////////////////////\n\n // update enable signals\n always_comb begin : mcountinhibit_update\n if (mcountinhibit_we == 1'b1) begin\n // bit 1 must always be 0\n mcountinhibit_d = {csr_wdata_int[MHPMCounterNum+2:2], 1'b0, csr_wdata_int[0]};\n end else begin\n mcountinhibit_d = mcountinhibit_q;\n end\n end\n\n // event selection (hardwired) & control\n always_comb begin : gen_mhpmcounter_incr\n\n // Assign inactive counters (first to prevent latch inference)\n for (int unsigned i = 0; i < 32; i++) begin : gen_mhpmcounter_incr_inactive\n mhpmcounter_incr[i] = 1'b0;\n end\n\n // When adding or altering performance counter meanings and default\n // mappings please update dv/verilator/pcount/cpp/ibex_pcounts.cc\n // appropriately.\n //\n // active counters\n mhpmcounter_incr[0] = 1'b1; // mcycle\n mhpmcounter_incr[1] = 1'b0; // reserved\n mhpmcounter_incr[2] = instr_ret_i; // minstret\n mhpmcounter_incr[3] = dside_wait_i; // cycles waiting for data memory\n mhpmcounter_incr[4] = iside_wait_i; // cycles waiting for instr fetches\n mhpmcounter_incr[5] = mem_load_i; // num of loads\n mhpmcounter_incr[6] = mem_store_i; // num of stores\n mhpmcounter_incr[7] = jump_i; // num of jumps (unconditional)\n mhpmcounter_incr[8] = branch_i; // num of branches (conditional)\n mhpmcounter_incr[9] = branch_taken_i; // num of taken branches (conditional)\n mhpmcounter_incr[10] = instr_ret_compressed_i; // num of compressed instr\n mhpmcounter_incr[11] = mul_wait_i; // cycles waiting for multiply\n mhpmcounter_incr[12] = div_wait_i; // cycles waiting for divide\n end\n\n // event selector (hardwired, 0 means no event)\n always_comb begin : gen_mhpmevent\n\n // activate all\n for (int i = 0; i < 32; i++) begin : gen_mhpmevent_active\n mhpmevent[i] = '0;\n\n if (i >= 3) begin\n mhpmevent[i][i - 3] = 1'b1;\n end\n end\n\n // deactivate\n mhpmevent[1] = '0; // not existing, reserved\n for (int unsigned i = 3 + MHPMCounterNum; i < 32; i++) begin : gen_mhpmevent_inactive\n mhpmevent[i] = '0;\n end\n end\n\n // mcycle\n ibex_counter #(\n .CounterWidth(64)\n ) mcycle_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[0] & ~mcountinhibit[0]),\n .counterh_we_i(mhpmcounterh_we[0]),\n .counter_we_i(mhpmcounter_we[0]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[0]),\n .counter_val_upd_o()\n );\n\n\n // minstret\n ibex_counter #(\n .CounterWidth(64),\n .ProvideValUpd(1)\n ) minstret_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[2] & ~mcountinhibit[2]),\n .counterh_we_i(mhpmcounterh_we[2]),\n .counter_we_i(mhpmcounter_we[2]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(minstret_raw),\n .counter_val_upd_o(minstret_next)\n );\n\n // Where the writeback stage is present instruction in ID observing value of minstret must take\n // into account any instruction in the writeback stage. If one is present the incremented value of\n // minstret is used. A speculative version of the signal is used to aid timing. When the writeback\n // stage sees an exception (so the speculative signal is incorrect) the ID stage will be flushed\n // so the incorrect value doesn't matter. A similar behaviour is required for the compressed\n // instruction retired counter below. When the writeback stage isn't present the speculative\n // signals are always 0.\n assign mhpmcounter[2] = instr_ret_spec_i & ~mcountinhibit[2] ? minstret_next : minstret_raw;\n\n // reserved:\n assign mhpmcounter[1] = '0;\n assign unused_mhpmcounter_we_1 = mhpmcounter_we[1];\n assign unused_mhpmcounterh_we_1 = mhpmcounterh_we[1];\n assign unused_mhpmcounter_incr_1 = mhpmcounter_incr[1];\n\n // Iterate through optionally included counters (MHPMCounterNum controls how many are included)\n for (genvar i = 0; i < 29; i++) begin : gen_cntrs\n localparam int Cnt = i + 3;\n\n if (i < MHPMCounterNum) begin : gen_imp\n logic [63:0] mhpmcounter_raw, mhpmcounter_next;\n\n ibex_counter #(\n .CounterWidth(MHPMCounterWidth),\n .ProvideValUpd(Cnt == 10)\n ) mcounters_variable_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[Cnt] & ~mcountinhibit[Cnt]),\n .counterh_we_i(mhpmcounterh_we[Cnt]),\n .counter_we_i(mhpmcounter_we[Cnt]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter_raw),\n .counter_val_upd_o(mhpmcounter_next)\n );\n\n if (Cnt == 10) begin : gen_compressed_instr_cnt\n // Special behaviour for reading compressed instruction retired counter, see comment on\n // `mhpmcounter[2]` above for further information.\n assign mhpmcounter[Cnt] =\n instr_ret_compressed_spec_i & ~mcountinhibit[Cnt] ? mhpmcounter_next:\n mhpmcounter_raw;\n end else begin : gen_other_cnts\n logic [63:0] unused_mhpmcounter_next;\n // All other counters just see the raw counter value directly.\n assign mhpmcounter[Cnt] = mhpmcounter_raw;\n assign unused_mhpmcounter_next = mhpmcounter_next;\n end\n end else begin : gen_unimp\n assign mhpmcounter[Cnt] = '0;\n\n if (Cnt == 10) begin : gen_no_compressed_instr_cnt\n logic unused_instr_ret_compressed_spec_i;\n assign unused_instr_ret_compressed_spec_i = instr_ret_compressed_spec_i;\n end\n end\n end\n\n if (MHPMCounterNum < 29) begin : g_mcountinhibit_reduced\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounterh_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_incr;\n\n assign mcountinhibit = {{29 - MHPMCounterNum{1'b0}}, mcountinhibit_q};\n // Lint tieoffs for unused bits\n assign unused_mhphcounter_we = mhpmcounter_we[31:MHPMCounterNum+3];\n assign unused_mhphcounterh_we = mhpmcounterh_we[31:MHPMCounterNum+3];\n assign unused_mhphcounter_incr = mhpmcounter_incr[31:MHPMCounterNum+3];\n end else begin : g_mcountinhibit_full\n assign mcountinhibit = mcountinhibit_q;\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n mcountinhibit_q <= '0;\n end else begin\n mcountinhibit_q <= mcountinhibit_d;\n end\n end\n\n /////////////////////////////\n // Debug trigger registers //\n /////////////////////////////\n\n if (DbgTriggerEn) begin : gen_trigger_regs\n localparam int unsigned DbgHwNumLen = DbgHwBreakNum > 1 ? $clog2(DbgHwBreakNum) : 1;\n localparam int unsigned MaxTselect = DbgHwBreakNum - 1;\n\n // Register values\n logic [DbgHwNumLen-1:0] tselect_d, tselect_q;\n logic tmatch_control_d;\n logic [DbgHwBreakNum-1:0] tmatch_control_q;\n logic [31:0] tmatch_value_d;\n logic [31:0] tmatch_value_q[DbgHwBreakNum];\n logic selected_tmatch_control;\n logic [31:0] selected_tmatch_value;\n\n // Write enables\n logic tselect_we;\n logic [DbgHwBreakNum-1:0] tmatch_control_we;\n logic [DbgHwBreakNum-1:0] tmatch_value_we;\n // Trigger comparison result\n logic [DbgHwBreakNum-1:0] trigger_match;\n\n // Write select\n assign tselect_we = csr_we_int & debug_mode_i & (csr_addr_i == CSR_TSELECT);\n for (genvar i = 0; i < DbgHwBreakNum; i++) begin : g_dbg_tmatch_we\n assign tmatch_control_we[i] = (i[DbgHwNumLen-1:0] == tselect_q) & csr_we_int & debug_mode_i &\n (csr_addr_i == CSR_TDATA1);\n assign tmatch_value_we[i] = (i[DbgHwNumLen-1:0] == tselect_q) & csr_we_int & debug_mode_i &\n (csr_addr_i == CSR_TDATA2);\n end\n\n // Debug interface tests the available number of triggers by writing and reading the trigger\n // select register. Only allow changes to the register if it is within the supported region.\n assign tselect_d = (csr_wdata_int < DbgHwBreakNum) ? csr_wdata_int[DbgHwNumLen-1:0] :\n MaxTselect[DbgHwNumLen-1:0];\n\n // tmatch_control is enabled when the execute bit is set\n assign tmatch_control_d = csr_wdata_int[2];\n assign tmatch_value_d = csr_wdata_int[31:0];\n\n // Registers\n ibex_csr #(\n .Width (DbgHwNumLen),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_tselect_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tselect_d),\n .wr_en_i (tselect_we),\n .rd_data_o (tselect_q),\n .rd_error_o()\n );\n\n for (genvar i = 0; i < DbgHwBreakNum; i++) begin : g_dbg_tmatch_reg\n ibex_csr #(\n .Width (1),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_tmatch_control_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tmatch_control_d),\n .wr_en_i (tmatch_control_we[i]),\n .rd_data_o (tmatch_control_q[i]),\n .rd_error_o()\n );\n\n ibex_csr #(\n .Width (32),\n .ShadowCopy(1'b0),\n .ResetValue('0)\n ) u_tmatch_value_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tmatch_value_d),\n .wr_en_i (tmatch_value_we[i]),\n .rd_data_o (tmatch_value_q[i]),\n .rd_error_o()\n );\n end\n\n // Assign read data\n // TSELECT - number of supported triggers defined by parameter DbgHwBreakNum\n localparam int unsigned TSelectRdataPadlen = DbgHwNumLen >= 32 ? 0 : (32 - DbgHwNumLen);\n assign tselect_rdata = {{TSelectRdataPadlen{1'b0}}, tselect_q};\n\n if (DbgHwBreakNum > 1) begin : g_dbg_tmatch_multiple_select\n assign selected_tmatch_control = tmatch_control_q[tselect_q];\n assign selected_tmatch_value = tmatch_value_q[tselect_q];\n end else begin : g_dbg_tmatch_single_select\n assign selected_tmatch_control = tmatch_control_q[0];\n assign selected_tmatch_value = tmatch_value_q[0];\n end\n\n // TDATA0 - only support simple address matching\n assign tmatch_control_rdata = {4'h2, // type : address/data match\n 1'b1, // dmode : access from D mode only\n 6'h00, // maskmax : exact match only\n 1'b0, // hit : not supported\n 1'b0, // select : address match only\n 1'b0, // timing : match before execution\n 2'b00, // sizelo : match any access\n 4'h1, // action : enter debug mode\n 1'b0, // chain : not supported\n 4'h0, // match : simple match\n 1'b1, // m : match in m-mode\n 1'b0, // 0 : zero\n 1'b0, // s : not supported\n 1'b1, // u : match in u-mode\n selected_tmatch_control, // execute : match instruction address\n 1'b0, // store : not supported\n 1'b0}; // load : not supported\n\n // TDATA1 - address match value only\n assign tmatch_value_rdata = selected_tmatch_value;\n\n // Breakpoint matching\n // We match against the next address, as the breakpoint must be taken before execution\n for (genvar i = 0; i < DbgHwBreakNum; i++) begin : g_dbg_trigger_match\n assign trigger_match[i] = tmatch_control_q[i] & (pc_if_i[31:0] == tmatch_value_q[i]);\n end\n assign trigger_match_o = |trigger_match;\n\n end else begin : gen_no_trigger_regs\n assign tselect_rdata = 'b0;\n assign tmatch_control_rdata = 'b0;\n assign tmatch_value_rdata = 'b0;\n assign trigger_match_o = 'b0;\n end\n\n //////////////////////////\n // CPU control register //\n //////////////////////////\n\n // Cast register write data\n assign cpuctrl_wdata_raw = cpu_ctrl_t'(csr_wdata_int[$bits(cpu_ctrl_t)-1:0]);\n\n // Generate fixed time execution bit\n if (DataIndTiming) begin : gen_dit\n // SEC_CM: CORE.DATA_REG_SW.SCA\n assign cpuctrl_wdata.data_ind_timing = cpuctrl_wdata_raw.data_ind_timing;\n\n end else begin : gen_no_dit\n // tieoff for the unused bit\n logic unused_dit;\n assign unused_dit = cpuctrl_wdata_raw.data_ind_timing;\n\n // field will always read as zero if not configured\n assign cpuctrl_wdata.data_ind_timing = 1'b0;\n end\n\n assign data_ind_timing_o = cpuctrl_q.data_ind_timing;\n\n // Generate dummy instruction signals\n if (DummyInstructions) begin : gen_dummy\n // SEC_CM: CTRL_FLOW.UNPREDICTABLE\n assign cpuctrl_wdata.dummy_instr_en = cpuctrl_wdata_raw.dummy_instr_en;\n assign cpuctrl_wdata.dummy_instr_mask = cpuctrl_wdata_raw.dummy_instr_mask;\n\n // Signal a write to the seed register\n assign dummy_instr_seed_en_o = csr_we_int && (csr_addr == CSR_SECURESEED);\n assign dummy_instr_seed_o = csr_wdata_int;\n\n end else begin : gen_no_dummy\n // tieoff for the unused bit\n logic unused_dummy_en;\n logic [2:0] unused_dummy_mask;\n assign unused_dummy_en = cpuctrl_wdata_raw.dummy_instr_en;\n assign unused_dummy_mask = cpuctrl_wdata_raw.dummy_instr_mask;\n\n // field will always read as zero if not configured\n assign cpuctrl_wdata.dummy_instr_en = 1'b0;\n assign cpuctrl_wdata.dummy_instr_mask = 3'b000;\n assign dummy_instr_seed_en_o = 1'b0;\n assign dummy_instr_seed_o = '0;\n end\n\n assign dummy_instr_en_o = cpuctrl_q.dummy_instr_en;\n assign dummy_instr_mask_o = cpuctrl_q.dummy_instr_mask;\n\n // Generate icache enable bit\n if (ICache) begin : gen_icache_enable\n assign cpuctrl_wdata.icache_enable = cpuctrl_wdata_raw.icache_enable;\n end else begin : gen_no_icache\n // tieoff for the unused icen bit\n logic unused_icen;\n assign unused_icen = cpuctrl_wdata_raw.icache_enable;\n\n // icen field will always read as zero if ICache not configured\n assign cpuctrl_wdata.icache_enable = 1'b0;\n end\n\n assign cpuctrl_wdata.double_fault_seen = cpuctrl_wdata_raw.double_fault_seen;\n assign cpuctrl_wdata.sync_exc_seen = cpuctrl_wdata_raw.sync_exc_seen;\n\n assign icache_enable_o = cpuctrl_q.icache_enable;\n\n ibex_csr #(\n .Width ($bits(cpu_ctrl_t)),\n .ShadowCopy(ShadowCSR),\n .ResetValue('0)\n ) u_cpuctrl_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({cpuctrl_d}),\n .wr_en_i (cpuctrl_we),\n .rd_data_o (cpuctrl_q),\n .rd_error_o(cpuctrl_err)\n );\n\n assign csr_shadow_err_o = mstatus_err | mtvec_err | pmp_csr_err | cpuctrl_err;\n\n ////////////////\n // Assertions //\n ////////////////\n\n `ASSERT(IbexCsrOpEnRequiresAccess, csr_op_en_i |-> csr_access_i)\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/cs_registers.rst", "doc/03_reference/debug.rst", "doc/03_reference/exception_interrupts.rst", "doc/03_reference/performance_counters.rst", "doc/03_reference/pmp.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1824, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# ibex_controller Behavioral Specification\n\n## Overview\n\nThe ibex_controller is the main control unit of the Ibex RISC‑V processor. It governs the flow of instructions through the pipeline, responds to exceptions and interrupts, manages debug mode entry and exit, and controls the instruction fetch unit. The controller operates as a finite state machine with the following major responsibilities:\n\n- **Reset and boot** – set the initial program counter and start instruction fetch. \n- **Normal execution** – coordinate instruction decode and execute, handle branches and jumps. \n- **Exception handling** – detect, prioritize, and service synchronous exceptions (instruction fetch faults, illegal instructions, ecall, ebreak, load/store faults). \n- **Interrupt handling** – service asynchronous interrupts (NMI, fast interrupts, external, timer, software) with configurable priority. \n- **Debug mode control** – enter/leave debug mode in response to external requests, single‑step, or trigger matches. \n- **Power management** – enter a low‑power sleep state when a WFI instruction is executed. \n- **Pipeline management** – generate stall, flush, and instruction valid signals to control the IF‑ID and optional writeback pipeline registers.\n\nThe controller’s behavior is parametric: it can be configured with or without a third (writeback) pipeline stage, with or without a branch predictor, and with or without memory‑ECC support (which adds an internal NMI source).\n\n---\n\n## Reset and Boot Sequence\n\nWhen the core is brought out of reset, the controller shall:\n\n1. Force the PC to the boot address (supplied by external logic). \n2. Instruct the prefetcher to begin fetching from that address. \n3. Transition to a state that waits for the first instruction to arrive. \n4. Once the instruction fetch unit has a valid instruction, the controller enters normal decode mode.\n\nDuring reset no instruction requests are made. The first instruction is fetched with the boot address and the core starts executing at that location.\n\n---\n\n## Normal Instruction Flow (Decode and Execute)\n\nIn the normal operating state (DECODE), the controller:\n\n- Allows the ID/EX stage to process the current instruction. \n- Monitors the decoder outputs for special instructions (e.g., ecall, mret, wfi). \n- Monitors for branch and jump requests from the execute logic. \n- Handles interrupts and debug requests when no multi‑cycle instruction is pending and no exception is active.\n\n### Branch and Jump Handling\n\nWhen a branch or jump instruction is executed:\n\n- The controller shall redirect the instruction fetch to the target PC. \n- If the branch predictor is enabled and a branch was predicted taken but is actually not taken, the controller shall signal a mispredict and flush the IF stage. \n- If the branch predictor is disabled, the controller directly forces the PC update. \n\nThe controller also outputs performance counting signals: one for taken branch instructions and one for jump instructions.\n\n### Multi‑Cycle and Stalled Instructions\n\nIf the current instruction cannot complete in one cycle (e.g., a load, store, multiply, or division), the controller shall stall the ID stage and pause instruction fetch until the operation finishes. The writeback stage (if present) may also cause stalls when it cannot accept a result. Stalls are coordinated so that pipeline ordering is preserved.\n\n---\n\n## Exception Handling\n\nThe controller detects and prioritizes synchronous exceptions as follows (highest priority first), with the exception that when a writeback stage is present, store/load errors from writeback take priority over exceptions from the ID stage:\n\n1. **Store access fault** – from writeback (if present) or from ID/EX. \n2. **Load access fault** – from writeback (if present) or from ID/EX. \n3. **Instruction access fault** – from the instruction fetch unit. \n4. **Illegal instruction** – reported by the decoder. \n5. **ECALL instruction** – environment call. \n6. **EBREAK instruction** – breakpoint (may instead enter debug mode if appropriate CSR bits are set).\n\nWhen any exception is taken, the controller shall:\n\n- Flush instructions that are currently in the IF and ID stages. \n- Save the relevant PC to `mepc` (or `dpc` if inside debug mode). \n- Save the current privilege mode and interrupt enable state to `mstatus`. \n- Set `mcause` to the appropriate exception code. \n- Optionally set `mtval` to a faulting address or instruction encoding. \n- Redirect the fetch PC to the trap handler address (from `mtvec`). \n- Await the writeback stage to complete (if present) before committing the exception.\n\nIf an EBREAK instruction is encountered and the core is not in debug mode, the controller shall check `dcsr.ebreakm` or `dcsr.ebreaku` (depending on current privilege mode). If those bits are set, the core shall enter debug mode instead of taking a breakpoint exception. If already in debug mode, EBREAK always re‑enters debug mode.\n\n---\n\n## Interrupt Handling\n\nInterrupts are serviced only when:\n\n- The core is **not** in debug mode. \n- The core is **not** in a single‑step sequence. \n- The core is **not** already servicing an NMI (nested NMIs are disallowed). \n- Interrupts are globally enabled (MIE bit in `mstatus` or, when in User Mode, interrupts are always enabled if the corresponding `mie` bit is set). \n\nAn NMI (from the external pin or from an internal source, such as a load integrity error) has the highest priority. When an NMI is taken, the controller sets the NMI mode flag, which prevents all further interrupts (including another NMI) from being taken until the core executes an `mret` instruction.\n\nFor standard interrupts (fast, external, timer, software), prioritization follows the RISC‑V privilege specification, with fast interrupts having the highest priority among them (lowest ID → highest priority).\n\nWhen an interrupt is taken:\n\n- The controller completes any instruction currently in the ID stage (including allowing writeback to finish), but does **not** flush that instruction. \n- It saves the PC of the next instruction to `mepc`. \n- It saves the current interrupt enable state and privilege mode to `mstatus`. \n- It sets `mcause` with the interrupt bit (bit 31) and the appropriate cause code. \n- For internal NMIs (load integrity error) `mtval` is set to the faulting address. \n- The fetch PC is redirected to the interrupt vector table base plus an offset equal to four times the interrupt ID. \n- The controller then returns to the normal decode state and begins executing the handler.\n\nThe controller outputs a signal indicating that an instruction in the writeback stage is taking an exception (used to prevent the writeback stage from writing results). This signal is also used to suppress new instructions from entering ID.\n\n### Internal NMI (Memory ECC)\n\nWhen the `MemECC` parameter is enabled, a load integrity error (single‑bit/multi‑bit error in data loaded from memory) causes an internal NMI. The controller shall:\n\n- Record the faulting address and the fact that an NMI is pending. \n- Take the NMI at most one instruction after the faulting load (a subsequent load or store may execute before the NMI is taken). \n- Set `mcause` to the internal NMI code and `mtval` to the recorded address. \n- Enter NMI mode, disabling all further interrupts. \n\nThe internal NMI is automatically cleared when the NMI handler is entered (or when an external NMI is taken on the same cycle). Only one internal NMI source exists (load integrity error).\n\n---\n\n## Debug Mode\n\nThe core can enter debug mode for three reasons (listed in priority order):\n\n1. **Trigger match** (hardware breakpoint). \n2. **External debug request** (`debug_req`). \n3. **Single‑step** (`dcsr.step` = 1, after executing one instruction).\n\nEntering debug mode is only possible when the core is **not** already in debug mode. When debug mode is entered:\n\n- The controller saves the return PC to `dpc`. \n- It saves the cause of debug entry into `dcsr.cause`. \n- It saves the current privilege mode into `dcsr.prv`. \n- It redirects fetch to the debug halt address. \n- It flushes the pipeline (except that the ID stage may be kept for EBREAK handling). \n\nIf a trigger match occurs while the controller is already handling another exception or interrupt, the debug entry shall be taken with priority over the exception handler. If an EBREAK causes debug mode entry while a debug request or single‑step is also pending, the EBREAK takes priority (since it is the actual instruction that must be associated with the breakpoint).\n\nWhen leaving debug mode (via a `dret` instruction or a debug module resume), the controller restores the PC from `dpc` and exits debug mode.\n\n### Single‑Step Operation\n\nIf `dcsr.step` is set, the controller shall execute exactly one instruction (outside debug mode) and then immediately request debug entry. The single‑step request is qualified with instruction validity; a delay due to a pipeline flush or a memory request will not cause an immediate debug entry until the next valid instruction.\n\n---\n\n## WFI and Sleep Mode\n\nWhen a WFI instruction is decoded and no interrupt or exception prevents it, the controller shall:\n\n- Stop instruction fetch. \n- Place the core into a low‑power sleep state (indicated by a busy signal deassertion). \n- Remain in sleep until one of the following occurs: \n - An NMI or a regular interrupt becomes pending. \n - A debug request arrives. \n - The core is already in debug mode or single‑step is active (in which case WFI behaves as a NOP and the core returns immediately to fetching). \n\nWhile sleeping, the controller continues to observe wake‑up events; it resumes fetching at the next instruction after the WFI.\n\n---\n\n## MRET and DRET\n\nThe `mret` instruction performs a return from trap handling:\n\n- Restores the PC from `mepc`. \n- Restores the interrupt enable state and privilege mode from `mstatus` (MPIE → MIE, MPP → current mode). \n- If the core is in NMI mode, `mret` exits NMI mode (clears the NMI flag). \n\nThe `dret` instruction performs a return from debug mode:\n\n- Restores the PC from `dpc`. \n- Leaves debug mode (clears the debug mode flag). \n\nBoth instructions cause the controller to flush the pipeline and redirect fetch to the restored PC.\n\n---\n\n## CSR‑Related Pipeline Flushes\n\nSome CSR write instructions (e.g., writing `mstatus` or `mie`) may require a pipeline flush to ensure that subsequent instructions see the updated CSR values. When the decoder signals a CSR pipeline flush, the controller shall:\n\n- Halt instruction fetch and flush the ID stage (similar to a taken branch). \n- After the flush, check if an interrupt is now pending and can be taken. If so, the controller may immediately take that interrupt instead of simply resuming normal execution.\n\n---\n\n## Pipeline Control Signals\n\nThe controller manages the IF and ID pipeline registers with the following behavioral rules:\n\n- **Instruction fetch request**: The controller normally keeps the fetch unit active. It shall stop fetching when the ID stage is stalled, when an exception/interrupt is being handled, during sleep, or during reset. \n- **ID stage ready**: The controller signals the ID stage to accept a new instruction only when: \n - No stall is active. \n - No halt is signaled (e.g., waiting for a multi‑cycle instruction). \n - The instruction is not being retained for exception handling. \n- **Flush ID**: The controller flushes the ID register (clears the valid bit) on branches, jumps, exceptions, interrupts, and certain special instructions. Flushing prevents the in‑flight instruction from completing. \n- **Clear IF valid**: The controller clears the IF‑ID register valid bit when an exception or mispredict occurs, ensuring that the next instruction fetched after the redirection is used. \n\n---\n\n## Performance Monitoring\n\nThe controller outputs two performance monitoring signals:\n\n- **taken branch**: asserted when a branch instruction actually takes the branch (regardless of prediction). \n- **jump**: asserted when a jump or jump‑and‑link instruction is executed.\n\n---\n\n## Initialization and Constant Outputs\n\nUpon reset, the controller is inactive until the first instruction fetch is initiated. The core’s busy output indicates whether it is actively processing instructions; during sleep or reset, busy is deasserted.\n\nThe controller does **not** directly handle instruction cache or memory address translation; it only provides the PC selection and set signals to the prefetcher. Exception and debug handler addresses are selected via dedicated multiplexers controlled by the controller.\n\n---\n\n## Summary of State Transitions (Behavioral)\n\n| State | Purpose |\n|----------------|-------------------------------------------------------------------------|\n| RESET | Initialize, set PC to boot address. |\n| BOOT_SET | Apply boot PC to fetch address. |\n| WAIT_SLEEP | Prepare to enter sleep (after WFI). |\n| SLEEP | Core halted, waiting for wake‑up event. |\n| FIRST_FETCH | Wait for first valid instruction after boot or wake‑up. |\n| DECODE | Normal execution, handles instructions, branches, interrupts, debug. |\n| FLUSH | Flush pipeline for exception, interrupt, or special instruction. |\n| IRQ_TAKEN | Take an interrupt: save state, redirect to vector. |\n| DBG_TAKEN_IF | Enter debug mode from IF state (single‑step, debug request, trigger). |\n| DBG_TAKEN_ID | Enter debug mode from ID state (EBREAK handling). |\n\nThe controller cycles through these states based on the conditions described above. It always returns to DECODE after completing an exception, interrupt, debug entry, or flush.\n\n---\n\n## Corner Cases and Priority Rules\n\n1. **Multiple exception sources**: When several exceptions are pending simultaneously (e.g., a load error in writeback and an illegal instruction in ID), the load/store error takes precedence if a writeback stage is present; otherwise, instruction fetch faults have top priority. Exactly one exception is serviced per flush cycle. \n2. **Interrupt during exception flush**: If an interrupt is pending when the controller is about to enter the exception handler, the interrupt may be taken after the flush completes (but before the exception handler starts) if it has higher priority. The controller supports a special transition from flush to interrupt taken for CSR‑related flushes. \n3. **Debug entry during exception**: If a debug request arrives while the core is flushing for an exception, the debug entry takes priority and the core enters debug mode instead of the exception handler. The exception state (PC, cause) is still saved to the appropriate CSRs, but the PC is redirected to the debug handler. \n4. **WFI with interrupts disabled**: If interrupts are disabled (MIE=0) and no debug request is pending, the core sleeps until an NMI or debug event occurs. \n5. **Halt due to debug request while sleeping**: A pending debug request will wake the core and cause immediate debug entry.\n\n---\n\n## Dependencies on Configuration Parameters\n\n- **WritebackStage**: When enabled, store/load errors are recorded in flip‑flops and take priority over ID‑stage exceptions. The controller also waits for the writeback stage to be ready before flushing the pipeline for a special instruction. \n- **BranchPredictor**: When enabled, the controller may skip a PC set for branches that are predicted taken (the predictor already set the PC). It also monitors for mispredictions of not‑taken branches. \n- **MemECC**: Enables logic to capture load integrity errors and generate an internal NMI. Without this parameter, integrity errors are treated as regular load faults (if `SecureIbex` is set) or are ignored.\n\nThe controller must function correctly with any combination of these parameter values. Undefined or unsupported combinations shall result in safe default behavior (e.g., ignoring ECC signals when `MemECC` is disabled).", "commit_id": "3943a4eca3917d0a00406abb36f4951304c0b394", "timestamp": "2022-10-13T16:30:05+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "48733e23ec19e68bd334f27fd9b06f667a012ca3", "pr_title": "Irq fixes", "pr_body": "I had a go at adding interrupts to the single step test. I ran into various failures but I suspect I'm chasing the same bugs as @ctopal and @hcallahan-lowrisc are in https://github.com/lowRISC/ibex/issues/1765 so I won't continue that work until #1765 is resolved.", "issue_title": "[dv] Investigate issues in mixed interrupts/traps/debug tests", "issue_body": "> estimate 16\r\n> remaining 2022-09-28 8", "commit_message": "[rtl] Ignore MIE bit in U mode", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex a14523a253..3dcdd1f77c 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -143,6 +143,7 @@ module ibex_controller #(\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@@ -398,12 +399,16 @@ module ibex_controller #(\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- assign handle_irq = ~debug_mode_q & ~nmi_mode_q &\n- (irq_nm | (irq_pending_i & csr_mstatus_mie_i));\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", "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\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 load_intg_err_i,\n input logic store_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 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, 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 // 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;\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 load_intg_err_irq_pending_q, load_intg_err_irq_pending_d;\n logic [31:0] load_intg_err_addr_q, load_intg_err_addr_d;\n logic load_intg_err_irq_set, load_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 load_intg_err_addr_d = load_intg_err_addr_q;\n load_intg_err_irq_set = 1'b0;\n load_intg_err_irq_clear = 1'b0;\n\n if (load_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 load_intg_err_irq_clear = 1'b1;\n end\n end else if (load_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 load_intg_err_addr_d = lsu_addr_last_i;\n load_intg_err_irq_set = 1'b1;\n end\n end\n\n assign load_intg_err_irq_pending_d =\n (load_intg_err_irq_pending_q & ~load_intg_err_irq_clear) | load_intg_err_irq_set;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n load_intg_err_irq_pending_q <= 1'b0;\n load_intg_err_addr_q <= '0;\n end else begin\n load_intg_err_irq_pending_q <= load_intg_err_irq_pending_d;\n load_intg_err_addr_q <= load_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 = load_intg_err_irq_set | load_intg_err_irq_pending_q;\n assign irq_nm_int_cause = NMI_INT_CAUSE_ECC;\n assign irq_nm_int_mtval = load_intg_err_addr_q;\n end else begin : g_no_intg_irq_int\n logic unused_load_intg_err_i;\n\n assign unused_load_intg_err_i = load_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 /////////////////////\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_cause_o = DBG_CAUSE_EBREAK;\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 if (trigger_match_i) begin\n debug_cause_o = DBG_CAUSE_TRIGGER; // (priority 4)\n end else if (debug_req_i) begin\n debug_cause_o = DBG_CAUSE_HALTREQ; // (priority 1)\n end else begin\n debug_cause_o = DBG_CAUSE_STEP; // (priority 0, lowest)\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 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 debug_cause_o = DBG_CAUSE_EBREAK;\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 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\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 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 //////////\n // FCOV //\n //////////\n\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 `ifdef INC_ASSERT\n // If something that causes a jump into an exception handler is seen that jump must occur before\n // the next instruction executes. The logic tracks whether a jump into an exception handler is\n // expected. Assertions check the jump occurs.\n\n logic exception_req, exception_req_pending, exception_req_accepted, exception_req_done;\n logic exception_pc_set, seen_exception_pc_set, expect_exception_pc_set;\n logic exception_req_needs_pc_set;\n\n assign exception_req = (special_req | enter_debug_mode | handle_irq);\n // Any exception rquest will cause a transition out of DECODE, once the controller transitions\n // back into DECODE we're done handling the request.\n assign exception_req_done =\n exception_req_pending & (ctrl_fsm_cs != DECODE) & (ctrl_fsm_ns == DECODE);\n\n assign exception_req_needs_pc_set = enter_debug_mode | handle_irq | special_req_pc_change;\n\n // An exception PC set uses specific PC types\n assign exception_pc_set =\n exception_req_pending & (pc_set_o & (pc_mux_o inside {PC_EXC, PC_ERET, PC_DRET}));\n\n always @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n exception_req_pending <= 1'b0;\n exception_req_accepted <= 1'b0;\n expect_exception_pc_set <= 1'b0;\n seen_exception_pc_set <= 1'b0;\n end else begin\n // Keep `exception_req_pending` asserted once an exception_req is seen until it is done\n exception_req_pending <= (exception_req_pending | exception_req) & ~exception_req_done;\n\n // The exception req has been accepted once the controller transitions out of decode\n exception_req_accepted <= (exception_req_accepted & ~exception_req_done) |\n (exception_req & ctrl_fsm_ns != DECODE);\n\n // Set `expect_exception_pc_set` if exception req needs one and keep it asserted until\n // exception req is done\n expect_exception_pc_set <= (expect_exception_pc_set | exception_req_needs_pc_set) &\n ~exception_req_done;\n\n // Keep `seen_exception_pc_set` asserted once an exception PC set is seen until the\n // exception req is done\n seen_exception_pc_set <= (seen_exception_pc_set | exception_pc_set) & ~exception_req_done;\n end\n end\n\n // Once an exception request has been accepted it must be handled before controller goes back to\n // DECODE\n `ASSERT(IbexNoDoubleExceptionReq, exception_req_accepted |-> ctrl_fsm_cs != DECODE)\n\n // Only signal ready, allowing a new instruction into ID, if there is no exception request\n // pending or it is done this cycle.\n `ASSERT(IbexDontSkipExceptionReq,\n id_in_ready_o |-> !exception_req_pending || exception_req_done)\n\n // Once a PC set has been performed for an exception request there must not be any other\n // excepting those to move into debug mode.\n `ASSERT(IbexNoDoubleSpecialReqPCSet,\n seen_exception_pc_set &&\n !((ctrl_fsm_cs inside {DBG_TAKEN_IF, DBG_TAKEN_ID}) &&\n (pc_mux_o == PC_EXC) && (exc_pc_mux_o == EXC_PC_DBD))\n |-> !pc_set_o)\n\n // When an exception request is done there must have been an appropriate PC set (either this\n // cycle or a previous one).\n `ASSERT(IbexSetExceptionPCOnSpecialReqIfExpected,\n exception_req_pending && expect_exception_pc_set && exception_req_done |->\n seen_exception_pc_set || exception_pc_set)\n\n // If there's a pending exception req that doesn't need a PC set we must not see one\n `ASSERT(IbexNoPCSetOnSpecialReqIfNotExpected,\n exception_req_pending && !expect_exception_pc_set |-> ~pc_set_o)\n `endif\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", "selected_doc_paths": ["doc/03_reference/exception_interrupts.rst", "doc/03_reference/debug.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/cs_registers.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1917, "lang": "sv", "rtl_files": ["rtl/ibex_top.sv"], "spec": "# Ibex Top-Level Module Design Specification\n\n## 1. Overview\n\nThe `ibex_top` module is the top-level wrapper for the Ibex RISC-V processor core. It integrates the core pipeline (`ibex_core`), the register file, optional instruction cache (I$) RAMs, and a scrambling infrastructure for secure implementations. It also supports an optional dual-core lockstep configuration for fault detection.\n\nThe module provides all external interfaces required to integrate Ibex into a system-on-chip (SoC), including instruction and data memory interfaces, interrupt inputs, debug interface, and system control signals. The design is parametric to allow configuration of instruction set extensions, performance features, and security mechanisms.\n\n## 2. Parameters\n\nThe following parameters control the configuration of the core and are static at synthesis time. They shall not change during operation.\n\n| Parameter | Type/Range | Default | Description |\n|-----------|------------|---------|-------------|\n| `PMPEnable` | bit | 0 | Enable Physical Memory Protection (PMP) support. |\n| `PMPGranularity` | int (0–31) | 0 | Minimum granularity of PMP address matching (2^(G+2) bytes). |\n| `PMPNumRegions` | int (1–16) | 4 | Number of implemented PMP regions (ignored if `PMPEnable = 0`). |\n| `MHPMCounterNum` | int (0–10) | 0 | Number of hardware performance monitor counters. |\n| `MHPMCounterWidth` | int (1–64) | 40 | Bit width of performance monitor counters. |\n| `RV32E` | bit | 0 | Enable RV32E mode (16 integer registers). |\n| `RV32M` | enum (rv32m_e) | `RV32MFast` | M-extension implementation: `RV32MNone`, `RV32MSlow`, `RV32MFast`, `RV32MSingleCycle`. |\n| `RV32B` | enum (rv32b_e) | `RV32BNone` | B-extension implementation: `RV32BNone`, `RV32BBalanced`, `RV32BOTEarlGrey`, `RV32BFull`. |\n| `RegFile` | enum (regfile_e) | `RegFileFF` | Register file implementation: flip-flop-based, FPGA-optimized, or latch-based. |\n| `BranchTargetALU` | bit | 0 | Enable branch target ALU to reduce taken branch penalty (experimental). |\n| `WritebackStage` | bit | 0 | Enable third pipeline stage (writeback) to improve load/store performance (experimental). |\n| `ICache` | bit | 0 | Enable instruction cache (experimental). |\n| `ICacheECC` | bit | 0 | Enable SECDED ECC protection in ICache tag and data RAMs (experimental, requires `ICache=1`). |\n| `ICacheScramble` | bit | 0 | Replace ICache RAMs with scrambling primitives for data obfuscation (experimental). |\n| `BranchPredictor` | bit | 0 | Enable static branch prediction (experimental). |\n| `DbgTriggerEn` | bit | 0 | Enable debug trigger support. |\n| `DbgHwBreakNum` | int unsigned | 1 | Number of hardware breakpoints (triggers). |\n| `SecureIbex` | bit | 0 | Enable security enhancements (dual-core lockstep, ECC, dummy instructions, etc.). |\n| `RndCnstLfsrSeed` | lfsr_seed_t | default | Initial seed for LFSR used by dummy instruction insertion. |\n| `RndCnstLfsrPerm` | lfsr_perm_t | default | Output permutation for LFSR used by dummy instruction insertion. |\n| `DmHaltAddr` | int | 0x1A110800 | Address to jump to when entering Debug Mode. |\n| `DmExceptionAddr` | int | 0x1A110808 | Address to jump to when an exception occurs in Debug Mode. |\n| `RndCnstIbexKey` | logic[SCRAMBLE_KEY_W-1:0] | default | Default scrambling key (used when ICacheScramble enabled). |\n| `RndCnstIbexNonce` | logic[SCRAMBLE_NONCE_W-1:0] | default | Default scrambling nonce (used when ICacheScramble enabled). |\n\n## 3. Interfaces\n\nAll I/O signals are synchronous to the provided clock and reset.\n\n### 3.1 Clock and Reset\n- **Clock input (`clk_i`)**: System clock.\n- **Reset input (`rst_ni`)**: Active-low asynchronous reset. All registers reset to their default values.\n- **Test enable (`test_en_i`)**: Enables all clock gates for testing. Must be tied low during normal operation.\n- **Scan reset (`scan_rst_ni`)**: DFT controlled reset. If not used, tie to 1'b1.\n- **RAM configuration (`ram_cfg_i`)**: Configuration bus for RAM primitives (e.g., ICache RAMs). Provided by the system and routed directly to RAM macros.\n\n### 3.2 Core Configuration\n- **Hart ID (`hart_id_i`)**: 32-bit hart identifier. Static. Readable via the `mhartid` CSR.\n- **Boot address (`boot_addr_i`)**: Initial program counter after reset. The core starts fetching from `boot_addr_i + 0x80` (default reset vector offset).\n\n### 3.3 Instruction Memory Interface\nStandard request/grant/valid handshake with error signalling.\n\n- Request output (`instr_req_o`): Indicates the core requires an instruction.\n- Grant input (`instr_gnt_i`): The memory system accepts the request.\n- Response valid (`instr_rvalid_i`): The memory system provides data.\n- Address (`instr_addr_o`): 32-bit instruction fetch address.\n- Read data (`instr_rdata_i`): 32-bit instruction data.\n- Read data integrity (`instr_rdata_intg_i`): 7-bit integrity checkbits (used when `SecureIbex` is enabled).\n- Error (`instr_err_i`): Indicates a bus error on the fetch.\n\nThe core supports a single outstanding request (no pipelining). The memory system shall respond with `instr_rvalid_i` for every granted request.\n\n### 3.4 Data Memory Interface\nStandard request/grant/valid handshake with byte enables, write data, and error signalling.\n\n- Request output (`data_req_o`): Core wants to access data memory.\n- Grant input (`data_gnt_i`): Memory system accepts the request.\n- Response valid (`data_rvalid_i`): Memory system provides data (read) or acknowledges write.\n- Write enable (`data_we_o`): `0` = read, `1` = write.\n- Byte enables (`data_be_o`): 4-bit mask for byte-level write granularity.\n- Address (`data_addr_o`): 32-bit data address.\n- Write data (`data_wdata_o`): 32-bit data for writes.\n- Write data integrity (`data_wdata_intg_o`): 7-bit integrity checkbits (used when `SecureIbex` is enabled).\n- Read data (`data_rdata_i`): 32-bit data for reads.\n- Read data integrity (`data_rdata_intg_i`): 7-bit integrity checkbits (used when `SecureIbex` is enabled).\n- Error (`data_err_i`): Bus error on the data access.\n\nThe core can have up to two outstanding data accesses (due to unaligned load/store splitting). The memory system shall respond in order.\n\n### 3.5 Interrupt Inputs\n- Software interrupt (`irq_software_i`): Machine-level software interrupt.\n- Timer interrupt (`irq_timer_i`): Machine-level timer interrupt.\n- External interrupt (`irq_external_i`): Machine-level external interrupt.\n- Fast interrupts (`irq_fast_i`): 15 dedicated fast interrupt lines (machine-level).\n- Non-maskable interrupt (`irq_nm_i`): NMI, always taken regardless of `mstatus.MIE`.\n\nAll interrupts are level-sensitive and must be held active until serviced (or cleared by the core). Fast interrupts have priority over standard interrupts and are individually maskable via the `mivec` CSR.\n\n### 3.6 Scrambling Interface (ICacheScramble)\nUsed only when the ICache is configured with `ICacheScramble = 1`.\n\n- Request output (`scramble_req_o`): Core requests a new scrambling key.\n- Key valid input (`scramble_key_valid_i`): System indicates a fresh key/nonce is available.\n- Key (`scramble_key_i`): Scrambling key (width per `ibex_pkg`).\n- Nonce (`scramble_nonce_i`): Scrambling nonce (width per `ibex_pkg`).\n\nThe protocol: The core asserts `scramble_req_o` to request a new key. When the system asserts `scramble_key_valid_i`, the core latches the key/nonce and deasserts `scramble_req_o`. The key is used for address and data scrambling in the ICache RAMs.\n\n### 3.7 Debug Interface\n- Debug request (`debug_req_i`): Level-sensitive input from the debug module to enter Debug Mode.\n- Crash dump (`crash_dump_o`): A packed structure containing the current PC, next PC, last data address, exception PC, and exception address. Useful for post-reset debugging.\n- Double fault seen (`double_fault_seen_o`): Sticky output indicating that a double fault (exception during exception handling) has occurred.\n\n### 3.8 System Control\n- Fetch enable (`fetch_enable_i`): Multi-bit (mubi) signal. When set to the `IbexMuBiOn` pattern, the core fetches instructions. When set to `IbexMuBiOff`, the core halts after completing in-flight instructions. The exact encoding is defined in `ibex_pkg`.\n- Core sleep (`core_sleep_o`): Indicates the core is in a WFI state with no outstanding memory accesses. Deasserted when an interrupt, debug request, or NMI wakes the core.\n- Alert minor (`alert_minor_o`): Pulse output indicating a recoverable security or functional anomaly (e.g., single-bit ECC errors, glitch warnings).\n- Alert major internal (`alert_major_internal_o`): Pulse (may be multi-cycle) indicating an unrecoverable internal fault (e.g., lockstep mismatch, register file ECC error, PC integrity violation).\n- Alert major bus (`alert_major_bus_o`): Pulse (may be multi-cycle) indicating an unrecoverable bus integrity fault (e.g., data memory integrity check failure).\n\n### 3.9 RISC-V Formal Interface (Optional)\nWhen compiled with `RISCV_FORMAL` defined, a set of `rvfi_*` outputs are provided for formal verification. They comply with the RISC-V Formal Interface Specification and are not used in functional operation.\n\n## 4. Functional Description\n\n### 4.1 Reset Behavior\nUpon assertion of `rst_ni` (active low), all registers in the core pipeline, CSRs, register file, and (if present) ICache are reset to their initial values. The boot address is sampled and the core will start instruction fetch from `boot_addr_i + 0x80` after reset release.\n\n### 4.2 Clock Gating\nThe module provides a main clock gate that is controlled by internal core activity. The clock to the core logic (`clk_o`) is gated when:\n- The core is idle (`core_busy` signal indicates no instruction execution).\n- No interrupt, NMI, or debug request is pending.\n- `fetch_enable_i` is off.\n\nWhen `SecureIbex = 1`, a robust multi-bit encoding is used for `core_busy` to prevent glitch-based enabling of the clock. The `core_sleep_o` output reflects the state of the clock gate: high when the clock is gated.\n\nThe `test_en_i` input forces the clock gate to be transparent for DFT purposes.\n\n### 4.3 Core Pipeline Operation\nThe core implements a 2-stage pipeline (IF/ID and EX) with an optional third writeback stage. It executes the RV32I base instruction set plus configurable extensions (M, B). The pipeline advances each cycle unless stalled by hazards (load-use, memory latency, structural hazards).\n\n- **Fetch**: Instructions are fetched from the instruction memory interface (or from the ICache if enabled). The fetch address increments by 2 or 4 bytes based on whether the instruction is compressed.\n- **Decode/Execute**: Instructions are decoded and executed. Register operands are read from the register file. Results are written back to the register file in the same or following cycle.\n- **Memory access**: Load and store operations go through the data memory interface. Unaligned accesses are split into two aligned bus transactions.\n- **Writeback**: If `WritebackStage = 1`, register writes occur in a separate stage to improve timing.\n\n### 4.4 Instruction Cache (ICache)\nIf `ICache = 1`, the prefetch buffer is replaced by an instruction cache. The cache is direct-mapped or set-associative (parameters fixed internally). It caches instruction lines and reduces latency for repeated code regions.\n\n- **Cache operations**: On a cache miss, the cache fetches a full line from instruction memory and allocates it. On a hit, data is returned in the same cycle.\n- **Invalidation**: A FENCE.I instruction triggers a full cache invalidation. While invalidating, the cache behaves as if disabled.\n- **ECC protection**: When `ICacheECC = 1`, single-error detection (and no correction) is applied to tag and data RAMs. Detected errors cause the cache to fetch from memory instead of using the corrupt data; a minor alert is raised.\n- **Scrambling**: When `ICacheScramble = 1`, RAM contents are obfuscated using a key/nonce. The interface described in Section 3.6 is used to update the key after FENCE.I.\n\n### 4.5 Register File\nThe register file contains 31 (RV32I) or 15 (RV32E) 32-bit registers. Register x0 is hardwired to zero.\n\nThree implementations are available:\n- **Flip-flop-based**: Suitable for simulation (Verilator) and general synthesis.\n- **FPGA-optimized**: Uses LUTRAMs on Xilinx devices; saves logic resources.\n- **Latch-based**: Area-efficient for ASICs; requires a specific clock gating scheme.\n\nAll implementations provide two read ports (combinational read) and one write port (registered). There is no read-to-write forwarding; a read of a register being written returns the old value.\n\nWhen `SecureIbex = 1`, ECC (detect only) is added to register file reads. Write enable glitch detection (one-hot check) is also enabled. A mismatch triggers an internal major alert.\n\n### 4.6 Physical Memory Protection (PMP)\nIf `PMPEnable = 1`, the PMP unit enforces region-based access control per the RISC-V Privileged Specification v1.11 with Smepmp enhancements. Addresses from instruction fetch and load/store units are checked against PMP configuration registers.\n\n- The number of regions is defined by `PMPNumRegions` (1–16). Regions are configured via `pmpcfg` and `pmpaddr` CSRs.\n- Granularity (2^(G+2) bytes) is set via `PMPGranularity`.\n- PMP check results are merged with external bus errors: if a PMP violation occurs, the access proceeds on the bus but the core sees an error response.\n\n### 4.7 Interrupt and Exception Handling\nThe core handles standard RISC-V interrupts and exceptions. Interrupts are taken when globally enabled (MIE) and the specific interrupt is not masked. NMIs are taken regardless.\n\n- Fast interrupts have programmable priorities and can be grouped.\n- An `irq_pending` internal signal is used to wake the core from WFI and to keep the clock enabled.\n- Upon taking an interrupt, the core saves the return PC and current privilege level, disables interrupts, and jumps to the trap vector.\n\n### 4.8 Debug Support\nThe core supports execution-based debug per the RISC-V Debug Specification v0.13.\n\n- **Entering Debug Mode**: When `debug_req_i` is asserted, the core halts at the next instruction boundary and jumps to the address in `DmHaltAddr`. It saves the PC to `dpc`.\n- **Debug Registers**: CSRs `dcsr`, `dpc`, and scratch registers are accessible only in Debug Mode.\n- **Triggers**: If `DbgTriggerEn = 1`, hardware triggers (breakpoints/watchpoints) are available. The number is given by `DbgHwBreakNum`.\n- **Double Fault**: If an exception occurs while the core is already handling an exception (or in Debug Mode), `double_fault_seen_o` is asserted and stays high until reset.\n\n### 4.9 Security Features (SecureIbex)\nWhen `SecureIbex = 1`, the following additional mechanisms are enabled:\n\n- **Dual-core lockstep**: A second, shadow core is instantiated with delayed inputs. Its outputs are compared against the main core. Any mismatch triggers an internal major alert. The shadow core does not interact with memory or register file; it only mirrors the main core's logic.\n- **Data independent timing**: When enabled via the `cpuctrl` CSR, branches execute with constant latency, and multiplier/divider early completion is suppressed.\n- **Dummy instruction insertion**: Random dummy multiply/divide instructions are inserted into the pipeline (requires `RV32M != None`). The frequency is controlled via `cpuctrl`.\n- **Bus integrity checking**: Incoming data integrity bits are checked. On mismatch, a bus major alert is raised and load data is not written to the register file.\n- **Register file ECC and write-glitch detection** (see Section 4.5).\n- **Hardened PC**: The IF-stage PC is checked to have incremented correctly; a mismatch causes an internal major alert.\n- **Shadow CSRs**: Critical CSRs (`mstatus`, `mtvec`, `cpuctrl`, PMP config) have duplicated, complemented copies to detect glitches.\n\nWhen lockstep is disabled (`SecureIbex = 0`), the shadow core is not instantiated and relevant alert outputs are tied to zero.\n\n### 4.10 Alert Aggregation\nThe three alert outputs are OR-ed from multiple sources:\n- Core-internal alerts (from `ibex_core`): minor, major internal, major bus.\n- Lockstep alerts (when `SecureIbex = 1`): same categories.\n- Register file alert (when `SecureIbex = 1`): major internal.\n\nThe combined output reflects any active fault condition.\n\n## 5. Behavioral Requirements\n\n- **Reset**: All outputs shall be at their reset values within one clock cycle after `rst_ni` assertion. After reset release, the core must begin fetching from the boot address.\n- **Clock gating**: The clock shall be disabled (gated) only when `core_sleep_o` is asserted. The core must wake up within one cycle of any interrupt or debug request.\n- **Memory protocol**: The core must not issue a new instruction request while a previous one is outstanding. For data side, up to two requests may be outstanding. The core must accept responses in order.\n- **Interrupts**: The core must sample interrupt inputs every cycle. When `mstatus.MIE` is set and interrupts are unmasked, the core must take the highest priority pending interrupt at the next instruction boundary.\n- **Debug**: The core must enter Debug Mode within a bounded number of cycles after `debug_req_i` is asserted and the current instruction completes. Debug Mode must be exited only via a `dret` instruction.\n- **Alerts**: `alert_minor_o` and `alert_major_*` outputs shall be pulsed (or held) for each detected event. The core must not reset itself on major alerts; the system is responsible for resetting the core.\n- **Scramble key renewal**: After a FENCE.I instruction (when `ICacheScramble = 1`), the core must request a new scrambling key and invalidate the cache. During invalidation, instruction fetches may continue from memory.\n- **Lockstep**: When configured, the shadow core must produce identical behavior to the main core. Any deviation (including timing differences due to the delayed input) must be flagged as an internal major alert.\n- **Register file**: Reads of register x0 shall return zero regardless of write attempts. Writes to x0 shall have no effect.\n- **PMP**: The core must not allow instruction fetch or data access to an address that is denied by PMP rules. The core must report an exception as if a bus error occurred.\n- **Dummy instructions**: Dummy instructions must not modify architectural state (except writing to x0). They must consume pipeline resources to mimic real execution.\n\n## 6. Additional Constraints\n\n- The core is compatible only with little-endian memory systems.\n- The instruction set does not support misaligned instruction fetches; addresses must be halfword-aligned.\n- All outputs must be glitch-free and shall not change due to clock gating transitions.\n- The `ram_cfg_i` input shall be tied to appropriate configuration for the target technology. It is used only by the ICache RAMs and is ignored when `ICache = 0`.", "commit_id": "94f9517287f14c468d76296a719ee04c610ffbfd", "timestamp": "2022-11-14T11:07:50+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "b399c7c8c496702cff66e5fe7a4c043b9b724b73", "pr_title": "[fpv] Fix linting issues in oustanding access tracking logic", "pr_body": "This refactors the code to avoid a -1 index access that caused no issues in functional verification but caused lint errors and is problematic for formal tools.\r\n\r\nFixes #1799", "issue_title": "[dv] Out of bounds access in dside access tracking logic", "issue_body": "This line: https://github.com/lowRISC/ibex/blob/056cb44ff75f797898709546ea1b0fd08d862e1a/rtl/ibex_top.sv#L1092\r\n\r\nUses `i - 1` and it's possible to evaluate this condition when `i == 0` giving an out of bounds access. This logic needs refactoring to more explicitly split out the `i == 0` case from the others to ensure this does not occur.\r\n\r\n> estimate 1", "commit_message": "[fpv] Fix linting issues in oustanding access tracking logic\n\nThis refactors the code to avoid a -1 index access that caused no issues\nin functional verification but caused lint errors and is problematic for\nformal tools.\n\nFixes #1799", "fix_patch": "diff --git a/rtl/ibex_top.sv b/rtl/ibex_top.sv\nindex 84b0f9cd1f..d8a9f89162 100644\n--- a/rtl/ibex_top.sv\n+++ b/rtl/ibex_top.sv\n@@ -1117,15 +1117,21 @@ module ibex_top import ibex_pkg::*; #(\n end\n end\n \n- always_comb begin\n- pending_dside_accesses_d[i] = pending_dside_accesses_shifted[i];\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) begin\n- if (i == 0 && !pending_dside_accesses_shifted[i].valid) begin\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 else if (pending_dside_accesses_shifted[i - 1].valid &\n- !pending_dside_accesses_shifted[i].valid) begin\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", "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_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_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 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 `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", "selected_doc_paths": ["doc/02_user/integration.rst", "doc/03_reference/security.rst", "doc/03_reference/pmp.rst", "doc/03_reference/debug.rst", "doc/03_reference/icache.rst", "doc/03_reference/register_file.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1446, "lang": "sv", "rtl_files": ["rtl/ibex_top_tracing.sv"], "spec": "# Design Specification for `ibex_top_tracing`\n\n## 1. Overview\n\n`ibex_top_tracing` is a SystemVerilog module that encapsulates a RISC‑V processor core (Ibex) together with a trace logging facility. It is intended as a drop‑in replacement for the standard `ibex_top` module when instruction‑level tracing is required during simulation. The module provides the same interfaces, parameters, and functional behavior as the core alone, but additionally produces a human‑readable log of every executed instruction.\n\n## 2. Functional Description\n\nThe module combines a synthesizable RISC‑V core (Ibex) and a simulation‑only tracer. The core fetches, decodes, executes, and commits instructions according to the RISC‑V instruction set architecture (RV32I, optionally with M, B, and C extensions). The tracer observes the core’s internal state via the RISC‑V Formal Interface (RVFI) and writes a trace record for each committed instruction.\n\nAll standard Ibex features (interrupt handling, debug support, PMP, performance counters, etc.) are preserved without modification. The tracer is purely observational and does not affect the core’s behavior or timing.\n\n## 3. Interfaces\n\n### 3.1 Clock and Reset\n\n- **Clock (`clk_i`)**: All synchronous logic shall operate on the rising edge of `clk_i`.\n- **Reset (`rst_ni`)**: Active‑low, asynchronous reset. The core and tracer shall be reset when this signal is asserted low.\n- **Test enable (`test_en_i`)**: When asserted, all clock gates shall be enabled for test purposes.\n- **Scan reset (`scan_rst_ni`)**: DFT‑controlled reset. If not used, this input must be tied to `1`.\n- **RAM configuration (`ram_cfg_i`)**: Configuration signals routed to internal instruction cache RAMs (if applicable).\n\n### 3.2 Core Configuration (Parameters)\n\nAll parameters listed below are identical to those of `ibex_top` and shall be passed through unchanged. For a detailed description of each parameter, refer to the Ibex core integration documentation.\n\n| Parameter | Type | Default |\n|-------------------------|-------------------------|--------------------------|\n| `PMPEnable` | bit | 0 |\n| `PMPGranularity` | int unsigned | 0 |\n| `PMPNumRegions` | int unsigned | 4 |\n| `MHPMCounterNum` | int unsigned | 0 |\n| `MHPMCounterWidth` | int unsigned | 40 |\n| `RV32E` | bit | 0 |\n| `RV32M` | `ibex_pkg::rv32m_e` | `RV32MFast` |\n| `RV32B` | `ibex_pkg::rv32b_e` | `RV32BNone` |\n| `RegFile` | `ibex_pkg::regfile_e` | `RegFileFF` |\n| `BranchTargetALU` | bit | 0 |\n| `WritebackStage` | bit | 0 |\n| `ICache` | bit | 0 |\n| `ICacheECC` | bit | 0 |\n| `BranchPredictor` | bit | 0 |\n| `DbgTriggerEn` | bit | 0 |\n| `DbgHwBreakNum` | int unsigned | 1 |\n| `SecureIbex` | bit | 0 |\n| `RndCnstLfsrSeed` | `lfsr_seed_t` | `RndCnstLfsrSeedDefault` |\n| `RndCnstLfsrPerm` | `lfsr_perm_t` | `RndCnstLfsrPermDefault` |\n| `DmHaltAddr` | int unsigned | 32’h1A110800 |\n| `DmExceptionAddr` | int unsigned | 32’h1A110808 |\n\n### 3.3 Core Inputs and Outputs\n\nThe module provides exactly the same ports as `ibex_top`:\n\n- **Hart ID** (`hart_id_i`): A static 32‑bit identifier used for CSR reads and tracer file naming.\n- **Boot address** (`boot_addr_i`): First PC after reset is `boot_addr_i + 0x80`.\n- **Instruction memory interface**: Includes `instr_req_o`, `instr_gnt_i`, `instr_rvalid_i`, `instr_addr_o`, `instr_rdata_i`, `instr_rdata_intg_i`, `instr_err_i`.\n- **Data memory interface**: Includes `data_req_o`, `data_gnt_i`, `data_rvalid_i`, `data_we_o`, `data_be_o`, `data_addr_o`, `data_wdata_o`, `data_wdata_intg_o`, `data_rdata_i`, `data_rdata_intg_i`, `data_err_i`.\n- **Interrupt inputs**: `irq_software_i`, `irq_timer_i`, `irq_external_i`, `irq_fast_i` (14 bits), `irq_nm_i`.\n- **Debug interface**: `debug_req_i` and `crash_dump_o`.\n- **Control signals**: `fetch_enable_i`, `alert_minor_o`, `alert_major_o`, `core_sleep_o`.\n\nAll signal widths, directions, and timing shall be identical to those defined for `ibex_top`. The module does not add, remove, or rename any core port.\n\n## 4. Trace Functionality\n\n### 4.1 Trace Generation\n\nThe tracer shall generate a log entry for every instruction that is committed (i.e., architecturally executed) by the core. The trace information is obtained from the RISC‑V Formal Interface (RVFI) of the core. The tracer is a simulation‑only module and shall be automatically instantiated; it does not require any external connection.\n\n**Note**: The RVFI signals must be enabled globally in the simulation environment (e.g., via a `define`). The module shall cause a simulation‑fatal error if RVFI is not available.\n\n### 4.2 Trace Output File\n\nThe tracer shall write a log file for each simulated hart. The file name shall be constructed as:\n\n```\n_.log\n```\n\nwhere:\n\n- `` defaults to `trace_core`. This base can be overridden by the simulation plusarg `ibex_tracer_file_base`.\n- `` is the 32‑bit value of `hart_id_i` formatted as an 8‑digit hexadecimal number (zero‑padded, uppercase hex).\n\nExample: With `hart_id_i = 32'h00000001` and default base, the file name is `trace_core_00000001.log`.\n\n### 4.3 Disabling the Tracer\n\nThe tracer can be disabled per simulation run using the plusarg `ibex_tracer_enable`. The tracer shall be enabled by default. To disable it, the user must set `ibex_tracer_enable=0`. When disabled, the tracer shall not write any log files and shall consume minimal simulation resources.\n\n### 4.4 Trace Output Format\n\nEach line of the log corresponds to one committed instruction and contains tab‑separated columns in the following order:\n\n1. **Time**: Current simulation time (units depend on simulator).\n2. **Cycle**: Number of cycles elapsed since the last de‑assertion of reset. The cycle count shall reset to zero when `rst_ni` goes low, and increment on every clock cycle where `rst_ni` is high.\n3. **PC**: Program counter of the instruction (32‑bit hexadecimal value, zero‑padded to 8 digits).\n4. **Instr**: Raw instruction encoding (hexadecimal). 8 hex digits for uncompressed (32‑bit) instructions, 4 hex digits for compressed (16‑bit) instructions.\n5. **Decoded instruction**: Disassembled instruction in a format equivalent to `objdump -Mnumeric -Mno-aliases -D`. \n - Unsigned immediate values shall be shown in hex (prefixed with `0x`). \n - Signed immediate values shall be shown as decimal numbers. \n - Register names shall be numeric (e.g., `x1`). \n - CSR names shall be symbolic where known. \n - Jump/branch targets shall be shown as absolute addresses (`PC + immediate`) if computable.\n6. **Register and memory contents**: A list of all register reads and writes, and memory accesses performed by the instruction. \n - Register writes: `register_name = value` (e.g., `x9=0x00000000`). \n - Register reads: `register_name : value` (e.g., `x8:0x00007fff`). \n - Memory accesses: The physical address (`PA:...`), stored value (`store:...`), and loaded value (`load:...`) for load and store instructions.\n\nWhen multiple register or memory accesses occur, they shall be listed in a natural order (e.g., reads before writes).\n\n### 4.5 Example Trace Lines\n\n```\n 130 61 00000150 4481 c.li x9,0 x9=0x00000000\n 132 62 00000152 00008437 lui x8,0x8 x8=0x00008000\n 142 67 0000015c c622 c.swsp x8,12(x2) x2:0x00002000 x8:0x00000000 PA:0x0000200c store:0x00000000 load:0xffffffff\n```\n\n## 5. Observability and Debug\n\n- **Crash dump (`crash_dump_o`)**: The core shall output a set of signals that can be sampled on assertion of reset to assist in diagnosing the cause of a crash. The behavior and contents of `crash_dump_o` are identical to `ibex_top`.\n- **Alerts (`alert_minor_o`, `alert_major_o`)**: The core shall generate pulse‑width alerts when recoverable or unrecoverable faults are detected, as defined in the Ibex core specification.\n\n## 6. Simulation Requirements\n\nThe module is intended for simulation only when tracing is active. When synthesised, the tracer is omitted; the module may be used as a wrapper that is equivalent to `ibex_top` in hardware. The tracer itself is not synthesizable.\n\n- The RVFI interface must be defined globally in the simulation environment (e.g., via `+define+RVFI`). Failure to do so shall cause a simulation‑fatal error.\n- The tracer writes to files using SystemVerilog file I/O. The simulation environment must support file operations.\n- The tracer uses simulation plusargs for configuration; no additional RTL parameters control its behavior.\n\n## 7. Backward Compatibility\n\nThe module shall be fully compatible with existing `ibex_top` instantiations: all parameters, ports, and timing are identical. Replacement of `ibex_top` with `ibex_top_tracing` shall not alter the core’s functional behavior, interface timing, or area/timing characteristics after synthesis (tracer removed automatically by tool optimizations).", "commit_id": "45f727dfc6e59119347aca62e38e69175f680bf6", "timestamp": "2021-09-27T10:06:04+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "305f0a80ea7080f80e638eb18f4448dd54598e72", "pr_title": "Add missing parameters to ibex_top_tracing", "pr_body": "Fixes #1444", "issue_title": "Building dependency in Fusesoc step fails on Ubuntu 20.04", "issue_body": "\r\n\r\n\r\n\r\nHii, I am trying to run the ibex core on my Ubuntu 20.04 system as suggested in https://github.com/lowRISC/ibex/tree/master/examples/simple_system. \r\n\r\nThe dependencies are correctly installed, but the fusesoc building simulation step fails inspite of that:\r\nfusesoc --cores-root=. run --target=sim --setup --build lowrisc:ibex:ibex_simple_system --RV32E=0 --RV32M=ibex_pkg::RV32MFast\r\n\r\nThe error is as follows:\r\n\r\nINFO: Running pre_build script check_tool_requirements\r\nINFO: Tool verilator present: Sufficiently recent version (found 4.213; needed 4.028)\r\nINFO: Tool edalize present: Sufficiently recent version (found 0.2.2; needed 0.2.0)\r\nINFO: Building simulation model\r\nverilator -f lowrisc_ibex_ibex_simple_system_0.vc --trace --trace-fst --trace-structs --trace-params --trace-max-array 1024 -CFLAGS \"-std=c++11 -Wall -DVM_TRACE_FMT_FST -DTOPLEVEL_NAME=ibex_simple_system -g\" -LDFLAGS \"-pthread -lutil -lelf\" -Wall -Wwarn-IMPERFECTSCH --unroll-count 72\r\n%Warning-UNUSED: ../src/lowrisc_ibex_ibex_top_tracing_0.1/rtl/ibex_top_tracing.sv:27:26: Parameter is not used: 'RndCnstLfsrSeed'\r\n : ... In instance ibex_simple_system.u_top\r\n 27 | parameter lfsr_seed_t RndCnstLfsrSeed = RndCnstLfsrSeedDefault,\r\n | ^~~~~~~~~~~~~~~\r\n ... For warning description see https://verilator.org/warn/UNUSED?v=4.213\r\n ... Use \"/* verilator lint_off UNUSED */\" and lint_on around source to disable this message.\r\n%Warning-UNUSED: ../src/lowrisc_ibex_ibex_top_tracing_0.1/rtl/ibex_top_tracing.sv:28:26: Parameter is not used: 'RndCnstLfsrPerm'\r\n : ... In instance ibex_simple_system.u_top\r\n 28 | parameter lfsr_perm_t RndCnstLfsrPerm = RndCnstLfsrPermDefault,\r\n | ^~~~~~~~~~~~~~~\r\n%Error: Exiting due to 2 warning(s)\r\nMakefile:16: recipe for target 'Vibex_simple_system.mk' failed\r\nmake: *** [Vibex_simple_system.mk] Error 1\r\nERROR: Failed to build lowrisc:ibex:ibex_simple_system:0 : 'make' exited with an error code\r\n\r\n\r\nI am new to ibex, can anyone be kind to help me with the resolution of the error. \r\nThanks in advance.\r\n\r\n\r\n\r\n\r\n\r\n## My Environment\r\n\r\n\r\n\r\n**EDA tool and version:**\r\n\r\n\r\n**Operating system:**\r\n\r\n\r\n**Version of the Ibex source code:**\r\n\r\n", "commit_message": "Add missing parameters to ibex_top_tracing", "fix_patch": "diff --git a/rtl/ibex_top_tracing.sv b/rtl/ibex_top_tracing.sv\nindex 02aa9db15e..7bbc6fd722 100644\n--- a/rtl/ibex_top_tracing.sv\n+++ b/rtl/ibex_top_tracing.sv\n@@ -129,6 +129,8 @@ module ibex_top_tracing import ibex_pkg::*; #(\n .DbgHwBreakNum ( DbgHwBreakNum ),\n .WritebackStage ( WritebackStage ),\n .SecureIbex ( SecureIbex ),\n+ .RndCnstLfsrSeed ( RndCnstLfsrSeed ),\n+ .RndCnstLfsrPerm ( RndCnstLfsrPerm ),\n .DmHaltAddr ( DmHaltAddr ),\n .DmExceptionAddr ( DmExceptionAddr )\n ) u_ibex_top (\n", "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 * Top level module of the ibex RISC-V core with tracing enabled\n */\n\nmodule ibex_top_tracing 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 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) (\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 logic scan_rst_ni,\n input prim_ram_1p_pkg::ram_1p_cfg_t ram_cfg_i,\n\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 // Debug Interface\n input logic debug_req_i,\n output crash_dump_t crash_dump_o,\n\n // CPU Control Signals\n input logic fetch_enable_i,\n output logic alert_minor_o,\n output logic alert_major_o,\n output logic core_sleep_o\n\n);\n\n // ibex_tracer relies on the signals from the RISC-V Formal Interface\n `ifndef RVFI\n $fatal(\"Fatal error: RVFI needs to be defined globally.\");\n `endif\n\n logic rvfi_valid;\n logic [63:0] rvfi_order;\n logic [31:0] rvfi_insn;\n logic rvfi_trap;\n logic rvfi_halt;\n logic rvfi_intr;\n logic [ 1:0] rvfi_mode;\n logic [ 1:0] rvfi_ixl;\n logic [ 4:0] rvfi_rs1_addr;\n logic [ 4:0] rvfi_rs2_addr;\n logic [ 4:0] rvfi_rs3_addr;\n logic [31:0] rvfi_rs1_rdata;\n logic [31:0] rvfi_rs2_rdata;\n logic [31:0] rvfi_rs3_rdata;\n logic [ 4:0] rvfi_rd_addr;\n logic [31:0] rvfi_rd_wdata;\n logic [31:0] rvfi_pc_rdata;\n logic [31:0] rvfi_pc_wdata;\n logic [31:0] rvfi_mem_addr;\n logic [ 3:0] rvfi_mem_rmask;\n logic [ 3:0] rvfi_mem_wmask;\n logic [31:0] rvfi_mem_rdata;\n logic [31:0] rvfi_mem_wdata;\n\n ibex_top #(\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 .RegFile ( RegFile ),\n .BranchTargetALU ( BranchTargetALU ),\n .ICache ( ICache ),\n .ICacheECC ( ICacheECC ),\n .BranchPredictor ( BranchPredictor ),\n .DbgTriggerEn ( DbgTriggerEn ),\n .DbgHwBreakNum ( DbgHwBreakNum ),\n .WritebackStage ( WritebackStage ),\n .SecureIbex ( SecureIbex ),\n .RndCnstLfsrSeed ( RndCnstLfsrSeed ),\n .RndCnstLfsrPerm ( RndCnstLfsrPerm ),\n .DmHaltAddr ( DmHaltAddr ),\n .DmExceptionAddr ( DmExceptionAddr )\n ) u_ibex_top (\n .clk_i,\n .rst_ni,\n\n .test_en_i,\n .scan_rst_ni,\n .ram_cfg_i,\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,\n .instr_rdata_intg_i,\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,\n .data_wdata_intg_o,\n .data_rdata_i,\n .data_rdata_intg_i,\n .data_err_i,\n\n .irq_software_i,\n .irq_timer_i,\n .irq_external_i,\n .irq_fast_i,\n .irq_nm_i,\n\n .debug_req_i,\n .crash_dump_o,\n\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\n .fetch_enable_i,\n .alert_minor_o,\n .alert_major_o,\n .core_sleep_o\n );\n\n ibex_tracer\n u_ibex_tracer (\n .clk_i,\n .rst_ni,\n\n .hart_id_i,\n\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 );\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/tracer.rst", "doc/03_reference/rvfi.rst", "doc/02_user/integration.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1735, "lang": "sv", "rtl_files": ["rtl/ibex_id_stage.sv"], "spec": "# Behavioral Specification: Instruction Decode and Execute Stage (ID/EX)\n\n## 1. Overview\n\nThe Instruction Decode and Execute (ID/EX) stage is the central execution unit of the Ibex processor. It receives instructions from the Instruction Fetch (IF) stage, decodes them, reads register operands, executes operations (either in one cycle or over multiple cycles), and writes results back to the register file. The stage also handles all control flow changes, exceptions, interrupts, and debug requests.\n\nThe stage operates in lockstep with the IF stage and, optionally, a third Writeback (WB) stage. It implements a small state machine to manage multi-cycle instructions (e.g., loads/stores, multi-cycle multipliers, dividers, branches, jumps) and stalls the pipeline as needed.\n\n## 2. External Interfaces\n\n### 2.1 Instruction Input from IF Stage\n\nThe ID/EX stage receives:\n- A **valid instruction signal** indicating a new instruction is present.\n- The **uncompressed 32-bit instruction data**.\n- A second copy of the instruction data (used for integrity checking; both copies must match).\n- A **16-bit compressed instruction** (used for CSR pipeline flush detection).\n- An **indicators** for whether the instruction is compressed, whether a branch predictor predicted it as taken, and whether it came from a compressed stream.\n- The **program counter (PC)** of the instruction.\n\nThe stage also receives **error signals** from the IF stage: a fetch error, and a fetch error that accounts for compressed instruction length (plus 2 bytes instead of 4).\n\n### 2.2 Instruction Output to IF Stage\n\nThe stage controls instruction fetch:\n- **Request new instruction** – asserted when the ID/EX is ready to accept the next instruction.\n- **Kill current instruction** – clears the IF–ID pipeline register (e.g., on branch mispredict, exception).\n- **Set PC** and **PC mux select** – to redirect fetch to a new address (branch target, exception vector, etc.).\n- **Not-taken branch address** – computed when branch predictor is enabled.\n- **Exception PC mux** and **exception cause** – for exception/interrupt handling.\n\n### 2.3 Register File Interface\n\nThe stage drives two read addresses and read enables to the register file. It receives read data for both operands. It also outputs:\n- Write address, write data, and write enable for the register file.\n- **Writeback address match flags** – indicates whether the read addresses match the write address from the writeback stage (used for hazard detection).\n\nThe register file is written only when the instruction is executing and no illegal CSR access is detected.\n\n### 2.4 ALU / Branch Target ALU\n\nOutputs:\n- ALU operation selector, two operand values (operand A and operand B).\n- For the optional **branch target ALU**: separate operand A and operand B (used to compute branch target simultaneously with condition evaluation).\n\n### 2.5 Multiplier/Divider\n\nOutputs:\n- Enable signals for multiply and divide.\n- Operation type (multiply, divide, remainder) and signed mode.\n- Operand A and B for the multiplier/divider.\n- A ready signal to indicate the multiplier/divider can proceed.\n\n### 2.6 Load-Store Unit (LSU)\n\nOutputs:\n- Request signal, write enable, data type (byte/halfword/word), sign extension control.\n- Write data (always the second register operand).\n- During misaligned accesses, the stage manipulates its internal ALU operand selection to generate the second address.\n\n### 2.7 CSR Interface\n\nOutputs:\n- CSR access request and operation type (read/write/set/clear).\n- An **op-enable** signal that is asserted only when the CSR instruction is actually executing.\n- Signals to save or restore CSR state for exceptions, interrupts, MRET, DRET, and debug.\n- **mtval** (machine trap value) output.\n- Inputs: privilege mode, mstatus TW bit, illegal CSR instruction flag, data independent timing flag.\n\nThe stage also generates **pipeline flush** signals when certain CSRs (e.g., MSTATUS, MIE, PMP CSRs, debug CSRs) are written with non-read operations. This flush ensures that the controller sees updated CSR values before proceeding.\n\n### 2.8 Writeback Stage Interface (Optional)\n\nWhen a third writeback stage is present:\n- Inputs: result from execute stage, CSR read data, writeback register write information (address, data, write enable), ready signal, outstanding load/store indicators, LSU response valid.\n- Outputs: write data and write enable for the register file, instruction type (load, store, other) for writeback, enable signal and ready handshake.\n\nThe ID/EX stage performs data forwarding from the writeback stage to read operands and stalls on load-use hazards until the load completes.\n\n### 2.9 Interrupt / Debug Signals\n\n- **Interrupt inputs**: MIE status, pending interrupt, individual interrupt sources, non-maskable interrupt.\n- **Debug inputs**: debug request, single-step, ebreak behavior in M‑ and U‑mode, trigger match.\n- **Outputs**: debug mode indicator, debug cause, CSR save for debug.\n\n### 2.10 Performance Counters\n\nThe stage outputs:\n- **Jump executed** – any unconditional jump instruction that completes.\n- **Branch executed** – any conditional branch instruction (taken or not).\n- **Taken branch executed** – a branch that was taken.\n- **Data-side wait** – the instruction in ID/EX is stalled because it is waiting for a memory access.\n- **Multiplier wait** – stalled due to a multiply operation not yet complete.\n- **Divider wait** – stalled due to a division operation not yet complete.\n- **Instruction ID done** – indicates the instruction has finished execution and, if writeback stage exists, is moving to writeback.\n\n## 3. Decode Behavior\n\nThe stage decodes the instruction into control signals for all execution units. Decoding also identifies:\n- Illegal instructions (including illegal compressed instructions, illegal CSR access, illegal DRET outside debug mode, illegal user‑mode instructions like MRET).\n- ebreak, ecall, mret, dret, wfi.\n- Whether the instruction is a jump or a branch.\n- Whether it requires multiple cycles (e.g., loads/stores, multiply, divide, certain bit‑manipulation instructions, branch with branch target ALU disabled, etc.).\n\nAn instruction is considered illegal if any of the decode‑level illegal signals are asserted, or if the CSR access is illegal, or if DRET is executed outside debug mode, or if MRET/WFI is executed in user mode with the TW bit set. Illegal instructions are never executed and cause an exception via the controller.\n\n## 4. Register File Operation\n\n**Read** \nThe stage requests two register reads every cycle that a valid, non‑illegal, non‑error instruction is present. Read enables are gated off for illegal or error instructions. The read data is used for ALU operands, store data, multiplier/divider operands, and branch target calculation.\n\n**Write** \nThe stage writes the register file only when an instruction is executing and no illegal CSR access is detected. The write data comes from either the ALU result or the CSR read data, selected based on the decoded instruction.\n\n**Writeback stage interaction** \nWhen a writeback stage is present, the ID/EX stage detects hazards where an instruction reads a register that the writeback stage is about to write. If the writeback data is from an ALU result (not a load), the stage forwards that data directly to the read operand, avoiding a stall. If the writeback data comes from a load (i.e., the result is not yet available), the ID/EX stage stalls until the load completes (load‑use hazard).\n\n## 5. Operand Selection\n\nThe stage selects values for the ALU and branch target ALU from the following sources:\n- Register file read data (forwarded from writeback if applicable).\n- The current PC.\n- Immediate values derived from the instruction (I‑type, S‑type, B‑type, U‑type, J‑type, or zero‑immediate for CSR instructions).\n- For misaligned load/store second access: the last address computed by the LSU.\n\nThe selection is driven by the decoder’s output, with the LSU misalignment override taking precedence.\n\n## 6. Multi‑Cycle Instruction Handling\n\nThe ID/EX stage contains a simple state machine that tracks whether the current instruction is in its first cycle or has entered a multi‑cycle execution state.\n\n**Single‑cycle instructions** (most integer computational, CSR accesses) complete in one cycle and do not stall beyond any pipeline dependencies.\n\n**Multi‑cycle instructions** cause the state machine to enter a MULTI_CYCLE state, during which the stage stalls and does not accept new instructions. The following instruction types may cause multi‑cycle execution:\n\n- **Loads/Stores** – Stall until the LSU responds. In a two‑stage pipeline, the first cycle always stalls; subsequent cycles stall until the response arrives. In a three‑stage pipeline, the stage may issue the request and move on, but stalls if there are outstanding memory accesses that could cause a precise exception.\n- **Multiplies (MUL, MULH)** – With a single‑cycle multiplier, only MULH stalls one cycle. With multi‑cycle multipliers, the instruction stalls for 2–4 cycles (fast) or up to 33 cycles (slow). Division always stalls for 1 cycle on divide‑by‑zero, otherwise 37 cycles.\n- **Branches (taken)** – With branch target ALU disabled, branches stall two cycles (one for condition, one for target). With branch target ALU enabled, taken branches stall one cycle. In fixed‑time execution mode (DataIndTiming=1), all branches stall two cycles regardless of taken/not‑taken.\n- **Jumps** – Jump with branch target ALU enabled completes in one cycle; without it, stalls one cycle.\n- **Special multi‑cycle bit‑manipulation instructions** – e.g., rotations, bit‑field place, CRC, ternary operations – stall one cycle.\n\nDuring the multi‑cycle state, the stage continues to hold the instruction and may keep the LSU, multiplier/divider, or branch control active.\n\n## 7. Branch and Jump Handling\n\n**Branches** \nThe stage evaluates the branch condition using the ALU output (comparison result). The branch decision (taken/not‑taken) is provided by the execute stage (ALU).\n\n- **Taken branch**: The stage asserts a branch‑set signal to the controller, which will flush the IF stage and redirect fetch to the branch target. The branch target is computed either by the main ALU (over two cycles) or by the branch target ALU (same cycle as condition). The stage also records that a branch set has occurred to avoid duplicate flush requests.\n- **Not‑taken branch**: No flush occurs. If a branch predictor indicated the branch would be taken, the stage may assert a not‑taken signal to correct the prediction.\n- **Branch predictor integration**: When a branch predictor is present, the stage uses the predicted taken indication. If the actual decision disagrees, it handles misprediction via the not‑taken or taken signals accordingly.\n\n**Jumps** \nUnconditional jumps (JAL, JALR) always force a new PC. The stage produces a jump‑set signal that triggers a flush and redirect. The target is computed using the same mechanisms as branches.\n\n**Branch target ALU** \nWhen enabled, a separate ALU computes the branch target in parallel with condition evaluation. This reduces the taken branch penalty from two cycles to one cycle (except in fixed‑time execution mode).\n\n**Alignment and return address** \nFor jumps and branches, the stage communicates the not‑taken address (next PC) to the IF stage when a branch predictor is enabled, allowing the predictor to learn the true not‑taken address.\n\n## 8. Exception, Interrupt, and Debug Handling\n\n**Exceptions** \nThe stage detects:\n- **Instruction fetch errors** – an error on the instruction fetch bus kills the current instruction and triggers an exception.\n- **Illegal instructions** – decode‑time illegal detection, illegal CSR access, illegal DRET/privileged instructions.\n- **Ecall, ebreak** – cause synchronous exceptions.\n- **Load/store errors** (from LSU) – cause precise exceptions from the writeback stage (if present) or directly from ID/EX (two‑stage pipeline).\n\nAll exception handling is performed by the controller block, which receives exception flags from the ID/EX stage. The stage outputs the appropriate exception cause and PC mux selection.\n\n**Interrupts** \nThe stage passes interrupt pending signals and individual interrupt sources to the controller. When an interrupt is taken, the controller saves the appropriate CSR state and redirects the PC. The stage provides CSR save/restore signals for this purpose.\n\n**Debug** \nThe stage handles debug entry (single‑step, trigger match, debug request), debug mode exit (DRET), and saves/restores debug CSRs. It also detects illegal DRET outside debug mode.\n\n**Pipeline flushes** \nThe stage generates a pipeline flush whenever certain CSRs are written (MSTATUS, MIE, PMP CSRs, debug CSRs) to ensure subsequent instructions see the updated state.\n\n## 9. Stall and Flush Conditions\n\nThe ID/EX stage may stall the pipeline for several reasons:\n\n- **Load‑use hazard** (three‑stage pipeline only) – the current instruction reads a register that is the target of an outstanding load.\n- **Memory access stall** – an outstanding load/store request is still pending or the LSU has not granted the request.\n- **Multi‑cycle operation stall** – a multiply, divide, branch, jump, or multi‑cycle ALU operation is in progress and not yet finished.\n- **Writeback stall** (three‑stage pipeline) – the instruction has finished execution but the writeback stage is not ready to accept it.\n- **Fixed‑time execution** – branch condition is computed one cycle early and re‑driven the next cycle, causing an extra stall.\n\nThe stage may also be flushed by the controller in response to exceptions, interrupts, debug entry, or branch/jump redirection. A flushed instruction does not complete and its results are discarded.\n\n## 10. Data Forwarding (Three‑Stage Pipeline)\n\nWhen a writeback stage is present, the ID/EX stage performs forwarding from the writeback stage to bypass the register file read data. This applies only to data that is already available (ALU results, CSR reads). Load data is not forwarded; a stall is used instead.\n\nThe stage outputs match flags (`rf_rd_a_wb_match_o`, `rf_rd_b_wb_match_o`) that indicate whether the current read addresses match the writeback write address. These are used for hazard detection.\n\n## 11. Performance Monitoring\n\nThe stage produces the following event signals for the performance counter block:\n- **Jump executed** – one pulse per completed jump instruction.\n- **Branch executed** – one pulse per branch instruction (regardless of taken/not‑taken).\n- **Taken branch executed** – one pulse per branch that was actually taken.\n- **Data‑side wait** – active while the instruction is stalled waiting for memory (load/store or outstanding access).\n- **Multiplier wait** – active during multiply stall cycles.\n- **Divider wait** – active during division stall cycles.\n- **Instruction ID done** – pulsed when the instruction has completed execution and can move to writeback (or retire in a two‑stage pipeline).\n\nThe `instr_perf_count_id_o` signal is used to count retired instructions (excluding traps, ebreak, ecall, and illegal instructions – those that cause exceptions are not counted toward `minstret`).\n\n## 12. Dependencies and Assumptions\n\n- The stage assumes the IF stage provides a stable instruction along with a valid signal; an instruction may be killed in the same cycle it becomes valid.\n- The register file read data is available in the same cycle as the read address and enable.\n- The ALU and multiplier/divider compute results combinationally or within the cycle; for multi‑cycle operations an external valid signal indicates completion.\n- The LSU may take multiple cycles; the stage adapts to either two‑stage or three‑stage pipeline configuration.\n- The decoder and controller are treated as separate sub‑blocks that the ID/EX stage instantiates and uses.\n- All control inputs (privilege mode, debug signals, interrupt lines) are assumed to be stable during instruction execution.", "commit_id": "23806e2ad7d0d6fab429ae227d9a45cbd42f0fb3", "timestamp": "2022-08-05T12:50:42+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "46404cf86f60f72fb84a2bc693d2ab08011bdb37", "pr_title": "[rtl] Do not register instruction fetch errors", "pr_body": "Registering instruction fetch errors causes problem in the case of seeing\r\na PMP execution access block. ID/EX stage learns about\r\nthe instruction that it executed should be blocked a\r\ncycle late. This commit fixes that.\r\n\r\nFound this one while working on fixing https://github.com/lowRISC/ibex/issues/1720. However it does not fully solves the issue because we are still seeing some mismatches because of some self modifying code problems.\r\n\r\nSigned-off-by: Canberk Topal ", "issue_title": "[dv] Exception divergence using MML PMP mode", "issue_body": "\r\nI'm seeing a divergence between Spike and Ibex when in MML mode and setting region 0 to read only. Spike throws a trap and Ibex zeroes out a destination register. I'm not sure if this is an issue with Spike, Ibex or with the UVM comparison.\r\n\r\n## Observed Behavior\r\n\r\nCosimulation result:\r\n```\r\nname: riscv_epmp_mml_read_only_test\r\nseed: 14822\r\nbinary: out/run/riscv_epmp_mml_read_only_test.14822/test.o\r\nuvm_log: out/run/riscv_epmp_mml_read_only_test.14822/rtl.log\r\nrtl_trace: out/run/riscv_epmp_mml_read_only_test.14822/trace_core_00000000.log\r\nrtl_trace_csv: out/run/riscv_epmp_mml_read_only_test.14822/trace_core_00000000.log.csv\r\niss_trace: \r\niss_trace_csv: \r\nen_cosim: True\r\ncosim_trace: \r\ncosim_trace_csv: \r\ncomparison_log: \r\npassed: False\r\nfailure_message: |-\r\n UVM_FATAL /home/mvdmaas/ibex/dv/uvm/core_ibex/common/ibex_cosim_agent/ibex_cosim_scoreboard.sv(131) @ 7304: uvm_test_top.env.cosim_agent.scoreboard [ibex_cosim_agent_pkg::ibex_cosim_scoreboard.run_cosim_rvfi] Cosim mismatch Synchronous trap was expected at ISS PC: 80001900 but DUT didn't report one at PC 80000118\r\n [FAILED]: sim error seen\r\n```\r\n\r\nIbex RVFI trace:\r\n```\r\nTime\tCycle\tPC\tInsn\tDecoded instruction\tRegister and memory contents\r\n 2524\t 24\t80000080\t400015b7\tlui\tx11,0x40001\t x11=0x40001000\r\n 2864\t 41\t80000084\t10658593\taddi\tx11,x11,262\t x11:0x40001000 x11=0x40001106\r\n 3004\t 48\t80000088\t30159073\tcsrrw\tx0,misa,x11\t x11:0x40001106 x0=0x00000000\r\n 3024\t 49\t8000008c\t0002c397\tauipc\tx7,0x2c\t x7=0x8002c08c\r\n 3444\t 70\t80000090\tc5838393\taddi\tx7,x7,-936\t x7:0x8002c08c x7=0x8002bce4\r\n 3724\t 84\t80000094\t00002597\tauipc\tx11,0x2\t x11=0x80002094\r\n 3744\t 85\t80000098\t86c58593\taddi\tx11,x11,-1940\t x11:0x80002094 x11=0x80001900\r\n 3944\t 95\t8000009c\t0015e593\tori\tx11,x11,1\t x11:0x80001900 x11=0x80001901\r\n 4364\t 116\t800000a0\t30559073\tcsrrw\tx0,mtvec,x11\t x11:0x80001901 x0=0x00000000\r\n 4384\t 117\t800000a4\t00002b17\tauipc\tx22,0x2\t x22=0x800020a4\r\n 4404\t 118\t800000a8\t2f0b0b13\taddi\tx22,x22,752\t x22:0x800020a4 x22=0x80002394\r\n 4424\t 119\t800000ac\t002b5b13\tsrli\tx22,x22,0x2\t x22:0x80002394 x22=0x200008e5\r\n 4584\t 127\t800000b0\t3b0b1073\tcsrrw\tx0,pmpaddr0,x22\t x22:0x200008e5 x0=0x00000000\r\n 4604\t 128\t800000b4\t74725073\tcsrrwi\tx0,0x747,4\t x0=0x00000000\r\n 4924\t 144\t800000b8\t08c00b13\taddi\tx22,x0,140\t x0:0x00000000 x22=0x0000008c\r\n 4944\t 145\t800000bc\t3a0b1073\tcsrrw\tx0,pmpcfg0,x22\t x22:0x0000008c x0=0x00000000\r\n 4964\t 146\t800000c0\t7472d073\tcsrrwi\tx0,0x747,5\t x0=0x00000000\r\n 4984\t 147\t800000c4\t00002b17\tauipc\tx22,0x2\t x22=0x800020c4\r\n 5024\t 149\t800000c8\t2d0b0b13\taddi\tx22,x22,720\t x22:0x800020c4 x22=0x80002394\r\n 5124\t 154\t800000cc\t6589\tc.lui\tx11,0x2\t x11=0x00002000\r\n 5544\t 175\t800000ce\t66658593\taddi\tx11,x11,1638\t x11:0x00002000 x11=0x00002666\r\n 5564\t 176\t800000d2\t9b2e\tc.add\tx22,x11\t x22:0x80002394 x11:0x00002666 x22=0x800049fa\r\n 5584\t 177\t800000d4\t002b5b13\tsrli\tx22,x22,0x2\t x22:0x800049fa x22=0x2000127e\r\n 5604\t 178\t800000d8\t3b1b1073\tcsrrw\tx0,pmpaddr1,x22\t x22:0x2000127e x0=0x00000000\r\n 5664\t 181\t800000dc\t00002b17\tauipc\tx22,0x2\t x22=0x800020dc\r\n 5804\t 188\t800000e0\t2b8b0b13\taddi\tx22,x22,696\t x22:0x800020dc x22=0x80002394\r\n 5824\t 189\t800000e4\t6595\tc.lui\tx11,0x5\t x11=0x00005000\r\n 5944\t 195\t800000e6\tccc58593\taddi\tx11,x11,-820\t x11:0x00005000 x11=0x00004ccc\r\n 5964\t 196\t800000ea\t9b2e\tc.add\tx22,x11\t x22:0x80002394 x11:0x00004ccc x22=0x80007060\r\n 6364\t 216\t800000ec\t002b5b13\tsrli\tx22,x22,0x2\t x22:0x80007060 x22=0x20001c18\r\n 6384\t 217\t800000f0\t3b2b1073\tcsrrw\tx0,pmpaddr2,x22\t x22:0x20001c18 x0=0x00000000\r\n 6644\t 230\t800000f4\t00002b17\tauipc\tx22,0x2\t x22=0x800020f4\r\n 6704\t 233\t800000f8\t2a0b0b13\taddi\tx22,x22,672\t x22:0x800020f4 x22=0x80002394\r\n 6724\t 234\t800000fc\t659d\tc.lui\tx11,0x7\t x11=0x00007000\r\n 6744\t 235\t800000fe\t33258593\taddi\tx11,x11,818\t x11:0x00007000 x11=0x00007332\r\n 6764\t 236\t80000102\t9b2e\tc.add\tx22,x11\t x22:0x80002394 x11:0x00007332 x22=0x800096c6\r\n 6784\t 237\t80000104\t002b5b13\tsrli\tx22,x22,0x2\t x22:0x800096c6 x22=0x200025b1\r\n 6924\t 244\t80000108\t3b3b1073\tcsrrw\tx0,pmpaddr3,x22\t x22:0x200025b1 x0=0x00000000\r\n 7104\t 253\t8000010c\t8f8f9b37\tlui\tx22,0x8f8f9\t x22=0x8f8f9000\r\n 7124\t 254\t80000110\tf8fb0b13\taddi\tx22,x22,-113\t x22:0x8f8f9000 x22=0x8f8f8f8f\r\n 7264\t 261\t80000114\t3a0b1073\tcsrrw\tx0,pmpcfg0,x22\t x22:0x8f8f8f8f x0=0x00000000\r\n 7284\t 262\t80000118\t00002b17\tauipc\tx22,0x2\t x22=0x80002118\r\n 7304\t 263\t8000011c\t27cb0b13\taddi\tx0,x0,636\t x0:0x00000000 x0=0x00000000\r\n```\r\n\r\nSpike RVFI trace:\r\n```\r\ncore 0: 0x80000080 (0x400015b7) lui a1, 0x40001\r\ncore 0: 3 0x80000080 (0x400015b7) x11 0x40001000\r\ncore 0: 0x80000084 (0x10658593) addi a1, a1, 262\r\ncore 0: 3 0x80000084 (0x10658593) x11 0x40001106\r\ncore 0: 0x80000088 (0x30159073) csrw misa, a1\r\ncore 0: 3 0x80000088 (0x30159073) c769_misa 0x40901104\r\ncore 0: 0x8000008c (0x0002c397) auipc t2, 0x2c\r\ncore 0: 3 0x8000008c (0x0002c397) x7 0x8002c08c\r\ncore 0: 0x80000090 (0xc5838393) addi t2, t2, -936\r\ncore 0: 3 0x80000090 (0xc5838393) x7 0x8002bce4\r\ncore 0: 0x80000094 (0x00002597) auipc a1, 0x2\r\ncore 0: 3 0x80000094 (0x00002597) x11 0x80002094\r\ncore 0: 0x80000098 (0x86c58593) addi a1, a1, -1940\r\ncore 0: 3 0x80000098 (0x86c58593) x11 0x80001900\r\ncore 0: 0x8000009c (0x0015e593) ori a1, a1, 1\r\ncore 0: 3 0x8000009c (0x0015e593) x11 0x80001901\r\ncore 0: 0x800000a0 (0x30559073) csrw mtvec, a1\r\ncore 0: 3 0x800000a0 (0x30559073) c773_mtvec 0x80001901\r\ncore 0: 0x800000a4 (0x00002b17) auipc s6, 0x2\r\ncore 0: 3 0x800000a4 (0x00002b17) x22 0x800020a4\r\ncore 0: 0x800000a8 (0x2f0b0b13) addi s6, s6, 752\r\ncore 0: 3 0x800000a8 (0x2f0b0b13) x22 0x80002394\r\ncore 0: 0x800000ac (0x002b5b13) srli s6, s6, 2\r\ncore 0: 3 0x800000ac (0x002b5b13) x22 0x200008e5\r\ncore 0: 0x800000b0 (0x3b0b1073) csrw pmpaddr0, s6\r\ncore 0: 3 0x800000b0 (0x3b0b1073) c944_pmpaddr0 0x200008e5\r\ncore 0: 0x800000b4 (0x74725073) csrwi mseccfg, 4\r\ncore 0: 3 0x800000b4 (0x74725073) c1863_mseccfg 0x00000004\r\ncore 0: 0x800000b8 (0x08c00b13) li s6, 140\r\ncore 0: 3 0x800000b8 (0x08c00b13) x22 0x0000008c\r\ncore 0: 0x800000bc (0x3a0b1073) csrw pmpcfg0, s6\r\ncore 0: 3 0x800000bc (0x3a0b1073) c928_pmpcfg0 0x0000008c\r\ncore 0: 0x800000c0 (0x7472d073) csrwi mseccfg, 5\r\ncore 0: 3 0x800000c0 (0x7472d073) c1863_mseccfg 0x00000005\r\ncore 0: 0x800000c4 (0x00002b17) auipc s6, 0x2\r\ncore 0: 3 0x800000c4 (0x00002b17) x22 0x800020c4\r\ncore 0: 0x800000c8 (0x2d0b0b13) addi s6, s6, 720\r\ncore 0: 3 0x800000c8 (0x2d0b0b13) x22 0x80002394\r\ncore 0: 0x800000cc (0x00006589) c.lui a1, 0x2\r\ncore 0: 3 0x800000cc (0x6589) x11 0x00002000\r\ncore 0: 0x800000ce (0x66658593) addi a1, a1, 1638\r\ncore 0: 3 0x800000ce (0x66658593) x11 0x00002666\r\ncore 0: 0x800000d2 (0x00009b2e) c.add s6, a1\r\ncore 0: 3 0x800000d2 (0x9b2e) x22 0x800049fa\r\ncore 0: 0x800000d4 (0x002b5b13) srli s6, s6, 2\r\ncore 0: 3 0x800000d4 (0x002b5b13) x22 0x2000127e\r\ncore 0: 0x800000d8 (0x3b1b1073) csrw pmpaddr1, s6\r\ncore 0: 3 0x800000d8 (0x3b1b1073) c945_pmpaddr1 0x2000127e\r\ncore 0: 0x800000dc (0x00002b17) auipc s6, 0x2\r\ncore 0: 3 0x800000dc (0x00002b17) x22 0x800020dc\r\ncore 0: 0x800000e0 (0x2b8b0b13) addi s6, s6, 696\r\ncore 0: 3 0x800000e0 (0x2b8b0b13) x22 0x80002394\r\ncore 0: 0x800000e4 (0x00006595) c.lui a1, 0x5\r\ncore 0: 3 0x800000e4 (0x6595) x11 0x00005000\r\ncore 0: 0x800000e6 (0xccc58593) addi a1, a1, -820\r\ncore 0: 3 0x800000e6 (0xccc58593) x11 0x00004ccc\r\ncore 0: 0x800000ea (0x00009b2e) c.add s6, a1\r\ncore 0: 3 0x800000ea (0x9b2e) x22 0x80007060\r\ncore 0: 0x800000ec (0x002b5b13) srli s6, s6, 2\r\ncore 0: 3 0x800000ec (0x002b5b13) x22 0x20001c18\r\ncore 0: 0x800000f0 (0x3b2b1073) csrw pmpaddr2, s6\r\ncore 0: 3 0x800000f0 (0x3b2b1073) c946_pmpaddr2 0x20001c18\r\ncore 0: 0x800000f4 (0x00002b17) auipc s6, 0x2\r\ncore 0: 3 0x800000f4 (0x00002b17) x22 0x800020f4\r\ncore 0: 0x800000f8 (0x2a0b0b13) addi s6, s6, 672\r\ncore 0: 3 0x800000f8 (0x2a0b0b13) x22 0x80002394\r\ncore 0: 0x800000fc (0x0000659d) c.lui a1, 0x7\r\ncore 0: 3 0x800000fc (0x659d) x11 0x00007000\r\ncore 0: 0x800000fe (0x33258593) addi a1, a1, 818\r\ncore 0: 3 0x800000fe (0x33258593) x11 0x00007332\r\ncore 0: 0x80000102 (0x00009b2e) c.add s6, a1\r\ncore 0: 3 0x80000102 (0x9b2e) x22 0x800096c6\r\ncore 0: 0x80000104 (0x002b5b13) srli s6, s6, 2\r\ncore 0: 3 0x80000104 (0x002b5b13) x22 0x200025b1\r\ncore 0: 0x80000108 (0x3b3b1073) csrw pmpaddr3, s6\r\ncore 0: 3 0x80000108 (0x3b3b1073) c947_pmpaddr3 0x200025b1\r\ncore 0: 0x8000010c (0x8f8f9b37) lui s6, 0x8f8f9\r\ncore 0: 3 0x8000010c (0x8f8f9b37) x22 0x8f8f9000\r\ncore 0: 0x80000110 (0xf8fb0b13) addi s6, s6, -113\r\ncore 0: 3 0x80000110 (0xf8fb0b13) x22 0x8f8f8f8f\r\ncore 0: 0x80000114 (0x3a0b1073) csrw pmpcfg0, s6\r\ncore 0: 3 0x80000114 (0x3a0b1073) c928_pmpcfg0 0x8f8f8f8f\r\ncore 0: exception trap_instruction_access_fault, epc 0x80000118\r\ncore 0: tval 0x80000118\r\n```\r\n\r\n## Expected Behavior\r\n\r\nNot sure if it's a bug in Spike, Ibex or the cosimulation environment\r\n\r\n## Steps to reproduce the issue\r\n\r\nUsing the following commands from the root of the ibex repo:\r\n```console\r\ncd dv/uvm/core_ibex\r\nmake -j7 --keep-going IBEX_CONFIG=opentitan ITERATIONS=1 SEED=14822 TEST=riscv_epmp_mml_read_only_test WAVES=0 COV=0\r\n```\r\n\r\n## My Environment\r\n\r\n\r\n\r\n**EDA tool and version:**\r\n\r\nUsing Spike version ibex_cosim on commit: 9af9730baf7b956c3072c1b436d867aca5ef8f4c\r\n\r\n**Operating system:**\r\n\r\nUbuntu Linux 20.04\r\n\r\n**Version of the Ibex source code:**\r\n\r\nCurrently running inside this PR: https://github.com/lowRISC/ibex/pull/1695\r\n", "commit_message": "[rtl] Flush controller in PMP CSR write ops\n\nAs Greg pointed out:\n\nWhen we have an instruction in ID/EX that writes a PMP register that\nupdate gets written to the CSR the same cycle the next instruction\nmoves from IF to ID/EX with it's PMP check done with the old value.\n\nThe solution is to flush the pipeline when we get a PMP CSR write.\n\nSigned-off-by: Canberk Topal ", "fix_patch": "diff --git a/rtl/ibex_id_stage.sv b/rtl/ibex_id_stage.sv\nindex a1c9c0f82c..9cdc64d3f9 100644\n--- a/rtl/ibex_id_stage.sv\n+++ b/rtl/ibex_id_stage.sv\n@@ -502,7 +502,7 @@ module ibex_id_stage #(\n );\n \n /////////////////////////////////\n- // CSR-related pipline flushes //\n+ // CSR-related pipeline flushes //\n /////////////////////////////////\n always_comb begin : csr_pipeline_flushes\n csr_pipe_flush = 1'b0;\n@@ -511,10 +511,14 @@ module ibex_id_stage #(\n // - When enabling interrupts, pending IRQs become visible to the controller only during\n // the next cycle. If during that cycle the core disables interrupts again, it does not\n // see any pending IRQs and consequently does not start to handle interrupts.\n+ // - When modifying any PMP CSR, PMP check of the next instruction might get invalidated.\n+ // Hence, a pipeline flush is needed to instantiate another PMP check with the updated CSRs.\n // - When modifying debug CSRs - TODO: Check if this is really needed\n if (csr_op_en_o == 1'b1 && (csr_op_o == CSR_OP_WRITE || csr_op_o == CSR_OP_SET)) begin\n- if (csr_num_e'(instr_rdata_i[31:20]) == CSR_MSTATUS ||\n- csr_num_e'(instr_rdata_i[31:20]) == CSR_MIE) begin\n+ if (csr_num_e'(instr_rdata_i[31:20]) == CSR_MSTATUS ||\n+ csr_num_e'(instr_rdata_i[31:20]) == CSR_MIE ||\n+ // To catch all PMPCFG/PMPADDR registers, get the shared top most 7 bits.\n+ instr_rdata_i[31:25] == 7'h1D) begin\n csr_pipe_flush = 1'b1;\n end\n end else if (csr_op_en_o == 1'b1 && csr_op_o != CSR_OP_READ) begin\n", "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`include \"dv_fcov_macros.svh\"\n\nmodule ibex_id_stage #(\n parameter bit RV32E = 0,\n parameter ibex_pkg::rv32m_e RV32M = ibex_pkg::RV32MFast,\n parameter ibex_pkg::rv32b_e RV32B = ibex_pkg::RV32BNone,\n parameter bit DataIndTiming = 1'b0,\n parameter bit BranchTargetALU = 0,\n parameter bit WritebackStage = 0,\n parameter bit BranchPredictor = 0,\n parameter bit MemECC = 1'b0\n) (\n input logic clk_i,\n input logic rst_ni,\n\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 [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 input logic instr_bp_taken_i,\n output logic instr_req_o,\n output logic instr_first_cycle_id_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 output logic icache_inval_o,\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 logic nt_branch_mispredict_o,\n output logic [31:0] nt_branch_addr_o,\n output ibex_pkg::exc_pc_sel_e exc_pc_mux_o,\n output ibex_pkg::exc_cause_t exc_cause_o,\n\n input logic illegal_c_insn_i,\n input logic instr_fetch_err_i,\n input logic instr_fetch_err_plus2_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_resp_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 // Multicycle Operation Stage Register\n input logic [1:0] imd_val_we_ex_i,\n input logic [33:0] imd_val_d_ex_i[2],\n output logic [33:0] imd_val_q_ex_o[2],\n\n // Branch target ALU\n output logic [31:0] bt_a_operand_o,\n output logic [31:0] bt_b_operand_o,\n\n // MUL, DIV\n output logic mult_en_ex_o,\n output logic div_en_ex_o,\n output logic mult_sel_ex_o,\n output logic div_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 output logic multdiv_ready_id_o,\n\n // CSR\n output logic csr_access_o,\n output ibex_pkg::csr_op_e csr_op_o,\n output logic csr_op_en_o,\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 input logic csr_mstatus_tw_i,\n input logic illegal_csr_insn_i,\n input logic data_ind_timing_i,\n\n // Interface to load store unit\n output logic lsu_req_o,\n output logic lsu_we_o,\n output logic [1:0] lsu_type_o,\n output logic lsu_sign_ext_o,\n output logic [31:0] lsu_wdata_o,\n\n input logic lsu_req_done_i, // Data req to LSU is complete and\n // instruction can move to writeback\n // (only relevant where writeback stage is\n // present)\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 input logic lsu_load_intg_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] result_ex_i,\n input logic [31:0] csr_rdata_i,\n\n // Register file read\n output logic [4:0] rf_raddr_a_o,\n input logic [31:0] rf_rdata_a_i,\n output logic [4:0] rf_raddr_b_o,\n input logic [31:0] rf_rdata_b_i,\n output logic rf_ren_a_o,\n output logic rf_ren_b_o,\n\n // Register file write (via writeback)\n output logic [4:0] rf_waddr_id_o,\n output logic [31:0] rf_wdata_id_o,\n output logic rf_we_id_o,\n output logic rf_rd_a_wb_match_o,\n output logic rf_rd_b_wb_match_o,\n\n // Register write information from writeback (for resolving data hazards)\n input logic [4:0] rf_waddr_wb_i,\n input logic [31:0] rf_wdata_fwd_wb_i,\n input logic rf_write_wb_i,\n\n output logic en_wb_o,\n output ibex_pkg::wb_instr_type_e instr_type_wb_o,\n output logic instr_perf_count_id_o,\n input logic ready_wb_i,\n input logic outstanding_load_wb_i,\n input logic outstanding_store_wb_i,\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 perf_dside_wait_o, // instruction in ID/EX is awaiting memory\n // access to finish before proceeding\n output logic perf_mul_wait_o,\n output logic perf_div_wait_o,\n output logic instr_id_done_o\n);\n\n import ibex_pkg::*;\n\n // Decoder/Controller, ID stage internal signals\n logic illegal_insn_dec;\n logic illegal_dret_insn;\n logic illegal_umode_insn;\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 wb_exception;\n logic id_exception;\n\n logic branch_in_dec;\n logic branch_set, branch_set_raw, branch_set_raw_d;\n logic branch_jump_set_done_q, branch_jump_set_done_d;\n logic branch_not_set;\n logic branch_taken;\n logic jump_in_dec;\n logic jump_set_dec;\n logic jump_set, jump_set_raw;\n\n logic instr_first_cycle;\n logic instr_executing_spec;\n logic instr_executing;\n logic instr_done;\n logic controller_run;\n logic stall_ld_hz;\n logic stall_mem;\n logic stall_multdiv;\n logic stall_branch;\n logic stall_jump;\n logic stall_id;\n logic stall_wb;\n logic flush_id;\n logic multicycle_done;\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\n rf_wd_sel_e rf_wdata_sel;\n logic rf_we_dec, rf_we_raw;\n logic rf_ren_a, rf_ren_b;\n logic rf_ren_a_dec, rf_ren_b_dec;\n\n // Read enables should only be asserted for valid and legal instructions\n assign rf_ren_a = instr_valid_i & ~instr_fetch_err_i & ~illegal_insn_o & rf_ren_a_dec;\n assign rf_ren_b = instr_valid_i & ~instr_fetch_err_i & ~illegal_insn_o & rf_ren_b_dec;\n\n assign rf_ren_a_o = rf_ren_a;\n assign rf_ren_b_o = rf_ren_b;\n\n logic [31:0] rf_rdata_a_fwd;\n logic [31:0] rf_rdata_b_fwd;\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 logic alu_multicycle_dec;\n logic stall_alu;\n\n logic [33:0] imd_val_q[2];\n\n op_a_sel_e bt_a_mux_sel;\n imm_b_sel_e bt_b_mux_sel;\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_en_dec;\n md_op_e multdiv_operator;\n logic [1:0] multdiv_signed_mode;\n\n // Data Memory Control\n logic lsu_we;\n logic [1:0] lsu_type;\n logic lsu_sign_ext;\n logic lsu_req, lsu_req_dec;\n logic data_req_allowed;\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 MUXES //\n ///////////////////\n\n // Main ALU immediate MUX for Operand A\n assign imm_a = (imm_a_mux_sel == IMM_A_Z) ? zimm_rs1_type : '0;\n\n // Main 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 = rf_rdata_a_fwd;\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 if (BranchTargetALU) begin : g_btalu_muxes\n // Branch target ALU operand A mux\n always_comb begin : bt_operand_a_mux\n unique case (bt_a_mux_sel)\n OP_A_REG_A: bt_a_operand_o = rf_rdata_a_fwd;\n OP_A_CURRPC: bt_a_operand_o = pc_id_i;\n default: bt_a_operand_o = pc_id_i;\n endcase\n end\n\n // Branch target ALU operand B mux\n always_comb begin : bt_immediate_b_mux\n unique case (bt_b_mux_sel)\n IMM_B_I: bt_b_operand_o = imm_i_type;\n IMM_B_B: bt_b_operand_o = imm_b_type;\n IMM_B_J: bt_b_operand_o = imm_j_type;\n IMM_B_INCR_PC: bt_b_operand_o = instr_is_compressed_i ? 32'h2 : 32'h4;\n default: bt_b_operand_o = instr_is_compressed_i ? 32'h2 : 32'h4;\n endcase\n end\n\n // Reduced main ALU 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_U: imm_b = imm_u_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 `ASSERT(IbexImmBMuxSelValid, instr_valid_i |-> imm_b_mux_sel inside {\n IMM_B_I,\n IMM_B_S,\n IMM_B_U,\n IMM_B_INCR_PC,\n IMM_B_INCR_ADDR})\n end else begin : g_nobtalu\n op_a_sel_e unused_a_mux_sel;\n imm_b_sel_e unused_b_mux_sel;\n\n assign unused_a_mux_sel = bt_a_mux_sel;\n assign unused_b_mux_sel = bt_b_mux_sel;\n assign bt_a_operand_o = '0;\n assign bt_b_operand_o = '0;\n\n // Full main ALU 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 `ASSERT(IbexImmBMuxSelValid, instr_valid_i |-> 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 end\n\n // ALU MUX for Operand B\n assign alu_operand_b = (alu_op_b_mux_sel == OP_B_IMM) ? imm_b : rf_rdata_b_fwd;\n\n /////////////////////////////////////////\n // Multicycle Operation Stage Register //\n /////////////////////////////////////////\n\n for (genvar i = 0; i < 2; i++) begin : gen_intermediate_val_reg\n always_ff @(posedge clk_i or negedge rst_ni) begin : intermediate_val_reg\n if (!rst_ni) begin\n imd_val_q[i] <= '0;\n end else if (imd_val_we_ex_i[i]) begin\n imd_val_q[i] <= imd_val_d_ex_i[i];\n end\n end\n end\n\n assign imd_val_q_ex_o = imd_val_q;\n\n ///////////////////////\n // Register File MUX //\n ///////////////////////\n\n // Suppress register write if there is an illegal CSR access or instruction is not executing\n assign rf_we_id_o = rf_we_raw & instr_executing & ~illegal_csr_insn_i;\n\n // Register file write data mux\n always_comb begin : rf_wdata_id_mux\n unique case (rf_wdata_sel)\n RF_WD_EX: rf_wdata_id_o = result_ex_i;\n RF_WD_CSR: rf_wdata_id_o = csr_rdata_i;\n default: rf_wdata_id_o = result_ex_i;\n endcase\n end\n\n /////////////\n // Decoder //\n /////////////\n\n ibex_decoder #(\n .RV32E (RV32E),\n .RV32M (RV32M),\n .RV32B (RV32B),\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_dec),\n .branch_taken_i(branch_taken),\n .icache_inval_o(icache_inval_o),\n\n // from IF-ID pipeline register\n .instr_first_cycle_i(instr_first_cycle),\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 .bt_a_mux_sel_o (bt_a_mux_sel),\n .bt_b_mux_sel_o (bt_b_mux_sel),\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 .rf_wdata_sel_o(rf_wdata_sel),\n .rf_we_o (rf_we_dec),\n\n .rf_raddr_a_o(rf_raddr_a_o),\n .rf_raddr_b_o(rf_raddr_b_o),\n .rf_waddr_o (rf_waddr_id_o),\n .rf_ren_a_o (rf_ren_a_dec),\n .rf_ren_b_o (rf_ren_b_dec),\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 .alu_multicycle_o (alu_multicycle_dec),\n\n // MULT & DIV\n .mult_en_o (mult_en_dec),\n .div_en_o (div_en_dec),\n .mult_sel_o (mult_sel_ex_o),\n .div_sel_o (div_sel_ex_o),\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\n // LSU\n .data_req_o (lsu_req_dec),\n .data_we_o (lsu_we),\n .data_type_o (lsu_type),\n .data_sign_extension_o(lsu_sign_ext),\n\n // jump/branches\n .jump_in_dec_o (jump_in_dec),\n .branch_in_dec_o(branch_in_dec)\n );\n\n /////////////////////////////////\n // CSR-related pipeline flushes //\n /////////////////////////////////\n always_comb begin : csr_pipeline_flushes\n csr_pipe_flush = 1'b0;\n\n // A pipeline flush is needed to let the controller react after modifying certain CSRs:\n // - When enabling interrupts, pending IRQs become visible to the controller only during\n // the next cycle. If during that cycle the core disables interrupts again, it does not\n // see any pending IRQs and consequently does not start to handle interrupts.\n // - When modifying any PMP CSR, PMP check of the next instruction might get invalidated.\n // Hence, a pipeline flush is needed to instantiate another PMP check with the updated CSRs.\n // - When modifying debug CSRs - TODO: Check if this is really needed\n if (csr_op_en_o == 1'b1 && (csr_op_o == CSR_OP_WRITE || csr_op_o == CSR_OP_SET)) begin\n if (csr_num_e'(instr_rdata_i[31:20]) == CSR_MSTATUS ||\n csr_num_e'(instr_rdata_i[31:20]) == CSR_MIE ||\n // To catch all PMPCFG/PMPADDR registers, get the shared top most 7 bits.\n instr_rdata_i[31:25] == 7'h1D) begin\n csr_pipe_flush = 1'b1;\n end\n end else if (csr_op_en_o == 1'b1 && csr_op_o != CSR_OP_READ) begin\n if (csr_num_e'(instr_rdata_i[31:20]) == CSR_DCSR ||\n csr_num_e'(instr_rdata_i[31:20]) == CSR_DPC ||\n csr_num_e'(instr_rdata_i[31:20]) == CSR_DSCRATCH0 ||\n csr_num_e'(instr_rdata_i[31:20]) == CSR_DSCRATCH1) begin\n csr_pipe_flush = 1'b1;\n end\n end\n end\n\n ////////////////\n // Controller //\n ////////////////\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_insn = dret_insn_dec & ~debug_mode_o;\n // Some instructions can only be executed in M-Mode\n assign illegal_umode_insn = (priv_mode_i != PRIV_LVL_M) &\n // MRET must be in M-Mode. TW means trap WFI to M-Mode.\n (mret_insn_dec | (csr_mstatus_tw_i & wfi_insn_dec));\n\n assign illegal_insn_o = instr_valid_i &\n (illegal_insn_dec | illegal_csr_insn_i | illegal_dret_insn | illegal_umode_insn);\n\n ibex_controller #(\n .WritebackStage (WritebackStage),\n .BranchPredictor(BranchPredictor),\n .MemECC(MemECC)\n ) controller_i (\n .clk_i (clk_i),\n .rst_ni(rst_ni),\n\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_bp_taken_i (instr_bp_taken_i),\n .instr_fetch_err_i (instr_fetch_err_i),\n .instr_fetch_err_plus2_i(instr_fetch_err_plus2_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 .controller_run_o (controller_run),\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 .nt_branch_mispredict_o(nt_branch_mispredict_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 .load_intg_err_i(lsu_load_intg_err_i),\n .store_err_i (lsu_store_err_i),\n .wb_exception_o (wb_exception),\n .id_exception_o (id_exception),\n\n // jump/branch control\n .branch_set_i (branch_set),\n .branch_not_set_i (branch_not_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_ext_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_save_wb_o (csr_save_wb_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\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_id_i(stall_id),\n .stall_wb_i(stall_wb),\n .flush_id_o(flush_id),\n .ready_wb_i(ready_wb_i),\n\n // Performance Counters\n .perf_jump_o (perf_jump_o),\n .perf_tbranch_o(perf_tbranch_o)\n );\n\n assign multdiv_en_dec = mult_en_dec | div_en_dec;\n\n assign lsu_req = instr_executing ? data_req_allowed & lsu_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 assign lsu_req_o = lsu_req;\n assign lsu_we_o = lsu_we;\n assign lsu_type_o = lsu_type;\n assign lsu_sign_ext_o = lsu_sign_ext;\n assign lsu_wdata_o = rf_rdata_b_fwd;\n // csr_op_en_o is set when CSR access should actually happen.\n // csv_access_o is set when CSR access instruction is present and is used to compute whether a CSR\n // access is illegal. A combinational loop would be created if csr_op_en_o was used along (as\n // asserting it for an illegal csr access would result in a flush that would need to deassert it).\n assign csr_op_en_o = csr_access_o & instr_executing & instr_id_done_o;\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 assign mult_en_ex_o = mult_en_id;\n assign div_en_ex_o = div_en_id;\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 = rf_rdata_a_fwd;\n assign multdiv_operand_b_ex_o = rf_rdata_b_fwd;\n\n ////////////////////////\n // Branch set control //\n ////////////////////////\n\n if (BranchTargetALU && !DataIndTiming) 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_raw = branch_set_raw_d;\n end else begin : g_branch_set_flop\n // SEC_CM: CORE.DATA_REG_SW.SCA\n // Branch set flopped without branch target ALU, or in fixed time execution mode\n // (condition pass/fail used next cycle where branch target is calculated)\n logic branch_set_raw_q;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n branch_set_raw_q <= 1'b0;\n end else begin\n branch_set_raw_q <= branch_set_raw_d;\n end\n end\n\n // Branches always take two cycles in fixed time execution mode, with or without the branch\n // target ALU (to avoid a path from the branch decision into the branch target ALU operand\n // muxing).\n assign branch_set_raw = (BranchTargetALU && !data_ind_timing_i) ? branch_set_raw_d :\n branch_set_raw_q;\n\n end\n\n // Track whether the current instruction in ID/EX has done a branch or jump set.\n assign branch_jump_set_done_d = (branch_set_raw | jump_set_raw | branch_jump_set_done_q) &\n ~instr_valid_clear_o;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n branch_jump_set_done_q <= 1'b0;\n end else begin\n branch_jump_set_done_q <= branch_jump_set_done_d;\n end\n end\n\n // the _raw signals from the state machine may be asserted for multiple cycles when\n // instr_executing_spec is asserted and instr_executing is not asserted. This may occur where\n // a memory error is seen or a there are outstanding memory accesses (indicate a load or store is\n // in the WB stage). The branch or jump speculatively begins the fetch but is held back from\n // completing until it is certain the outstanding access hasn't seen a memory error. This logic\n // ensures only the first cycle of a branch or jump set is sent to the controller to prevent\n // needless extra IF flushes and fetches.\n assign jump_set = jump_set_raw & ~branch_jump_set_done_q;\n assign branch_set = branch_set_raw & ~branch_jump_set_done_q;\n\n // Branch condition is calculated in the first cycle and flopped for use in the second cycle\n // (only used in fixed time execution mode to determine branch destination).\n if (DataIndTiming) begin : g_sec_branch_taken\n // SEC_CM: CORE.DATA_REG_SW.SCA\n logic branch_taken_q;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n branch_taken_q <= 1'b0;\n end else begin\n branch_taken_q <= branch_decision_i;\n end\n end\n\n assign branch_taken = ~data_ind_timing_i | branch_taken_q;\n\n end else begin : g_nosec_branch_taken\n\n // Signal unused without fixed time execution mode - only taken branches will trigger\n // branch_set_raw\n assign branch_taken = 1'b1;\n\n end\n\n // Holding branch_set/jump_set high for more than one cycle should not cause a functional issue.\n // However it could generate needless prefetch buffer flushes and instruction fetches. The ID/EX\n // designs ensures that this never happens for non-predicted branches.\n `ASSERT(NeverDoubleBranch, branch_set & ~instr_bp_taken_i |=> ~branch_set)\n `ASSERT(NeverDoubleJump, jump_set & ~instr_bp_taken_i |=> ~jump_set)\n\n //////////////////////////////\n // Branch not-taken address //\n //////////////////////////////\n\n if (BranchPredictor) begin : g_calc_nt_addr\n assign nt_branch_addr_o = pc_id_i + (instr_is_compressed_i ? 32'd2 : 32'd4);\n end else begin : g_n_calc_nt_addr\n assign nt_branch_addr_o = 32'd0;\n end\n\n ///////////////\n // ID-EX FSM //\n ///////////////\n\n typedef enum logic { FIRST_CYCLE, MULTI_CYCLE } id_fsm_e;\n id_fsm_e id_fsm_q, id_fsm_d;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin : id_pipeline_reg\n if (!rst_ni) begin\n id_fsm_q <= FIRST_CYCLE;\n end else if (instr_executing) begin\n id_fsm_q <= id_fsm_d;\n end\n end\n\n // ID/EX stage can be in two states, FIRST_CYCLE and MULTI_CYCLE. An instruction enters\n // MULTI_CYCLE if it requires multiple cycles to complete regardless of stalls and other\n // considerations. An instruction may be held in FIRST_CYCLE if it's unable to begin executing\n // (this is controlled by instr_executing).\n\n always_comb begin\n id_fsm_d = id_fsm_q;\n rf_we_raw = rf_we_dec;\n stall_multdiv = 1'b0;\n stall_jump = 1'b0;\n stall_branch = 1'b0;\n stall_alu = 1'b0;\n branch_set_raw_d = 1'b0;\n branch_not_set = 1'b0;\n jump_set_raw = 1'b0;\n perf_branch_o = 1'b0;\n\n if (instr_executing_spec) begin\n unique case (id_fsm_q)\n FIRST_CYCLE: begin\n unique case (1'b1)\n lsu_req_dec: begin\n if (!WritebackStage) begin\n // LSU operation\n id_fsm_d = MULTI_CYCLE;\n end else begin\n if(~lsu_req_done_i) begin\n id_fsm_d = MULTI_CYCLE;\n end\n end\n end\n multdiv_en_dec: begin\n // MUL or DIV operation\n if (~ex_valid_i) begin\n // When single-cycle multiply is configured mul can finish in the first cycle so\n // only enter MULTI_CYCLE state if a result isn't immediately available\n id_fsm_d = MULTI_CYCLE;\n rf_we_raw = 1'b0;\n stall_multdiv = 1'b1;\n end\n end\n branch_in_dec: begin\n // cond branch operation\n // All branches take two cycles in fixed time execution mode, regardless of branch\n // condition.\n // SEC_CM: CORE.DATA_REG_SW.SCA\n id_fsm_d = (data_ind_timing_i || (!BranchTargetALU && branch_decision_i)) ?\n MULTI_CYCLE : FIRST_CYCLE;\n stall_branch = (~BranchTargetALU & branch_decision_i) | data_ind_timing_i;\n branch_set_raw_d = (branch_decision_i | data_ind_timing_i);\n\n if (BranchPredictor) begin\n branch_not_set = ~branch_decision_i;\n end\n\n perf_branch_o = 1'b1;\n end\n jump_in_dec: begin\n // uncond branch operation\n // BTALU means jumps only need one cycle\n id_fsm_d = BranchTargetALU ? FIRST_CYCLE : MULTI_CYCLE;\n stall_jump = ~BranchTargetALU;\n jump_set_raw = jump_set_dec;\n end\n alu_multicycle_dec: begin\n stall_alu = 1'b1;\n id_fsm_d = MULTI_CYCLE;\n rf_we_raw = 1'b0;\n end\n default: begin\n id_fsm_d = FIRST_CYCLE;\n end\n endcase\n end\n\n MULTI_CYCLE: begin\n if(multdiv_en_dec) begin\n rf_we_raw = rf_we_dec & ex_valid_i;\n end\n\n if (multicycle_done & ready_wb_i) begin\n id_fsm_d = FIRST_CYCLE;\n end else begin\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_fsm_d = FIRST_CYCLE;\n end\n endcase\n end\n end\n\n // Note for the two-stage configuration ready_wb_i is always set\n assign multdiv_ready_id_o = ready_wb_i;\n\n `ASSERT(StallIDIfMulticycle, (id_fsm_q == FIRST_CYCLE) & (id_fsm_d == MULTI_CYCLE) |-> stall_id)\n\n\n // Stall ID/EX stage for reason that relates to instruction in ID/EX, update assertion below if\n // modifying this.\n assign stall_id = stall_ld_hz | stall_mem | stall_multdiv | stall_jump | stall_branch |\n stall_alu;\n\n // Generally illegal instructions have no reason to stall, however they must still stall waiting\n // for outstanding memory requests so exceptions related to them take priority over the illegal\n // instruction exception.\n `ASSERT(IllegalInsnStallMustBeMemStall, illegal_insn_o & stall_id |-> stall_mem &\n ~(stall_ld_hz | stall_multdiv | stall_jump | stall_branch | stall_alu))\n\n assign instr_done = ~stall_id & ~flush_id & instr_executing;\n\n // Signal instruction in ID is in it's first cycle. It can remain in its\n // first cycle if it is stalled.\n assign instr_first_cycle = instr_valid_i & (id_fsm_q == FIRST_CYCLE);\n // Used by RVFI to know when to capture register read data\n // Used by ALU to access RS3 if ternary instruction.\n assign instr_first_cycle_id_o = instr_first_cycle;\n\n if (WritebackStage) begin : gen_stall_mem\n // Register read address matches write address in WB\n logic rf_rd_a_wb_match;\n logic rf_rd_b_wb_match;\n // Hazard between registers being read and written\n logic rf_rd_a_hz;\n logic rf_rd_b_hz;\n\n logic outstanding_memory_access;\n\n logic instr_kill;\n\n assign multicycle_done = lsu_req_dec ? ~stall_mem : ex_valid_i;\n\n // Is a memory access ongoing that isn't finishing this cycle\n assign outstanding_memory_access = (outstanding_load_wb_i | outstanding_store_wb_i) &\n ~lsu_resp_valid_i;\n\n // Can start a new memory access if any previous one has finished or is finishing\n assign data_req_allowed = ~outstanding_memory_access;\n\n // Instruction won't execute because:\n // - There is a pending exception in writeback\n // The instruction in ID/EX will be flushed and the core will jump to an exception handler\n // - The controller isn't running instructions\n // This either happens in preparation for a flush and jump to an exception handler e.g. in\n // response to an IRQ or debug request or whilst the core is sleeping or resetting/fetching\n // first instruction in which case any valid instruction in ID/EX should be ignored.\n // - There was an error on instruction fetch\n assign instr_kill = instr_fetch_err_i |\n wb_exception |\n id_exception |\n ~controller_run;\n\n // With writeback stage instructions must be prevented from executing if there is:\n // - A load hazard\n // - A pending memory access\n // If it receives an error response this results in a precise exception from WB so ID/EX\n // instruction must not execute until error response is known).\n // - A load/store error\n // This will cause a precise exception for the instruction in WB so ID/EX instruction must not\n // execute\n //\n // instr_executing_spec is a speculative signal. It indicates an instruction can execute\n // assuming there are no exceptions from writeback and any outstanding memory access won't\n // receive an error. It is required so branch and jump requests don't factor in an incoming dmem\n // error (that in turn would factor directly into imem requests leading to a feedthrough path).\n //\n // instr_executing is the full signal, it will only allow execution once any potential\n // exceptions from writeback have been resolved.\n assign instr_executing_spec = instr_valid_i &\n ~instr_fetch_err_i &\n controller_run &\n ~stall_ld_hz;\n\n assign instr_executing = instr_valid_i &\n ~instr_kill &\n ~stall_ld_hz &\n ~outstanding_memory_access;\n\n `ASSERT(IbexExecutingSpecIfExecuting, instr_executing |-> instr_executing_spec)\n\n `ASSERT(IbexStallIfValidInstrNotExecuting,\n instr_valid_i & ~instr_kill & ~instr_executing |-> stall_id)\n\n `ASSERT(IbexCannotRetireWithPendingExceptions,\n instr_done |-> ~(wb_exception | outstanding_memory_access))\n\n // Stall for reasons related to memory:\n // * There is an outstanding memory access that won't resolve this cycle (need to wait to allow\n // precise exceptions)\n // * There is a load/store request not being granted or which is unaligned and waiting to issue\n // a second request (needs to stay in ID for the address calculation)\n assign stall_mem = instr_valid_i &\n (outstanding_memory_access | (lsu_req_dec & ~lsu_req_done_i));\n\n // If we stall a load in ID for any reason, it must not make an LSU request\n // (otherwide we might issue two requests for the same instruction)\n `ASSERT(IbexStallMemNoRequest,\n instr_valid_i & lsu_req_dec & ~instr_done |-> ~lsu_req_done_i)\n\n assign rf_rd_a_wb_match = (rf_waddr_wb_i == rf_raddr_a_o) & |rf_raddr_a_o;\n assign rf_rd_b_wb_match = (rf_waddr_wb_i == rf_raddr_b_o) & |rf_raddr_b_o;\n\n assign rf_rd_a_wb_match_o = rf_rd_a_wb_match;\n assign rf_rd_b_wb_match_o = rf_rd_b_wb_match;\n\n // If instruction is reading register that load will be writing stall in\n // ID until load is complete. No need to stall when reading zero register.\n assign rf_rd_a_hz = rf_rd_a_wb_match & rf_ren_a;\n assign rf_rd_b_hz = rf_rd_b_wb_match & rf_ren_b;\n\n // If instruction is read register that writeback is writing forward writeback data to read\n // data. Note this doesn't factor in load data as it arrives too late, such hazards are\n // resolved via a stall (see above).\n assign rf_rdata_a_fwd = rf_rd_a_wb_match & rf_write_wb_i ? rf_wdata_fwd_wb_i : rf_rdata_a_i;\n assign rf_rdata_b_fwd = rf_rd_b_wb_match & rf_write_wb_i ? rf_wdata_fwd_wb_i : rf_rdata_b_i;\n\n assign stall_ld_hz = outstanding_load_wb_i & (rf_rd_a_hz | rf_rd_b_hz);\n\n assign instr_type_wb_o = ~lsu_req_dec ? WB_INSTR_OTHER :\n lsu_we ? WB_INSTR_STORE :\n WB_INSTR_LOAD;\n\n assign instr_id_done_o = en_wb_o & ready_wb_i;\n\n // Stall ID/EX as instruction in ID/EX cannot proceed to writeback yet\n assign stall_wb = en_wb_o & ~ready_wb_i;\n\n assign perf_dside_wait_o = instr_valid_i & ~instr_kill &\n (outstanding_memory_access | stall_ld_hz);\n end else begin : gen_no_stall_mem\n\n assign multicycle_done = lsu_req_dec ? lsu_resp_valid_i : ex_valid_i;\n\n assign data_req_allowed = instr_first_cycle;\n\n // Without Writeback Stage always stall the first cycle of a load/store.\n // Then stall until it is complete\n assign stall_mem = instr_valid_i & (lsu_req_dec & (~lsu_resp_valid_i | instr_first_cycle));\n\n // No load hazards without Writeback Stage\n assign stall_ld_hz = 1'b0;\n\n // Without writeback stage any valid instruction that hasn't seen an error will execute\n assign instr_executing_spec = instr_valid_i & ~instr_fetch_err_i & controller_run;\n assign instr_executing = instr_executing_spec;\n\n `ASSERT(IbexStallIfValidInstrNotExecuting,\n instr_valid_i & ~instr_fetch_err_i & ~instr_executing & controller_run |-> stall_id)\n\n // No data forwarding without writeback stage so always take source register data direct from\n // register file\n assign rf_rdata_a_fwd = rf_rdata_a_i;\n assign rf_rdata_b_fwd = rf_rdata_b_i;\n\n assign rf_rd_a_wb_match_o = 1'b0;\n assign rf_rd_b_wb_match_o = 1'b0;\n\n // Unused Writeback stage only IO & wiring\n // Assign inputs and internal wiring to unused signals to satisfy lint checks\n // Tie-off outputs to constant values\n logic unused_data_req_done_ex;\n logic [4:0] unused_rf_waddr_wb;\n logic unused_rf_write_wb;\n logic unused_outstanding_load_wb;\n logic unused_outstanding_store_wb;\n logic unused_wb_exception;\n logic [31:0] unused_rf_wdata_fwd_wb;\n logic unused_id_exception;\n\n assign unused_data_req_done_ex = lsu_req_done_i;\n assign unused_rf_waddr_wb = rf_waddr_wb_i;\n assign unused_rf_write_wb = rf_write_wb_i;\n assign unused_outstanding_load_wb = outstanding_load_wb_i;\n assign unused_outstanding_store_wb = outstanding_store_wb_i;\n assign unused_wb_exception = wb_exception;\n assign unused_rf_wdata_fwd_wb = rf_wdata_fwd_wb_i;\n assign unused_id_exception = id_exception;\n\n assign instr_type_wb_o = WB_INSTR_OTHER;\n assign stall_wb = 1'b0;\n\n assign perf_dside_wait_o = instr_executing & lsu_req_dec & ~lsu_resp_valid_i;\n\n assign instr_id_done_o = instr_done;\n end\n\n // Signal which instructions to count as retired in minstret, all traps along with ebrk and\n // ecall instructions are not counted.\n assign instr_perf_count_id_o = ~ebrk_insn & ~ecall_insn_dec & ~illegal_insn_dec &\n ~illegal_csr_insn_i & ~instr_fetch_err_i;\n\n // An instruction is ready to move to the writeback stage (or retire if there is no writeback\n // stage)\n assign en_wb_o = instr_done;\n\n assign perf_mul_wait_o = stall_multdiv & mult_en_dec;\n assign perf_div_wait_o = stall_multdiv & div_en_dec;\n\n //////////\n // FCOV //\n //////////\n\n `DV_FCOV_SIGNAL_GEN_IF(logic, rf_rd_wb_hz,\n (gen_stall_mem.rf_rd_a_hz | gen_stall_mem.rf_rd_b_hz) & instr_valid_i, WritebackStage)\n `DV_FCOV_SIGNAL(logic, branch_taken,\n instr_executing & (id_fsm_q == FIRST_CYCLE) & branch_decision_i)\n `DV_FCOV_SIGNAL(logic, branch_not_taken,\n instr_executing & (id_fsm_q == FIRST_CYCLE) & ~branch_decision_i)\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT_KNOWN_IF(IbexAluOpMuxSelKnown, alu_op_a_mux_sel, instr_valid_i)\n `ASSERT(IbexAluAOpMuxSelValid, instr_valid_i |-> alu_op_a_mux_sel inside {\n OP_A_REG_A,\n OP_A_FWD,\n OP_A_CURRPC,\n OP_A_IMM})\n `ASSERT_KNOWN_IF(IbexBTAluAOpMuxSelKnown, bt_a_mux_sel, instr_valid_i)\n `ASSERT(IbexBTAluAOpMuxSelValid, instr_valid_i |-> bt_a_mux_sel inside {\n OP_A_REG_A,\n OP_A_CURRPC})\n `ASSERT_KNOWN_IF(IbexBTAluBOpMuxSelKnown, bt_b_mux_sel, instr_valid_i)\n `ASSERT(IbexBTAluBOpMuxSelValid, instr_valid_i |-> bt_b_mux_sel inside {\n IMM_B_I,\n IMM_B_B,\n IMM_B_J,\n IMM_B_INCR_PC})\n `ASSERT(IbexRegfileWdataSelValid, instr_valid_i |-> rf_wdata_sel inside {\n RF_WD_EX,\n RF_WD_CSR})\n `ASSERT_KNOWN(IbexWbStateKnown, id_fsm_q)\n\n // Branch decision must be valid when jumping.\n `ASSERT_KNOWN_IF(IbexBranchDecisionValid, branch_decision_i,\n instr_valid_i && !(illegal_csr_insn_i || instr_fetch_err_i))\n\n // Instruction delivered to ID stage can not contain X.\n `ASSERT_KNOWN_IF(IbexIdInstrKnown, instr_rdata_i,\n instr_valid_i && !(illegal_c_insn_i || instr_fetch_err_i))\n\n // Instruction delivered to ID stage can not contain X.\n `ASSERT_KNOWN_IF(IbexIdInstrALUKnown, instr_rdata_alu_i,\n instr_valid_i && !(illegal_c_insn_i || instr_fetch_err_i))\n\n // Multicycle enable signals must be unique.\n `ASSERT(IbexMulticycleEnableUnique,\n $onehot0({lsu_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", "selected_doc_paths": ["doc/03_reference/instruction_decode_execute.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/register_file.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1554, "lang": "sv", "rtl_files": ["examples/fpga/artya7/rtl/top_artya7.sv"], "spec": "# Design Specification: `top_artya7` – Ibex Core FPGA Top-Level for Arty A7\n\n## 1. Introduction\n\nThe `top_artya7` module provides a minimal, self-contained FPGA implementation of the lowRISC Ibex 32‑bit RISC‑V processor targeted at the Digilent Arty A7 development board. It integrates the Ibex core, a dual‑port synchronous SRAM for instruction and data storage, a clock generator for the Xilinx 7‑series FPGA, and a simple LED interface for user feedback.\n\nThis design is intended as a starting point for evaluation, experimentation, and education. It does not include peripheral buses, external memory controllers, or complex interrupt handling; the core runs code solely from the internal SRAM.\n\n## 2. Block Diagram Overview\n\n```\nExternal Clock ──► Clock Generator ──► System Clock\nExternal Reset ──► Generator ──► System Reset\n\nIbex Core (ibex_top) <──> Dual‑Port SRAM (ram_2p)\n │ (Instruction + Data)\n │\n └── Data write detection ──► LED output (4 bits)\n```\n\n- The core’s instruction fetch and data load/store interfaces both connect to a single shared dual‑port SRAM.\n- The system clock and reset are derived from the board’s 100 MHz oscillator and the reset push‑button.\n- Four LEDs on the Arty A7 board are updated whenever the core writes to the data memory; the lower 4 bits of the most‑significant byte of the written word are reflected on the LEDs.\n\n## 3. Functional Description\n\n### 3.1 Core and Memory\n\n- The module instantiates a single Ibex core with the register file implementation set to `RegFileFPGA` (optimised for FPGA fabrics).\n- The core executes code starting at address `0x0000_0000` plus the standard reset vector offset (`0x80`).\n- The core’s instruction and data requests are both directed to a single dual‑port synchronous SRAM. The SRAM is word‑addressed (32‑bit) and has a depth equal to `MEM_SIZE / 4` words.\n- The two ports operate independently:\n - Port A is used for data accesses (reads and writes).\n - Port B is used for instruction fetches (read‑only).\n- Each request is accepted in the same cycle it is issued (grant is tied to request). The SRAM provides a valid response one clock cycle after the request is granted, with no wait states (zero‑cycle grant, one‑cycle read latency).\n\n### 3.2 Clock and Reset\n\n- An external single‑ended clock (typically 100 MHz from the on‑board oscillator) is used as the reference.\n- An external active‑low reset signal (typically from the reset button) is used.\n- The internal clock generator (a Xilinx 7‑series MMCM/PLL) produces the system clock (`clk_sys`) and a synchronised, de‑glitched active‑low system reset (`rst_sys_n`).\n- The system reset is asserted asynchronously and de‑asserted synchronously relative to the system clock.\n\n### 3.3 LED Output\n\n- Four board‑level LEDs are driven directly by a 4‑bit register.\n- This register is updated on every data memory write that is granted (i.e., every write transaction that completes).\n- For each write, the new LED value is the lower four bits of the most‑significant byte of the data being written (`data_wdata[31:28]`). The update is byte‑enable‑masked: only if the corresponding byte enable (the most‑significant byte enable, i.e., `data_be[3]`) is asserted will the LEDs be updated.\n- The LED register is cleared (all LEDs off) upon system reset.\n\n### 3.4 Interrupts, Debug, and Other Features\n\n- All interrupt inputs (`irq_software`, `irq_timer`, `irq_external`, `irq_fast`, `irq_nm`) are tied to `0`. The core does not respond to interrupts in this configuration.\n- The debug request input (`debug_req_i`) is de‑asserted.\n- The core’s `fetch_enable_i` is permanently asserted (`1`). The CPU begins fetching immediately after reset.\n- Parameters related to physical memory protection, performance counters, bit‑manipulation, caches, and security are left at their default values (typically disabled or minimal).\n- The two debug‑halt and debug‑exception addresses are set to `0x0000_0000`; debug mode is not used.\n- The core’s `crash_dump_o`, `alert_minor_o`, `alert_major_internal_o`, `alert_major_bus_o`, and `core_sleep_o` outputs are not connected externally.\n\n## 4. Parameters and Configuration\n\nThe module supports the following compile‑time parameters:\n\n| Parameter | Type | Default / Range | Description |\n|----------------------|------------|--------------------------|--------------------------------------------------------------------|\n| `FPGAPowerAnalysis` | integer | 0 | When set to `1`, the SRAM size is increased to 256 kiB (for power‑analysis builds). Otherwise, 64 kiB is used. |\n| `MEM_SIZE` | integer | 64 × 1024 or 256 × 1024 | Total SRAM capacity in bytes. Computed from `FPGAPowerAnalysis`. |\n| `MEM_START` | 32‑bit | `32'h0000_0000` | Base address of the SRAM in the core’s address map. |\n| `MEM_MASK` | 32‑bit | `MEM_SIZE - 1` | Address mask for the SRAM (used for address decoding, but not exposed outside). |\n| `SRAMInitFile` | string | `\"\"` | Path to a file used to pre‑initialize the SRAM contents at synthesis time. A non‑empty path instructs the SRAM to load initial content from the given hex file. |\n\n**Note:** For the Arty A7‑35 board (with 35 k logic cells), a 256 kiB SRAM does not fit. The default 64 kiB must be used unless a larger FPGA (Arty A7‑100) is targeted.\n\n## 5. I/O Interfaces\n\nAll top‑level ports are described below.\n\n| Port | Width | Direction | Description |\n|--------------------|-------|-----------|---------------------------------------------------------------------------------------------------------------------------------------------|\n| `IO_CLK` | 1 | Input | External clock source (typically 100 MHz single‑ended). Must be a free‑running clock. |\n| `IO_RST_N` | 1 | Input | External reset, active‑low, asynchronous. A low level forces the system into reset state. |\n| `LED` | 4 | Output | Four board LEDs. Driven by the LED register described in Section 3.3. All LEDs are off after reset. `LED[0]` corresponds to the least significant bit. |\n\n## 6. Operational Behavior\n\n### 6.1 Startup Sequence\n\n1. After power‑up and release of the external reset, the clock generator starts and produces a stable system clock and de‑asserts the internal reset synchronously.\n2. The core begins fetching instructions from the SRAM at address `0x80` (offset from `boot_addr_i` which is `0x0000_0000`).\n3. If an initialisation file is provided (`SRAMInitFile != \"\"`), the SRAM is pre‑loaded with that content during synthesis. Otherwise, the SRAM content is undefined (typically all zeros).\n\n### 6.2 Instruction and Data Memory Access\n\n- The core issues instruction fetches via the instruction‑side interface. Each request is immediately granted, and the SRAM returns valid data one clock later.\n- Data reads and writes follow the same single‑cycle latency protocol: request is granted in the same cycle, response is valid one cycle later.\n- The SRAM does not support write‑masks on port B (instructions); that port is always read‑only.\n- The address space is flat: both instruction and data accesses target the same SRAM starting at `MEM_START`. Any access outside the SRAM range (addresses >= `MEM_START + MEM_SIZE`) produces an undefined result (the top‑level decoding is not implemented; only the SRAM is present).\n\n### 6.3 LED Update Behavior\n\n- The LED register is updated only on successful data writes (when `data_req` is asserted and `data_we` is high and the write is granted).\n- The update is **byte‑enable‑gated**: the LEDs change only if the byte enable for the most‑significant byte (`data_be[3]`) is asserted.\n- The new LED value is taken from the four most significant bits of the write data (`data_wdata[31:28]`).\n- No other writes (e.g., instruction fetches) affect the LEDs.\n- The LED register is cleared on system reset; it is not affected by external events other than writes.\n\n### 6.4 Reset\n\n- An active‑low level on `IO_RST_N` resets the entire system: the clock generator’s internal reset logic, the core, the SRAM (content becomes undefined), and the LED register.\n- After reset, the core restarts execution from the reset vector.\n\n### 6.5 Unused Capabilities\n\n- Interrupts are permanently disabled. The core will never take an interrupt trap.\n- Debug mode is not accessible.\n- The core does not signal any alerts or crash dumps externally.\n\n## 7. Constraints and Limitations\n\n- The design expects a single external clock with a frequency suitable for the Arty A7 board (typically 100 MHz). The internal clock generator multiplies/divides as needed to produce the system clock (the exact frequency is derived from the Xilinx MMCM configuration; the core can run up to the device’s timing limits).\n- The SRAM size is fixed at synthesis time. The `FPGAPowerAnalysis` parameter selects between 64 kiB and 256 kiB; the latter exceeds the resources of the Arty A7‑35.\n- No external memory or peripheral I/O is provided. All code and data must fit within the SRAM.\n- The SRAM initialisation file must be a hex file compatible with the `$readmemh`‑style format used by the `ram_2p` instantiation (little‑endian 32‑bit words, one per line, address incrementing from zero).\n- The LED output is updated only on the rising edge of the system clock when a write occurs. No filtering or debouncing is applied.\n\n---\n\n*This specification describes the required external behavior of the `top_artya7` module. It does not prescribe a particular internal implementation, only the functional contracts visible at its ports and through its parameters.*", "commit_id": "e6eb4fb11d8e1626e01ca76052352696f476586e", "timestamp": "2022-03-15T15:37:03+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "2f1e188346decdef988ee7cfafc7d44e8d256e7c", "pr_title": "Fix port list in top_artya7 example", "pr_body": "The \"alert_major\" port was split into \"internal\" and \"bus\" parts back\r\nin commit 9943f9a. Update the example to match.\r\n\r\nFixes #1553.", "issue_title": "alert_major_o output port must be removed from ibex_top.sv module in top_artya7.sv ", "issue_body": "\r\n\r\n## Observed Behavior\r\n\r\n\r\n## Expected Behavior\r\n\r\n\r\n## Steps to reproduce the issue\r\n\r\n\r\n## My Environment\r\n\r\n\r\n\r\n**EDA tool and version:**\r\n\r\n\r\n**Operating system:**\r\n\r\n\r\n**Version of the Ibex source code:**\r\n\r\nalert_major_o output port of ibex_top.sv module has to be removed as Vivado throws error when synthesizing top_artya7.sv module. This port is not defined in ibex_top.sv module used in FPGA example", "commit_message": "Fix port list in top_artya7 example\n\nThe \"alert_major\" port was split into \"internal\" and \"bus\" parts back\nin commit 9943f9a. Update the example to match.", "fix_patch": "diff --git a/examples/fpga/artya7/rtl/top_artya7.sv b/examples/fpga/artya7/rtl/top_artya7.sv\nindex b15ee978d3..d6000a2067 100644\n--- a/examples/fpga/artya7/rtl/top_artya7.sv\n+++ b/examples/fpga/artya7/rtl/top_artya7.sv\n@@ -82,7 +82,8 @@ module top_artya7 (\n \n .fetch_enable_i ('b1),\n .alert_minor_o (),\n- .alert_major_o (),\n+ .alert_major_internal_o(),\n+ .alert_major_bus_o (),\n .core_sleep_o ()\n );\n \n", "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 top_artya7 (\n input IO_CLK,\n input IO_RST_N,\n output [3:0] LED\n);\n\n parameter int FPGAPowerAnalysis = 0;\n // Choose 64kb memory for normal builds and 256kb for FPGAPowerAnalysis builds. The latter will\n // not fit in the Arty A7-35 Board FPGA.\n parameter int MEM_SIZE = FPGAPowerAnalysis == 0 ? 64 * 1024 : 256 * 1024;\n parameter logic [31:0] MEM_START = 32'h00000000;\n parameter logic [31:0] MEM_MASK = MEM_SIZE-1;\n parameter SRAMInitFile = \"\";\n\n logic clk_sys, rst_sys_n;\n\n // Instruction connection to SRAM\n logic instr_req;\n logic instr_gnt;\n logic instr_rvalid;\n logic [31:0] instr_addr;\n logic [31:0] instr_rdata;\n\n // Data connection to SRAM\n logic data_req;\n logic data_gnt;\n logic data_rvalid;\n logic data_we;\n logic [3:0] data_be;\n logic [31:0] data_addr;\n logic [31:0] data_wdata;\n logic [31:0] data_rdata;\n\n ibex_top #(\n .RegFile(ibex_pkg::RegFileFPGA),\n .DmHaltAddr(32'h00000000),\n .DmExceptionAddr(32'h00000000)\n ) u_top (\n .clk_i (clk_sys),\n .rst_ni (rst_sys_n),\n\n .test_en_i ('b0),\n .scan_rst_ni (1'b1),\n .ram_cfg_i ('b0),\n\n .hart_id_i (32'b0),\n // First instruction executed is at 0x0 + 0x80\n .boot_addr_i (32'h00000000),\n\n .instr_req_o (instr_req),\n .instr_gnt_i (instr_gnt),\n .instr_rvalid_i (instr_rvalid),\n .instr_addr_o (instr_addr),\n .instr_rdata_i (instr_rdata),\n .instr_rdata_intg_i ('0),\n .instr_err_i ('b0),\n\n .data_req_o (data_req),\n .data_gnt_i (data_gnt),\n .data_rvalid_i (data_rvalid),\n .data_we_o (data_we),\n .data_be_o (data_be),\n .data_addr_o (data_addr),\n .data_wdata_o (data_wdata),\n .data_wdata_intg_o (),\n .data_rdata_i (data_rdata),\n .data_rdata_intg_i ('0),\n .data_err_i ('b0),\n\n .irq_software_i (1'b0),\n .irq_timer_i (1'b0),\n .irq_external_i (1'b0),\n .irq_fast_i (15'b0),\n .irq_nm_i (1'b0),\n\n .debug_req_i ('b0),\n .crash_dump_o (),\n\n .fetch_enable_i ('b1),\n .alert_minor_o (),\n .alert_major_internal_o(),\n .alert_major_bus_o (),\n .core_sleep_o ()\n );\n\n // SRAM block for instruction and data storage\n ram_2p #(\n .Depth(MEM_SIZE / 4),\n .MemInitFile(SRAMInitFile)\n ) u_ram (\n .clk_i (clk_sys),\n .rst_ni(rst_sys_n),\n\n .a_req_i (data_req),\n .a_we_i (data_we),\n .a_be_i (data_be),\n .a_addr_i (data_addr),\n .a_wdata_i (data_wdata),\n .a_rvalid_o(data_rvalid),\n .a_rdata_o (data_rdata),\n\n .b_req_i (instr_req),\n .b_we_i (1'b0),\n .b_be_i (4'b0),\n .b_addr_i (instr_addr),\n .b_wdata_i (32'b0),\n .b_rvalid_o(instr_rvalid),\n .b_rdata_o (instr_rdata)\n );\n\n assign instr_gnt = instr_req;\n assign data_gnt = data_req;\n\n // Connect the LED output to the lower four bits of the most significant\n // byte\n logic [3:0] leds;\n always_ff @(posedge clk_sys or negedge rst_sys_n) begin\n if (!rst_sys_n) begin\n leds <= 4'b0;\n end else begin\n if (data_req && data_we) begin\n for (int i = 0; i < 4; i = i + 1) begin\n if (data_be[i] == 1'b1) begin\n leds <= data_wdata[i*8 +: 4];\n end\n end\n end\n end\n end\n assign LED = leds;\n\n // Clock and reset\n clkgen_xil7series\n clkgen(\n .IO_CLK,\n .IO_RST_N,\n .clk_sys,\n .rst_sys_n\n );\n\nendmodule\n", "selected_doc_paths": ["doc/02_user/examples.rst", "doc/02_user/integration.rst", "doc/03_reference/load_store_unit.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1547, "lang": "sv", "rtl_files": ["rtl/ibex_if_stage.sv"], "spec": "# Instruction Fetch Stage (IF) Specification\n\n## Overview\n\nThe Instruction Fetch (IF) stage is responsible for supplying the Instruction Decode and Execute (ID/EX) stage with one instruction per cycle, together with its program counter (PC) and associated status signals. It manages the flow of instructions from the instruction memory or instruction cache, handles PC selection for branches, jumps, exceptions, and interrupts, and optionally expands compressed (16‑bit) instructions into their 32‑bit equivalents. The IF stage also supports static branch prediction and dummy instruction insertion for security or testing purposes.\n\n## Functional Requirements\n\n### Program Counter (PC) Management\n\nThe IF stage must maintain the current PC for each instruction being fetched. On every cycle where a new instruction is accepted by the ID stage, the PC must be updated to the next sequential address (PC + 2 for a compressed instruction, PC + 4 for an uncompressed instruction). The PC must be aligned to a halfword boundary (bit 0 always zero). The IF stage shall support the following PC sources, selected by an external control signal:\n\n- **Boot address** – used after reset or on the first instruction fetch. The boot address is provided by an external input, with the least significant byte forced to `0x80`.\n- **Jump/branch target** – supplied by the execution stage for unconditional jumps or taken branches.\n- **Exception / interrupt handler address** – computed from the `mtvec` CSR and optionally the interrupt ID. For non‑vectored exceptions the address equals `mtvec` with the lower 8 bits set to zero; for vectored interrupts it is `mtvec` plus four times the interrupt ID. Debug halt and debug exception addresses are fixed parameters.\n- **Exception return (`mret`)** – the address from the `mepc` CSR.\n- **Debug return (`dret`)** – the address from the `depc` CSR.\n- **Branch predictor (optional)** – when static branch prediction is enabled and no other PC change is requested, the predictor may supply a new PC.\n\nThe IF stage must accept a PC change request (e.g., a branch, jump, or exception) with zero latency: the new PC shall be used for the next instruction fetch in the same cycle the request is asserted.\n\n### Instruction Fetch and Buffering\n\nThe IF stage must fetch instructions from the instruction memory (or instruction cache) using a request/grant protocol. It shall maintain a prefetch buffer (or an instruction cache when configured) to decouple the fetch rate from the execution rate and to reduce timing closure issues. The buffer must be able to hold several instructions and must be flushed on every PC change that is not a sequential increment (i.e., on any branch, jump, exception, or return).\n\nAfter reset, the IF stage shall start fetching from the reset boot address as soon as the core requests instructions.\n\n### Instruction Decoding and Decompression\n\nAll fetched instructions must be passed through a compressed decoder. The decoder determines whether the fetched instruction is a 16‑bit compressed instruction or a 32‑bit uncompressed instruction. Compressed instructions must be expanded to their 32‑bit equivalent before being passed to the ID stage. The expanded instruction, along with a flag indicating whether it was originally compressed, and the original lower 16 bits of the instruction (for use in the `mtval` CSR), must be forwarded to the ID stage. The decoder also generates an illegal compressed instruction flag when the fetched halfword does not correspond to any valid compressed instruction; this signal must be forwarded to the ID stage.\n\n### Instruction Valid and Pipeline Handshake\n\nThe IF stage communicates with the ID stage using a ready/valid handshake. An instruction is considered valid when the ID stage is ready to accept it and no exception or PC change intervenes. The IF stage must ensure that:\n\n- A valid instruction and its associated PC are presented to the ID stage only when the ID stage is ready.\n- The valid signal remains asserted until the ID stage acknowledges acceptance or until the instruction is explicitly cleared (e.g., due to an exception or a new PC set).\n- A new instruction is presented on the same cycle that the ID stage accepts the previous instruction, if the fetch buffer has one available.\n- The IF stage must stall when the ID stage is not ready, preserving the current instruction until it is accepted.\n\n### Error Handling\n\nThe IF stage must detect and report two kinds of instruction fetch errors:\n\n- **Bus error** – asserted by the memory system when an instruction fetch encounters a bus fault.\n- **PMU (Physical Memory Protection) error** – asserted externally when a fetch violates a PMP rule.\n\nThese errors must be combined and forwarded to the ID stage as an instruction fetch error signal. For unaligned uncompressed instructions (those whose PC bit 2 is set), the IF stage must also indicate whether the error applies to the second word of the instruction. The error plus-2 signal must only be active when an error is reported for an uncompressed instruction, and must be cleared by the next instruction.\n\nWhen an error occurs, the instruction data is undefined and must not be used by the ID stage. The valid flag to the ID stage must still be asserted so that the error is recognized; the ID stage will then trigger the appropriate exception.\n\n### Branch Prediction (Optional)\n\nWhen configured with a static branch predictor, the IF stage shall:\n\n- Predict that branches with a negative offset are taken and branches with a positive offset are not taken.\n- On a predicted taken branch, immediately redirect the PC to the predicted target address, without waiting for the ID stage to resolve the branch.\n- Introduce a skid buffer to hold the predicted branch instruction until the ID stage is ready to accept it, preventing a combinational path from the memory grant signal back to the fetch request.\n- Inform the ID stage whether the current instruction was predicted taken, so that the ID stage can later signal a misprediction.\n\nIf the ID stage detects a mispredicted branch (the branch was predicted taken but the condition is not met), it must assert a mispredict signal. The IF stage shall then:\n\n- Flush any instructions fetched after the mispredicted branch.\n- Present the instruction at the not‑taken fallthrough address (the sequential PC following the branch) as soon as possible.\n\nThe branch predictor must not predict on instructions that have a bus error.\n\n### Dummy Instruction Insertion (Optional)\n\nWhen dummy instruction insertion is enabled, the IF stage may replace a fetched real instruction with a pseudo‑random dummy instruction. The dummy instruction is generated by a dedicated sub‑module and is controlled by an enable and mask input. The insertion frequency and seed can be configured via external signals.\n\n- When a dummy instruction is inserted, the original compressed/illegal/error flags must be overridden: the dummy shall be considered uncompressed, legal, and non‑erroneous.\n- The IF stage must stall itself for one cycle when inserting a dummy instruction, so that the dummy executes between whatever is in the ID stage and the next instruction from the prefetch buffer.\n- A separate flag must be asserted to the ID stage to indicate that the instruction is a dummy.\n\n### Security Feature: PC Increment Check (Optional)\n\nIf enabled, the IF stage must verify that the PC of each sequentially fetched instruction is exactly 2 or 4 bytes greater than the PC of the previous instruction (depending on whether that previous instruction was compressed). This check must be performed only after the first instruction has been accepted by the ID stage and must be disabled after any PC change (branch, jump, exception, debug, or dummy insertion). A mismatch shall assert a security alert output. The check must be hardened against synthesis optimisations that could remove the comparison logic.\n\n### Reset Behavior\n\nOn asynchronous reset:\n\n- The IF stage must clear all internal state, including the PC (to an undefined value), the instruction valid flag, the branch predictor state, and any pending error flags.\n- The very first instruction fetch after reset must use the boot address provided to the module.\n- No instructions shall be presented to the ID stage until the core requests instruction fetching.\n\n### Miscellaneous\n\n- The IF stage must provide a busy output that is asserted whenever the fetch buffer or instruction cache is actively fetching data. This signal can be used to gate the clock.\n- The IF stage shall initialise `mtvec` by asserting a one‑cycle pulse when the PC is set to the boot address.\n- All control inputs (such as PC select and exception cause) must be stable and valid when used. The module may assume they are valid.\n\n---\n\n*This specification describes the expected behavior of the instruction fetch stage. It does not prescribe any particular implementation, register names, or internal signals.*", "commit_id": "bdf2f2b44076c8e9a00fa6dcbee0a409026e5c3a", "timestamp": "2022-03-03T13:48:10+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "c15f3b88883781808eaa96bda205a9bdaff5eb98", "pr_title": "[icache] Define some fake DPI functions to simplify linking", "pr_body": "This is triggered by the fact that if the `ICache` parameter is false\r\nthen we don't instantiate the `ibex_icache` module. For verilator\r\nsimulations, the module is then discarded entirely, which means that\r\nits two DPI functions are not defined. That's unfortunate because\r\nwe're also compiling the code in `scrambled_ecc32_mem_area.cc`, which\r\nexpects the functions to be defined.\r\n\r\nThe obvious solution (don't include `scrambled_ecc32_mem_area.cc` if you\r\ndon't have an icache) isn't easy to do, because FuseSoc doesn't\r\ncurrently allow us to use parameters to configure its dependency\r\ntree (see [fusesoc issue 438](https://github.com/olofk/fusesoc/issues/438) for a discussion).\r\n\r\nThe super-clever solution that I came up with before(!) was to declare\r\nthese symbols as weak in the C++ code. That way, we can do a runtime\r\ncheck to make sure that no-one is silly enough to call them without an\r\nicache, but everything will still build properly either way.\r\n\r\nUnfortunately, that doesn't work well with xcelium simulations.\r\nXcelium turns out to compile all the C++ code into one .so library and\r\ngenerate functions for exported DPI functions in another. These two\r\nsolibs then get loaded at runtime with `dlopen()`. But this doesn't work\r\nwith weak symbols: in fact, it seems you end up with the C++ version\r\nevery time. Boo!\r\n\r\nSo let's be stupider about it and define (bogus) versions of the DPI\r\nfunctions in this case. Fortunately, both of them are designed to\r\nreturn zero on failure so we can just return zero and needn't worry\r\ntoo much.\r\n\r\nThe idea is that when this lands, we can revert the [OpenTitan change](https://github.com/lowRISC/opentitan/pull/9304)\r\nthat switched the C++ code to using weak symbols and Xcelium\r\nsimulations will start working.", "issue_title": "Modify/Extend Simple System to be a more generic base ", "issue_body": "This PR https://github.com/lowRISC/ibex/pull/311 introduces Simple System. It allows you to build programs and easily run them on a basic Ibex system.\r\n\r\nIt shares many commonalities with the riscv-compliance system and the FPGA example. It should be possible to refactor these things so they are all working off the same base.\r\n\r\nIn addition it would be useful to add debugging support into Simple System to demonstrate how to setup a working debug environment. Though this may draw us away from it being a simple system so perhaps it would be a new example derived from Simple System.", "commit_message": "[icache] Define some fake DPI functions to simplify linking\n\nThis is triggered by the fact that if the ICache parameter is false\nthen we don't instantiate the ibex_icache module. For verilator\nsimulations, the module is then discarded entirely, which means that\nits two DPI functions are not defined. That's unfortunate because\nwe're also compiling the code in scrambled_ecc32_mem_area.cc, which\nexpects the functions to be defined.\n\nThe obvious solution (don't include scrambled_ecc32_mem_area.cc if you\ndon't have an icache) isn't easy to do, because FuseSoc doesn't\ncurrently allow us to use parameters to configure its dependency\ntree (see fusesoc issue 438 for a discussion).\n\nThe super-clever solution that I came up with before(!) was to declare\nthese symbols as weak in the C++ code. That way, we can do a runtime\ncheck to make sure that no-one is silly enough to call them without an\nicache, but everything will still build properly either way.\n\nUnfortunately, that doesn't work well with xcelium simulations.\nXcelium turns out to compile all the C++ code into one .so library and\ngenerate functions for exported DPI functions in another. These two\nsolibs then get loaded at runtime with dlopen(). But this doesn't work\nwith weak symbols: in fact, it seems you end up with the C++ version\nevery time. Boo!\n\nSo let's be stupider about it and define (bogus) versions of the DPI\nfunctions in this case. Fortunately, both of them are designed to\nreturn zero on failure so we can just return zero and needn't worry\ntoo much.\n\nThe idea is that when this lands, we can revert the OpenTitan change\nthat switched the C++ code to using weak symbols and Xcelium\nsimulations will start working.", "fix_patch": "diff --git a/rtl/ibex_if_stage.sv b/rtl/ibex_if_stage.sv\nindex aa63257872..2697833e41 100644\n--- a/rtl/ibex_if_stage.sv\n+++ b/rtl/ibex_if_stage.sv\n@@ -301,6 +301,23 @@ module ibex_if_stage import ibex_pkg::*; #(\n assign ic_data_write_o = 'b0;\n assign ic_data_addr_o = 'b0;\n assign ic_data_wdata_o = 'b0;\n+\n+`ifndef SYNTHESIS\n+ // If we don't instantiate an icache and this is a simulation then we have a problem because the\n+ // simulator might discard the icache module entirely, including some DPI exports that it\n+ // implies. This then causes problems for linking against C++ testbench code that expected them.\n+ // As a slightly ugly hack, let's define the DPI functions here (the real versions are defined\n+ // in prim_util_get_scramble_params.svh)\n+ export \"DPI-C\" function simutil_get_scramble_key;\n+ export \"DPI-C\" function simutil_get_scramble_nonce;\n+ function automatic int simutil_get_scramble_key(output bit [127:0] val);\n+ return 0;\n+ endfunction\n+ function automatic int simutil_get_scramble_nonce(output bit [319:0] nonce);\n+ return 0;\n+ endfunction\n+`endif\n+\n end\n \n assign unused_fetch_addr_n0 = fetch_addr_n[0];\n", "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 * Instruction Fetch Stage\n *\n * Instruction fetch unit: Selection of the next PC, and buffering (sampling) of\n * the read instruction.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_if_stage import ibex_pkg::*; #(\n parameter int unsigned DmHaltAddr = 32'h1A110800,\n parameter int unsigned DmExceptionAddr = 32'h1A110808,\n parameter bit DummyInstructions = 1'b0,\n parameter bit ICache = 1'b0,\n parameter bit ICacheECC = 1'b0,\n parameter int unsigned BusSizeECC = BUS_SIZE,\n parameter int unsigned TagSizeECC = IC_TAG_SIZE,\n parameter int unsigned LineSizeECC = IC_LINE_SIZE,\n parameter bit PCIncrCheck = 1'b0,\n parameter bit ResetAll = 1'b0,\n parameter lfsr_seed_t RndCnstLfsrSeed = RndCnstLfsrSeedDefault,\n parameter lfsr_perm_t RndCnstLfsrPerm = RndCnstLfsrPermDefault,\n parameter bit BranchPredictor = 1'b0\n) (\n input logic clk_i,\n input logic rst_ni,\n\n input logic [31:0] boot_addr_i, // also used for mtvec\n input logic req_i, // instruction request control\n\n // instruction cache interface\n output logic instr_req_o,\n output logic [31:0] instr_addr_o,\n input logic instr_gnt_i,\n input logic instr_rvalid_i,\n input logic [31:0] instr_rdata_i,\n input logic instr_err_i,\n\n // ICache RAM IO\n output logic [IC_NUM_WAYS-1:0] ic_tag_req_o,\n output logic ic_tag_write_o,\n output logic [IC_INDEX_W-1:0] ic_tag_addr_o,\n output logic [TagSizeECC-1:0] ic_tag_wdata_o,\n input logic [TagSizeECC-1:0] ic_tag_rdata_i [IC_NUM_WAYS],\n output logic [IC_NUM_WAYS-1:0] ic_data_req_o,\n output logic ic_data_write_o,\n output logic [IC_INDEX_W-1:0] ic_data_addr_o,\n output logic [LineSizeECC-1:0] ic_data_wdata_o,\n input logic [LineSizeECC-1:0] ic_data_rdata_i [IC_NUM_WAYS],\n input logic ic_scr_key_valid_i,\n\n // output of ID stage\n output logic instr_valid_id_o, // instr in IF-ID is valid\n output logic instr_new_id_o, // instr in IF-ID is new\n output logic [31:0] instr_rdata_id_o, // instr for ID stage\n output logic [31:0] instr_rdata_alu_id_o, // replicated instr for ID stage\n // to reduce fan-out\n output logic [15:0] instr_rdata_c_id_o, // compressed instr for ID stage\n // (mtval), meaningful only if\n // instr_is_compressed_id_o = 1'b1\n output logic instr_is_compressed_id_o, // compressed decoder thinks this\n // is a compressed instr\n output logic instr_bp_taken_o, // instruction was predicted to be\n // a taken branch\n output logic instr_fetch_err_o, // bus error on fetch\n output logic instr_fetch_err_plus2_o, // bus error misaligned\n output logic illegal_c_insn_id_o, // compressed decoder thinks this\n // is an invalid instr\n output logic dummy_instr_id_o, // Instruction is a dummy\n output logic [31:0] pc_if_o,\n output logic [31:0] pc_id_o,\n input logic pmp_err_if_i,\n input logic pmp_err_if_plus2_i,\n\n // control signals\n input logic instr_valid_clear_i, // clear instr valid bit in IF-ID\n input logic pc_set_i, // set the PC to a new value\n input pc_sel_e pc_mux_i, // selector for PC multiplexer\n input logic nt_branch_mispredict_i, // Not-taken branch in ID/EX was\n // mispredicted (predicted taken)\n input logic [31:0] nt_branch_addr_i, // Not-taken branch address in ID/EX\n input exc_pc_sel_e exc_pc_mux_i, // selects ISR address\n input exc_cause_e exc_cause, // selects ISR address for\n // vectorized interrupt lines\n input logic dummy_instr_en_i,\n input logic [2:0] dummy_instr_mask_i,\n input logic dummy_instr_seed_en_i,\n input logic [31:0] dummy_instr_seed_i,\n input logic icache_enable_i,\n input logic icache_inval_i,\n\n // jump and branch target\n input logic [31:0] branch_target_ex_i, // branch/jump target address\n\n // CSRs\n input logic [31:0] csr_mepc_i, // PC to restore after handling\n // the interrupt/exception\n input logic [31:0] csr_depc_i, // PC to restore after handling\n // the debug request\n input logic [31:0] csr_mtvec_i, // base PC to jump to on exception\n output logic csr_mtvec_init_o, // tell CS regfile to init mtvec\n\n // pipeline stall\n input logic id_in_ready_i, // ID stage is ready for new instr\n\n // misc signals\n output logic pc_mismatch_alert_o,\n output logic if_busy_o // IF stage is busy fetching instr\n);\n\n logic instr_valid_id_d, instr_valid_id_q;\n logic instr_new_id_d, instr_new_id_q;\n\n // prefetch buffer related signals\n logic prefetch_busy;\n logic branch_req;\n logic [31:0] fetch_addr_n;\n logic unused_fetch_addr_n0;\n\n logic fetch_valid;\n logic fetch_ready;\n logic [31:0] fetch_rdata;\n logic [31:0] fetch_addr;\n logic fetch_err;\n logic fetch_err_plus2;\n\n logic [31:0] instr_decompressed;\n logic illegal_c_insn;\n logic instr_is_compressed;\n\n logic if_instr_valid;\n logic [31:0] if_instr_rdata;\n logic [31:0] if_instr_addr;\n logic if_instr_bus_err;\n logic if_instr_pmp_err;\n logic if_instr_err;\n logic if_instr_err_plus2;\n\n logic [31:0] exc_pc;\n\n logic [5:0] irq_id;\n logic unused_irq_bit;\n\n logic if_id_pipe_reg_we; // IF-ID pipeline reg write enable\n\n // Dummy instruction signals\n logic stall_dummy_instr;\n logic [31:0] instr_out;\n logic instr_is_compressed_out;\n logic illegal_c_instr_out;\n logic instr_err_out;\n\n logic predict_branch_taken;\n logic [31:0] predict_branch_pc;\n\n ibex_pkg::pc_sel_e pc_mux_internal;\n\n logic [7:0] unused_boot_addr;\n logic [7:0] unused_csr_mtvec;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n assign unused_csr_mtvec = csr_mtvec_i[7:0];\n\n // extract interrupt ID from exception cause\n assign irq_id = {exc_cause};\n assign unused_irq_bit = irq_id[5]; // MSB distinguishes interrupts from exceptions\n\n // exception PC selection mux\n always_comb begin : exc_pc_mux\n unique case (exc_pc_mux_i)\n EXC_PC_EXC: exc_pc = { csr_mtvec_i[31:8], 8'h00 };\n EXC_PC_IRQ: exc_pc = { csr_mtvec_i[31:8], 1'b0, irq_id[4:0], 2'b00 };\n EXC_PC_DBD: exc_pc = DmHaltAddr;\n EXC_PC_DBG_EXC: exc_pc = DmExceptionAddr;\n default: exc_pc = { csr_mtvec_i[31:8], 8'h00 };\n endcase\n end\n\n // The Branch predictor can provide a new PC which is internal to if_stage. Only override the mux\n // select to choose this if the core isn't already trying to set a PC.\n assign pc_mux_internal =\n (BranchPredictor && predict_branch_taken && !pc_set_i) ? PC_BP : pc_mux_i;\n\n // fetch address selection mux\n always_comb begin : fetch_addr_mux\n unique case (pc_mux_internal)\n PC_BOOT: fetch_addr_n = { boot_addr_i[31:8], 8'h80 };\n PC_JUMP: fetch_addr_n = branch_target_ex_i;\n PC_EXC: fetch_addr_n = exc_pc; // set PC to exception handler\n PC_ERET: fetch_addr_n = csr_mepc_i; // restore PC when returning from EXC\n PC_DRET: fetch_addr_n = csr_depc_i;\n // Without branch predictor will never get pc_mux_internal == PC_BP. We still handle no branch\n // predictor case here to ensure redundant mux logic isn't synthesised.\n PC_BP: fetch_addr_n = BranchPredictor ? predict_branch_pc : { boot_addr_i[31:8], 8'h80 };\n default: fetch_addr_n = { boot_addr_i[31:8], 8'h80 };\n endcase\n end\n\n // tell CS register file to initialize mtvec on boot\n assign csr_mtvec_init_o = (pc_mux_i == PC_BOOT) & pc_set_i;\n\n if (ICache) begin : gen_icache\n // Full I-Cache option\n ibex_icache #(\n .ICacheECC (ICacheECC),\n .ResetAll (ResetAll),\n .BusSizeECC (BusSizeECC),\n .TagSizeECC (TagSizeECC),\n .LineSizeECC (LineSizeECC)\n ) icache_i (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n .req_i ( req_i ),\n\n .branch_i ( branch_req ),\n .branch_mispredict_i ( nt_branch_mispredict_i ),\n .mispredict_addr_i ( nt_branch_addr_i ),\n .addr_i ( {fetch_addr_n[31:1], 1'b0} ),\n\n .ready_i ( fetch_ready ),\n .valid_o ( fetch_valid ),\n .rdata_o ( fetch_rdata ),\n .addr_o ( fetch_addr ),\n .err_o ( fetch_err ),\n .err_plus2_o ( fetch_err_plus2 ),\n\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 .instr_err_i ( instr_err_i ),\n\n .ic_tag_req_o ( ic_tag_req_o ),\n .ic_tag_write_o ( ic_tag_write_o ),\n .ic_tag_addr_o ( ic_tag_addr_o ),\n .ic_tag_wdata_o ( ic_tag_wdata_o ),\n .ic_tag_rdata_i ( ic_tag_rdata_i ),\n .ic_data_req_o ( ic_data_req_o ),\n .ic_data_write_o ( ic_data_write_o ),\n .ic_data_addr_o ( ic_data_addr_o ),\n .ic_data_wdata_o ( ic_data_wdata_o ),\n .ic_data_rdata_i ( ic_data_rdata_i ),\n .ic_scr_key_valid_i ( ic_scr_key_valid_i ),\n\n .icache_enable_i ( icache_enable_i ),\n .icache_inval_i ( icache_inval_i ),\n .busy_o ( prefetch_busy )\n );\n end else begin : gen_prefetch_buffer\n // prefetch buffer, caches a fixed number of instructions\n ibex_prefetch_buffer #(\n .ResetAll (ResetAll)\n ) prefetch_buffer_i (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n .req_i ( req_i ),\n\n .branch_i ( branch_req ),\n .branch_mispredict_i ( nt_branch_mispredict_i ),\n .mispredict_addr_i ( nt_branch_addr_i ),\n .addr_i ( {fetch_addr_n[31:1], 1'b0} ),\n\n .ready_i ( fetch_ready ),\n .valid_o ( fetch_valid ),\n .rdata_o ( fetch_rdata ),\n .addr_o ( fetch_addr ),\n .err_o ( fetch_err ),\n .err_plus2_o ( fetch_err_plus2 ),\n\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 .instr_err_i ( instr_err_i ),\n\n .busy_o ( prefetch_busy )\n );\n // ICache tieoffs\n logic unused_icen, unused_icinv, unused_scr_key_valid;\n logic [TagSizeECC-1:0] unused_tag_ram_input [IC_NUM_WAYS];\n logic [LineSizeECC-1:0] unused_data_ram_input [IC_NUM_WAYS];\n assign unused_icen = icache_enable_i;\n assign unused_icinv = icache_inval_i;\n assign unused_tag_ram_input = ic_tag_rdata_i;\n assign unused_data_ram_input = ic_data_rdata_i;\n assign unused_scr_key_valid = ic_scr_key_valid_i;\n assign ic_tag_req_o = 'b0;\n assign ic_tag_write_o = 'b0;\n assign ic_tag_addr_o = 'b0;\n assign ic_tag_wdata_o = 'b0;\n assign ic_data_req_o = 'b0;\n assign ic_data_write_o = 'b0;\n assign ic_data_addr_o = 'b0;\n assign ic_data_wdata_o = 'b0;\n\n`ifndef SYNTHESIS\n // If we don't instantiate an icache and this is a simulation then we have a problem because the\n // simulator might discard the icache module entirely, including some DPI exports that it\n // implies. This then causes problems for linking against C++ testbench code that expected them.\n // As a slightly ugly hack, let's define the DPI functions here (the real versions are defined\n // in prim_util_get_scramble_params.svh)\n export \"DPI-C\" function simutil_get_scramble_key;\n export \"DPI-C\" function simutil_get_scramble_nonce;\n function automatic int simutil_get_scramble_key(output bit [127:0] val);\n return 0;\n endfunction\n function automatic int simutil_get_scramble_nonce(output bit [319:0] nonce);\n return 0;\n endfunction\n`endif\n\n end\n\n assign unused_fetch_addr_n0 = fetch_addr_n[0];\n\n assign branch_req = pc_set_i | predict_branch_taken;\n\n assign pc_if_o = if_instr_addr;\n assign if_busy_o = prefetch_busy;\n\n // PMP errors\n // An error can come from the instruction address, or the next instruction address for unaligned,\n // uncompressed instructions.\n assign if_instr_pmp_err = pmp_err_if_i |\n (if_instr_addr[2] & ~instr_is_compressed & pmp_err_if_plus2_i);\n\n // Combine bus errors and pmp errors\n assign if_instr_err = if_instr_bus_err | if_instr_pmp_err;\n\n // Capture the second half of the address for errors on the second part of an instruction\n assign if_instr_err_plus2 = ((if_instr_addr[2] & ~instr_is_compressed & pmp_err_if_plus2_i) |\n fetch_err_plus2) & ~pmp_err_if_i;\n\n // compressed instruction decoding, or more precisely compressed instruction\n // expander\n //\n // since it does not matter where we decompress instructions, we do it here\n // to ease timing closure\n ibex_compressed_decoder compressed_decoder_i (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .valid_i (fetch_valid & ~fetch_err),\n .instr_i (if_instr_rdata),\n .instr_o (instr_decompressed),\n .is_compressed_o(instr_is_compressed),\n .illegal_instr_o(illegal_c_insn)\n );\n\n // Dummy instruction insertion\n if (DummyInstructions) begin : gen_dummy_instr\n logic insert_dummy_instr;\n logic [31:0] dummy_instr_data;\n\n ibex_dummy_instr #(\n .RndCnstLfsrSeed (RndCnstLfsrSeed),\n .RndCnstLfsrPerm (RndCnstLfsrPerm)\n ) dummy_instr_i (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .dummy_instr_en_i (dummy_instr_en_i),\n .dummy_instr_mask_i (dummy_instr_mask_i),\n .dummy_instr_seed_en_i(dummy_instr_seed_en_i),\n .dummy_instr_seed_i (dummy_instr_seed_i),\n .fetch_valid_i (fetch_valid),\n .id_in_ready_i (id_in_ready_i),\n .insert_dummy_instr_o (insert_dummy_instr),\n .dummy_instr_data_o (dummy_instr_data)\n );\n\n // Mux between actual instructions and dummy instructions\n assign instr_out = insert_dummy_instr ? dummy_instr_data : instr_decompressed;\n assign instr_is_compressed_out = insert_dummy_instr ? 1'b0 : instr_is_compressed;\n assign illegal_c_instr_out = insert_dummy_instr ? 1'b0 : illegal_c_insn;\n assign instr_err_out = insert_dummy_instr ? 1'b0 : if_instr_err;\n\n // Stall the IF stage if we insert a dummy instruction. The dummy will execute between whatever\n // is currently in the ID stage and whatever is valid from the prefetch buffer this cycle. The\n // PC of the dummy instruction will match whatever is next from the prefetch buffer.\n assign stall_dummy_instr = insert_dummy_instr;\n\n // Register the dummy instruction indication into the ID stage\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n dummy_instr_id_o <= 1'b0;\n end else if (if_id_pipe_reg_we) begin\n dummy_instr_id_o <= insert_dummy_instr;\n end\n end\n\n end else begin : gen_no_dummy_instr\n logic unused_dummy_en;\n logic [2:0] unused_dummy_mask;\n logic unused_dummy_seed_en;\n logic [31:0] unused_dummy_seed;\n\n assign unused_dummy_en = dummy_instr_en_i;\n assign unused_dummy_mask = dummy_instr_mask_i;\n assign unused_dummy_seed_en = dummy_instr_seed_en_i;\n assign unused_dummy_seed = dummy_instr_seed_i;\n assign instr_out = instr_decompressed;\n assign instr_is_compressed_out = instr_is_compressed;\n assign illegal_c_instr_out = illegal_c_insn;\n assign instr_err_out = if_instr_err;\n assign stall_dummy_instr = 1'b0;\n assign dummy_instr_id_o = 1'b0;\n end\n\n // The ID stage becomes valid as soon as any instruction is registered in the ID stage flops.\n // Note that the current instruction is squashed by the incoming pc_set_i signal.\n // Valid is held until it is explicitly cleared (due to an instruction completing or an exception)\n assign instr_valid_id_d = (if_instr_valid & id_in_ready_i & ~pc_set_i) |\n (instr_valid_id_q & ~instr_valid_clear_i);\n assign instr_new_id_d = if_instr_valid & id_in_ready_i;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_valid_id_q <= 1'b0;\n instr_new_id_q <= 1'b0;\n end else begin\n instr_valid_id_q <= instr_valid_id_d;\n instr_new_id_q <= instr_new_id_d;\n end\n end\n\n assign instr_valid_id_o = instr_valid_id_q;\n // Signal when a new instruction enters the ID stage (only used for RVFI signalling).\n assign instr_new_id_o = instr_new_id_q;\n\n // IF-ID pipeline registers, frozen when the ID stage is stalled\n assign if_id_pipe_reg_we = instr_new_id_d;\n\n if (ResetAll) begin : g_instr_rdata_ra\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_rdata_id_o <= '0;\n instr_rdata_alu_id_o <= '0;\n instr_fetch_err_o <= '0;\n instr_fetch_err_plus2_o <= '0;\n instr_rdata_c_id_o <= '0;\n instr_is_compressed_id_o <= '0;\n illegal_c_insn_id_o <= '0;\n pc_id_o <= '0;\n end else if (if_id_pipe_reg_we) begin\n instr_rdata_id_o <= instr_out;\n // To reduce fan-out and help timing from the instr_rdata_id flops they are replicated.\n instr_rdata_alu_id_o <= instr_out;\n instr_fetch_err_o <= instr_err_out;\n instr_fetch_err_plus2_o <= if_instr_err_plus2;\n instr_rdata_c_id_o <= if_instr_rdata[15:0];\n instr_is_compressed_id_o <= instr_is_compressed_out;\n illegal_c_insn_id_o <= illegal_c_instr_out;\n pc_id_o <= pc_if_o;\n end\n end\n end else begin : g_instr_rdata_nr\n always_ff @(posedge clk_i) begin\n if (if_id_pipe_reg_we) begin\n instr_rdata_id_o <= instr_out;\n // To reduce fan-out and help timing from the instr_rdata_id flops they are replicated.\n instr_rdata_alu_id_o <= instr_out;\n instr_fetch_err_o <= instr_err_out;\n instr_fetch_err_plus2_o <= if_instr_err_plus2;\n instr_rdata_c_id_o <= if_instr_rdata[15:0];\n instr_is_compressed_id_o <= instr_is_compressed_out;\n illegal_c_insn_id_o <= illegal_c_instr_out;\n pc_id_o <= pc_if_o;\n end\n end\n end\n\n // Check for expected increments of the PC when security hardening enabled\n if (PCIncrCheck) begin : g_secure_pc\n logic [31:0] prev_instr_addr_incr, prev_instr_addr_incr_buf;\n logic prev_instr_seq_q, prev_instr_seq_d;\n\n // Do not check for sequential increase after a branch, jump, exception, interrupt or debug\n // request, all of which will set branch_req. Also do not check after reset or for dummys.\n assign prev_instr_seq_d = (prev_instr_seq_q | instr_new_id_d) &\n ~branch_req & ~if_instr_err & ~stall_dummy_instr;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n prev_instr_seq_q <= 1'b0;\n end else begin\n prev_instr_seq_q <= prev_instr_seq_d;\n end\n end\n\n assign prev_instr_addr_incr = pc_id_o + (instr_is_compressed_id_o ? 32'd2 : 32'd4);\n\n // Buffer anticipated next PC address to ensure optimiser cannot remove the check.\n prim_buf #(.Width(32)) u_prev_instr_addr_incr_buf (\n .in_i (prev_instr_addr_incr),\n .out_o(prev_instr_addr_incr_buf)\n );\n\n // Check that the address equals the previous address +2/+4\n assign pc_mismatch_alert_o = prev_instr_seq_q & (pc_if_o != prev_instr_addr_incr_buf);\n\n end else begin : g_no_secure_pc\n assign pc_mismatch_alert_o = 1'b0;\n end\n\n if (BranchPredictor) begin : g_branch_predictor\n logic [31:0] instr_skid_data_q;\n logic [31:0] instr_skid_addr_q;\n logic instr_skid_bp_taken_q;\n logic instr_skid_valid_q, instr_skid_valid_d;\n logic instr_skid_en;\n logic instr_bp_taken_q, instr_bp_taken_d;\n\n logic predict_branch_taken_raw;\n\n // ID stages needs to know if branch was predicted taken so it can signal mispredicts\n if (ResetAll) begin : g_bp_taken_ra\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_bp_taken_q <= '0;\n end else if (if_id_pipe_reg_we) begin\n instr_bp_taken_q <= instr_bp_taken_d;\n end\n end\n end else begin : g_bp_taken_nr\n always_ff @(posedge clk_i) begin\n if (if_id_pipe_reg_we) begin\n instr_bp_taken_q <= instr_bp_taken_d;\n end\n end\n end\n\n // When branch prediction is enabled a skid buffer between the IF and ID/EX stage is introduced.\n // If an instruction in IF is predicted to be a taken branch and ID/EX is not ready the\n // instruction in IF is moved to the skid buffer which becomes the output of the IF stage until\n // the ID/EX stage accepts the instruction. The skid buffer is required as otherwise the ID/EX\n // ready signal is coupled to the instr_req_o output which produces a feedthrough path from\n // data_gnt_i -> instr_req_o (which needs to be avoided as for some interconnects this will\n // result in a combinational loop).\n\n assign instr_skid_en = predict_branch_taken & ~pc_set_i & ~id_in_ready_i & ~instr_skid_valid_q;\n\n assign instr_skid_valid_d = (instr_skid_valid_q & ~id_in_ready_i & ~stall_dummy_instr) |\n instr_skid_en;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_skid_valid_q <= 1'b0;\n end else begin\n instr_skid_valid_q <= instr_skid_valid_d;\n end\n end\n\n if (ResetAll) begin : g_instr_skid_ra\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n instr_skid_bp_taken_q <= '0;\n instr_skid_data_q <= '0;\n instr_skid_addr_q <= '0;\n end else if (instr_skid_en) begin\n instr_skid_bp_taken_q <= predict_branch_taken;\n instr_skid_data_q <= fetch_rdata;\n instr_skid_addr_q <= fetch_addr;\n end\n end\n end else begin : g_instr_skid_nr\n always_ff @(posedge clk_i) begin\n if (instr_skid_en) begin\n instr_skid_bp_taken_q <= predict_branch_taken;\n instr_skid_data_q <= fetch_rdata;\n instr_skid_addr_q <= fetch_addr;\n end\n end\n end\n\n ibex_branch_predict branch_predict_i (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .fetch_rdata_i(fetch_rdata),\n .fetch_pc_i (fetch_addr),\n .fetch_valid_i(fetch_valid),\n\n .predict_branch_taken_o(predict_branch_taken_raw),\n .predict_branch_pc_o (predict_branch_pc)\n );\n\n // If there is an instruction in the skid buffer there must be no branch prediction.\n // Instructions are only placed in the skid after they have been predicted to be a taken branch\n // so with the skid valid any prediction has already occurred.\n // Do not branch predict on instruction errors.\n assign predict_branch_taken = predict_branch_taken_raw & ~instr_skid_valid_q & ~fetch_err;\n\n assign if_instr_valid = fetch_valid | (instr_skid_valid_q & ~nt_branch_mispredict_i);\n assign if_instr_rdata = instr_skid_valid_q ? instr_skid_data_q : fetch_rdata;\n assign if_instr_addr = instr_skid_valid_q ? instr_skid_addr_q : fetch_addr;\n\n // Don't branch predict on instruction error so only instructions without errors end up in the\n // skid buffer.\n assign if_instr_bus_err = ~instr_skid_valid_q & fetch_err;\n assign instr_bp_taken_d = instr_skid_valid_q ? instr_skid_bp_taken_q : predict_branch_taken;\n\n assign fetch_ready = id_in_ready_i & ~stall_dummy_instr & ~instr_skid_valid_q;\n\n assign instr_bp_taken_o = instr_bp_taken_q;\n\n `ASSERT(NoPredictSkid, instr_skid_valid_q |-> ~predict_branch_taken)\n `ASSERT(NoPredictIllegal, predict_branch_taken |-> ~illegal_c_insn)\n end else begin : g_no_branch_predictor\n assign instr_bp_taken_o = 1'b0;\n assign predict_branch_taken = 1'b0;\n assign predict_branch_pc = 32'b0;\n\n assign if_instr_valid = fetch_valid;\n assign if_instr_rdata = fetch_rdata;\n assign if_instr_addr = fetch_addr;\n assign if_instr_bus_err = fetch_err;\n assign fetch_ready = id_in_ready_i & ~stall_dummy_instr;\n end\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT_KNOWN(IbexExcPcMuxKnown, exc_pc_mux_i)\n\n if (BranchPredictor) begin : g_branch_predictor_asserts\n `ASSERT_IF(IbexPcMuxValid, pc_mux_internal inside {\n PC_BOOT,\n PC_JUMP,\n PC_EXC,\n PC_ERET,\n PC_DRET,\n PC_BP},\n pc_set_i)\n\n`ifdef INC_ASSERT\n /**\n * Checks for branch prediction interface to fetch_fifo/icache\n *\n * The interface has two signals:\n * - predicted_branch_i: When set with a branch (branch_i) indicates the branch is a predicted\n * one, it should be ignored when a branch_i isn't set.\n * - branch_mispredict_i: Indicates the previously predicted branch was mis-predicted and\n * execution should resume with the not-taken side of the branch (i.e. continue with the PC\n * that followed the predicted branch). This must be raised before the instruction that is\n * made available following a predicted branch is accepted (Following a cycle with branch_i\n * & predicted_branch_i, branch_mispredict_i can only be asserted before or on the same cycle\n * as seeing fetch_valid & fetch_ready). When branch_mispredict_i is asserted, fetch_valid may\n * be asserted in response. If fetch_valid is asserted on the same cycle as\n * branch_mispredict_i this indicates the fetch_fifo/icache has the not-taken side of the\n * branch immediately ready for use\n */\n logic predicted_branch_live_q, predicted_branch_live_d;\n logic [31:0] predicted_branch_nt_pc_q, predicted_branch_nt_pc_d;\n logic [31:0] awaiting_instr_after_mispredict_q, awaiting_instr_after_mispredict_d;\n logic [31:0] next_pc;\n\n logic mispredicted, mispredicted_d, mispredicted_q;\n\n assign next_pc = fetch_addr + (instr_is_compressed_out ? 32'd2 : 32'd4);\n\n logic predicted_branch;\n\n // pc_set_i takes precendence over branch prediction\n assign predicted_branch = predict_branch_taken & ~pc_set_i;\n\n always_comb begin\n predicted_branch_live_d = predicted_branch_live_q;\n mispredicted_d = mispredicted_q;\n\n if (branch_req & predicted_branch) begin\n predicted_branch_live_d = 1'b1;\n mispredicted_d = 1'b0;\n end else if (predicted_branch_live_q) begin\n if (fetch_valid & fetch_ready) begin\n predicted_branch_live_d = 1'b0;\n end else if (nt_branch_mispredict_i) begin\n mispredicted_d = 1'b1;\n end\n end\n end\n\n always @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n predicted_branch_live_q <= 1'b0;\n mispredicted_q <= 1'b0;\n end else begin\n predicted_branch_live_q <= predicted_branch_live_d;\n mispredicted_q <= mispredicted_d;\n end\n end\n\n always @(posedge clk_i) begin\n if (branch_req & predicted_branch) begin\n predicted_branch_nt_pc_q <= next_pc;\n end\n end\n\n // Must only see mispredict after we've performed a predicted branch but before we've accepted\n // any instruction (with fetch_ready & fetch_valid) that follows that predicted branch.\n `ASSERT(MispredictOnlyImmediatelyAfterPredictedBranch,\n nt_branch_mispredict_i |-> predicted_branch_live_q)\n // Check that on mispredict we get the correct PC for the non-taken side of the branch when\n // prefetch buffer/icache makes that PC available.\n `ASSERT(CorrectPCOnMispredict,\n predicted_branch_live_q & mispredicted_d & fetch_valid |->\n fetch_addr == predicted_branch_nt_pc_q)\n // Must not signal mispredict over multiple cycles but it's possible to have back to back\n // mispredicts for different branches (core signals mispredict, prefetch buffer/icache immediate\n // has not-taken side of the mispredicted branch ready, which itself is a predicted branch,\n // following cycle core signal that that branch has mispredicted).\n `ASSERT(MispredictSingleCycle,\n nt_branch_mispredict_i & ~(fetch_valid & fetch_ready) |=> ~nt_branch_mispredict_i)\n // Note that we should never see a mispredict and an incoming branch on the same cycle.\n // The mispredict also cancels any predicted branch so overall branch_req must be low.\n `ASSERT(NoMispredBranch, nt_branch_mispredict_i |-> ~branch_req)\n`endif\n\n end else begin : g_no_branch_predictor_asserts\n `ASSERT_IF(IbexPcMuxValid, pc_mux_internal inside {\n PC_BOOT,\n PC_JUMP,\n PC_EXC,\n PC_ERET,\n PC_DRET},\n pc_set_i)\n end\n\n // Boot address must be aligned to 256 bytes.\n `ASSERT(IbexBootAddrUnaligned, boot_addr_i[7:0] == 8'h00)\n\n // Address must not contain X when request is sent.\n `ASSERT(IbexInstrAddrUnknown, instr_req_o |-> !$isunknown(instr_addr_o))\n\n // Address must be word aligned when request is sent.\n `ASSERT(IbexInstrAddrUnaligned, instr_req_o |-> (instr_addr_o[1:0] == 2'b00))\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/instruction_fetch.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/icache.rst", "doc/03_reference/exception_interrupts.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 2251, "lang": "sv", "rtl_files": ["rtl/ibex_core.sv"], "spec": "# Behavioral Design Specification for ibex_core\n\n## Overview\n\nThe `ibex_core` module implements a 32-bit RISC‑V processor core that executes the RV32I base integer instruction set (with the C extension for compressed instructions) and may optionally support further extensions (M, B, Zicsr, Zifencei). It is designed as a two‑stage pipeline (Instruction Fetch; Instruction Decode and Execute) with an optional third Writeback stage. The core interacts with external memory systems for instruction and data access, accepts interrupts and debug requests, and provides security monitoring outputs.\n\nThe core shall comply with the RISC‑V Privileged Architecture Specification v1.11 (Machine and User modes) and supports a subset of the version 0.13 Debug Specification. All optional features are controlled via compile‑time parameters.\n\n---\n\n## Configuration Parameters\n\nThe core’s behaviour is adjusted by the following parameters. The listed defaults apply unless otherwise overridden.\n\n| Parameter | Range / Values | Default | Behavioural Effect |\n|-------------------------|------------------------------------|----------------|--------------------------------------------------------------|\n| `PMPEnable` | `0` or `1` | `0` | When 1, Physical Memory Protection (PMP) is instantiated and enforced. |\n| `PMPGranularity` | `0` to `31` | `0` | Minimum region granularity in 2^(G+2) bytes. NA4 mode is unavailable if >0. |\n| `PMPNumRegions` | `1` to `16` | `4` | Number of implemented PMP regions (ignored if PMPEnable=0). |\n| `MHPMCounterNum` | `0` to `10` | `0` | Number of hardware performance‑monitor event counters. |\n| `MHPMCounterWidth` | `1` to `64` | `40` | Bit width of each performance‑monitor counter. |\n| `RV32E` | `0` or `1` | `0` | When 1, only 16 integer registers (x0–x15) are implemented (RV32E). |\n| `RV32M` | Enum: `RV32MNone`, `RV32MSlow`, `RV32MFast`, `RV32MSingleCycle` | `RV32MFast` | Multiplier/divider implementation variant (see M‑extension support). |\n| `RV32B` | Enum: `RV32BNone`, `RV32BBalanced`, `RV32BOTEarlGrey`, `RV32BFull` | `RV32BNone` | Bit‑manipulation extension feature set. |\n| `BranchTargetALU` | `0` or `1` | `0` | When 1, a dedicated ALU computes branch targets, removing one stall cycle for taken branches. |\n| `WritebackStage` | `0` or `1` | `0` | When 1, a third pipeline stage (Writeback) is added; improves load/store throughput. |\n| `ICache` | `0` or `1` | `0` | When 1, an instruction cache replaces the prefetch buffer. |\n| `ICacheECC` | `0` or `1` | `0` | Enable SECDED ECC on ICache tag/data RAMs (only if ICache=1). |\n| `BranchPredictor` | `0` or `1` | `0` | When 1, static branch prediction is attempted (experimental). |\n| `DbgTriggerEn` | `0` or `1` | `0` | Enable debug trigger (hardware breakpoint) support. |\n| `DbgHwBreakNum` | `1` (currently fixed) | `1` | Number of hardware breakpoints (ignored if DbgTriggerEn=0). |\n| `DmBaseAddr` | 32‑bit address | `0x1A110000` | Base address of the Debug Module. |\n| `DmAddrMask` | 32‑bit mask | `0x00000FFF` | Address mask for Debug Module accesses. |\n| `DmHaltAddr` | 32‑bit address | `0x1A110800` | Address to jump to when entering Debug Mode. |\n| `DmExceptionAddr` | 32‑bit address | `0x1A110808` | Address to jump to for exceptions in Debug Mode. |\n| `SecureIbex` | `0` or `1` | `0` | When 1, security‑enhancing features (data‑independent timing, dummy instructions, bus integrity, register‑file ECC, hardened PC, shadow CSRs) are enabled. This parameter must not be used together with `RV32M = RV32MNone`. |\n| `RndCnstLfsrSeed` | 32‑bit seed | *package default* | Initial LFSR seed for dummy instruction generation. |\n| `RndCnstLfsrPerm` | 32‑bit permutation | *package default* | Output permutation for the dummy‑instruction LFSR. |\n| `ResetAll` | `0` or `1` | `0` | When 1, more registers are reset to known values (affects debug features). |\n| `DummyInstructions` | `0` or `1` | `0` | When 1, dummy instruction insertion is available (requires SecureIbex). |\n| `RegFileECC` | `0` or `1` | `0` | When 1, register file reads are protected with ECC (requires SecureIbex). |\n| `MemECC` | `0` or `1` | `0` | When 1, bus integrity check bits are transmitted/received on memory interfaces. |\n\n---\n\n## External Interfaces\n\nThe core communicates with the outside world through the following groups of signals. All signals are synchronous to the single clock input `clk_i` and use an active‑low asynchronous reset `rst_ni`.\n\n### Clock and Reset\n\n- **`clk_i`** – System clock. All state changes occur on the rising edge.\n- **`rst_ni`** – Asynchronous reset, active low. Must be asserted for at least one full clock cycle.\n\n### Configuration\n\n- **`hart_id_i[31:0]`** – Hart identifier. Used to implement the `mhartid` CSR.\n- **`boot_addr_i[31:0]`** – Base address for the first instruction fetch. The core starts executing from `boot_addr_i + 0x80`.\n\n### Instruction‑Side Memory Interface\n\nThe core fetches instructions over a request‑grant‑response protocol. All addresses are word‑aligned; misaligned fetches are handled internally by issuing two word‑aligned requests.\n\n- **Request** (`instr_req_o`): asserted to indicate a new fetch request. Must remain high until grant is received.\n- **Address** (`instr_addr_o[31:0]`): valid when request is active.\n- **Grant** (`instr_gnt_i`): the memory system accepts the request. The core may change address and de‑assert request in the next cycle.\n- **Response valid** (`instr_rvalid_i`): asserted for one cycle to indicate that the read data and error signal are valid.\n- **Read data** (`instr_rdata_i`): instruction data, width depends on `MemDataWidth` (32 bits when `MemECC=0`; wider when ECC is used).\n- **Error** (`instr_err_i`): asserted with response valid to indicate a bus error.\n\nWhen `MemECC` is enabled, optional integrity bits accompany the read data (not listed individually in this spec). The core expects these bits to be checked internally and will raise an alert on mismatch.\n\n### Data‑Side Memory Interface (Load‑Store Unit)\n\nThe LSU uses the same request‑grant‑response protocol as the instruction interface, with additional signals for write enable, byte enables, write data, and error.\n\n- **Request** (`data_req_o`): asserted for read or write.\n- **Address** (`data_addr_o[31:0]`): word‑aligned for non‑misaligned accesses; misaligned accesses are split into two word‑aligned transactions.\n- **Write Enable** (`data_we_o`): `1` for store, `0` for load.\n- **Byte Enables** (`data_be_o[3:0]`): selects which bytes are active.\n- **Write Data** (`data_wdata_o`): value to be stored.\n- **Grant** (`data_gnt_i`): memory accepts the request.\n- **Response Valid** (`data_rvalid_i`): single‑cycle pulse indicating that read data and error are ready.\n- **Read Data** (`data_rdata_i`): data for loads.\n- **Error** (`data_err_i`): bus/access error indication.\n\nWhen `MemECC` is enabled, integrity bits are present on the data bus. The core checks them and suppresses load‑destination register write when an integrity error is detected.\n\n#### Protocol Details\n\n1. The core presents a request (`data_req_o` high) with valid address, write enable, byte enables, and write data (for stores).\n2. The memory responds with `data_gnt_i` high when it can commit the request. After grant, the core may change outputs in the next cycle.\n3. One or more cycles later, the memory returns a single‑cycle `data_rvalid_i` together with `data_rdata_i` and `data_err_i`.\n4. Multiple outstanding requests are not supported; the core issues a new request only after the previous grant.\n5. Responses are returned in order.\n\nWhen a PMP error is detected, the core still issues the external request (gated by the PMP check result only for the purpose of signalling an exception internally). The PMP error is captured and the core treats it as a bus error.\n\n### Interrupts\n\nThe core receives five categories of interrupt signals. All are level‑sensitive. The core samples them on every clock cycle and takes any pending interrupt according to the priority order defined by the RISC‑V Privileged Specification (fast interrupts have the highest priority; the lowest‑numbered fast interrupt has the highest priority among them).\n\n- **`irq_software_i`** – Machine software interrupt (ID 3).\n- **`irq_timer_i`** – Machine timer interrupt (ID 7).\n- **`irq_external_i`** – Machine external interrupt (ID 11).\n- **`irq_fast_i[14:0]`** – Up to 15 fast, local interrupts (IDs 16 to 30).\n- **`irq_nm_i`** – Non‑maskable interrupt (ID 31). It is always enabled (independent of `mstatus.MIE` and `mie`) and takes priority over all other interrupts. When an NMI is taken, further NMIs are suppressed until the handler returns (no nesting). The core jumps to `mtvec + 0x7C` to service the NMI.\n\nAll other interrupts require both the global enable bit (`mstatus.MIE`) and the corresponding bit in `mie` to be set. If multiple interrupts are pending simultaneously, the one with the highest priority (lowest ID per fast interrupts) will be taken.\n\n### Debug Interface\n\n- **`debug_req_i`** – Request to enter Debug Mode. This is a level‑sensitive input. The core will enter Debug Mode at the next instruction boundary (if not already in Debug Mode).\n\n- **`crash_dump_o`** – A structure containing the current PC, next PC, last data address, exception PC, and exception address. Useful for post‑mortem analysis.\n\n- **`double_fault_seen_o`** – Pulses high for one cycle when a synchronous exception occurs while another synchronous exception is already being handled (double‑fault detection).\n\n### CPU Control\n\n- **`fetch_enable_i`** – A multi‑bit signal using a “mubi” (multi‑bit) encoding. When the value equals `IbexMuBiOn`, the core may fetch new instructions; otherwise, it halts fetching after draining all in‑flight instructions. The core remains busy until all operations complete.\n- **`alert_minor_o`** – Pulse indicating a recoverable security event (e.g., ICache ECC error).\n- **`alert_major_internal_o`** – Pulse (may span multiple cycles) indicating an unrecoverable internal fault (e.g., register‑file ECC error, PC mismatch, shadow CSR inconsistency).\n- **`alert_major_bus_o`** – Pulse indicating an unrecoverable bus integrity or data integrity error.\n- **`core_busy_o`** – Multi‑bit signal (mubi encoding) that is `IbexMuBiOn` when the core is executing, has outstanding memory transactions, or is in a WFI sleep state (but not sleeping). It becomes `IbexMuBiOff` when the core is fully idle.\n\n### Register File Interface (External)\n\nThe core exposes the register file read/write ports so that the actual register storage can be placed outside the core logic (e.g., for dual‑core lockstep or ECC insertion).\n\n- **Read addresses** (`rf_raddr_a_o`, `rf_raddr_b_o`) – Two read ports for operand fetching.\n- **Write address** (`rf_waddr_wb_o`), **Write enable** (`rf_we_wb_o`), **Write data (with ECC)** (`rf_wdata_wb_ecc_o`).\n- **Read data (with ECC)** (`rf_rdata_a_ecc_i`, `rf_rdata_b_ecc_i`).\n- **Dummy instruction indicators** (`dummy_instr_id_o`, `dummy_instr_wb_o`) – Indicate that the current instruction in a pipeline stage is a dummy instruction.\n\n### Instruction Cache RAM Interface\n\nWhen `ICache=1`, the core provides separate interfaces for tag and data RAMs, including request, write enable, address, write data, and read data ports. An additional scrambling‑key interface (`ic_scr_key_valid_i`, `ic_scr_key_req_o`) is used when `SecureIbex=1`.\n\n---\n\n## Pipeline Behaviour\n\n### Two‑Stage Pipeline (default)\n\nThe core executes instructions through two stages:\n\n1. **Instruction Fetch (IF)** – Fetches instructions from memory via a prefetch buffer (or ICache). It issues requests to the instruction‑side memory, stores fetched instructions in a small FIFO, and passes them to the ID/EX stage along with the associated program counter (PC). Compressed instructions are expanded to their uncompressed form before decode.\n2. **Instruction Decode and Execute (ID/EX)** – Decodes the instruction, reads the register file, executes the operation (using the ALU, multiplier/divider, CSR block, or LSU), and writes results back to the register file. Multi‑cycle instructions (loads, stores, multiplies, divides, branches, jumps) may stall the pipeline for multiple cycles.\n\nThe register file is written in the same cycle as the result is produced. For load instructions, the write occurs in the cycle the load response is received, potentially causing a stall until that response arrives.\n\n### Three‑Stage Pipeline (WritebackStage=1)\n\nWhen the `WritebackStage` parameter is set, a third stage (Writeback) is inserted between ID/EX and the register file. In this configuration:\n\n- Load data is written to the register file in the Writeback stage.\n- The Writeback stage also handles store completion and exception reporting.\n- This reduces the number of stall cycles for loads because the ID/EX stage can proceed while the Writeback stage waits for memory.\n- The pipeline depth becomes three: IF, ID/EX, WB.\n\n### Multi‑Cycle Instruction Performance\n\nThe core exhibits the following stall behaviour (based on the two‑stage pipeline; three‑stage improves load/store stalling):\n\n| Instruction Type | Minimum stall cycles | Details |\n|--------------------------|----------------------|---------|\n| Integer computational | 0 | One‑cycle instructions. |\n| CSR access | 0 | One‑cycle instructions. |\n| Load / Store | 1 (up to N) | Stalled until memory response arrives. N depends on memory latency. |\n| Multiplication (fast) | 2 (MUL), 3 (MULH) | Three‑cycle multiply‑accumulate. |\n| Division | 1 (div0) or 37 | Long division algorithm; early exit on divide‑by‑zero. |\n| Jump | 1 (up to N) | New PC request on instruction bus; wait for first instruction. |\n| Branch (not‑taken) | 0 | No stall. |\n| Branch (taken) | 2 (up to N) | Branch target calculation + fetch. With `BranchTargetALU=1` reduces to 1 (up to N). |\n| Fence.I | Same as jump | Internally behaves as a jump. |\n\nWhen data‑independent timing is enabled (SecureIbex=1, `data_ind_timing=1`), the core forces all branches to behave as taken (removing early exit), and disables early completion of multiply/divide by zero/one to make execution time constant.\n\n---\n\n## Instruction Execution\n\nThe core implements the following RISC‑V instruction sets and extensions based on configuration:\n\n- **RV32I** – Base integer instruction set (always present).\n- **RV32C** – Compressed instructions (always present).\n- **Zicsr** – CSR instructions (always present).\n- **Zifencei** – Instruction‑fence instructions (always present).\n- **RV32M** – Multiply/divide extension (optional, controlled by `RV32M` parameter). If `RV32M=None`, any multiply/div instruction raises an illegal instruction exception.\n- **RV32B** – Bit‑manipulation extension (optional, controlled by `RV32B` parameter, see documentation for sub‑extension breakdown).\n- **User‑mode support** – The core supports User Mode (U‑Mode) and Machine Mode (M‑Mode). Traps from U‑Mode go to M‑Mode. The `mstatus.TW` bit causes a trap when WFI is executed in U‑Mode.\n\nThe core does **not** support Supervisor Mode or hypervisor extensions.\n\n---\n\n## Exceptions and Interrupts (Trap Handling)\n\n### Trap Entry\n\nWhen an exception or interrupt is taken:\n\n1. The current PC is saved in `mepc` (for exceptions) or set to the appropriate return address for interrupts.\n2. `mstatus.MIE` is copied to `mstatus.MPIE`, then `mstatus.MIE` is cleared.\n3. The current privilege mode is saved into `mstatus.MPP`.\n4. The cause is stored in `mcause`, and optional trap‑specific information is stored in `mtval`.\n5. The core jumps to the trap handler address: for interrupts, `mtvec + 4 * interrupt_id` (vectored mode); for exceptions, `mtvec` (always aligned to 256 bytes).\n6. After reset, `mtvec` is initialised to the `boot_addr_i` with the lowest two bits set to `01` (vectored mode).\n\n### Trap Return\n\nOn executing an `MRET` instruction (in M‑Mode) or `DRET` (in Debug Mode):\n\n- The PC is restored from `mepc` (or `dpc` for debug).\n- `mstatus.MIE` is restored from `mstatus.MPIE`.\n- The privilege mode is restored from `mstatus.MPP`.\n\n### Exception Causes\n\n| Exception Code | Cause |\n|----------------|--------------------------------|\n| 1 | Instruction access fault |\n| 2 | Illegal instruction |\n| 3 | Breakpoint (EBREAK) |\n| 5 | Load access fault |\n| 7 | Store access fault |\n| 8 | ECALL from U‑Mode |\n| 11 | ECALL from M‑Mode |\n\n### Nested Trap Handling\n\nThe core does **not** automatically nest traps. While servicing an exception or interrupt, further interrupts are disabled (because `mstatus.MIE` is cleared). Software may re‑enable interrupts after saving the necessary CSRs. A double‑fault condition is detected when a synchronous exception occurs while a previous synchronous exception is already being handled (see `double_fault_seen_o` output).\n\n### Internal Interrupts (SecureIbex)\n\nWhen `SecureIbex=1`, the core can generate an internal NMI for load‑integrity errors. The `mcause` for this internal interrupt is `0xFFFFFFE0`; `mtval` holds the faulting address. The external NMI input (`irq_nm_i`) takes priority over this internal interrupt.\n\n---\n\n## Debug Support\n\nDebug support follows the RISC‑V Debug Specification v0.13. The core provides:\n\n- **Debug Mode entry** via `debug_req_i`, EBREAK instruction (if configured), single‑step (`dcsr.step`), or hardware trigger match.\n- **Core debug registers**: `dcsr`, `dpc`, `dscratch0`, `dscratch1`, accessible only in Debug Mode.\n- **Trigger registers** (`tselect`, `tdata1`, `tdata2`, `tdata3`, `mcontext`, `scontext`) – These are only available when `DbgTriggerEn=1` and support one hardware breakpoint on instruction address.\n- **Debug module address region** – PMP checks are bypassed for accesses to the Debug Module address range (defined by `DmBaseAddr` and `DmAddrMask`). The core jumps to `DmHaltAddr` when entering Debug Mode, and to `DmExceptionAddr` if an exception occurs while in Debug Mode.\n\n---\n\n## Security Features (SecureIbex == 1)\n\nWhen `SecureIbex=1`, the core activates several countermeasures. Most are runtime‑configurable through the `cpuctrl` custom CSR.\n\n- **Data‑independent timing**: Branches execute as if taken; early termination of multiply/divide is suppressed. (Controlled by `cpuctrl.data_ind_timing`.)\n- **Dummy instruction insertion**: At random intervals, dummy instructions (multiply/divide) are injected into the pipeline without affecting architectural state. The injection rate is controlled by `cpuctrl.dummy_instr_mask`. The LFSR can be reseeded via the `secureseed` CSR.\n- **Bus integrity checking**: Incoming instruction and data read signals include SECDED check bits. On a mismatch:\n - A bus major alert is generated.\n - Load data is not written to the destination register.\n - An internal NMI is raised.\n- **Register file ECC**: Reads from the register file are ECC‑protected. Detection results in an internal major alert.\n- **Hardened PC**: The IF‑stage PC is checked to be the previous PC plus the instruction size. On mismatch, an internal major alert is generated.\n- **Shadow CSRs**: Critical CSRs (`mstatus`, `mtvec`, `cpuctrl`, `pmpcfg`, `pmpaddr`) have duplicated, inverted copies that are constantly compared. Mismatch causes an internal major alert. (This feature is not presently used when SecureIbex=1; dual‑core lockstep is used instead.)\n\n### Alert Outputs\n\n- `alert_minor_o` – Asserted for one cycle per ICache ECC error.\n- `alert_major_internal_o` – Asserted for register file ECC errors, PC mismatch, or shadow CSR mismatch.\n- `alert_major_bus_o` – Asserted for instruction or data bus integrity errors.\n\n---\n\n## Power Management\n\nThe core can be placed into a low‑power sleep mode by executing the `WFI` instruction. While sleeping:\n\n- No instruction fetches are performed.\n- The core remains responsive to external interrupts, non‑maskable interrupts, and debug requests.\n- The `core_busy_o` output becomes `IbexMuBiOff` once all outstanding memory transactions are complete and the core is asleep.\n\nThe `fetch_enable_i` input provides an alternative way to halt instruction fetching. When disabled, the core completes any in‑flight instructions and then stops fetching.\n\n---\n\n## Implementation‑Specific Behaviour\n\n### Misaligned Accesses\n\n- **Instruction fetches**: Externally always word‑aligned; misaligned accesses are handled internally by performing two word‑aligned fetches.\n- **Loads and stores**: The LSU splits misaligned transactions into two word‑aligned bus accesses. Each sub‑access follows the standard grant/response protocol. If the first sub‑access receives an error, the second is still issued but its response is ignored.\n\n### Bus Error Handling\n\n- A bus error on an instruction fetch causes an instruction access fault exception.\n- A bus error (or PMP error) on a load causes a load access fault exception. The destination register is not updated.\n- A bus error on a store causes a store access fault exception.\n- Integrity errors on bus data cause an internal major alert and, for loads, suppress the destination register write.\n\n### Reset Behaviour\n\n- On reset, the core starts fetching from `boot_addr_i + 0x80`.\n- All CSRs are set to their reset values (see documentation for each CSR). The `mtvec` CSR is set to the boot address (aligned) plus the vectored‑mode indicator.\n- The LFSR for dummy instructions is initialised to the parameterised seed/permutation.\n- The ICache is disabled if present.\n\n### Performance Counters\n\nThe core implements `mcycle` (cycle counter), `minstret` (instruction‑retired counter), and up to 10 additional `mhpmcounter` registers that count selected events (e.g., jumps, branches, memory loads/stores, stalls). The event selector for each counter is configurable via `mhpmevent*` CSRs. All counters can be inhibited by `mcountinhibit`.\n\n---\n\n## Summary of Compliance\n\n- **ISA**: RV32I[MC] + Zicsr + Zifencei + optional B extension.\n- **Privileged Architecture**: v1.11 (M‑Mode and U‑Mode).\n- **Debug**: v0.13 (select features: halt, resume, single‑step, triggers).\n- **PMP**: v1.12, including Smepmp v1.0 enhancements.\n- **Security enhancements**: Data‑independent timing, dummy instructions, SECDED bus integrity, register file ECC, hardened PC, shadow CSRs, dual‑core lockstep (external to this module).", "commit_id": "591c3812f951a4acc8014eb2d9d727936d11bf99", "timestamp": "2025-01-24T13:08:20+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "78739562ce7b2606c4e208d4029ab890255769f6", "pr_title": "[ibex_core] Fix assertion when SecureIbex is false", "pr_body": "This assertion wasn't quite correct if SecureIbex is false because it was checking for the magic IbexMuBiOn value instead of just looking at the bottom bit.\r\n\r\nFixes #2249.", "issue_title": "Ibex core assertion NoExecWhenFetchEnableNotOn not gated correctly.", "issue_body": "## Observed Behavior\nI'm seeing the NoExecWhenFetchEnableNotOn assertion fire inside of ibex_core.sv in a case where I'm not using the lockstep mode. I have a single instance of Ibex with the default parameters including `parameter bit SecureIbex = 1'b0,`\n\nThe assertion in question is part of the following code block:\n\n```\n // Keep track of the PC last seen in the ID stage when fetch is disabled\n logic [31:0] pc_at_fetch_disable;\n ibex_mubi_t last_fetch_enable;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pc_at_fetch_disable <= '0;\n last_fetch_enable <= '0;\n end else begin\n last_fetch_enable <= fetch_enable_i;\n\n if ((fetch_enable_i != IbexMuBiOn) && (last_fetch_enable == IbexMuBiOn)) begin\n pc_at_fetch_disable <= pc_id;\n end\n end\n end\n\n // When fetch is disabled no instructions should be executed. Once fetch is disabled either the\n // ID/EX stage is not valid or the PC of the ID/EX stage must remain as it was at disable. The\n // ID/EX valid should not ressert once it has been cleared.\n `ASSERT(\n NoExecWhenFetchEnableNotOn,\n fetch_enable_i != IbexMuBiOn |=> (~instr_valid_id || (pc_id == pc_at_fetch_disable)) && ~$rose\n (instr_valid_id))\n```\n\nMy understanding from reading the documentation about `fetch_enable_i` was that I just needed to tie the LSB to 1. So I'm driving the input port to `4'b0001`. If that is correct, then it looks like this assertion shouldn't be firing. It should probably only be used when `SecureIbex == 1`?\n\nThe assertion fires for the first valid instruction fetched after reset.\n\n## Expected Behavior\nNo assertion should fire - unless I'm missing the fact that I'm doing something stupid.\n\n## Steps to reproduce the issue\nMy instantiation looks like:\n```\n ibex_top #(\n .RV32M (ibex_pkg::RV32MSlow),\n .RV32B (ibex_pkg::RV32BNone),\n .RegFile(ibex_pkg::RegFileFPGA)\n ) u_top (\n // Clock and reset\n .clk_i (clk),\n .rst_ni (!rst),\n .test_en_i ('0),\n .scan_rst_ni('0),\n .ram_cfg_i ('0),\n\n // Configuration\n .hart_id_i ('0),\n .boot_addr_i('0),\n\n // Instruction memory interface\n .instr_req_o (instr_req),\n .instr_gnt_i (instr_gnt),\n .instr_rvalid_i (instr_rvalid),\n .instr_addr_o (instr_addr),\n .instr_rdata_i (instr_rdata),\n .instr_rdata_intg_i('0),\n .instr_err_i (instr_err),\n\n // Data memory interface\n .data_req_o (data_req),\n .data_gnt_i (data_gnt),\n .data_rvalid_i (data_rvalid),\n .data_we_o (data_we),\n .data_be_o (data_be),\n .data_addr_o (data_addr),\n .data_wdata_o (data_wdata),\n .data_wdata_intg_o(),\n .data_rdata_i (data_rdata),\n .data_rdata_intg_i('0),\n .data_err_i (data_err),\n\n // Interrupt inputs\n .irq_software_i('0),\n .irq_timer_i (timer_irq),\n .irq_external_i('0),\n .irq_fast_i ('0),\n .irq_nm_i ('0),\n\n // Scrambling Interface\n .scramble_key_valid_i('0),\n .scramble_key_i ('0),\n .scramble_nonce_i ('0),\n .scramble_req_o (),\n\n // Debug interface\n .debug_req_i ('0),\n .crash_dump_o (),\n .double_fault_seen_o(),\n\n // Special control signals\n .fetch_enable_i (4'b0001),\n .alert_minor_o (),\n .alert_major_internal_o(),\n .alert_major_bus_o (),\n .core_sleep_o ()\n );\n```\n\n## My Environment\n\n**EDA tool and version:**\nCadence Xcelium 24.03\n\n**Operating system:**\nRHEL 9.5\n\n**Version of the Ibex source code:**\n8f4c75c5e43e61b994248307c814e01860303056\n", "commit_message": "[ibex_core] Fix assertion when SecureIbex is false\n\nThis assertion wasn't quite correct if SecureIbex is false because it\nwas checking for the magic IbexMuBiOn value instead of just looking at\nthe bottom bit.\n\nFixes #2249.", "fix_patch": "diff --git a/rtl/ibex_core.sv b/rtl/ibex_core.sv\nindex 67ab922466..3e19196284 100644\n--- a/rtl/ibex_core.sv\n+++ b/rtl/ibex_core.sv\n@@ -1020,13 +1020,19 @@ module ibex_core import ibex_pkg::*; #(\n end\n end\n \n- // When fetch is disabled no instructions should be executed. Once fetch is disabled either the\n+ // A 1-bit encoding of fetch_enable_i to avoid polluting the NoExecWhenFetchEnableNotOn assertion\n+ // with notes about SecureIbex and mubi values.\n+ logic fetch_enable_raw;\n+ assign fetch_enable_raw = SecureIbex ? (fetch_enable_i == IbexMuBiOn) : fetch_enable_i[0];\n+\n+ // When fetch is disabled, no instructions should be executed. Once fetch is disabled either the\n // ID/EX stage is not valid or the PC of the ID/EX stage must remain as it was at disable. The\n // ID/EX valid should not ressert once it has been cleared.\n- `ASSERT(NoExecWhenFetchEnableNotOn, fetch_enable_i != IbexMuBiOn |=>\n- (~instr_valid_id || (pc_id == pc_at_fetch_disable)) && ~$rose(instr_valid_id))\n+ `ASSERT(NoExecWhenFetchEnableNotOn,\n+ !fetch_enable_raw |=>\n+ (~instr_valid_id || (pc_id == pc_at_fetch_disable)) && ~$rose(instr_valid_id))\n \n- `endif\n+ `endif // INC_ASSERT\n \n ////////////////////////\n // RF (Register File) //\n", "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`include \"dv_fcov_macros.svh\"\n\n/**\n * Top level module of the ibex RISC-V core\n */\nmodule ibex_core import ibex_pkg::*; #(\n parameter bit PMPEnable = 1'b0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter ibex_pkg::pmp_cfg_t PMPRstCfg[16] = ibex_pkg::PmpCfgRst,\n parameter logic [33:0] PMPRstAddr[16] = ibex_pkg::PmpAddrRst,\n parameter ibex_pkg::pmp_mseccfg_t PMPRstMsecCfg = ibex_pkg::PmpMseccfgRst,\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 bit BranchTargetALU = 1'b0,\n parameter bit WritebackStage = 1'b0,\n parameter bit ICache = 1'b0,\n parameter bit ICacheECC = 1'b0,\n parameter int unsigned BusSizeECC = BUS_SIZE,\n parameter int unsigned TagSizeECC = IC_TAG_SIZE,\n parameter int unsigned LineSizeECC = IC_LINE_SIZE,\n parameter bit BranchPredictor = 1'b0,\n parameter bit DbgTriggerEn = 1'b0,\n parameter int unsigned DbgHwBreakNum = 1,\n parameter bit ResetAll = 1'b0,\n parameter lfsr_seed_t RndCnstLfsrSeed = RndCnstLfsrSeedDefault,\n parameter lfsr_perm_t RndCnstLfsrPerm = RndCnstLfsrPermDefault,\n parameter bit SecureIbex = 1'b0,\n parameter bit DummyInstructions= 1'b0,\n parameter bit RegFileECC = 1'b0,\n parameter int unsigned RegFileDataWidth = 32,\n parameter bit MemECC = 1'b0,\n parameter int unsigned MemDataWidth = MemECC ? 32 + 7 : 32,\n parameter int unsigned DmBaseAddr = 32'h1A110000,\n parameter int unsigned DmAddrMask = 32'h00000FFF,\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 // Internally generated resets in ibex_lockstep cause IMPERFECTSCH warnings.\n // TODO: Remove when upgrading Verilator #2134.\n /* verilator lint_off IMPERFECTSCH */\n input logic rst_ni,\n /* verilator lint_on IMPERFECTSCH */\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 [MemDataWidth-1:0] instr_rdata_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 [MemDataWidth-1:0] data_wdata_o,\n input logic [MemDataWidth-1:0] data_rdata_i,\n input logic data_err_i,\n\n // Register file interface\n output logic dummy_instr_id_o,\n output logic dummy_instr_wb_o,\n output logic [4:0] rf_raddr_a_o,\n output logic [4:0] rf_raddr_b_o,\n output logic [4:0] rf_waddr_wb_o,\n output logic rf_we_wb_o,\n output logic [RegFileDataWidth-1:0] rf_wdata_wb_ecc_o,\n input logic [RegFileDataWidth-1:0] rf_rdata_a_ecc_i,\n input logic [RegFileDataWidth-1:0] rf_rdata_b_ecc_i,\n\n // RAMs interface\n output logic [IC_NUM_WAYS-1:0] ic_tag_req_o,\n output logic ic_tag_write_o,\n output logic [IC_INDEX_W-1:0] ic_tag_addr_o,\n output logic [TagSizeECC-1:0] ic_tag_wdata_o,\n input logic [TagSizeECC-1:0] ic_tag_rdata_i [IC_NUM_WAYS],\n output logic [IC_NUM_WAYS-1:0] ic_data_req_o,\n output logic ic_data_write_o,\n output logic [IC_INDEX_W-1:0] ic_data_addr_o,\n output logic [LineSizeECC-1:0] ic_data_wdata_o,\n input logic [LineSizeECC-1:0] ic_data_rdata_i [IC_NUM_WAYS],\n input logic ic_scr_key_valid_i,\n output logic ic_scr_key_req_o,\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 output logic irq_pending_o,\n\n // Debug Interface\n input logic debug_req_i,\n output crash_dump_t crash_dump_o,\n // SEC_CM: EXCEPTION.CTRL_FLOW.LOCAL_ESC\n // SEC_CM: EXCEPTION.CTRL_FLOW.GLOBAL_ESC\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_pre_mip,\n output logic [31:0] rvfi_ext_post_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 output logic rvfi_ext_irq_valid,\n `endif\n\n // CPU Control Signals\n // SEC_CM: FETCH.CTRL.LC_GATED\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 ibex_mubi_t core_busy_o\n);\n\n localparam int unsigned PMPNumChan = 3;\n // SEC_CM: CORE.DATA_REG_SW.SCA\n localparam bit DataIndTiming = SecureIbex;\n localparam bit PCIncrCheck = SecureIbex;\n localparam bit ShadowCSR = 1'b0;\n\n // IF/ID signals\n logic dummy_instr_id;\n logic instr_valid_id;\n logic instr_new_id;\n logic [31:0] instr_rdata_id; // Instruction sampled inside IF stage\n logic [31:0] instr_rdata_alu_id; // Instruction sampled inside IF stage (replicated to\n // ease fan-out)\n logic [15:0] instr_rdata_c_id; // Compressed instruction sampled inside IF stage\n logic instr_is_compressed_id;\n logic instr_perf_count_id;\n logic instr_bp_taken_id;\n logic instr_fetch_err; // Bus error on instr fetch\n logic instr_fetch_err_plus2; // Instruction error is misaligned\n logic illegal_c_insn_id; // Illegal compressed instruction sent to ID stage\n logic [31:0] pc_if; // Program counter in IF stage\n logic [31:0] pc_id; // Program counter in ID stage\n logic [31:0] pc_wb; // Program counter in WB stage\n logic [33:0] imd_val_d_ex[2]; // Intermediate register for multicycle Ops\n logic [33:0] imd_val_q_ex[2]; // Intermediate register for multicycle Ops\n logic [1:0] imd_val_we_ex;\n\n logic data_ind_timing;\n logic dummy_instr_en;\n logic [2:0] dummy_instr_mask;\n logic dummy_instr_seed_en;\n logic [31:0] dummy_instr_seed;\n logic icache_enable;\n logic icache_inval;\n logic icache_ecc_error;\n logic pc_mismatch_alert;\n logic csr_shadow_err;\n\n logic instr_first_cycle_id;\n logic instr_valid_clear;\n logic pc_set;\n logic nt_branch_mispredict;\n logic [31:0] nt_branch_addr;\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_t exc_cause; // Exception cause\n\n logic instr_intg_err;\n logic lsu_load_err, lsu_load_err_raw;\n logic lsu_store_err, lsu_store_err_raw;\n logic lsu_load_resp_intg_err;\n logic lsu_store_resp_intg_err;\n\n logic expecting_load_resp_id;\n logic expecting_store_resp_id;\n\n // LSU signals\n logic lsu_addr_incr_req;\n logic [31:0] lsu_addr_last;\n\n // Jump and branch target and decision (EX->IF)\n logic [31:0] branch_target_ex;\n logic branch_decision;\n\n // Core busy signals\n logic ctrl_busy;\n logic if_busy;\n logic lsu_busy;\n\n // Register File\n logic [4:0] rf_raddr_a;\n logic [31:0] rf_rdata_a;\n logic [4:0] rf_raddr_b;\n logic [31:0] rf_rdata_b;\n logic rf_ren_a;\n logic rf_ren_b;\n logic [4:0] rf_waddr_wb;\n logic [31:0] rf_wdata_wb;\n // Writeback register write data that can be used on the forwarding path (doesn't factor in memory\n // read data as this is too late for the forwarding path)\n logic [31:0] rf_wdata_fwd_wb;\n logic [31:0] rf_wdata_lsu;\n logic rf_we_wb;\n logic rf_we_lsu;\n logic rf_ecc_err_comb;\n\n logic [4:0] rf_waddr_id;\n logic [31:0] rf_wdata_id;\n logic rf_we_id;\n logic rf_rd_a_wb_match;\n logic rf_rd_b_wb_match;\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] bt_a_operand;\n logic [31:0] bt_b_operand;\n\n logic [31:0] alu_adder_result_ex; // Used to forward computed address to LSU\n logic [31:0] result_ex;\n\n // Multiplier Control\n logic mult_en_ex;\n logic div_en_ex;\n logic mult_sel_ex;\n logic div_sel_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 logic multdiv_ready_id;\n\n // CSR control\n logic csr_access;\n csr_op_e csr_op;\n logic csr_op_en;\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 lsu_we;\n logic [1:0] lsu_type;\n logic lsu_sign_ext;\n logic lsu_req;\n logic lsu_rdata_valid;\n logic [31:0] lsu_wdata;\n logic lsu_req_done;\n\n // stall control\n logic id_in_ready;\n logic ex_valid;\n\n logic lsu_resp_valid;\n logic lsu_resp_err;\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 logic instr_req_gated;\n logic instr_exec;\n\n // Writeback stage\n logic en_wb;\n wb_instr_type_e instr_type_wb;\n logic ready_wb;\n logic rf_write_wb;\n logic outstanding_load_wb;\n logic outstanding_store_wb;\n logic dummy_instr_wb;\n\n // Interrupts\n logic nmi_mode;\n irqs_t irqs;\n logic csr_mstatus_mie;\n logic [31:0] csr_mepc, csr_depc;\n\n // PMP signals\n logic [33:0] csr_pmp_addr [PMPNumRegions];\n pmp_cfg_t csr_pmp_cfg [PMPNumRegions];\n pmp_mseccfg_t csr_pmp_mseccfg;\n logic pmp_req_err [PMPNumChan];\n logic data_req_out;\n\n logic csr_save_if;\n logic csr_save_id;\n logic csr_save_wb;\n logic csr_restore_mret_id;\n logic csr_restore_dret_id;\n logic csr_save_cause;\n logic csr_mtvec_init;\n logic [31:0] csr_mtvec;\n logic [31:0] csr_mtval;\n logic csr_mstatus_tw;\n priv_lvl_e priv_mode_id;\n priv_lvl_e priv_mode_lsu;\n\n // debug mode and dcsr configuration\n logic debug_mode;\n logic debug_mode_entering;\n dbg_cause_e debug_cause;\n logic debug_csr_save;\n logic debug_single_step;\n logic debug_ebreakm;\n logic debug_ebreaku;\n logic trigger_match;\n\n // signals relating to instruction movements between pipeline stages\n // used by performance counters and RVFI\n logic instr_id_done;\n logic instr_done_wb;\n\n logic perf_instr_ret_wb;\n logic perf_instr_ret_compressed_wb;\n logic perf_instr_ret_wb_spec;\n logic perf_instr_ret_compressed_wb_spec;\n logic perf_iside_wait;\n logic perf_dside_wait;\n logic perf_mul_wait;\n logic perf_div_wait;\n logic perf_jump;\n logic perf_branch;\n logic perf_tbranch;\n logic perf_load;\n logic perf_store;\n\n // for RVFI\n logic illegal_insn_id, unused_illegal_insn_id; // ID stage sees an illegal instruction\n\n //////////////////////\n // Clock management //\n //////////////////////\n\n // Before going to sleep, wait for I- and D-side\n // interfaces to finish ongoing operations.\n if (SecureIbex) begin : g_core_busy_secure\n // For secure Ibex, the individual bits of core_busy_o are generated from different copies of\n // the various busy signal.\n localparam int unsigned NumBusySignals = 3;\n localparam int unsigned NumBusyBits = $bits(ibex_mubi_t) * NumBusySignals;\n logic [NumBusyBits-1:0] busy_bits_buf;\n prim_buf #(\n .Width(NumBusyBits)\n ) u_fetch_enable_buf (\n .in_i ({$bits(ibex_mubi_t){ctrl_busy, if_busy, lsu_busy}}),\n .out_o(busy_bits_buf)\n );\n\n // Set core_busy_o to IbexMuBiOn if even a single input is high.\n for (genvar i = 0; i < $bits(ibex_mubi_t); i++) begin : g_core_busy_bits\n if (IbexMuBiOn[i] == 1'b1) begin : g_pos\n assign core_busy_o[i] = |busy_bits_buf[i*NumBusySignals +: NumBusySignals];\n end else begin : g_neg\n assign core_busy_o[i] = ~|busy_bits_buf[i*NumBusySignals +: NumBusySignals];\n end\n end\n end else begin : g_core_busy_non_secure\n // For non secure Ibex, synthesis is allowed to optimize core_busy_o.\n assign core_busy_o = (ctrl_busy || if_busy || lsu_busy) ? IbexMuBiOn : IbexMuBiOff;\n end\n\n //////////////\n // IF stage //\n //////////////\n\n ibex_if_stage #(\n .DmHaltAddr (DmHaltAddr),\n .DmExceptionAddr (DmExceptionAddr),\n .DummyInstructions(DummyInstructions),\n .ICache (ICache),\n .ICacheECC (ICacheECC),\n .BusSizeECC (BusSizeECC),\n .TagSizeECC (TagSizeECC),\n .LineSizeECC (LineSizeECC),\n .PCIncrCheck (PCIncrCheck),\n .ResetAll (ResetAll),\n .RndCnstLfsrSeed (RndCnstLfsrSeed),\n .RndCnstLfsrPerm (RndCnstLfsrPerm),\n .BranchPredictor (BranchPredictor),\n .MemECC (MemECC),\n .MemDataWidth (MemDataWidth)\n ) if_stage_i (\n .clk_i (clk_i),\n .rst_ni(rst_ni),\n\n .boot_addr_i(boot_addr_i),\n .req_i (instr_req_gated), // 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 .instr_bus_err_i (instr_err_i),\n .instr_intg_err_o (instr_intg_err),\n\n .ic_tag_req_o (ic_tag_req_o),\n .ic_tag_write_o (ic_tag_write_o),\n .ic_tag_addr_o (ic_tag_addr_o),\n .ic_tag_wdata_o (ic_tag_wdata_o),\n .ic_tag_rdata_i (ic_tag_rdata_i),\n .ic_data_req_o (ic_data_req_o),\n .ic_data_write_o (ic_data_write_o),\n .ic_data_addr_o (ic_data_addr_o),\n .ic_data_wdata_o (ic_data_wdata_o),\n .ic_data_rdata_i (ic_data_rdata_i),\n .ic_scr_key_valid_i(ic_scr_key_valid_i),\n .ic_scr_key_req_o (ic_scr_key_req_o),\n\n // outputs to ID stage\n .instr_valid_id_o (instr_valid_id),\n .instr_new_id_o (instr_new_id),\n .instr_rdata_id_o (instr_rdata_id),\n .instr_rdata_alu_id_o (instr_rdata_alu_id),\n .instr_rdata_c_id_o (instr_rdata_c_id),\n .instr_is_compressed_id_o(instr_is_compressed_id),\n .instr_bp_taken_o (instr_bp_taken_id),\n .instr_fetch_err_o (instr_fetch_err),\n .instr_fetch_err_plus2_o (instr_fetch_err_plus2),\n .illegal_c_insn_id_o (illegal_c_insn_id),\n .dummy_instr_id_o (dummy_instr_id),\n .pc_if_o (pc_if),\n .pc_id_o (pc_id),\n .pmp_err_if_i (pmp_req_err[PMP_I]),\n .pmp_err_if_plus2_i (pmp_req_err[PMP_I2]),\n\n // control signals\n .instr_valid_clear_i (instr_valid_clear),\n .pc_set_i (pc_set),\n .pc_mux_i (pc_mux_id),\n .nt_branch_mispredict_i(nt_branch_mispredict),\n .exc_pc_mux_i (exc_pc_mux_id),\n .exc_cause (exc_cause),\n .dummy_instr_en_i (dummy_instr_en),\n .dummy_instr_mask_i (dummy_instr_mask),\n .dummy_instr_seed_en_i (dummy_instr_seed_en),\n .dummy_instr_seed_i (dummy_instr_seed),\n .icache_enable_i (icache_enable),\n .icache_inval_i (icache_inval),\n .icache_ecc_error_o (icache_ecc_error),\n\n // branch targets\n .branch_target_ex_i(branch_target_ex),\n .nt_branch_addr_i (nt_branch_addr),\n\n // CSRs\n .csr_mepc_i (csr_mepc), // exception return address\n .csr_depc_i (csr_depc), // debug return address\n .csr_mtvec_i (csr_mtvec), // trap-vector base address\n .csr_mtvec_init_o(csr_mtvec_init),\n\n // pipeline stalls\n .id_in_ready_i(id_in_ready),\n\n .pc_mismatch_alert_o(pc_mismatch_alert),\n .if_busy_o (if_busy)\n );\n\n // Core is waiting for the ISide when ID/EX stage is ready for a new instruction but none are\n // available\n assign perf_iside_wait = id_in_ready & ~instr_valid_id;\n\n // Multi-bit fetch enable used when SecureIbex == 1. When SecureIbex == 0 only use the bottom-bit\n // of fetch_enable_i. Ensure the multi-bit encoding has the bottom bit set for on and unset for\n // off so IbexMuBiOn/IbexMuBiOff can be used without needing to know the value of SecureIbex.\n `ASSERT_INIT(IbexMuBiSecureOnBottomBitSet, IbexMuBiOn[0] == 1'b1)\n `ASSERT_INIT(IbexMuBiSecureOffBottomBitClear, IbexMuBiOff[0] == 1'b0)\n\n // fetch_enable_i can be used to stop the core fetching new instructions\n if (SecureIbex) begin : g_instr_req_gated_secure\n // For secure Ibex fetch_enable_i must be a specific multi-bit pattern to enable instruction\n // fetch\n // SEC_CM: FETCH.CTRL.LC_GATED\n assign instr_req_gated = instr_req_int & (fetch_enable_i == IbexMuBiOn);\n assign instr_exec = fetch_enable_i == IbexMuBiOn;\n end else begin : g_instr_req_gated_non_secure\n // For non secure Ibex only the bottom bit of fetch enable is considered\n logic unused_fetch_enable;\n assign unused_fetch_enable = ^fetch_enable_i[$bits(ibex_mubi_t)-1:1];\n\n assign instr_req_gated = instr_req_int & fetch_enable_i[0];\n assign instr_exec = fetch_enable_i[0];\n end\n\n //////////////\n // ID stage //\n //////////////\n\n ibex_id_stage #(\n .RV32E (RV32E),\n .RV32M (RV32M),\n .RV32B (RV32B),\n .BranchTargetALU(BranchTargetALU),\n .DataIndTiming (DataIndTiming),\n .WritebackStage (WritebackStage),\n .BranchPredictor(BranchPredictor),\n .MemECC (MemECC)\n ) id_stage_i (\n .clk_i (clk_i),\n .rst_ni(rst_ni),\n\n // Processor Enable\n .ctrl_busy_o (ctrl_busy),\n .illegal_insn_o(illegal_insn_id),\n\n // from/to IF-ID pipeline register\n .instr_valid_i (instr_valid_id),\n .instr_rdata_i (instr_rdata_id),\n .instr_rdata_alu_i (instr_rdata_alu_id),\n .instr_rdata_c_i (instr_rdata_c_id),\n .instr_is_compressed_i(instr_is_compressed_id),\n .instr_bp_taken_i (instr_bp_taken_id),\n\n // Jumps and branches\n .branch_decision_i(branch_decision),\n\n // IF and ID control signals\n .instr_first_cycle_id_o(instr_first_cycle_id),\n .instr_valid_clear_o (instr_valid_clear),\n .id_in_ready_o (id_in_ready),\n .instr_exec_i (instr_exec),\n .instr_req_o (instr_req_int),\n .pc_set_o (pc_set),\n .pc_mux_o (pc_mux_id),\n .nt_branch_mispredict_o(nt_branch_mispredict),\n .nt_branch_addr_o (nt_branch_addr),\n .exc_pc_mux_o (exc_pc_mux_id),\n .exc_cause_o (exc_cause),\n .icache_inval_o (icache_inval),\n\n .instr_fetch_err_i (instr_fetch_err),\n .instr_fetch_err_plus2_i(instr_fetch_err_plus2),\n .illegal_c_insn_i (illegal_c_insn_id),\n\n .pc_id_i(pc_id),\n\n // Stalls\n .ex_valid_i (ex_valid),\n .lsu_resp_valid_i(lsu_resp_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 .imd_val_q_ex_o (imd_val_q_ex),\n .imd_val_d_ex_i (imd_val_d_ex),\n .imd_val_we_ex_i(imd_val_we_ex),\n\n .bt_a_operand_o(bt_a_operand),\n .bt_b_operand_o(bt_b_operand),\n\n .mult_en_ex_o (mult_en_ex),\n .div_en_ex_o (div_en_ex),\n .mult_sel_ex_o (mult_sel_ex),\n .div_sel_ex_o (div_sel_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 .multdiv_ready_id_o (multdiv_ready_id),\n\n // CSR ID/EX\n .csr_access_o (csr_access),\n .csr_op_o (csr_op),\n .csr_op_en_o (csr_op_en),\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_save_wb_o (csr_save_wb), // control signal to save PC\n .csr_restore_mret_id_o(csr_restore_mret_id), // restore mstatus upon MRET\n .csr_restore_dret_id_o(csr_restore_dret_id), // restore mstatus upon MRET\n .csr_save_cause_o (csr_save_cause),\n .csr_mtval_o (csr_mtval),\n .priv_mode_i (priv_mode_id),\n .csr_mstatus_tw_i (csr_mstatus_tw),\n .illegal_csr_insn_i (illegal_csr_insn_id),\n .data_ind_timing_i (data_ind_timing),\n\n // LSU\n .lsu_req_o (lsu_req), // to load store unit\n .lsu_we_o (lsu_we), // to load store unit\n .lsu_type_o (lsu_type), // to load store unit\n .lsu_sign_ext_o(lsu_sign_ext), // to load store unit\n .lsu_wdata_o (lsu_wdata), // to load store unit\n .lsu_req_done_i(lsu_req_done), // from load store unit\n\n .lsu_addr_incr_req_i(lsu_addr_incr_req),\n .lsu_addr_last_i (lsu_addr_last),\n\n .lsu_load_err_i (lsu_load_err),\n .lsu_load_resp_intg_err_i (lsu_load_resp_intg_err),\n .lsu_store_err_i (lsu_store_err),\n .lsu_store_resp_intg_err_i(lsu_store_resp_intg_err),\n\n .expecting_load_resp_o (expecting_load_resp_id),\n .expecting_store_resp_o(expecting_store_resp_id),\n\n // Interrupt Signals\n .csr_mstatus_mie_i(csr_mstatus_mie),\n .irq_pending_i (irq_pending_o),\n .irqs_i (irqs),\n .irq_nm_i (irq_nm_i),\n .nmi_mode_o (nmi_mode),\n\n // Debug Signal\n .debug_mode_o (debug_mode),\n .debug_mode_entering_o(debug_mode_entering),\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 .debug_ebreaku_i (debug_ebreaku),\n .trigger_match_i (trigger_match),\n\n // write data to commit in the register file\n .result_ex_i(result_ex),\n .csr_rdata_i(csr_rdata),\n\n .rf_raddr_a_o (rf_raddr_a),\n .rf_rdata_a_i (rf_rdata_a),\n .rf_raddr_b_o (rf_raddr_b),\n .rf_rdata_b_i (rf_rdata_b),\n .rf_ren_a_o (rf_ren_a),\n .rf_ren_b_o (rf_ren_b),\n .rf_waddr_id_o (rf_waddr_id),\n .rf_wdata_id_o (rf_wdata_id),\n .rf_we_id_o (rf_we_id),\n .rf_rd_a_wb_match_o(rf_rd_a_wb_match),\n .rf_rd_b_wb_match_o(rf_rd_b_wb_match),\n\n .rf_waddr_wb_i (rf_waddr_wb),\n .rf_wdata_fwd_wb_i(rf_wdata_fwd_wb),\n .rf_write_wb_i (rf_write_wb),\n\n .en_wb_o (en_wb),\n .instr_type_wb_o (instr_type_wb),\n .instr_perf_count_id_o (instr_perf_count_id),\n .ready_wb_i (ready_wb),\n .outstanding_load_wb_i (outstanding_load_wb),\n .outstanding_store_wb_i(outstanding_store_wb),\n\n // Performance Counters\n .perf_jump_o (perf_jump),\n .perf_branch_o (perf_branch),\n .perf_tbranch_o (perf_tbranch),\n .perf_dside_wait_o(perf_dside_wait),\n .perf_mul_wait_o (perf_mul_wait),\n .perf_div_wait_o (perf_div_wait),\n .instr_id_done_o (instr_id_done)\n );\n\n // for RVFI only\n assign unused_illegal_insn_id = illegal_insn_id;\n\n ibex_ex_block #(\n .RV32M (RV32M),\n .RV32B (RV32B),\n .BranchTargetALU(BranchTargetALU)\n ) ex_block_i (\n .clk_i (clk_i),\n .rst_ni(rst_ni),\n\n // ALU signal from ID stage\n .alu_operator_i (alu_operator_ex),\n .alu_operand_a_i (alu_operand_a_ex),\n .alu_operand_b_i (alu_operand_b_ex),\n .alu_instr_first_cycle_i(instr_first_cycle_id),\n\n // Branch target ALU signal from ID stage\n .bt_a_operand_i(bt_a_operand),\n .bt_b_operand_i(bt_b_operand),\n\n // Multipler/Divider signal from ID stage\n .multdiv_operator_i (multdiv_operator_ex),\n .mult_en_i (mult_en_ex),\n .div_en_i (div_en_ex),\n .mult_sel_i (mult_sel_ex),\n .div_sel_i (div_sel_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 .multdiv_ready_id_i (multdiv_ready_id),\n .data_ind_timing_i (data_ind_timing),\n\n // Intermediate value register\n .imd_val_we_o(imd_val_we_ex),\n .imd_val_d_o (imd_val_d_ex),\n .imd_val_q_i (imd_val_q_ex),\n\n // Outputs\n .alu_adder_result_ex_o(alu_adder_result_ex), // to LSU\n .result_ex_o (result_ex), // to ID\n\n .branch_target_o (branch_target_ex), // to IF\n .branch_decision_o(branch_decision), // to ID\n\n .ex_valid_o(ex_valid)\n );\n\n /////////////////////\n // Load/store unit //\n /////////////////////\n\n assign data_req_o = data_req_out & ~pmp_req_err[PMP_D];\n assign lsu_resp_err = lsu_load_err | lsu_store_err;\n\n ibex_load_store_unit #(\n .MemECC(MemECC),\n .MemDataWidth(MemDataWidth)\n ) load_store_unit_i (\n .clk_i (clk_i),\n .rst_ni(rst_ni),\n\n // data interface\n .data_req_o (data_req_out),\n .data_gnt_i (data_gnt_i),\n .data_rvalid_i (data_rvalid_i),\n .data_bus_err_i(data_err_i),\n .data_pmp_err_i(pmp_req_err[PMP_D]),\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 // signals to/from ID/EX stage\n .lsu_we_i (lsu_we),\n .lsu_type_i (lsu_type),\n .lsu_wdata_i (lsu_wdata),\n .lsu_sign_ext_i(lsu_sign_ext),\n\n .lsu_rdata_o (rf_wdata_lsu),\n .lsu_rdata_valid_o(lsu_rdata_valid),\n .lsu_req_i (lsu_req),\n .lsu_req_done_o (lsu_req_done),\n\n .adder_result_ex_i(alu_adder_result_ex),\n\n .addr_incr_req_o(lsu_addr_incr_req),\n .addr_last_o (lsu_addr_last),\n\n\n .lsu_resp_valid_o(lsu_resp_valid),\n\n // exception signals\n .load_err_o (lsu_load_err_raw),\n .load_resp_intg_err_o (lsu_load_resp_intg_err),\n .store_err_o (lsu_store_err_raw),\n .store_resp_intg_err_o(lsu_store_resp_intg_err),\n\n .busy_o(lsu_busy),\n\n .perf_load_o (perf_load),\n .perf_store_o(perf_store)\n );\n\n ibex_wb_stage #(\n .ResetAll (ResetAll),\n .WritebackStage (WritebackStage),\n .DummyInstructions(DummyInstructions)\n ) wb_stage_i (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .en_wb_i (en_wb),\n .instr_type_wb_i (instr_type_wb),\n .pc_id_i (pc_id),\n .instr_is_compressed_id_i(instr_is_compressed_id),\n .instr_perf_count_id_i (instr_perf_count_id),\n\n .ready_wb_o (ready_wb),\n .rf_write_wb_o (rf_write_wb),\n .outstanding_load_wb_o (outstanding_load_wb),\n .outstanding_store_wb_o (outstanding_store_wb),\n .pc_wb_o (pc_wb),\n .perf_instr_ret_wb_o (perf_instr_ret_wb),\n .perf_instr_ret_compressed_wb_o (perf_instr_ret_compressed_wb),\n .perf_instr_ret_wb_spec_o (perf_instr_ret_wb_spec),\n .perf_instr_ret_compressed_wb_spec_o(perf_instr_ret_compressed_wb_spec),\n\n .rf_waddr_id_i(rf_waddr_id),\n .rf_wdata_id_i(rf_wdata_id),\n .rf_we_id_i (rf_we_id),\n\n .dummy_instr_id_i(dummy_instr_id),\n\n .rf_wdata_lsu_i(rf_wdata_lsu),\n .rf_we_lsu_i (rf_we_lsu),\n\n .rf_wdata_fwd_wb_o(rf_wdata_fwd_wb),\n\n .rf_waddr_wb_o(rf_waddr_wb),\n .rf_wdata_wb_o(rf_wdata_wb),\n .rf_we_wb_o (rf_we_wb),\n\n .dummy_instr_wb_o(dummy_instr_wb),\n\n .lsu_resp_valid_i(lsu_resp_valid),\n .lsu_resp_err_i (lsu_resp_err),\n\n .instr_done_wb_o(instr_done_wb)\n );\n\n if (SecureIbex) begin : g_check_mem_response\n // For secure configurations only process load/store responses if we're expecting them to guard\n // against false responses being injected on to the bus\n assign lsu_load_err = lsu_load_err_raw & (outstanding_load_wb | expecting_load_resp_id);\n assign lsu_store_err = lsu_store_err_raw & (outstanding_store_wb | expecting_store_resp_id);\n assign rf_we_lsu = lsu_rdata_valid & (outstanding_load_wb | expecting_load_resp_id);\n end else begin : g_no_check_mem_response\n // For non-secure configurations trust the bus protocol is being followed and we'll only ever\n // see a response if we have an outstanding request.\n assign lsu_load_err = lsu_load_err_raw;\n assign lsu_store_err = lsu_store_err_raw;\n assign rf_we_lsu = lsu_rdata_valid;\n\n // expected_load_resp_id/expected_store_resp_id signals are only used to guard against false\n // responses so they are unused in non-secure configurations\n logic unused_expecting_load_resp_id;\n logic unused_expecting_store_resp_id;\n\n assign unused_expecting_load_resp_id = expecting_load_resp_id;\n assign unused_expecting_store_resp_id = expecting_store_resp_id;\n end\n\n /////////////////////////////\n // Register file interface //\n /////////////////////////////\n\n assign dummy_instr_id_o = dummy_instr_id;\n assign dummy_instr_wb_o = dummy_instr_wb;\n assign rf_raddr_a_o = rf_raddr_a;\n assign rf_waddr_wb_o = rf_waddr_wb;\n assign rf_we_wb_o = rf_we_wb;\n assign rf_raddr_b_o = rf_raddr_b;\n\n if (RegFileECC) begin : gen_regfile_ecc\n\n // SEC_CM: DATA_REG_SW.INTEGRITY\n logic [1:0] rf_ecc_err_a, rf_ecc_err_b;\n logic rf_ecc_err_a_id, rf_ecc_err_b_id;\n\n // ECC checkbit generation for regiter file wdata\n prim_secded_inv_39_32_enc regfile_ecc_enc (\n .data_i(rf_wdata_wb),\n .data_o(rf_wdata_wb_ecc_o)\n );\n\n // ECC checking on register file rdata\n prim_secded_inv_39_32_dec regfile_ecc_dec_a (\n .data_i (rf_rdata_a_ecc_i),\n .data_o (),\n .syndrome_o(),\n .err_o (rf_ecc_err_a)\n );\n prim_secded_inv_39_32_dec regfile_ecc_dec_b (\n .data_i (rf_rdata_b_ecc_i),\n .data_o (),\n .syndrome_o(),\n .err_o (rf_ecc_err_b)\n );\n\n // Assign read outputs - no error correction, just trigger an alert\n assign rf_rdata_a = rf_rdata_a_ecc_i[31:0];\n assign rf_rdata_b = rf_rdata_b_ecc_i[31:0];\n\n // Calculate errors - qualify with WB forwarding to avoid xprop into the alert signal\n assign rf_ecc_err_a_id = |rf_ecc_err_a & rf_ren_a & ~(rf_rd_a_wb_match & rf_write_wb);\n assign rf_ecc_err_b_id = |rf_ecc_err_b & rf_ren_b & ~(rf_rd_b_wb_match & rf_write_wb);\n\n // Combined error\n assign rf_ecc_err_comb = instr_valid_id & (rf_ecc_err_a_id | rf_ecc_err_b_id);\n\n end else begin : gen_no_regfile_ecc\n logic unused_rf_ren_a, unused_rf_ren_b;\n logic unused_rf_rd_a_wb_match, unused_rf_rd_b_wb_match;\n\n assign unused_rf_ren_a = rf_ren_a;\n assign unused_rf_ren_b = rf_ren_b;\n assign unused_rf_rd_a_wb_match = rf_rd_a_wb_match;\n assign unused_rf_rd_b_wb_match = rf_rd_b_wb_match;\n assign rf_wdata_wb_ecc_o = rf_wdata_wb;\n assign rf_rdata_a = rf_rdata_a_ecc_i;\n assign rf_rdata_b = rf_rdata_b_ecc_i;\n assign rf_ecc_err_comb = 1'b0;\n end\n\n ///////////////////////\n // Crash dump output //\n ///////////////////////\n\n logic [31:0] crash_dump_mtval;\n assign crash_dump_o.current_pc = pc_id;\n assign crash_dump_o.next_pc = pc_if;\n assign crash_dump_o.last_data_addr = lsu_addr_last;\n assign crash_dump_o.exception_pc = csr_mepc;\n assign crash_dump_o.exception_addr = crash_dump_mtval;\n\n ///////////////////\n // Alert outputs //\n ///////////////////\n\n // Minor alert - core is in a recoverable state\n assign alert_minor_o = icache_ecc_error;\n\n // Major internal alert - core is unrecoverable\n assign alert_major_internal_o = rf_ecc_err_comb | pc_mismatch_alert | csr_shadow_err;\n // Major bus alert\n assign alert_major_bus_o = lsu_load_resp_intg_err | lsu_store_resp_intg_err | instr_intg_err;\n\n // Explict INC_ASSERT block to avoid unused signal lint warnings were asserts are not included\n `ifdef INC_ASSERT\n // Signals used for assertions only\n logic outstanding_load_resp;\n logic outstanding_store_resp;\n\n logic outstanding_load_id;\n logic outstanding_store_id;\n\n assign outstanding_load_id = id_stage_i.instr_executing & id_stage_i.lsu_req_dec &\n ~id_stage_i.lsu_we;\n assign outstanding_store_id = id_stage_i.instr_executing & id_stage_i.lsu_req_dec &\n id_stage_i.lsu_we;\n\n if (WritebackStage) begin : gen_wb_stage\n // When the writeback stage is present a load/store could be in ID or WB. A Load/store in ID can\n // see a response before it moves to WB when it is unaligned otherwise we should only see\n // a response when load/store is in WB.\n assign outstanding_load_resp = outstanding_load_wb |\n (outstanding_load_id & load_store_unit_i.split_misaligned_access);\n\n assign outstanding_store_resp = outstanding_store_wb |\n (outstanding_store_id & load_store_unit_i.split_misaligned_access);\n\n // When writing back the result of a load, the load must have made it to writeback\n `ASSERT(NoMemRFWriteWithoutPendingLoad, rf_we_lsu |-> outstanding_load_wb, clk_i, !rst_ni)\n end else begin : gen_no_wb_stage\n // Without writeback stage only look into whether load or store is in ID to determine if\n // a response is expected.\n assign outstanding_load_resp = outstanding_load_id;\n assign outstanding_store_resp = outstanding_store_id;\n\n `ASSERT(NoMemRFWriteWithoutPendingLoad, rf_we_lsu |-> outstanding_load_id, clk_i, !rst_ni)\n end\n\n `ASSERT(NoMemResponseWithoutPendingAccess,\n data_rvalid_i |-> outstanding_load_resp | outstanding_store_resp, clk_i, !rst_ni)\n\n\n // Keep track of the PC last seen in the ID stage when fetch is disabled\n logic [31:0] pc_at_fetch_disable;\n ibex_mubi_t last_fetch_enable;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pc_at_fetch_disable <= '0;\n last_fetch_enable <= '0;\n end else begin\n last_fetch_enable <= fetch_enable_i;\n\n if ((fetch_enable_i != IbexMuBiOn) && (last_fetch_enable == IbexMuBiOn)) begin\n pc_at_fetch_disable <= pc_id;\n end\n end\n end\n\n // A 1-bit encoding of fetch_enable_i to avoid polluting the NoExecWhenFetchEnableNotOn assertion\n // with notes about SecureIbex and mubi values.\n logic fetch_enable_raw;\n assign fetch_enable_raw = SecureIbex ? (fetch_enable_i == IbexMuBiOn) : fetch_enable_i[0];\n\n // When fetch is disabled, no instructions should be executed. Once fetch is disabled either the\n // ID/EX stage is not valid or the PC of the ID/EX stage must remain as it was at disable. The\n // ID/EX valid should not ressert once it has been cleared.\n `ASSERT(NoExecWhenFetchEnableNotOn,\n !fetch_enable_raw |=>\n (~instr_valid_id || (pc_id == pc_at_fetch_disable)) && ~$rose(instr_valid_id))\n\n `endif // INC_ASSERT\n\n ////////////////////////\n // RF (Register File) //\n ////////////////////////\n`ifdef RVFI\n`endif\n\n\n /////////////////////////////////////////\n // CSRs (Control and Status Registers) //\n /////////////////////////////////////////\n\n assign csr_wdata = alu_operand_a_ex;\n assign csr_addr = csr_num_e'(csr_access ? alu_operand_b_ex[11:0] : 12'b0);\n\n ibex_cs_registers #(\n .DbgTriggerEn (DbgTriggerEn),\n .DbgHwBreakNum (DbgHwBreakNum),\n .DataIndTiming (DataIndTiming),\n .DummyInstructions(DummyInstructions),\n .ShadowCSR (ShadowCSR),\n .ICache (ICache),\n .MHPMCounterNum (MHPMCounterNum),\n .MHPMCounterWidth (MHPMCounterWidth),\n .PMPEnable (PMPEnable),\n .PMPGranularity (PMPGranularity),\n .PMPNumRegions (PMPNumRegions),\n .PMPRstCfg (PMPRstCfg),\n .PMPRstAddr (PMPRstAddr),\n .PMPRstMsecCfg (PMPRstMsecCfg),\n .RV32E (RV32E),\n .RV32M (RV32M),\n .RV32B (RV32B)\n ) cs_registers_i (\n .clk_i (clk_i),\n .rst_ni(rst_ni),\n\n // Hart ID from outside\n .hart_id_i (hart_id_i),\n .priv_mode_id_o (priv_mode_id),\n .priv_mode_lsu_o(priv_mode_lsu),\n\n // mtvec\n .csr_mtvec_o (csr_mtvec),\n .csr_mtvec_init_i(csr_mtvec_init),\n .boot_addr_i (boot_addr_i),\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_op_en_i (csr_op_en),\n .csr_rdata_o (csr_rdata),\n\n // Interrupt related control signals\n .irq_software_i (irq_software_i),\n .irq_timer_i (irq_timer_i),\n .irq_external_i (irq_external_i),\n .irq_fast_i (irq_fast_i),\n .nmi_mode_i (nmi_mode),\n .irq_pending_o (irq_pending_o),\n .irqs_o (irqs),\n .csr_mstatus_mie_o(csr_mstatus_mie),\n .csr_mstatus_tw_o (csr_mstatus_tw),\n .csr_mepc_o (csr_mepc),\n .csr_mtval_o (crash_dump_mtval),\n\n // PMP\n .csr_pmp_cfg_o (csr_pmp_cfg),\n .csr_pmp_addr_o (csr_pmp_addr),\n .csr_pmp_mseccfg_o(csr_pmp_mseccfg),\n\n // debug\n .csr_depc_o (csr_depc),\n .debug_mode_i (debug_mode),\n .debug_mode_entering_i(debug_mode_entering),\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 .debug_ebreaku_o (debug_ebreaku),\n .trigger_match_o (trigger_match),\n\n .pc_if_i(pc_if),\n .pc_id_i(pc_id),\n .pc_wb_i(pc_wb),\n\n .data_ind_timing_o (data_ind_timing),\n .dummy_instr_en_o (dummy_instr_en),\n .dummy_instr_mask_o (dummy_instr_mask),\n .dummy_instr_seed_en_o(dummy_instr_seed_en),\n .dummy_instr_seed_o (dummy_instr_seed),\n .icache_enable_o (icache_enable),\n .csr_shadow_err_o (csr_shadow_err),\n .ic_scr_key_valid_i (ic_scr_key_valid_i),\n\n .csr_save_if_i (csr_save_if),\n .csr_save_id_i (csr_save_id),\n .csr_save_wb_i (csr_save_wb),\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_mcause_i (exc_cause),\n .csr_mtval_i (csr_mtval),\n .illegal_csr_insn_o(illegal_csr_insn_id),\n\n .double_fault_seen_o,\n\n // performance counter related signals\n .instr_ret_i (perf_instr_ret_wb),\n .instr_ret_compressed_i (perf_instr_ret_compressed_wb),\n .instr_ret_spec_i (perf_instr_ret_wb_spec),\n .instr_ret_compressed_spec_i(perf_instr_ret_compressed_wb_spec),\n .iside_wait_i (perf_iside_wait),\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 .dside_wait_i (perf_dside_wait),\n .mul_wait_i (perf_mul_wait),\n .div_wait_i (perf_div_wait)\n );\n\n // These assertions are in top-level as instr_valid_id required as the enable term\n `ASSERT(IbexCsrOpValid, instr_valid_id |-> csr_op inside {\n CSR_OP_READ,\n CSR_OP_WRITE,\n CSR_OP_SET,\n CSR_OP_CLEAR\n })\n `ASSERT_KNOWN_IF(IbexCsrWdataIntKnown, cs_registers_i.csr_wdata_int, csr_op_en)\n\n if (PMPEnable) begin : g_pmp\n logic [31:0] pc_if_inc;\n logic [33:0] pmp_req_addr [PMPNumChan];\n pmp_req_e pmp_req_type [PMPNumChan];\n priv_lvl_e pmp_priv_lvl [PMPNumChan];\n\n assign pc_if_inc = pc_if + 32'd2;\n assign pmp_req_addr[PMP_I] = {2'b00, pc_if};\n assign pmp_req_type[PMP_I] = PMP_ACC_EXEC;\n assign pmp_priv_lvl[PMP_I] = priv_mode_id;\n assign pmp_req_addr[PMP_I2] = {2'b00, pc_if_inc};\n assign pmp_req_type[PMP_I2] = PMP_ACC_EXEC;\n assign pmp_priv_lvl[PMP_I2] = priv_mode_id;\n assign pmp_req_addr[PMP_D] = {2'b00, data_addr_o[31:0]};\n assign pmp_req_type[PMP_D] = data_we_o ? PMP_ACC_WRITE : PMP_ACC_READ;\n assign pmp_priv_lvl[PMP_D] = priv_mode_lsu;\n\n ibex_pmp #(\n .DmBaseAddr (DmBaseAddr),\n .DmAddrMask (DmAddrMask),\n .PMPGranularity(PMPGranularity),\n .PMPNumChan (PMPNumChan),\n .PMPNumRegions (PMPNumRegions)\n ) pmp_i (\n // Interface to CSRs\n .csr_pmp_cfg_i (csr_pmp_cfg),\n .csr_pmp_addr_i (csr_pmp_addr),\n .csr_pmp_mseccfg_i(csr_pmp_mseccfg),\n .debug_mode_i (debug_mode),\n .priv_mode_i (pmp_priv_lvl),\n // Access checking channels\n .pmp_req_addr_i (pmp_req_addr),\n .pmp_req_type_i (pmp_req_type),\n .pmp_req_err_o (pmp_req_err)\n );\n end else begin : g_no_pmp\n // Unused signal tieoff\n priv_lvl_e unused_priv_lvl_ls;\n logic [33:0] unused_csr_pmp_addr [PMPNumRegions];\n pmp_cfg_t unused_csr_pmp_cfg [PMPNumRegions];\n pmp_mseccfg_t unused_csr_pmp_mseccfg;\n assign unused_priv_lvl_ls = priv_mode_lsu;\n assign unused_csr_pmp_addr = csr_pmp_addr;\n assign unused_csr_pmp_cfg = csr_pmp_cfg;\n assign unused_csr_pmp_mseccfg = csr_pmp_mseccfg;\n\n // Output tieoff\n assign pmp_req_err[PMP_I] = 1'b0;\n assign pmp_req_err[PMP_I2] = 1'b0;\n assign pmp_req_err[PMP_D] = 1'b0;\n end\n\n`ifdef RVFI\n // When writeback stage is present RVFI information is emitted when instruction is finished in\n // third stage but some information must be captured whilst the instruction is in the second\n // stage. Without writeback stage RVFI information is all emitted when instruction retires in\n // second stage. RVFI outputs are all straight from flops. So 2 stage pipeline requires a single\n // set of flops (instr_info => RVFI_out), 3 stage pipeline requires two sets (instr_info => wb\n // => RVFI_out)\n localparam int RVFI_STAGES = WritebackStage ? 2 : 1;\n\n logic rvfi_stage_valid [RVFI_STAGES];\n logic [63:0] rvfi_stage_order [RVFI_STAGES];\n logic [31:0] rvfi_stage_insn [RVFI_STAGES];\n logic rvfi_stage_trap [RVFI_STAGES];\n logic rvfi_stage_halt [RVFI_STAGES];\n logic rvfi_stage_intr [RVFI_STAGES];\n logic [ 1:0] rvfi_stage_mode [RVFI_STAGES];\n logic [ 1:0] rvfi_stage_ixl [RVFI_STAGES];\n logic [ 4:0] rvfi_stage_rs1_addr [RVFI_STAGES];\n logic [ 4:0] rvfi_stage_rs2_addr [RVFI_STAGES];\n logic [ 4:0] rvfi_stage_rs3_addr [RVFI_STAGES];\n logic [31:0] rvfi_stage_rs1_rdata [RVFI_STAGES];\n logic [31:0] rvfi_stage_rs2_rdata [RVFI_STAGES];\n logic [31:0] rvfi_stage_rs3_rdata [RVFI_STAGES];\n logic [ 4:0] rvfi_stage_rd_addr [RVFI_STAGES];\n logic [31:0] rvfi_stage_rd_wdata [RVFI_STAGES];\n logic [31:0] rvfi_stage_pc_rdata [RVFI_STAGES];\n logic [31:0] rvfi_stage_pc_wdata [RVFI_STAGES];\n logic [31:0] rvfi_stage_mem_addr [RVFI_STAGES];\n logic [ 3:0] rvfi_stage_mem_rmask [RVFI_STAGES];\n logic [ 3:0] rvfi_stage_mem_wmask [RVFI_STAGES];\n logic [31:0] rvfi_stage_mem_rdata [RVFI_STAGES];\n logic [31:0] rvfi_stage_mem_wdata [RVFI_STAGES];\n\n logic rvfi_instr_new_wb;\n logic rvfi_intr_d;\n logic rvfi_intr_q;\n logic rvfi_set_trap_pc_d;\n logic rvfi_set_trap_pc_q;\n logic [31:0] rvfi_insn_id;\n logic [4:0] rvfi_rs1_addr_d;\n logic [4:0] rvfi_rs1_addr_q;\n logic [4:0] rvfi_rs2_addr_d;\n logic [4:0] rvfi_rs2_addr_q;\n logic [4:0] rvfi_rs3_addr_d;\n logic [31:0] rvfi_rs1_data_d;\n logic [31:0] rvfi_rs1_data_q;\n logic [31:0] rvfi_rs2_data_d;\n logic [31:0] rvfi_rs2_data_q;\n logic [31:0] rvfi_rs3_data_d;\n logic [4:0] rvfi_rd_addr_wb;\n logic [4:0] rvfi_rd_addr_q;\n logic [4:0] rvfi_rd_addr_d;\n logic [31:0] rvfi_rd_wdata_wb;\n logic [31:0] rvfi_rd_wdata_d;\n logic [31:0] rvfi_rd_wdata_q;\n logic rvfi_rd_we_wb;\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 logic rvfi_trap_id;\n logic rvfi_trap_wb;\n logic rvfi_irq_valid;\n logic [63:0] rvfi_stage_order_d;\n logic rvfi_id_done;\n logic rvfi_wb_done;\n\n logic new_debug_req;\n logic new_nmi;\n logic new_nmi_int;\n logic new_irq;\n ibex_pkg::irqs_t captured_mip;\n logic captured_nmi;\n logic captured_nmi_int;\n logic captured_debug_req;\n logic captured_valid;\n\n // RVFI extension for co-simulation support\n // debug_req and MIP captured at IF -> ID transition so one extra stage\n ibex_pkg::irqs_t rvfi_ext_stage_pre_mip [RVFI_STAGES+1];\n ibex_pkg::irqs_t rvfi_ext_stage_post_mip [RVFI_STAGES];\n logic rvfi_ext_stage_nmi [RVFI_STAGES+1];\n logic rvfi_ext_stage_nmi_int [RVFI_STAGES+1];\n logic rvfi_ext_stage_debug_req [RVFI_STAGES+1];\n logic rvfi_ext_stage_debug_mode [RVFI_STAGES];\n logic [63:0] rvfi_ext_stage_mcycle [RVFI_STAGES];\n logic [31:0] rvfi_ext_stage_mhpmcounters [RVFI_STAGES][10];\n logic [31:0] rvfi_ext_stage_mhpmcountersh [RVFI_STAGES][10];\n logic rvfi_ext_stage_ic_scr_key_valid [RVFI_STAGES];\n logic rvfi_ext_stage_irq_valid [RVFI_STAGES+1];\n\n\n logic rvfi_stage_valid_d [RVFI_STAGES];\n\n assign rvfi_valid = rvfi_stage_valid [RVFI_STAGES-1];\n assign rvfi_order = rvfi_stage_order [RVFI_STAGES-1];\n assign rvfi_insn = rvfi_stage_insn [RVFI_STAGES-1];\n assign rvfi_trap = rvfi_stage_trap [RVFI_STAGES-1];\n assign rvfi_halt = rvfi_stage_halt [RVFI_STAGES-1];\n assign rvfi_intr = rvfi_stage_intr [RVFI_STAGES-1];\n assign rvfi_mode = rvfi_stage_mode [RVFI_STAGES-1];\n assign rvfi_ixl = rvfi_stage_ixl [RVFI_STAGES-1];\n assign rvfi_rs1_addr = rvfi_stage_rs1_addr [RVFI_STAGES-1];\n assign rvfi_rs2_addr = rvfi_stage_rs2_addr [RVFI_STAGES-1];\n assign rvfi_rs3_addr = rvfi_stage_rs3_addr [RVFI_STAGES-1];\n assign rvfi_rs1_rdata = rvfi_stage_rs1_rdata[RVFI_STAGES-1];\n assign rvfi_rs2_rdata = rvfi_stage_rs2_rdata[RVFI_STAGES-1];\n assign rvfi_rs3_rdata = rvfi_stage_rs3_rdata[RVFI_STAGES-1];\n assign rvfi_rd_addr = rvfi_stage_rd_addr [RVFI_STAGES-1];\n assign rvfi_rd_wdata = rvfi_stage_rd_wdata [RVFI_STAGES-1];\n assign rvfi_pc_rdata = rvfi_stage_pc_rdata [RVFI_STAGES-1];\n assign rvfi_pc_wdata = rvfi_stage_pc_wdata [RVFI_STAGES-1];\n assign rvfi_mem_addr = rvfi_stage_mem_addr [RVFI_STAGES-1];\n assign rvfi_mem_rmask = rvfi_stage_mem_rmask[RVFI_STAGES-1];\n assign rvfi_mem_wmask = rvfi_stage_mem_wmask[RVFI_STAGES-1];\n assign rvfi_mem_rdata = rvfi_stage_mem_rdata[RVFI_STAGES-1];\n assign rvfi_mem_wdata = rvfi_stage_mem_wdata[RVFI_STAGES-1];\n\n assign rvfi_rd_addr_wb = rf_waddr_wb;\n assign rvfi_rd_wdata_wb = rf_we_wb ? rf_wdata_wb : rf_wdata_lsu;\n assign rvfi_rd_we_wb = rf_we_wb | rf_we_lsu;\n\n always_comb begin\n // Use always_comb instead of continuous assign so first assign can set 0 as default everywhere\n // that is overridden by more specific settings.\n rvfi_ext_pre_mip = '0;\n rvfi_ext_pre_mip[CSR_MSIX_BIT] = rvfi_ext_stage_pre_mip[RVFI_STAGES].irq_software;\n rvfi_ext_pre_mip[CSR_MTIX_BIT] = rvfi_ext_stage_pre_mip[RVFI_STAGES].irq_timer;\n rvfi_ext_pre_mip[CSR_MEIX_BIT] = rvfi_ext_stage_pre_mip[RVFI_STAGES].irq_external;\n\n rvfi_ext_pre_mip[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] =\n rvfi_ext_stage_pre_mip[RVFI_STAGES].irq_fast;\n\n rvfi_ext_post_mip = '0;\n rvfi_ext_post_mip[CSR_MSIX_BIT] = rvfi_ext_stage_post_mip[RVFI_STAGES-1].irq_software;\n rvfi_ext_post_mip[CSR_MTIX_BIT] = rvfi_ext_stage_post_mip[RVFI_STAGES-1].irq_timer;\n rvfi_ext_post_mip[CSR_MEIX_BIT] = rvfi_ext_stage_post_mip[RVFI_STAGES-1].irq_external;\n\n rvfi_ext_post_mip[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] =\n rvfi_ext_stage_post_mip[RVFI_STAGES-1].irq_fast;\n end\n\n assign rvfi_ext_nmi = rvfi_ext_stage_nmi [RVFI_STAGES];\n assign rvfi_ext_nmi_int = rvfi_ext_stage_nmi_int [RVFI_STAGES];\n assign rvfi_ext_debug_req = rvfi_ext_stage_debug_req [RVFI_STAGES];\n assign rvfi_ext_debug_mode = rvfi_ext_stage_debug_mode [RVFI_STAGES-1];\n assign rvfi_ext_mcycle = rvfi_ext_stage_mcycle [RVFI_STAGES-1];\n assign rvfi_ext_mhpmcounters = rvfi_ext_stage_mhpmcounters [RVFI_STAGES-1];\n assign rvfi_ext_mhpmcountersh = rvfi_ext_stage_mhpmcountersh [RVFI_STAGES-1];\n assign rvfi_ext_ic_scr_key_valid = rvfi_ext_stage_ic_scr_key_valid [RVFI_STAGES-1];\n assign rvfi_ext_irq_valid = rvfi_ext_stage_irq_valid [RVFI_STAGES];\n\n // When an instruction takes a trap the `rvfi_trap` signal will be set. Instructions that take\n // traps flush the pipeline so ordinarily wouldn't be seen to be retire. The RVFI tracking\n // pipeline is kept going for flushed instructions that trapped so they are still visible on the\n // RVFI interface.\n\n // Factor in exceptions taken in ID so RVFI tracking picks up flushed instructions that took\n // a trap\n assign rvfi_id_done = instr_id_done | (id_stage_i.controller_i.rvfi_flush_next &\n id_stage_i.controller_i.id_exception_o);\n\n if (WritebackStage) begin : gen_rvfi_wb_stage\n logic unused_instr_new_id;\n\n assign unused_instr_new_id = instr_new_id;\n\n // With writeback stage first RVFI stage buffers instruction information captured in ID/EX\n // awaiting instruction retirement and RF Write data/Mem read data whilst instruction is in WB\n // So first stage becomes valid when instruction leaves ID/EX stage and remains valid until\n // instruction leaves WB\n assign rvfi_stage_valid_d[0] = (rvfi_id_done & ~dummy_instr_id) |\n (rvfi_stage_valid[0] & ~rvfi_wb_done);\n // Second stage is output stage so simple valid cycle after instruction leaves WB (and so has\n // retired)\n assign rvfi_stage_valid_d[1] = rvfi_wb_done;\n\n // Signal new instruction in WB cycle after instruction leaves ID/EX (to enter WB)\n logic rvfi_instr_new_wb_q;\n\n // Signal new instruction in WB either when one has just entered or when a trap is progressing\n // through the tracking pipeline\n assign rvfi_instr_new_wb = rvfi_instr_new_wb_q | (rvfi_stage_valid[0] & rvfi_stage_trap[0]);\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_instr_new_wb_q <= 0;\n end else begin\n rvfi_instr_new_wb_q <= rvfi_id_done;\n end\n end\n\n assign rvfi_trap_id = id_stage_i.controller_i.id_exception_o &\n ~(id_stage_i.ebrk_insn & id_stage_i.controller_i.ebreak_into_debug);\n\n assign rvfi_trap_wb = id_stage_i.controller_i.exc_req_lsu;\n // WB is instantly done in the tracking pipeline when a trap is progress through the pipeline\n assign rvfi_wb_done = rvfi_stage_valid[0] & (instr_done_wb | rvfi_stage_trap[0]);\n end else begin : gen_rvfi_no_wb_stage\n // Without writeback stage first RVFI stage is output stage so simply valid the cycle after\n // instruction leaves ID/EX (and so has retired)\n assign rvfi_stage_valid_d[0] = rvfi_id_done & ~dummy_instr_id;\n // Without writeback stage signal new instr_new_wb when instruction enters ID/EX to correctly\n // setup register write signals\n assign rvfi_instr_new_wb = instr_new_id;\n assign rvfi_trap_id =\n (id_stage_i.controller_i.exc_req_d | id_stage_i.controller_i.exc_req_lsu) &\n ~(id_stage_i.ebrk_insn & id_stage_i.controller_i.ebreak_into_debug);\n assign rvfi_trap_wb = 1'b0;\n assign rvfi_wb_done = instr_done_wb;\n end\n\n assign rvfi_stage_order_d = dummy_instr_id ? rvfi_stage_order[0] : rvfi_stage_order[0] + 64'd1;\n\n // For interrupts and debug Ibex will take the relevant trap as soon as whatever instruction in ID\n // finishes or immediately if the ID stage is empty. The rvfi_ext interface provides the DV\n // environment with information about the irq/debug_req/nmi state that applies to a particular\n // instruction.\n //\n // When a irq/debug_req/nmi appears the ID stage will finish whatever instruction it is currently\n // executing (if any) then take the trap the cycle after that instruction leaves the ID stage. The\n // trap taken depends upon the state of irq/debug_req/nmi on that cycle. In the cycles following\n // that before the first instruction of the trap handler enters the ID stage the state of\n // irq/debug_req/nmi could change but this has no effect on the trap handler (e.g. a higher\n // priority interrupt might appear but this wouldn't stop the lower priority interrupt trap\n // handler executing first as it's already being fetched). To provide the DV environment with the\n // correct information for it to verify execution we need to capture the irq/debug_req/nmi state\n // the cycle the trap decision is made. Which the captured_X signals below do.\n //\n // The new_X signals take the raw irq/debug_req/nmi inputs and factor in the enable terms required\n // to determine if a trap will actually happen.\n //\n // These signals and the comment above are referred to in the documentation (cosim.rst). If\n // altering the names or meanings of these signals or this comment please adjust the documentation\n // appropriately.\n assign new_debug_req = (debug_req_i & ~debug_mode);\n assign new_nmi = irq_nm_i & ~nmi_mode & ~debug_mode;\n assign new_nmi_int = id_stage_i.controller_i.irq_nm_int & ~nmi_mode & ~debug_mode;\n assign new_irq = irq_pending_o & (csr_mstatus_mie || (priv_mode_id == PRIV_LVL_U)) & ~nmi_mode &\n ~debug_mode;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n captured_valid <= 1'b0;\n captured_mip <= '0;\n captured_nmi <= 1'b0;\n captured_nmi_int <= 1'b0;\n captured_debug_req <= 1'b0;\n rvfi_irq_valid <= 1'b0;\n end else begin\n // Capture when ID stage has emptied out and something occurs that will cause a trap and we\n // haven't yet captured\n //\n // When we already captured a trap, and there is upcoming nmi interrupt or\n // a debug request then recapture as nmi or debug request are supposed to\n // be serviced.\n if (~instr_valid_id & (new_debug_req | new_irq | new_nmi | new_nmi_int) &\n ((~captured_valid) |\n (new_debug_req & ~captured_debug_req) |\n (new_nmi & ~captured_nmi & ~captured_debug_req))) begin\n captured_valid <= 1'b1;\n captured_nmi <= irq_nm_i;\n captured_nmi_int <= id_stage_i.controller_i.irq_nm_int;\n captured_mip <= cs_registers_i.mip;\n captured_debug_req <= debug_req_i;\n end\n\n // When the pipeline has emptied in preparation for handling a new interrupt send\n // a notification up the RVFI pipeline. This is used by the cosim to deal with cases where an\n // interrupt occurs before another interrupt or debug request but both occur before the first\n // instruction of the handler is executed and retired (where the cosim will see all the\n // interrupts and debug requests at once with no way to determine which occurred first).\n if (~instr_valid_id & ~new_debug_req & (new_irq | new_nmi | new_nmi_int) & ready_wb &\n ~captured_valid) begin\n rvfi_irq_valid <= 1'b1;\n end else begin\n rvfi_irq_valid <= 1'b0;\n end\n\n // Capture cleared out as soon as a new instruction appears in ID\n if (if_stage_i.instr_valid_id_d) begin\n captured_valid <= 1'b0;\n end\n end\n end\n\n // Pass the captured irq/debug_req/nmi state to the rvfi_ext interface tracking pipeline.\n //\n // To correctly capture we need to factor in various enable terms, should there be a fault in this\n // logic we won't tell the DV environment about a trap that should have been taken. So if there's\n // no valid capture we grab the raw values of the irq/debug_req/nmi inputs whatever they are and\n // the DV environment will see if a trap should have been taken but wasn't.\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_ext_stage_pre_mip[0] <= '0;\n rvfi_ext_stage_nmi[0] <= '0;\n rvfi_ext_stage_nmi_int[0] <= '0;\n rvfi_ext_stage_debug_req[0] <= '0;\n end else if ((if_stage_i.instr_valid_id_d & if_stage_i.instr_new_id_d) | rvfi_irq_valid) begin\n rvfi_ext_stage_pre_mip[0] <= instr_valid_id | ~captured_valid ? cs_registers_i.mip :\n captured_mip;\n rvfi_ext_stage_nmi[0] <= instr_valid_id | ~captured_valid ? irq_nm_i :\n captured_nmi;\n rvfi_ext_stage_nmi_int[0] <=\n instr_valid_id | ~captured_valid ? id_stage_i.controller_i.irq_nm_int :\n captured_nmi_int;\n rvfi_ext_stage_debug_req[0] <= instr_valid_id | ~captured_valid ? debug_req_i :\n captured_debug_req;\n end\n end\n\n\n // rvfi_irq_valid signals an interrupt event to the cosim. These should only occur when the RVFI\n // pipe is empty so just send it straigh through.\n for (genvar i = 0; i < RVFI_STAGES + 1; i = i + 1) begin : g_rvfi_irq_valid\n if (i == 0) begin : g_rvfi_irq_valid_first_stage\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_ext_stage_irq_valid[i] <= 1'b0;\n end else begin\n rvfi_ext_stage_irq_valid[i] <= rvfi_irq_valid;\n end\n end\n end else begin : g_rvfi_irq_valid_other_stages\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_ext_stage_irq_valid[i] <= 1'b0;\n end else begin\n rvfi_ext_stage_irq_valid[i] <= rvfi_ext_stage_irq_valid[i-1];\n end\n end\n end\n end\n\n for (genvar i = 0; i < RVFI_STAGES; i = i + 1) begin : g_rvfi_stages\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_stage_halt[i] <= '0;\n rvfi_stage_trap[i] <= '0;\n rvfi_stage_intr[i] <= '0;\n rvfi_stage_order[i] <= '0;\n rvfi_stage_insn[i] <= '0;\n rvfi_stage_mode[i] <= {PRIV_LVL_M};\n rvfi_stage_ixl[i] <= CSR_MISA_MXL;\n rvfi_stage_rs1_addr[i] <= '0;\n rvfi_stage_rs2_addr[i] <= '0;\n rvfi_stage_rs3_addr[i] <= '0;\n rvfi_stage_pc_rdata[i] <= '0;\n rvfi_stage_pc_wdata[i] <= '0;\n rvfi_stage_mem_rmask[i] <= '0;\n rvfi_stage_mem_wmask[i] <= '0;\n rvfi_stage_valid[i] <= '0;\n rvfi_stage_rs1_rdata[i] <= '0;\n rvfi_stage_rs2_rdata[i] <= '0;\n rvfi_stage_rs3_rdata[i] <= '0;\n rvfi_stage_rd_wdata[i] <= '0;\n rvfi_stage_rd_addr[i] <= '0;\n rvfi_stage_mem_rdata[i] <= '0;\n rvfi_stage_mem_wdata[i] <= '0;\n rvfi_stage_mem_addr[i] <= '0;\n rvfi_ext_stage_pre_mip[i+1] <= '0;\n rvfi_ext_stage_post_mip[i] <= '0;\n rvfi_ext_stage_nmi[i+1] <= '0;\n rvfi_ext_stage_nmi_int[i+1] <= '0;\n rvfi_ext_stage_debug_req[i+1] <= '0;\n rvfi_ext_stage_debug_mode[i] <= '0;\n rvfi_ext_stage_mcycle[i] <= '0;\n rvfi_ext_stage_mhpmcounters[i] <= '{10{'0}};\n rvfi_ext_stage_mhpmcountersh[i] <= '{10{'0}};\n rvfi_ext_stage_ic_scr_key_valid[i] <= '0;\n end else begin\n rvfi_stage_valid[i] <= rvfi_stage_valid_d[i];\n\n if (i == 0) begin\n if (rvfi_id_done) begin\n rvfi_stage_halt[i] <= '0;\n rvfi_stage_trap[i] <= rvfi_trap_id;\n rvfi_stage_intr[i] <= rvfi_intr_d;\n rvfi_stage_order[i] <= rvfi_stage_order_d;\n rvfi_stage_insn[i] <= rvfi_insn_id;\n rvfi_stage_mode[i] <= {priv_mode_id};\n rvfi_stage_ixl[i] <= CSR_MISA_MXL;\n rvfi_stage_rs1_addr[i] <= rvfi_rs1_addr_d;\n rvfi_stage_rs2_addr[i] <= rvfi_rs2_addr_d;\n rvfi_stage_rs3_addr[i] <= rvfi_rs3_addr_d;\n rvfi_stage_pc_rdata[i] <= pc_id;\n rvfi_stage_pc_wdata[i] <= pc_set ? branch_target_ex : pc_if;\n rvfi_stage_mem_rmask[i] <= rvfi_mem_mask_int;\n rvfi_stage_mem_wmask[i] <= data_we_o ? rvfi_mem_mask_int : 4'b0000;\n rvfi_stage_rs1_rdata[i] <= rvfi_rs1_data_d;\n rvfi_stage_rs2_rdata[i] <= rvfi_rs2_data_d;\n rvfi_stage_rs3_rdata[i] <= rvfi_rs3_data_d;\n rvfi_stage_rd_addr[i] <= rvfi_rd_addr_d;\n rvfi_stage_rd_wdata[i] <= rvfi_rd_wdata_d;\n rvfi_stage_mem_rdata[i] <= rvfi_mem_rdata_d;\n rvfi_stage_mem_wdata[i] <= rvfi_mem_wdata_d;\n rvfi_stage_mem_addr[i] <= rvfi_mem_addr_d;\n rvfi_ext_stage_debug_mode[i] <= debug_mode;\n rvfi_ext_stage_mcycle[i] <= cs_registers_i.mcycle_counter_i.counter_val_o;\n rvfi_ext_stage_ic_scr_key_valid[i] <= cs_registers_i.cpuctrlsts_ic_scr_key_valid_q;\n // This is done this way because SystemVerilog does not support looping through\n // gen_cntrs[k] within a for loop.\n for (int k=0; k < 10; k++) begin\n rvfi_ext_stage_mhpmcounters[i][k] <= cs_registers_i.mhpmcounter[k+3][31:0];\n rvfi_ext_stage_mhpmcountersh[i][k] <= cs_registers_i.mhpmcounter[k+3][63:32];\n end\n end\n\n // Some of the rvfi_ext_* signals are used to provide an interrupt notification (signalled\n // via rvfi_ext_irq_valid) when there isn't a valid retired instruction as well as\n // providing information along with a retired instruction. Move these up the rvfi pipeline\n // for both cases.\n if (rvfi_id_done | rvfi_ext_stage_irq_valid[i]) begin\n rvfi_ext_stage_pre_mip[i+1] <= rvfi_ext_stage_pre_mip[i];\n rvfi_ext_stage_post_mip[i] <= cs_registers_i.mip;\n rvfi_ext_stage_nmi[i+1] <= rvfi_ext_stage_nmi[i];\n rvfi_ext_stage_nmi_int[i+1] <= rvfi_ext_stage_nmi_int[i];\n rvfi_ext_stage_debug_req[i+1] <= rvfi_ext_stage_debug_req[i];\n end\n end else begin\n if (rvfi_wb_done) begin\n rvfi_stage_halt[i] <= rvfi_stage_halt[i-1];\n rvfi_stage_trap[i] <= rvfi_stage_trap[i-1] | rvfi_trap_wb;\n rvfi_stage_intr[i] <= rvfi_stage_intr[i-1];\n rvfi_stage_order[i] <= rvfi_stage_order[i-1];\n rvfi_stage_insn[i] <= rvfi_stage_insn[i-1];\n rvfi_stage_mode[i] <= rvfi_stage_mode[i-1];\n rvfi_stage_ixl[i] <= rvfi_stage_ixl[i-1];\n rvfi_stage_rs1_addr[i] <= rvfi_stage_rs1_addr[i-1];\n rvfi_stage_rs2_addr[i] <= rvfi_stage_rs2_addr[i-1];\n rvfi_stage_rs3_addr[i] <= rvfi_stage_rs3_addr[i-1];\n rvfi_stage_pc_rdata[i] <= rvfi_stage_pc_rdata[i-1];\n rvfi_stage_pc_wdata[i] <= rvfi_stage_pc_wdata[i-1];\n rvfi_stage_mem_rmask[i] <= rvfi_stage_mem_rmask[i-1];\n rvfi_stage_mem_wmask[i] <= rvfi_stage_mem_wmask[i-1];\n rvfi_stage_rs1_rdata[i] <= rvfi_stage_rs1_rdata[i-1];\n rvfi_stage_rs2_rdata[i] <= rvfi_stage_rs2_rdata[i-1];\n rvfi_stage_rs3_rdata[i] <= rvfi_stage_rs3_rdata[i-1];\n rvfi_stage_mem_wdata[i] <= rvfi_stage_mem_wdata[i-1];\n rvfi_stage_mem_addr[i] <= rvfi_stage_mem_addr[i-1];\n\n // For 2 RVFI_STAGES/Writeback Stage ignore first stage flops for rd_addr, rd_wdata and\n // mem_rdata. For RF write addr/data actual write happens in writeback so capture\n // address/data there. For mem_rdata that is only available from the writeback stage.\n // Previous stage flops still exist in RTL as they are used by the non writeback config\n rvfi_stage_rd_addr[i] <= rvfi_rd_addr_d;\n rvfi_stage_rd_wdata[i] <= rvfi_rd_wdata_d;\n rvfi_stage_mem_rdata[i] <= rvfi_mem_rdata_d;\n\n rvfi_ext_stage_debug_mode[i] <= rvfi_ext_stage_debug_mode[i-1];\n rvfi_ext_stage_mcycle[i] <= rvfi_ext_stage_mcycle[i-1];\n rvfi_ext_stage_ic_scr_key_valid[i] <= rvfi_ext_stage_ic_scr_key_valid[i-1];\n rvfi_ext_stage_mhpmcounters[i] <= rvfi_ext_stage_mhpmcounters[i-1];\n rvfi_ext_stage_mhpmcountersh[i] <= rvfi_ext_stage_mhpmcountersh[i-1];\n end\n\n // Some of the rvfi_ext_* signals are used to provide an interrupt notification (signalled\n // via rvfi_ext_irq_valid) when there isn't a valid retired instruction as well as\n // providing information along with a retired instruction. Move these up the rvfi pipeline\n // for both cases.\n if (rvfi_wb_done | rvfi_ext_stage_irq_valid[i]) begin\n rvfi_ext_stage_pre_mip[i+1] <= rvfi_ext_stage_pre_mip[i];\n rvfi_ext_stage_post_mip[i] <= rvfi_ext_stage_post_mip[i-1];\n rvfi_ext_stage_nmi[i+1] <= rvfi_ext_stage_nmi[i];\n rvfi_ext_stage_nmi_int[i+1] <= rvfi_ext_stage_nmi_int[i];\n rvfi_ext_stage_debug_req[i+1] <= rvfi_ext_stage_debug_req[i];\n end\n end\n end\n end\n end\n\n\n // Memory address/write data available first cycle of ld/st instruction from register read\n always_comb begin\n if (instr_first_cycle_id) begin\n rvfi_mem_addr_d = alu_adder_result_ex;\n rvfi_mem_wdata_d = lsu_wdata;\n end else begin\n rvfi_mem_addr_d = rvfi_mem_addr_q;\n rvfi_mem_wdata_d = rvfi_mem_wdata_q;\n end\n end\n\n // Capture read data from LSU when it becomes valid\n always_comb begin\n if (lsu_resp_valid) begin\n rvfi_mem_rdata_d = rf_wdata_lsu;\n end else begin\n rvfi_mem_rdata_d = rvfi_mem_rdata_q;\n end\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_mem_addr_q <= '0;\n rvfi_mem_rdata_q <= '0;\n rvfi_mem_wdata_q <= '0;\n end else 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 end\n // Byte enable based on data type\n always_comb begin\n unique case (lsu_type)\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 always_comb begin\n if (instr_is_compressed_id) begin\n rvfi_insn_id = {16'b0, instr_rdata_c_id};\n end else begin\n rvfi_insn_id = instr_rdata_id;\n end\n end\n\n // Source registers 1 and 2 are read in the first instruction cycle\n // Source register 3 is read in the second instruction cycle.\n always_comb begin\n if (instr_first_cycle_id) begin\n rvfi_rs1_data_d = rf_ren_a ? multdiv_operand_a_ex : '0;\n rvfi_rs1_addr_d = rf_ren_a ? rf_raddr_a : '0;\n rvfi_rs2_data_d = rf_ren_b ? multdiv_operand_b_ex : '0;\n rvfi_rs2_addr_d = rf_ren_b ? rf_raddr_b : '0;\n rvfi_rs3_data_d = '0;\n rvfi_rs3_addr_d = '0;\n end else begin\n rvfi_rs1_data_d = rvfi_rs1_data_q;\n rvfi_rs1_addr_d = rvfi_rs1_addr_q;\n rvfi_rs2_data_d = rvfi_rs2_data_q;\n rvfi_rs2_addr_d = rvfi_rs2_addr_q;\n rvfi_rs3_data_d = multdiv_operand_a_ex;\n rvfi_rs3_addr_d = rf_raddr_a;\n end\n end\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_rs1_data_q <= '0;\n rvfi_rs1_addr_q <= '0;\n rvfi_rs2_data_q <= '0;\n rvfi_rs2_addr_q <= '0;\n\n end else begin\n rvfi_rs1_data_q <= rvfi_rs1_data_d;\n rvfi_rs1_addr_q <= rvfi_rs1_addr_d;\n rvfi_rs2_data_q <= rvfi_rs2_data_d;\n rvfi_rs2_addr_q <= rvfi_rs2_addr_d;\n end\n end\n\n always_comb begin\n if (rvfi_rd_we_wb) begin\n // Capture address/data of write to register file\n rvfi_rd_addr_d = rvfi_rd_addr_wb;\n // If writing to x0 zero write data as required by RVFI specification\n if (rvfi_rd_addr_wb == 5'b0) begin\n rvfi_rd_wdata_d = '0;\n end else begin\n rvfi_rd_wdata_d = rvfi_rd_wdata_wb;\n end\n end else if (rvfi_instr_new_wb) begin\n // If no RF write but new instruction in Writeback (when present) or ID/EX (when no writeback\n // stage present) then zero RF write address/data as required by RVFI specification\n rvfi_rd_addr_d = '0;\n rvfi_rd_wdata_d = '0;\n end else begin\n // Otherwise maintain previous value\n rvfi_rd_addr_d = rvfi_rd_addr_q;\n rvfi_rd_wdata_d = rvfi_rd_wdata_q;\n end\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_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_rd_addr_q <= '0;\n rvfi_rd_wdata_q <= '0;\n end else begin\n rvfi_rd_addr_q <= rvfi_rd_addr_d;\n rvfi_rd_wdata_q <= rvfi_rd_wdata_d;\n end\n end\n\n if (WritebackStage) begin : g_rvfi_rf_wr_suppress_wb\n logic rvfi_stage_rf_wr_suppress_wb;\n logic rvfi_rf_wr_suppress_wb;\n\n // Set when RF write from load data is suppressed due to an integrity error\n assign rvfi_rf_wr_suppress_wb =\n instr_done_wb & ~rf_we_wb_o & outstanding_load_wb & lsu_load_resp_intg_err;\n\n always@(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_stage_rf_wr_suppress_wb <= 1'b0;\n end else if (rvfi_wb_done) begin\n rvfi_stage_rf_wr_suppress_wb <= rvfi_rf_wr_suppress_wb;\n end\n end\n\n assign rvfi_ext_rf_wr_suppress = rvfi_stage_rf_wr_suppress_wb;\n end else begin : g_rvfi_no_rf_wr_suppress_wb\n assign rvfi_ext_rf_wr_suppress = 1'b0;\n end\n\n // rvfi_intr must be set for first instruction that is part of a trap handler.\n // On the first cycle of a new instruction see if a trap PC was set by the previous instruction,\n // otherwise maintain value.\n assign rvfi_intr_d = instr_first_cycle_id ? rvfi_set_trap_pc_q : rvfi_intr_q;\n\n always_comb begin\n rvfi_set_trap_pc_d = rvfi_set_trap_pc_q;\n\n if (pc_set && pc_mux_id == PC_EXC &&\n (exc_pc_mux_id == EXC_PC_EXC || exc_pc_mux_id == EXC_PC_IRQ)) begin\n // PC is set to enter a trap handler\n rvfi_set_trap_pc_d = 1'b1;\n end else if (rvfi_set_trap_pc_q && rvfi_id_done) begin\n // first instruction has been executed after PC is set to trap handler\n rvfi_set_trap_pc_d = 1'b0;\n end\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n rvfi_set_trap_pc_q <= 1'b0;\n rvfi_intr_q <= 1'b0;\n end else begin\n rvfi_set_trap_pc_q <= rvfi_set_trap_pc_d;\n rvfi_intr_q <= rvfi_intr_d;\n end\n end\n\n`else\n logic unused_instr_new_id, unused_instr_id_done, unused_instr_done_wb;\n assign unused_instr_id_done = instr_id_done;\n assign unused_instr_new_id = instr_new_id;\n assign unused_instr_done_wb = instr_done_wb;\n`endif\n\n // Certain parameter combinations are not supported\n `ASSERT_INIT(IllegalParamSecure, !(SecureIbex && (RV32M == RV32MNone)))\n\n // If the ID stage signals its ready the mult/div FSMs must be idle in the following cycle\n `ASSERT(MultDivFSMIdleOnIdReady, id_in_ready |=> ex_block_i.sva_multdiv_fsm_idle)\n\n //////////\n // FCOV //\n //////////\n\n`ifndef SYNTHESIS\n // fcov signals for V2S\n `DV_FCOV_SIGNAL_GEN_IF(logic, rf_ecc_err_a_id, gen_regfile_ecc.rf_ecc_err_a_id, RegFileECC)\n `DV_FCOV_SIGNAL_GEN_IF(logic, rf_ecc_err_b_id, gen_regfile_ecc.rf_ecc_err_b_id, RegFileECC)\n\n // fcov signals for CSR access. These are complicated by illegal accesses. Where an access is\n // legal `csr_op_en` signals the operation occurring, but this is deasserted where an access is\n // illegal. Instead `illegal_insn_id` confirms the instruction is taking an illegal instruction\n // exception.\n // All CSR operations perform a read, `CSR_OP_READ` is the only one that only performs a read\n `DV_FCOV_SIGNAL(logic, csr_read_only,\n (csr_op == CSR_OP_READ) && csr_access && (csr_op_en || illegal_insn_id))\n `DV_FCOV_SIGNAL(logic, csr_write,\n cs_registers_i.csr_wr && csr_access && (csr_op_en || illegal_insn_id))\n\n if (PMPEnable) begin : g_pmp_fcov_signals\n logic [PMPNumRegions-1:0] fcov_pmp_region_ichan_priority;\n logic [PMPNumRegions-1:0] fcov_pmp_region_ichan2_priority;\n logic [PMPNumRegions-1:0] fcov_pmp_region_dchan_priority;\n\n logic unused_fcov_pmp_region_priority;\n\n assign unused_fcov_pmp_region_priority = ^{fcov_pmp_region_ichan_priority,\n fcov_pmp_region_ichan2_priority,\n fcov_pmp_region_dchan_priority};\n\n for (genvar i_region = 0; i_region < PMPNumRegions; i_region += 1) begin : g_pmp_region_fcov\n `DV_FCOV_SIGNAL(logic, pmp_region_ichan_access,\n g_pmp.pmp_i.region_match_all[PMP_I][i_region] & if_stage_i.if_id_pipe_reg_we)\n `DV_FCOV_SIGNAL(logic, pmp_region_ichan2_access,\n g_pmp.pmp_i.region_match_all[PMP_I2][i_region] & if_stage_i.if_id_pipe_reg_we)\n `DV_FCOV_SIGNAL(logic, pmp_region_dchan_access,\n g_pmp.pmp_i.region_match_all[PMP_D][i_region] & data_req_out)\n // pmp_cfg[5:6] is reserved and because of that the width of it inside cs_registers module\n // is 6-bit.\n `DV_FCOV_SIGNAL(logic, warl_check_pmpcfg,\n fcov_csr_write &&\n (cs_registers_i.g_pmp_registers.g_pmp_csrs[i_region].u_pmp_cfg_csr.wr_data_i !=\n {cs_registers_i.csr_wdata_int[(i_region%4)*PMP_CFG_W+:5],\n cs_registers_i.csr_wdata_int[(i_region%4)*PMP_CFG_W+7]}))\n\n if (i_region > 0) begin : g_region_priority\n assign fcov_pmp_region_ichan_priority[i_region] =\n g_pmp.pmp_i.region_match_all[PMP_I][i_region] &\n ~|g_pmp.pmp_i.region_match_all[PMP_I][i_region-1:0];\n\n assign fcov_pmp_region_ichan2_priority[i_region] =\n g_pmp.pmp_i.region_match_all[PMP_I2][i_region] &\n ~|g_pmp.pmp_i.region_match_all[PMP_I2][i_region-1:0];\n\n assign fcov_pmp_region_dchan_priority[i_region] =\n g_pmp.pmp_i.region_match_all[PMP_D][i_region] &\n ~|g_pmp.pmp_i.region_match_all[PMP_D][i_region-1:0];\n end else begin : g_region_highest_priority\n assign fcov_pmp_region_ichan_priority[i_region] =\n g_pmp.pmp_i.region_match_all[PMP_I][i_region];\n\n assign fcov_pmp_region_ichan2_priority[i_region] =\n g_pmp.pmp_i.region_match_all[PMP_I2][i_region];\n\n assign fcov_pmp_region_dchan_priority[i_region] =\n g_pmp.pmp_i.region_match_all[PMP_D][i_region];\n end\n end\n end\n`endif\n\nendmodule\n", "selected_doc_paths": ["doc/02_user/integration.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/instruction_fetch.rst", "doc/03_reference/instruction_decode_execute.rst", "doc/03_reference/load_store_unit.rst", "doc/03_reference/cs_registers.rst", "doc/03_reference/pmp.rst", "doc/03_reference/exception_interrupts.rst", "doc/03_reference/debug.rst", "doc/03_reference/security.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1725, "lang": "sv", "rtl_files": ["rtl/ibex_top.sv"], "spec": "# Behavioral Design Specification: `ibex_top`\n\n## 1. Module Overview\n\n`ibex_top` is the top-level module of the Ibex RISC‑V core. It implements a 32‑bit, 2‑stage pipeline (instruction fetch, instruction decode/execute) with an optional third writeback stage. The core supports a wide range of configurable extensions and features, including:\n\n- Multiplication and division (M‑extension, several performance variants)\n- Bit‑manipulation (B‑extension)\n- Physical memory protection (PMP)\n- Debug support (RISC‑V debug, hardware breakpoints)\n- Instruction cache (with optional ECC and scrambling)\n- Branch target ALU and static branch prediction\n- Dual‑core lockstep for fault detection\n- Various security enhancements (register file ECC, memory ECC, dummy instructions, scrambling)\n\nThe module acts as the system integration point: it instantiates the main core logic (`ibex_core`), the register file, the instruction cache RAMs, and (optionally) a lockstep checker. It also provides all external interfaces (bus, interrupts, debug, alerts) and handles clock gating for power management.\n\n## 2. Configuration Parameters\n\nAll parameters are compile‑time constants. The behaviour of the core changes according to these selections.\n\n| Parameter | Type / Values | Default | Description |\n|------------------------|-----------------------------------|-----------------|--------------------------------------------------------------------------------------------------------------------------------------------------|\n| `PMPEnable` | bit | 0 | Enable Physical Memory Protection (PMP). |\n| `PMPGranularity` | unsigned (0..31) | 0 | Minimum address matching granularity for PMP (in bytes, as power of 2). |\n| `PMPNumRegions` | unsigned (1..16) | 4 | Number of implemented PMP regions (ignored if `PMPEnable` is 0). |\n| `MHPMCounterNum` | unsigned (0..10) | 0 | Number of Machine Hardware Performance Monitor event counters. |\n| `MHPMCounterWidth` | unsigned (1..64) | 40 | Width of the performance monitor counters in bits. |\n| `RV32E` | bit | 0 | Enable RV32E (16 general‑purpose registers). |\n| `RV32M` | `rv32m_e` enum | `RV32MFast` | Select M‑extension implementation: `RV32MNone`, `RV32MSlow`, `RV32MFast`, `RV32MSingleCycle`. |\n| `RV32B` | `rv32b_e` enum | `RV32BNone` | Select B‑extension subset: `RV32BNone`, `RV32BBalanced`, `RV32BOTEarlGrey`, `RV32BFull`. |\n| `RegFile` | `regfile_e` enum | `RegFileFF` | Register file implementation: `RegFileFF` (flip‑flop), `RegFileFPGA` (FPGA‑optimised), `RegFileLatch` (latch‑based). |\n| `BranchTargetALU` | bit | 0 | Enable dedicated branch target ALU (removes one stall cycle for taken branches). |\n| `WritebackStage` | bit | 0 | Enable a third writeback pipeline stage (improves load/store performance). |\n| `ICache` | bit | 0 | Enable instruction cache (instead of prefetch buffer). |\n| `ICacheECC` | bit | 0 | Enable SECDED ECC for instruction cache tag and data RAMs (only used if `ICache==1`). |\n| `ICacheScramble` | bit | 0 | Replace cache RAMs with scrambling RAM primitives (address and data scrambling). |\n| `BranchPredictor` | bit | 0 | Enable static branch prediction (predict forward taken, backward not‑taken). |\n| `SecureIbex` | bit | 0 | Enable a set of security features: dummy instructions, register file ECC, memory ECC, lockstep, reset‑all, and optional scrambling. |\n| `RndCnstLfsrSeed` | `lfsr_seed_t` | default | Starting seed of the LFSR used to generate dummy instructions (only when `SecureIbex==1`). |\n| `RndCnstLfsrPerm` | `lfsr_perm_t` | default | Permutation applied to LFSR output for dummy instructions (only when `SecureIbex==1`). |\n| `DbgTriggerEn` | bit | 0 | Enable RISC‑V debug trigger support (one hardware trigger). |\n| `DbgHwBreakNum` | unsigned | 1 | Number of hardware breakpoints (ignored if `DbgTriggerEn==0`). |\n| `DmHaltAddr` | 32‑bit address | 0x1A110800 | Address the core jumps to when entering debug mode. |\n| `DmExceptionAddr` | 32‑bit address | 0x1A110808 | Address the core jumps to when an exception occurs while in debug mode. |\n| `RndCnstIbexKey` | `SCRAMBLE_KEY_W`‑bit vector | default | Default scrambling key (used if `ICacheScramble` is enabled and no key has been supplied). |\n| `RndCnstIbexNonce` | `SCRAMBLE_NONCE_W`‑bit vector | default | Default scrambling nonce. |\n\n## 3. Interfaces\n\n### 3.1 Clock, Reset and Test\n\n| Port | Width | Direction | Behaviour |\n|-------------------------|-------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------------|\n| `clk_i` | 1 | input | Main system clock. |\n| `rst_ni` | 1 | input | Active‑low asynchronous reset. Resets all core logic. |\n| `test_en_i` | 1 | input | Test mode enable. When asserted, all clock gates are forced open and the core can be tested via scan or other DFT. |\n| `scan_rst_ni` | 1 | input | DFT‑controlled reset. Must be tied to 1 if DFT is not used. Used by the lockstep logic to initialise shadow registers. |\n| `ram_cfg_i` | `ram_1p_cfg_t` | input | Memory configuration signals (e.g. timing, retention) passed to the instruction cache RAMs. |\n\n### 3.2 Core Identification\n\n| Port | Width | Direction | Behaviour |\n|---------------|-------|-----------|----------------------------------------------------------------------------|\n| `hart_id_i` | 32 | input | Hart ID, readable via `mhartid` CSR. Typically static. |\n| `boot_addr_i` | 32 | input | Base address; the first instruction is fetched from `boot_addr_i + 0x80`. |\n\n### 3.3 Instruction Fetch Interface\n\nAll signals follow the valid‑ready‑response handshake typical of a bus slave.\n\n| Port | Width | Direction | Behaviour |\n|------------------------|-------|-----------|-----------------------------------------------------------------------------------------------------|\n| `instr_req_o` | 1 | output | Request to fetch an instruction word. |\n| `instr_gnt_i` | 1 | input | The bus grants the request (may be same cycle). |\n| `instr_rvalid_i` | 1 | input | Response valid; associated data and error flags are valid. |\n| `instr_addr_o` | 32 | output | Address of the requested instruction. |\n| `instr_rdata_i` | 32 | input | Fetched instruction word. |\n| `instr_rdata_intg_i` | 7 | input | Integrity bits (ECC or parity) for the fetched instruction (only used when `MemECC==1`). |\n| `instr_err_i` | 1 | input | Error flag from bus (bus fault, ECC error, etc.). |\n\n**Behaviour**:\n- The core generates fetch requests until it is stalled or sleeping.\n- A request is considered outstanding from the cycle it is asserted and granted. The core may have up to two outstanding fetch requests (due to prefetch or cache line fills).\n- When a response arrives (`instr_rvalid_i`), the core accepts the instruction on the same cycle.\n- If `instr_err_i` is asserted, the core takes an instruction access fault exception.\n\n### 3.4 Load‑Store Unit (Data) Interface\n\n| Port | Width | Direction | Behaviour |\n|-----------------------|-------|-----------|----------------------------------------------------------------------------------------------------|\n| `data_req_o` | 1 | output | Request for a data memory access (load or store). |\n| `data_gnt_i` | 1 | input | The bus grants the request. |\n| `data_rvalid_i` | 1 | input | Response valid. |\n| `data_we_o` | 1 | output | Write enable: 1 for store, 0 for load. |\n| `data_be_o` | 4 | output | Byte enables for the addressed word (one hot per byte). |\n| `data_addr_o` | 32 | output | Byte address of the data access. |\n| `data_wdata_o` | 32 | output | Data to be written (for stores). |\n| `data_wdata_intg_o` | 7 | output | Integrity bits for the written data (only used when `MemECC==1`). |\n| `data_rdata_i` | 32 | input | Read data (for loads). |\n| `data_rdata_intg_i` | 7 | input | Integrity bits for the read data (only used when `MemECC==1`). |\n| `data_err_i` | 1 | input | Error flag from bus (bus fault, ECC error, etc.). |\n\n**Behaviour**:\n- The core issues at most two outstanding data requests (due to unaligned access splitting). The request is considered pending until its response arrives.\n- For a load, the read data is written to the register file in the same cycle `data_rvalid_i` is asserted.\n- For a store, no data is written back; the core waits for `data_rvalid_i` to confirm completion (error or success).\n- If `data_err_i` is asserted, the core takes a load/store access fault (or store page fault as appropriate).\n\n### 3.5 Interrupts\n\n| Port | Width | Direction | Behaviour |\n|--------------------|-------|-----------|--------------------------------------------------------------|\n| `irq_software_i` | 1 | input | Machine software interrupt (MSI). |\n| `irq_timer_i` | 1 | input | Machine timer interrupt (MTI). |\n| `irq_external_i` | 1 | input | Machine external interrupt (MEI). |\n| `irq_fast_i` | 15 | input | Fast (local) interrupts, 0‑14 (for platform‑specific use). |\n| `irq_nm_i` | 1 | input | Non‑maskable interrupt (NMI). |\n\n**Behaviour**:\n- Interrupts are level‑sensitive. The core samples them at the start of each instruction execution.\n- If an interrupt is pending and global interrupts are enabled (`MSTATUS.MIE`), the core takes the corresponding trap (or NMI immediately if enabled).\n- The core asserts `irq_pending_o` (internal) when any enabled interrupt is active; this signal is used to wake the core from sleep.\n- NMI takes highest priority; it is taken regardless of `MSTATUS.MIE` and even from debug mode.\n\n### 3.6 Debug Interface\n\n| Port | Width | Direction | Behaviour |\n|-------------------|-------|-----------|----------------------------------------------------------------------------------------------|\n| `debug_req_i` | 1 | input | Debug request (level sensitive). The core enters debug mode when it can take a breakpoint. |\n| `crash_dump_o` | `crash_dump_t` | output | Captured state dump (PC, cause, etc.) when a double fault occurs. |\n| `double_fault_seen_o` | 1 | output | Pulses high when a double fault (exception during exception handling) is detected. |\n\n**Behaviour**:\n- Debug mode is entered at a breakpoint, single‑step, or on `debug_req_i` (if programmed as a halt request).\n- When in debug mode, the core executes from `DmHaltAddr` and uses `DmExceptionAddr` for exceptions.\n- The optional hardware trigger (`DbgTriggerEn`) allows a memory‑address or instruction‑address match to act as a breakpoint.\n\n### 3.7 Scrambling Interface (for ICache)\n\n| Port | Width | Direction | Behaviour |\n|--------------------------|-----------------------|-----------|------------------------------------------------------------------------------------------|\n| `scramble_key_valid_i` | 1 | input | Indicates that a new scrambling key and nonce are available on `scramble_key_i` and `scramble_nonce_i`. |\n| `scramble_key_i` | `SCRAMBLE_KEY_W` | input | Scrambling key. |\n| `scramble_nonce_i` | `SCRAMBLE_NONCE_W` | input | Scrambling nonce. |\n| `scramble_req_o` | 1 | output | Request for a new scrambling key. |\n\n**Behaviour**:\n- This interface is active only when `ICacheScramble` is enabled. Otherwise all ports are tied off.\n- The core requests a new key by asserting `scramble_req_o` after an instruction cache invalidation. The system must respond with a valid key on `scramble_key_valid_i`.\n- The key and nonce are used by the scrambling cache RAMs to encrypt/decrypt addresses and data.\n\n### 3.8 Control and Status Outputs\n\n| Port | Width | Direction | Behaviour |\n|----------------------------|-------|-----------|-------------------------------------------------------------------------------------------------------------------|\n| `fetch_enable_i` | 4 | input | Multi‑bit enable: when `FetchEnableOn`, the core proceeds with instruction fetch; `FetchEnableOff` halts fetch. |\n| `alert_minor_o` | 1 | output | Pulse indicating a recoverable fault (e.g., ECC error corrected, glitch detected). |\n| `alert_major_internal_o` | 1 | output | Pulse indicating an unrecoverable internal fault (e.g., integrity error in register file or data path). |\n| `alert_major_bus_o` | 1 | output | Pulse indicating an unrecoverable bus fault (e.g., transaction error or double error on the cache). |\n| `core_sleep_o` | 1 | output | Asserted when the core is in WFI (Wait for Interrupt) with no outstanding memory requests. |\n\n**Behaviour**:\n- `alert_minor_o` is typically a single‑cycle pulse per event. `alert_major_*` may be pulsed for multiple cycles.\n- `core_sleep_o` is de‑asserted when an interrupt, NMI, or debug request arrives.\n\n## 4. Functional Behaviour\n\n### 4.1 Pipeline Execution\n\nThe core implements a two‑stage pipeline (ID/EX) by default. With `WritebackStage=1` a third stage is added.\n\n- **Instruction Fetch (IF)**: Instructions are fetched from the instruction interface (prefetch buffer or cache). The IF stage can fetch one instruction per cycle if the memory system responds quickly.\n- **Decode/Execute (ID/EX)**: The fetched instruction is decoded and executed immediately. Register reads and writes are performed in this stage.\n- **Writeback (WB)**: When present, loads obtain data in the ID/EX stage and can forward it without stalling; the WB stage formalises the register write timing.\n\n**Stall Behaviour**: Instructions that cannot complete in one cycle stall the ID/EX stage. Stall cycles are as follows (from pipeline documentation):\n\n| Instruction Type | Stall Cycles (2‑stage) |\n|--------------------------|----------------------------------------------------------|\n| Integer computational | 0 |\n| CSR access | 0 |\n| Load/store | ≥1 (until memory response) |\n| Multiplication (fast) | 2 (MUL), 3 (MULH) |\n| Multiplication (slow) | up to 32 (MULH) |\n| Division | 1 (div by 0) or 37 (full) |\n| Branch (taken) | ≥2 (≥1 if `BranchTargetALU` is enabled) |\n| Jump / JALR | ≥1 (flush prefetch, wait for new instruction) |\n| FENCE.I | treated as a jump (≥1 stall) |\n| Branch (not‑taken) | 0 |\n\n### 4.2 Exception and Interrupt Handling\n\n- All RISC‑V machine‑level exceptions are supported: instruction access fault, illegal instruction, breakpoint, load/store access fault, ecall, and (if configured) PMP violations.\n- Interrupts are taken at instruction boundaries. The core saves the current PC (`mepc`) and cause (`mcause`), then jumps to the trap handler base address (`mtvec`).\n- NMI (`irq_nm_i`) bypasses the usual interrupt enable and is taken immediately (unless the core is already handling an NMI). A double fault (another exception during exception handling) is detected and signalled via `double_fault_seen_o`. The `crash_dump_o` provides a snapshot of key state for debugging.\n\n### 4.3 Debug Mode\n\n- The core supports RISC‑V Debug Specification 0.13. It can enter debug mode via `debug_req_i`, by hitting a hardware breakpoint, or by single‑stepping.\n- While in debug mode, the core executes instructions from `DmHaltAddr`. If an exception occurs, it jumps to `DmExceptionAddr`.\n- Debug mode is exited by executing a `dret` instruction.\n\n### 4.4 Security Features (when `SecureIbex = 1`)\n\nThe following features are enabled collectively by `SecureIbex` (some may also be independently enabled by their own parameters):\n\n- **Dummy Instructions**: After a trap, the core randomly inserts dummy instructions (using an LFSR) to obscure timing.\n- **Register File ECC**: The register file uses SECDED encoding (32 data bits + 7 ECC bits). `RegFileECC` is forced to 1.\n- **Memory Interface ECC**: The instruction and data busses carry 7 integrity bits (`MemECC`). The core checks these on all reads.\n- **Register File Write‑Enable Check**: A glitch‑detection mechanism verifies that the write‑enable signal is consistent with the instruction.\n- **Reset‑All**: All internal state (including PC) is forced to a deterministic value on reset.\n- **Lockstep**: A duplicate shadow core (`ibex_lockstep`) runs in parallel and compares its outputs with the main core. Any mismatch generates an alert.\n- **Instruction Cache Scrambling**: When `ICacheScramble` is enabled, the cache RAMs use cryptographic scrambling to protect against physical attacks.\n\n### 4.5 Clock Gating and Power Management\n\n- The module has an internal clock gate. The clock to the core logic is enabled whenever:\n - The core is busy (`core_busy`), or\n - A debug request is pending, or\n - An interrupt (including NMI) is pending.\n- When the core enters WFI and has no outstanding memory transactions, `core_sleep_o` is asserted. The external clock may be stopped or reduced. Any interrupt or debug request will re‑enable the clock and de‑assert `core_sleep_o`.\n\n### 4.6 Alert Aggregation\n\nThe module ORs the alert signals from the core, the lockstep checker, and the register file:\n\n- `alert_minor_o` = `core_alert_minor` OR `lockstep_alert_minor`.\n- `alert_major_internal_o` = `core_alert_major_internal` OR `lockstep_alert_major_internal` OR `rf_alert_major_internal`.\n- `alert_major_bus_o` = `core_alert_major_bus` OR `lockstep_alert_major_bus`.\n\nAll alerts are pulsed outputs. The system integrator should assign them to appropriate error‑handling logic (e.g., reset generation, interrupt controller, or error logging).\n\n### 4.7 Instruction Cache (when `ICache = 1`)\n\nIf `ICache` is enabled, the core instantiates a set‑associative instruction cache (two ways, line size 16 bytes). The cache operates as a fetch‑through buffer: on a miss, a line fill is initiated. Cacheable vs. non‑cacheable regions are determined by PMP (if enabled) or by an external memory‑mapped scheme.\n\nThe cache RAMs can optionally include ECC (`ICacheECC`) or scrambling (`ICacheScramble`). When scrambling is enabled, the cache uses dedicated `prim_ram_1p_scr` primitives that require a valid scrambling key before operation. The core automatically requests a new key on every cache invalidation (e.g., after a FENCE.I or hardware reset).\n\n## 5. Reset Behaviour\n\nWhen `rst_ni` is asserted (low), the core goes through the following resets:\n\n- All pipeline registers, CSRs, and control logic are reset to their default values.\n- The program counter is set to `boot_addr_i + 0x80` (the reset vector after the exception handler area).\n- If `ResetAll` is enabled (only when `SecureIbex=1`), additional state such as the LFSR and scrambling key registers are also forced to deterministic values.\n- The instruction cache (if present) is invalidated.\n- The lockstep shadow core is reset, and its outputs are ignored until the main core has stabilised.\n\nAfter reset de‑assertion, the core begins fetching instructions from the reset vector.\n\n## 6. Simulation and Formal Verification Interfaces\n\nWhen compiled with the `RISCV_FORMAL` definition active (`-DRISCV_FORMAL`), the module exports the RISC‑V Formal Interface (RVFI) signals. These include:\n\n- `rvfi_valid`, `rvfi_order`, `rvfi_insn`, `rvfi_trap`, `rvfi_halt`, `rvfi_intr`\n- Register read/write data, PC, memory access details, CSR values, and performance counters.\n\nThese signals are for formal verification and not intended for normal functional use. They shall be connected to the RVFI formal checker when verifying the core.\n\n## 7. Assertions and Design Constraints\n\nThe RTL includes a set of SystemVerilog assertions that must hold for correct operation:\n\n- All output ports shall be free of X/Z values when in functional (non‑test) mode.\n- The data side memory interface shall never exceed two outstanding requests.\n- Response valid (`data_rvalid_i`) must only occur when a request is pending.\n- A request must not be issued if the maximum outstanding count has been reached (unless a response arrives in the same cycle).\n\nThese assertions serve as design rules; they shall be verified during simulation and formal analysis.\n\n---\n\n*This specification describes the intended observable behaviour of the `ibex_top` module. Any discrepancy between this specification and the RTL implementation should be reported as a design issue.*", "commit_id": "7bae3b7ba34d9611bc263d84bd358ec5021f82d3", "timestamp": "2022-07-26T15:58:31+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "6dc0683773635bfde3949c6fa7d9c3e7282ab916", "pr_title": "[dv] Fix IbexDataRPayloadX assertion", "pr_body": "Some aspects of the memory response are only relevant to reads. This\r\nintroduces outstanding request tracking so we know which outstanding\r\nrequests are reads and applies X checks appropriately.\r\n\r\nFixes #1645", "issue_title": "Simple system VCS simulation fails with multiple errors", "issue_body": "\r\n\r\n\r\nI want to simulate the simple system example using VCS, the build passes without any issue, but when I run the simulation, I get multiple errors caused by failed assertion\r\n\r\n## My Environment\r\n\r\n\r\n\r\n**EDA tool and version:**\r\n\r\nVCS S-2021.09-SP1_Full64\r\n**Operating system:**\r\nRed Hat Enterprise Linux release 8.5 \r\n\r\n**Version of the Ibex source code:**\r\n master branch hash : 668856441a73ebd067c09fdd2432241a32b8f03d\r\n\r\n**first part of the long errors list**\r\n\r\nChronologic VCS simulator copyright 1991-2021\r\nContains Synopsys proprietary information.\r\nCompiler version S-2021.09-SP1_Full64; Runtime version S-2021.09-SP1_Full64; May 2 13:47 2022\r\nInitializing memory ibex_simple_system.u_ram.u_ram.gen_generic.u_impl_generic.unnamed$$_2.gen_meminit from file './examples/sw/simple_system/hello_test/hello_test.vmem'.\r\n\"../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv\", 982: ibex_simple_system.u_top.u_ibex_top.IbexInstrReqX: started at 18s failed at 18s\r\n\tOffending '(!$isunknown(instr_req_o))'\r\nError: \"../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv\", 982: ibex_simple_system.u_top.u_ibex_top.IbexInstrReqX: at time 18\r\n18: (../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv:982) [ibex_simple_system.u_top.u_ibex_top.IbexInstrReqX] [ASSERT FAILED] IbexInstrReqX\r\n\"../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv\", 983: ibex_simple_system.u_top.u_ibex_top.IbexInstrReqPayloadXKnownEnable: started at 18s failed at 18s\r\n\tOffending '(!$isunknown(instr_req_o))'\r\nError: \"../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv\", 983: ibex_simple_system.u_top.u_ibex_top.IbexInstrReqPayloadXKnownEnable: at time 18\r\n18: (../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv:983) [ibex_simple_system.u_top.u_ibex_top.IbexInstrReqPayloadXKnownEnable] [ASSERT FAILED] IbexInstrReqPayloadXKnownEnable\r\n\"../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv\", 1002: ibex_simple_system.u_top.u_ibex_top.IbexInstrGntX: started at 18s failed at 18s\r\n\tOffending '(!$isunknown(instr_gnt_i))'\r\nError: \"../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv\", 1002: ibex_simple_system.u_top.u_ibex_top.IbexInstrGntX: at time 18\r\n18: (../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv:1002) [ibex_simple_system.u_top.u_ibex_top.IbexInstrGntX] [ASSERT FAILED] IbexInstrGntX\r\n\"../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv\", 982: ibex_simple_system.u_top.u_ibex_top.IbexInstrReqX: started at 20s failed at 20s\r\n\tOffending '(!$isunknown(instr_req_o))'\r\nError: \"../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv\", 982: ibex_simple_system.u_top.u_ibex_top.IbexInstrReqX: at time 20\r\n20: (../src/lowrisc_ibex_ibex_top_0.1/rtl/ibex_top.sv:982) [ibex_simple_system.u_top.u_ibex_top.IbexInstrReqX] [ASSERT FAILED] IbexInstrReqX\r\n", "commit_message": "[dv] Fix IbexDataRPayloadX assertion\n\nSome aspects of the memory response are only relevant to reads. This\nintroduces outstanding request tracking so we know which outstanding\nrequests are reads and applies X checks appropriately.\n\nFixes #1645", "fix_patch": "diff --git a/rtl/ibex_top.sv b/rtl/ibex_top.sv\nindex e6056d1c58..01343f0a3b 100644\n--- a/rtl/ibex_top.sv\n+++ b/rtl/ibex_top.sv\n@@ -1045,7 +1045,78 @@ module ibex_top import ibex_pkg::*; #(\n \n `ASSERT_KNOWN(IbexDataGntX, data_gnt_i)\n `ASSERT_KNOWN(IbexDataRValidX, data_rvalid_i)\n- `ASSERT_KNOWN_IF(IbexDataRPayloadX, {data_rdata_i, data_rdata_intg_i, data_err_i}, 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+ always_comb begin\n+ pending_dside_accesses_d[i] = pending_dside_accesses_shifted[i];\n+\n+ if (data_req_o && data_gnt_i) begin\n+ if (i == 0 && !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 else if (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_d[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+ // data_rdata_i and data_rdata_intg_i are only relevant to reads. Check neither are X on\n+ // 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+\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+ `endif\n \n `ASSERT_KNOWN(IbexIrqX, {irq_software_i, irq_timer_i, irq_external_i, irq_fast_i, irq_nm_i})\n \n", "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_debug_req,\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`endif\n\n // CPU Control Signals\n input fetch_enable_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 logic 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 [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 // 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 icache_inval;\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 fetch_enable_t fetch_enable_buf;\n\n /////////////////////\n // Main clock gate //\n /////////////////////\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_d;\n end\n end\n\n assign clock_en = core_busy_q | debug_req_i | irq_pending | irq_nm_i;\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(fetch_enable_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 .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\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_debug_req,\n .rvfi_ext_mcycle,\n .rvfi_ext_mhpmcounters,\n .rvfi_ext_mhpmcountersh,\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 .icache_inval_o (icache_inval),\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\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\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\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 icache_inval ? 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 : icache_inval;\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 icache_inval & 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 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 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 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 icache_inval,\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 [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\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 fetch_enable_t fetch_enable_local;\n\n logic icache_inval_local;\n logic 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 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 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 icache_inval,\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 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 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 icache_inval_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 .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\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 .icache_inval_i (icache_inval_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 always_comb begin\n pending_dside_accesses_d[i] = pending_dside_accesses_shifted[i];\n\n if (data_req_o && data_gnt_i) begin\n if (i == 0 && !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 else if (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_d[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 // data_rdata_i and data_rdata_intg_i are only relevant to reads. Check neither are X on\n // 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\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 `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)\nendmodule\n", "selected_doc_paths": ["doc/02_user/integration.rst", "doc/03_reference/pipeline_details.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1643, "lang": "sv", "rtl_files": ["rtl/ibex_top.sv"], "spec": "# Behavioral Design Specification for Ibex Top-Level Module (ibex_top)\n\n## 1. Introduction\n\nThe Ibex top-level module integrates a 32-bit RISC-V processor core (the “main core”) with its register file, optional instruction cache (I$), scrambling infrastructure for the I$, and an optional dual-core lockstep shadow core. It provides all external interfaces required to integrate the processor into a system-on-chip.\n\nThe module is synthesizable and targets ASIC or FPGA implementations. It supports a range of configurations selected at synthesis time, allowing trade-offs among area, performance, and security.\n\n## 2. Functional Overview\n\nThe module shall implement a 32-bit RISC‑V processor that can execute the base integer instruction set (RV32I) and optionally the “M”, “B”, and “C” extensions (when configured accordingly). It includes:\n\n- a single‑issue, in‑order pipeline with a variable number of stages (two or three, configurable);\n- an optional instruction cache (I$) that replaces the default prefetch buffer;\n- an optional dual‑core lockstep unit for fault detection;\n- optional physical memory protection (PMP);\n- debug support compliant with the RISC‑V debug specification;\n- security enhancements configurable via the `SecureIbex` parameter.\n\nThe module communicates with external memory systems through separate instruction and data interfaces. It accepts interrupt requests, debug requests, and a fetch enable signal. It outputs alerts and status signals.\n\n## 3. Configuration Parameters\n\nAll configuration parameters are static (compile‑time). Changing them shall alter the hardware implementation accordingly.\n\n| Parameter | Effect |\n|------------------------|----------------------------------------------------------------------------------------------|\n| `PMPEnable` | Enable physical memory protection registers. |\n| `PMPGranularity` | Minimum alignment for PMP address matching (0=4 bytes, 1=8 bytes, …). |\n| `PMPNumRegions` | Number of PMP regions implemented (1–16). |\n| `MHPMCounterNum` | Number of hardware performance‑monitor counters. |\n| `MHPMCounterWidth` | Bit width of each performance‑monitor counter. |\n| `RV32E` | If set, only 16 integer registers are available (RV32E). |\n| `RV32M` | Select the multiplier/divider implementation: none, slow, fast, or single‑cycle. |\n| `RV32B` | Select the bit‑manipulation extension subset: none, balanced, EarlGrey, or full. |\n| `RegFile` | Register file implementation: flip‑flop, FPGA‑optimized, or latch‑based. |\n| `BranchTargetALU` | When set, reduces the taken‑branch penalty by one cycle (experimental). |\n| `WritebackStage` | Adds a third pipeline stage for loads/stores, improving performance (experimental). |\n| `ICache` | Enable instruction cache (replaces prefetch buffer, experimental). |\n| `ICacheECC` | Add SECDED ECC protection to I$ tag and data RAMs (requires `ICache`). |\n| `ICacheScramble` | Replace I$ RAMs with scrambling primitives (requires `ICache`). |\n| `BranchPredictor` | Enable static branch prediction (experimental). |\n| `DbgTriggerEn` | Enable a single debug trigger. |\n| `DbgHwBreakNum` | Number of hardware breakpoints (at least one). |\n| `SecureIbex` | Enable a set of security features (see Section 8). |\n| `RndCnstLfsrSeed` | Initial seed for the LFSR used in dummy‑instruction generation. |\n| `RndCnstLfsrPerm` | Permutation applied to the LFSR output. |\n| `DmHaltAddr` | Entry address when entering debug mode. |\n| `DmExceptionAddr` | Exception address when an exception occurs while in debug mode. |\n| `RndCnstIbexKey` | Default key for I$ scrambling. |\n| `RndCnstIbexNonce` | Default nonce for I$ scrambling. |\n\n## 4. Interface Signals – Behavioral Description\n\nThe module shall observe the following external interfaces. Signal names are omitted; behavior is described in terms of the function they perform.\n\n### 4.1 Clock and Reset\n\n- A single clock input shall drive all synchronous logic. An active‑low asynchronous reset input shall reset the processor to its initial state.\n- A test enable input may be used to force all clock gates open during scan testing.\n- A scan reset input is provided for DFT; if not used it must be tied inactive.\n\n### 4.2 Memory Interfaces\n\nThe module has two independent memory interfaces: one for instruction fetch and one for load/store operations.\n\n**Instruction fetch interface** \nThe module shall issue instruction fetch requests via a request/‑grant‑/‑valid handshake. Requested addresses are 32‑bit word‑aligned (or halfword‑aligned in the presence of compressed instructions). The interface supports pipelined transactions. The module shall accept response data together with an error flag. Optionally, integrity bits may be provided alongside the data; if configured (`MemECC`) these shall be checked on incoming data.\n\n**Data load/store interface** \nA separate request‑/‑grant‑/‑valid handshake is used for data memory accesses. The module drives a byte‑enable mask, a write‑enable signal, an address, and write data. Read data and error flags are returned on the response. Integrity bits may be supplied for write data and checked on read data when `MemECC` is enabled.\n\nBoth interfaces shall comply with the single‑clock handshake protocol described in the core’s integration guide.\n\n### 4.3 Interrupt Inputs\n\nThe module shall accept the following interrupt inputs:\n\n- Software interrupt, timer interrupt, external interrupt (standard RISC‑V machine‑level interrupts).\n- Up to 15 fast interrupts (custom, platform‑specific).\n- A non‑maskable interrupt (NMI) that cannot be disabled by software.\n\nWhen an interrupt is pending and the core is not in a critical section, the core shall take the appropriate trap (if enabled) according to the RISC‑V privilege specification. Interrupts are sampled in the instruction fetch stage; the module shall output a pending flag that can be used to gate the core’s clock.\n\n### 4.4 Debug Interface\n\nA single debug request input shall cause the core to halt and enter debug mode (if not already halted). The core shall jump to the configured `DmHaltAddr`. It shall output a crash dump structure (which includes essential processor state) and a flag indicating that a double fault has been observed (i.e., a second exception occurred while already handling an exception).\n\n### 4.5 Fetch Enable and Core Sleep\n\nA fetch enable input, using a multi‑bit encoding (two valid values: ON and OFF), shall control whether the core may fetch new instructions. When fetch enable is OFF, the core shall finish any ongoing memory transactions and then cease fetching; in that state it shall not initiate any new instruction or data accesses.\n\nThe module shall output a core sleep signal. This signal shall be asserted whenever the core is in a `WFI` state *and* there are no outstanding instruction or data memory requests. The core shall be woken by any unmasked interrupt or debug request.\n\n### 4.6 Alert Outputs\n\nThree alert signals are provided for system‑level security monitoring:\n\n- **Minor alert**: A pulse indicating a recoverable fault (e.g., ECC error in I$, dummy‑instruction watchdog). The system should log this but may continue operation.\n- **Major internal alert**: A pulse (possibly multi‑cycle) indicating a non‑recoverable internal fault (e.g., register file ECC error, write‑through integrity error, lockstep mismatch, hardened PC mismatch, shadow CSR mismatch).\n- **Major bus alert**: A pulse indicating a non‑recoverable fault originating from the memory system (e.g., bus integrity check failure on incoming data).\n\nAll alerts are the OR‑combination of the corresponding alerts from the main core, the register file, and the lockstep shadow core (if present).\n\n## 5. Processor Core Behavior\n\nThe module shall execute the RISC‑V ISA as defined by the “unprivileged specification” (version 2.1 or later) for the implemented extensions.\n\n- **Pipeline stages**: By default the core has two pipeline stages (fetch, execute). If `WritebackStage` is set, a third write‑back stage is inserted.\n- **Branch prediction**: When `BranchPredictor` is set, static branch prediction (forward not‑taken, backward taken) is enabled.\n- **Memory ordering**: The core uses a relaxed memory model (RVWMO) for data memory accesses.\n- **Exception handling**: Machine‑level traps (interrupts, exceptions, debug) are taken according to the RISC‑V privileged specification (version 1.11).\n\nWhen the `RV32E` parameter is set, only registers x0‑x15 are implemented; otherwise all 32 registers (x0‑x31) are present.\n\n## 6. Instruction Cache (I$) Behavior\n\nIf `ICache` is enabled, the module shall include an instruction cache that replaces the default prefetch buffer. The I$ operates as follows:\n\n- It presents fetched instructions to the core using a ready‑valid protocol.\n- On reset or when an explicit invalidation is requested (via an internal signal from the core after a `FENCE.I` instruction), the I$ shall invalidate all its stored data.\n- While invalidation is in progress, no new data shall be allocated to the cache, but instructions may still be fetched from memory (pass‑through mode).\n- The cache is set‑associative with configurable number of ways and line size.\n- When `ICacheECC` is enabled, tag and data RAMs are protected by SECDED codes. A detected ECC error shall cause the cache to invalidate the erroneous line and fetch the data from memory; a minor alert shall be raised.\n- When `ICacheScramble` is enabled, the RAMs are replaced by scrambling primitives that require an external key. The module shall request a new key from the system; the key and nonce are provided via dedicated inputs with a request‑acknowledge handshake. The scrambling key is latched inside the module and used for all subsequent accesses until a new key is requested.\n\n## 7. Scrambling Key Protocol\n\nWhen `ICacheScramble` is set, the module shall implement the following protocol for acquiring a scrambling key:\n\n1. After reset, the module uses a built‑in default key and nonce.\n2. When the core performs a `FENCE.I` instruction (or any event that causes an I$ invalidation), the module shall assert a request for a new key.\n3. The request remains asserted until the system provides a valid key (indicated by a dedicated input). At that point the module deasserts the request.\n4. While the request is asserted, the module continues to use the current key; it shall only switch to the new key after the request is deasserted.\n\nThis protocol ensures the core can obtain fresh ephemeral keys from a trusted source (e.g., OTP).\n\n## 8. Security Features (SecureIbex)\n\nWhen the `SecureIbex` parameter is set, the module shall incorporate the following additional measures:\n\n- **Data‑independent timing**: A software‑control bit (`data_ind_timing`) can be set to eliminate data‑dependent execution times for branches, multiplication, and division. Memory accesses to unaligned addresses are not covered.\n- **Dummy instruction insertion**: A software‑control bit (`dummy_instr_en`) can be set to insert random dummy instructions into the pipeline at intervals controlled by a mask register. Dummy instructions are chosen from the multiply/divide unit (hence the multiplier must be present). The insertion pattern is governed by an LFSR; software may reseed the LFSR via a custom CSR.\n- **Bus integrity checking**: Incoming instruction and data read data shall be compared against associated integrity bits (`MemECC`). If a mismatch is detected, a major bus alert is raised and the load’s destination register is not updated. Write data integrity bits are forwarded to the memory system for end‑to‑end protection.\n- **Register file ECC**: All reads from the register file are checked with an ECC code. A detected error raises a major internal alert; the core does not attempt correction.\n- **Hardened PC**: The instruction fetch PC is checked against a predicted increment; a mismatch raises a major internal alert (disabled after branches and reset).\n- **Shadow CSRs**: Certain critical CSRs (`mstatus`, `mtvec`, `cpuctrl`, PMP registers) are duplicated with complemented copies; a mismatch between the two copies raises a major internal alert.\n- **Dual‑core lockstep** (enabled automatically when `SecureIbex` is set): A second, identical core is instantiated but receives all inputs through a delay buffer. Its outputs are compared with the delayed outputs of the main core. Any mismatch raises a major internal alert. The register file and I$ RAMs are not duplicated (they are already covered by ECC).\n\n## 9. Lockstep Shadow Core\n\nWhen `SecureIbex` is set (which forces `Lockstep = 1`), the module shall contain a shadow core that runs one clock cycle behind the main core. All inputs to the main core are buffered and fed to the shadow core after one cycle. All outputs of the shadow core are compared to the delayed outputs of the main core. The comparison covers all relevant signals, including memory interface handshakes and internal state outputs. On any mismatch, a major internal alert is generated.\n\nThe shadow core does not drive any external outputs; it is used solely for detection.\n\n## 10. Reset and Initialization\n\n- After reset, the processor shall start fetching instructions from an address derived from the boot address input (`boot_addr_i` + 0x80). The hart ID and boot address inputs are considered static and sampled at reset.\n- The register file shall be initialized to zero (with the exception of x0, which is hard‑wired to zero).\n- The optional instruction cache shall be invalidated.\n- The scrambling key (if used) shall start with the default configuration.\n- All internal registers (CSRs, pipeline flip‑flops) shall be set to their reset values as defined in the RISC‑V privileged specification and the Ibex custom CSRs.\n\n## 11. Formal Verification Interface (RVFI)\n\nWhen the `RISCV_FORMAL` define is set, the module shall export a set of signals that comply with the RISC‑V Formal Interface (RVFI) specification. These signals describe every retired instruction, its operands, results, and associated memory access details. They are used for formal verification of the core.\n\n## 12. Error Handling\n\nThe module shall handle the following error conditions:\n\n- **Instruction fetch error**: When the memory system returns an error for an instruction fetch, the core shall take an instruction access fault exception. If the instruction is uncompressed and spans two words, the error on the second half shall be recorded in `mtval`.\n- **Data access error**: When an error is returned for a load or store, the core shall take a corresponding data access fault exception.\n- **Double fault**: If an exception or interrupt occurs while the core is already handling a trap, the core shall enter a “double fault” state. It shall set the `double_fault_seen_o` output and continue operation (typically by asserting a major alert). The precise behavior is defined in the debug/trap handling specification.\n- **Bus integrity errors**: As described in Section 8, such errors cause an interrupt or a major alert depending on the security configuration.\n- **Lockstep mismatch**: Generates a major internal alert. The system must decide how to respond (e.g., reset).\n\n## 13. Clock Gating\n\nThe module shall automatically gate its internal clock when the core is idle (no pending execution, no outstanding memory transactions, no interrupts or debug requests). The core sleep output indicates that the clock may be safely gated. The clock gating is controlled by an enable signal derived from the core busy state, pending interrupts, and debug requests.\n\n## 14. Testability\n\nThe test enable input shall force all internal clock gates to be transparent during scan testing. The scan reset input may be used to override the functional reset during scan operations.\n\n## 15. Implementation Notes (for completeness, not behavioral)\n\nThe specification above covers the required behavior of the Ibex top‑level module. Any internal implementation choices (e.g., exact pipeline structure, arbitration logic, buffering) shall be transparent to the user as long as the external behavior conforms to this specification.", "commit_id": "e34bb4d92f602ed1dde464da67818f99b5a1ed81", "timestamp": "2022-05-04T13:40:00+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "361f2ddedf0ea95dbdfeda1cd1c510b83fb323f4", "pr_title": "Instantiate plain memory primitives for ICache when ICache scrambling is disabled", "pr_body": "Opening a PR to resolve issue #1514. Plain (ie. not scrambled) memory primitives are instantiated conditionally when parameter ICacheScramble=0. This change eliminates some unused logic when scrambling is disabled.\r\n\r\nI have successfully run riscv_machine_mode_rand_test with and without ICache enabled, as well as with and without ICache scrambling enabled. I have also run synthesis and see a minor reduction in cell area about 10-15% when ICache is enabled without scrambling, not including memory area itself.", "issue_title": "Use plain memory primitives when ICache scrambling is disabled", "issue_body": "The recent PR to add scrambling support to the ICache lacks an option to allow the use of non-scrambled RAMs. Scrambling is only of interest to applications requiring security hardening, other applications may simply want an ICache without scrambled memories.", "commit_message": "Update ibex_top.sv\n\nAdding conditional to instantiate non-scrambling instruction cache memories when ICacheScramble parameter is not set.", "fix_patch": "diff --git a/rtl/ibex_top.sv b/rtl/ibex_top.sv\nindex ab4934b095..5b5c691d53 100644\n--- a/rtl/ibex_top.sv\n+++ b/rtl/ibex_top.sv\n@@ -514,73 +514,117 @@ module ibex_top import ibex_pkg::*; #(\n \n for (genvar way = 0; way < IC_NUM_WAYS; way++) begin : gen_rams_inner\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+ 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+ 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- // 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+ end\n end\n \n end else begin : gen_norams\n", "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_debug_req,\n output logic [63:0] rvfi_ext_mcycle,\n`endif\n\n // CPU Control Signals\n input fetch_enable_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 logic 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 [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 // 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 icache_inval;\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 fetch_enable_t fetch_enable_buf;\n\n /////////////////////\n // Main clock gate //\n /////////////////////\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_d;\n end\n end\n\n assign clock_en = core_busy_q | debug_req_i | irq_pending | irq_nm_i;\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(fetch_enable_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 .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\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_debug_req,\n .rvfi_ext_mcycle,\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 .icache_inval_o (icache_inval),\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\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\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\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 icache_inval ? 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 : icache_inval;\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 icache_inval & 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 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 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 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 icache_inval,\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 [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\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 fetch_enable_t fetch_enable_local;\n\n logic icache_inval_local;\n logic 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 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 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 icache_inval,\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 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 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 icache_inval_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 .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\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 .icache_inval_i (icache_inval_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 `ASSERT_KNOWN_IF(IbexDataRPayloadX, {data_rdata_i, data_rdata_intg_i, data_err_i}, data_rvalid_i)\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)\nendmodule\n", "selected_doc_paths": ["doc/02_user/integration.rst", "doc/03_reference/security.rst", "doc/03_reference/icache.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1595, "lang": "sv", "rtl_files": ["shared/rtl/ram_2p.sv"], "spec": "# Dual-Port RAM (ram_2p) Design Specification\n\n## Overview\n\nThe `ram_2p` module implements a synchronous, 32‑bit wide, dual‑port static RAM. \nIt provides two independent access ports (A and B), each capable of both read and write operations. \nThe memory supports byte‑level write granularity via byte enable signals. \nRead data is available one clock cycle after the request is asserted, with a corresponding valid indication. \nThe module is intended for use as a general‑purpose memory or register file in CPU cores, caches, or other digital logic blocks.\n\n## Features\n\n- True dual‑port operation – Port A and Port B can be accessed concurrently without interference.\n- Single‑cycle read latency (pipelined): data valid one clock cycle after request.\n- Write with byte enables: any combination of the four bytes (8‑bit per enable) can be written.\n- Word‑aligned addressing: address bits [1:0] are ignored internally; the logical address space is byte‑addressed with word granularity.\n- Configuration parameters: memory depth (number of 32‑bit words) and optional initial content file.\n- Active‑low synchronous reset clears the read‑valid flags only; the memory content is not reset.\n- All inputs and outputs are registered on the rising edge of the clock.\n\n## Interface Description\n\n### Parameters\n\n| Parameter | Type | Default | Description |\n|----------------|---------|---------|-----------------------------------------------------------------------|\n| `Depth` | integer | 128 | Number of 32‑bit words in the memory. Must be a power of two. |\n| `MemInitFile` | string | \"\" | Path to a file containing initial memory contents (format is tool‑dependent). If empty, memory is uninitialized. |\n\n### Ports (per interface)\n\n- **Clock and Reset** \n A single clock (`clk_i`) and an active‑low asynchronous reset (`rst_ni`) drive both ports.\n\n- **Request and Control** \n Each port provides: \n - A **request** signal (`req`): indicates that a valid access is being presented. \n - A **write enable** (`we`): when high, the access is a write; when low, it is a read. \n - A **byte enable** (`be`): a 4‑bit vector, each bit selects one byte of the 32‑bit word. \n - An **address** (`addr`): 32‑bit word‑aligned address (only the bits needed to index `Depth` entries are used; the two LSBs and the upper bits beyond the required width are ignored). \n - **Write data** (`wdata`): 32‑bit data to be written (only relevant for writes).\n\n- **Response** \n Each port provides: \n - A **read valid** (`rvalid`): asserted for one cycle following a read request, indicating that the read data is available. \n - **Read data** (`rdata`): 32‑bit data from the requested address, valid when `rvalid` is high.\n\n## Functional Behavior\n\n### General Operation\n\n- All state transitions occur on the rising edge of `clk_i`. \n- When `rst_ni` is low, the `rvalid` outputs of both ports are de‑asserted (driven to logic 0). The memory array itself is **not** affected by reset. \n- The memory array is addressed as a collection of `Depth` 32‑bit words. The word‑aligned address is obtained by ignoring the lower two address bits (`addr[1:0]`) and any bits above `log2(Depth) + 1` (the most significant part of the address). Thus, the effective address range is `A[log2(Depth)-1+2 : 2]`.\n\n### Read Operation\n\n1. To perform a read, the requesting port must assert its request signal with write enable low. The byte enable signals have **no effect** on read operations; the entire 32‑bit word is returned. \n2. The module latches the request on the next rising clock edge and starts a read from the addressed word. \n3. One clock cycle later, the `rvalid` output is driven high, and `rdata` contains the data read from that location. \n4. If a read request is asserted for only one cycle, the corresponding `rvalid` will be high for exactly one cycle. If the request is held high over multiple cycles (e.g., for a multi‑cycle eager request), the module will continue to generate read valid pulses every cycle, but the read data will be that of the last qualified request. For correct operation, the request should be left high until the operation is granted by an external handshake (if applicable) – in this simple module, there is no back‑pressure; the memory accepts requests every cycle.\n\n### Write Operation\n\n1. To perform a write, the requesting port must assert its request signal with write enable high. The byte enable signals select which bytes of the addressed word shall be written. \n2. The write data and byte enables are latched along with the address. \n3. On the next rising clock edge, the selected bytes of the memory word are updated with the corresponding bytes of write data. \n4. There is no separate write response; the write completes in one clock cycle. The `rvalid` output for that port will be asserted one cycle after the write request, but the data on `rdata` during that cycle is **undefined** (the memory may return the old value, the new value, or remain unchanged – the module does not guarantee a read after write to the same address on the same port in consecutive cycles without additional external handling).\n\n> **Note**: In the current implementation, a write also triggers a read‑valid pulse after one cycle. The read data output during that cycle must not be relied upon; it is an artifact of the pipelined read‑valid generation.\n\n### Byte Enable Behavior\n\n- Each bit of the 4‑bit byte enable corresponds to one byte of the 32‑bit word: \n - `be[0]` enables byte 0 (bits [7:0]) \n - `be[1]` enables byte 1 (bits [15:8]) \n - `be[2]` enables byte 2 (bits [23:16]) \n - `be[3]` enables byte 3 (bits [31:24]) \n- During a write, only bytes whose enable bit is high are updated. Bytes with a low enable retain their previous value. \n- Byte enables have no effect during reads; they may be safely left at any value.\n\n### Dual‑Port Access\n\n- Both ports A and B operate independently and simultaneously. \n- The memory array is truly dual‑ported: a read and a write (or two reads) to the same address from different ports can occur in the same clock cycle without causing data corruption or undefined behavior. \n- If both ports write to the same address in the same cycle, the result is **implementation‑defined** (the technology‑specific memory primitive may have a conflict). To avoid such situations, software or hardware arbitration should ensure that simultaneous writes to the same address do not occur.\n\n## Timing\n\n- **Read latency**: 1 clock cycle. \n - Cycle 0: request asserted. \n - Cycle 1: `rvalid` high, `rdata` valid. \n- **Write latency**: 1 clock cycle. \n - Cycle 0: request asserted (with `we` high). \n - Cycle 1: memory updated. \n- **Back‑to‑back reads**: successive reads to different addresses can be issued every cycle; each read returns its data after one cycle with a valid pulse. \n- **Reset**: `rvalid` outputs become low asynchronously (on `rst_ni` low) and remain low until after the first rising edge where reset is released and a new request is made.\n\n## Initialization\n\nIf the `MemInitFile` parameter is set to a non‑empty string, the memory shall be initialized with data from that file before simulation or synthesis (tool‑dependent). The file format must comply with the tools used (typically a hex or binary file). If `MemInitFile` is empty, the initial content of each word is undefined.\n\n## Constraints and Usage Notes\n\n- The module relies on an underlying technology‑dependent RAM primitive (`prim_ram_2p`). All timing and arbitration guarantees are subject to the characteristics of that primitive. \n- The address width is derived from `Depth`; any address bits beyond the necessary width are ignored. This means that addresses wrapping beyond the memory size will alias to the lower addresses. \n- The module does **not** implement any error detection or correction (ECC). \n- For simulations, the module is purely behavioural and synthesizable, provided the target library contains a matching dual‑port RAM.", "commit_id": "2fc4cde7d269e69c77f784468959779cef2f3a55", "timestamp": "2022-04-01T14:32:46+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "db926e5ef5720189a1c42a5f6274a2365f78c39c", "pr_title": "[ram_2p] Set DataBitsPerMask parameter for prim_ram_2p", "pr_body": "It turned out that with the default value of 1, Vivado infers a separate 18 Kbit BRAM instance for each bit of the 32-bit word for the FPGA examples. This can be very wasteful in terms of resource utilization especially for smaller configurations.\r\n\r\nAs our examples don't use ECC or parity and mainly target simualation and FPGA, it's better to use a value of 8 for the DataBitsPerMask parameter. Vivado will then not distribute words across different BRAM instances which results in more efficient FPGA resource utilization.\r\n\r\nFor a detailed analysis and explanation, please refer to lowRISC/Ibex#1587.", "issue_title": "changing MEM_SIZE does not affect BRAM utilization ", "issue_body": "I wanted to check if 2 KB memory works with IBEX ARTY A7 example. The default is 64 KB with FPGAPowerAnalysis option set to '0' and 256 KB otherwise.\r\n\r\nI changed top_artya7.sv file such as:\r\n// parameter int MEM_SIZE = FPGAPowerAnalysis == 0 ? 64 * 1024 : 256 * 1024;\r\n parameter int MEM_SIZE = 2 * 1024; // use 2 KB RAM for instr & data\r\n\r\nI checked both synthesis results for 64 KB and 2 KB, somehow BRAM utilization numbers are the same: 16\r\n\r\nI checked synth reports (top_artya7.vds) and synth utilization reports (top_artya7_utilization_synth.rpt) and be sure that the parameters related to memory are really consistent according to my changes: \r\n\r\nThe log for 2 KB synth from top_artya7.vds\r\n\r\nINFO: [Synth 8-6157] synthesizing module 'top_artya7' [/home/mbaykenar/ibex_mba/ibex/build/lowrisc_ibex_top_artya7_0.1/src/lowrisc_ibex_top_artya7_0.1/rtl/top_artya7.sv:5]\r\n Parameter FPGAPowerAnalysis bound to: 32'sb00000000000000000000000000000000\r\n Parameter MEM_SIZE bound to: 32'sb00000000000000000000100000000000\r\n Parameter MEM_START bound to: 0 - type: integer\r\n Parameter MEM_MASK bound to: 32'b00000000000000000000011111111111\r\n Parameter SRAMInitFile bound to: ../../../../../examples/sw/led/led.vmem - type: string\r\n\r\nINFO: [Synth 8-6157] synthesizing module 'ram_2p' [/home/mbaykenar/ibex_mba/ibex/build/lowrisc_ibex_top_artya7_0.1/src/lowrisc_ibex_fpga_xilinx_shared_0/rtl/ram_2p.sv:11]\r\n Parameter Depth bound to: 32'sb00000000000000000000001000000000\r\n Parameter MemInitFile bound to: ../../../../../examples/sw/led/led.vmem - type: string\r\n Parameter Aw bound to: 32'sb00000000000000000000000000001001\r\nINFO: [Synth 8-6157] synthesizing module 'prim_ram_2p' [/home/mbaykenar/ibex_mba/ibex/build/lowrisc_ibex_top_artya7_0.1/src/lowrisc_prim_abstract_ram_2p_0/prim_ram_2p.sv:14]\r\n Parameter Width bound to: 32'sb00000000000000000000000000100000\r\n Parameter Depth bound to: 32'sb00000000000000000000001000000000\r\n Parameter DataBitsPerMask bound to: 32'sb00000000000000000000000000000001\r\n Parameter MemInitFile bound to: ../../../../../examples/sw/led/led.vmem - type: string\r\n Parameter Aw bound to: 32'sb00000000000000000000000000001001\r\nINFO: [Synth 8-6157] synthesizing module 'prim_generic_ram_2p' [/home/mbaykenar/ibex_mba/ibex/build/lowrisc_ibex_top_artya7_0.1/src/lowrisc_prim_generic_ram_2p_0/rtl/prim_generic_ram_2p.sv:9]\r\n Parameter Width bound to: 32'sb00000000000000000000000000100000\r\n Parameter Depth bound to: 32'sb00000000000000000000001000000000\r\n Parameter DataBitsPerMask bound to: 32'sb00000000000000000000000000000001\r\n Parameter MemInitFile bound to: ../../../../../examples/sw/led/led.vmem - type: string\r\n Parameter Aw bound to: 32'sb00000000000000000000000000001001\r\n Parameter MaskWidth bound to: 32'sb00000000000000000000000000100000\r\n\r\nThe log for 64 KB synth:\r\n\r\nINFO: [Synth 8-6157] synthesizing module 'top_artya7' [/home/mbaykenar/ibex_mba/ibex/build/lowrisc_ibex_top_artya7_0.1/src/lowrisc_ibex_top_artya7_0.1/rtl/top_artya7.sv:5]\r\n Parameter FPGAPowerAnalysis bound to: 32'sb00000000000000000000000000000000\r\n Parameter MEM_SIZE bound to: 32'sb00000000000000010000000000000000\r\n Parameter MEM_START bound to: 0 - type: integer\r\n Parameter MEM_MASK bound to: 32'b00000000000000001111111111111111\r\n Parameter SRAMInitFile bound to: ../../../../../examples/sw/led/led.vmem - type: string\r\n\r\nINFO: [Synth 8-6157] synthesizing module 'ram_2p' [/home/mbaykenar/ibex_mba/ibex/build/lowrisc_ibex_top_artya7_0.1/src/lowrisc_ibex_fpga_xilinx_shared_0/rtl/ram_2p.sv:11]\r\n Parameter Depth bound to: 32'sb00000000000000000100000000000000\r\n Parameter MemInitFile bound to: ../../../../../examples/sw/led/led.vmem - type: string\r\n Parameter Aw bound to: 32'sb00000000000000000000000000001110\r\nINFO: [Synth 8-6157] synthesizing module 'prim_ram_2p' [/home/mbaykenar/ibex_mba/ibex/build/lowrisc_ibex_top_artya7_0.1/src/lowrisc_prim_abstract_ram_2p_0/prim_ram_2p.sv:14]\r\n Parameter Width bound to: 32'sb00000000000000000000000000100000\r\n Parameter Depth bound to: 32'sb00000000000000000100000000000000\r\n Parameter DataBitsPerMask bound to: 32'sb00000000000000000000000000000001\r\n Parameter MemInitFile bound to: ../../../../../examples/sw/led/led.vmem - type: string\r\n Parameter Aw bound to: 32'sb00000000000000000000000000001110\r\nINFO: [Synth 8-6157] synthesizing module 'prim_generic_ram_2p' [/home/mbaykenar/ibex_mba/ibex/build/lowrisc_ibex_top_artya7_0.1/src/lowrisc_prim_generic_ram_2p_0/rtl/prim_generic_ram_2p.sv:9]\r\n Parameter Width bound to: 32'sb00000000000000000000000000100000\r\n Parameter Depth bound to: 32'sb00000000000000000100000000000000\r\n Parameter DataBitsPerMask bound to: 32'sb00000000000000000000000000000001\r\n Parameter MemInitFile bound to: ../../../../../examples/sw/led/led.vmem - type: string\r\n Parameter Aw bound to: 32'sb00000000000000000000000000001110\r\n Parameter MaskWidth bound to: 32'sb00000000000000000000000000100000\r\n\r\n\r\nI see that the parameters on prim_generic_ram_2p.sv are elaborated correctly:\r\n\r\n2 KB (32-bit * 512 = 2 KB)\r\n Parameter Width bound to: 32'sb00000000000000000000000000100000\r\n Parameter Depth bound to: 32'sb00000000000000000000001000000000\r\n64 KB (32-bit * 16384 = 64 KB)\r\n Parameter Width bound to: 32'sb00000000000000000000000000100000\r\n Parameter Depth bound to: 32'sb00000000000000000100000000000000\r\n\r\nI also checked detailed module level utilization and found out that all the BRAM instances are utilized for ram_2p. The register file utilizes LUT RAMs.\r\n\r\nDo I miss a detail on synthesizing for 2 KB RAM or what can cause inferring same amount of BRAM for 64 KB and 2 KB ?\r\n\r\nRegards,\r\n\r\n## My Environment\r\n\r\n**EDA tool and version:**\r\nVIVADO 2020.2\r\n\r\n**Operating system:**\r\nUBUNTU 20.04\r\n\r\n**Version of the Ibex source code:**\r\n6bb67e20f8a7c670e4baf5fe8f130a5ef360f411\r\n", "commit_message": "[ram_2p] Set DataBitsPerMask parameter for prim_ram_2p\n\nIt turned out that with the default value of 1, Vivado infers a separate\n18 Kbit BRAM instance for each bit of the 32-bit word for the FPGA\nexamples. This can be very wasteful in terms of resource utilization\nespecially for smaller configurations.\n\nAs our examples don't use ECC or parity and mainly target simualation\nand FPGA, it's better to use a value of 8 for the DataBitsPerMask\nparameter. Vivado will then not distribute words across different BRAM\ninstances which results in more efficient FPGA resource utilization.\n\nFor a detailed analysis and explanation, please refer to\nlowRISC/Ibex#1587.\n\nSigned-off-by: Pirmin Vogel ", "fix_patch": "diff --git a/shared/rtl/ram_2p.sv b/shared/rtl/ram_2p.sv\nindex e4cf238cad..52ff15598e 100644\n--- a/shared/rtl/ram_2p.sv\n+++ b/shared/rtl/ram_2p.sv\n@@ -68,6 +68,7 @@ module ram_2p #(\n prim_ram_2p #(\n .Width(32),\n .Depth(Depth),\n+ .DataBitsPerMask(8),\n .MemInitFile(MemInitFile)\n ) u_ram (\n .clk_a_i (clk_i),\n", "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 * Dual-port RAM with 1 cycle read/write delay, 32 bit words.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ram_2p #(\n parameter int Depth = 128,\n parameter MemInitFile = \"\"\n) (\n input clk_i,\n input rst_ni,\n\n input a_req_i,\n input a_we_i,\n input [ 3:0] a_be_i,\n input [31:0] a_addr_i,\n input [31:0] a_wdata_i,\n output logic a_rvalid_o,\n output logic [31:0] a_rdata_o,\n\n input b_req_i,\n input b_we_i,\n input [ 3:0] b_be_i,\n input [31:0] b_addr_i,\n input [31:0] b_wdata_i,\n output logic b_rvalid_o,\n output logic [31:0] b_rdata_o\n);\n\n localparam int Aw = $clog2(Depth);\n\n logic [Aw-1:0] a_addr_idx;\n assign a_addr_idx = a_addr_i[Aw-1+2:2];\n logic [31-Aw:0] unused_a_addr_parts;\n assign unused_a_addr_parts = {a_addr_i[31:Aw+2], a_addr_i[1:0]};\n\n logic [Aw-1:0] b_addr_idx;\n assign b_addr_idx = b_addr_i[Aw-1+2:2];\n logic [31-Aw:0] unused_b_addr_parts;\n assign unused_b_addr_parts = {b_addr_i[31:Aw+2], b_addr_i[1:0]};\n\n // Convert byte mask to SRAM bit mask.\n logic [31:0] a_wmask;\n logic [31:0] b_wmask;\n always_comb begin\n for (int i = 0 ; i < 4 ; i++) begin\n // mask for read data\n a_wmask[8*i+:8] = {8{a_be_i[i]}};\n b_wmask[8*i+:8] = {8{b_be_i[i]}};\n end\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n a_rvalid_o <= '0;\n b_rvalid_o <= '0;\n end else begin\n a_rvalid_o <= a_req_i;\n b_rvalid_o <= b_req_i;\n end\n end\n\n prim_ram_2p #(\n .Width(32),\n .Depth(Depth),\n .DataBitsPerMask(8),\n .MemInitFile(MemInitFile)\n ) u_ram (\n .clk_a_i (clk_i),\n .clk_b_i (clk_i),\n .cfg_i ('0),\n .a_req_i (a_req_i),\n .a_write_i (a_we_i),\n .a_addr_i (a_addr_idx),\n .a_wdata_i (a_wdata_i),\n .a_wmask_i (a_wmask),\n .a_rdata_o (a_rdata_o),\n .b_req_i (b_req_i),\n .b_write_i (b_we_i),\n .b_wmask_i (b_wmask),\n .b_addr_i (b_addr_idx),\n .b_wdata_i (b_wdata_i),\n .b_rdata_o (b_rdata_o)\n );\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/load_store_unit.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1326, "lang": "sv", "rtl_files": ["rtl/ibex_compressed_decoder.sv"], "spec": "# Behavioral Design Specification: Compressed Instruction Decoder\n\n## Overview\n\nThe compressed instruction decoder transforms 16‑bit RISC‑V compressed (C‑extension) instructions into their equivalent 32‑bit uncompressed forms. It is a purely combinatorial module: all outputs are determined solely by the current input instruction and must be valid in the same cycle. The module also indicates whether the incoming instruction is compressed and whether it represents an illegal encoding.\n\n## Inputs and Outputs\n\n### Inputs\n\n- **Instruction word** (32 bits): The raw fetched instruction, which may be either a 16‑bit compressed instruction (placed in the lower 16 bits, bits [15:0]) or a standard 32‑bit uncompressed instruction.\n- **Valid indication** (1 bit): When asserted, the module’s behavior is fully defined and all assertions about the input are expected to hold. This signal is used only for formal verification purposes and does not influence any functional output.\n\n### Outputs\n\n- **Decoded instruction** (32 bits): For a compressed instruction, this is the equivalent 32‑bit uncompressed instruction. For an uncompressed instruction, this output reflects the input instruction unchanged. The output must always be a valid instruction encoding (either the original or the transformed one).\n- **Compressed flag** (1 bit): Indicates whether the input instruction is a compressed instruction (as defined by the low two bits).\n- **Illegal instruction flag** (1 bit): Asserted when the input instruction is a compressed instruction that is reserved, has an illegal immediate value, or is otherwise not a valid RISC‑V compressed instruction. For uncompressed instructions this flag must be cleared.\n\n## Functional Behavior\n\n### Detection of Compressed Instructions\n\nA compressed instruction is identified by the two least‑significant bits of the input instruction not being `11`. \n\n- If `instr[1:0] != 2'b11`, the module must:\n - Set the compressed flag to 1.\n - Decode the instruction according to the rules below.\n- Otherwise (bits `11`), the instruction is considered a standard 32‑bit uncompressed instruction. The module must:\n - Set the compressed flag to 0.\n - Pass the input instruction through unmodified as the decoded output.\n - Clear the illegal instruction flag.\n\n### Decoding of Compressed Instructions\n\nThe decoder supports all mandatory and most optional compressed instructions from the RISC‑V C extension (RV32C). The decoding is performed based on the quadrants and sub‑fields defined by the standard. The following subsections specify the required behavior for each major encoding group.\n\n#### Quadrant C0 (`inst[1:0] = 00`)\n\n- **c.addi4spn** (`inst[15:13] = 000`): Decode into an `ADDI` instruction with destination register `rd'` (from bits [4:2]), source register `x2`, and an immediate formed from bits [12:5]. If the immediate value is all zeros, the instruction is illegal and the illegal flag must be asserted.\n- **c.lw** (`inst[15:13] = 010`): Decode into a `LW` instruction with destination register `rd'`, base address in `rs1'`, and an offset formed from bits [5,12:10,6].\n- **c.sw** (`inst[15:13] = 110`): Decode into a `SW` instruction with source register `rs2'`, base address in `rs1'`, and an offset formed from bits [5,12,4:2,11:10,6].\n- All other values of `inst[15:13]` in this quadrant are reserved and must cause the illegal flag to be asserted.\n\n#### Quadrant C1 (`inst[1:0] = 01`)\n\n- **c.addi / c.nop** (`inst[15:13] = 000`): Decode into an `ADDI` instruction using the same register for source and destination, with a sign‑extended immediate. When all register and immediate bits are zero, this corresponds to the `NOP` instruction (no special handling required).\n- **c.jal** (`inst[15:13] = 001`): Decode into a `JAL` instruction with destination register `x1` and a target offset formed from the instruction’s immediate field.\n- **c.li** (`inst[15:13] = 010`): Decode into an `ADDI` instruction with source register `x0` and destination as given, using the sign‑extended immediate.\n- **c.lui / c.addi16sp** (`inst[15:13] = 011`):\n - If the destination register is `x2`, this is **c.addi16sp**: decode into an `ADDI` instruction modifying `x2` with an immediate formed from bits [12,4:3,5,2,6].\n - Otherwise, decode into a `LUI` instruction with the immediate formed from bits [12,6:2].\n - In both cases, if the immediate is all‑zeros, the instruction is illegal.\n- **c.srli / c.srai** (`inst[15:13] = 100`, `inst[11:10] = 00` or `01`): Decode into a shift‑right instruction (`SRLI` or `SRAI`) with both source and destination being register `rd'`. If bit 12 is set, the instruction is illegal.\n- **c.andi** (`inst[15:13] = 100`, `inst[11:10] = 10`): Decode into an `ANDI` instruction with the sign‑extended immediate.\n- **c.sub, c.xor, c.or, c.and** (`inst[15:13] = 100`, `inst[11:10] = 11`): Decode into the corresponding register‑register ALU operations using the `rd'` and `rs2'` fields. The specific operation is determined by bits [12,6:5]. Encodings with [12,6:5] = `10x` or `11x` are reserved and must be flagged as illegal.\n- **c.beqz / c.bnez** (`inst[15:13] = 110` or `111`): Decode into a branch instruction (`BEQ` for `110`, `BNE` for `111`) comparing `rs1'` with zero, with an offset formed from the instruction’s immediate.\n\n#### Quadrant C2 (`inst[1:0] = 10`)\n\n- **c.slli** (`inst[15:13] = 000`): Decode into a `SLLI` instruction. If bit 12 is set, the instruction is illegal (reserved for custom extensions).\n- **c.lwsp** (`inst[15:13] = 010`): Decode into a `LW` instruction with base register `x2`. If the destination register is zero, the instruction is illegal.\n- **c.mv / c.jr / c.add / c.jalr / c.ebreak** (`inst[15:13] = 100`): \n The behavior depends on bits [12] and [6:2]:\n - If `inst[12] = 0`:\n - If `inst[6:2]` is non‑zero: decode into an `ADD` instruction (c.mv) with destination = `inst[11:7]` and source = `inst[6:2]`.\n - If `inst[6:2]` is zero: decode into a `JALR` instruction (c.jr) with source register `inst[11:7]`, immediate zero, and destination `x0`. If the source register is also zero, the instruction is illegal.\n - If `inst[12] = 1`:\n - If `inst[6:2]` is non‑zero: decode into an `ADD` instruction (c.add) with destination = `inst[11:7]` and both source registers equal to the same register.\n - If `inst[6:2]` is zero:\n - If `inst[11:7]` is zero: decode into an `EBREAK` instruction.\n - Otherwise: decode into a `JALR` instruction (c.jalr) with source register `inst[11:7]`, immediate zero, and destination `x1`.\n- **c.swsp** (`inst[15:13] = 110`): Decode into a `SW` instruction with base register `x2`.\n\nAll other encodings in quadrant C2 (`inst[15:13]` values not covered above) are reserved and must assert the illegal flag.\n\n### Illegal Instruction Detection\n\nThe module must assert the illegal instruction output whenever:\n1. A compressed instruction encoding falls into a reserved or custom‑extension space (e.g., all undefined quadrants, unused sub‑fields, or bit 12 set in shift‑by‑immediate instructions).\n2. A compressed instruction has an immediate value that the RISC‑V specification defines as invalid (e.g., all‑zeros for `c.addi4spn`, all‑zeros for `c.lui`/`c.addi16sp`, zero register for `c.jr` or `c.lwsp`).\n\nFor all other cases, including all valid compressed instructions and all uncompressed instructions, the illegal flag must be cleared.\n\n### Additional Notes\n\n- The module performs **no register address validation** for the RV32E subset. Any necessary checks on the register fields (e.g., ensuring that only registers x0–x15 are used for the compressed register specifiers `rd'`, `rs1'`, `rs2'`) are expected to be performed later in the instruction decoder pipeline.\n- The module’s behavior is entirely combinational; it must not depend on any internal state, clock edges, or reset conditions. Clock and reset inputs are present only to support formal assertion checks.\n- All asserted outputs must be stable and glitch‑free while the input instruction is stable. There is no latency: the decoded instruction, compressed flag, and illegal flag are available in the same cycle as the input.", "commit_id": "8d37af2751a25cffd50d09d91845cf2c111f39b3", "timestamp": "2021-04-06T16:22:56+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "a799a92e5eef5fbaa7b2a3054c88e5e48260f04f", "pr_title": "[rtl] Add SVA to ensure valid_i in compressed decoder is known", "pr_body": "This signal is used to gate several assertions related to unknown/invalid selector signals. We want to be sure to catch any X\r\nvalues entering the compressed decoder and ultimately ID.\r\n\r\nThis is related to lowRISC/Ibex#540.", "issue_title": "Check how X values end up in C decoder", "issue_body": "Currently, X values can end up in the C decoder when the IF stage does not have a valid instruction. This requires the assertions in the C decoder to be qualified with `instr_valid` (see #536).\r\n\r\nWe allow X values for uninitialized memories and the DV environment can drive them on the external bus. It seems that the X can come from both the uninitialized flops in the prefetch buffer (`ibex_fetch_fifo.sv`) or the bus signal directly, or a combination of the two (depending on the requested address, and FIFO fill status).\r\n\r\nWe need to understand where exactly these X come from in this particular case.\r\n\r\n", "commit_message": "[rtl] Add SVA to ensure valid_i in compressed decoder is known\n\nThis signal is used to gate several assertions related to\nunknown/invalid selector signals. We want to be sure to catch any X\nvalues entering the compressed decoder and ultimately ID.\n\nThis is related to lowRISC/Ibex#540.\n\nSigned-off-by: Pirmin Vogel ", "fix_patch": "diff --git a/rtl/ibex_compressed_decoder.sv b/rtl/ibex_compressed_decoder.sv\nindex 12a487fe1d..ec694f51cb 100644\n--- a/rtl/ibex_compressed_decoder.sv\n+++ b/rtl/ibex_compressed_decoder.sv\n@@ -282,6 +282,9 @@ module ibex_compressed_decoder (\n // Assertions //\n ////////////////\n \n+ // The valid_i signal used to gate below assertions must be known.\n+ `ASSERT_KNOWN(IbexInstrValidKnown, valid_i)\n+\n // Selectors must be known/valid.\n `ASSERT(IbexInstrLSBsKnown, valid_i |->\n !$isunknown(instr_i[1:0]))\n", "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 * Compressed instruction decoder\n *\n * Decodes RISC-V compressed instructions into their RV32 equivalent.\n * This module is fully combinatorial, clock and reset are used for\n * assertions only.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_compressed_decoder (\n input logic clk_i,\n input logic rst_ni,\n input logic valid_i,\n input logic [31:0] instr_i,\n output logic [31:0] instr_o,\n output logic is_compressed_o,\n output logic illegal_instr_o\n);\n import ibex_pkg::*;\n\n // valid_i indicates if instr_i is valid and is used for assertions only.\n // The following signal is used to avoid possible lint errors.\n logic unused_valid;\n assign unused_valid = valid_i;\n\n ////////////////////////\n // Compressed decoder //\n ////////////////////////\n\n always_comb begin\n // By default, forward incoming instruction, mark it as legal.\n instr_o = instr_i;\n illegal_instr_o = 1'b0;\n\n // Check if incoming instruction is compressed.\n unique case (instr_i[1:0])\n // C0\n 2'b00: begin\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.addi4spn -> addi rd', x2, imm\n instr_o = {2'b0, instr_i[10:7], instr_i[12:11], instr_i[5],\n instr_i[6], 2'b00, 5'h02, 3'b000, 2'b01, instr_i[4:2], {OPCODE_OP_IMM}};\n if (instr_i[12:5] == 8'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b010: begin\n // c.lw -> lw rd', imm(rs1')\n instr_o = {5'b0, instr_i[5], instr_i[12:10], instr_i[6],\n 2'b00, 2'b01, instr_i[9:7], 3'b010, 2'b01, instr_i[4:2], {OPCODE_LOAD}};\n end\n\n 3'b110: begin\n // c.sw -> sw rs2', imm(rs1')\n instr_o = {5'b0, instr_i[5], instr_i[12], 2'b01, instr_i[4:2],\n 2'b01, instr_i[9:7], 3'b010, instr_i[11:10], instr_i[6],\n 2'b00, {OPCODE_STORE}};\n end\n\n 3'b001,\n 3'b011,\n 3'b100,\n 3'b101,\n 3'b111: begin\n illegal_instr_o = 1'b1;\n end\n\n default: begin\n illegal_instr_o = 1'b1;\n end\n endcase\n end\n\n // C1\n //\n // Register address checks for RV32E are performed in the regular instruction decoder.\n // If this check fails, an illegal instruction exception is triggered and the controller\n // writes the actual faulting instruction to mtval.\n 2'b01: begin\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.addi -> addi rd, rd, nzimm\n // c.nop\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2],\n instr_i[11:7], 3'b0, instr_i[11:7], {OPCODE_OP_IMM}};\n end\n\n 3'b001, 3'b101: begin\n // 001: c.jal -> jal x1, imm\n // 101: c.j -> jal x0, imm\n instr_o = {instr_i[12], instr_i[8], instr_i[10:9], instr_i[6],\n instr_i[7], instr_i[2], instr_i[11], instr_i[5:3],\n {9 {instr_i[12]}}, 4'b0, ~instr_i[15], {OPCODE_JAL}};\n end\n\n 3'b010: begin\n // c.li -> addi rd, x0, nzimm\n // (c.li hints are translated into an addi hint)\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2], 5'b0,\n 3'b0, instr_i[11:7], {OPCODE_OP_IMM}};\n end\n\n 3'b011: begin\n // c.lui -> lui rd, imm\n // (c.lui hints are translated into a lui hint)\n instr_o = {{15 {instr_i[12]}}, instr_i[6:2], instr_i[11:7], {OPCODE_LUI}};\n\n if (instr_i[11:7] == 5'h02) begin\n // c.addi16sp -> addi x2, x2, nzimm\n instr_o = {{3 {instr_i[12]}}, instr_i[4:3], instr_i[5], instr_i[2],\n instr_i[6], 4'b0, 5'h02, 3'b000, 5'h02, {OPCODE_OP_IMM}};\n end\n\n if ({instr_i[12], instr_i[6:2]} == 6'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b100: begin\n unique case (instr_i[11:10])\n 2'b00,\n 2'b01: begin\n // 00: c.srli -> srli rd, rd, shamt\n // 01: c.srai -> srai rd, rd, shamt\n // (c.srli/c.srai hints are translated into a srli/srai hint)\n instr_o = {1'b0, instr_i[10], 5'b0, instr_i[6:2], 2'b01, instr_i[9:7],\n 3'b101, 2'b01, instr_i[9:7], {OPCODE_OP_IMM}};\n if (instr_i[12] == 1'b1) illegal_instr_o = 1'b1;\n end\n\n 2'b10: begin\n // c.andi -> andi rd, rd, imm\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2], 2'b01, instr_i[9:7],\n 3'b111, 2'b01, instr_i[9:7], {OPCODE_OP_IMM}};\n end\n\n 2'b11: begin\n unique case ({instr_i[12], instr_i[6:5]})\n 3'b000: begin\n // c.sub -> sub rd', rd', rs2'\n instr_o = {2'b01, 5'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7],\n 3'b000, 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b001: begin\n // c.xor -> xor rd', rd', rs2'\n instr_o = {7'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7], 3'b100,\n 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b010: begin\n // c.or -> or rd', rd', rs2'\n instr_o = {7'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7], 3'b110,\n 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b011: begin\n // c.and -> and rd', rd', rs2'\n instr_o = {7'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7], 3'b111,\n 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b100,\n 3'b101,\n 3'b110,\n 3'b111: begin\n // 100: c.subw\n // 101: c.addw\n illegal_instr_o = 1'b1;\n end\n\n default: begin\n illegal_instr_o = 1'b1;\n end\n endcase\n end\n\n default: begin\n illegal_instr_o = 1'b1;\n end\n endcase\n end\n\n 3'b110, 3'b111: begin\n // 0: c.beqz -> beq rs1', x0, imm\n // 1: c.bnez -> bne rs1', x0, imm\n instr_o = {{4 {instr_i[12]}}, instr_i[6:5], instr_i[2], 5'b0, 2'b01,\n instr_i[9:7], 2'b00, instr_i[13], instr_i[11:10], instr_i[4:3],\n instr_i[12], {OPCODE_BRANCH}};\n end\n\n default: begin\n illegal_instr_o = 1'b1;\n end\n endcase\n end\n\n // C2\n //\n // Register address checks for RV32E are performed in the regular instruction decoder.\n // If this check fails, an illegal instruction exception is triggered and the controller\n // writes the actual faulting instruction to mtval.\n 2'b10: begin\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.slli -> slli rd, rd, shamt\n // (c.ssli hints are translated into a slli hint)\n instr_o = {7'b0, instr_i[6:2], instr_i[11:7], 3'b001, instr_i[11:7], {OPCODE_OP_IMM}};\n if (instr_i[12] == 1'b1) illegal_instr_o = 1'b1; // reserved for custom extensions\n end\n\n 3'b010: begin\n // c.lwsp -> lw rd, imm(x2)\n instr_o = {4'b0, instr_i[3:2], instr_i[12], instr_i[6:4], 2'b00, 5'h02,\n 3'b010, instr_i[11:7], OPCODE_LOAD};\n if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b100: begin\n if (instr_i[12] == 1'b0) begin\n if (instr_i[6:2] != 5'b0) begin\n // c.mv -> add rd/rs1, x0, rs2\n // (c.mv hints are translated into an add hint)\n instr_o = {7'b0, instr_i[6:2], 5'b0, 3'b0, instr_i[11:7], {OPCODE_OP}};\n end else begin\n // c.jr -> jalr x0, rd/rs1, 0\n instr_o = {12'b0, instr_i[11:7], 3'b0, 5'b0, {OPCODE_JALR}};\n if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n end\n end else begin\n if (instr_i[6:2] != 5'b0) begin\n // c.add -> add rd, rd, rs2\n // (c.add hints are translated into an add hint)\n instr_o = {7'b0, instr_i[6:2], instr_i[11:7], 3'b0, instr_i[11:7], {OPCODE_OP}};\n end else begin\n if (instr_i[11:7] == 5'b0) begin\n // c.ebreak -> ebreak\n instr_o = {32'h00_10_00_73};\n end else begin\n // c.jalr -> jalr x1, rs1, 0\n instr_o = {12'b0, instr_i[11:7], 3'b000, 5'b00001, {OPCODE_JALR}};\n end\n end\n end\n end\n\n 3'b110: begin\n // c.swsp -> sw rs2, imm(x2)\n instr_o = {4'b0, instr_i[8:7], instr_i[12], instr_i[6:2], 5'h02, 3'b010,\n instr_i[11:9], 2'b00, {OPCODE_STORE}};\n end\n\n 3'b001,\n 3'b011,\n 3'b101,\n 3'b111: begin\n illegal_instr_o = 1'b1;\n end\n\n default: begin\n illegal_instr_o = 1'b1;\n end\n endcase\n end\n\n // Incoming instruction is not compressed.\n 2'b11:;\n\n default: begin\n illegal_instr_o = 1'b1;\n end\n endcase\n end\n\n assign is_compressed_o = (instr_i[1:0] != 2'b11);\n\n ////////////////\n // Assertions //\n ////////////////\n\n // The valid_i signal used to gate below assertions must be known.\n `ASSERT_KNOWN(IbexInstrValidKnown, valid_i)\n\n // Selectors must be known/valid.\n `ASSERT(IbexInstrLSBsKnown, valid_i |->\n !$isunknown(instr_i[1:0]))\n `ASSERT(IbexC0Known1, (valid_i && (instr_i[1:0] == 2'b00)) |->\n !$isunknown(instr_i[15:13]))\n `ASSERT(IbexC1Known1, (valid_i && (instr_i[1:0] == 2'b01)) |->\n !$isunknown(instr_i[15:13]))\n `ASSERT(IbexC1Known2, (valid_i && (instr_i[1:0] == 2'b01) && (instr_i[15:13] == 3'b100)) |->\n !$isunknown(instr_i[11:10]))\n `ASSERT(IbexC1Known3, (valid_i &&\n (instr_i[1:0] == 2'b01) && (instr_i[15:13] == 3'b100) && (instr_i[11:10] == 2'b11)) |->\n !$isunknown({instr_i[12], instr_i[6:5]}))\n `ASSERT(IbexC2Known1, (valid_i && (instr_i[1:0] == 2'b10)) |->\n !$isunknown(instr_i[15:13]))\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/instruction_decode_execute.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1620, "lang": "sv", "rtl_files": ["rtl/ibex_pkg.sv"], "spec": "# Behavioral Design Specification for the Ibex RISC-V Core\n\n## 1. Purpose and Overview\n\nThe Ibex core is a 32-bit RISC-V processor implementing the RV32I base instruction set. It supports optional extensions: integer multiplication and division (M), compressed instructions (C), bit manipulation (B), and control and status register access (Zicsr). The core is designed for embedded and security-critical applications.\n\nThe core executes instructions in a two-stage pipeline (Instruction Fetch, Instruction Decode and Execute). All instructions complete in a minimum of two cycles, with multi-cycle instructions stalling the decode/execute stage. The core supports Machine (M) and User (U) privilege modes.\n\n## 2. Instruction Set Support\n\nThe core shall implement the following RISC-V instruction sets:\n\n- **RV32I**: All base integer instructions (including Zifencei for instruction-fence and Zicsr for CSR access).\n- **RV32M** (optional): Multiply and divide instructions, configurable via parameter to one of four variants: none, slow, fast, single‑cycle.\n- **RV32C** (optional): Compressed instructions (16‑bit).\n- **RV32B** (optional): Bit‑manipulation extension, configurable as balanced, OTEarlGrey, or full version.\n\nThe core shall correctly execute all defined opcodes and generate an illegal instruction exception for any unsupported opcode or combination.\n\n## 3. Pipeline Behavior\n\nThe core uses a two‑stage pipeline:\n\n- **Instruction Fetch (IF)** \n Fetches instructions from memory via a prefetch buffer. It can fetch one instruction per cycle if the instruction memory interface permits. The fetch address is supplied by the core's program counter, which is updated on every branch, jump, or exception.\n\n- **Instruction Decode and Execute (ID/EX)** \n Decodes the fetched instruction and executes it in the same cycle. Register file read and write occur in this stage. Multi‑cycle instructions (e.g., load/store, multiply, divide) stall the ID/EX stage until completion. The maximum instruction throughput is one instruction per cycle.\n\n### 3.1 Multi-Cycle Instructions\n\nThe following instruction types have specific stall counts:\n\n| Instruction Type | Stall Cycles (minimum) | Remarks |\n| -------------------------------------------------- | ---------------------- | --------------------------------------- |\n| Integer computational (RV32I) | 0 | Single‑cycle |\n| CSR access (Zicsr) | 0 | Single‑cycle |\n| Load / Store | 1 – N | Depends on data memory latency |\n| Multiply (single‑cycle variant) | 0 (MUL), 1 (MULH) | |\n| Multiply (fast multi‑cycle) | 2 (MUL), 3 (MULH) | |\n| Multiply (slow multi‑cycle) | `clog2(op)` / 32 | |\n| Divide / Remainder | 1 or 37 | 1 if divide‑by‑zero, else 37 |\n| Jump (JAL, JALR) | 1 – N | Instruction memory latency |\n| Branch (not taken) | 0 | No stall |\n| Branch (taken) | 2 – N | Additional cycle for target calculation |\n| FENCE.I | 1 – N | Behaves as a jump |\n\nIf a branch target ALU is enabled (parameter), taken branches stall only 1 – N cycles.\n\n### 3.2 Pipeline Hazards\n\n- **Register file**: Two read ports, one write port. No data forwarding; a read of a register being written in the same cycle returns the old value.\n- **Control hazards**: Branches and jumps flush the IF stage and prefetch buffer. The new instruction is fetched from the target address.\n- **Data hazards**: For loads, the destination register is written in the same cycle the load data arrives from memory. Subsequent instructions that read that register must wait until the load completes (load‑use hazard handled by stalling).\n\n## 4. Register File\n\nThe register file contains 31 general‑purpose registers (x1–x31). Register x0 is hardwired to zero and may be read but not written. The core may optionally implement the RV32E extension (15 registers). Three implementation flavors are available:\n\n- Flip‑flop based (default)\n- FPGA RAM based (uses synchronous write, asynchronous read)\n- Latch based (for ASIC, requires specific clock gating)\n\nThe register file shall provide the written data within the same cycle as the write enable. Read data shall be available in the same cycle as the read address is presented.\n\n## 5. Control and Status Registers (CSRs)\n\nThe core implements the following CSRs as defined in the RISC‑V Privileged Specification v1.11. All CSR accesses are performed in a single cycle. The access type (WARL, WLRL, RW, R) is as documented.\n\n### 5.1 Machine‑Level CSRs\n\n- `mstatus` (0x300): Machine status – contains MIE, MPIE, MPP, MPRV, TW bits. Only M‑ and U‑mode supported.\n- `misa` (0x301): Machine ISA – hardwired to indicate supported extensions.\n- `mie` (0x304): Machine interrupt enable – per‑interrupt enables.\n- `mtvec` (0x305): Machine trap vector – BASE (aligned to 256 bytes) and MODE (fixed to vectored mode, 2’b01).\n- `mepc` (0x341): Exception program counter – updated on traps, used by MRET.\n- `mcause` (0x342): Exception cause – bit 31 indicates interrupt; lower bits indicate cause code.\n- `mtval` (0x343): Trap value – holds faulting address for load/store errors, faulting instruction for illegal instruction, else zero.\n- `mip` (0x344): Interrupt pending – read‑only, reflects enabled and asserted interrupt lines.\n- `mscratch` (0x340): Scratch register.\n- `mcountinhibit` (0x320): Control to enable/disable cycle and event counters.\n- `mhpmevent3..31` (0x323..0x33F): Event selectors for performance counters.\n- `mcycle` (0xB00), `minstret` (0xB02): Cycle and instruction counters (64‑bit via ...H CSR).\n- `mhpmcounter3..31` (0xB03..0xB1F): Performance event counters (64‑bit via ...H).\n- `mvendorid` (0xF11), `marchid` (0xF12), `mimpid` (0xF13), `mhartid` (0xF14): Read‑only identification registers. `mhartid` reflects the `hart_id_i` input.\n\n### 5.2 Physical Memory Protection CSRs\n\n- `pmpcfg0..3` (0x3A0..0x3A3): Configuration for up to 16 PMP regions.\n- `pmpaddr0..15` (0x3B0..0x3BF): Address registers for PMP regions.\n- `mseccfg` (0x747), `mseccfgh` (0x757): Machine security configuration (ePMP). Only lower 3 bits used; upper bits read zero. Accessible only when PMP is enabled.\n\n### 5.3 Debug CSRs\n\n- `tselect` (0x7A0), `tdata1` (0x7A1), `tdata2` (0x7A2), `tdata3` (0x7A3): Debug trigger registers (optional, accessible only in Debug Mode or M‑Mode with trigger support).\n- `dcsr` (0x7B0): Debug control and status – accessible only in Debug Mode.\n- `dpc` (0x7B1): Debug PC – updated when entering Debug Mode, used when resuming.\n- `dscratch0` (0x7B2), `dscratch1` (0x7B3): Debug scratch registers, accessible only in Debug Mode.\n\n### 5.4 Custom CSRs\n\n- `cpuctrl` (0x7C0): CPU control – fields for ICache enable, data independent timing, dummy instruction insertion, double‑fault detection. Accessible in M‑Mode.\n- `secureseed` (0x7C1): Write‑only seed for security LFSRs; reads return zero. Accessible in M‑Mode.\n\n### 5.5 CSR Access Rules\n\n- Reads of unimplemented CSR addresses shall cause an illegal instruction exception.\n- Writes to read‑only registers shall be ignored (no exception, but values unchanged).\n- WARL registers shall implement only the specified writable bits; writing reserved bits is ignored.\n- Access to Debug‑only CSRs from M‑Mode (when not in Debug Mode) shall cause an illegal instruction exception.\n\n## 6. Exception and Interrupt Handling\n\n### 6.1 Exceptions\n\nThe core shall take the following synchronous exceptions:\n\n- Instruction access fault (cause 1)\n- Illegal instruction (cause 2)\n- Breakpoint (cause 3)\n- Load access fault (cause 5)\n- Store access fault (cause 7)\n- Environment call from U‑Mode (cause 8)\n- Environment call from M‑Mode (cause 11)\n\nAll exceptions are taken immediately. On exception, the core:\n1. Saves the current PC into `mepc`.\n2. Saves the current privilege mode into `mstatus.MPP`.\n3. Saves the current interrupt‑enable state into `mstatus.MPIE`.\n4. Disables interrupts (`mstatus.MIE = 0`).\n5. Sets the PC to the base address in `mtvec` (vectored mode: for interrupts, base + 4×interrupt ID; for exceptions, base).\n6. Sets `mcause` and, where applicable, `mtval`.\n\n### 6.2 Interrupts\n\nThe core supports the following interrupt sources:\n\n| Signal | ID | Description |\n| ------------------- | --- | --------------------------------- |\n| `irq_nm_i` | 31 | Non‑maskable interrupt (NMI) |\n| `irq_fast_i[14:0]` | 30..16 | Fast local interrupts |\n| `irq_external_i` | 11 | Platform‑level interrupt |\n| `irq_timer_i` | 7 | Timer interrupt |\n| `irq_software_i` | 3 | Software interrupt |\n\nInterrupts are level‑sensitive. The core samples interrupt inputs each cycle. An interrupt is taken only if:\n- Global interrupt enable (`mstatus.MIE`) is 1.\n- Corresponding enable bit in `mie` is 1.\n- The interrupt is pending (input asserted).\n- The core is not in Debug Mode.\n- The core is not already handling an NMI (for non‑NMI interrupts; NMI is taken regardless of `mstatus.MIE`).\n\nPriority order (highest first): NMI (31), fast interrupts (30..16), external (11), timer (7), software (3). Among fast interrupts, lower ID has higher priority.\n\nNMI is always taken when asserted, even if in an interrupt handler, but is ignored if already handling an NMI (no nesting). NMI cause is 0x8000001F.\n\nInternal interrupts (e.g., load integrity error) also behave as NMI with specific cause codes.\n\n### 6.3 Trap Handling\n\nWhen an exception or interrupt is taken, the core enters M‑Mode and jumps to the trap vector. `mstatus.MIE` is cleared to prevent further interrupts. The handler can re‑enable interrupts by writing to `mstatus.MIE`. The `MRET` instruction restores the PC from `mepc` and restores `mstatus.MIE` from `mstatus.MPIE` and privilege mode from `mstatus.MPP`.\n\n### 6.4 Double‑Fault Detection\n\nThe core monitors for synchronous exceptions occurring while another synchronous exception is being handled (i.e., while `cpuctrl.sync_exc_seen` is set). If a second synchronous exception occurs, `cpuctrl.double_fault_seen` is set and the `double_fault_seen_o` output is pulsed high. `sync_exc_seen` is set on any synchronous exception and cleared on `MRET`. This mechanism provides software visibility into double faults.\n\n## 7. Debug Support\n\nThe core supports external debug according to the RISC‑V Debug Specification v0.13. The debug interface consists of:\n\n- **Debug request** (`debug_req_i`): When asserted, the core shall enter Debug Mode at the next appropriate point (instruction boundary, after completing current instruction).\n- **Debug Mode**: A special privilege mode where the core executes from the Debug Module. In Debug Mode:\n - All interrupts (including NMI) are ignored.\n - Debug CSRs (`dcsr`, `dpc`, `dscratch0/1`) are accessible.\n - The core resumes normal execution when the Debug Module issues a resume request (via the interface).\n\nThe core implements optional hardware breakpoints (triggers) configurable via `tselect`, `tdata1`, `tdata2`. When a trigger matches, the core enters Debug Mode (if `action` field is set accordingly). Only instruction‑address match triggers are supported (execute matching). The number of triggers is parameterizable.\n\nDebug Mode entry sets `dcsr.cause` to the reason (EBREAK, trigger, halt request, single step) and saves the current PC into `dpc`.\n\n## 8. Physical Memory Protection (PMP)\n\nThe core may be configured with up to 16 PMP regions. PMP checking is applied to instruction fetches and load/store accesses. The PMP unit enforces read/write/execute permissions according to the RISC‑V Privileged Specification and the optional Smepmp extensions (ePMP).\n\n- When PMP is disabled, all PMP CSRs read as zero and no checking is performed.\n- PMP address matching supports OFF, TOR, NA4 (if granularity=0), and NAPOT modes.\n- The granularity parameter increases minimum region size; NA4 is unavailable when granularity > 0.\n- ePMP features (RLB, MMWP, MML) are available when PMP is enabled; they modify the interpretation of PMP configuration bits.\n\nIf a PMP check fails, the access is not performed externally. The error is reported to the core as an access fault exception (instruction, load, or store). The faulting address is captured in `mtval` when applicable.\n\n## 9. Security Features\n\nWhen the `SecureIbex` parameter is set, the core provides additional security mechanisms:\n\n- **Data‑independent timing**: When enabled via `cpuctrl.data_ind_timing`, all instructions (including branches, multiply, divide) shall execute with constant timing regardless of operand values.\n- **Dummy instruction insertion**: When enabled via `cpuctrl.dummy_instr_en`, the core randomly inserts dummy instructions (multiply/divide) to obfuscate execution timing and power. The insertion interval is controlled by `cpuctrl.dummy_instr_mask` and an internal LFSR. Software may reseed the LFSR via the `secureseed` CSR.\n- **Bus integrity checking**: Incoming instruction and data bus data are verified against checkbits (ECC or parity). On mismatch, a bus major alert is raised and the data is not used (for loads, the destination register write is suppressed).\n- **Register file ECC**: All register file reads are ECC‑protected. Detected errors trigger a major alert; correction is not attempted.\n- **Hardened PC**: The core checks that the PC increments correctly; mismatch triggers a major alert.\n- **Shadow CSRs**: Critical CSRs (`mstatus`, `mtvec`, `cpuctrl`, PMP config) have duplicate shadow copies that are continuously compared to detect glitches; mismatch triggers a major alert.\n- **Dual core lockstep**: When configured, a shadow core executes using delayed inputs; its outputs are compared against the main core outputs. Any mismatch triggers a major alert.\n\nThe core provides three alert outputs: major internal, major bus, and minor. Minor alerts are used for recoverable events (e.g., ICache ECC errors). Major alerts indicate unrecoverable security events.\n\n## 10. Performance Counters\n\nThe core implements hardware performance counters as per the RISC‑V Privileged Specification. The `mcycle` and `minstret` counters are always present and 64‑bit wide. Up to 29 additional event counters (`mhpmcounter3..31`) may be configured, each with configurable width (1–64 bits). The number of available event counters is parameterizable (0 to 8). Event to counter mapping is fixed (see documentation). Software can inhibit counters via `mcountinhibit`. Event selectors (`mhpmeventX`) define which events are counted; they are hardwired to a specific event mask per counter. Unimplemented counters always read zero.\n\n## 11. Instruction Cache (ICache)\n\nThe core may include an optional instruction cache that replaces the prefetch buffer. The cache is set‑associative, configurable in size (default 4 kB), line size (default 64 bits), and number of ways (default 2). It supports:\n\n- **Normal operation**: Fetches instructions from memory, caches lines, and returns data to the IF stage. Addresses are incremented automatically; branches reset the address counter.\n- **Pass‑through mode**: When `icache_enable` is low or an invalidation is in progress, the cache behaves as a simple buffer (no caching of fetched data).\n- **Cache invalidation**: Triggered by a dedicated signal (or after reset). While invalidating, no new lines are allocated.\n- **ECC protection** (optional): Tag and data RAMs may be ECC‑protected. On any ECC error, the line is invalidated and a minor alert is raised.\n- **Scrambling** (optional): RAMs may use address scrambling with a key provided via a request/acknowledge handshake.\n\nThe cache ensures that all instructions returned to the core are consistent with the memory system. It does not provide coherence with data accesses; software must invalidate the cache after modifying instruction memory.\n\n## 12. Reset and Boot\n\nOn reset, the core starts fetching from the reset address (boot address). The `mtvec` CSR is initialized to the boot address (256‑byte aligned). The core starts in M‑Mode with interrupts disabled (`mstatus.MIE = 0`). All CSRs enter their reset values as documented.\n\nThe core shall monitor the `fetch_enable` input; fetching proceeds only when this signal indicates enable (bottom bit = 1). If the signal disables fetching, the core shall stop fetching instructions and may enter a low‑power state.\n\n## 13. Sleep and Wakeup\n\nThe core implements the `WFI` instruction. When executed, the core waits for an interrupt or debug request. While sleeping, the core stops fetching instructions but remains clocked to respond to wake events. The sleep state is entered regardless of the interrupt‑enable state.\n\n## 14. Pipeline Depth Configuration\n\nThe core may be configured with an optional third pipeline stage (Writeback). When enabled, the pipeline behavior changes (details TBD in future documentation). All other requirements in this specification apply to the default two‑stage pipeline.\n\n---\n\nThis specification captures the required observable behavior of the Ibex core across all functional areas. Implementations must satisfy these requirements regardless of internal microarchitecture.", "commit_id": "8d044a3ddce53dba4652083b404a4821a7bc9be9", "timestamp": "2022-04-19T14:11:25+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "3264fe85c608703006790118e7228109220f45bf", "pr_title": "Update fetch enable encoding", "pr_body": "This is done to match the encoding update done in the OpenTitan repo\r\nhere: [#12153](https://github.com/lowRISC/opentitan/pull/12153)\r\n\r\nSigned-off-by: Michael Schaffner ", "issue_title": "", "issue_body": "", "commit_message": "Update fetch enable encoding\n\nThis is done to match the encoding update done in the OpenTitan repo\nhere: https://github.com/lowRISC/opentitan/pull/12153\n\nSigned-off-by: Michael Schaffner ", "fix_patch": "diff --git a/rtl/ibex_pkg.sv b/rtl/ibex_pkg.sv\nindex 813f78ab4d..4dcae7b33b 100644\n--- a/rtl/ibex_pkg.sv\n+++ b/rtl/ibex_pkg.sv\n@@ -648,6 +648,6 @@ package ibex_pkg;\n // for Off. This allows the use of FetchEnableOn/FetchEnableOff to work for both secure and\n // non-secure Ibex. If this assumption is broken the RTL that uses the fetch_enable signal within\n // `ibex_core` may need adjusting.\n- parameter fetch_enable_t FetchEnableOn = 4'b1001;\n- parameter fetch_enable_t FetchEnableOff = 4'b0110;\n+ parameter fetch_enable_t FetchEnableOn = 4'b0101;\n+ parameter fetch_enable_t FetchEnableOff = 4'b1010;\n endpackage\n", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2017 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 * Package with constants used by Ibex\n */\npackage ibex_pkg;\n\n ////////////////\n // IO Structs //\n ////////////////\n\n typedef struct packed {\n logic [31:0] current_pc;\n logic [31:0] next_pc;\n logic [31:0] last_data_addr;\n logic [31:0] exception_addr;\n } crash_dump_t;\n\n typedef struct packed {\n logic dummy_instr_id;\n logic [4:0] raddr_a;\n logic [4:0] waddr_a;\n logic we_a;\n logic [4:0] raddr_b;\n } core2rf_t;\n\n /////////////////////\n // Parameter Enums //\n /////////////////////\n\n typedef enum integer {\n RegFileFF = 0,\n RegFileFPGA = 1,\n RegFileLatch = 2\n } regfile_e;\n\n typedef enum integer {\n RV32MNone = 0,\n RV32MSlow = 1,\n RV32MFast = 2,\n RV32MSingleCycle = 3\n } rv32m_e;\n\n typedef enum integer {\n RV32BNone = 0,\n RV32BBalanced = 1,\n RV32BOTEarlGrey = 2,\n RV32BFull = 3\n } rv32b_e;\n\n /////////////\n // Opcodes //\n /////////////\n\n typedef enum logic [6:0] {\n OPCODE_LOAD = 7'h03,\n OPCODE_MISC_MEM = 7'h0f,\n OPCODE_OP_IMM = 7'h13,\n OPCODE_AUIPC = 7'h17,\n OPCODE_STORE = 7'h23,\n OPCODE_OP = 7'h33,\n OPCODE_LUI = 7'h37,\n OPCODE_BRANCH = 7'h63,\n OPCODE_JALR = 7'h67,\n OPCODE_JAL = 7'h6f,\n OPCODE_SYSTEM = 7'h73\n } opcode_e;\n\n\n ////////////////////\n // ALU operations //\n ////////////////////\n\n typedef enum logic [6:0] {\n // Arithmetics\n ALU_ADD,\n ALU_SUB,\n\n // Logics\n ALU_XOR,\n ALU_OR,\n ALU_AND,\n // RV32B\n ALU_XNOR,\n ALU_ORN,\n ALU_ANDN,\n\n // Shifts\n ALU_SRA,\n ALU_SRL,\n ALU_SLL,\n // RV32B\n ALU_SRO,\n ALU_SLO,\n ALU_ROR,\n ALU_ROL,\n ALU_GREV,\n ALU_GORC,\n ALU_SHFL,\n ALU_UNSHFL,\n ALU_XPERM_N,\n ALU_XPERM_B,\n ALU_XPERM_H,\n\n // Address Calculations\n // RV32B\n ALU_SH1ADD,\n ALU_SH2ADD,\n ALU_SH3ADD,\n\n // Comparisons\n ALU_LT,\n ALU_LTU,\n ALU_GE,\n ALU_GEU,\n ALU_EQ,\n ALU_NE,\n // RV32B\n ALU_MIN,\n ALU_MINU,\n ALU_MAX,\n ALU_MAXU,\n\n // Pack\n // RV32B\n ALU_PACK,\n ALU_PACKU,\n ALU_PACKH,\n\n // Sign-Extend\n // RV32B\n ALU_SEXTB,\n ALU_SEXTH,\n\n // Bitcounting\n // RV32B\n ALU_CLZ,\n ALU_CTZ,\n ALU_CPOP,\n\n // Set lower than\n ALU_SLT,\n ALU_SLTU,\n\n // Ternary Bitmanip Operations\n // RV32B\n ALU_CMOV,\n ALU_CMIX,\n ALU_FSL,\n ALU_FSR,\n\n // Single-Bit Operations\n // RV32B\n ALU_BSET,\n ALU_BCLR,\n ALU_BINV,\n ALU_BEXT,\n\n // Bit Compress / Decompress\n // RV32B\n ALU_BCOMPRESS,\n ALU_BDECOMPRESS,\n\n // Bit Field Place\n // RV32B\n ALU_BFP,\n\n // Carry-less Multiply\n // RV32B\n ALU_CLMUL,\n ALU_CLMULR,\n ALU_CLMULH,\n\n // Cyclic Redundancy Check\n ALU_CRC32_B,\n ALU_CRC32C_B,\n ALU_CRC32_H,\n ALU_CRC32C_H,\n ALU_CRC32_W,\n ALU_CRC32C_W\n } alu_op_e;\n\n typedef enum logic [1:0] {\n // Multiplier/divider\n MD_OP_MULL,\n MD_OP_MULH,\n MD_OP_DIV,\n MD_OP_REM\n } md_op_e;\n\n\n //////////////////////////////////\n // Control and status registers //\n //////////////////////////////////\n\n // CSR operations\n typedef enum logic [1:0] {\n CSR_OP_READ,\n CSR_OP_WRITE,\n CSR_OP_SET,\n CSR_OP_CLEAR\n } csr_op_e;\n\n // Privileged mode\n typedef enum logic[1:0] {\n PRIV_LVL_M = 2'b11,\n PRIV_LVL_H = 2'b10,\n PRIV_LVL_S = 2'b01,\n PRIV_LVL_U = 2'b00\n } priv_lvl_e;\n\n // Constants for the dcsr.xdebugver fields\n typedef enum logic[3:0] {\n XDEBUGVER_NO = 4'd0, // no external debug support\n XDEBUGVER_STD = 4'd4, // external debug according to RISC-V debug spec\n XDEBUGVER_NONSTD = 4'd15 // debug not conforming to RISC-V debug spec\n } x_debug_ver_e;\n\n //////////////\n // WB stage //\n //////////////\n\n // Type of instruction present in writeback stage\n typedef enum logic[1:0] {\n WB_INSTR_LOAD, // Instruction is awaiting load data\n WB_INSTR_STORE, // Instruction is awaiting store response\n WB_INSTR_OTHER // Instruction doesn't fit into above categories\n } wb_instr_type_e;\n\n //////////////\n // ID stage //\n //////////////\n\n // Operand a selection\n typedef enum logic[1:0] {\n OP_A_REG_A,\n OP_A_FWD,\n OP_A_CURRPC,\n OP_A_IMM\n } op_a_sel_e;\n\n // Immediate a selection\n typedef enum logic {\n IMM_A_Z,\n IMM_A_ZERO\n } imm_a_sel_e;\n\n // Operand b selection\n typedef enum logic {\n OP_B_REG_B,\n OP_B_IMM\n } op_b_sel_e;\n\n // Immediate b selection\n typedef enum logic [2:0] {\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 } imm_b_sel_e;\n\n // Regfile write data selection\n typedef enum logic {\n RF_WD_EX,\n RF_WD_CSR\n } rf_wd_sel_e;\n\n // Controller FSM state encoding\n typedef enum logic [3:0] {\n RESET,\n BOOT_SET,\n WAIT_SLEEP,\n SLEEP,\n FIRST_FETCH,\n DECODE,\n FLUSH,\n IRQ_TAKEN,\n DBG_TAKEN_IF,\n DBG_TAKEN_ID\n } ctrl_fsm_e;\n\n //////////////\n // IF stage //\n //////////////\n\n // PC mux selection\n typedef enum logic [2:0] {\n PC_BOOT,\n PC_JUMP,\n PC_EXC,\n PC_ERET,\n PC_DRET,\n PC_BP\n } pc_sel_e;\n\n // Exception PC mux selection\n typedef enum logic [1:0] {\n EXC_PC_EXC,\n EXC_PC_IRQ,\n EXC_PC_DBD,\n EXC_PC_DBG_EXC // Exception while in debug mode\n } exc_pc_sel_e;\n\n // Interrupt requests\n typedef struct packed {\n logic irq_software;\n logic irq_timer;\n logic irq_external;\n logic [14:0] irq_fast; // 15 fast interrupts,\n // one interrupt is reserved for NMI (not visible through mip/mie)\n } irqs_t;\n\n typedef struct packed {\n logic irq_int;\n logic irq_ext;\n logic [4:0] lower_cause;\n } exc_cause_t;\n\n localparam exc_cause_t ExcCauseIrqSoftwareM =\n '{irq_ext: 1'b1, irq_int: 1'b0, lower_cause: 5'd03};\n localparam exc_cause_t ExcCauseIrqTimerM =\n '{irq_ext: 1'b1, irq_int: 1'b0, lower_cause: 5'd07};\n localparam exc_cause_t ExcCauseIrqExternalM =\n '{irq_ext: 1'b1, irq_int: 1'b0, lower_cause: 5'd11};\n localparam exc_cause_t ExcCauseIrqNm =\n '{irq_ext: 1'b1, irq_int: 1'b0, lower_cause: 5'd31};\n\n localparam exc_cause_t ExcCauseInsnAddrMisa =\n '{irq_ext: 1'b0, irq_int: 1'b0, lower_cause: 5'd00};\n localparam exc_cause_t ExcCauseInstrAccessFault =\n '{irq_ext: 1'b0, irq_int: 1'b0, lower_cause: 5'd01};\n localparam exc_cause_t ExcCauseIllegalInsn =\n '{irq_ext: 1'b0, irq_int: 1'b0, lower_cause: 5'd02};\n localparam exc_cause_t ExcCauseBreakpoint =\n '{irq_ext: 1'b0, irq_int: 1'b0, lower_cause: 5'd03};\n localparam exc_cause_t ExcCauseLoadAccessFault =\n '{irq_ext: 1'b0, irq_int: 1'b0, lower_cause: 5'd05};\n localparam exc_cause_t ExcCauseStoreAccessFault =\n '{irq_ext: 1'b0, irq_int: 1'b0, lower_cause: 5'd07};\n localparam exc_cause_t ExcCauseEcallUMode =\n '{irq_ext: 1'b0, irq_int: 1'b0, lower_cause: 5'd08};\n localparam exc_cause_t ExcCauseEcallMMode =\n '{irq_ext: 1'b0, irq_int: 1'b0, lower_cause: 5'd11};\n\n // Internal NMI cause\n typedef enum logic [4:0] {\n NMI_INT_CAUSE_ECC = 5'b0\n } nmi_int_cause_e;\n\n // Debug cause\n typedef enum logic [2:0] {\n DBG_CAUSE_NONE = 3'h0,\n DBG_CAUSE_EBREAK = 3'h1,\n DBG_CAUSE_TRIGGER = 3'h2,\n DBG_CAUSE_HALTREQ = 3'h3,\n DBG_CAUSE_STEP = 3'h4\n } dbg_cause_e;\n\n // ICache constants\n parameter int unsigned ADDR_W = 32;\n parameter int unsigned BUS_SIZE = 32;\n parameter int unsigned BUS_BYTES = BUS_SIZE/8;\n parameter int unsigned BUS_W = $clog2(BUS_BYTES);\n parameter int unsigned IC_SIZE_BYTES = 4096;\n parameter int unsigned IC_NUM_WAYS = 2;\n parameter int unsigned IC_LINE_SIZE = 64;\n parameter int unsigned IC_LINE_BYTES = IC_LINE_SIZE/8;\n parameter int unsigned IC_LINE_W = $clog2(IC_LINE_BYTES);\n parameter int unsigned IC_NUM_LINES = IC_SIZE_BYTES / IC_NUM_WAYS / IC_LINE_BYTES;\n parameter int unsigned IC_LINE_BEATS = IC_LINE_BYTES / BUS_BYTES;\n parameter int unsigned IC_LINE_BEATS_W = $clog2(IC_LINE_BEATS);\n parameter int unsigned IC_INDEX_W = $clog2(IC_NUM_LINES);\n parameter int unsigned IC_INDEX_HI = IC_INDEX_W + IC_LINE_W - 1;\n parameter int unsigned IC_TAG_SIZE = ADDR_W - IC_INDEX_W - IC_LINE_W + 1; // 1 valid bit\n parameter int unsigned IC_OUTPUT_BEATS = (BUS_BYTES / 2); // number of halfwords\n // ICache Scrambling Parameters\n parameter int unsigned SCRAMBLE_KEY_W = 128;\n parameter int unsigned SCRAMBLE_NONCE_W = 64;\n\n // PMP constants\n parameter int unsigned PMP_MAX_REGIONS = 16;\n parameter int unsigned PMP_CFG_W = 8;\n\n // PMP acces type\n parameter int unsigned PMP_I = 0;\n parameter int unsigned PMP_I2 = 1;\n parameter int unsigned PMP_D = 2;\n\n typedef enum logic [1:0] {\n PMP_ACC_EXEC = 2'b00,\n PMP_ACC_WRITE = 2'b01,\n PMP_ACC_READ = 2'b10\n } pmp_req_e;\n\n // PMP cfg structures\n typedef enum logic [1:0] {\n PMP_MODE_OFF = 2'b00,\n PMP_MODE_TOR = 2'b01,\n PMP_MODE_NA4 = 2'b10,\n PMP_MODE_NAPOT = 2'b11\n } pmp_cfg_mode_e;\n\n typedef struct packed {\n logic lock;\n pmp_cfg_mode_e mode;\n logic exec;\n logic write;\n logic read;\n } pmp_cfg_t;\n\n // Machine Security Configuration (ePMP)\n typedef struct packed {\n logic rlb; // Rule Locking Bypass\n logic mmwp; // Machine Mode Whitelist Policy\n logic mml; // Machine Mode Lockdown\n } pmp_mseccfg_t;\n\n // CSRs\n typedef enum logic[11:0] {\n // Machine information\n CSR_MVENDORID = 12'hF11,\n CSR_MARCHID = 12'hF12,\n CSR_MIMPID = 12'hF13,\n CSR_MHARTID = 12'hF14,\n\n // Machine trap setup\n CSR_MSTATUS = 12'h300,\n CSR_MISA = 12'h301,\n CSR_MIE = 12'h304,\n CSR_MTVEC = 12'h305,\n CSR_MCOUNTEREN= 12'h306,\n\n // Machine trap handling\n CSR_MSCRATCH = 12'h340,\n CSR_MEPC = 12'h341,\n CSR_MCAUSE = 12'h342,\n CSR_MTVAL = 12'h343,\n CSR_MIP = 12'h344,\n\n // Physical memory protection\n CSR_PMPCFG0 = 12'h3A0,\n CSR_PMPCFG1 = 12'h3A1,\n CSR_PMPCFG2 = 12'h3A2,\n CSR_PMPCFG3 = 12'h3A3,\n CSR_PMPADDR0 = 12'h3B0,\n CSR_PMPADDR1 = 12'h3B1,\n CSR_PMPADDR2 = 12'h3B2,\n CSR_PMPADDR3 = 12'h3B3,\n CSR_PMPADDR4 = 12'h3B4,\n CSR_PMPADDR5 = 12'h3B5,\n CSR_PMPADDR6 = 12'h3B6,\n CSR_PMPADDR7 = 12'h3B7,\n CSR_PMPADDR8 = 12'h3B8,\n CSR_PMPADDR9 = 12'h3B9,\n CSR_PMPADDR10 = 12'h3BA,\n CSR_PMPADDR11 = 12'h3BB,\n CSR_PMPADDR12 = 12'h3BC,\n CSR_PMPADDR13 = 12'h3BD,\n CSR_PMPADDR14 = 12'h3BE,\n CSR_PMPADDR15 = 12'h3BF,\n\n // ePMP control\n CSR_MSECCFG = 12'h747,\n CSR_MSECCFGH = 12'h757,\n\n // Debug trigger\n CSR_TSELECT = 12'h7A0,\n CSR_TDATA1 = 12'h7A1,\n CSR_TDATA2 = 12'h7A2,\n CSR_TDATA3 = 12'h7A3,\n CSR_MCONTEXT = 12'h7A8,\n CSR_SCONTEXT = 12'h7AA,\n\n // Debug/trace\n CSR_DCSR = 12'h7b0,\n CSR_DPC = 12'h7b1,\n\n // Debug\n CSR_DSCRATCH0 = 12'h7b2, // optional\n CSR_DSCRATCH1 = 12'h7b3, // optional\n\n // Machine Counter/Timers\n CSR_MCOUNTINHIBIT = 12'h320,\n CSR_MHPMEVENT3 = 12'h323,\n CSR_MHPMEVENT4 = 12'h324,\n CSR_MHPMEVENT5 = 12'h325,\n CSR_MHPMEVENT6 = 12'h326,\n CSR_MHPMEVENT7 = 12'h327,\n CSR_MHPMEVENT8 = 12'h328,\n CSR_MHPMEVENT9 = 12'h329,\n CSR_MHPMEVENT10 = 12'h32A,\n CSR_MHPMEVENT11 = 12'h32B,\n CSR_MHPMEVENT12 = 12'h32C,\n CSR_MHPMEVENT13 = 12'h32D,\n CSR_MHPMEVENT14 = 12'h32E,\n CSR_MHPMEVENT15 = 12'h32F,\n CSR_MHPMEVENT16 = 12'h330,\n CSR_MHPMEVENT17 = 12'h331,\n CSR_MHPMEVENT18 = 12'h332,\n CSR_MHPMEVENT19 = 12'h333,\n CSR_MHPMEVENT20 = 12'h334,\n CSR_MHPMEVENT21 = 12'h335,\n CSR_MHPMEVENT22 = 12'h336,\n CSR_MHPMEVENT23 = 12'h337,\n CSR_MHPMEVENT24 = 12'h338,\n CSR_MHPMEVENT25 = 12'h339,\n CSR_MHPMEVENT26 = 12'h33A,\n CSR_MHPMEVENT27 = 12'h33B,\n CSR_MHPMEVENT28 = 12'h33C,\n CSR_MHPMEVENT29 = 12'h33D,\n CSR_MHPMEVENT30 = 12'h33E,\n CSR_MHPMEVENT31 = 12'h33F,\n CSR_MCYCLE = 12'hB00,\n CSR_MINSTRET = 12'hB02,\n CSR_MHPMCOUNTER3 = 12'hB03,\n CSR_MHPMCOUNTER4 = 12'hB04,\n CSR_MHPMCOUNTER5 = 12'hB05,\n CSR_MHPMCOUNTER6 = 12'hB06,\n CSR_MHPMCOUNTER7 = 12'hB07,\n CSR_MHPMCOUNTER8 = 12'hB08,\n CSR_MHPMCOUNTER9 = 12'hB09,\n CSR_MHPMCOUNTER10 = 12'hB0A,\n CSR_MHPMCOUNTER11 = 12'hB0B,\n CSR_MHPMCOUNTER12 = 12'hB0C,\n CSR_MHPMCOUNTER13 = 12'hB0D,\n CSR_MHPMCOUNTER14 = 12'hB0E,\n CSR_MHPMCOUNTER15 = 12'hB0F,\n CSR_MHPMCOUNTER16 = 12'hB10,\n CSR_MHPMCOUNTER17 = 12'hB11,\n CSR_MHPMCOUNTER18 = 12'hB12,\n CSR_MHPMCOUNTER19 = 12'hB13,\n CSR_MHPMCOUNTER20 = 12'hB14,\n CSR_MHPMCOUNTER21 = 12'hB15,\n CSR_MHPMCOUNTER22 = 12'hB16,\n CSR_MHPMCOUNTER23 = 12'hB17,\n CSR_MHPMCOUNTER24 = 12'hB18,\n CSR_MHPMCOUNTER25 = 12'hB19,\n CSR_MHPMCOUNTER26 = 12'hB1A,\n CSR_MHPMCOUNTER27 = 12'hB1B,\n CSR_MHPMCOUNTER28 = 12'hB1C,\n CSR_MHPMCOUNTER29 = 12'hB1D,\n CSR_MHPMCOUNTER30 = 12'hB1E,\n CSR_MHPMCOUNTER31 = 12'hB1F,\n CSR_MCYCLEH = 12'hB80,\n CSR_MINSTRETH = 12'hB82,\n CSR_MHPMCOUNTER3H = 12'hB83,\n CSR_MHPMCOUNTER4H = 12'hB84,\n CSR_MHPMCOUNTER5H = 12'hB85,\n CSR_MHPMCOUNTER6H = 12'hB86,\n CSR_MHPMCOUNTER7H = 12'hB87,\n CSR_MHPMCOUNTER8H = 12'hB88,\n CSR_MHPMCOUNTER9H = 12'hB89,\n CSR_MHPMCOUNTER10H = 12'hB8A,\n CSR_MHPMCOUNTER11H = 12'hB8B,\n CSR_MHPMCOUNTER12H = 12'hB8C,\n CSR_MHPMCOUNTER13H = 12'hB8D,\n CSR_MHPMCOUNTER14H = 12'hB8E,\n CSR_MHPMCOUNTER15H = 12'hB8F,\n CSR_MHPMCOUNTER16H = 12'hB90,\n CSR_MHPMCOUNTER17H = 12'hB91,\n CSR_MHPMCOUNTER18H = 12'hB92,\n CSR_MHPMCOUNTER19H = 12'hB93,\n CSR_MHPMCOUNTER20H = 12'hB94,\n CSR_MHPMCOUNTER21H = 12'hB95,\n CSR_MHPMCOUNTER22H = 12'hB96,\n CSR_MHPMCOUNTER23H = 12'hB97,\n CSR_MHPMCOUNTER24H = 12'hB98,\n CSR_MHPMCOUNTER25H = 12'hB99,\n CSR_MHPMCOUNTER26H = 12'hB9A,\n CSR_MHPMCOUNTER27H = 12'hB9B,\n CSR_MHPMCOUNTER28H = 12'hB9C,\n CSR_MHPMCOUNTER29H = 12'hB9D,\n CSR_MHPMCOUNTER30H = 12'hB9E,\n CSR_MHPMCOUNTER31H = 12'hB9F,\n CSR_CPUCTRL = 12'h7C0,\n CSR_SECURESEED = 12'h7C1\n } csr_num_e;\n\n // CSR pmp-related offsets\n parameter logic [11:0] CSR_OFF_PMP_CFG = 12'h3A0; // pmp_cfg @ 12'h3a0 - 12'h3a3\n parameter logic [11:0] CSR_OFF_PMP_ADDR = 12'h3B0; // pmp_addr @ 12'h3b0 - 12'h3bf\n\n // CSR status bits\n parameter int unsigned CSR_MSTATUS_MIE_BIT = 3;\n parameter int unsigned CSR_MSTATUS_MPIE_BIT = 7;\n parameter int unsigned CSR_MSTATUS_MPP_BIT_LOW = 11;\n parameter int unsigned CSR_MSTATUS_MPP_BIT_HIGH = 12;\n parameter int unsigned CSR_MSTATUS_MPRV_BIT = 17;\n parameter int unsigned CSR_MSTATUS_TW_BIT = 21;\n\n // CSR machine ISA\n parameter logic [1:0] CSR_MISA_MXL = 2'd1; // M-XLEN: XLEN in M-Mode for RV32\n\n // CSR interrupt pending/enable bits\n parameter int unsigned CSR_MSIX_BIT = 3;\n parameter int unsigned CSR_MTIX_BIT = 7;\n parameter int unsigned CSR_MEIX_BIT = 11;\n parameter int unsigned CSR_MFIX_BIT_LOW = 16;\n parameter int unsigned CSR_MFIX_BIT_HIGH = 30;\n\n // CSR Machine Security Configuration bits\n parameter int unsigned CSR_MSECCFG_MML_BIT = 0;\n parameter int unsigned CSR_MSECCFG_MMWP_BIT = 1;\n parameter int unsigned CSR_MSECCFG_RLB_BIT = 2;\n\n // Vendor ID\n // No JEDEC ID has been allocated to lowRISC so the value is 0 to indicate the field is not\n // implemented\n localparam logic [31:0] CSR_MVENDORID_VALUE = 32'b0;\n\n // Architecture ID\n // Top bit is unset to indicate an open source project. The lower bits are an ID allocated by the\n // RISC-V Foundation. Note this is allocated specifically to Ibex, should significant changes be\n // made a different architecture ID should be supplied.\n localparam logic [31:0] CSR_MARCHID_VALUE = {1'b0, 31'd22};\n\n // Implementation ID\n // 0 indicates this field is not implemeted. Ibex implementors may wish to indicate an RTL/netlist\n // version here using their own unique encoding (e.g. 32 bits of the git hash of the implemented\n // commit).\n localparam logic [31:0] CSR_MIMPID_VALUE = 32'b0;\n\n // These LFSR parameters have been generated with\n // $ opentitan/util/design/gen-lfsr-seed.py --width 32 --seed 2480124384 --prefix \"\"\n parameter int LfsrWidth = 32;\n typedef logic [LfsrWidth-1:0] lfsr_seed_t;\n typedef logic [LfsrWidth-1:0][$clog2(LfsrWidth)-1:0] lfsr_perm_t;\n parameter lfsr_seed_t RndCnstLfsrSeedDefault = 32'hac533bf4;\n parameter lfsr_perm_t RndCnstLfsrPermDefault = {\n 160'h1e35ecba467fd1b12e958152c04fa43878a8daed\n };\n parameter logic [SCRAMBLE_KEY_W-1:0] RndCnstIbexKeyDefault =\n 128'h14e8cecae3040d5e12286bb3cc113298;\n parameter logic [SCRAMBLE_NONCE_W-1:0] RndCnstIbexNonceDefault =\n 64'hf79780bc735f3843;\n\n // Fetch enable. Mult-bit signal used for security hardening. For non-secure implementation all\n // bits other than the bottom bit are ignored.\n typedef logic [3:0] fetch_enable_t;\n\n // Note that if adjusting these parameters it is assumed the bottom bit is set for On and unset\n // for Off. This allows the use of FetchEnableOn/FetchEnableOff to work for both secure and\n // non-secure Ibex. If this assumption is broken the RTL that uses the fetch_enable signal within\n // `ibex_core` may need adjusting.\n parameter fetch_enable_t FetchEnableOn = 4'b0101;\n parameter fetch_enable_t FetchEnableOff = 4'b1010;\nendpackage\n", "selected_doc_paths": ["doc/03_reference/cs_registers.rst", "doc/03_reference/pmp.rst", "doc/03_reference/debug.rst", "doc/03_reference/instruction_decode_execute.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/register_file.rst", "doc/03_reference/icache.rst", "doc/03_reference/exception_interrupts.rst", "doc/03_reference/security.rst", "doc/03_reference/performance_counters.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1107, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# Behavioral Specification: `ibex_controller`\n\n## Overview\n\nThe `ibex_controller` module is the main finite state machine controlling the pipeline of the Ibex processor. It manages instruction fetch, decode, execution, exception handling, interrupt handling, debug mode entry/exit, and power saving (WFI). The controller ensures that instructions are correctly processed in accordance with the RISC-V privileged and debug specifications (version 1.11 and 0.13.2 respectively).\n\nThe controller operates with a finite state machine that transitions through states based on pipeline control signals, stall conditions, exception requests, interrupt requests, and debug requests. It orchestrates the flow of instructions from the instruction fetch stage to the decode/execute stage and the optional writeback stage.\n\n## Reset and Boot\n\nUpon power-on reset, the controller must:\n\n- Initialize the core to fetch instructions starting from the boot address (as supplied by the system).\n- Assert a request to the instruction fetch unit to begin fetching from the boot address.\n- After one cycle, the controller enters a state in which it waits for the first instruction to be fetched.\n- Once the first instruction is available, the controller transitions to normal decode operation.\n\nThe core always starts in Machine Mode (M‑Mode) with all interrupts disabled.\n\n## Normal Instruction Execution\n\nIn normal operation (the DECODE state), the controller:\n\n- Signals that the decode/execute stage is ready to accept new instructions.\n- Allows instructions to be decoded and executed unless stalls or exception/interrupt/debug conditions intervene.\n- For **jump** and **branch** instructions, the controller must assert a PC update signal to redirect instruction fetch to the target address.\n - For taken branches, the controller asserts a “speculative” PC update signal to allow early fetch; the actual PC set is asserted only when the branch is resolved as taken.\n - When branch prediction is enabled, the controller may suppress the speculative PC update if the predictor already triggered the fetch, and it signals a **mispredict** if a predicted-taken branch is actually not taken.\n- For **multi‑cycle instructions** (e.g., loads, stores, multiplies), the controller stalls the pipeline until the instruction completes. While stalled, the decode stage is held, and the instruction remains valid.\n- The controller maintains a `busy` indication that is high while the core is actively processing instructions; it becomes low during sleep (WFI).\n\n## Exception Handling\n\nThe controller must detect and prioritize exceptions as defined by the RISC‑V Privileged Specification (Table 3.7). Exceptions can arise from:\n\n- Instruction fetch errors (access fault)\n- Illegal instruction (including illegal DRET, illegal user‑mode instructions)\n- Environment call (ECALL from M‑Mode or U‑Mode)\n- Breakpoint (EBREAK)\n- Load/store access faults (from the LSU)\n\nException prioritization (highest to lowest):\n\n1. Load/store access fault from the instruction in the writeback stage (if writeback stage is present).\n2. Instruction fetch error (in ID/EX stage).\n3. Illegal instruction.\n4. ECALL.\n5. EBREAK.\n6. Store access fault (in ID/EX, or in WB if no writeback stage).\n7. Load access fault.\n\nWhen an exception is taken, the controller must:\n\n- Halt instruction fetch (prevent new instructions from entering the decode stage).\n- Flush the decode stage (discard the currently decoded instruction).\n- Save the current program counter (PC) to the `mepc` CSR.\n- Save the exception cause to `mcause`.\n- Set the exception PC (address to jump to) based on `mtvec` (vectored mode, i.e., base address + 4 * exception code).\n- If in debug mode, the exception handler address is the debug exception address (`DmExceptionAddr`).\n- For instruction access faults, store the faulting PC in `mtval`.\n- For illegal instructions, store the instruction word (uncompressed or compressed) in `mtval`.\n- For load/store faults, store the faulting data address in `mtval`.\n- Save the previous privilege mode and interrupt enable state in `mstatus` (MPP, MPIE).\n- Enter M‑Mode (if not already) and disable interrupts (clear MIE).\n\nThe controller must ensure that exceptions from the writeback stage (load/store access faults) take priority over exceptions from the ID/EX stage. The pipeline is flushed only after the writeback stage is ready or has raised its own exception.\n\n**EBREAK** instruction handling depends on the debug configuration and current mode:\n\n- If the core is already in Debug Mode, EBREAK re‑enters Debug Mode without updating `dpc` or `dcsr`.\n- If the `ebreakm` or `ebreaku` CSR bit is set (forcing debug mode entry), EBREAK causes entry into Debug Mode, saving PC to `dpc` and setting `dcsr.cause` to 1 (breakpoint).\n- Otherwise, EBREAK generates a breakpoint exception (exception code 3) and the core enters the normal exception handler.\n\n## Interrupt Handling\n\nThe controller must handle machine‑level interrupts according to the RISC‑V specification. Interrupt sources include:\n\n- Non‑maskable interrupt (NMI)\n- 15 fast local interrupts\n- External interrupt (`irq_external`)\n- Timer interrupt (`irq_timer`)\n- Software interrupt (`irq_software`)\n\nInterrupts are taken only when:\n\n- The core is **not** in Debug Mode.\n- The core is **not** currently executing an NMI handler (NMI mode).\n- Global interrupts are enabled (`mstatus.MIE` = 1) **and** the specific interrupt is enabled in `mie`.\n\nThe NMI is always enabled (independent of `mie` and `mstatus.MIE`), but is ignored during Debug Mode and during execution of another NMI handler.\n\n### Interrupt Priority\n\nPriority order (highest to lowest) is determined by interrupt ID (highest ID first), except the timer interrupt has the lowest priority. The NMI has the highest priority (ID 31). Fast interrupts have IDs 16‑30; external ID 11; software ID 3; timer ID 7.\n\nIf multiple fast interrupts are pending, the one with the highest index is selected.\n\n### Interrupt Acknowledgment\n\nWhen an interrupt is taken, the controller must:\n\n- Halt instruction fetch (prevent further instructions from entering the decode stage), but **do not flush** the current instruction if it is a multi‑cycle instruction (e.g., load/store). The current instruction must complete first.\n- After the current instruction completes, save the PC of the next instruction to `mepc`.\n- Save the cause to `mcause` (with interrupt bit set).\n- Save `mstatus.MIE` to `mstatus.MPIE` and clear `mstatus.MIE` (disable interrupts).\n- Set the PC to `mtvec` base + 4 * interrupt ID (vectored mode).\n- For NMI, set the `nmi_mode` flag to indicate the core is handling an NMI. Interrupts (including NMI) are ignored until the MRET instruction exits NMI mode.\n\n### Interrupt During CSR Pipeline Flush\n\nIf the pipeline is being flushed due to a CSR-related flush (e.g., `fence.i`, CSR write with side effect), and a pending interrupt is present, the controller may redirect the pipeline to handle the interrupt after the flush instead of proceeding to the next instruction.\n\n## Debug Mode\n\nDebug support follows the RISC‑V Debug Specification v0.13.2. The controller must support:\n\n- Entry into Debug Mode via `debug_req_i` (external halt request).\n- Entry due to single‑step (`dcsr.step` = 1) after each instruction.\n- Entry due to a trigger match (hardware breakpoint).\n- Entry due to EBREAK with `ebreakm`/`ebreaku` set.\n\n### Entering Debug Mode\n\nWhen a debug entry condition is detected (except EBREAK), the controller must:\n\n- Wait for the current instruction to complete (if any).\n- Flush the decode stage.\n- Save the PC of the next instruction to `dpc`.\n- Set `dcsr.cause` accordingly (halt request = 3, step = 4, trigger = 2).\n- Set the PC to the debug halt address (`DmHaltAddr`).\n- Enter Debug Mode (set `debug_mode` flag).\n\nIf the debug entry condition is a single‑step, it is qualified by `instr_valid` to ensure the core steps over real instructions, not bubbles.\n\nFor EBREAK causing debug entry (via `ebreakm`/`ebreaku`), the controller:\n\n- Saves the PC of the EBREAK instruction (not the next instruction) to `dpc`.\n- Sets `dcsr.cause` to 1 (breakpoint).\n- Does **not** flush the decode stage (because the EBREAK instruction itself is the one being debugged).\n- Enters Debug Mode and jumps to `DmHaltAddr`.\n\nIf a `debug_req` or single‑step occurs while an exception is being processed (in the FLUSH state), the controller must still handle the exception first, then upon completing the exception entry, it will immediately enter Debug Mode (overriding the normal exception handler address with the debug halt address). The exception PC is saved to `mepc` as usual, but `dpc` is set to the appropriate value based on the reason for debug entry.\n\n### Behavior While in Debug Mode\n\n- All interrupts (including NMI) are ignored.\n- EBREAK re‑enters Debug Mode without updating `dpc` or `dcsr`.\n- Exceptions are handled normally but use the debug exception address (`DmExceptionAddr`) instead of the standard `mtvec` base. The `dpc` is **not** updated for exceptions in Debug Mode (the exception causes entry to the debug exception handler, not a change in debug state).\n\n### Exiting Debug Mode\n\n- The debug module will instruct the core to resume via a `dret` instruction or by clearing `debug_req_i` and setting a resume PC through `dpc`. The controller must support `dret` (Debug Return) which restores the PC from `dpc` and exits Debug Mode.\n\n## Sleep (WFI)\n\nWhen a `wfi` (wait for interrupt) instruction is decoded and is legal:\n\n- The controller transitions to a sleep state.\n- It halts instruction fetch, flushes the decode stage, and indicates the core is not busy.\n- The core remains in sleep until:\n - An interrupt (standard or NMI) arrives.\n - A debug request is received.\n - The core is already in Debug Mode or single‑step mode (in which case WFI behaves as a NOP and the core immediately exits sleep).\n\nIn the sleep state, the controller must continue monitoring interrupt and debug signals. Upon wake‑up, the controller restarts fetching from the next instruction after the WFI.\n\n## Pipeline Control Signals\n\nThe controller generates control signals for the pipeline stages:\n\n- **Instruction fetch request**: asserted during normal operation to keep fetching instructions, deasserted during sleep, flush, or when waiting for a resolution.\n- **PC set signals**: asserted to redirect the fetch address for branches, jumps, exceptions, interrupts, or returns (MRET, DRET).\n- **Flush and stall signals**: The controller must stall the decode stage (due to multi‑cycle instructions, load/store waiting, etc.) and flush the decode stage when an exception or interrupt is taken, or when a branch redirect occurs.\n- **Instruction valid clear**: The controller must clear the valid bit of the instruction in the IF‑ID pipeline register when the instruction is to be discarded (e.g., due to exception, mispredict, or flush). This is distinct from stalling, where the valid bit must be preserved.\n\n## Performance Counters\n\nThe controller must provide output indicators for performance monitoring:\n\n- `perf_jump`: asserted for one cycle when a jump instruction is executed (including JAL, JALR).\n- `perf_tbranch`: asserted for one cycle when a branch is taken (any conditional branch that is resolved as taken).\n\n## Parameterization\n\nThe controller’s behavior may be influenced by two parameters:\n\n- **WritebackStage**: When present, the writeback stage alters the timing of exception handling. Load/store access faults are detected one cycle later (in the writeback stage) and take priority over exceptions from the ID/EX stage. The controller also saves the PC from writeback (not ID) for such exceptions.\n- **BranchPredictor**: When enabled, the controller supports speculative branch prediction. The branch condition may be predicted taken based on static heuristics (negative offset branches predicted taken). The controller suppresses its own speculative PC set if the predictor already set it, and detects mispredicts (predicted taken but actually not taken), triggering a pipeline flush and correction.\n\n## Summary of Priority and Integration\n\nThe controller must integrate with the core’s pipeline stages, CSR registers, instruction fetch unit, load‑store unit, and debug module. It must adhere to the following overall priority (higher number = higher priority, but handled differently):\n\n1. Instruction in writeback raising a load/store exception.\n2. Debug entry request (debug_req, single‑step, trigger) – processed after current instruction completes.\n3. Interrupt (including NMI) – processed after current instruction completes.\n4. Exceptions from ID/EX stage – handled immediately by flushing.\n5. Branch/jump redirect – normal operation.\n6. Stall / wait for multi‑cycle instruction completion.\n\nThe controller’s behavior is fully defined by the RISC‑V specifications and the Ibex microarchitecture, as described above. It must not introduce any data hazards or incorrect execution ordering.", "commit_id": "c31d066130bdce11dfbacf7afab7641dbd9157f5", "timestamp": "2020-09-14T13:19:36+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "2c22c1ee01b9842d3ee75bb80265cb84c014eaaf", "pr_title": "[rtl] Fix debug step over EBREAK issue", "pr_body": "- If there is a request to enter debug mode (either due to a halt\r\n request or single stepping mode) on the same cycle as an EBREAK\r\n instruction, continue with the EBREAK and capture the ID PC rather\r\n than the IF PC.\r\n- relates to #1106\r\n\r\nSigned-off-by: Tom Roberts ", "issue_title": "The step operation is error when the SW bp is set in a J instruction.", "issue_body": "Hi Guys: \r\n I use the Ibex core running a simple test C code. \r\n I set a SW bp before a “jump” instruction, when the cpu fetched the SW bp instruction, the cpu is halted. \r\n But after that, i use the “step\" cmd in telnet, the PC in CPU is wrong, it's not the correct PC which the JUMP instruction expected , the dpc has been changed. \r\n When I use the HW bp, the dpc has‘t been changed.\r\n So, i think this is a bug\r\n please see the following figure.\r\n \r\n\r\n\r\n![image](https://user-images.githubusercontent.com/71075865/92725183-51254200-f39e-11ea-81fc-698ca50d9b6b.png)\r\n\r\n![image](https://user-images.githubusercontent.com/71075865/92725197-571b2300-f39e-11ea-8c1b-1e2a62d5aed7.png)\r\n\r\n![image](https://user-images.githubusercontent.com/71075865/92725252-70bc6a80-f39e-11ea-8581-3ed01bcebc3b.png)\r\n\r\n\r\n\r\n\r\n", "commit_message": "[rtl] Fix debug step over EBREAK issue\n\n- If there is a request to enter debug mode (either due to a halt\n request or single stepping mode) on the same cycle as an EBREAK\n instruction, continue with the EBREAK and capture the ID PC rather\n than the IF PC.\n- relates to #1106\n\nSigned-off-by: Tom Roberts ", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex afa7fff87b..f943b30d15 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -766,7 +766,10 @@ module ibex_controller #(\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+ // 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.\n+ if (enter_debug_mode && !(ebrk_insn_prio && ebreak_into_debug)) begin\n ctrl_fsm_ns = DBG_TAKEN_IF;\n end\n end // FLUSH\n", "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\nmodule ibex_controller #(\n parameter bit WritebackStage = 0,\n parameter bit BranchPredictor = 0\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\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 logic pc_set_spec_o, // speculative branch\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_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 output logic wb_exception_o, // Instruction in WB 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_set_spec_i, // speculative branch signal (branch\n // may be 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_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 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 input logic csr_mstatus_tw_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 // 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 // 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 illegal_dret;\n logic illegal_umode;\n logic exc_req_lsu;\n logic special_req_all;\n logic special_req_branch;\n logic enter_debug_mode;\n logic ebreak_into_debug;\n logic handle_irq;\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, 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 // All terms in this expression are qualified by instr_valid_i\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 // 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\n // special requests: special instructions, pipeline flushes, exceptions...\n\n // To avoid creating a path from data_err_i -> instr_req_o and to help timing the below\n // special_req_all has a version that only applies to branches. For a branch the controller needs\n // to set pc_set_o but only if there is no special request. If the generic special_req_all signal\n // is used then a variety of signals that will never cause a special request during a branch\n // instruction end up factored into pc_set_o. The special_req_branch only considers the special\n // request reasons that are relevant to a branch.\n\n // generic special request signal, applies to all instructions\n // All terms in this expression 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 assign special_req_all = mret_insn | dret_insn | wfi_insn | csr_pipe_flush |\n exc_req_d | exc_req_lsu;\n\n // special request that can specifically occur during branch instructions\n // All terms in this expression are qualified by instr_valid_i\n assign special_req_branch = instr_fetch_err & (ctrl_fsm_cs != FLUSH);\n\n `ASSERT(SpecialReqBranchGivesSpecialReqAll,\n special_req_branch |-> special_req_all)\n\n `ASSERT(SpecialReqAllGivesSpecialReqBranchIfBranchInst,\n special_req_all && (branch_set_i || jump_set_i) |-> special_req_branch)\n\n // Exception/fault prioritisation is taken from Table 3.7 of Priviledged Spec v1.11\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 // 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 assign enter_debug_mode = (debug_req_i | (debug_single_step_i & instr_valid_i) |\n 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 // Interrupts including NMI are ignored,\n // - while in debug mode [Debug Spec v0.13.2, p.39],\n // - while in NMI mode (nested NMIs are not supported, NMI has highest priority and\n // cannot be interrupted by regular interrupts).\n assign handle_irq = ~debug_mode_q & ~nmi_mode_q &\n (irq_nm_i | (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 (irqs_i.irq_fast[14]) mfip_id = 4'd14;\n else if (irqs_i.irq_fast[13]) mfip_id = 4'd13;\n else if (irqs_i.irq_fast[12]) mfip_id = 4'd12;\n else if (irqs_i.irq_fast[11]) mfip_id = 4'd11;\n else if (irqs_i.irq_fast[10]) mfip_id = 4'd10;\n else if (irqs_i.irq_fast[ 9]) mfip_id = 4'd9;\n else if (irqs_i.irq_fast[ 8]) mfip_id = 4'd8;\n else if (irqs_i.irq_fast[ 7]) mfip_id = 4'd7;\n else if (irqs_i.irq_fast[ 6]) mfip_id = 4'd6;\n else if (irqs_i.irq_fast[ 5]) mfip_id = 4'd5;\n else if (irqs_i.irq_fast[ 4]) mfip_id = 4'd4;\n else if (irqs_i.irq_fast[ 3]) mfip_id = 4'd3;\n else if (irqs_i.irq_fast[ 2]) mfip_id = 4'd2;\n else if (irqs_i.irq_fast[ 1]) mfip_id = 4'd1;\n else mfip_id = 4'd0;\n end\n\n assign unused_irq_timer = irqs_i.irq_timer;\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 pc_set_spec_o = 1'b0;\n nt_branch_mispredict_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\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_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 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 pc_set_spec_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 pc_set_spec_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_i || 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_all) 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 (!special_req_branch) begin\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 end\n\n // pc_set signal excluding branch taken condition\n if ((branch_set_spec_i || jump_set_i) && !special_req_branch) begin\n // Only speculatively set the PC if the branch predictor hasn't already done the branch\n // for us\n pc_set_spec_o = BranchPredictor ? ~instr_bp_taken_i : 1'b1;\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\n if (!stall && !special_req_all) 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 pc_set_spec_o = 1'b1;\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 (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 EXC_CAUSE_IRQ_FAST_0 = {1'b1, 5'd16}\n exc_cause_o = exc_cause_e'({2'b11, mfip_id});\n end else if (irqs_i.irq_external) begin\n exc_cause_o = EXC_CAUSE_IRQ_EXTERNAL_M;\n end else if (irqs_i.irq_software) begin\n exc_cause_o = EXC_CAUSE_IRQ_SOFTWARE_M;\n end else begin // irqs_i.irq_timer\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 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 if (debug_single_step_i || debug_req_i || trigger_match_i) begin\n flush_id = 1'b1;\n pc_set_o = 1'b1;\n pc_set_spec_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 if (trigger_match_i) begin\n debug_cause_o = DBG_CAUSE_TRIGGER;\n end else 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 flush_id = 1'b1;\n pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n pc_set_spec_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\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_set_spec_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 = EXC_CAUSE_INSTR_ACCESS_FAULT;\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 = EXC_CAUSE_ILLEGAL_INSN;\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) ? EXC_CAUSE_ECALL_MMODE :\n EXC_CAUSE_ECALL_UMODE;\n end\n ebrk_insn_prio: 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 pc_set_spec_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 end\n store_err_prio: begin\n exc_cause_o = EXC_CAUSE_STORE_ACCESS_FAULT;\n csr_mtval_o = lsu_addr_last_i;\n end\n load_err_prio: begin\n exc_cause_o = EXC_CAUSE_LOAD_ACCESS_FAULT;\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 pc_set_spec_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 pc_set_spec_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 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 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.\n if (enter_debug_mode && !(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 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 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\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 // The speculative branch signal should be set whenever the actual branch signal is set\n `ASSERT(IbexSpecImpliesSetPC, pc_set_o |-> pc_set_spec_o)\n\nendmodule\n", "selected_doc_paths": ["doc/exception_interrupts.rst", "doc/debug.rst", "doc/instruction_fetch.rst", "doc/pipeline_details.rst", "doc/cs_registers.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1443, "lang": "sv", "rtl_files": ["rtl/ibex_tracer.sv"], "spec": "# Behavioral Design Specification: ibex_tracer\n\n## 1. Overview\n\nThe `ibex_tracer` module is a simulation-only component that records executed instructions of an Ibex (RISC-V) core into a human-readable log file. It uses the RISC-V Formal Interface (RVFI) standard signals to obtain instruction details, including program counter, register operands, and memory accesses. The trace output is formatted as tab‑separated columns, closely matching the output of `objdump -Mnumeric -Mno-aliases -D` to simplify correlation between static disassembly and runtime execution.\n\nThe tracer is intended for debugging, performance analysis, and verification of RISC‑V programs running on Ibex.\n\n## 2. I/O Signals (RVFI-based)\n\nThe module receives the following groups of signals (all synchronous to the rising edge of the clock):\n\n- **Clock and reset** – a free‑running clock and an active‑low asynchronous reset.\n- **Hart identifier** – a 32‑bit value identifying the core being traced (e.g., Hart ID).\n- **RVFI valid** – pulsed high for one clock cycle when a new instruction is committed.\n- **RVFI instruction details** – the raw instruction encoding, program counter (before execution), next program counter (PC after execution), source/destination register addresses and data, memory operation address and data, and qualification signals (trap, halt, interrupt, mode, etc.).\n\nThe module does **not** use the following RVFI signals (they are present for interface compatibility): `rvfi_order`, `rvfi_trap`, `rvfi_halt`, `rvfi_intr`, `rvfi_mode`, `rvfi_ixl`.\n\n## 3. Functional Behavior\n\n### 3.1 Trace Log File Creation\n\n- On the first valid instruction after reset (or when the module is first enabled), a log file is created.\n- The file name is `_.log`, where:\n - `` defaults to `\"trace_core\"`.\n - `` is the 8‑digit hexadecimal representation of the Hart ID input.\n- The file base may be overridden by the simulation plusarg `+ibex_tracer_file_base=`.\n- The log file includes a header line: \n `Time\\tCycle\\tPC\\tInsn\\tDecoded instruction\\tRegister and memory contents`\n\n### 3.2 Tracer Enable/Disable\n\n- By default, tracing is **enabled**.\n- The plusarg `+ibex_tracer_enable=<0|1>` can be used to disable (value 0) or enable (value 1) tracing.\n- When disabled, no file is created and no trace lines are written.\n- A message is printed to the simulation console when tracing is explicitly disabled.\n\n### 3.3 Logging on Instruction Commit\n\n- At every clock cycle where `rvfi_valid` is asserted and tracing is enabled, a single line is written to the log file.\n- The line contains six tab‑separated columns (see Section 4 for format).\n\n### 3.4 Cycle Counter\n\n- An internal cycle counter increments on every rising clock edge after reset.\n- The counter resets to zero when the reset is asserted.\n- The cycle count is included in the trace output.\n\n### 3.5 Instruction Decoding\n\nThe tracer must decode every committed instruction into a human‑readable assembly‑like mnemonic and operand string. Decoding shall follow these rules:\n\n- **Register names** – Always numeric (`x0`, `x1`, …, `x31`).\n- **CSR names** – Use the symbolic names defined in the RISC‑V privileged specification (e.g., `mstatus`, `mie`, `stvec`). Unrecognised CSR addresses are shown as `0x`.\n- **Immediate values** – Signed immediates appear as decimal numbers (e.g., `-1`, `12`). Unsigned immediates appear as hexadecimal (prefix `0x`), except for shift amounts which are also shown in hex.\n- **Jump and branch targets** – For unconditional jumps (`jal`, `c.jal`, `c.j`), the absolute target address (`PC + offset`) is shown. \n For conditional branches (`beq`, `bne`, etc.) and compressed branches (`c.beqz`, `c.bnez`), the absolute target address is computed as `current PC + sign‑extended immediate`.\n- **Pseudo‑instructions** – The decoder does **not** emit pseudo‑instructions (e.g., `nop` for `addi x0, x0, 0`); it always shows the base mnemonic.\n- **Invalid instructions** – If the instruction encoding does not match any known pattern, the decoded instruction field shall contain the string `\"INVALID\"`.\n\nThe decoder shall support all instruction encodings implemented by Ibex, including:\n\n- **Base ISA (RV32I)** – all integer, branch, load/store, CSR, fence, and system instructions.\n- **Compressed ISA (RV32C)** – all compressed instructions.\n- **Multiply/Divide extension (RV32M)** – `mul`, `mulh`, `mulhsu`, `mulhu`, `div`, `divu`, `rem`, `remu`.\n- **Bit‑manipulation extensions** – Zbb (basic), Zbs (single-bit), Zbe (bit extract/deposit), Zbp (permutation), Zbt (ternary), Zbf (bit‑field), Zbc (carry‑less multiply), Zbr (CRC).\n\n### 3.6 Register and Memory Content Reporting\n\nFor each instruction, the tracer shall record which operands were read and which were written. The reported values are the actual data observed on the RVFI interface.\n\n- **Register reads** – For every register that was read (source operands), the register name and its value before execution are listed.\n- **Register writes** – For the destination register, the register name and the value written are listed. The format uses `=` to denote a write (e.g., `x5=0x12345678`).\n- **Memory accesses** – For memory operations (loads, stores, and compressed loads/stores), the tracer shall report:\n - The physical address (`PA:0x`)\n - If the instruction wrote to memory (store): `store:0x`\n - If the instruction read from memory (load): `load:0x`\n\nThe tracer shall correctly distinguish between read, write, and read‑write accesses.\n\n### 3.7 Reset and File Closing\n\n- On assertion of the synchronous reset (active low), all internal state (cycle counter) is cleared.\n- The output log file remains open during normal operation.\n- At the end of simulation (via a `final` block), the log file is closed if open.\n\n## 4. Trace Output Format\n\nEach line of the log file (excluding the header) consists of six tab‑separated fields:\n\n1. **Time** – Simulation time as printed by `$time` (left‑justified in a 15‑character field).\n2. **Cycle** – Integer cycle count (decimal, left‑justified).\n3. **PC** – Program counter of the instruction (hexadecimal, no prefix, lead zeros omitted).\n4. **Insn** – Instruction encoding:\n - 32‑bit instructions: 8 hex digits (full 32‑bit instruction).\n - Compressed (16‑bit) instructions: 4 hex digits (bits 15:0).\n5. **Decoded instruction** – Mnemonic and operands as described in Section 3.5. Each operand is separated by a tab character from the mnemonic and from other operands.\n6. **Register and memory contents** – A possibly empty list of register and memory access records, separated by spaces. Records are formatted as:\n - Register read: `x:0x` (e.g., `x2:0x00002000`)\n - Register write: `x=0x` (e.g., `x8=0x00007fff`)\n - Memory: `PA:0x store:0x` and/or `load:0x`\n\nThe header line is written once at the beginning of the file.\n\n## 5. Configuration Parameters (Simulation Plusargs)\n\nThe module uses two simulation plusargs:\n\n| Plusarg | Type | Default | Description |\n|---------|------|---------|-------------|\n| `+ibex_tracer_file_base=` | string | `\"trace_core\"` | Base name of the output log file. |\n| `+ibex_tracer_enable=<0|1>` | bool | `1` (enabled) | Controls whether tracing is active. |\n\n## 6. Assumptions and Constraints\n\n- The module is intended for **simulation only** and uses SystemVerilog system calls (`$fopen`, `$fwrite`, `$fclose`, `$value$plusargs`, `$sformat`). It is not synthesizable.\n- The RVFI input signals must be stable and valid when `rvfi_valid` is high.\n- The module does not check for overflow of the cycle counter.\n- The tracer does **not** output any information about interrupts, traps, or mode changes except what can be inferred from the decoded instruction (e.g., `mret`).\n- The compressed instruction detection relies on the lower two bits of the instruction encoding not being `2'b11`.\n- The decoder assumes that RVFI source and destination register addresses reflect the actual architectural registers used (including `x0` being a source or destination).", "commit_id": "45f727dfc6e59119347aca62e38e69175f680bf6", "timestamp": "2021-10-01T16:51:18+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "873e2281cf9332e47119f61b2c1e32aa22c6d58e", "pr_title": "Remove unused RD in branch insn from tracer", "pr_body": "There is an unnecessary use of RD in branch instruction in `ibex_tracer.sv` which is removed. This PR resolves this issue #1441.\r\nhttps://github.com/lowRISC/ibex/blob/ac8934459b028220ce9fd20683bb018244b59756/rtl/ibex_tracer.sv#L493", "issue_title": "Use of RD in B type.", "issue_body": "https://github.com/lowRISC/ibex/blob/ac8934459b028220ce9fd20683bb018244b59756/rtl/ibex_tracer.sv#L493\r\n\r\nI am wondering why there is a use of RD in B-type instructions? Is this an issue or I am missing something.", "commit_message": "remove unused RD in branch insn from tracer", "fix_patch": "diff --git a/rtl/ibex_tracer.sv b/rtl/ibex_tracer.sv\nindex bbee71b662..be523686cb 100644\n--- a/rtl/ibex_tracer.sv\n+++ b/rtl/ibex_tracer.sv\n@@ -490,7 +490,7 @@ module ibex_tracer (\n rvfi_insn[30:25], rvfi_insn[11:8], 1'b0 });\n branch_target = rvfi_pc_rdata + imm;\n \n- data_accessed = RS1 | RS2 | RD;\n+ data_accessed = RS1 | RS2;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0x\",\n mnemonic, rvfi_rs1_addr, rvfi_rs2_addr, branch_target);\n endfunction\n", "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 * Trace executed instructions in simulation\n *\n * This tracer takes execution information from the RISC-V Verification Interface (RVFI) and\n * produces a text file with a human-readable trace.\n *\n * All traced instructions are written to a log file. By default, the log file is named\n * trace_core_.log, with being the 8 digit hart ID of the core being traced.\n *\n * The file name base, defaulting to \"trace_core\" can be set using the \"ibex_tracer_file_base\"\n * plusarg passed to the simulation, e.g. \"+ibex_tracer_file_base=ibex_my_trace\". The exact syntax\n * of passing plusargs to a simulation depends on the simulator.\n *\n * The creation of the instruction trace is enabled by default but can be disabled for a simulation.\n * This behaviour is controlled by the plusarg \"ibex_tracer_enable\". Use \"ibex_tracer_enable=0\" to\n * disable the tracer.\n *\n * The trace contains six columns, separated by tabs:\n * - The simulation time\n * - The clock cycle count since reset\n * - The program counter (PC)\n * - The instruction\n * - The decoded instruction in the same format as objdump, together with the accessed registers and\n * read/written memory values. Jumps and branches show the target address.\n * This column may be omitted if the instruction does not decode into a long form.\n * - Accessed registers and memory locations.\n *\n * Significant effort is spent to make the decoding produced by this tracer as similar as possible\n * to the one produced by objdump. This simplifies the correlation between the static program\n * information from the objdump-generated disassembly, and the runtime information from this tracer.\n */\nmodule ibex_tracer (\n input logic clk_i,\n input logic rst_ni,\n\n input logic [31:0] hart_id_i,\n\n // RVFI as described at https://github.com/SymbioticEDA/riscv-formal/blob/master/docs/rvfi.md\n // The standard interface does not have _i/_o suffixes. For consistency with the standard the\n // signals in this module don't have the suffixes either.\n input logic rvfi_valid,\n input logic [63:0] rvfi_order,\n input logic [31:0] rvfi_insn,\n input logic rvfi_trap,\n input logic rvfi_halt,\n input logic rvfi_intr,\n input logic [ 1:0] rvfi_mode,\n input logic [ 1:0] rvfi_ixl,\n input logic [ 4:0] rvfi_rs1_addr,\n input logic [ 4:0] rvfi_rs2_addr,\n input logic [ 4:0] rvfi_rs3_addr,\n input logic [31:0] rvfi_rs1_rdata,\n input logic [31:0] rvfi_rs2_rdata,\n input logic [31:0] rvfi_rs3_rdata,\n input logic [ 4:0] rvfi_rd_addr,\n input logic [31:0] rvfi_rd_wdata,\n input logic [31:0] rvfi_pc_rdata,\n input logic [31:0] rvfi_pc_wdata,\n input logic [31:0] rvfi_mem_addr,\n input logic [ 3:0] rvfi_mem_rmask,\n input logic [ 3:0] rvfi_mem_wmask,\n input logic [31:0] rvfi_mem_rdata,\n input logic [31:0] rvfi_mem_wdata\n);\n\n // These signals are part of RVFI, but not used in this module currently.\n // Keep them as part of the interface to change the tracer more easily in the future. Assigning\n // these signals to unused_* signals marks them explicitly as unused, an annotation picked up by\n // linters, including Verilator lint.\n logic [63:0] unused_rvfi_order = rvfi_order;\n logic unused_rvfi_trap = rvfi_trap;\n logic unused_rvfi_halt = rvfi_halt;\n logic unused_rvfi_intr = rvfi_intr;\n logic [ 1:0] unused_rvfi_mode = rvfi_mode;\n logic [ 1:0] unused_rvfi_ixl = rvfi_ixl;\n\n import ibex_tracer_pkg::*;\n\n int file_handle;\n string file_name;\n\n int unsigned cycle;\n string decoded_str;\n logic insn_is_compressed;\n\n // Data items accessed during this instruction\n localparam logic [4:0] RS1 = (1 << 0);\n localparam logic [4:0] RS2 = (1 << 1);\n localparam logic [4:0] RS3 = (1 << 2);\n localparam logic [4:0] RD = (1 << 3);\n localparam logic [4:0] MEM = (1 << 4);\n logic [4:0] data_accessed;\n\n logic trace_log_enable;\n initial begin\n if ($value$plusargs(\"ibex_tracer_enable=%b\", trace_log_enable)) begin\n if (trace_log_enable == 1'b0) begin\n $display(\"%m: Instruction trace disabled.\");\n end\n end else begin\n trace_log_enable = 1'b1;\n end\n end\n\n function automatic void printbuffer_dumpline();\n string rvfi_insn_str;\n\n if (file_handle == 32'h0) begin\n string file_name_base = \"trace_core\";\n $value$plusargs(\"ibex_tracer_file_base=%s\", file_name_base);\n $sformat(file_name, \"%s_%h.log\", file_name_base, hart_id_i);\n\n $display(\"%m: Writing execution trace to %s\", file_name);\n file_handle = $fopen(file_name, \"w\");\n $fwrite(file_handle,\n \"Time\\tCycle\\tPC\\tInsn\\tDecoded instruction\\tRegister and memory contents\\n\");\n end\n\n // Write compressed instructions as four hex digits (16 bit word), and\n // uncompressed ones as 8 hex digits (32 bit words).\n if (insn_is_compressed) begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn[15:0]);\n end else begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn);\n end\n\n $fwrite(file_handle, \"%15t\\t%d\\t%h\\t%s\\t%s\\t\",\n $time, cycle, rvfi_pc_rdata, rvfi_insn_str, decoded_str);\n\n if ((data_accessed & RS1) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs1_addr), rvfi_rs1_rdata);\n end\n if ((data_accessed & RS2) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs2_addr), rvfi_rs2_rdata);\n end\n if ((data_accessed & RS3) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs3_addr), rvfi_rs3_rdata);\n end\n if ((data_accessed & RD) != 0) begin\n $fwrite(file_handle, \" %s=0x%08x\", reg_addr_to_str(rvfi_rd_addr), rvfi_rd_wdata);\n end\n if ((data_accessed & MEM) != 0) begin\n $fwrite(file_handle, \" PA:0x%08x\", rvfi_mem_addr);\n\n if (rvfi_mem_rmask != 4'b0000) begin\n $fwrite(file_handle, \" store:0x%08x\", rvfi_mem_wdata);\n end\n if (rvfi_mem_wmask != 4'b0000) begin\n $fwrite(file_handle, \" load:0x%08x\", rvfi_mem_rdata);\n end\n end\n\n $fwrite(file_handle, \"\\n\");\n endfunction\n\n\n // Format register address with \"x\" prefix, left-aligned to a fixed width of 3 characters.\n function automatic string reg_addr_to_str(input logic [4:0] addr);\n if (addr < 10) begin\n return $sformatf(\" x%0d\", addr);\n end else begin\n return $sformatf(\"x%0d\", addr);\n end\n endfunction\n\n // Get a CSR name for a CSR address.\n function automatic string get_csr_name(input logic [11:0] csr_addr);\n unique case (csr_addr)\n 12'd0: return \"ustatus\";\n 12'd4: return \"uie\";\n 12'd5: return \"utvec\";\n 12'd64: return \"uscratch\";\n 12'd65: return \"uepc\";\n 12'd66: return \"ucause\";\n 12'd67: return \"utval\";\n 12'd68: return \"uip\";\n 12'd1: return \"fflags\";\n 12'd2: return \"frm\";\n 12'd3: return \"fcsr\";\n 12'd3072: return \"cycle\";\n 12'd3073: return \"time\";\n 12'd3074: return \"instret\";\n 12'd3075: return \"hpmcounter3\";\n 12'd3076: return \"hpmcounter4\";\n 12'd3077: return \"hpmcounter5\";\n 12'd3078: return \"hpmcounter6\";\n 12'd3079: return \"hpmcounter7\";\n 12'd3080: return \"hpmcounter8\";\n 12'd3081: return \"hpmcounter9\";\n 12'd3082: return \"hpmcounter10\";\n 12'd3083: return \"hpmcounter11\";\n 12'd3084: return \"hpmcounter12\";\n 12'd3085: return \"hpmcounter13\";\n 12'd3086: return \"hpmcounter14\";\n 12'd3087: return \"hpmcounter15\";\n 12'd3088: return \"hpmcounter16\";\n 12'd3089: return \"hpmcounter17\";\n 12'd3090: return \"hpmcounter18\";\n 12'd3091: return \"hpmcounter19\";\n 12'd3092: return \"hpmcounter20\";\n 12'd3093: return \"hpmcounter21\";\n 12'd3094: return \"hpmcounter22\";\n 12'd3095: return \"hpmcounter23\";\n 12'd3096: return \"hpmcounter24\";\n 12'd3097: return \"hpmcounter25\";\n 12'd3098: return \"hpmcounter26\";\n 12'd3099: return \"hpmcounter27\";\n 12'd3100: return \"hpmcounter28\";\n 12'd3101: return \"hpmcounter29\";\n 12'd3102: return \"hpmcounter30\";\n 12'd3103: return \"hpmcounter31\";\n 12'd3200: return \"cycleh\";\n 12'd3201: return \"timeh\";\n 12'd3202: return \"instreth\";\n 12'd3203: return \"hpmcounter3h\";\n 12'd3204: return \"hpmcounter4h\";\n 12'd3205: return \"hpmcounter5h\";\n 12'd3206: return \"hpmcounter6h\";\n 12'd3207: return \"hpmcounter7h\";\n 12'd3208: return \"hpmcounter8h\";\n 12'd3209: return \"hpmcounter9h\";\n 12'd3210: return \"hpmcounter10h\";\n 12'd3211: return \"hpmcounter11h\";\n 12'd3212: return \"hpmcounter12h\";\n 12'd3213: return \"hpmcounter13h\";\n 12'd3214: return \"hpmcounter14h\";\n 12'd3215: return \"hpmcounter15h\";\n 12'd3216: return \"hpmcounter16h\";\n 12'd3217: return \"hpmcounter17h\";\n 12'd3218: return \"hpmcounter18h\";\n 12'd3219: return \"hpmcounter19h\";\n 12'd3220: return \"hpmcounter20h\";\n 12'd3221: return \"hpmcounter21h\";\n 12'd3222: return \"hpmcounter22h\";\n 12'd3223: return \"hpmcounter23h\";\n 12'd3224: return \"hpmcounter24h\";\n 12'd3225: return \"hpmcounter25h\";\n 12'd3226: return \"hpmcounter26h\";\n 12'd3227: return \"hpmcounter27h\";\n 12'd3228: return \"hpmcounter28h\";\n 12'd3229: return \"hpmcounter29h\";\n 12'd3230: return \"hpmcounter30h\";\n 12'd3231: return \"hpmcounter31h\";\n 12'd256: return \"sstatus\";\n 12'd258: return \"sedeleg\";\n 12'd259: return \"sideleg\";\n 12'd260: return \"sie\";\n 12'd261: return \"stvec\";\n 12'd262: return \"scounteren\";\n 12'd320: return \"sscratch\";\n 12'd321: return \"sepc\";\n 12'd322: return \"scause\";\n 12'd323: return \"stval\";\n 12'd324: return \"sip\";\n 12'd384: return \"satp\";\n 12'd3857: return \"mvendorid\";\n 12'd3858: return \"marchid\";\n 12'd3859: return \"mimpid\";\n 12'd3860: return \"mhartid\";\n 12'd768: return \"mstatus\";\n 12'd769: return \"misa\";\n 12'd770: return \"medeleg\";\n 12'd771: return \"mideleg\";\n 12'd772: return \"mie\";\n 12'd773: return \"mtvec\";\n 12'd774: return \"mcounteren\";\n 12'd832: return \"mscratch\";\n 12'd833: return \"mepc\";\n 12'd834: return \"mcause\";\n 12'd835: return \"mtval\";\n 12'd836: return \"mip\";\n 12'd928: return \"pmpcfg0\";\n 12'd929: return \"pmpcfg1\";\n 12'd930: return \"pmpcfg2\";\n 12'd931: return \"pmpcfg3\";\n 12'd944: return \"pmpaddr0\";\n 12'd945: return \"pmpaddr1\";\n 12'd946: return \"pmpaddr2\";\n 12'd947: return \"pmpaddr3\";\n 12'd948: return \"pmpaddr4\";\n 12'd949: return \"pmpaddr5\";\n 12'd950: return \"pmpaddr6\";\n 12'd951: return \"pmpaddr7\";\n 12'd952: return \"pmpaddr8\";\n 12'd953: return \"pmpaddr9\";\n 12'd954: return \"pmpaddr10\";\n 12'd955: return \"pmpaddr11\";\n 12'd956: return \"pmpaddr12\";\n 12'd957: return \"pmpaddr13\";\n 12'd958: return \"pmpaddr14\";\n 12'd959: return \"pmpaddr15\";\n 12'd2816: return \"mcycle\";\n 12'd2818: return \"minstret\";\n 12'd2819: return \"mhpmcounter3\";\n 12'd2820: return \"mhpmcounter4\";\n 12'd2821: return \"mhpmcounter5\";\n 12'd2822: return \"mhpmcounter6\";\n 12'd2823: return \"mhpmcounter7\";\n 12'd2824: return \"mhpmcounter8\";\n 12'd2825: return \"mhpmcounter9\";\n 12'd2826: return \"mhpmcounter10\";\n 12'd2827: return \"mhpmcounter11\";\n 12'd2828: return \"mhpmcounter12\";\n 12'd2829: return \"mhpmcounter13\";\n 12'd2830: return \"mhpmcounter14\";\n 12'd2831: return \"mhpmcounter15\";\n 12'd2832: return \"mhpmcounter16\";\n 12'd2833: return \"mhpmcounter17\";\n 12'd2834: return \"mhpmcounter18\";\n 12'd2835: return \"mhpmcounter19\";\n 12'd2836: return \"mhpmcounter20\";\n 12'd2837: return \"mhpmcounter21\";\n 12'd2838: return \"mhpmcounter22\";\n 12'd2839: return \"mhpmcounter23\";\n 12'd2840: return \"mhpmcounter24\";\n 12'd2841: return \"mhpmcounter25\";\n 12'd2842: return \"mhpmcounter26\";\n 12'd2843: return \"mhpmcounter27\";\n 12'd2844: return \"mhpmcounter28\";\n 12'd2845: return \"mhpmcounter29\";\n 12'd2846: return \"mhpmcounter30\";\n 12'd2847: return \"mhpmcounter31\";\n 12'd2944: return \"mcycleh\";\n 12'd2946: return \"minstreth\";\n 12'd2947: return \"mhpmcounter3h\";\n 12'd2948: return \"mhpmcounter4h\";\n 12'd2949: return \"mhpmcounter5h\";\n 12'd2950: return \"mhpmcounter6h\";\n 12'd2951: return \"mhpmcounter7h\";\n 12'd2952: return \"mhpmcounter8h\";\n 12'd2953: return \"mhpmcounter9h\";\n 12'd2954: return \"mhpmcounter10h\";\n 12'd2955: return \"mhpmcounter11h\";\n 12'd2956: return \"mhpmcounter12h\";\n 12'd2957: return \"mhpmcounter13h\";\n 12'd2958: return \"mhpmcounter14h\";\n 12'd2959: return \"mhpmcounter15h\";\n 12'd2960: return \"mhpmcounter16h\";\n 12'd2961: return \"mhpmcounter17h\";\n 12'd2962: return \"mhpmcounter18h\";\n 12'd2963: return \"mhpmcounter19h\";\n 12'd2964: return \"mhpmcounter20h\";\n 12'd2965: return \"mhpmcounter21h\";\n 12'd2966: return \"mhpmcounter22h\";\n 12'd2967: return \"mhpmcounter23h\";\n 12'd2968: return \"mhpmcounter24h\";\n 12'd2969: return \"mhpmcounter25h\";\n 12'd2970: return \"mhpmcounter26h\";\n 12'd2971: return \"mhpmcounter27h\";\n 12'd2972: return \"mhpmcounter28h\";\n 12'd2973: return \"mhpmcounter29h\";\n 12'd2974: return \"mhpmcounter30h\";\n 12'd2975: return \"mhpmcounter31h\";\n 12'd803: return \"mhpmevent3\";\n 12'd804: return \"mhpmevent4\";\n 12'd805: return \"mhpmevent5\";\n 12'd806: return \"mhpmevent6\";\n 12'd807: return \"mhpmevent7\";\n 12'd808: return \"mhpmevent8\";\n 12'd809: return \"mhpmevent9\";\n 12'd810: return \"mhpmevent10\";\n 12'd811: return \"mhpmevent11\";\n 12'd812: return \"mhpmevent12\";\n 12'd813: return \"mhpmevent13\";\n 12'd814: return \"mhpmevent14\";\n 12'd815: return \"mhpmevent15\";\n 12'd816: return \"mhpmevent16\";\n 12'd817: return \"mhpmevent17\";\n 12'd818: return \"mhpmevent18\";\n 12'd819: return \"mhpmevent19\";\n 12'd820: return \"mhpmevent20\";\n 12'd821: return \"mhpmevent21\";\n 12'd822: return \"mhpmevent22\";\n 12'd823: return \"mhpmevent23\";\n 12'd824: return \"mhpmevent24\";\n 12'd825: return \"mhpmevent25\";\n 12'd826: return \"mhpmevent26\";\n 12'd827: return \"mhpmevent27\";\n 12'd828: return \"mhpmevent28\";\n 12'd829: return \"mhpmevent29\";\n 12'd830: return \"mhpmevent30\";\n 12'd831: return \"mhpmevent31\";\n 12'd1952: return \"tselect\";\n 12'd1953: return \"tdata1\";\n 12'd1954: return \"tdata2\";\n 12'd1955: return \"tdata3\";\n 12'd1968: return \"dcsr\";\n 12'd1969: return \"dpc\";\n 12'd1970: return \"dscratch\";\n 12'd512: return \"hstatus\";\n 12'd514: return \"hedeleg\";\n 12'd515: return \"hideleg\";\n 12'd516: return \"hie\";\n 12'd517: return \"htvec\";\n 12'd576: return \"hscratch\";\n 12'd577: return \"hepc\";\n 12'd578: return \"hcause\";\n 12'd579: return \"hbadaddr\";\n 12'd580: return \"hip\";\n 12'd896: return \"mbase\";\n 12'd897: return \"mbound\";\n 12'd898: return \"mibase\";\n 12'd899: return \"mibound\";\n 12'd900: return \"mdbase\";\n 12'd901: return \"mdbound\";\n 12'd800: return \"mcountinhibit\";\n default: return $sformatf(\"0x%x\", csr_addr);\n endcase\n endfunction\n\n function automatic void decode_mnemonic(input string mnemonic);\n decoded_str = mnemonic;\n endfunction\n\n function automatic void decode_r_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr,\n rvfi_rs2_addr);\n endfunction\n\n function automatic void decode_r1_insn(input string mnemonic);\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr);\n endfunction\n\n function automatic void decode_r_cmixcmov_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RS3 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,x%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr,\n rvfi_rs1_addr, rvfi_rs3_addr);\n endfunction\n\n function automatic void decode_r_funnelshift_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RS3 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,x%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr,\n rvfi_rs3_addr, rvfi_rs2_addr);\n endfunction\n\n function automatic void decode_i_insn(input string mnemonic);\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}));\n endfunction\n\n function automatic void decode_i_shift_insn(input string mnemonic);\n // SLLI, SRLI, SRAI, SROI, SLOI, RORI\n logic [4:0] shamt;\n shamt = {rvfi_insn[24:20]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,0x%0x\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr, shamt);\n endfunction\n\n function automatic void decode_i_funnelshift_insn( input string mnemonic);\n // fsri\n logic [5:0] shamt;\n shamt = {rvfi_insn[25:20]};\n data_accessed = RS1 | RS3 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,x%0d,0x%0x\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr,\n rvfi_rs3_addr, shamt);\n endfunction\n\n function automatic void decode_i_jalr_insn(input string mnemonic);\n // JALR\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function automatic void decode_u_insn(input string mnemonic);\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, {rvfi_insn[31:12]});\n endfunction\n\n function automatic void decode_j_insn(input string mnemonic);\n // JAL\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rd_addr, rvfi_pc_wdata);\n endfunction\n\n function automatic void decode_b_insn(input string mnemonic);\n logic [31:0] branch_target;\n logic [31:0] imm;\n\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = $signed({ {19 {rvfi_insn[31]}}, rvfi_insn[31], rvfi_insn[7],\n rvfi_insn[30:25], rvfi_insn[11:8], 1'b0 });\n branch_target = rvfi_pc_rdata + imm;\n\n data_accessed = RS1 | RS2;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0x\",\n mnemonic, rvfi_rs1_addr, rvfi_rs2_addr, branch_target);\n endfunction\n\n function automatic void decode_csr_insn(input string mnemonic);\n logic [11:0] csr;\n string csr_name;\n csr = rvfi_insn[31:20];\n csr_name = get_csr_name(csr);\n\n data_accessed = RD;\n\n if (!rvfi_insn[14]) begin\n data_accessed |= RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%s,x%0d\",\n mnemonic, rvfi_rd_addr, csr_name, rvfi_rs1_addr);\n end else begin\n decoded_str = $sformatf(\"%s\\tx%0d,%s,%0d\",\n mnemonic, rvfi_rd_addr, csr_name, {27'b0, rvfi_insn[19:15]});\n end\n endfunction\n\n function automatic void decode_cr_insn(input string mnemonic);\n if (rvfi_rs2_addr == 5'b0) begin\n if (rvfi_insn[12] == 1'b1) begin\n // C.JALR\n data_accessed = RS1 | RD;\n end else begin\n // C.JR\n data_accessed = RS1;\n end\n decoded_str = $sformatf(\"%s\\tx%0d\", mnemonic, rvfi_rs1_addr);\n end else begin\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n end\n endfunction\n\n function automatic void decode_ci_cli_insn(input string mnemonic);\n logic [5:0] imm;\n imm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n endfunction\n\n function automatic void decode_ci_caddi_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function automatic void decode_ci_caddi16sp_insn(input string mnemonic);\n logic [9:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[4:3], rvfi_insn[5], rvfi_insn[2], rvfi_insn[6], 4'b0};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function automatic void decode_ci_clui_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, 20'($signed(nzimm)));\n endfunction\n\n function automatic void decode_ci_cslli_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, shamt);\n endfunction\n\n function automatic void decode_ciw_insn(input string mnemonic);\n // C.ADDI4SPN\n logic [9:0] nzuimm;\n nzuimm = {rvfi_insn[10:7], rvfi_insn[12:11], rvfi_insn[5], rvfi_insn[6], 2'b00};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x2,%0d\", mnemonic, rvfi_rd_addr, nzuimm);\n endfunction\n\n function automatic void decode_cb_sr_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, shamt);\n endfunction\n\n function automatic void decode_cb_insn(input string mnemonic);\n logic [7:0] imm;\n logic [31:0] jump_target;\n if (rvfi_insn[15:13] == 3'b110 || rvfi_insn[15:13] == 3'b111) begin\n // C.BNEZ and C.BEQZ\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = {rvfi_insn[12], rvfi_insn[6:5], rvfi_insn[2], rvfi_insn[11:10], rvfi_insn[4:3]};\n jump_target = rvfi_pc_rdata + 32'($signed({imm, 1'b0}));\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rs1_addr, jump_target);\n end else if (rvfi_insn[15:13] == 3'b100) begin\n // C.ANDI\n imm = {{2{rvfi_insn[12]}}, rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n end else begin\n imm = {rvfi_insn[12], rvfi_insn[6:2], 2'b00};\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, imm);\n end\n endfunction\n\n function automatic void decode_cs_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n endfunction\n\n function automatic void decode_cj_insn(input string mnemonic);\n if (rvfi_insn[15:13] == 3'b001) begin\n // C.JAL\n data_accessed = RD;\n end\n decoded_str = $sformatf(\"%s\\t%0x\", mnemonic, rvfi_pc_wdata);\n endfunction\n\n function automatic void decode_compressed_load_insn(input string mnemonic);\n logic [7:0] imm;\n\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.LW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.LWSP\n imm = {rvfi_insn[3:2], rvfi_insn[12], rvfi_insn[6:4], 2'b00};\n end\n data_accessed = RS1 | RD | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function automatic void decode_compressed_store_insn(input string mnemonic);\n logic [7:0] imm;\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.SW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.SWSP\n imm = {rvfi_insn[8:7], rvfi_insn[12:9], 2'b00};\n end\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rs2_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function automatic void decode_load_insn();\n string mnemonic;\n\n /*\n Gives wrong results in Verilator < 4.020.\n See https://github.com/lowRISC/ibex/issues/372 and\n https://www.veripool.org/issues/1536-Verilator-Misoptimization-in-if-and-case-with-default-statement-inside-a-function\n\n unique case (rvfi_insn[14:12])\n 3'b000: mnemonic = \"lb\";\n 3'b001: mnemonic = \"lh\";\n 3'b010: mnemonic = \"lw\";\n 3'b100: mnemonic = \"lbu\";\n 3'b101: mnemonic = \"lhu\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n */\n logic [2:0] size;\n size = rvfi_insn[14:12];\n if (size == 3'b000) begin\n mnemonic = \"lb\";\n end else if (size == 3'b001) begin\n mnemonic = \"lh\";\n end else if (size == 3'b010) begin\n mnemonic = \"lw\";\n end else if (size == 3'b100) begin\n mnemonic = \"lbu\";\n end else if (size == 3'b101) begin\n mnemonic = \"lhu\";\n end else begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n\n\n data_accessed = RD | RS1 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function automatic void decode_store_insn();\n string mnemonic;\n\n unique case (rvfi_insn[13:12])\n 2'b00: mnemonic = \"sb\";\n 2'b01: mnemonic = \"sh\";\n 2'b10: mnemonic = \"sw\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n\n if (!rvfi_insn[14]) begin\n // regular store\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\",\n mnemonic,\n rvfi_rs2_addr,\n $signed({{20{rvfi_insn[31]}}, rvfi_insn[31:25], rvfi_insn[11:7]}),\n rvfi_rs1_addr);\n end else begin\n decode_mnemonic(\"INVALID\");\n end\n endfunction\n\n function automatic string get_fence_description(logic [3:0] bits);\n string desc = \"\";\n if (bits[3]) begin\n desc = {desc, \"i\"};\n end\n if (bits[2]) begin\n desc = {desc, \"o\"};\n end\n if (bits[1]) begin\n desc = {desc, \"r\"};\n end\n if (bits[0]) begin\n desc = {desc, \"w\"};\n end\n return desc;\n endfunction\n\n function automatic void decode_fence();\n string predecessor;\n string successor;\n predecessor = get_fence_description(rvfi_insn[27:24]);\n successor = get_fence_description(rvfi_insn[23:20]);\n decoded_str = $sformatf(\"fence\\t%s,%s\", predecessor, successor);\n endfunction\n\n // cycle counter\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n cycle <= 0;\n end else begin\n cycle <= cycle + 1;\n end\n end\n\n // close output file for writing\n final begin\n if (file_handle != 32'h0) begin\n $fclose(file_handle);\n end\n end\n\n // log execution\n always_ff @(posedge clk_i) begin\n if (rvfi_valid && trace_log_enable) begin\n printbuffer_dumpline();\n end\n end\n\n always_comb begin\n decoded_str = \"\";\n data_accessed = 5'h0;\n insn_is_compressed = 0;\n\n // Check for compressed instructions\n if (rvfi_insn[1:0] != 2'b11) begin\n insn_is_compressed = 1;\n // Separate case to avoid overlapping decoding\n if (rvfi_insn[15:13] == INSN_CMV[15:13] && rvfi_insn[1:0] == OPCODE_C2) begin\n if (rvfi_insn[12] == INSN_CADD[12]) begin\n if (rvfi_insn[11:2] == INSN_CEBREAK[11:2]) begin\n decode_mnemonic(\"c.ebreak\");\n end else if (rvfi_insn[6:2] == INSN_CJALR[6:2]) begin\n decode_cr_insn(\"c.jalr\");\n end else begin\n decode_cr_insn(\"c.add\");\n end\n end else begin\n if (rvfi_insn[6:2] == INSN_CJR[6:2]) begin\n decode_cr_insn(\"c.jr\");\n end else begin\n decode_cr_insn(\"c.mv\");\n end\n end\n end else begin\n unique casez (rvfi_insn[15:0])\n // C0 Opcodes\n INSN_CADDI4SPN: begin\n if (rvfi_insn[12:2] == 11'h0) begin\n // Align with pseudo-mnemonic used by GNU binutils and LLVM's MC layer\n decode_mnemonic(\"c.unimp\");\n end else begin\n decode_ciw_insn(\"c.addi4spn\");\n end\n end\n INSN_CLW: decode_compressed_load_insn(\"c.lw\");\n INSN_CSW: decode_compressed_store_insn(\"c.sw\");\n // C1 Opcodes\n INSN_CADDI: decode_ci_caddi_insn(\"c.addi\");\n INSN_CJAL: decode_cj_insn(\"c.jal\");\n INSN_CJ: decode_cj_insn(\"c.j\");\n INSN_CLI: decode_ci_cli_insn(\"c.li\");\n INSN_CLUI: begin\n // These two instructions share opcode\n if (rvfi_insn[11:7] == 5'd2) begin\n decode_ci_caddi16sp_insn(\"c.addi16sp\");\n end else begin\n decode_ci_clui_insn(\"c.lui\");\n end\n end\n INSN_CSRLI: decode_cb_sr_insn(\"c.srli\");\n INSN_CSRAI: decode_cb_sr_insn(\"c.srai\");\n INSN_CANDI: decode_cb_insn(\"c.andi\");\n INSN_CSUB: decode_cs_insn(\"c.sub\");\n INSN_CXOR: decode_cs_insn(\"c.xor\");\n INSN_COR: decode_cs_insn(\"c.or\");\n INSN_CAND: decode_cs_insn(\"c.and\");\n INSN_CBEQZ: decode_cb_insn(\"c.beqz\");\n INSN_CBNEZ: decode_cb_insn(\"c.bnez\");\n // C2 Opcodes\n INSN_CSLLI: decode_ci_cslli_insn(\"c.slli\");\n INSN_CLWSP: decode_compressed_load_insn(\"c.lwsp\");\n INSN_SWSP: decode_compressed_store_insn(\"c.swsp\");\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end else begin\n unique casez (rvfi_insn)\n // Regular opcodes\n INSN_LUI: decode_u_insn(\"lui\");\n INSN_AUIPC: decode_u_insn(\"auipc\");\n INSN_JAL: decode_j_insn(\"jal\");\n INSN_JALR: decode_i_jalr_insn(\"jalr\");\n // BRANCH\n INSN_BEQ: decode_b_insn(\"beq\");\n INSN_BNE: decode_b_insn(\"bne\");\n INSN_BLT: decode_b_insn(\"blt\");\n INSN_BGE: decode_b_insn(\"bge\");\n INSN_BLTU: decode_b_insn(\"bltu\");\n INSN_BGEU: decode_b_insn(\"bgeu\");\n // OPIMM\n INSN_ADDI: begin\n if (rvfi_insn == 32'h00_00_00_13) begin\n // TODO: objdump doesn't decode this as nop currently, even though it would be helpful\n // Decide what to do here: diverge from objdump, or make the trace less readable to\n // users.\n //decode_mnemonic(\"nop\");\n decode_i_insn(\"addi\");\n end else begin\n decode_i_insn(\"addi\");\n end\n end\n INSN_SLTI: decode_i_insn(\"slti\");\n INSN_SLTIU: decode_i_insn(\"sltiu\");\n INSN_XORI: decode_i_insn(\"xori\");\n INSN_ORI: decode_i_insn(\"ori\");\n // Version 0.92 of the Bitmanip Extension defines the pseudo-instruction\n // zext.b rd rs = andi rd, rs, 255.\n // Currently instruction set simulators don't output this pseudo-instruction.\n INSN_ANDI: decode_i_insn(\"andi\");\n // INSN_ANDI:begin\n // casez (rvfi_insn)\n // INSN_ZEXTB: decode_r1_insn(\"zext.b\");\n // default: decode_i_insn(\"andi\");\n // endcase\n // end\n INSN_SLLI: decode_i_shift_insn(\"slli\");\n INSN_SRLI: decode_i_shift_insn(\"srli\");\n INSN_SRAI: decode_i_shift_insn(\"srai\");\n // OP\n INSN_ADD: decode_r_insn(\"add\");\n INSN_SUB: decode_r_insn(\"sub\");\n INSN_SLL: decode_r_insn(\"sll\");\n INSN_SLT: decode_r_insn(\"slt\");\n INSN_SLTU: decode_r_insn(\"sltu\");\n INSN_XOR: decode_r_insn(\"xor\");\n INSN_SRL: decode_r_insn(\"srl\");\n INSN_SRA: decode_r_insn(\"sra\");\n INSN_OR: decode_r_insn(\"or\");\n INSN_AND: decode_r_insn(\"and\");\n // SYSTEM (CSR manipulation)\n INSN_CSRRW: decode_csr_insn(\"csrrw\");\n INSN_CSRRS: decode_csr_insn(\"csrrs\");\n INSN_CSRRC: decode_csr_insn(\"csrrc\");\n INSN_CSRRWI: decode_csr_insn(\"csrrwi\");\n INSN_CSRRSI: decode_csr_insn(\"csrrsi\");\n INSN_CSRRCI: decode_csr_insn(\"csrrci\");\n // SYSTEM (others)\n INSN_ECALL: decode_mnemonic(\"ecall\");\n INSN_EBREAK: decode_mnemonic(\"ebreak\");\n INSN_MRET: decode_mnemonic(\"mret\");\n INSN_DRET: decode_mnemonic(\"dret\");\n INSN_WFI: decode_mnemonic(\"wfi\");\n // RV32M\n INSN_PMUL: decode_r_insn(\"mul\");\n INSN_PMUH: decode_r_insn(\"mulh\");\n INSN_PMULHSU: decode_r_insn(\"mulhsu\");\n INSN_PMULHU: decode_r_insn(\"mulhu\");\n INSN_DIV: decode_r_insn(\"div\");\n INSN_DIVU: decode_r_insn(\"divu\");\n INSN_REM: decode_r_insn(\"rem\");\n INSN_REMU: decode_r_insn(\"remu\");\n // LOAD & STORE\n INSN_LOAD: decode_load_insn();\n INSN_STORE: decode_store_insn();\n // MISC-MEM\n INSN_FENCE: decode_fence();\n INSN_FENCEI: decode_mnemonic(\"fence.i\");\n // RV32B - ZBB\n INSN_SLOI: decode_i_shift_insn(\"sloi\");\n INSN_SROI: decode_i_shift_insn(\"sroi\");\n INSN_RORI: decode_i_shift_insn(\"rori\");\n INSN_SLO: decode_r_insn(\"slo\");\n INSN_SRO: decode_r_insn(\"sro\");\n INSN_ROL: decode_r_insn(\"rol\");\n INSN_ROR: decode_r_insn(\"ror\");\n INSN_MIN: decode_r_insn(\"min\");\n INSN_MAX: decode_r_insn(\"max\");\n INSN_MINU: decode_r_insn(\"minu\");\n INSN_MAXU: decode_r_insn(\"maxu\");\n INSN_XNOR: decode_r_insn(\"xnor\");\n INSN_ORN: decode_r_insn(\"orn\");\n INSN_ANDN: decode_r_insn(\"andn\");\n // Version 0.92 of the Bitmanip Extension defines the pseudo-instruction\n // zext.h rd rs = pack rd, rs, zero.\n // Currently instruction set simulators don't output this pseudo-instruction.\n INSN_PACK: decode_r_insn(\"pack\");\n // INSN_PACK: begin\n // casez (rvfi_insn)\n // INSN_ZEXTH: decode_r1_insn(\"zext.h\");\n // default: decode_r_insn(\"pack\");\n // endcase\n // end\n INSN_PACKH: decode_r_insn(\"packh\");\n INSN_PACKU: decode_r_insn(\"packu\");\n INSN_CLZ: decode_r1_insn(\"clz\");\n INSN_CTZ: decode_r1_insn(\"ctz\");\n INSN_PCNT: decode_r1_insn(\"pcnt\");\n INSN_SEXTB: decode_r1_insn(\"sext.b\");\n INSN_SEXTH: decode_r1_insn(\"sext.h\");\n // RV32B - ZBS\n INSN_SBCLRI: decode_i_insn(\"sbclri\");\n INSN_SBSETI: decode_i_insn(\"sbseti\");\n INSN_SBINVI: decode_i_insn(\"sbinvi\");\n INSN_SBEXTI: decode_i_insn(\"sbexti\");\n INSN_SBCLR: decode_r_insn(\"sbclr\");\n INSN_SBSET: decode_r_insn(\"sbset\");\n INSN_SBINV: decode_r_insn(\"sbinv\");\n INSN_SBEXT: decode_r_insn(\"sbext\");\n // RV32B - ZBE\n INSN_BDEP: decode_r_insn(\"bdep\");\n INSN_BEXT: decode_r_insn(\"bext\");\n // RV32B - ZBP\n INSN_GREV: decode_r_insn(\"grev\");\n INSN_GREVI: begin\n unique casez (rvfi_insn)\n INSN_REV_P: decode_r1_insn(\"rev.p\");\n INSN_REV2_N: decode_r1_insn(\"rev2.n\");\n INSN_REV_N: decode_r1_insn(\"rev.n\");\n INSN_REV4_B: decode_r1_insn(\"rev4.b\");\n INSN_REV2_B: decode_r1_insn(\"rev2.b\");\n INSN_REV_B: decode_r1_insn(\"rev.b\");\n INSN_REV8_H: decode_r1_insn(\"rev8.h\");\n INSN_REV4_H: decode_r1_insn(\"rev4.h\");\n INSN_REV2_H: decode_r1_insn(\"rev2.h\");\n INSN_REV_H: decode_r1_insn(\"rev.h\");\n INSN_REV16: decode_r1_insn(\"rev16\");\n INSN_REV8: decode_r1_insn(\"rev8\");\n INSN_REV4: decode_r1_insn(\"rev4\");\n INSN_REV2: decode_r1_insn(\"rev2\");\n INSN_REV: decode_r1_insn(\"rev\");\n default: decode_i_insn(\"grevi\");\n endcase\n end\n INSN_GORC: decode_r_insn(\"gorc\");\n INSN_GORCI: begin\n unique casez (rvfi_insn)\n INSN_ORC_P: decode_r1_insn(\"orc.p\");\n INSN_ORC2_N: decode_r1_insn(\"orc2.n\");\n INSN_ORC_N: decode_r1_insn(\"orc.n\");\n INSN_ORC4_B: decode_r1_insn(\"orc4.b\");\n INSN_ORC2_B: decode_r1_insn(\"orc2.b\");\n INSN_ORC_B: decode_r1_insn(\"orc.b\");\n INSN_ORC8_H: decode_r1_insn(\"orc8.h\");\n INSN_ORC4_H: decode_r1_insn(\"orc4.h\");\n INSN_ORC2_H: decode_r1_insn(\"orc2.h\");\n INSN_ORC_H: decode_r1_insn(\"orc.h\");\n INSN_ORC16: decode_r1_insn(\"orc16\");\n INSN_ORC8: decode_r1_insn(\"orc8\");\n INSN_ORC4: decode_r1_insn(\"orc4\");\n INSN_ORC2: decode_r1_insn(\"orc2\");\n INSN_ORC: decode_r1_insn(\"orc\");\n default: decode_i_insn(\"gorci\");\n endcase\n end\n INSN_SHFL: decode_r_insn(\"shfl\");\n INSN_SHFLI: begin\n unique casez (rvfi_insn)\n INSN_ZIP_N: decode_r1_insn(\"zip.n\");\n INSN_ZIP2_B: decode_r1_insn(\"zip2.b\");\n INSN_ZIP_B: decode_r1_insn(\"zip.b\");\n INSN_ZIP4_H: decode_r1_insn(\"zip4.h\");\n INSN_ZIP2_H: decode_r1_insn(\"zip2.h\");\n INSN_ZIP_H: decode_r1_insn(\"zip.h\");\n INSN_ZIP8: decode_r1_insn(\"zip8\");\n INSN_ZIP4: decode_r1_insn(\"zip4\");\n INSN_ZIP2: decode_r1_insn(\"zip2\");\n INSN_ZIP: decode_r1_insn(\"zip\");\n default: decode_i_insn(\"shfli\");\n endcase\n end\n INSN_UNSHFL: decode_r_insn(\"unshfl\");\n INSN_UNSHFLI: begin\n unique casez (rvfi_insn)\n INSN_UNZIP_N: decode_r1_insn(\"unzip.n\");\n INSN_UNZIP2_B: decode_r1_insn(\"unzip2.b\");\n INSN_UNZIP_B: decode_r1_insn(\"unzip.b\");\n INSN_UNZIP4_H: decode_r1_insn(\"unzip4.h\");\n INSN_UNZIP2_H: decode_r1_insn(\"unzip2.h\");\n INSN_UNZIP_H: decode_r1_insn(\"unzip.h\");\n INSN_UNZIP8: decode_r1_insn(\"unzip8\");\n INSN_UNZIP4: decode_r1_insn(\"unzip4\");\n INSN_UNZIP2: decode_r1_insn(\"unzip2\");\n INSN_UNZIP: decode_r1_insn(\"unzip\");\n default: decode_i_insn(\"unshfli\");\n endcase\n end\n\n // RV32B - ZBT\n INSN_CMIX: decode_r_cmixcmov_insn(\"cmix\");\n INSN_CMOV: decode_r_cmixcmov_insn(\"cmov\");\n INSN_FSR: decode_r_funnelshift_insn(\"fsr\");\n INSN_FSL: decode_r_funnelshift_insn(\"fsl\");\n INSN_FSRI: decode_i_funnelshift_insn(\"fsri\");\n\n // RV32B - ZBF\n INSN_BFP: decode_r_insn(\"bfp\");\n\n // RV32B - ZBC\n INSN_CLMUL: decode_r_insn(\"clmul\");\n INSN_CLMULR: decode_r_insn(\"clmulr\");\n INSN_CLMULH: decode_r_insn(\"clmulh\");\n\n // RV32B - ZBR\n INSN_CRC32_B: decode_r1_insn(\"crc32.b\");\n INSN_CRC32_H: decode_r1_insn(\"crc32.h\");\n INSN_CRC32_W: decode_r1_insn(\"crc32.w\");\n INSN_CRC32C_B: decode_r1_insn(\"crc32c.b\");\n INSN_CRC32C_H: decode_r1_insn(\"crc32c.h\");\n INSN_CRC32C_W: decode_r1_insn(\"crc32c.w\");\n\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/tracer.rst", "doc/03_reference/rvfi.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1179, "lang": "sv", "rtl_files": ["rtl/ibex_pmp.sv"], "spec": "# Physical Memory Protection (PMP) Module Specification\n\n## Overview\n\nThe Physical Memory Protection (PMP) module enforces per-region access permissions on physical addresses. It implements the PMP mechanism defined in the RISC-V Privileged Architecture Specification (version 1.11). The module checks every memory access from the instruction fetch and load/store units (channels) against a programmable set of PMP regions and either permits or denies the access accordingly.\n\n## Parameters\n\nThe following configuration parameters control the module's behavior:\n\n- **`PMPGranularity`** \n Minimum region size exponent (base 2). A value of 0 means no additional granularity restriction (minimum region size is 4 bytes). A value of *G* imposes a minimum region size of \\(2^{(G+2)}\\) bytes. When `PMPGranularity > 0`, the NA4 mode is not available and any region configured as NA4 shall behave as OFF.\n\n- **`PMPNumChan`** \n Number of independent access channels (e.g., one for instruction fetch, one for load/store). All channels operate identically and in parallel.\n\n- **`PMPNumRegions`** \n Number of PMP regions implemented, from 1 to 16. Each region has its own configuration register and address register.\n\n## Interface Signals\n\n### Clock and Reset\n- Clock and active-low reset control all sequential elements.\n\n### Configuration Inputs\n- For each PMP region, the module receives:\n - A configuration word containing:\n - Operating mode (OFF, NA4, NAPOT, TOR).\n - Permission bits: read, write, execute.\n - Lock bit (L).\n - An address value (34 bits wide, representing bits [33:0] of the physical address). The interpretation of this address depends on the region's mode.\n\n### Channel Request Inputs\n- For each channel, the module receives:\n - The privilege level of the current access (Machine, Supervisor, or User).\n - The physical address of the access (34 bits).\n - The access type: read, write, or execute.\n\n### Channel Outputs\n- For each channel, a single error flag is asserted when the access is denied. When the flag is deasserted, the access is permitted.\n\n## Functional Behavior\n\n### Access Decision per Channel\n\nEach channel independently evaluates all PMP regions and produces a single access-fault indication. The evaluation follows these rules:\n\n1. **Default Permission** \n - If the processor is in M-mode and no PMP region matches the access address, the access **shall** be allowed.\n - If the processor is in any mode other than M-mode and no PMP region matches the access address, the access **shall** be denied (fault).\n\n2. **Region Matching** \n\n A region matches the access address if the address falls within the region's defined address range, according to the region's mode:\n\n - **OFF mode**: The region is disabled. No address matches.\n - **NA4 mode** (only when `PMPGranularity == 0`): The region covers a single 4-byte aligned block. The address must exactly equal the address value (bits [33:0]) provided.\n - **NAPOT mode**: The region covers a naturally aligned power-of-two region. The address matches if, after applying a mask derived from the address register, the masked access address equals the masked region base.\n - **TOR mode**: The region covers addresses from the *previous* region's address (or zero for region 0) up to (but not including) this region's address. An address matches if it is greater than or equal to the start address and strictly less than this region’s address.\n\n Address comparison bits are truncated according to `PMPGranularity`: only bits [33:G+2] are used for matching. Consequently, all regions have a minimum alignment and size determined by the granularity.\n\n3. **Priority and Permission Check** \n\n PMP regions are statically prioritized by index: region 0 has the lowest priority, region `PMPNumRegions-1` the highest. When multiple regions match, the highest-priority matching region (largest index) determines the result.\n\n For the highest-priority matching region:\n\n - **Machine mode**: \n If the lock bit (L) is clear, the access is allowed regardless of the permission bits. \n If the lock bit is set, the access is allowed only if the access type matches one of the permission bits (read, write, execute) set in that region. Otherwise, a fault is generated.\n\n - **Supervisor/User mode**: \n The access is allowed only if the access type matches one of the permission bits set in the matching region. The lock bit has no effect on the decision. If no permission bit matches, a fault is generated.\n\n4. **Lock Bit Effect** \n - When a region’s lock bit is set, its configuration becomes read-only to software. This module does not enforce the read-only aspect (handled by the CSR logic), but the lock bit does affect M-mode access decisions as described above.\n - A locked region remains active for all privilege levels.\n\n### Output Behavior\n\n- The error output for each channel is asserted (1) when a fault is determined; otherwise it is deasserted (0). The decision is combinatorial from the inputs and configuration.\n- The module does not register errors; timing closure is addressed externally.\n\n## Edge Cases and Specific Behavior\n\n- **Region 0 in TOR mode**: The start address is 0 (the region covers addresses from 0 to the first region’s address).\n- **Multiple matching regions**: Only the highest-indexed matching region's permission check is applied; lower-indexed regions are ignored.\n- **Unsupported mode (default in case statement)**: Any unrecognized mode value shall result in no match (OFF behavior).\n- **Granularity effect on NA4**: When `PMPGranularity > 0`, the NA4 mode is treated as OFF (no match). This is consistent with the RISC-V specification requirement that NA4 is unavailable when granularity exceeds 0.\n\n## Reset Behavior\n\nUpon reset, all PMP configuration registers are assumed to be initialized to zero (OFF mode, no permissions, lock clear). The address register values are undefined at reset; however, since all regions start in OFF mode, no matches occur, and the default permission rules apply (M-mode allowed; other modes denied).\n\n## Dependencies and Usage\n\n- The module is purely combinational (except for configuration storage which is external). It does not contain any state beyond the combinational logic.\n- The external system must provide stable configuration and address inputs synchronous with the clock for proper operation.\n- The error output should be used by the core to suppress any bus request or to raise an exception as dictated by the RISC-V privilege specification.\n\n---\n\n*This specification describes the externally observable behavior of the PMP module. It does not prescribe internal implementation details.*", "commit_id": "1f3b462b9477531a9bf8627a05f92cadfd3c54bb", "timestamp": "2020-11-06T17:47:27+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "9b0d78cf97fd4bd22db8b2479f30ed135f761a13", "pr_title": "[rtl] Fix NAPOT address matching (#1178)", "pr_body": "Generate correct masks for NAPOT range addresses covering the entire granule. When PMPGranularity > 0, then a NAPOT range can span the whole granule, which requires the next-lowest bit (i.e. highest bit that is not part of the granule) to be 0. Fixes #1178 ", "issue_title": "PMP NAPOT masks are incorrect when the region address spans the entire granule", "issue_body": "The address masking logic in [`ibex_pmp.sv`](https://github.com/lowRISC/ibex/blob/master/rtl/ibex_pmp.sv) always considers the lowest bit of the granule of the PMP address configuration register (i.e. `csr_pmp_addr_i[r][PMPGranularity+2]`) not to be part of the range address in NAPOT mode. This is correct when `PMPGranularity == 0`, since then NA4 mode must be selected if the range address uses all bits, but it is incorrect when `PMPGranularity > 0`, since then it is legal in NAPOT mode to have a range address span the entire granule, with the next-lowest bit (i.e. `csr_pmp_addr_i[r][PMPGranularity+1]`) cleared to indicate that all higher bits are part of the range address.\r\n\r\nFor instance with `PMPGranularity == 28`, the granule covers bits `csr_pmp_addr_i[r][33:30]`, yet bit `csr_pmp_addr_i[r][29]` must also be considered to check whether a range address spans all 4 bits of the granule. A range address of `csr_pmp_addr_i[r] == 34'b00_0101_1111_1111_1111_1111_1111_1111_1111` could be used to specify a range from 1 GiB to 2 GiB for example and in that case the region address mask should be `region_addr_mask [r] == 4'b1111` (i.e. the entire granule). However, since only bits `csr_pmp_addr_i[r][33:30]` are currently considered when generating the mask, it is incorrectly set to `region_addr_mask [r] == 4'b1100`.\r\n\r\nThe specification states that bits `G-2:0` (i.e. bits `csr_pmp_addr_i[r][PMPGranularity:0]`) are implicitly set to all ones and hence do not need to be considered, but that implies that bit `G-1` (i.e. `csr_pmp_addr_i[r][PMPGranularity+1]`) is still used to specify the range:\r\n\r\n> When G≥1, the NA4 mode is not selectable. When G≥2 and pmpcfgi.A[1] is set, i.e. the mode is NAPOT, then bits pmpaddri[G-2:0] read as all ones.\r\n> -- [Volume II: RISC-V Privileged Architectures V20190608-Priv-MSU-Ratified, Sect. 3.6.1](https://github.com/riscv/riscv-isa-manual/releases/download/Ratified-IMFDQC-and-Priv-v1.11/riscv-privileged-20190608.pdf)", "commit_message": "[rtl] Fix NAPOT address matching\n\n- Generate correct masks for NAPOT range addresses covering the entire\n granule. When PMPGranularity > 0, then a NAPOT range can span the\n whole granule, which requires the next-lowest bit (i.e. highest bit\n that is not part of the granule) to be 0.\n- Fixes #1178", "fix_patch": "diff --git a/rtl/ibex_pmp.sv b/rtl/ibex_pmp.sv\nindex 1b48693a0a..cbe2193310 100644\n--- a/rtl/ibex_pmp.sv\n+++ b/rtl/ibex_pmp.sv\n@@ -55,8 +55,8 @@ module ibex_pmp #(\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+ if (b == 2) begin : g_bit0\n+ // Always mask bit 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@@ -65,7 +65,7 @@ module ibex_pmp #(\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+ ~&csr_pmp_addr_i[r][b-1:PMPGranularity+1];\n end\n end\n end\n", "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 == 2) begin : g_bit0\n // Always mask bit 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+1];\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", "selected_doc_paths": ["doc/03_reference/pmp.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1300, "lang": "sv", "rtl_files": ["rtl/ibex_icache.sv"], "spec": "# Behavioral Design Specification: ibex_icache\n\n## 1. Overview\n\nThe instruction cache (icache) is a configurable, optionally set-associative cache that provides fetched instructions to the core’s instruction fetch stage. It replaces the standard prefetch buffer when enabled and is optimized for systems with moderate to high instruction memory latency. The icache supports multiple configuration options including cache size, associativity, line size, ECC protection, and branch-target-only caching.\n\nThe icache operates with a two‑stage internal pipeline and uses multiple fill buffers to manage outstanding memory requests, data buffering, and instruction delivery. It communicates with the core via a ready/valid handshake and with the instruction memory via a simple request‑grant‑valid protocol. The cache can be enabled/disabled dynamically and supports invalidation on request (e.g., for FENCE.I).\n\nThe icache must always behave correctly under all valid input conditions. Its functionality is fully determined by the state of its configuration parameters and control inputs; there is no undefined or unreachable behavior.\n\n---\n\n## 2. Core Interface Signals (Observable Behavior)\n\nThe icache presents the following interface to the core’s instruction fetch stage:\n\n- **Instruction Request (`req_i`)**: When asserted, the core indicates it will soon consume instructions. The cache may perform prefetching while this signal is high; when de‑asserted, the cache ceases new instruction fetches after completing any outstanding line fill.\n- **Branch Signals**: \n - `branch_i`: Non‑speculative branch taken. The address counter is reloaded to `addr_i`. \n - `branch_spec_i`: Speculative version of the branch, available earlier in the cycle. If `branch_spec_i` is asserted but `branch_i` is not, any lookup initiated in that cycle is suppressed. \n - `predicted_branch_i`: Indicates that the branch was predicted taken (used for branch prediction). \n - `branch_mispredict_i`: Indicates that a predicted taken branch was actually not taken; the address counter is reloaded to the saved fall‑through address.\n- **Address Input (`addr_i`)**: New program counter value, must be half‑word aligned (LSB = 0). Sampled when `branch_i` or `branch_mispredict_i` is asserted.\n- **Instruction Output**: \n - `valid_o`: Asserted when `rdata_o`, `addr_o`, `err_o`, and `err_plus2_o` are stable and valid. \n - `ready_i`: Core signal indicating it can accept an instruction. A transfer occurs when both `valid_o` and `ready_i` are high. \n - `rdata_o[31:0]`: 32‑bit instruction data. \n - `addr_o[31:0]`: Address of the instruction (half‑word aligned). \n - `err_o`: Asserted when an error occurred during fetch (PMP violation or bus error). \n - `err_plus2_o`: When `err_o` is high, this signal indicates that the error is due to the second half of a misaligned uncompressed instruction (only valid for uncompressed instructions).\n- **Cache Enable (`icache_enable_i`)**: When low, the cache operates in pass‑through mode: all instruction fetches bypass the cache and no lines are allocated. When high, caching is active.\n- **Cache Invalidate (`icache_inval_i`)**: Transition to high (for at least one cycle) initiates a full invalidation of all cache lines. An ongoing invalidation temporarily forces pass‑through behavior (no new allocations). A second invalidation request while one is in progress is ignored.\n- **Busy (`busy_o`)**: High while an invalidation is in progress or while any fill buffer holds an outstanding memory request that has not yet received all expected data. When low, the cache is idle and may be clock‑gated.\n\nThe core must assert `branch_i` (or `branch_mispredict_i`) before or on the first cycle that `req_i` is high after reset; otherwise cache behavior is unspecified (the address counter is uninitialized).\n\n---\n\n## 3. Instruction Fetch Flow\n\n### 3.1 Address Tracking\n\nThe icache maintains an internal address counter that tracks the next instruction to be delivered. This counter is updated as follows:\n\n- On reset, the counter is undefined.\n- When `branch_i` is asserted, the counter is set to `addr_i`.\n- When `branch_mispredict_i` is asserted, the counter is set to the saved fall‑through address (captured earlier when the predicted branch was taken).\n- During sequential fetching (no branch), the counter is incremented after each instruction is successfully transferred to the core. The increment is 2 if the delivered instruction is compressed (bits [1:0] ≠ 2'b11) and 4 otherwise. The data of the instruction itself determines the increment, not a separate signal.\n\n### 3.2 Lookup and Fill\n\nWhen the core requests instructions (`req_i` high) and the cache is not busy with a forced invalidation or ECC correction, a lookup is performed. The lookup address is taken from:\n\n- The branch target address if `branch_spec_i` is high.\n- The mispredict fall‑through address if `branch_mispredict_i` is high.\n- The internal prefetch address otherwise (which increments by one cache line after each granted lookup).\n\nA lookup reads the tag and data RAMs. In the next pipeline stage (IC1), the tag is compared against the address to determine a hit or miss:\n\n- **Hit**: The cached line supplies the requested instruction. The data word corresponding to the request address is extracted.\n- **Miss**: A new fill buffer is allocated to fetch the missing cache line from memory.\n\nIf the cache is disabled (`icache_enable_i` low) or an invalidation is in progress, every lookup behaves as a miss: the data is fetched directly from memory and no cache line is allocated.\n\n### 3.3 Instruction Delivery\n\nInstruction data is delivered to the core from one of three sources, multiplexed in order of priority:\n\n1. **Incoming memory bus data**: When a fill buffer receives the very beat that matches the current output address, that data is forwarded immediately (bypassing buffering).\n2. **Cache hit data**: When a lookup results in a hit, the requested word from the cache line is output on the same cycle it is read from the RAMs.\n3. **Fill buffer data**: For a miss that has already received some data beats, the buffered line is used to supply subsequent sequential instructions.\n\nIf a compressed instruction is delivered from a half‑word that is not the lower half of the output word, a 16‑bit skid buffer stores the upper half‑word. The skid buffer is used to realign the stream when a compressed instruction appears at an odd half‑word offset, or when an unaligned uncompressed instruction spans two memory words.\n\nThe cache shall output instructions in order: sequential addresses increment by 2 or 4 as determined by the instruction itself. No out‑of‑order delivery is allowed.\n\n---\n\n## 4. Cache Management\n\n### 4.1 Fill Buffers\n\nThe icache contains a fixed number of fill buffers (4 by design, configurable). Each buffer tracks one outstanding instruction fetch request. A fill buffer is allocated on every lookup that is granted (whether hit or miss) and is freed when all of the following conditions are met:\n\n- The line has been written to the cache (if it was a miss and allocation is enabled) **or** the request was a hit **or** the line is not to be cached.\n- All beats of data have been output to the core **or** the request became stale (due to an intervening branch).\n- All external memory requests for the line have completed.\n\nFill buffers are used for:\n\n- **Speculative prefetching**: When a branch is taken or the cache is disabled, a speculative external request may be issued before the cache lookup completes. The resulting fill buffer holds the speculative state.\n- **Hit data storage**: Even on a cache hit, a fill buffer is allocated to buffer the remainder of the cache line for subsequent sequential fetches.\n- **Miss handling**: For a miss, the fill buffer issues multiple external memory requests to fill the entire cache line (wrapping address order starting from the requested beat). It counts received data beats and stores them.\n\nArbitration among fill buffers (for external memory access, RAM write, and output to core) is age‑based: an older fill buffer (allocated earlier) always takes priority over a younger one.\n\nA fill buffer becomes **stale** when a new branch occurs while it still holds uncompleted work. After becoming stale, the buffer cannot supply new instructions to the core, but may still complete its current external requests and write the line to the cache if caching is enabled.\n\n### 4.2 Cache Allocation\n\nA cache line is allocated only if:\n\n- The fetch was a miss (no tag match and no ECC error).\n- `icache_enable_i` is high.\n- No invalidation is in progress.\n- The `BranchCache` parameter is either 0 or, if 1, the request is the result of a branch or is within a limited number of sequential lines following a branch (configurable, default 2).\n\nWhen allocation occurs, the fill buffer writes the entire line to the data RAM and updates the tag RAM with the new tag and valid bit. The victim way is chosen as:\n\n- The first invalid way (if any), or\n- A round‑robin (pseudorandom) way if all ways are valid.\n\n### 4.3 Cache Disable Behavior\n\nWhen `icache_enable_i` is low:\n\n- Every lookup triggers an external memory request (pass‑through mode).\n- No lines are written to the cache.\n- Fill buffers still track the requests and supply data to the core, but after the line has been fully consumed or a branch occurs, the buffer is released without allocating.\n\n### 4.4 Cache Invalidation\n\nA cache invalidation is triggered by:\n\n- The rising edge of `icache_inval_i` (must be high for at least one cycle).\n- The first cycle after reset (automatically).\n\nDuring invalidation, the cache writes an invalid tag (valid bit = 0) for every index in all ways, one index per cycle. While the invalidation is in progress:\n\n- New lookups and fill allocations are allowed, but no lines are cached (equivalent to pass‑through).\n- The `busy_o` signal remains high.\n\nAfter the invalidation completes (all indices processed), normal caching resumes.\n\n---\n\n## 5. Error Handling\n\n### 5.1 Bus Errors and PMP Violations\n\nErrors from the instruction memory are reported via two signals:\n\n- `instr_err_i`: Bus error on a memory transaction.\n- `instr_pmp_err_i`: Physical Memory Protection violation. When a PMP error is detected, the cache treats the request as if it never happened (the external request is dropped) and no further requests are issued for that cache line.\n\nWhen an error (bus or PMP) occurs on a beat that is being delivered to the core, the `err_o` signal is asserted for that instruction. The instruction data (`rdata_o`) is unspecified. For a misaligned uncompressed instruction that spans two memory words, `err_plus2_o` indicates that the error is on the second half.\n\nErrors on beats that are part of a line fill but not yet delivered to the core are recorded per beat in the fill buffer. The error is propagated to the core when that beat is subsequently output.\n\n### 5.2 ECC Errors (Optional)\n\nWhen ECC protection is enabled (configurable), the tag and data RAMs include SECDED checkbits. In the pipeline stage after a RAM read (IC1), the ECC decoder reports single‑ or double‑bit errors.\n\nIf any ECC error is detected (on either tag or data) for a supposed cache hit:\n\n- The hit is cancelled; the cache behaves as if a miss occurred.\n- The data from RAMs is ignored; the instruction is fetched from external memory instead.\n- The way(s) that experienced the error are invalidated (valid bit cleared) by performing a tag write in the following cycle.\n- No lookup is allowed during that invalidation write cycle.\n\nECC errors on the data RAM are per beat (for each BusWidth‑sized chunk). The entire cache line is still considered corrupted and the error is reported to the core as a bus error.\n\n---\n\n## 6. Branch Prediction Support\n\nIf the core includes a branch predictor (configured by a parameter), the icache saves the address immediately following a predicted‑taken branch. This saved address is used when a misprediction occurs (predicted taken but actually not taken) so that the core can resume fetching from the fall‑through path.\n\nThe mispredict address is captured on the cycle when `branch_i` and `predicted_branch_i` are both high. It is the address that would have been the next sequential fetch if the branch had not been taken. On a `branch_mispredict_i` event, the icache sets its address counter to this saved value.\n\nWhen no branch predictor is present, `predicted_branch_i` is ignored and `branch_mispredict_i` should never be asserted.\n\n---\n\n## 7. Configuration Parameters\n\nThe behavior of the icache depends on the following parameters (set at instantiation):\n\n| Parameter | Default | Description |\n|----------------------|---------|-------------|\n| `BusWidth` | 32 | Width of the instruction memory bus (fixed at 32 for Ibex). |\n| `CacheSizeBytes` | 4 KiB | Total data storage capacity of the cache (excluding tags and ECC). |\n| `LineSize` | 64 | Width of one cache line in bits. Must be > 32. |\n| `NumWays` | 2 | Associativity (number of ways). |\n| `ICacheECC` | Off | If enabled, SECDED ECC is added to tag and data RAMs. |\n| `BranchCache` | Off | If enabled, only branch targets and two subsequent cache lines are eligible for cache allocation. |\n| `BranchPredictor` | Off | If enabled, the cache supports the branch mispredict address save/restore mechanism. |\n\nThese parameters affect the internal RAM sizes, ECC encoding/decoding logic, and allocation policy. All other behavioral aspects (protocol, error handling, invalidation) are independent of the parameter values.\n\n---\n\n## 8. Timing and Handshake Guarantees\n\n- The core must keep `req_i` high while it expects to consume instructions. When `req_i` goes low, the cache may finish an ongoing line fill but will not start new external requests.\n- The `valid_o` signal, once asserted, remains high and all output signals (except `rdata_o`) remain stable until either a transfer completes (`ready_i` high) or a branch is asserted. After an error, `valid_o` may be de‑asserted on the next cycle even without a branch.\n- The instruction memory interface (`instr_req_o`, `instr_addr_o`, `instr_gnt_i`, `instr_rvalid_i`, `instr_rdata_i`, `instr_err_i`) follows the same protocol as the core‑side instruction fetch interface: request remains valid until granted; response is valid for one cycle.\n- The cache may issue up to one outstanding request per fill buffer. The number of fill buffers is fixed (≥2) to allow pipelining.\n- No deadlock scenarios are possible: the cache will always eventually respond to a core request (by asserting `valid_o` or by being cancelled by a branch).", "commit_id": "6d9e1aca8ad7cf09d4effcde97e471d6c213ead1", "timestamp": "2021-03-12T17:27:52+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "42827fc9cd0b2043d5d179cae46b0238a55d3652", "pr_title": "[rtl/icache] Switch ECC granularity to 32bits", "pr_body": "Changes the ECC granularity in the data RAMs from 64bit to 32bit. This\r\nis to align with an upcoming change in bus ECC. Relates to\r\nlowRISC/opentitan#5450\r\n\r\nSigned-off-by: Tom Roberts ", "issue_title": "", "issue_body": "", "commit_message": "[rtl/icache] Switch ECC granularity to 32bits\n\nChanges the ECC granularity in the data RAMs from 64bit to 32bit. This\nis to align with an upcoming change in bus ECC. Relates to\nlowRISC/opentitan#5450\n\nSigned-off-by: Tom Roberts ", "fix_patch": "diff --git a/rtl/ibex_icache.sv b/rtl/ibex_icache.sv\nindex 346e6a28f4..504d005329 100644\n--- a/rtl/ibex_icache.sv\n+++ b/rtl/ibex_icache.sv\n@@ -64,14 +64,15 @@ module ibex_icache #(\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_SIZE_ECC = ICacheECC ? (BusWidth + 7) : BusWidth;\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 LINE_SIZE_ECC = BUS_SIZE_ECC * LINE_BEATS;\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@@ -110,7 +111,8 @@ module ibex_icache #(\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 [LINE_SIZE_ECC-1:0] hit_data_ecc_ic1;\n+ logic [LineSize-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@@ -315,10 +317,12 @@ module ibex_icache #(\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+ for (genvar bank = 0; bank < LINE_BEATS; bank ++) begin : gen_ecc_banks\n+ prim_secded_39_32_enc data_ecc_enc (\n+ .in (fill_wdata_ic0[bank*BusWidth+:BusWidth]),\n+ .out (data_wdata_ic0[bank*BUS_SIZE_ECC+:BUS_SIZE_ECC])\n+ );\n+ end\n \n end else begin : gen_noecc_wdata\n assign tag_wdata_ic0 = fill_tag_ic0;\n@@ -390,10 +394,10 @@ module ibex_icache #(\n \n // Hit data mux\n always_comb begin\n- hit_data_ic1 = 'b0;\n+ hit_data_ecc_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+ hit_data_ecc_ic1 |= data_rdata_ic1[way];\n end\n end\n end\n@@ -421,11 +425,11 @@ module ibex_icache #(\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+ logic [NumWays-1:0] tag_err_ic1;\n+ logic [LINE_BEATS*2-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@@ -448,12 +452,17 @@ module ibex_icache #(\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+ for (genvar bank = 0; bank < LINE_BEATS; bank++) begin : gen_ecc_banks\n+ prim_secded_39_32_dec data_ecc_dec (\n+ .in (hit_data_ecc_ic1[bank*BUS_SIZE_ECC+:BUS_SIZE_ECC]),\n+ .d_o (),\n+ .syndrome_o (),\n+ .err_o (data_err_ic1[bank*2+:2])\n+ );\n+\n+ assign hit_data_ic1[bank*BusWidth+:BusWidth] = hit_data_ecc_ic1[bank*BUS_SIZE_ECC+:BusWidth];\n+\n+ end\n \n assign ecc_err_ic1 = lookup_valid_ic1 & ((|data_err_ic1) | (|tag_err_ic1));\n \n@@ -497,6 +506,7 @@ module ibex_icache #(\n assign ecc_write_req = 1'b0;\n assign ecc_write_ways = '0;\n assign ecc_write_index = '0;\n+ assign hit_data_ic1 = hit_data_ecc_ic1;\n end\n \n ///////////////////////////////\n@@ -782,7 +792,7 @@ module ibex_icache #(\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] ? hit_data_ic1[LineSize-1:0] :\n+ assign fill_data_d[fb] = fill_hit_ic1[fb] ? hit_data_ic1 :\n {LINE_BEATS{instr_rdata_i}};\n \n for (genvar b = 0; b < LINE_BEATS; b++) begin : gen_data_buf\n@@ -881,7 +891,7 @@ module ibex_icache #(\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_data = |fill_data_hit ? hit_data_ic1 : 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@@ -1059,7 +1069,7 @@ module ibex_icache #(\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+ `ASSERT_INIT(ecc_data_param_legal, !ICacheECC || (BusWidth == 32))\n \n // Lookups in the tag ram should always give a known result\n `ASSERT_KNOWN(TagHitKnown, lookup_valid_ic1 & tag_hit_ic1)\n", "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 parameter bit BranchPredictor = 1'b0,\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 // 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 predicted_branch_i,\n input logic branch_mispredict_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 prim_ram_1p_pkg::ram_1p_cfg_t ram_cfg_i,\n input logic icache_enable_i,\n input logic icache_inval_i,\n output logic busy_o\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_BYTES = LineSize/8;\n localparam int unsigned LINE_W = $clog2(LINE_SIZE_BYTES);\n localparam int unsigned BUS_SIZE_ECC = ICacheECC ? (BusWidth + 7) : BusWidth;\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 LINE_SIZE_ECC = BUS_SIZE_ECC * LINE_BEATS;\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] branch_mispredict_addr;\n logic [ADDR_W-1:0] prefetch_addr_d, prefetch_addr_q;\n logic prefetch_addr_en;\n logic branch_or_mispredict;\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_ecc_ic1;\n logic [LineSize-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_d, fill_ext_done_q;\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_ext_beat, 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_incr;\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 if (BranchPredictor) begin : g_branch_predictor\n // Where the branch predictor is present record what address followed a predicted branch. If\n // that branch is predicted taken but mispredicted (so not-taken) this is used to resume on\n // the not-taken code path.\n logic [31:0] branch_mispredict_addr_q;\n logic branch_mispredict_addr_en;\n\n assign branch_mispredict_addr_en = branch_i & predicted_branch_i;\n\n always_ff @(posedge clk_i) begin\n if (branch_mispredict_addr_en) begin\n branch_mispredict_addr_q <= {output_addr_incr, 1'b0};\n end\n end\n\n assign branch_mispredict_addr = branch_mispredict_addr_q;\n\n end else begin : g_no_branch_predictor\n logic unused_predicted_branch;\n\n assign unused_predicted_branch = predicted_branch_i;\n\n assign branch_mispredict_addr = '0;\n end\n\n assign branch_or_mispredict = branch_i | branch_mispredict_i;\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 branch_i ? addr_i :\n branch_mispredict_addr;\n\n assign prefetch_addr_en = branch_or_mispredict | 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_or_mispredict | ~lookup_throttle) &\n ~ecc_write_req;\n assign lookup_addr_ic0 = branch_spec_i ? addr_i :\n branch_mispredict_i ? branch_mispredict_addr :\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 for (genvar bank = 0; bank < LINE_BEATS; bank ++) begin : gen_ecc_banks\n prim_secded_39_32_enc data_ecc_enc (\n .in (fill_wdata_ic0[bank*BusWidth+:BusWidth]),\n .out (data_wdata_ic0[bank*BUS_SIZE_ECC+:BUS_SIZE_ECC])\n );\n end\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 .cfg_i (ram_cfg_i),\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 .cfg_i (ram_cfg_i),\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_ecc_ic1 = 'b0;\n for (int way = 0; way < NumWays; way++) begin\n if (tag_match_ic1[way]) begin\n hit_data_ecc_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 [LINE_BEATS*2-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 for (genvar bank = 0; bank < LINE_BEATS; bank++) begin : gen_ecc_banks\n prim_secded_39_32_dec data_ecc_dec (\n .in (hit_data_ecc_ic1[bank*BUS_SIZE_ECC+:BUS_SIZE_ECC]),\n .d_o (),\n .syndrome_o (),\n .err_o (data_err_ic1[bank*2+:2])\n );\n\n assign hit_data_ic1[bank*BusWidth+:BusWidth] = hit_data_ecc_ic1[bank*BUS_SIZE_ECC+:BusWidth];\n\n end\n\n assign ecc_err_ic1 = lookup_valid_ic1 & ((|data_err_ic1) | (|tag_err_ic1));\n\n // Error correction\n // All ways will be invalidated on a tag error to prevent X-propagation from data_err_ic1 on\n // spurious hits. Also prevents the same line being allocated twice when there was a true\n // hit and a spurious hit.\n assign ecc_correction_ways_d = {NumWays{|tag_err_ic1}} |\n (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 assign hit_data_ic1 = hit_data_ecc_ic1;\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 // Speculative requests are only made for branches, or if the cache is disabled\n assign fill_spec_req = (~icache_enable_i | branch_or_mispredict) & ~|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_or_mispredict) &\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_or_mispredict | 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 & ~ecc_err_ic1;\n assign fill_hit_d[fb] = fill_hit_ic1[fb] | (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_d[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_d[fb] = (fill_ext_cnt_q[fb][LINE_BEATS_W] |\n // external requests are considered complete if the request hit\n fill_hit_ic1[fb] | 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 won't be cached and, it is stale\n (~fill_cache_q[fb] & (branch_or_mispredict | fill_stale_q[fb] |\n // or we're already at the end of the line\n fill_ext_beat[fb][LINE_BEATS_W]))) &\n // can't cancel while we are waiting for a grant on the bus\n ~fill_ext_hold_q[fb] & fill_busy_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_q[fb] & ~fill_ext_hold_q[fb]) &\n (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;\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_ext_beat[fb] = {1'b0,fill_addr_q[fb][LINE_W-1:BUS_W]} +\n fill_ext_cnt_q[fb][LINE_BEATS_W:0];\n assign fill_ext_off[fb] = fill_ext_beat[fb][LINE_BEATS_W-1:0];\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_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_ext_done_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_ext_done_q[fb] <= fill_ext_done_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] ? hit_data_ic1 :\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 = ((~icache_enable_i | branch_or_mispredict) & 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 : 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 assign data_valid = |fill_out_arb;\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_or_mispredict ? 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_or_mispredict | (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 // Next IF stage PC\n assign output_addr_incr = (output_addr_q[31:1] +\n // Increment address by 4 or 2\n {29'd0, ~addr_incr_two, addr_incr_two});\n\n // Redirect the address on branches or mispredicts\n assign output_addr_d = branch_i ? addr_i[31:1] :\n branch_mispredict_i ? branch_mispredict_addr[31:1] :\n output_addr_incr;\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 & ~branch_mispredict_i;\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, !ICacheECC || (BusWidth == 32))\n\n // Lookups in the tag ram should always give a known result\n `ASSERT_KNOWN(TagHitKnown, lookup_valid_ic1 & tag_hit_ic1)\n `ASSERT_KNOWN(TagInvalidKnown, lookup_valid_ic1 & tag_invalid_ic1)\n\n // This is only used for the Yosys-based formal flow. Once we have working bind support, we can\n // get rid of it.\n`ifdef FORMAL\n `ifdef YOSYS\n // Unfortunately, Yosys doesn't support passing unpacked arrays as ports. Explicitly pack up the\n // signals we need.\n logic [NUM_FB-1:0][ADDR_W-1:0] packed_fill_addr_q;\n always_comb begin\n for (int i = 0; i < NUM_FB; i++) begin\n packed_fill_addr_q[i][ADDR_W-1:0] = fill_addr_q[i];\n end\n end\n\n `include \"formal_tb_frag.svh\"\n `endif\n`endif\n\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/icache.rst", "doc/03_reference/instruction_fetch.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/pmp.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1216, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# Behavioral Design Specification: Ibex Controller\n\n## 1. Overview\n\nThe controller is the central finite-state machine of the Ibex processor. It orchestrates instruction fetch, decode/execute pipeline control, exception and interrupt handling, debug mode entry, and low‑power sleep. The controller reacts to signals from the decoder, load‑store unit, interrupt inputs, debug request, and pipeline stall/flush requests. It determines when the processor must:\n\n- Start fetching from a new program counter (PC) due to reset, branches, jumps, exceptions, interrupts, or debug entry.\n- Flush the instruction fetch and ID pipeline stages.\n- Save or restore architectural state (CSRs) for exception/interrupt/debug traps.\n- Enter or exit sleep mode on a WFI instruction.\n\nThe controller supports two optional features controlled by parameters: a third pipeline stage (writeback) and a branch predictor.\n\n## 2. Reset and Initialization\n\nUpon deassertion of the system reset, the controller must:\n\n- Set the program counter to the boot address and initiate the first instruction fetch.\n- Start the processor in Machine Mode (M‑Mode) with interrupts disabled and debug mode inactive.\n- Remain busy until the first instruction has been fetched and enters the decode stage.\n\n## 3. Normal Instruction Execution (DECODE)\n\nWhen the processor is in the normal run state (DECODE):\n\n- The controller must allow instruction fetch to proceed as long as the pipeline is not stalled.\n- If there is no pending special request (exception, interrupt, debug, or CSR‑pipeline flush), the controller must handle conditional branch and jump instructions as follows:\n - For a taken branch or unconditional jump, it must set the PC to the target address and flush the currently prefetched instructions.\n - If the branch predictor is enabled, the controller may rely on the predictor’s speculative PC update. If the predictor indicated a taken branch but the branch is actually not taken (mispredict), the controller must correct the PC and flush the pipeline.\n - When no branch predictor is used, the controller must set the PC directly whenever a branch or jump is taken.\n- The controller must indicate whether the current cycle’s instruction is a taken branch or a jump for performance counters.\n\n### 3.1 Pipeline Stalls\n\n- The controller must halt instruction fetch when the ID/EX stage is stalled (e.g., multi‑cycle instruction, writeback stage not ready). \n- When a special instruction (e.g., MRET, DRET, WFI, CSR‑pipe flush) or an exception is detected, the controller must prevent new instructions from entering the ID stage and wait until the writeback stage is ready or raises its own exception before proceeding to the FLUSH state. \n- If the writeback stage is not present, the controller must always proceed immediately to FLUSH for special instructions.\n\n## 4. Exception Handling\n\nThe controller handles the following exceptions: instruction access fault, illegal instruction, breakpoint (EBREAK), environment calls (ECALL from M‑ or U‑Mode), load access fault, and store access fault. Exceptions occur on the instruction currently in the ID/EX stage or, when the writeback stage exists, on the instruction in the writeback stage.\n\n### 4.1 Exception Priority\n\nWhen multiple exceptions are pending, the controller must resolve them with the following priority (highest first):\n\n1. Store access fault (writeback stage, if present)\n2. Load access fault (writeback stage, if present)\n3. Instruction access fault\n4. Illegal instruction\n5. ECALL (M‑ or U‑Mode)\n6. EBREAK\n\nThe controller must ensure that only one exception cause is selected and saved to the `mcause` CSR.\n\n### 4.2 Exception Entry\n\nWhen an exception is taken, the controller must:\n\n- Set the PC to the exception vector address (`mtvec` base).\n- Save the appropriate program counter into `mepc`:\n - For instruction fetch errors, `mepc` must hold the address of the faulting instruction (adjusted if the fault is on a 32‑bit instruction in a 16‑bit fetch).\n - For illegal instructions, `mepc` must hold the address of the illegal instruction.\n - For ECALL and EBREAK, `mepc` must hold the address of the trapping instruction itself (not the next instruction).\n - For load/store errors, `mepc` must hold the address of the instruction that performed the access. With writeback stage, this address comes from writeback; without it, from ID/EX.\n- Save `mstatus.MIE` into `mstatus.MPIE` and clear `mstatus.MIE`.\n- Set `mepc` to the instruction’s address (see above note for instruction fetch errors).\n- Store the exception cause and, for relevant exceptions, the `mtval` value (instruction encoding for illegal instruction, faulting address for access faults, PC for instruction fetch errors).\n- When in debug mode, jump to the debug exception handler address (`DmExceptionAddr`) instead of the normal exception handler.\n\n### 4.3 EBREAK Special Case\n\n- If an EBREAK is executed while the core is already in debug mode, the controller must not save or update any CSRs; instead it must re‑enter debug mode (go to DBG_TAKEN_ID state) without flushing or saving state.\n- If an EBREAK is executed outside debug mode and the processor is configured to enter debug mode on EBREAK (via `debug_ebreakm`/`debug_ebreaku` bits), the controller must treat it as a debug entry rather than an exception.\n\n## 5. Interrupt Handling\n\nThe controller supports both maskable interrupts and a non‑maskable interrupt (NMI). Interrupts are taken only when the core is not in debug mode and not currently handling an NMI.\n\n### 5.1 Standard Interrupts\n\n- An interrupt is taken when the global interrupt enable bit (`mstatus.MIE`) is set and the corresponding interrupt request (`irq`) is pending and enabled in `mie`.\n- The controller must wait for the currently executing instruction to complete before servicing the interrupt (unless a CSR‑related pipeline flush is occurring).\n- On interrupt entry, the controller must:\n - Set the PC to `mtvec` base + 4×interrupt ID (vectored mode).\n - Save the return PC (address of the next instruction to execute after the handler) into `mepc`.\n - Save `mstatus.MIE` into `mstatus.MPIE` and clear `mstatus.MIE`.\n - Save the interrupt cause in `mcause`.\n - Disable further interrupts (by clearing `mstatus.MIE`).\n\n### 5.2 Non‑Maskable Interrupt (NMI)\n\n- The NMI has the highest priority among all interrupts and is taken regardless of `mstatus.MIE` and `mie`.\n- While handling an NMI, the controller must ignore all other interrupts (including a second NMI).\n- On NMI entry, the controller must:\n - Jump to the trap handler base address plus 0x7C.\n - Save the return PC into the standard `mepc` and also backup `mepc` and `mstatus` into non‑software‑accessible CSRs to support recoverable NMI handling.\n - Set a flag to indicate NMI mode; this flag suppresses further interrupts.\n- On MRET executed while in NMI mode, the controller must clear the NMI mode flag.\n\n### 5.3 Interrupt Priority Among Standard Interrupts\n\nWhen multiple maskable interrupts are pending, the controller must select the one with the highest ID, except timer interrupts (ID 7) which have the lowest priority. The NMI (ID 31) is always the highest.\n\n## 6. Debug Mode\n\nThe controller supports run‑control debug as defined in the RISC‑V Debug Specification v0.13. The core enters debug mode due to:\n\n- Assertion of the debug request signal (`debug_req_i`).\n- Single‑step mode when a valid instruction completes (`debug_single_step_i`).\n- A hardware trigger match (`trigger_match_i`).\n- EBREAK execution when the appropriate `debug_ebreak*` control bits are set.\n\n### 6.1 Entry Conditions\n\n- Debug mode can only be entered when the core is not already in debug mode.\n- If a debug request or single‑step occurs while the processor is handling an interrupt or exception, the debug entry is deferred until the current trap handling completes (the PC is set for the trap, then the controller re‑directs to the debug handler instead).\n- When entering debug mode, the controller must:\n - Save the program counter of the current instruction into `dpc`.\n - For debug requests and single‑step: save the PC of the instruction that would be executed next (from the IF stage).\n - For EBREAK (forced entry): save the PC of the EBREAK instruction itself (from ID stage).\n - For trigger matches: save the PC of the instruction that hit the trigger (from IF stage).\n - Set `dcsr.cause` to the appropriate debug cause (halt request, single‑step, EBREAK, or trigger).\n - Set the debug mode flag.\n - Jump to the debug entry address (`DmHaltAddr`).\n\n### 6.2 Behavior While in Debug Mode\n\n- While in debug mode, the controller must ignore all interrupts (including NMI) and debug requests.\n- The controller must allow execution of all instructions, including those that could normally cause exceptions. When an exception occurs in debug mode, the controller must not take the normal exception; instead it must jump to the debug exception address (`DmExceptionAddr`).\n\n### 6.3 Leaving Debug Mode\n\n- The controller leaves debug mode upon execution of a DRET instruction.\n- On DRET, the controller restores `dpc` to the PC and clears the debug mode flag.\n\n## 7. WFI and Sleep\n\nWhen a WFI instruction is decoded:\n\n- The controller must set the processor into a low‑power sleep state.\n- In the sleep state, the controller must:\n - Stop all instruction fetch and pipeline activity.\n - Continue to monitor interrupts (including NMI), debug requests, and single‑step events.\n - Wake up (resume fetching) when:\n - A maskable interrupt (enabled in `mstatus` and `mie`) is pending.\n - An NMI is asserted.\n - A debug request, single‑step condition, or trigger match occurs.\n - The core is already in debug mode or single‑step mode (in that case WFI behaves as a NOP and the core wakes immediately).\n- While sleeping, the controller may indicate that the core is not busy (allowing clock gating).\n\n## 8. Pipeline Control Signals\n\nThe controller must generate the following control actions:\n\n- **Instruction fetch enable**: must be active except during reset, sleep, and when the pipeline is stalled or flushing.\n- **PC set**: must be asserted whenever the processor needs to change the PC (reset, branch, jump, exception, interrupt, MRET, DRET, debug entry). The PC selector decides the source of the new PC (boot, normal jump, exception vector, interrupt vector, MRET, DRET, debug handler).\n- **Speculative PC set**: when the branch predictor is enabled, the controller may set the PC speculatively before the branch outcome is known. When the predictor is disabled, speculative PC set follows the actual branch condition.\n- **Pipeline flush**: must flush the IF‑ID pipeline register on taken branches, jumps, exceptions, interrupts, debug entry, and CSR‑related pipeline flushes. The controller must clear the valid bit for the current instruction in the ID stage when a flush is required.\n- **ID stage ready**: must indicate that the ID stage can accept a new instruction, which is true when not stalled and not halted (e.g., during special instruction handling or before entering sleep).\n- **Stall control**: the controller must stall the ID stage when the writeback stage is not ready or the ID stage itself is busy (multi‑cycle instruction). It must also prevent new instructions from entering ID while a special instruction is being processed.\n\n## 9. Performance Monitoring\n\nThe controller must generate pulse signals for:\n\n- A taken branch (conditional branch that is actually taken).\n- A jump (unconditional jump or call).\n\nThese signals are used by performance counters to count control‑flow events.\n\n## 10. Parameters\n\nThe behavior of the controller is influenced by two parameters:\n\n### `WritebackStage` (0 or 1)\n\n- When set (1), a third pipeline stage exists. The controller must:\n - Prioritize load/store exceptions from the writeback stage over those from the ID stage.\n - Wait for the writeback stage to be ready before handling exceptions or special instructions from the ID stage.\n - Use the writeback stage’s PC for load/store exception `mepc` saving.\n- When clear (0), two‑stage pipeline: no writeback stage. All exceptions are handled from the ID stage directly.\n\n### `BranchPredictor` (0 or 1)\n\n- When set (1), the controller uses a branch predictor that provides a speculative taken/not‑taken hint and a speculative PC update. The controller must:\n - Not set the PC for branches/jumps if the predictor already set it.\n - Detect a mispredict when the predictor predicted taken but the branch is not taken, and correct the PC.\n - Assert a mispredict signal to clear the speculatively fetched instruction.\n- When clear (0), the controller always sets the PC for branches/jumps without speculative assistance.\n\n---\n\n*This specification describes the functional requirements of the Ibex controller module. It does not prescribe internal implementation details such as state encoding, flip‑flop names, or RTL constructs.*", "commit_id": "aa7582b8d420888541c2e8688447c17918a71aeb", "timestamp": "2020-12-17T11:25:04+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "0199bbae665b9b142144e6688279e2ecef7d83a0", "pr_title": "This is modification request for xcelium", "pr_body": "Assert not correctly understood by some versions of xcelium.\r\nA single character added line in rtl/ibex_controller.sv .", "issue_title": "'Assert' line 836 of file ibex_controller.sv not understood by some version of Xcelium", "issue_body": "Current code:\r\n`ASSERT(AlwaysInstrClearOnMispredict, nt_branch_mispredict_o -> instr_valid_clear_o)\r\n\r\nSuggested code (a 'pipe'='|' added):\r\n`ASSERT(AlwaysInstrClearOnMispredict, nt_branch_mispredict_o |-> instr_valid_clear_o)\r\n\r\nCurrent code fails with Xcellium 19.03-s001 for example. But works with a more recent version (20.10...)\r\n", "commit_message": "Use overlapping implications for Xcelium 19.03\n\nXcelium 19.03 doesn't support the `->` (binary logical) operator, but\nusing `|->` (overlapping implication) is equivalent here and supported;\nuse this operator instead.\n\nFixes #1213", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex b59833d5b6..db98a0ae48 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -833,7 +833,7 @@ module ibex_controller #(\n // Assertions //\n ////////////////\n \n- `ASSERT(AlwaysInstrClearOnMispredict, nt_branch_mispredict_o -> instr_valid_clear_o)\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", "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\nmodule ibex_controller #(\n parameter bit WritebackStage = 0,\n parameter bit BranchPredictor = 0\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\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 logic pc_set_spec_o, // speculative branch\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_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 output logic wb_exception_o, // Instruction in WB 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_set_spec_i, // speculative branch signal (branch\n // may be 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_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 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 input logic csr_mstatus_tw_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 // 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 // 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 illegal_dret;\n logic illegal_umode;\n logic exc_req_lsu;\n logic special_req_all;\n logic special_req_branch;\n logic enter_debug_mode;\n logic ebreak_into_debug;\n logic handle_irq;\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, 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 // All terms in this expression are qualified by instr_valid_i\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 // 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\n // special requests: special instructions, pipeline flushes, exceptions...\n\n // To avoid creating a path from data_err_i -> instr_req_o and to help timing the below\n // special_req_all has a version that only applies to branches. For a branch the controller needs\n // to set pc_set_o but only if there is no special request. If the generic special_req_all signal\n // is used then a variety of signals that will never cause a special request during a branch\n // instruction end up factored into pc_set_o. The special_req_branch only considers the special\n // request reasons that are relevant to a branch.\n\n // generic special request signal, applies to all instructions\n // All terms in this expression 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 assign special_req_all = mret_insn | dret_insn | wfi_insn | csr_pipe_flush |\n exc_req_d | exc_req_lsu;\n\n // special request that can specifically occur during branch instructions\n // All terms in this expression are qualified by instr_valid_i\n assign special_req_branch = instr_fetch_err & (ctrl_fsm_cs != FLUSH);\n\n `ASSERT(SpecialReqBranchGivesSpecialReqAll,\n special_req_branch |-> special_req_all)\n\n `ASSERT(SpecialReqAllGivesSpecialReqBranchIfBranchInst,\n special_req_all && (branch_set_i || jump_set_i) |-> special_req_branch)\n\n // Exception/fault prioritisation is taken from Table 3.7 of Priviledged Spec v1.11\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 // 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 assign enter_debug_mode = (debug_req_i | (debug_single_step_i & instr_valid_i) |\n 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 // Interrupts including NMI are ignored,\n // - while in debug mode [Debug Spec v0.13.2, p.39],\n // - while in NMI mode (nested NMIs are not supported, NMI has highest priority and\n // cannot be interrupted by regular interrupts).\n assign handle_irq = ~debug_mode_q & ~nmi_mode_q &\n (irq_nm_i | (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 (irqs_i.irq_fast[14]) mfip_id = 4'd14;\n else if (irqs_i.irq_fast[13]) mfip_id = 4'd13;\n else if (irqs_i.irq_fast[12]) mfip_id = 4'd12;\n else if (irqs_i.irq_fast[11]) mfip_id = 4'd11;\n else if (irqs_i.irq_fast[10]) mfip_id = 4'd10;\n else if (irqs_i.irq_fast[ 9]) mfip_id = 4'd9;\n else if (irqs_i.irq_fast[ 8]) mfip_id = 4'd8;\n else if (irqs_i.irq_fast[ 7]) mfip_id = 4'd7;\n else if (irqs_i.irq_fast[ 6]) mfip_id = 4'd6;\n else if (irqs_i.irq_fast[ 5]) mfip_id = 4'd5;\n else if (irqs_i.irq_fast[ 4]) mfip_id = 4'd4;\n else if (irqs_i.irq_fast[ 3]) mfip_id = 4'd3;\n else if (irqs_i.irq_fast[ 2]) mfip_id = 4'd2;\n else if (irqs_i.irq_fast[ 1]) mfip_id = 4'd1;\n else mfip_id = 4'd0;\n end\n\n assign unused_irq_timer = irqs_i.irq_timer;\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 pc_set_spec_o = 1'b0;\n nt_branch_mispredict_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\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_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 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 pc_set_spec_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 pc_set_spec_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_i || 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_all) 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 (!special_req_branch) begin\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 end\n\n // pc_set signal excluding branch taken condition\n if ((branch_set_spec_i || jump_set_i) && !special_req_branch) begin\n // Only speculatively set the PC if the branch predictor hasn't already done the branch\n // for us\n pc_set_spec_o = BranchPredictor ? ~instr_bp_taken_i : 1'b1;\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\n if (!stall && !special_req_all) 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 pc_set_spec_o = 1'b1;\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 (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 EXC_CAUSE_IRQ_FAST_0 = {1'b1, 5'd16}\n exc_cause_o = exc_cause_e'({2'b11, mfip_id});\n end else if (irqs_i.irq_external) begin\n exc_cause_o = EXC_CAUSE_IRQ_EXTERNAL_M;\n end else if (irqs_i.irq_software) begin\n exc_cause_o = EXC_CAUSE_IRQ_SOFTWARE_M;\n end else begin // irqs_i.irq_timer\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 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 if (debug_single_step_i || debug_req_i || trigger_match_i) begin\n flush_id = 1'b1;\n pc_set_o = 1'b1;\n pc_set_spec_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 if (trigger_match_i) begin\n debug_cause_o = DBG_CAUSE_TRIGGER;\n end else 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 flush_id = 1'b1;\n pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n pc_set_spec_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\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_set_spec_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 = EXC_CAUSE_INSTR_ACCESS_FAULT;\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 = EXC_CAUSE_ILLEGAL_INSN;\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) ? EXC_CAUSE_ECALL_MMODE :\n EXC_CAUSE_ECALL_UMODE;\n end\n ebrk_insn_prio: 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 pc_set_spec_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 end\n store_err_prio: begin\n exc_cause_o = EXC_CAUSE_STORE_ACCESS_FAULT;\n csr_mtval_o = lsu_addr_last_i;\n end\n load_err_prio: begin\n exc_cause_o = EXC_CAUSE_LOAD_ACCESS_FAULT;\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 pc_set_spec_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 pc_set_spec_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 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 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.\n if (enter_debug_mode && !(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 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 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\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 // The speculative branch signal should be set whenever the actual branch signal is set\n `ASSERT(IbexSpecImpliesSetPC, pc_set_o |-> pc_set_spec_o)\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/exception_interrupts.rst", "doc/03_reference/debug.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/instruction_decode_execute.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1380, "lang": "sv", "rtl_files": ["rtl/ibex_cs_registers.sv"], "spec": "# Behavioral Specification for Ibex Control and Status Register (CSR) Module\n\n## Overview\n\nThis module implements the control and status register (CSR) file for the Ibex RISC-V processor core. It provides the storage and update logic for all machine-level CSRs defined in the RISC-V Privileged Specification (version 1.11), plus custom CSRs for core control and debug support. The module manages privilege mode transitions, interrupt and exception handling, physical memory protection (PMP) configuration, performance monitoring counters, and debug capabilities.\n\n## CSR Access and Protection\n\nThe module receives CSR read/write requests from the processor pipeline. Each access is qualified by the requested operation (read, write, set, clear) and an operation enable signal.\n\n### Address Space and Privilege Check\n\n- CSR addresses are 12‑bit values. The two most significant bits of the address encode the required privilege level:\n - `00` – User mode\n - `01` – Supervisor mode (not supported)\n - `10` – Hypervisor mode (not supported)\n - `11` – Machine mode\n- An access is **illegal** if the current privilege mode is lower than the required level.\n\n### Write Protection\n\n- CSR addresses with bits `[11:10] == 2’b11` are read‑only; any write to such a register is illegal. This includes the `mhartid` and `misa` registers.\n- Certain registers are writable only when the core is in Debug Mode (e.g., `dcsr`, `dpc`, `dscratch0`, `dscratch1`, and trigger registers). An access from any other mode is illegal.\n- The `mcountinhibit` CSR prohibits setting bit 1 (counter index 1) to 1; writes to that bit are ignored.\n\n### Illegal Instruction Generation\n\nThe module asserts an `illegal_csr_insn` output whenever:\n- A CSR access is attempted to a non‑existent address.\n- The required privilege level is not met.\n- A write is attempted to a read‑only register.\n- An access is made to debug‑only registers from a non‑debug mode.\n\n## Interrupt Handling\n\n### Interrupt Pending (`mip`)\n\nThe `mip` register is a read‑only, combinational reflection of the incoming interrupt request inputs:\n- `irq_software_i` → `mip.irq_software` (bit 3)\n- `irq_timer_i` → `mip.irq_timer` (bit 7)\n- `irq_external_i` → `mip.irq_external` (bit 11)\n- `irq_fast_i[14:0]` → `mip.irq_fast[14:0]` (bits 30:16)\n\nNo other bits are set.\n\n### Interrupt Enable (`mie`)\n\nThe `mie` register is a WARL register that enables individual interrupt sources. It is updated only on explicit CSR writes. Reset value is all zeros (all interrupts disabled).\n\n### Global Interrupt Enables (`mstatus`)\n\n- `mstatus.MIE` (bit 3) – global interrupt enable. When 0, all maskable interrupts are disabled.\n- `mstatus.MPIE` (bit 7) – stores the value of `MIE` when an exception was taken.\n- `mstatus.MPP` (bits 12:11) – stores the privilege mode when an exception was taken. Only Machine Mode (`PRIV_LVL_M`) and User Mode (`PRIV_LVL_U`) are supported; any write of an unsupported value is converted to Machine Mode.\n- `mstatus.MPRV` (bit 17) – when set, load/store instructions use the privilege level in `MPP` for PMP checking instead of the current privilege level.\n- `mstatus.TW` (bit 21) – when set, executing `WFI` instruction in User Mode triggers an illegal instruction exception.\n\nThe module outputs the qualified interrupt requests as `irqs_o` = `mip & mie`. The overall `irq_pending_o` signal is the OR‑reduce of `irqs_o`.\n\n### Non‑Maskable Interrupt (NMI)\n\nThe NMI has the highest priority (interrupt ID 31). It is enabled independent of `mstatus.MIE` and `mie`, and is not visible in `mip`. During NMI handling, all interrupts (including further NMIs) are ignored. The NMI handler entry is at `mtvec.BASE + 0x7C`.\n\n## Exception and Interrupt Entry\n\nWhen an exception (or interrupt) is taken, the core saves state into the CSRs. The module receives specific save and restore control signals from the pipeline.\n\n### State Save\n\n- **Privilege mode**: Always transitions to Machine Mode (`PRIV_LVL_M`).\n- **`mepc`**: Saved with the program counter of the faulting instruction (the source depends on the pipeline stage: IF, ID, or WB).\n- **`mcause`**: Saved with the exception code and interrupt flag supplied by the pipeline (`csr_mcause_i`).\n- **`mtval`**: Saved with the trap value (`csr_mtval_i`). This may be the faulting address (for load/store faults) or the faulting instruction (for illegal instruction exceptions).\n- **`mstatus`**: Updated as follows:\n - `MIE` cleared to 0 (interrupts disabled).\n - `MPIE` loaded with the previous `MIE`.\n - `MPP` loaded with the current privilege level.\n\n### Debug Mode Exception Save\n\nWhen the core is not in Debug Mode but a debug exception (e.g., breakpoint) occurs, the module also saves:\n- `dcsr.cause` and `dcsr.prv` (privilege level at the time of exception).\n- `depc` with the exception program counter.\nNo updates to `mepc`, `mcause`, `mtval`, or `mstatus` are performed in this case.\n\n### Recoverable NMI Stack\n\nThe module maintains three additional, non‑standard CSRs (`mstack`, `mstack_epc`, `mstack_cause`) that are not accessible to software. On any exception (including interrupts and NMIs), the current `mstatus.MPIE` and `mstatus.MPP` are saved into `mstack`, and `mepc`/`mcause` are saved into the corresponding shadow registers. These are used to restore state when returning from an NMI‑triggered handler via `MRET`.\n\n## Exception Return\n\n### MRET Instruction\n\n- The privilege mode is restored from `mstatus.MPP`.\n- `mstatus.MIE` is restored from `mstatus.MPIE`.\n- `mstatus.MPIE` is set to 1.\n- `mstatus.MPP` is set to User Mode (`PRIV_LVL_U`).\n- The program counter is restored from `mepc`.\n\nIf the core was in NMI mode (`nmi_mode_i` asserted), instead of using `mepc` and `mstatus.MPP`/`MPIE`, the module restores from the `mstack` shadow registers:\n- `mstack_epc` → `mepc`\n- `mstack_cause` → `mcause`\n- `mstack.MPIE` → `mstatus.MPIE`\n- `mstack.MPP` → `mstatus.MPP`\n\n### DRET Instruction\n\n- The privilege mode is restored from `dcsr.prv`.\n- The program counter is restored from `depc`.\n\n## Privilege Mode Outputs\n\nThe module outputs the current privilege level for three pipeline domains:\n- **ID stage** (`priv_mode_id_o`) – driven by the registered privilege level.\n- **IF stage** (`priv_mode_if_o`) – driven by the *next* privilege level (combinational update) so that instruction fetches immediately reflect changes from exception return.\n- **LSU stage** (`priv_mode_lsu_o`) – driven by the privilege level used for PMP checking: if `mstatus.MPRV` is set, the LSU uses `mstatus.MPP`; otherwise it uses the current privilege level.\n\n## Machine Trap Vector (`mtvec`)\n\n- **Reset value**: `0x0000_0001` (vectored mode, base address 0).\n- **Mode bits** (bits 1:0): Always read as `2’b01` (vectored mode). Writes are ignored.\n- **Base address** (bits 31:2): Must be 256‑byte aligned (bits 7:2 always forced to 0). On a write, the base is taken from the upper 24 bits of the write data; the lower 6 bits are cleared.\n- **Initialization**: At reset, `mtvec` is loaded from the boot address (`boot_addr_i`) with the same alignment constraint. The boot address’s lower 8 bits are ignored (assumed to be 0x00). A dedicated init signal (`csr_mtvec_init_i`) performs this once.\n\n## Debug Support\n\n### Debug Control and Status (`dcsr`)\n\n- Accessible only in Debug Mode.\n- **xdebugver** (bits 31:28): Read‑only, hardwired to `XDEBUGVER_STD` (value 4).\n- **ebreakm** (bit 15): When set, an `ebreak` in Machine Mode enters Debug Mode; otherwise it behaves as a standard breakpoint.\n- **ebreaku** (bit 12): When set, an `ebreak` in User Mode enters Debug Mode.\n- **cause** (bits 8:6): Read‑only. Updated on debug entry: 1=EBREAK, 2=trigger match, 3=halt request, 4=single step.\n- **step** (bit 2): When set, the core executes a single instruction and then enters Debug Mode.\n- **prv** (bits 1:0): WARL. Stores the privilege level when Debug Mode was entered. The debugger may modify it to change the privilege level upon DRET. Only Machine Mode and User Mode are supported.\n- Other fields (`stepie`, `stopcount`, `stoptime`, `mprven`, `nmip`) are forced to 0.\n\n### Debug PC (`depc`)\n\n- Accessible only in Debug Mode.\n- On debug entry, saved with the address of the next instruction that would have been executed.\n- On DRET, the PC is restored from `depc`.\n- Writes must ensure the least significant bit is 0 (instruction‑aligned).\n\n### Debug Scratch Registers (`dscratch0`, `dscratch1`)\n\n- Accessible only in Debug Mode. Standard 32‑bit read/write registers.\n\n### Trigger Registers (optional, controlled by `DbgTriggerEn`)\n\n- **tselect**: Selects which hardware trigger (0 to `DbgHwBreakNum-1`) is accessed via `tdata1` and `tdata2`. Writing a value ≥ `DbgHwBreakNum` sets the register to the maximum valid index.\n- **tdata1**: Read‑only fields indicate the trigger type (address/data match), debug mode only access, and matching capabilities. The only writable field is the `execute` bit (bit 2), which enables instruction address matching.\n- **tdata2**: Stores the instruction address to match. The core generates a trigger match signal when the instruction fetch address equals this value and the `execute` bit is set.\n- Other trigger‑related CSRs (`tdata3`, `mcontext`, `scontext`) read as zero and ignore writes.\n\nTrigger matching occurs on the instruction fetch address (`pc_if_i`). Matches are asserted before instruction execution.\n\n## Physical Memory Protection (PMP)\n\n### PMP Configuration Registers (`pmpcfg0`–`pmpcfg3`)\n\n- Each register contains four 8‑bit configuration fields (`pmpXcfg`), one per PMP region.\n- Each field consists of:\n - Lock bit (bit 7)\n - Reserved bits (6:5), read as 0\n - Mode bits (4:3): OFF (00), TOR (01), NA4 (10, not available when granularity > 0), NAPOT (11)\n - Execute permission (bit 2)\n - Write permission (bit 1)\n - Read permission (bit 0)\n- The combination `write=1, read=0` is reserved and forces write to 0 unless `mseccfg.MML` is set.\n- Locked entries cannot be modified unless `mseccfg.RLB` is set.\n\n### PMP Address Registers (`pmpaddr0`–`pmpaddr15`)\n\n- Hold the address matching value for each region. The stored width is `PMPAddrWidth` (33 – granularity bits).\n- Read data is expanded to 32 bits according to the configured mode and granularity:\n - In OFF or TOR modes, the lowest `G` bits (granularity) read as 0.\n - In NAPOT mode, the lowest `G-1` bits read as 1, and the address is padded with trailing 1’s.\n- The region’s base address for PMP checking is the value padded with two zeros in the least significant bits.\n\n### Machine Security Configuration (`mseccfg`)\n\n- Accessible only when PMP is enabled (`PMPEnable=1`). Otherwise, accesses are illegal.\n- Bits:\n - Bit 0 (`MML`): Machine Mode Lockdown – once set, cannot be cleared.\n - Bit 1 (`MMWP`): Machine Mode Whitelist Policy – once set, cannot be cleared.\n - Bit 2 (`RLB`): Rule Locking Bypass – can only be set if no PMP entry is locked (with `RLB` being considered). When set, locked entries can be modified.\n- The upper 32 bits (`mseccfgh`) always read as zero and ignore writes.\n\n### PMP Outputs\n\nThe module provides the PMP configuration, address, and `mseccfg` values to the core’s PMP checker for instruction and data access validation.\n\n## Performance Counters\n\n### Cycle Counter (`mcycle` / `mcycleh`)\n\n64‑bit counter, always increments every cycle unless inhibited by `mcountinhibit[0]`.\n\n### Retired Instruction Counter (`minstret` / `minstreth`)\n\n64‑bit counter, increments when `instr_ret_i` is asserted, unless inhibited by `mcountinhibit[2]`.\n\n### Event Counters (`mhpmcounter3`–`mhpmcounter31`)\n\n- Up to 29 event counters are available, parameterized by `MHPMCounterNum` and `MHPMCounterWidth`.\n- Each counter increments when its associated event condition is true and the corresponding bit in `mcountinhibit` is 0.\n- The events are hardwired and mapped to counter indices as follows:\n - Index 3: cycles waiting for data memory (`dside_wait_i`)\n - Index 4: cycles waiting for instruction fetch (`iside_wait_i`)\n - Index 5: number of memory loads (`mem_load_i`)\n - Index 6: number of memory stores (`mem_store_i`)\n - Index 7: number of unconditional jumps (`jump_i`)\n - Index 8: number of conditional branches (`branch_i`)\n - Index 9: number of taken branches (`branch_taken_i`)\n - Index 10: number of retired compressed instructions (`instr_ret_compressed_i`)\n - Index 11: cycles waiting for multiply (`mul_wait_i`)\n - Index 12: cycles waiting for divide (`div_wait_i`)\n- Counter indices 13–31 are not associated with any event (counters tied to zero).\n- Event selection CSRs (`mhpmevent3`–`mhpmevent31`) are WARL but hardwired such that each register has exactly one bit set corresponding to its index. For example, `mhpmevent3` has bit 3 set. Writes are ignored; reads return the fixed value.\n\n### Counter‑Inhibit Register (`mcountinhibit`)\n\n- Bit 0: inhibit `mcycle`\n- Bit 1: reserved (always 0)\n- Bit 2: inhibit `minstret`\n- Bits 3 to `MHPMCounterNum+2`: inhibit corresponding event counters\n- Bits above `MHPMCounterNum+2` tie to 1 (counters not present are effectively inhibited).\n\n### Counter Read/Write\n\n- All counters are accessible as two 32‑bit halves via the base register (`mhpmcounterX`) and the `h` register (`mhpmcounterXh`). Writes to the lower 32 bits update the counter; writes to the upper bits update only the upper half.\n\n## Custom CPU Control Register (`cpuctrl`)\n\n- Accessible from Machine Mode only.\n- Bit 0 (`icache_enable`): Enable (1) or disable (0) the instruction cache. Reads as 0 if the cache is not instantiated (`ICache` parameter = 0).\n- Bit 1 (`data_ind_timing`): Enable (1) or disable (0) data‑independent timing feature. Reads as 0 if not configured (`DataIndTiming` parameter = 0).\n- Bit 2 (`dummy_instr_en`): Enable dummy instruction insertion. Reads as 0 if not configured (`DummyInstructions` = 0).\n- Bits 5:3 (`dummy_instr_mask`): Mask that controls frequency of dummy instruction insertion. Reads as zero if `DummyInstructions` = 0.\n\n## Custom Security Seed Register (`secureseed`)\n\n- Accessible from Machine Mode only.\n- Writing to this CSR updates a seed value used by security‑related pseudo‑random number generators in the core (e.g., for dummy instruction placement).\n- Reads always return 0.\n\n## Shadow CSR Error\n\nThe module outputs a combinational `csr_shadow_err_o` signal that is the OR of individual error signals from any CSR instance that supports shadow copy. This indicates that a shadow copy mismatch (e.g., due to a single‑event upset) has been detected. The error is asserted if any of `mstatus`, `mtvec`, PMP configuration, or the CPU control register report an error.\n\n## Hardware Thread ID (`mhartid`)\n\nRead‑only. Returns the value of the `hart_id_i` input. No other CSR at address 0xF14 is implemented.\n\n## Reset Behavior\n\nOn reset (`rst_ni` assertion):\n- Privilege level defaults to Machine Mode.\n- `mstatus` reset value: `MIE=0`, `MPIE=1`, `MPP=U‑Mode`, `MPRV=0`, `TW=0`.\n- `mtvec` reset value: `0x0000_0001`. The base address is overwritten by the boot initialization signal.\n- All other CSRs reset to 0, except `dcsr` which resets to `0x4000_0003` (`xdebugver=4`, `prv=M‑Mode`, `cause=0`).\n- Performance counter inhibit register resets to all zeros (counters enabled).\n- CPU control register resets to all zeros.", "commit_id": "7ceff60749bc5907bd720d554ce2fa6fe997d34d", "timestamp": "2021-06-09T13:59:33+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "7071b04a6687a09d9a7fa00ce7be4a3e23cab8da", "pr_title": "[rtl] Fix typo in MCOUNTEREN", "pr_body": "DbgTriggerEn has no impact on whether this is an illegal csr op.\r\n\r\nFixes #1379\r\n\r\nSigned-off-by: Tom Roberts ", "issue_title": "DbgTriggerEn impacts mcounteren", "issue_body": "Why does DbgTriggerEn impact mcounteren? That does not look correct to me.\r\n\r\n> // mcounteren: machine counter enable\r\n> CSR_MCOUNTEREN: begin\r\n> csr_rdata_int = '0;\r\n> illegal_csr = ~DbgTriggerEn;\r\n> end\r\n", "commit_message": "[rtl] Fix typo in MCOUNTEREN\n\nDbgTriggerEn has no impact on whether this is an illegal csr op.\n\nFixes #1379\n\nSigned-off-by: Tom Roberts ", "fix_patch": "diff --git a/rtl/ibex_cs_registers.sv b/rtl/ibex_cs_registers.sv\nindex 50a34a2176..75ef2e5de1 100644\n--- a/rtl/ibex_cs_registers.sv\n+++ b/rtl/ibex_cs_registers.sv\n@@ -322,7 +322,6 @@ module ibex_cs_registers #(\n // mcounteren: machine counter enable\n CSR_MCOUNTEREN: begin\n csr_rdata_int = '0;\n- illegal_csr = ~DbgTriggerEn;\n end\n \n CSR_MSCRATCH: csr_rdata_int = mscratch_q;\n", "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 * Control and Status Registers\n *\n * Control and Status Registers (CSRs) following the RISC-V Privileged\n * Specification, draft version 1.11\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_cs_registers #(\n parameter bit DbgTriggerEn = 0,\n parameter int unsigned DbgHwBreakNum = 1,\n parameter bit DataIndTiming = 1'b0,\n parameter bit DummyInstructions = 1'b0,\n parameter bit ShadowCSR = 1'b0,\n parameter bit ICache = 1'b0,\n parameter int unsigned MHPMCounterNum = 10,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit PMPEnable = 0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter bit RV32E = 0,\n parameter ibex_pkg::rv32m_e RV32M = ibex_pkg::RV32MFast,\n parameter ibex_pkg::rv32b_e RV32B = ibex_pkg::RV32BNone\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n // Hart ID\n input logic [31:0] hart_id_i,\n\n // Privilege mode\n output ibex_pkg::priv_lvl_e priv_mode_id_o,\n output ibex_pkg::priv_lvl_e priv_mode_if_o,\n output ibex_pkg::priv_lvl_e priv_mode_lsu_o,\n output logic csr_mstatus_tw_o,\n\n // mtvec\n output logic [31:0] csr_mtvec_o,\n input logic csr_mtvec_init_i,\n input logic [31:0] boot_addr_i,\n\n // Interface to registers (SRAM like)\n input logic csr_access_i,\n input ibex_pkg::csr_num_e csr_addr_i,\n input logic [31:0] csr_wdata_i,\n input ibex_pkg::csr_op_e csr_op_i,\n input csr_op_en_i,\n output logic [31:0] csr_rdata_o,\n\n // interrupts\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 nmi_mode_i,\n output logic irq_pending_o, // interrupt request pending\n output ibex_pkg::irqs_t irqs_o, // interrupt requests qualified with mie\n output logic csr_mstatus_mie_o,\n output logic [31:0] csr_mepc_o,\n\n // PMP\n output ibex_pkg::pmp_cfg_t csr_pmp_cfg_o [PMPNumRegions],\n output logic [33:0] csr_pmp_addr_o [PMPNumRegions],\n output ibex_pkg::pmp_mseccfg_t csr_pmp_mseccfg_o,\n\n // debug\n input logic debug_mode_i,\n input ibex_pkg::dbg_cause_e debug_cause_i,\n input logic debug_csr_save_i,\n output logic [31:0] csr_depc_o,\n output logic debug_single_step_o,\n output logic debug_ebreakm_o,\n output logic debug_ebreaku_o,\n output logic trigger_match_o,\n\n input logic [31:0] pc_if_i,\n input logic [31:0] pc_id_i,\n input logic [31:0] pc_wb_i,\n\n // CPU control bits\n output logic data_ind_timing_o,\n output logic dummy_instr_en_o,\n output logic [2:0] dummy_instr_mask_o,\n output logic dummy_instr_seed_en_o,\n output logic [31:0] dummy_instr_seed_o,\n output logic icache_enable_o,\n output logic csr_shadow_err_o,\n\n // Exception save/restore\n input logic csr_save_if_i,\n input logic csr_save_id_i,\n input logic csr_save_wb_i,\n input logic csr_restore_mret_i,\n input logic csr_restore_dret_i,\n input logic csr_save_cause_i,\n input ibex_pkg::exc_cause_e csr_mcause_i,\n input logic [31:0] csr_mtval_i,\n output logic illegal_csr_insn_o, // access to non-existent CSR,\n // with wrong priviledge level, or\n // missing write permissions\n // Performance Counters\n input logic instr_ret_i, // instr retired in ID/EX stage\n input logic instr_ret_compressed_i, // compressed instr retired\n input logic iside_wait_i, // core waiting for the iside\n input logic jump_i, // jump instr seen (j, jr, jal, jalr)\n input logic branch_i, // branch instr seen (bf, bnf)\n input logic branch_taken_i, // branch was taken\n input logic mem_load_i, // load from memory in this cycle\n input logic mem_store_i, // store to memory in this cycle\n input logic dside_wait_i, // core waiting for the dside\n input logic mul_wait_i, // core waiting for multiply\n input logic div_wait_i // core waiting for divide\n);\n\n import ibex_pkg::*;\n\n localparam int unsigned RV32BEnabled = (RV32B == RV32BNone) ? 0 : 1;\n localparam int unsigned RV32MEnabled = (RV32M == RV32MNone) ? 0 : 1;\n localparam int unsigned PMPAddrWidth = (PMPGranularity > 0) ? 33 - PMPGranularity : 32;\n\n // misa\n localparam logic [31:0] MISA_VALUE =\n (0 << 0) // A - Atomic Instructions extension\n | (RV32BEnabled << 1) // B - Bit-Manipulation extension\n | (1 << 2) // C - Compressed extension\n | (0 << 3) // D - Double precision floating-point extension\n | (32'(RV32E) << 4) // E - RV32E base ISA\n | (0 << 5) // F - Single precision floating-point extension\n | (32'(!RV32E) << 8) // I - RV32I/64I/128I base ISA\n | (RV32MEnabled << 12) // M - Integer Multiply/Divide extension\n | (0 << 13) // N - User level interrupts supported\n | (0 << 18) // S - Supervisor mode implemented\n | (1 << 20) // U - User mode implemented\n | (0 << 23) // X - Non-standard extensions present\n | (32'(CSR_MISA_MXL) << 30); // M-XLEN\n\n typedef struct packed {\n logic mie;\n logic mpie;\n priv_lvl_e mpp;\n logic mprv;\n logic tw;\n } status_t;\n\n typedef struct packed {\n logic mpie;\n priv_lvl_e mpp;\n } status_stk_t;\n\n typedef struct packed {\n x_debug_ver_e xdebugver;\n logic [11:0] zero2;\n logic ebreakm;\n logic zero1;\n logic ebreaks;\n logic ebreaku;\n logic stepie;\n logic stopcount;\n logic stoptime;\n dbg_cause_e cause;\n logic zero0;\n logic mprven;\n logic nmip;\n logic step;\n priv_lvl_e prv;\n } dcsr_t;\n\n // CPU control register fields\n typedef struct packed {\n logic [2:0] dummy_instr_mask;\n logic dummy_instr_en;\n logic data_ind_timing;\n logic icache_enable;\n } cpu_ctrl_t;\n\n // Interrupt and exception control signals\n logic [31:0] exception_pc;\n\n // CSRs\n priv_lvl_e priv_lvl_q, priv_lvl_d;\n status_t mstatus_q, mstatus_d;\n logic mstatus_err;\n logic mstatus_en;\n irqs_t mie_q, mie_d;\n logic mie_en;\n logic [31:0] mscratch_q;\n logic mscratch_en;\n logic [31:0] mepc_q, mepc_d;\n logic mepc_en;\n logic [5:0] mcause_q, mcause_d;\n logic mcause_en;\n logic [31:0] mtval_q, mtval_d;\n logic mtval_en;\n logic [31:0] mtvec_q, mtvec_d;\n logic mtvec_err;\n logic mtvec_en;\n irqs_t mip;\n dcsr_t dcsr_q, dcsr_d;\n logic dcsr_en;\n logic [31:0] depc_q, depc_d;\n logic depc_en;\n logic [31:0] dscratch0_q;\n logic [31:0] dscratch1_q;\n logic dscratch0_en, dscratch1_en;\n\n // CSRs for recoverable NMIs\n // NOTE: these CSRS are nonstandard, see https://github.com/riscv/riscv-isa-manual/issues/261\n status_stk_t mstack_q, mstack_d;\n logic mstack_en;\n logic [31:0] mstack_epc_q, mstack_epc_d;\n logic [5:0] mstack_cause_q, mstack_cause_d;\n\n // PMP Signals\n logic [31:0] pmp_addr_rdata [PMP_MAX_REGIONS];\n logic [PMP_CFG_W-1:0] pmp_cfg_rdata [PMP_MAX_REGIONS];\n logic pmp_csr_err;\n pmp_mseccfg_t pmp_mseccfg;\n\n // Hardware performance monitor signals\n logic [31:0] mcountinhibit;\n // Only have mcountinhibit flops for counters that actually exist\n logic [MHPMCounterNum+3-1:0] mcountinhibit_d, mcountinhibit_q;\n logic mcountinhibit_we;\n\n // mhpmcounter flops are elaborated below providing only the precise number that is required based\n // on MHPMCounterNum/MHPMCounterWidth. This signal connects to the Q output of these flops\n // where they exist and is otherwise 0.\n logic [63:0] mhpmcounter [32];\n logic [31:0] mhpmcounter_we;\n logic [31:0] mhpmcounterh_we;\n logic [31:0] mhpmcounter_incr;\n logic [31:0] mhpmevent [32];\n logic [4:0] mhpmcounter_idx;\n logic unused_mhpmcounter_we_1;\n logic unused_mhpmcounterh_we_1;\n logic unused_mhpmcounter_incr_1;\n\n // Debug / trigger registers\n logic [31:0] tselect_rdata;\n logic [31:0] tmatch_control_rdata;\n logic [31:0] tmatch_value_rdata;\n\n // CPU control bits\n cpu_ctrl_t cpuctrl_q, cpuctrl_d, cpuctrl_wdata;\n logic cpuctrl_we;\n logic cpuctrl_err;\n\n // CSR update logic\n logic [31:0] csr_wdata_int;\n logic [31:0] csr_rdata_int;\n logic csr_we_int;\n logic csr_wr;\n\n // Access violation signals\n logic illegal_csr;\n logic illegal_csr_priv;\n logic illegal_csr_write;\n\n logic [7:0] unused_boot_addr;\n logic [2:0] unused_csr_addr;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n\n /////////////\n // CSR reg //\n /////////////\n\n logic [$bits(csr_num_e)-1:0] csr_addr;\n assign csr_addr = {csr_addr_i};\n assign unused_csr_addr = csr_addr[7:5];\n assign mhpmcounter_idx = csr_addr[4:0];\n\n // See RISC-V Privileged Specification, version 1.11, Section 2.1\n assign illegal_csr_priv = (csr_addr[9:8] > {priv_lvl_q});\n assign illegal_csr_write = (csr_addr[11:10] == 2'b11) && csr_wr;\n assign illegal_csr_insn_o = csr_access_i & (illegal_csr | illegal_csr_write | illegal_csr_priv);\n\n // mip CSR is purely combinational - must be able to re-enable the clock upon WFI\n assign mip.irq_software = irq_software_i;\n assign mip.irq_timer = irq_timer_i;\n assign mip.irq_external = irq_external_i;\n assign mip.irq_fast = irq_fast_i;\n\n // read logic\n always_comb begin\n csr_rdata_int = '0;\n illegal_csr = 1'b0;\n\n unique case (csr_addr_i)\n // mhartid: unique hardware thread id\n CSR_MHARTID: csr_rdata_int = hart_id_i;\n\n // mstatus: always M-mode, contains IE bit\n CSR_MSTATUS: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSTATUS_MIE_BIT] = mstatus_q.mie;\n csr_rdata_int[CSR_MSTATUS_MPIE_BIT] = mstatus_q.mpie;\n csr_rdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW] = mstatus_q.mpp;\n csr_rdata_int[CSR_MSTATUS_MPRV_BIT] = mstatus_q.mprv;\n csr_rdata_int[CSR_MSTATUS_TW_BIT] = mstatus_q.tw;\n end\n\n // misa\n CSR_MISA: csr_rdata_int = MISA_VALUE;\n\n // interrupt enable\n CSR_MIE: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mie_q.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mie_q.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mie_q.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mie_q.irq_fast;\n end\n\n // mcounteren: machine counter enable\n CSR_MCOUNTEREN: begin\n csr_rdata_int = '0;\n end\n\n CSR_MSCRATCH: csr_rdata_int = mscratch_q;\n\n // mtvec: trap-vector base address\n CSR_MTVEC: csr_rdata_int = mtvec_q;\n\n // mepc: exception program counter\n CSR_MEPC: csr_rdata_int = mepc_q;\n\n // mcause: exception cause\n CSR_MCAUSE: csr_rdata_int = {mcause_q[5], 26'b0, mcause_q[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: csr_rdata_int = mtval_q;\n\n // mip: interrupt pending\n CSR_MIP: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mip.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mip.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mip.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mip.irq_fast;\n end\n\n CSR_MSECCFG: begin\n if (PMPEnable) begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSECCFG_MML_BIT] = pmp_mseccfg.mml;\n csr_rdata_int[CSR_MSECCFG_MMWP_BIT] = pmp_mseccfg.mmwp;\n csr_rdata_int[CSR_MSECCFG_RLB_BIT] = pmp_mseccfg.rlb;\n end else begin\n illegal_csr = 1'b1;\n end\n end\n\n CSR_MSECCFGH: begin\n if (PMPEnable) begin\n csr_rdata_int = '0;\n end else begin\n illegal_csr = 1'b1;\n end\n end\n\n // PMP registers\n CSR_PMPCFG0: csr_rdata_int = {pmp_cfg_rdata[3], pmp_cfg_rdata[2],\n pmp_cfg_rdata[1], pmp_cfg_rdata[0]};\n CSR_PMPCFG1: csr_rdata_int = {pmp_cfg_rdata[7], pmp_cfg_rdata[6],\n pmp_cfg_rdata[5], pmp_cfg_rdata[4]};\n CSR_PMPCFG2: csr_rdata_int = {pmp_cfg_rdata[11], pmp_cfg_rdata[10],\n pmp_cfg_rdata[9], pmp_cfg_rdata[8]};\n CSR_PMPCFG3: csr_rdata_int = {pmp_cfg_rdata[15], pmp_cfg_rdata[14],\n pmp_cfg_rdata[13], pmp_cfg_rdata[12]};\n CSR_PMPADDR0: csr_rdata_int = pmp_addr_rdata[0];\n CSR_PMPADDR1: csr_rdata_int = pmp_addr_rdata[1];\n CSR_PMPADDR2: csr_rdata_int = pmp_addr_rdata[2];\n CSR_PMPADDR3: csr_rdata_int = pmp_addr_rdata[3];\n CSR_PMPADDR4: csr_rdata_int = pmp_addr_rdata[4];\n CSR_PMPADDR5: csr_rdata_int = pmp_addr_rdata[5];\n CSR_PMPADDR6: csr_rdata_int = pmp_addr_rdata[6];\n CSR_PMPADDR7: csr_rdata_int = pmp_addr_rdata[7];\n CSR_PMPADDR8: csr_rdata_int = pmp_addr_rdata[8];\n CSR_PMPADDR9: csr_rdata_int = pmp_addr_rdata[9];\n CSR_PMPADDR10: csr_rdata_int = pmp_addr_rdata[10];\n CSR_PMPADDR11: csr_rdata_int = pmp_addr_rdata[11];\n CSR_PMPADDR12: csr_rdata_int = pmp_addr_rdata[12];\n CSR_PMPADDR13: csr_rdata_int = pmp_addr_rdata[13];\n CSR_PMPADDR14: csr_rdata_int = pmp_addr_rdata[14];\n CSR_PMPADDR15: csr_rdata_int = pmp_addr_rdata[15];\n\n CSR_DCSR: begin\n csr_rdata_int = dcsr_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DPC: begin\n csr_rdata_int = depc_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH0: begin\n csr_rdata_int = dscratch0_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH1: begin\n csr_rdata_int = dscratch1_q;\n illegal_csr = ~debug_mode_i;\n end\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: csr_rdata_int = mcountinhibit;\n CSR_MHPMEVENT3,\n CSR_MHPMEVENT4, CSR_MHPMEVENT5, CSR_MHPMEVENT6, CSR_MHPMEVENT7,\n CSR_MHPMEVENT8, CSR_MHPMEVENT9, CSR_MHPMEVENT10, CSR_MHPMEVENT11,\n CSR_MHPMEVENT12, CSR_MHPMEVENT13, CSR_MHPMEVENT14, CSR_MHPMEVENT15,\n CSR_MHPMEVENT16, CSR_MHPMEVENT17, CSR_MHPMEVENT18, CSR_MHPMEVENT19,\n CSR_MHPMEVENT20, CSR_MHPMEVENT21, CSR_MHPMEVENT22, CSR_MHPMEVENT23,\n CSR_MHPMEVENT24, CSR_MHPMEVENT25, CSR_MHPMEVENT26, CSR_MHPMEVENT27,\n CSR_MHPMEVENT28, CSR_MHPMEVENT29, CSR_MHPMEVENT30, CSR_MHPMEVENT31: begin\n csr_rdata_int = mhpmevent[mhpmcounter_idx];\n end\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][31:0];\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][63:32];\n end\n\n // Debug triggers\n CSR_TSELECT: begin\n csr_rdata_int = tselect_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA1: begin\n csr_rdata_int = tmatch_control_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA2: begin\n csr_rdata_int = tmatch_value_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA3: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_MCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_SCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n\n // Custom CSR for controlling CPU features\n CSR_CPUCTRL: begin\n csr_rdata_int = {{32-$bits(cpu_ctrl_t){1'b0}},cpuctrl_q};\n end\n\n // Custom CSR for LFSR re-seeding (cannot be read)\n CSR_SECURESEED: begin\n csr_rdata_int = '0;\n end\n\n default: begin\n illegal_csr = 1'b1;\n end\n endcase\n end\n\n // write logic\n always_comb begin\n exception_pc = pc_id_i;\n\n priv_lvl_d = priv_lvl_q;\n mstatus_en = 1'b0;\n mstatus_d = mstatus_q;\n mie_en = 1'b0;\n mscratch_en = 1'b0;\n mepc_en = 1'b0;\n mepc_d = {csr_wdata_int[31:1], 1'b0};\n mcause_en = 1'b0;\n mcause_d = {csr_wdata_int[31], csr_wdata_int[4:0]};\n mtval_en = 1'b0;\n mtval_d = csr_wdata_int;\n mtvec_en = csr_mtvec_init_i;\n // mtvec.MODE set to vectored\n // mtvec.BASE must be 256-byte aligned\n mtvec_d = csr_mtvec_init_i ? {boot_addr_i[31:8], 6'b0, 2'b01} :\n {csr_wdata_int[31:8], 6'b0, 2'b01};\n dcsr_en = 1'b0;\n dcsr_d = dcsr_q;\n depc_d = {csr_wdata_int[31:1], 1'b0};\n depc_en = 1'b0;\n dscratch0_en = 1'b0;\n dscratch1_en = 1'b0;\n\n mstack_en = 1'b0;\n mstack_d.mpie = mstatus_q.mpie;\n mstack_d.mpp = mstatus_q.mpp;\n mstack_epc_d = mepc_q;\n mstack_cause_d = mcause_q;\n\n mcountinhibit_we = 1'b0;\n mhpmcounter_we = '0;\n mhpmcounterh_we = '0;\n\n cpuctrl_we = 1'b0;\n\n if (csr_we_int) begin\n unique case (csr_addr_i)\n // mstatus: IE bit\n CSR_MSTATUS: begin\n mstatus_en = 1'b1;\n mstatus_d = '{\n mie: csr_wdata_int[CSR_MSTATUS_MIE_BIT],\n mpie: csr_wdata_int[CSR_MSTATUS_MPIE_BIT],\n mpp: priv_lvl_e'(csr_wdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW]),\n mprv: csr_wdata_int[CSR_MSTATUS_MPRV_BIT],\n tw: csr_wdata_int[CSR_MSTATUS_TW_BIT]\n };\n // Convert illegal values to M-mode\n if ((mstatus_d.mpp != PRIV_LVL_M) && (mstatus_d.mpp != PRIV_LVL_U)) begin\n mstatus_d.mpp = PRIV_LVL_M;\n end\n end\n\n // interrupt enable\n CSR_MIE: mie_en = 1'b1;\n\n CSR_MSCRATCH: mscratch_en = 1'b1;\n\n // mepc: exception program counter\n CSR_MEPC: mepc_en = 1'b1;\n\n // mcause\n CSR_MCAUSE: mcause_en = 1'b1;\n\n // mtval: trap value\n CSR_MTVAL: mtval_en = 1'b1;\n\n // mtvec\n CSR_MTVEC: mtvec_en = 1'b1;\n\n CSR_DCSR: begin\n dcsr_d = csr_wdata_int;\n dcsr_d.xdebugver = XDEBUGVER_STD;\n // Change to PRIV_LVL_M if software writes an unsupported value\n if ((dcsr_d.prv != PRIV_LVL_M) && (dcsr_d.prv != PRIV_LVL_U)) begin\n dcsr_d.prv = PRIV_LVL_M;\n end\n\n // Read-only for SW\n dcsr_d.cause = dcsr_q.cause;\n\n // Interrupts always disabled during single stepping\n dcsr_d.stepie = 1'b0;\n\n // currently not supported:\n dcsr_d.nmip = 1'b0;\n dcsr_d.mprven = 1'b0;\n dcsr_d.stopcount = 1'b0;\n dcsr_d.stoptime = 1'b0;\n\n // forced to be zero\n dcsr_d.zero0 = 1'b0;\n dcsr_d.zero1 = 1'b0;\n dcsr_d.zero2 = 12'h0;\n dcsr_en = 1'b1;\n end\n\n // dpc: debug program counter\n CSR_DPC: depc_en = 1'b1;\n\n CSR_DSCRATCH0: dscratch0_en = 1'b1;\n CSR_DSCRATCH1: dscratch1_en = 1'b1;\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: mcountinhibit_we = 1'b1;\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n mhpmcounter_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n mhpmcounterh_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_CPUCTRL: cpuctrl_we = 1'b1;\n\n default:;\n endcase\n end\n\n // exception controller gets priority over other writes\n unique case (1'b1)\n\n csr_save_cause_i: begin\n unique case (1'b1)\n csr_save_if_i: begin\n exception_pc = pc_if_i;\n end\n csr_save_id_i: begin\n exception_pc = pc_id_i;\n end\n csr_save_wb_i: begin\n exception_pc = pc_wb_i;\n end\n default:;\n endcase\n\n // Any exception, including debug mode, causes a switch to M-mode\n priv_lvl_d = PRIV_LVL_M;\n\n if (debug_csr_save_i) begin\n // all interrupts are masked\n // do not update cause, epc, tval, epc and status\n dcsr_d.prv = priv_lvl_q;\n dcsr_d.cause = debug_cause_i;\n dcsr_en = 1'b1;\n depc_d = exception_pc;\n depc_en = 1'b1;\n end else if (!debug_mode_i) begin\n // In debug mode, \"exceptions do not update any registers. That\n // includes cause, epc, tval, dpc and mstatus.\" [Debug Spec v0.13.2, p.39]\n mtval_en = 1'b1;\n mtval_d = csr_mtval_i;\n mstatus_en = 1'b1;\n mstatus_d.mie = 1'b0; // disable interrupts\n // save current status\n mstatus_d.mpie = mstatus_q.mie;\n mstatus_d.mpp = priv_lvl_q;\n mepc_en = 1'b1;\n mepc_d = exception_pc;\n mcause_en = 1'b1;\n mcause_d = {csr_mcause_i};\n // save previous status for recoverable NMI\n mstack_en = 1'b1;\n end\n end // csr_save_cause_i\n\n csr_restore_dret_i: begin // DRET\n priv_lvl_d = dcsr_q.prv;\n end // csr_restore_dret_i\n\n csr_restore_mret_i: begin // MRET\n priv_lvl_d = mstatus_q.mpp;\n mstatus_en = 1'b1;\n mstatus_d.mie = mstatus_q.mpie; // re-enable interrupts\n\n if (nmi_mode_i) begin\n // when returning from an NMI restore state from mstack CSR\n mstatus_d.mpie = mstack_q.mpie;\n mstatus_d.mpp = mstack_q.mpp;\n mepc_en = 1'b1;\n mepc_d = mstack_epc_q;\n mcause_en = 1'b1;\n mcause_d = mstack_cause_q;\n end else begin\n // otherwise just set mstatus.MPIE/MPP\n // See RISC-V Privileged Specification, version 1.11, Section 3.1.6.1\n mstatus_d.mpie = 1'b1;\n mstatus_d.mpp = PRIV_LVL_U;\n end\n end // csr_restore_mret_i\n\n default:;\n endcase\n end\n\n // Update current priv level\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n priv_lvl_q <= PRIV_LVL_M;\n end else begin\n priv_lvl_q <= priv_lvl_d;\n end\n end\n\n // Send current priv level to the decoder\n assign priv_mode_id_o = priv_lvl_q;\n // New instruction fetches need to account for updates to priv_lvl_q this cycle\n assign priv_mode_if_o = priv_lvl_d;\n // Load/store instructions must factor in MPRV for PMP checking\n assign priv_mode_lsu_o = mstatus_q.mprv ? mstatus_q.mpp : priv_lvl_q;\n\n // CSR operation logic\n always_comb begin\n unique case (csr_op_i)\n CSR_OP_WRITE: csr_wdata_int = csr_wdata_i;\n CSR_OP_SET: csr_wdata_int = csr_wdata_i | csr_rdata_o;\n CSR_OP_CLEAR: csr_wdata_int = ~csr_wdata_i & csr_rdata_o;\n CSR_OP_READ: csr_wdata_int = csr_wdata_i;\n default: csr_wdata_int = csr_wdata_i;\n endcase\n end\n\n assign csr_wr = (csr_op_i inside {CSR_OP_WRITE, CSR_OP_SET, CSR_OP_CLEAR});\n\n // only write CSRs during one clock cycle\n assign csr_we_int = csr_wr & csr_op_en_i & ~illegal_csr_insn_o;\n\n assign csr_rdata_o = csr_rdata_int;\n\n // directly output some registers\n assign csr_mepc_o = mepc_q;\n assign csr_depc_o = depc_q;\n assign csr_mtvec_o = mtvec_q;\n\n assign csr_mstatus_mie_o = mstatus_q.mie;\n assign csr_mstatus_tw_o = mstatus_q.tw;\n assign debug_single_step_o = dcsr_q.step;\n assign debug_ebreakm_o = dcsr_q.ebreakm;\n assign debug_ebreaku_o = dcsr_q.ebreaku;\n\n // Qualify incoming interrupt requests in mip CSR with mie CSR for controller and to re-enable\n // clock upon WFI (must be purely combinational).\n assign irqs_o = mip & mie_q;\n assign irq_pending_o = |irqs_o;\n\n ////////////////////////\n // CSR instantiations //\n ////////////////////////\n\n // MSTATUS\n localparam status_t MSTATUS_RST_VAL = '{mie: 1'b0,\n mpie: 1'b1,\n mpp: PRIV_LVL_U,\n mprv: 1'b0,\n tw: 1'b0};\n ibex_csr #(\n .Width ($bits(status_t)),\n .ShadowCopy (ShadowCSR),\n .ResetValue ({MSTATUS_RST_VAL})\n ) u_mstatus_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mstatus_d}),\n .wr_en_i (mstatus_en),\n .rd_data_o (mstatus_q),\n .rd_error_o (mstatus_err)\n );\n\n // MEPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mepc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mepc_d),\n .wr_en_i (mepc_en),\n .rd_data_o (mepc_q),\n .rd_error_o ()\n );\n\n // MIE\n assign mie_d.irq_software = csr_wdata_int[CSR_MSIX_BIT];\n assign mie_d.irq_timer = csr_wdata_int[CSR_MTIX_BIT];\n assign mie_d.irq_external = csr_wdata_int[CSR_MEIX_BIT];\n assign mie_d.irq_fast = csr_wdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW];\n ibex_csr #(\n .Width ($bits(irqs_t)),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mie_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mie_d}),\n .wr_en_i (mie_en),\n .rd_data_o (mie_q),\n .rd_error_o ()\n );\n\n // MSCRATCH\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mscratch_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (mscratch_en),\n .rd_data_o (mscratch_q),\n .rd_error_o ()\n );\n\n // MCAUSE\n ibex_csr #(\n .Width (6),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mcause_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mcause_d),\n .wr_en_i (mcause_en),\n .rd_data_o (mcause_q),\n .rd_error_o ()\n );\n\n // MTVAL\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mtval_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mtval_d),\n .wr_en_i (mtval_en),\n .rd_data_o (mtval_q),\n .rd_error_o ()\n );\n\n // MTVEC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (ShadowCSR),\n .ResetValue (32'd1)\n ) u_mtvec_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mtvec_d),\n .wr_en_i (mtvec_en),\n .rd_data_o (mtvec_q),\n .rd_error_o (mtvec_err)\n );\n\n // DCSR\n localparam dcsr_t DCSR_RESET_VAL = '{\n xdebugver: XDEBUGVER_STD,\n cause: DBG_CAUSE_NONE, // 3'h0\n prv: PRIV_LVL_M,\n default: '0\n };\n ibex_csr #(\n .Width ($bits(dcsr_t)),\n .ShadowCopy (1'b0),\n .ResetValue ({DCSR_RESET_VAL})\n ) u_dcsr_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({dcsr_d}),\n .wr_en_i (dcsr_en),\n .rd_data_o (dcsr_q),\n .rd_error_o ()\n );\n\n // DEPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_depc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (depc_d),\n .wr_en_i (depc_en),\n .rd_data_o (depc_q),\n .rd_error_o ()\n );\n\n // DSCRATCH0\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_dscratch0_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (dscratch0_en),\n .rd_data_o (dscratch0_q),\n .rd_error_o ()\n );\n\n // DSCRATCH1\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_dscratch1_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (dscratch1_en),\n .rd_data_o (dscratch1_q),\n .rd_error_o ()\n );\n\n // MSTACK\n localparam status_stk_t MSTACK_RESET_VAL = '{\n mpie: 1'b1,\n mpp: PRIV_LVL_U\n };\n ibex_csr #(\n .Width ($bits(status_stk_t)),\n .ShadowCopy (1'b0),\n .ResetValue ({MSTACK_RESET_VAL})\n ) u_mstack_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mstack_d}),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_q),\n .rd_error_o ()\n );\n\n // MSTACK_EPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mstack_epc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mstack_epc_d),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_epc_q),\n .rd_error_o ()\n );\n\n // MSTACK_CAUSE\n ibex_csr #(\n .Width (6),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mstack_cause_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mstack_cause_d),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_cause_q),\n .rd_error_o ()\n );\n\n // -----------------\n // PMP registers\n // -----------------\n\n if (PMPEnable) begin : g_pmp_registers\n pmp_mseccfg_t pmp_mseccfg_q, pmp_mseccfg_d;\n logic pmp_mseccfg_we;\n logic pmp_mseccfg_err;\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_locked;\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n logic [PMPAddrWidth-1:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n logic [PMPNumRegions-1:0] pmp_cfg_err;\n logic [PMPNumRegions-1:0] pmp_addr_we;\n logic [PMPNumRegions-1:0] pmp_addr_err;\n logic any_pmp_entry_locked;\n\n // Expanded / qualified register read data\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_exp_rd_data\n if (i < PMPNumRegions) begin : g_implemented_regions\n // Add in zero padding for reserved fields\n assign pmp_cfg_rdata[i] = {pmp_cfg[i].lock, 2'b00, pmp_cfg[i].mode,\n pmp_cfg[i].exec, pmp_cfg[i].write, pmp_cfg[i].read};\n\n // Address field read data depends on the current programmed mode and the granularity\n // See RISC-V Privileged Specification, version 1.11, Section 3.6.1\n if (PMPGranularity == 0) begin : g_pmp_g0\n // If G == 0, read data is unmodified\n assign pmp_addr_rdata[i] = pmp_addr[i];\n\n end else if (PMPGranularity == 1) begin : g_pmp_g1\n // If G == 1, bit [G-1] reads as zero in TOR or OFF mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n\n end else begin : g_pmp_g2\n // For G >= 2, bits are masked to one or zero depending on the mode\n always_comb begin\n // In NAPOT mode, bits [G-2:0] must read as one\n pmp_addr_rdata[i] = {pmp_addr[i], {PMPGranularity-1{1'b1}}};\n\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n // In TOR or OFF mode, bits [G-1:0] must read as zero\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n end\n\n end else begin : g_other_regions\n // Non-implemented regions read as zero\n assign pmp_cfg_rdata[i] = '0;\n assign pmp_addr_rdata[i] = '0;\n end\n end\n\n // Write data calculation\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_pmp_csrs\n // -------------------------\n // Instantiate cfg registers\n // -------------------------\n assign pmp_cfg_we[i] = csr_we_int & ~pmp_cfg_locked[i] &\n (csr_addr == (CSR_OFF_PMP_CFG + (i[11:0] >> 2)));\n\n // Select the correct WDATA (each CSR contains 4 CFG fields, each with 2 RES bits)\n assign pmp_cfg_wdata[i].lock = csr_wdata_int[(i%4)*PMP_CFG_W+7];\n // NA4 mode is not selectable when G > 0, mode is treated as OFF\n always_comb begin\n unique case (csr_wdata_int[(i%4)*PMP_CFG_W+3+:2])\n 2'b00 : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n 2'b01 : pmp_cfg_wdata[i].mode = PMP_MODE_TOR;\n 2'b10 : pmp_cfg_wdata[i].mode = (PMPGranularity == 0) ? PMP_MODE_NA4:\n PMP_MODE_OFF;\n 2'b11 : pmp_cfg_wdata[i].mode = PMP_MODE_NAPOT;\n default : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n endcase\n end\n assign pmp_cfg_wdata[i].exec = csr_wdata_int[(i%4)*PMP_CFG_W+2];\n // When MSECCFG.MML is unset, W = 1, R = 0 is a reserved combination, so force W to 0 if R ==\n // 0. Otherwise allow all possible values to be written.\n assign pmp_cfg_wdata[i].write = pmp_mseccfg_q.mml ? csr_wdata_int[(i%4)*PMP_CFG_W+1] :\n &csr_wdata_int[(i%4)*PMP_CFG_W+:2];\n assign pmp_cfg_wdata[i].read = csr_wdata_int[(i%4)*PMP_CFG_W];\n\n ibex_csr #(\n .Width ($bits(pmp_cfg_t)),\n .ShadowCopy (ShadowCSR),\n .ResetValue ('0)\n ) u_pmp_cfg_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({pmp_cfg_wdata[i]}),\n .wr_en_i (pmp_cfg_we[i]),\n .rd_data_o (pmp_cfg[i]),\n .rd_error_o (pmp_cfg_err[i])\n );\n\n // MSECCFG.RLB allows the lock bit to be bypassed (allowing cfg writes when MSECCFG.RLB is\n // set).\n assign pmp_cfg_locked[i] = pmp_cfg[i].lock & ~pmp_mseccfg_q.rlb;\n\n // --------------------------\n // Instantiate addr registers\n // --------------------------\n if (i < PMPNumRegions - 1) begin : g_lower\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg_locked[i] &\n (~pmp_cfg_locked[i+1] | (pmp_cfg[i+1].mode != PMP_MODE_TOR)) &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end else begin : g_upper\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg_locked[i] &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end\n\n ibex_csr #(\n .Width (PMPAddrWidth),\n .ShadowCopy (ShadowCSR),\n .ResetValue ('0)\n ) u_pmp_addr_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int[31-:PMPAddrWidth]),\n .wr_en_i (pmp_addr_we[i]),\n .rd_data_o (pmp_addr[i]),\n .rd_error_o (pmp_addr_err[i])\n );\n\n assign csr_pmp_cfg_o[i] = pmp_cfg[i];\n assign csr_pmp_addr_o[i] = {pmp_addr_rdata[i], 2'b00};\n end\n\n assign pmp_mseccfg_we = csr_we_int & (csr_addr == CSR_MSECCFG);\n\n // MSECCFG.MML/MSECCFG.MMWP cannot be unset once set\n assign pmp_mseccfg_d.mml = pmp_mseccfg_q.mml ? 1'b1 : csr_wdata_int[CSR_MSECCFG_MML_BIT];\n assign pmp_mseccfg_d.mmwp = pmp_mseccfg_q.mmwp ? 1'b1 : csr_wdata_int[CSR_MSECCFG_MMWP_BIT];\n\n // pmp_cfg_locked factors in MSECCFG.RLB so any_pmp_entry_locked will only be set if MSECCFG.RLB\n // is unset\n assign any_pmp_entry_locked = |pmp_cfg_locked;\n\n // When any PMP entry is locked (A PMP entry has the L bit set and MSECCFG.RLB is unset),\n // MSECCFG.RLB cannot be set again\n assign pmp_mseccfg_d.rlb = any_pmp_entry_locked ? 1'b0 : csr_wdata_int[CSR_MSECCFG_RLB_BIT];\n\n ibex_csr #(\n .Width ($bits(pmp_mseccfg_t)),\n .ShadowCopy (ShadowCSR),\n .ResetValue ('0)\n ) u_pmp_mseccfg (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (pmp_mseccfg_d),\n .wr_en_i (pmp_mseccfg_we),\n .rd_data_o (pmp_mseccfg_q),\n .rd_error_o (pmp_mseccfg_err)\n );\n\n assign pmp_csr_err = (|pmp_cfg_err) | (|pmp_addr_err) | pmp_mseccfg_err;\n assign pmp_mseccfg = pmp_mseccfg_q;\n\n end else begin : g_no_pmp_tieoffs\n // Generate tieoffs when PMP is not configured\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_rdata\n assign pmp_addr_rdata[i] = '0;\n assign pmp_cfg_rdata[i] = '0;\n end\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_outputs\n assign csr_pmp_cfg_o[i] = pmp_cfg_t'(1'b0);\n assign csr_pmp_addr_o[i] = '0;\n end\n assign pmp_csr_err = 1'b0;\n assign pmp_mseccfg = '0;\n end\n\n assign csr_pmp_mseccfg_o = pmp_mseccfg;\n\n //////////////////////////\n // Performance monitor //\n //////////////////////////\n\n // update enable signals\n always_comb begin : mcountinhibit_update\n if (mcountinhibit_we == 1'b1) begin\n // bit 1 must always be 0\n mcountinhibit_d = {csr_wdata_int[MHPMCounterNum+2:2], 1'b0, csr_wdata_int[0]};\n end else begin\n mcountinhibit_d = mcountinhibit_q;\n end\n end\n\n // event selection (hardwired) & control\n always_comb begin : gen_mhpmcounter_incr\n\n // Assign inactive counters (first to prevent latch inference)\n for (int unsigned i=0; i<32; i++) begin : gen_mhpmcounter_incr_inactive\n mhpmcounter_incr[i] = 1'b0;\n end\n\n // When adding or altering performance counter meanings and default\n // mappings please update dv/verilator/pcount/cpp/ibex_pcounts.cc\n // appropriately.\n //\n // active counters\n mhpmcounter_incr[0] = 1'b1; // mcycle\n mhpmcounter_incr[1] = 1'b0; // reserved\n mhpmcounter_incr[2] = instr_ret_i; // minstret\n mhpmcounter_incr[3] = dside_wait_i; // cycles waiting for data memory\n mhpmcounter_incr[4] = iside_wait_i; // cycles waiting for instr fetches\n mhpmcounter_incr[5] = mem_load_i; // num of loads\n mhpmcounter_incr[6] = mem_store_i; // num of stores\n mhpmcounter_incr[7] = jump_i; // num of jumps (unconditional)\n mhpmcounter_incr[8] = branch_i; // num of branches (conditional)\n mhpmcounter_incr[9] = branch_taken_i; // num of taken branches (conditional)\n mhpmcounter_incr[10] = instr_ret_compressed_i; // num of compressed instr\n mhpmcounter_incr[11] = mul_wait_i; // cycles waiting for multiply\n mhpmcounter_incr[12] = div_wait_i; // cycles waiting for divide\n end\n\n // event selector (hardwired, 0 means no event)\n always_comb begin : gen_mhpmevent\n\n // activate all\n for (int i=0; i<32; i++) begin : gen_mhpmevent_active\n mhpmevent[i] = '0;\n mhpmevent[i][i] = 1'b1;\n end\n\n // deactivate\n mhpmevent[1] = '0; // not existing, reserved\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmevent_inactive\n mhpmevent[i] = '0;\n end\n end\n\n // mcycle\n ibex_counter #(\n .CounterWidth(64)\n ) mcycle_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[0] & ~mcountinhibit[0]),\n .counterh_we_i(mhpmcounterh_we[0]),\n .counter_we_i(mhpmcounter_we[0]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[0])\n );\n\n // minstret\n ibex_counter #(\n .CounterWidth(64)\n ) minstret_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[2] & ~mcountinhibit[2]),\n .counterh_we_i(mhpmcounterh_we[2]),\n .counter_we_i(mhpmcounter_we[2]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[2])\n );\n\n // reserved:\n assign mhpmcounter[1] = '0;\n assign unused_mhpmcounter_we_1 = mhpmcounter_we[1];\n assign unused_mhpmcounterh_we_1 = mhpmcounterh_we[1];\n assign unused_mhpmcounter_incr_1 = mhpmcounter_incr[1];\n\n for (genvar cnt=0; cnt < 29; cnt++) begin : gen_cntrs\n if (cnt < MHPMCounterNum) begin : gen_imp\n ibex_counter #(\n .CounterWidth(MHPMCounterWidth)\n ) mcounters_variable_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[cnt+3] & ~mcountinhibit[cnt+3]),\n .counterh_we_i(mhpmcounterh_we[cnt+3]),\n .counter_we_i(mhpmcounter_we[cnt+3]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[cnt+3])\n );\n end else begin : gen_unimp\n assign mhpmcounter[cnt+3] = '0;\n end\n end\n\n if(MHPMCounterNum < 29) begin : g_mcountinhibit_reduced\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounterh_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_incr;\n\n assign mcountinhibit = {{29-MHPMCounterNum{1'b1}}, mcountinhibit_q};\n // Lint tieoffs for unused bits\n assign unused_mhphcounter_we = mhpmcounter_we[31:MHPMCounterNum+3];\n assign unused_mhphcounterh_we = mhpmcounterh_we[31:MHPMCounterNum+3];\n assign unused_mhphcounter_incr = mhpmcounter_incr[31:MHPMCounterNum+3];\n end else begin : g_mcountinhibit_full\n assign mcountinhibit = mcountinhibit_q;\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n mcountinhibit_q <= '0;\n end else begin\n mcountinhibit_q <= mcountinhibit_d;\n end\n end\n\n /////////////////////////////\n // Debug trigger registers //\n /////////////////////////////\n\n if (DbgTriggerEn) begin : gen_trigger_regs\n localparam int unsigned DbgHwNumLen = DbgHwBreakNum > 1 ? $clog2(DbgHwBreakNum) : 1;\n localparam int unsigned MaxTselect = DbgHwBreakNum - 1;\n\n // Register values\n logic [DbgHwNumLen-1:0] tselect_d, tselect_q;\n logic tmatch_control_d;\n logic [DbgHwBreakNum-1:0] tmatch_control_q;\n logic [31:0] tmatch_value_d;\n logic [31:0] tmatch_value_q[DbgHwBreakNum];\n logic selected_tmatch_control;\n logic [31:0] selected_tmatch_value;\n\n // Write enables\n logic tselect_we;\n logic [DbgHwBreakNum-1:0] tmatch_control_we;\n logic [DbgHwBreakNum-1:0] tmatch_value_we;\n // Trigger comparison result\n logic [DbgHwBreakNum-1:0] trigger_match;\n\n // Write select\n assign tselect_we = csr_we_int & debug_mode_i & (csr_addr_i == CSR_TSELECT);\n for (genvar i = 0; i < DbgHwBreakNum; i++) begin : g_dbg_tmatch_we\n assign tmatch_control_we[i] = (i[DbgHwNumLen-1:0] == tselect_q) & csr_we_int & debug_mode_i &\n (csr_addr_i == CSR_TDATA1);\n assign tmatch_value_we[i] = (i[DbgHwNumLen-1:0] == tselect_q) & csr_we_int & debug_mode_i &\n (csr_addr_i == CSR_TDATA2);\n end\n\n // Debug interface tests the available number of triggers by writing and reading the trigger\n // select register. Only allow changes to the register if it is within the supported region.\n assign tselect_d = (csr_wdata_int < DbgHwBreakNum) ? csr_wdata_int[DbgHwNumLen-1:0] :\n MaxTselect[DbgHwNumLen-1:0];\n\n // tmatch_control is enabled when the execute bit is set\n assign tmatch_control_d = csr_wdata_int[2];\n assign tmatch_value_d = csr_wdata_int[31:0];\n\n // Registers\n ibex_csr #(\n .Width (DbgHwNumLen),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_tselect_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tselect_d),\n .wr_en_i (tselect_we),\n .rd_data_o (tselect_q),\n .rd_error_o ()\n );\n\n for (genvar i = 0; i < DbgHwBreakNum; i++) begin : g_dbg_tmatch_reg\n ibex_csr #(\n .Width (1),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_tmatch_control_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tmatch_control_d),\n .wr_en_i (tmatch_control_we[i]),\n .rd_data_o (tmatch_control_q[i]),\n .rd_error_o ()\n );\n\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_tmatch_value_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tmatch_value_d),\n .wr_en_i (tmatch_value_we[i]),\n .rd_data_o (tmatch_value_q[i]),\n .rd_error_o ()\n );\n end\n\n // Assign read data\n // TSELECT - number of supported triggers defined by parameter DbgHwBreakNum\n localparam int unsigned TSelectRdataPadlen = DbgHwNumLen >= 32 ? 0 : (32 - DbgHwNumLen);\n assign tselect_rdata = {{TSelectRdataPadlen{1'b0}}, tselect_q};\n\n if (DbgHwBreakNum > 1) begin : g_dbg_tmatch_multiple_select\n assign selected_tmatch_control = tmatch_control_q[tselect_q];\n assign selected_tmatch_value = tmatch_value_q[tselect_q];\n end else begin : g_dbg_tmatch_single_select\n assign selected_tmatch_control = tmatch_control_q[0];\n assign selected_tmatch_value = tmatch_value_q[0];\n end\n\n // TDATA0 - only support simple address matching\n assign tmatch_control_rdata = {4'h2, // type : address/data match\n 1'b1, // dmode : access from D mode only\n 6'h00, // maskmax : exact match only\n 1'b0, // hit : not supported\n 1'b0, // select : address match only\n 1'b0, // timing : match before execution\n 2'b00, // sizelo : match any access\n 4'h1, // action : enter debug mode\n 1'b0, // chain : not supported\n 4'h0, // match : simple match\n 1'b1, // m : match in m-mode\n 1'b0, // 0 : zero\n 1'b0, // s : not supported\n 1'b1, // u : match in u-mode\n selected_tmatch_control, // execute : match instruction address\n 1'b0, // store : not supported\n 1'b0}; // load : not supported\n\n // TDATA1 - address match value only\n assign tmatch_value_rdata = selected_tmatch_value;\n\n // Breakpoint matching\n // We match against the next address, as the breakpoint must be taken before execution\n for (genvar i = 0; i < DbgHwBreakNum; i++) begin : g_dbg_trigger_match\n assign trigger_match[i] = tmatch_control_q[i] & (pc_if_i[31:0] == tmatch_value_q[i]);\n end\n assign trigger_match_o = |trigger_match;\n\n end else begin : gen_no_trigger_regs\n assign tselect_rdata = 'b0;\n assign tmatch_control_rdata = 'b0;\n assign tmatch_value_rdata = 'b0;\n assign trigger_match_o = 'b0;\n end\n\n //////////////////////////\n // CPU control register //\n //////////////////////////\n\n // Cast register write data\n assign cpuctrl_wdata = cpu_ctrl_t'(csr_wdata_int[$bits(cpu_ctrl_t)-1:0]);\n\n // Generate fixed time execution bit\n if (DataIndTiming) begin : gen_dit\n assign cpuctrl_d.data_ind_timing = cpuctrl_wdata.data_ind_timing;\n\n end else begin : gen_no_dit\n // tieoff for the unused bit\n logic unused_dit;\n assign unused_dit = cpuctrl_wdata.data_ind_timing;\n\n // field will always read as zero if not configured\n assign cpuctrl_d.data_ind_timing = 1'b0;\n end\n\n assign data_ind_timing_o = cpuctrl_q.data_ind_timing;\n\n // Generate dummy instruction signals\n if (DummyInstructions) begin : gen_dummy\n assign cpuctrl_d.dummy_instr_en = cpuctrl_wdata.dummy_instr_en;\n assign cpuctrl_d.dummy_instr_mask = cpuctrl_wdata.dummy_instr_mask;\n\n // Signal a write to the seed register\n assign dummy_instr_seed_en_o = csr_we_int && (csr_addr == CSR_SECURESEED);\n assign dummy_instr_seed_o = csr_wdata_int;\n\n end else begin : gen_no_dummy\n // tieoff for the unused bit\n logic unused_dummy_en;\n logic [2:0] unused_dummy_mask;\n assign unused_dummy_en = cpuctrl_wdata.dummy_instr_en;\n assign unused_dummy_mask = cpuctrl_wdata.dummy_instr_mask;\n\n // field will always read as zero if not configured\n assign cpuctrl_d.dummy_instr_en = 1'b0;\n assign cpuctrl_d.dummy_instr_mask = 3'b000;\n assign dummy_instr_seed_en_o = 1'b0;\n assign dummy_instr_seed_o = '0;\n end\n\n assign dummy_instr_en_o = cpuctrl_q.dummy_instr_en;\n assign dummy_instr_mask_o = cpuctrl_q.dummy_instr_mask;\n\n // Generate icache enable bit\n if (ICache) begin : gen_icache_enable\n assign cpuctrl_d.icache_enable = cpuctrl_wdata.icache_enable;\n end else begin : gen_no_icache\n // tieoff for the unused icen bit\n logic unused_icen;\n assign unused_icen = cpuctrl_wdata.icache_enable;\n\n // icen field will always read as zero if ICache not configured\n assign cpuctrl_d.icache_enable = 1'b0;\n end\n\n assign icache_enable_o = cpuctrl_q.icache_enable;\n\n ibex_csr #(\n .Width ($bits(cpu_ctrl_t)),\n .ShadowCopy (ShadowCSR),\n .ResetValue ('0)\n ) u_cpuctrl_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({cpuctrl_d}),\n .wr_en_i (cpuctrl_we),\n .rd_data_o (cpuctrl_q),\n .rd_error_o (cpuctrl_err)\n );\n\n assign csr_shadow_err_o = mstatus_err | mtvec_err | pmp_csr_err | cpuctrl_err;\n\n ////////////////\n // Assertions //\n ////////////////\n\n `ASSERT(IbexCsrOpEnRequiresAccess, csr_op_en_i |-> csr_access_i)\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/cs_registers.rst", "doc/03_reference/pmp.rst", "doc/03_reference/debug.rst", "doc/03_reference/performance_counters.rst", "doc/03_reference/exception_interrupts.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1130, "lang": "sv", "rtl_files": ["rtl/ibex_decoder.sv"], "spec": "# ibex Decoder Module Behavioral Specification\n\n## 1. Overview\n\nThe decoder module is a fully combinational block (excluding a single register for rs3 prediction) that receives a 32-bit uncompressed RISC-V instruction and generates all control signals required to execute that instruction in the ID/EX stage. It decodes every valid instruction from the RV32I base set, optionally extended with the M‑extension (multiply/divide) and B‑extension (bit manipulation). The decoder also detects illegal instructions, handles RV32E register file restrictions, manages CSR access semantics, and supports a configurable branch target ALU.\n\nAll outputs are valid in the same cycle the instruction is presented, except for a small number of multi‑cycle instructions that require the decoder to retain one bit of state (for rs3 read address selection). The decoder does not use a clock or reset for its decoding logic; those signals are present only for assertion purposes.\n\n## 2. Inputs (Conceptual)\n\n- **Instruction word**: the 32‑bit uncompressed instruction to be decoded.\n- **First cycle indicator**: asserted when the instruction is entering the ID/EX stage for the first time. Used to distinguish the first and second cycles of two‑cycle operations (e.g., jumps and branches without branch target ALU, FENCE.I).\n- **Branch taken indicator**: registered value indicating whether a previous branch condition evaluated to taken. Used for branch target selection in the second cycle.\n- **Illegal compressed instruction flag**: asserted when the instruction fetch stage could not decode a compressed instruction. When high, the decoder must treat the resulting 32‑bit word as illegal regardless of its content.\n- **Parameters**: `RV32E`, `RV32M`, `RV32B`, `BranchTargetALU`.\n\n## 3. Outputs (Conceptual)\n\n- **Illegal instruction flag**: indicates the instruction is illegal.\n- **Exception / special instruction flags**: ebreak, ecall, mret, dret, wfi.\n- **Jump and branch control**: jump in decoder, branch in decoder, jump set, icache invalidate.\n- **Register file control**: write enable, write address, read addresses (two ports), read enables, write data source select.\n- **ALU control**: operation, operand A and B mux selects, immediate mux selects, multicycle flag.\n- **Immediate values**: I‑type, S‑type, B‑type, U‑type, J‑type, Z‑type (zero‑extended rs1).\n- **Multiplier/divider control**: enable (static and dynamic), operation, signed modes.\n- **CSR access control**: access enable, operation type (read, write, set, clear).\n- **LSU control**: data request, write enable, data size, sign extension.\n- **Jump/branch target ALU control**: operand A and B selects for the separate branch target ALU (if configured).\n\n## 4. Detailed Behavioral Requirements\n\n### 4.1 Instruction Decoding\n\nThe decoder shall inspect the opcode (bits 6:0) and, for some instruction groups, the funct3 (bits 14:12) and/or funct7 (bits 31:25) fields to determine the instruction class and its control signals. It shall generate the outputs described in the following subsections for each valid instruction class. Any combination of opcode, funct3, funct7 (and optionally funct7 sub‑fields) that does not correspond to a defined instruction must cause the illegal instruction flag to be asserted.\n\n### 4.2 Illegal Instruction Detection\n\nThe decoder shall combine several sources to produce the final illegal instruction flag:\n\n- **Illegal opcode / funct3 / funct7**: as detailed per instruction class below.\n- **Illegal compressed instruction**: if the external illegal compressed flag is asserted, the instruction shall be marked illegal irrespective of other decode logic.\n- **RV32E register check** (when `RV32E=1`): any instruction that reads from a register with address bit 4 set (x16–x31) when that read is actually used (as determined by the register file read enables) shall be marked illegal. Similarly, any instruction that writes to a register with address bit 4 set when the write enable is active shall be illegal.\n- **CSR operand check**: for CSR instructions of type `CSRRS` or `CSRRC` (opcode SYSTEM, funct3 != 0), the decoder shall examine the rs1 field. If rs1 equals zero, the CSR operation shall be downgraded to a read-only access. This is not an illegal condition, but the `csr_op_o` output must be `CSR_OP_READ` in that case. For `CSRRSI`/`CSRRCI` (immediate variants), if the uimm[4:0] field (rs1) is zero, the operation shall also be downgraded to read-only.\n\nWhen illegal instruction is asserted, the decoder **must** clear the following outputs to their inactive states: register file write enable, LSU data request and write enable, jump in decoder and jump set, branch in decoder, CSR access enable. The multiplier/divider dynamic enable signals shall also be suppressed.\n\n### 4.3 Immediate Generation\n\nThe decoder shall compute the following immediate values from the instruction word:\n\n- **I‑type**: sign‑extended 12‑bit immediate (bits 31:20).\n- **S‑type**: sign‑extended 12‑bit immediate formed from bits 31:25 and 11:7.\n- **B‑type**: sign‑extended 13‑bit immediate formed from bits 31, 7, 30:25, 11:8, left‑shifted by 1 (i.e., multiple of 2).\n- **U‑type**: upper 20 bits (31:12) left‑shifted by 12, lower bits zero.\n- **J‑type**: sign‑extended 21‑bit immediate formed from bits 31, 19:12, 20, 30:21, left‑shifted by 1.\n- **Z‑type**: the contents of the rs1 field expanded to 32 bits by zero extension (used for CSR immediate operations).\n\nAll immediate outputs are combinatorial and available in the same cycle.\n\n### 4.4 Register File Control\n\nThe decoder shall provide two read addresses and one write address. The read port A address shall normally be rs1 (bits 19:15). For instructions that use a third source register (rs3, bits 31:27) in the second cycle of a multi‑cycle operation (e.g., CMIX, CMOV, FSL, FSR, FSRI), the decoder must output the rs3 address on read port A in the cycle following the instruction’s first cycle. The decoder internally maintains a one‑bit state to track this switch. The read port B address is always rs2 (bits 24:20). The write address is always rd (bits 11:7).\n\n**Register file write enable**: shall be generated for all instructions that write a result. Exceptions: illegal instructions (cleared), FENCE, FENCE.I, ECALL, EBREAK, MRET, DRET, WFI, and branches. For jumps (JAL, JALR) the write enable depends on the cycle and the `BranchTargetALU` parameter (see Section 4.7). For CSR instructions, write enable is always active (unless illegal). Under RV32E, the write enable must be masked to zero when rd has bit 4 set.\n\n**Read enable A**: shall be asserted for instructions that read rs1 (or rs3 in the second cycle). **Read enable B**: shall be asserted for instructions that read rs2.\n\nThe decoder shall also select the write data source:\n- `RF_WD_EX` for ALU results (most integer computational, jump link address, load data, CSR read data).\n- `RF_WD_CSR` for CSR read data (when CSR access is performed). The decoder outputs this selection.\n\n### 4.5 ALU Control\n\nThe decoder shall produce the following ALU related signals:\n\n- **ALU operation**: one of `ADD`, `SUB`, `SLL`, `SLT`, `SLTU`, `XOR`, `SRL`, `SRA`, `OR`, `AND`, plus many bit‑manipulation operations (e.g., ROL, ROR, MIN, MAX, PACK, CLZ, CTZ, etc.) as defined by the RISC‑V B‑extension specification.\n- **Operand A selection source**: one of current PC, register value from read port A, immediate value, or zero.\n- **Operand B selection source**: one of register value from read port B or immediate value.\n- **Immediate selection for operand B**: one of I‑type, S‑type, B‑type, U‑type, J‑type, PC increment (4), or Z‑type (used for CSR immediate).\n- **Immediate selection for operand A**: one of zero or Z‑type (for CSR immediate).\n- **ALU multicycle flag**: indicates that the ALU operation requires more than one cycle (e.g., rotate, CRC, bit extract/deposit). The decoder shall assert this flag for the appropriate B‑extension instructions.\n\nThe decoder must generate the correct ALU operation and operand selections for each instruction class, considering the current cycle (first or second) for multi‑cycle instructions (see Section 4.6).\n\n### 4.6 Multi‑Cycle Instruction Handling\n\nSome instructions require two cycles in the ID/EX stage. The decoder distinguishes the first cycle from subsequent cycles using the first‑cycle indicator input.\n\n- **Jumps (JAL, JALR) without BranchTargetALU**: \n In the first cycle, the decoder shall configure the ALU to compute the jump target (PC + J‑immediate or register + I‑immediate). In the second cycle, it shall configure the ALU to compute the link address (PC + 4). The jump‑set flag shall be asserted in the first cycle (to redirect fetch). If `BranchTargetALU` is enabled, the jump target is computed in a separate ALU, and the main ALU computes the link address in the first cycle; the instruction completes in one cycle.\n\n- **Branches without BranchTargetALU**: \n In the first cycle, the decoder shall configure the ALU to evaluate the branch condition (compare rs1 and rs2). In the second cycle, it shall configure the ALU to compute the branch target (PC + B‑immediate or PC + 4 if not taken). The branch‑in‑decoder flag shall be asserted in both cycles. The branch‑taken input selects the immediate for the second cycle. If `BranchTargetALU` is enabled, the target is computed in the separate ALU simultaneously with the condition, and the instruction completes in one cycle.\n\n- **FENCE.I without BranchTargetALU**: \n Behaves like a jump to the next PC. In the first cycle, the decoder shall assert jump‑set and configure the ALU to compute PC + 4. The instruction completes in one cycle (the fetch flush occurs immediately). If `BranchTargetALU` is enabled, the same jump target is computed in the separate ALU; the main ALU is not used.\n\n- **B‑extension multi‑cycle instructions (e.g., CMIX, CMOV, FSL, FSR, FSRI, CRC, BDEP, BEXT)**: \n These instructions require two cycles. In the first cycle, the decoder shall assert the multicycle flag, set up the ALU for the partially evaluated result, and for those using rs3, it shall set the internal state so that in the second cycle read port A reads rs3 instead of rs1. In the second cycle, the decoder shall complete the operation. The write enable shall be asserted in the second cycle.\n\n### 4.7 Multiplier/Divider Control\n\nThe decoder shall produce the following signals for M‑extension instructions (when `RV32M` is not `RV32MNone`):\n\n- **Static selection signals** (`mult_sel_o`, `div_sel_o`): asserted for multiply and divide/remainder instructions, respectively. These signals are static (not gated by illegal) and drive the data path muxes in the execute block.\n- **Dynamic enable signals** (`mult_en_o`, `div_en_o`): asserted for the same instructions, but gated by the illegal instruction condition (disabled when illegal).\n- **Operation** (`multdiv_operator_o`): one of `MULL`, `MULH`, `DIV`, `REM`.\n- **Signed mode** (`multdiv_signed_mode_o`): two bits encoding (signed operand A, signed operand B).\n\nThe decoder must disable both dynamic enables when the instruction is illegal (including when `RV32M == RV32MNone`).\n\n### 4.8 CSR Access Control\n\nFor instructions with opcode SYSTEM and funct3 != 0, the decoder shall:\n\n- Assert `csr_access_o`.\n- Set the write data source to `RF_WD_CSR`.\n- Assert the register file write enable (unless illegal).\n- Assert read enable A only when funct3[2] is 0 (register‑based variants), because the instruction reads rs1.\n- Select the CSR operation type (`csr_op_o`) according to funct3: 01→WRITE, 10→SET, 11→CLEAR.\n- Implement the special case when rs1 (or immediate) is zero as described in Section 4.2.\n\n### 4.9 Load/Store Unit Control\n\n- **Loads (opcode LOAD)**: \n The decoder shall assert data request, set data write enable to 0, configure the data size and sign extension according to funct3. Invalid funct3 combinations (e.g., `lwu`) shall be marked illegal. The ALU is used to compute the effective address (register + I‑immediate).\n\n- **Stores (opcode STORE)**: \n The decoder shall assert data request, set data write enable to 1, configure the data size according to funct3 (excluding bit 14 which must be 0). The ALU is used to compute the effective address (register + S‑immediate, or register+register when bit 14 is set – note that the decoder treats the S‑immediate case only; the register+register case is used for indexed stores in some B‑extension variants). The decoder shall mark as illegal any store with funct3 bit 14 set.\n\n### 4.10 Jump/Branch and Special Instructions\n\n- **JAL, JALR**: \n Set `jump_in_dec_o`. In the first cycle (or if BranchTargetALU enabled, single cycle) set `jump_set_o`. Mark illegal if JALR funct3 != 0.\n\n- **Branches**: \n Set `branch_in_dec_o`. Assert read enables for both rs1 and rs2. Illegal if funct3 not in {000,001,100,101,110,111}.\n\n- **ECALL, EBREAK, MRET, DRET, WFI**: \n Assert the respective output flags. No register write or LSU activity. ECALL/EBREAK/WFI are not illegal; MRET/DRET require funct3=0 and rs1, rd = 0, else illegal.\n\n- **FENCE**: \n Treated as a NOP; all control signals remain inactive.\n\n- **FENCE.I**: \n Implemented as a jump to the next PC (to flush the instruction fetch pipeline). If present (and `RV32B` includes ICache), the decoder shall also assert `icache_inval_o` in the first cycle. The ALU or branch target ALU calculates PC+4. The decoder shall assert `jump_in_dec_o` and in the first cycle assert `jump_set_o`. FENCE.I is never illegal.\n\n### 4.11 Parameterization Effects\n\n- **RV32E**: \n When set to 1, the decoder shall enforce that no register with index ≥ 16 is read or written. This check is applied in addition to all other decode legality checks.\n\n- **RV32M**: \n When set to `RV32MNone`, all M‑extension instructions shall be marked illegal. For other values, the decoder shall enable the multiplier/divider as described above.\n\n- **RV32B**: \n When set to `RV32BNone`, all B‑extension instructions shall be marked illegal. When set to `RV32BBalanced` or `RV32BFull`, the decoder shall enable the corresponding subset of B‑extension instructions (including the multi‑cycle handling). The exact set of instructions enabled for each configuration is defined in the official Ibex documentation (see `doc/03_reference/instruction_decode_execute.rst`).\n\n- **BranchTargetALU**: \n When set to 1, the decoder shall generate separate control signals for a second ALU dedicated to computing branch/jump targets. This reduces the stall cycles for jumps and branches. The main ALU is then used only for the link address computation or branch condition evaluation, as appropriate.\n\n## 5. Timing and Pipelining\n\nThe decoder is purely combinational; all outputs except the internal rs3 prediction register are available in the same cycle as the input instruction. The rs3 prediction register is updated every cycle (on the positive clock edge) to remember whether the next cycle should use rs3. This register is initialized to 0 at reset. The decoder must ensure that for instructions not requiring rs3, the read port A continues to use rs1.\n\nThe illegal compressed instruction flag, when asserted, overrides all other decode logic and forces the instruction to be treated as illegal in the same cycle.\n\n## 6. Reset Behavior\n\nThe decoder does not contain any logic that requires reset except the rs3 prediction register, which shall be cleared to 0 on reset. All combinational outputs are undefined during reset but will become valid as soon as reset is de‑asserted and inputs are stable.\n\n## 7. Summary of Output Activation by Instruction Class\n\n| Instruction Class | Key Outputs Activated |\n|-------------------------|---------------------------------------------------------------------------------------|\n| Integer computational | rf_we, ALU ops, (mult/div if M‑extension), immediate selects |\n| Load | data_req, data_we=0, ALU address, immediate, rf_we |\n| Store | data_req, data_we=1, ALU address, immediate |\n| Branch | branch_in_dec, rf_ren_a, rf_ren_b, ALU condition, BTALU (if enabled) |\n| JAL/JALR | jump_in_dec, jump_set (first cycle), rf_we (link addr), ALU target/link |\n| FENCE | none (NOP) |\n| FENCE.I | jump_in_dec, jump_set, icache_inval, ALU PC+4 |\n| CSR (non‑SYSTEM 0) | csr_access, rf_we, rf_wdata_sel=CSR, ALU immediate, rf_ren_a (if register variant) |\n| ECALL/EBREAK/MRET/DRET/WFI | respective flag, rf_we=0, LSU inactive |\n| Illegal (any) | illegal_insn, all other outputs cleared |\n\nThis specification defines the correct observable behavior of the `ibex_decoder` module. Implementation details such as specific signal names, internal state encoding, or combinational logic structure are not part of this behavioral description.", "commit_id": "bcbf1a7adf27c3bfc57205c684c2192c0d24fa3f", "timestamp": "2020-10-14T08:49:31+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "adc574b8b0c10381a7728badc2c67c21daabc63f", "pr_title": "[rtl] Fix missing else branch in decoder", "pr_body": "- Without the B extension, a gorci instruction should decode as an\r\n illegal instruction.\r\n- Relates to #1129\r\n\r\nSigned-off-by: Tom Roberts ", "issue_title": "Illegal Instruction Exception not Raised", "issue_body": "**RISC-V Specification:**\r\n\r\n> Unprivileged ISA\r\n\r\n**Issue Description:**\r\n\r\nAn illegal instruction updates the register file and the associated csrs and executes normally without raising an illegal instruction exception.\r\n\r\n**Example:**\r\n\r\nThe instruction 32'h2820d013 is decoded and executed with no illegal instruction exception being flagged, as machine csrs: mepc, mstatus and mcause aren't updated. \r\n\r\n![illegalInstr](https://user-images.githubusercontent.com/54367010/95882023-7cbe9200-0d79-11eb-97de-fd485e24e459.PNG)\r\n\r\n---\r\n\r\nProduct: OneSpin 360 DV-Verify\r\nApp: Processor Verification App\r\nTool's version: 2020.2.0", "commit_message": "[rtl] Fix missing else branch in decoder\n\n- Without the B extension, a gorci instruction should decode as an\n illegal instruction.\n- Relates to #1129\n\nSigned-off-by: Tom Roberts ", "fix_patch": "diff --git a/rtl/ibex_decoder.sv b/rtl/ibex_decoder.sv\nindex f55b719cec..c8d4141899 100644\n--- a/rtl/ibex_decoder.sv\n+++ b/rtl/ibex_decoder.sv\n@@ -408,6 +408,8 @@ module ibex_decoder #(\n illegal_insn = 1'b0; // gorci\n end else if (instr[24:20] == 5'b00111) begin\n illegal_insn = (RV32B == RV32BBalanced) ? 1'b0 : 1'b1; // orc.b\n+ end else begin\n+ illegal_insn = 1'b1;\n end\n end\n 5'b0_0001: begin\n", "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 * Instruction decoder\n *\n * This module is fully combinatorial, clock and reset are used for\n * assertions only.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_decoder #(\n parameter bit RV32E = 0,\n parameter ibex_pkg::rv32m_e RV32M = ibex_pkg::RV32MFast,\n parameter ibex_pkg::rv32b_e RV32B = ibex_pkg::RV32BNone,\n parameter bit BranchTargetALU = 0\n) (\n input logic clk_i,\n input logic rst_ni,\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 input logic branch_taken_i, // registered branch decision\n output logic icache_inval_o,\n\n // from IF-ID pipeline register\n input logic instr_first_cycle_i, // instruction read is in its first cycle\n input logic [31:0] instr_rdata_i, // instruction read from memory/cache\n input logic [31:0] instr_rdata_alu_i, // instruction read from memory/cache\n // replicated to ease fan-out)\n\n input logic illegal_c_insn_i, // compressed instruction decode failed\n\n // immediates\n output ibex_pkg::imm_a_sel_e imm_a_mux_sel_o, // immediate selection for operand a\n output ibex_pkg::imm_b_sel_e imm_b_mux_sel_o, // immediate selection for operand b\n output ibex_pkg::op_a_sel_e bt_a_mux_sel_o, // branch target selection operand a\n output ibex_pkg::imm_b_sel_e bt_b_mux_sel_o, // branch target selection 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_pkg::rf_wd_sel_e rf_wdata_sel_o, // RF write data selection\n output logic rf_we_o, // write enable for regfile\n output logic [4:0] rf_raddr_a_o,\n output logic [4:0] rf_raddr_b_o,\n output logic [4:0] rf_waddr_o,\n output logic rf_ren_a_o, // Instruction reads from RF addr A\n output logic rf_ren_b_o, // Instruction reads from RF addr B\n\n // ALU\n output ibex_pkg::alu_op_e alu_operator_o, // ALU operation selection\n output ibex_pkg::op_a_sel_e alu_op_a_mux_sel_o, // operand a selection: reg value, PC,\n // immediate or zero\n output ibex_pkg::op_b_sel_e alu_op_b_mux_sel_o, // operand b selection: reg value or\n // immediate\n output logic alu_multicycle_o, // ternary bitmanip instruction\n\n // MULT & DIV\n output logic mult_en_o, // perform integer multiplication\n output logic div_en_o, // perform integer division or remainder\n output logic mult_sel_o, // as above but static, for data muxes\n output logic div_sel_o, // as above but static, for data muxes\n\n output ibex_pkg::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_pkg::csr_op_e csr_op_o, // operation to perform on 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\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_pkg::*;\n\n logic illegal_insn;\n logic illegal_reg_rv32e;\n logic csr_illegal;\n logic rf_we;\n\n logic [31:0] instr;\n logic [31:0] instr_alu;\n // Source/Destination register instruction index\n logic [4:0] instr_rs1;\n logic [4:0] instr_rs2;\n logic [4:0] instr_rs3;\n logic [4:0] instr_rd;\n\n logic use_rs3_d;\n logic use_rs3_q;\n\n csr_op_e csr_op;\n\n opcode_e opcode;\n opcode_e opcode_alu;\n\n // To help timing the flops containing the current instruction are replicated to reduce fan-out.\n // instr_alu is used to determine the ALU control logic and associated operand/imm select signals\n // as the ALU is often on the more critical timing paths. instr is used for everything else.\n assign instr = instr_rdata_i;\n assign instr_alu = instr_rdata_alu_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_rs1 }; // rs1\n\n // the use of rs3 is known one cycle ahead.\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n use_rs3_q <= 1'b0;\n end else begin\n use_rs3_q <= use_rs3_d;\n end\n end\n\n // source registers\n assign instr_rs1 = instr[19:15];\n assign instr_rs2 = instr[24:20];\n assign instr_rs3 = instr[31:27];\n assign rf_raddr_a_o = (use_rs3_q & ~instr_first_cycle_i) ? instr_rs3 : instr_rs1; // rs3 / rs1\n assign rf_raddr_b_o = instr_rs2; // rs2\n\n // destination register\n assign instr_rd = instr[11:7];\n assign rf_waddr_o = instr_rd; // rd\n\n ////////////////////\n // Register check //\n ////////////////////\n if (RV32E) begin : gen_rv32e_reg_check_active\n assign illegal_reg_rv32e = ((rf_raddr_a_o[4] & (alu_op_a_mux_sel_o == OP_A_REG_A)) |\n (rf_raddr_b_o[4] & (alu_op_b_mux_sel_o == OP_B_REG_B)) |\n (rf_waddr_o[4] & rf_we));\n end else begin : gen_rv32e_reg_check_inactive\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_rs1 == '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 icache_inval_o = 1'b0;\n\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n\n rf_wdata_sel_o = RF_WD_EX;\n rf_we = 1'b0;\n rf_ren_a_o = 1'b0;\n rf_ren_b_o = 1'b0;\n\n csr_access_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_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\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n jump_in_dec_o = 1'b1;\n\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n if (instr[14:12] != 3'b0) begin\n illegal_insn = 1'b1;\n end\n\n rf_ren_a_o = 1'b1;\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,\n 3'b001,\n 3'b100,\n 3'b101,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n default: illegal_insn = 1'b1;\n endcase\n\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n end\n\n ////////////////\n // Load/store //\n ////////////////\n\n OPCODE_STORE: begin\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n data_req_o = 1'b1;\n data_we_o = 1'b1;\n\n if (instr[14]) begin\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: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_LOAD: begin\n rf_ren_a_o = 1'b1;\n data_req_o = 1'b1;\n data_type_o = 2'b00;\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(u)\n 2'b01: data_type_o = 2'b01; // lh(u)\n 2'b10: begin\n data_type_o = 2'b00; // lw\n if (instr[14]) begin\n illegal_insn = 1'b1; // lwu does not exist\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n /////////\n // ALU //\n /////////\n\n OPCODE_LUI: begin // Load Upper Immediate\n rf_we = 1'b1;\n end\n\n OPCODE_AUIPC: begin // Add Upper Immediate to PC\n rf_we = 1'b1;\n end\n\n OPCODE_OP_IMM: begin // Register-Immediate ALU Operations\n rf_ren_a_o = 1'b1;\n rf_we = 1'b1;\n\n unique case (instr[14:12])\n 3'b000,\n 3'b010,\n 3'b011,\n 3'b100,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n\n 3'b001: begin\n unique case (instr[31:27])\n 5'b0_0000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // slli\n 5'b0_0100, // sloi\n 5'b0_1001, // sbclri\n 5'b0_0101, // sbseti\n 5'b0_1101: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sbinvi\n 5'b0_0001: if (instr[26] == 1'b0) begin\n illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // shfl\n end else begin\n illegal_insn = 1'b1;\n end\n 5'b0_1100: begin\n unique case(instr[26:20])\n 7'b000_0000, // clz\n 7'b000_0001, // ctz\n 7'b000_0010, // pcnt\n 7'b000_0100, // sext.b\n 7'b000_0101: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sext.h\n 7'b001_0000, // crc32.b\n 7'b001_0001, // crc32.h\n 7'b001_0010, // crc32.w\n 7'b001_1000, // crc32c.b\n 7'b001_1001, // crc32c.h\n 7'b001_1010: illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // crc32c.w\n\n default: illegal_insn = 1'b1;\n endcase\n end\n default : illegal_insn = 1'b1;\n endcase\n end\n\n 3'b101: begin\n if (instr[26]) begin\n illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // fsri\n end else begin\n unique case (instr[31:27])\n 5'b0_0000, // srli\n 5'b0_1000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // srai\n\n 5'b0_0100, // sroi\n 5'b0_1100, // rori\n 5'b0_1001: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sbexti\n\n 5'b0_1101: begin\n if ((RV32B == RV32BFull)) begin\n illegal_insn = 1'b0; // grevi\n end else begin\n unique case (instr[24:20])\n 5'b11111, // rev\n 5'b11000: illegal_insn = (RV32B == RV32BBalanced) ? 1'b0 : 1'b1; // rev8\n\n default: illegal_insn = 1'b1;\n endcase\n end\n end\n 5'b0_0101: begin\n if ((RV32B == RV32BFull)) begin\n illegal_insn = 1'b0; // gorci\n end else if (instr[24:20] == 5'b00111) begin\n illegal_insn = (RV32B == RV32BBalanced) ? 1'b0 : 1'b1; // orc.b\n end else begin\n illegal_insn = 1'b1;\n end\n end\n 5'b0_0001: begin\n if (instr[26] == 1'b0) begin\n illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // unshfl\n end else begin\n illegal_insn = 1'b1;\n end\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_OP: begin // Register-Register ALU operation\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n rf_we = 1'b1;\n if ({instr[26], instr[13:12]} == {1'b1, 2'b01}) begin\n illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // cmix / cmov / fsl / fsr\n end else begin\n unique case ({instr[31:25], instr[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000},\n {7'b010_0000, 3'b000},\n {7'b000_0000, 3'b010},\n {7'b000_0000, 3'b011},\n {7'b000_0000, 3'b100},\n {7'b000_0000, 3'b110},\n {7'b000_0000, 3'b111},\n {7'b000_0000, 3'b001},\n {7'b000_0000, 3'b101},\n {7'b010_0000, 3'b101}: illegal_insn = 1'b0;\n\n // RV32B zbb\n {7'b010_0000, 3'b111}, // andn\n {7'b010_0000, 3'b110}, // orn\n {7'b010_0000, 3'b100}, // xnor\n {7'b001_0000, 3'b001}, // slo\n {7'b001_0000, 3'b101}, // sro\n {7'b011_0000, 3'b001}, // rol\n {7'b011_0000, 3'b101}, // ror\n {7'b000_0101, 3'b100}, // min\n {7'b000_0101, 3'b101}, // max\n {7'b000_0101, 3'b110}, // minu\n {7'b000_0101, 3'b111}, // maxu\n {7'b000_0100, 3'b100}, // pack\n {7'b010_0100, 3'b100}, // packu\n {7'b000_0100, 3'b111}, // packh\n // RV32B zbs\n {7'b010_0100, 3'b001}, // sbclr\n {7'b001_0100, 3'b001}, // sbset\n {7'b011_0100, 3'b001}, // sbinv\n {7'b010_0100, 3'b101}, // sbext\n // RV32B zbf\n {7'b010_0100, 3'b111}: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // bfp\n // RV32B zbe\n {7'b010_0100, 3'b110}, // bdep\n {7'b000_0100, 3'b110}, // bext\n // RV32B zbp\n {7'b011_0100, 3'b101}, // grev\n {7'b001_0100, 3'b101}, // gorc\n {7'b000_0100, 3'b001}, // shfl\n {7'b000_0100, 3'b101}, // unshfl\n // RV32B zbc\n {7'b000_0101, 3'b001}, // clmul\n {7'b000_0101, 3'b010}, // clmulr\n {7'b000_0101, 3'b011}: illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // clmulh\n\n // RV32M instructions\n {7'b000_0001, 3'b000}: begin // mul\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b01;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b100}: begin // div\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b101}: begin // divu\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b110}: begin // rem\n multdiv_operator_o = MD_OP_REM;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b111}: begin // remu\n multdiv_operator_o = MD_OP_REM;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\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 unique case (instr[14:12])\n 3'b000: begin\n // FENCE is treated as a NOP since all memory operations are already strictly ordered.\n rf_we = 1'b0;\n end\n 3'b001: begin\n // FENCE.I is implemented as a jump to the next PC, this gives the required flushing\n // behaviour (iside prefetch buffer flushed and response to any outstanding iside\n // requests will be ignored).\n // If present, the ICache will also be flushed.\n jump_in_dec_o = 1'b1;\n\n rf_we = 1'b0;\n\n if (instr_first_cycle_i) begin\n jump_set_o = 1'b1;\n icache_inval_o = 1'b1;\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr[14:12] == 3'b000) begin\n // non CSR related SYSTEM instructions\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_rs1 != 5'b0 || instr_rd != 5'b0) 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 rf_wdata_sel_o = RF_WD_CSR;\n rf_we = 1'b1;\n\n if (~instr[14]) begin\n rf_ren_a_o = 1'b1;\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 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, PC\n // NOTE: instructions can also be detected to be illegal inside the CSRs (upon accesses with\n // insufficient privileges), or when accessing non-available registers in RV32E,\n // these cases are not handled here\n if (illegal_insn) begin\n rf_we = 1'b0;\n data_req_o = 1'b0;\n data_we_o = 1'b0;\n jump_in_dec_o = 1'b0;\n jump_set_o = 1'b0;\n branch_in_dec_o = 1'b0;\n csr_access_o = 1'b0;\n end\n end\n\n /////////////////////////////\n // Decoder for ALU control //\n /////////////////////////////\n\n always_comb begin\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 bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_I;\n\n\n opcode_alu = opcode_e'(instr_alu[6:0]);\n\n use_rs3_d = 1'b0;\n alu_multicycle_o = 1'b0;\n mult_sel_o = 1'b0;\n div_sel_o = 1'b0;\n\n unique case (opcode_alu)\n\n ///////////\n // Jumps //\n ///////////\n\n OPCODE_JAL: begin // Jump and Link\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_J;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_REG_A;\n bt_b_mux_sel_o = IMM_B_I;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_BRANCH: begin // Branch\n // Check branch condition selection\n unique case (instr_alu[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: ;\n endcase\n\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n // Not-taken branch will jump to next instruction (used in secure mode)\n bt_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n end\n\n // Without branch target ALU, a branch is a two-stage operation using the Main ALU in both\n // stages\n if (instr_first_cycle_i) begin\n // First evaluate the 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 // Then calculate jump target\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n // Not-taken branch will jump to next instruction (used in secure mode)\n imm_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n alu_operator_o = ALU_ADD;\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 alu_operator_o = ALU_ADD;\n\n if (!instr_alu[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\n end\n\n OPCODE_LOAD: begin\n alu_op_a_mux_sel_o = OP_A_REG_A;\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 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 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 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\n unique case (instr_alu[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 if (RV32B != RV32BNone) begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n 5'b0_0100: alu_operator_o = ALU_SLO; // Shift Left Ones by Immediate\n 5'b0_1001: alu_operator_o = ALU_SBCLR; // Clear bit specified by immediate\n 5'b0_0101: alu_operator_o = ALU_SBSET; // Set bit specified by immediate\n 5'b0_1101: alu_operator_o = ALU_SBINV; // Invert bit specified by immediate.\n // Shuffle with Immediate Control Value\n 5'b0_0001: if (instr_alu[26] == 0) alu_operator_o = ALU_SHFL;\n 5'b0_1100: begin\n unique case (instr_alu[26:20])\n 7'b000_0000: alu_operator_o = ALU_CLZ; // clz\n 7'b000_0001: alu_operator_o = ALU_CTZ; // ctz\n 7'b000_0010: alu_operator_o = ALU_PCNT; // pcnt\n 7'b000_0100: alu_operator_o = ALU_SEXTB; // sext.b\n 7'b000_0101: alu_operator_o = ALU_SEXTH; // sext.h\n 7'b001_0000: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_B; // crc32.b\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_0001: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_H; // crc32.h\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_0010: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_W; // crc32.w\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1000: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_B; // crc32c.b\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1001: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_H; // crc32c.h\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1010: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_W; // crc32c.w\n alu_multicycle_o = 1'b1;\n end\n end\n default: ;\n endcase\n end\n\n default: ;\n endcase\n end else begin\n alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n end\n end\n\n 3'b101: begin\n if (RV32B != RV32BNone) begin\n if (instr_alu[26] == 1'b1) begin\n alu_operator_o = ALU_FSR;\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end else begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n 5'b0_1000: alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n 5'b0_0100: alu_operator_o = ALU_SRO; // Shift Right Ones by Immediate\n 5'b0_1001: alu_operator_o = ALU_SBEXT; // Extract bit specified by immediate.\n 5'b0_1100: begin\n alu_operator_o = ALU_ROR; // Rotate Right by Immediate\n alu_multicycle_o = 1'b1;\n end\n 5'b0_1101: alu_operator_o = ALU_GREV; // General Reverse with Imm Control Val\n 5'b0_0101: alu_operator_o = ALU_GORC; // General Or-combine with Imm Control Val\n // Unshuffle with Immediate Control Value\n 5'b0_0001: begin\n if (RV32B == RV32BFull) begin\n if (instr_alu[26] == 1'b0) alu_operator_o = ALU_UNSHFL;\n end\n end\n default: ;\n endcase\n end\n\n end else begin\n if (instr_alu[31:27] == 5'b0_0000) begin\n alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n end else if (instr_alu[31:27] == 5'b0_1000) begin\n alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n end\n end\n end\n\n default: ;\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\n if (instr_alu[26]) begin\n if (RV32B != RV32BNone) begin\n unique case ({instr_alu[26:25], instr_alu[14:12]})\n {2'b11, 3'b001}: begin\n alu_operator_o = ALU_CMIX; // cmix\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b11, 3'b101}: begin\n alu_operator_o = ALU_CMOV; // cmov\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b10, 3'b001}: begin\n alu_operator_o = ALU_FSL; // fsl\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b10, 3'b101}: begin\n alu_operator_o = ALU_FSR; // fsr\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n default: ;\n endcase\n end\n end else begin\n unique case ({instr_alu[31:25], instr_alu[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000}: alu_operator_o = ALU_ADD; // Add\n {7'b010_0000, 3'b000}: alu_operator_o = ALU_SUB; // Sub\n {7'b000_0000, 3'b010}: alu_operator_o = ALU_SLT; // Set Lower Than\n {7'b000_0000, 3'b011}: alu_operator_o = ALU_SLTU; // Set Lower Than Unsigned\n {7'b000_0000, 3'b100}: alu_operator_o = ALU_XOR; // Xor\n {7'b000_0000, 3'b110}: alu_operator_o = ALU_OR; // Or\n {7'b000_0000, 3'b111}: alu_operator_o = ALU_AND; // And\n {7'b000_0000, 3'b001}: alu_operator_o = ALU_SLL; // Shift Left Logical\n {7'b000_0000, 3'b101}: alu_operator_o = ALU_SRL; // Shift Right Logical\n {7'b010_0000, 3'b101}: alu_operator_o = ALU_SRA; // Shift Right Arithmetic\n\n // RV32B ALU Operations\n {7'b001_0000, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SLO; // slo\n {7'b001_0000, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_SRO; // sro\n {7'b011_0000, 3'b001}: begin\n if (RV32B != RV32BNone) begin\n alu_operator_o = ALU_ROL; // rol\n alu_multicycle_o = 1'b1;\n end\n end\n {7'b011_0000, 3'b101}: begin\n if (RV32B != RV32BNone) begin\n alu_operator_o = ALU_ROR; // ror\n alu_multicycle_o = 1'b1;\n end\n end\n\n {7'b000_0101, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_MIN; // min\n {7'b000_0101, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_MAX; // max\n {7'b000_0101, 3'b110}: if (RV32B != RV32BNone) alu_operator_o = ALU_MINU; // minu\n {7'b000_0101, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_MAXU; // maxu\n\n {7'b000_0100, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACK; // pack\n {7'b010_0100, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACKU; // packu\n {7'b000_0100, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACKH; // packh\n\n {7'b010_0000, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_XNOR; // xnor\n {7'b010_0000, 3'b110}: if (RV32B != RV32BNone) alu_operator_o = ALU_ORN; // orn\n {7'b010_0000, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_ANDN; // andn\n\n // RV32B zbs\n {7'b010_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBCLR; // sbclr\n {7'b001_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBSET; // sbset\n {7'b011_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBINV; // sbinv\n {7'b010_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBEXT; // sbext\n\n // RV32B zbf\n {7'b010_0100, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_BFP; // bfp\n\n // RV32B zbp\n {7'b011_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_GREV; // grev\n {7'b001_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_GORC; // grev\n {7'b000_0100, 3'b001}: if (RV32B == RV32BFull) alu_operator_o = ALU_SHFL; // shfl\n {7'b000_0100, 3'b101}: if (RV32B == RV32BFull) alu_operator_o = ALU_UNSHFL; // unshfl\n\n // RV32B zbc\n {7'b000_0101, 3'b001}: if (RV32B == RV32BFull) alu_operator_o = ALU_CLMUL; // clmul\n {7'b000_0101, 3'b010}: if (RV32B == RV32BFull) alu_operator_o = ALU_CLMULR; // clmulr\n {7'b000_0101, 3'b011}: if (RV32B == RV32BFull) alu_operator_o = ALU_CLMULH; // clmulh\n\n // RV32B zbe\n {7'b010_0100, 3'b110}: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_BDEP; // bdep\n alu_multicycle_o = 1'b1;\n end\n end\n {7'b000_0100, 3'b110}: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_BEXT; // bext\n alu_multicycle_o = 1'b1;\n end\n end\n\n // RV32M instructions, all use the same ALU operation\n {7'b000_0001, 3'b000}: begin // mul\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b100}: begin // div\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b101}: begin // divu\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b110}: begin // rem\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b111}: begin // remu\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n\n default: ;\n endcase\n end\n end\n\n /////////////\n // Special //\n /////////////\n\n OPCODE_MISC_MEM: begin\n unique case (instr_alu[14:12])\n 3'b000: begin\n // FENCE is treated as a NOP since all memory operations are already strictly ordered.\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 end\n 3'b001: begin\n // FENCE.I will flush the IF stage, prefetch buffer and ICache if present.\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_INCR_PC;\n end else begin\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 end\n end\n default: ;\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr_alu[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 end else begin\n // instruction to read/modify CSR\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_alu[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 end\n\n end\n default: ;\n endcase\n end\n\n // do not enable multdiv in case of illegal instruction exceptions\n assign mult_en_o = illegal_insn ? 1'b0 : mult_sel_o;\n assign div_en_o = illegal_insn ? 1'b0 : div_sel_o;\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 rf_we_o = rf_we & ~illegal_reg_rv32e;\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT(IbexRegImmAluOpKnown, (opcode == OPCODE_OP_IMM) |->\n !$isunknown(instr[14:12]))\nendmodule // controller\n", "selected_doc_paths": ["doc/03_reference/instruction_decode_execute.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/register_file.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1087, "lang": "sv", "rtl_files": ["rtl/ibex_decoder.sv"], "spec": "# Behavioral Design Specification: Instruction Decoder (ibex_decoder)\n\n## 1. Overview\n\nThe instruction decoder is a purely combinational module that receives a 32‑bit RISC‑V instruction (in uncompressed form) and produces all control signals required to execute that instruction in a single cycle or, for certain multi‑cycle instructions, over two cycles. It is the central decision‑making block that determines what operation the ALU must perform, which registers to read and write, whether a memory access is needed, whether a CSR access occurs, and whether the instruction is legal.\n\nThe decoder works in close cooperation with the pipeline’s instruction fetch stage, the controller, the ALU, the load‑store unit (LSU), the register file, and the CSR block. It shall produce valid output signals for every possible input instruction, even if that instruction is illegal; in the illegal case, all execution‑related side effects (register writes, memory requests, CSR accesses, jump/branch updates) must be suppressed.\n\nThe decoder supports the RV32I base integer instruction set and the optional extensions RV32M (multiply/divide), RV32B (bit‑manipulation, with three granularity levels: none, balanced, full), and RV32E (embedded, with half the number of registers). It also handles system instructions, fence operations, and compressed instruction legality indication.\n\n## 2. Functional Behavior\n\n### 2.1 Instruction Decoding Flow\n\nFor each incoming instruction, the decoder shall:\n\n1. Determine the opcode (bits [6:0]).\n2. Extract source register addresses (rs1, rs2) and the destination register address (rd).\n3. Extract and sign‑extend the immediate field appropriate to the instruction type (I‑type, S‑type, B‑type, U‑type, J‑type, or zero‑extended for CSR).\n4. Based on the opcode and the function fields, set control signals for:\n - Register file read/write enable and addresses.\n - ALU operation and operand source selection (register, immediate, PC, zero).\n - Immediate selection for ALU operand B.\n - Branch target address selection (using either the ALU or the dedicated branch target ALU, depending on a configuration parameter).\n - Jump / branch trigger and target computation sequencing.\n - Memory request type and size (for load/store).\n - CSR access and operation.\n - Multi‑cycle instruction indicator.\n - Multiplier/divider enable and operation.\n5. Assert an illegal‑instruction flag if the opcode or any combination of function bits is not valid for the configured extensions.\n6. For compressed instructions that failed decoding (external signal `illegal_c_insn`), force the illegal‑instruction flag.\n7. For RV32E configurations, check that all accessed register numbers are within the lower 16 registers; otherwise raise the illegal‑instruction flag.\n\n### 2.2 Opcode Groups and Their Control Signals\n\n#### 2.2.1 Jumps (JAL, JALR)\n\n- **JAL** (jump and link) and **JALR** (jump and link register) shall initiate a jump.\n- The jump target shall be computed using either the main ALU or a dedicated branch‑target ALU, depending on the `BranchTargetALU` parameter.\n- **First cycle**: if `BranchTargetALU` is **not** used, the jump target is computed by the ALU (PC + immediate for JAL, rs1 + immediate for JALR). In this cycle the register‑file write is enabled only when `BranchTargetALU` is used (to store the return address PC+4).\n- **Second cycle**: if the jump target was not computed in the first cycle, the second cycle stores PC+4 into the link register. If `BranchTargetALU` is used, the ALU is free during the first cycle to compute the return address; then the second cycle is not needed.\n- JALR requires rs1 read; JAL does not.\n- A jump is always taken; the decoder shall output the jump‑taken signal synchronously with the first cycle.\n- JALR with a non‑zero funct3 field shall be flagged as illegal.\n\n#### 2.2.2 Branches (BEQ, BNE, BLT, BGE, BLTU, BGEU)\n\n- Branches are conditional; the branch condition is evaluated by the ALU.\n- **First cycle**: the ALU evaluates the condition (operand A = rs1, operand B = rs2, ALU operation selected by funct3). No register write.\n- **Second cycle**: the ALU computes the branch target address (PC + B‑type immediate) if the branch was taken; if not taken, the target is PC+4 (used in secure modes). The branch target may also be computed by the branch‑target ALU if configured, in which case the ALU is only used for the condition.\n- The decoded branch condition must match one of the six valid funct3 encodings; all others are illegal.\n\n#### 2.2.3 Load Instructions (LB, LH, LW, LBU, LHU)\n\n- The base address shall be computed by the ALU: operand A = rs1, operand B = I‑type immediate, ALU operation = add.\n- The data memory request is issued on the same cycle as the address computation.\n- The load size is encoded in bits [13:12]; valid sizes: byte (2’b10), halfword (2’b01), word (2’b00). Illegal if bits [14] is set for word (LWU does not exist in RV32).\n- Sign extension is controlled by bit [14]: 0 = sign‑extend, 1 = zero‑extend. For word loads, sign extension is implicitly zero.\n- Only rs1 is read; rs2 is not required.\n\n#### 2.2.4 Store Instructions (SB, SH, SW)\n\n- The address is computed by the ALU: operand A = rs1, operand B = I‑type immediate (bit [14] = 0) or register rs2 (bit [14] = 1). The ALU operation is add.\n- Data memory write request is issued in the same cycle.\n- The store size is encoded in bits [13:12]; illegal if bit [14] is set (no reserved encodings).\n- Both rs1 (address) and rs2 (data) are read.\n\n#### 2.2.5 ALU Immediate Instructions (LUI, AUIPC, OP-IMM)\n\n- **LUI**: load upper immediate; value = U‑type immediate, written to rd.\n- **AUIPC**: add upper immediate to PC; value = PC + U‑type immediate, written to rd.\n- **OP‑IMM** (register‑immediate ALU): perform ALU operation with operand A = rs1, operand B = I‑type immediate. Supported operations (by funct3):\n - ADDI (000), SLTI (010), SLTIU (011), XORI (100), ORI (110), ANDI (111).\n - SLLI (001), SRLI (101), SRAI (101 with bit30=1) – base RV32I.\n - Additional operations enabled by RV32B extensions (e.g., shift‑ones, bit‑clear, bit‑set, rotate, shuffle, CRC, etc.) – see Section 4.\n- All funct3 values must be valid; otherwise illegal.\n\n#### 2.2.6 Register‑Register ALU Instructions (OP)\n\n- Operand A = rs1, operand B = rs2.\n- Supported operations (by funct7 and funct3) include:\n - ADD, SUB, SLT, SLTU, XOR, OR, AND, SLL, SRL, SRA (RV32I).\n - RV32M: MUL, MULH, MULHSU, MULHU, DIV, DIVU, REM, REMU.\n - RV32B instructions (Zbb, Zbs, Zbp, Zbe, Zbf, Zbc, Zbt, Zb_tmp).\n- For RV32M multiplications and divisions, the ALU operation is set to ADD (the actual computation is performed by the mult/div block). The multiplier/divider enable signals must be asserted only for actually available M‑extension instructions.\n- Any combination not covered by the enabled extensions shall be flagged illegal.\n\n#### 2.2.7 System Instructions (ECALL, EBREAK, MRET, DRET, WFI)\n\n- When funct3 = 000, the instruction is a non‑CSR system instruction, identified by bits [31:20]:\n - 0x000: ECALL (environment call).\n - 0x001: EBREAK (debug breakpoint).\n - 0x302: MRET (machine return).\n - 0x7B2: DRET (debug return).\n - 0x105: WFI (wait for interrupt).\n- All other values are illegal. Additionally, if rs1 or rd are non‑zero, the instruction is illegal.\n- When funct3 ≠ 000, the instruction is a CSR read‑modify‑write, referenced as CSRRS, CSRRC, CSRRSI, CSRRCI, or CSRRW. The decoder shall:\n - Enable CSR access.\n - Set the CSR operation according to funct2 (01: write, 10: set, 11: clear). If funct2 is 00, the operation is illegal.\n - Use rs1 (or the immediate zimm) as the source operand; for CSRRSI/CSRRCI with rs1=0, the operation degrades to read‑only (CSR_OP_READ).\n - Route write data from the CSR read result to the register file.\n - For instructions that use rs1 as an immediate (when bit [14] is set), the ALU operand A is the zero‑extended immediate; otherwise it is rs1.\n - CSR address is encoded in the I‑type immediate.\n\n#### 2.2.8 Memory Fence Instructions (FENCE, FENCE.I)\n\n- **FENCE** (funct3=000): treated as a NOP; no side effects.\n- **FENCE.I** (funct3=001): shall flush the instruction cache (if present) and the instruction prefetch buffer. This is implemented by forcing a jump to the next consecutive PC (PC+4). The jump takes two cycles if the branch‑target ALU is not used, otherwise one cycle. The icache invalidation signal shall be asserted in the first cycle.\n\n#### 2.2.9 Reserved Opcodes\n\nAny opcode not listed above shall be flagged as illegal.\n\n### 2.3 Immediate Generation\n\nThe decoder shall produce five separate sign‑extended immediate values and one zero‑extended immediate from the instruction bits:\n\n| Immediate Type | Derivation | Use |\n|----------------|------------|-----|\n| I‑type | Sign‑extend bits [31:20] | Loads, OP‑IMM, JALR, CSR address |\n| S‑type | Sign‑extend bits [31:25, 11:7] | Store instructions |\n| B‑type | Sign‑extend bits [31,7,30:25,11:8] with LSB zero | Branches |\n| U‑type | Bits [31:12] with lower 12 bits zero | LUI, AUIPC |\n| J‑type | Sign‑extend bits [31,19:12,20,30:21] with LSB zero | JAL |\n| Z‑type (zimm) | Zero‑extend rs1 field | CSR immediate instructions |\n\nAll immediates shall be available as 32‑bit values to subsequent pipeline stages.\n\n### 2.4 Register File Control\n\n- The decoder shall output the addresses of two source registers (rs1, rs2) and one destination register (rd).\n- Register file read enables shall be asserted only when the instruction actually requires the corresponding source register.\n- Register file write enable shall be asserted for any instruction that writes a destination register, except when the instruction is illegal (see 2.6).\n- For RV32E, if any accessed register number (rs1, rs2, rd) has bit 4 set, the instruction shall be treated as illegal and the write enable shall be suppressed.\n\n### 2.5 ALU Control\n\nThe decoder shall select:\n\n- **ALU operation** (add, sub, slt, sltu, xor, or, and, sll, srl, sra, and various bit‑manipulation operations).\n- **Operand A source**: register value (rs1), current PC, immediate, or zero.\n- **Operand B source**: register value (rs2) or immediate.\n- **Immediate mux selects** for the two immediate paths (A and B) that feed the ALU inputs.\n\nFor branch/jump target calculation, separate branch‑target mux selects are provided, allowing the branch‑target ALU (if present) to compute the target address independently from the main ALU.\n\n### 2.6 Multi‑Cycle Instruction Handling\n\nCertain bit‑manipulation instructions (e.g., rotate, ternary operations like cmix/cmov, shuffle, CRC, bit extract/deposit) require two cycles to complete. The decoder shall:\n\n- Indicate `alu_multicycle` for those instructions.\n- For instructions that require a third source register (rs3), the decoder shall assert a signal that is registered and used one cycle later to select rs3 over rs1 for the first source operand. The rs3 address is taken from bits [31:27].\n\nThe decoder itself does not manage the multi‑cycle sequencing; it simply provides the control signals to the pipeline controller, which will stall the stage as needed.\n\n### 2.7 Illegal Instruction Detection\n\nThe decoder shall combine several conditions to assert the illegal‑instruction flag:\n\n1. Any opcode that is not recognized.\n2. Any invalid funct3/funct7 combination for the configured extensions.\n3. Any compressed instruction that was flagged illegal by the decompressor.\n4. Any instruction that accesses a register with number ≥ 16 in RV32E mode.\n5. Any CSR instruction with an invalid funct2.\n6. Any system instruction (funct3=000) with non‑zero rs1 or rd unless the instruction is one of the legal ones.\n7. JALR with funct3 ≠ 0.\n8. Load/store with illegal size encoding.\n\nWhen the illegal flag is set, the decoder shall override all side‑effect‑producing outputs to safe values:\n\n- Register file write enable = 0.\n- Data memory request and write enable = 0.\n- CSR access = 0.\n- Jump/branch control signals = 0.\n- Multiplier/divider enable = 0.\n\nThe illegal‑instruction flag shall be propagated to the controller to trigger an exception.\n\n### 2.8 Data Memory (LSU) Control\n\nFor load instructions, the decoder shall generate:\n\n- Data request (data_req).\n- Sign extension control (data_sign_extension).\n- Data type (size) encoding.\n\nFor store instructions, additionally:\n\n- Write enable (data_we).\n\nFor load‑store operations, the ALU computes the effective address. No LSU transaction shall be generated for illegal instructions.\n\n### 2.9 CSR Control\n\n- CSR access enable and operation shall be generated only for CSR instructions (funct3 ≠ 000 in SYSTEM opcode).\n- For instructions that use the rs1 immediate (bit [14] = 1), the CSR operation shall be read‑only if the immediate is zero.\n- The decoder shall not itself validate privilege or CSR address range; that is done by the CSR block.\n\n## 3. Parameter Dependencies\n\n### 3.1 RV32E (Embedded)\n\nWhen enabled, the decoder must check all register addresses against the upper 16 registers (bit 4). Any instruction that would read or write a register with bit 4 set shall be treated as illegal, regardless of the instruction type.\n\n### 3.2 RV32M (Multiply/Divide)\n\n- If RV32M = RV32MNone, all multiply/divide instructions shall be illegal.\n- If RV32M is one of the other three values (SingleCycle, Fast, Slow), the decoder shall generate the appropriate multiplier/divider operation (MD_OP_MULL/MULH/DIV/REM) and signed‑mode indicator.\n- The mu​ltiplication/division enable signals shall only be asserted when the instruction is legal.\n\n### 3.3 RV32B (Bit‑Manipulation)\n\n- If RV32B = RV32BNone, all bit‑manipulation instructions shall be illegal, and the ALU shall fall back to base RV32I ops where possible (e.g., SLLI, SRLI, SRAI remain).\n- If RV32B = RV32BBalanced, only a subset (Zbb, Zbs, Zbf, Zbc? Actually Zbf is balanced; Zbc full? The spec says Balanced/Full for Zbb, Zbs, Zbf, Zbt, Zb_tmp, and Full for Zbp, Zbe, Zbc, Zbr.) The exact subset is defined by the decoder’s case statements. The decoder shall correctly map each funct7/funct3 combination to the ALU operation only if the corresponding instruction is included in the chosen version; otherwise it shall flag illegal.\n- If RV32B = RV32BFull, all listed bit‑manipulation instructions are legal.\n\n### 3.4 BranchTargetALU\n\n- When this parameter is set, a dedicated adder is available for computing branch/jump targets. The decoder shall then:\n - Use separate branch‑target mux selects instead of the main ALU for target computation.\n - Allow the main ALU to be used for other purposes (e.g., computing the return address in the same cycle as a jump target).\n - For branches, use the branch‑taken decision input to select between taken and not‑taken targets.\n- When not set, all target computations must use the main ALU over two cycles.\n\n## 4. Special Cases\n\n### 4.1 FENCE.I\n\nThe decoder shall translate FENCE.I into an unconditional jump to PC+4. This jump has the same sequencing as a JAL targeting x0. The icache invalidation signal shall be asserted in the first cycle.\n\n### 4.2 CSR Immediate (zimm_rs1_type)\n\nFor CSR instructions with bit [14] = 1, the immediate is the zero‑extended rs1 field. This immediate is used as the ALU operand A source.\n\n### 4.3 Use of rs3 for Ternary Instructions\n\nInstructions such as cmix, cmov, fsl, fsr, and certain shift‑like ops use a third operand (rs3). The decoder shall output a signal indicating that rs3 will be needed in the next cycle. This signal is registered externally and controls the read address mux for the first source operand (rs3 over rs1) in the second cycle.\n\n## 5. Reset and Clock\n\nThe decoder is purely combinational and does not contain any state. The clock and reset inputs are used only for simulation assertions; no functional dependency on them exists.\n\n## 6. Summary of Outputs\n\nThe decoder shall produce the following groups of signals (described functionally):\n\n- **Immediate values**: I‑type, S‑type, B‑type, U‑type, J‑type, Z‑type.\n- **Register file control**: read addresses (two), write address, read enables, write enable.\n- **ALU control**: operation, operand A/B mux selects, immediate mux selects, multi‑cycle indicator.\n- **Branch/jump control**: jump‑in‑decode, jump‑set, branch‑in‑decode, plus branch‑target mux selects.\n- **Memory control**: data request, write enable, data type (size), sign extension.\n- **CSR control**: access enable, operation.\n- **Multiplier/divider control**: enable and static sel signals, operation, signed mode.\n- **Cache control**: icache invalidation.\n- **Exception control**: illegal instruction flag, trap instruction flags (ebreak, ecall, mret, dret, wfi).\n\nAll outputs must be determined purely by the current instruction and the configuration parameters; no history is retained.", "commit_id": "e145a49b321cbcf41d04b3fd7c29f40f521b6e52", "timestamp": "2020-08-21T10:09:13+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "23e21c949497f92fb450ad407cd525cec0d513d2", "pr_title": "[rtl] Fix FENCE comment in decoder", "pr_body": "- Clarify FENCE treatment rationale\r\n- Update comment around ICache flushing\r\n- Fixes #1048\r\n\r\nSigned-off-by: Tom Roberts ", "issue_title": "Fix comment or code in decoder regarding FENCE behavior", "issue_body": "I just stumbled across this comment in the decoder:\r\n\r\nhttps://github.com/lowRISC/ibex/blob/94d505716870ddf240d0896021871176d6336579/rtl/ibex_decoder.sv#L538-L540\r\n\r\n@tomroberts-lowrisc Can you have a look at that behavior and (probably) update the comment to what we have today?", "commit_message": "[rtl] Fix FENCE comment in decoder\n\n- Clarify FENCE treatment rationale\n- Update comment around ICache flushing\n- Fixes #1048\n\nSigned-off-by: Tom Roberts ", "fix_patch": "diff --git a/rtl/ibex_decoder.sv b/rtl/ibex_decoder.sv\nindex 309ba04d11..f55b719cec 100644\n--- a/rtl/ibex_decoder.sv\n+++ b/rtl/ibex_decoder.sv\n@@ -535,11 +535,9 @@ module ibex_decoder #(\n /////////////\n \n OPCODE_MISC_MEM: begin\n- // For now, treat the FENCE (funct3 == 000) instruction as a NOP. This may not be correct\n- // in a system with caches and should be revisited.\n- // FENCE.I will flush the IF stage and prefetch buffer (or ICache) but nothing else.\n unique case (instr[14:12])\n 3'b000: begin\n+ // FENCE is treated as a NOP since all memory operations are already strictly ordered.\n rf_we = 1'b0;\n end\n 3'b001: begin\n@@ -1078,16 +1076,15 @@ module ibex_decoder #(\n /////////////\n \n OPCODE_MISC_MEM: begin\n- // For now, treat the FENCE (funct3 == 000) instruction as a NOP. This may not be correct\n- // in a system with caches and should be revisited.\n- // FENCE.I will flush the IF stage and prefetch buffer but nothing else.\n unique case (instr_alu[14:12])\n 3'b000: begin\n+ // FENCE is treated as a NOP since all memory operations are already strictly ordered.\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 end\n 3'b001: begin\n+ // FENCE.I will flush the IF stage, prefetch buffer and ICache if present.\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_INCR_PC;\n", "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 * Instruction decoder\n *\n * This module is fully combinatorial, clock and reset are used for\n * assertions only.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_decoder #(\n parameter bit RV32E = 0,\n parameter ibex_pkg::rv32m_e RV32M = ibex_pkg::RV32MFast,\n parameter ibex_pkg::rv32b_e RV32B = ibex_pkg::RV32BNone,\n parameter bit BranchTargetALU = 0\n) (\n input logic clk_i,\n input logic rst_ni,\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 input logic branch_taken_i, // registered branch decision\n output logic icache_inval_o,\n\n // from IF-ID pipeline register\n input logic instr_first_cycle_i, // instruction read is in its first cycle\n input logic [31:0] instr_rdata_i, // instruction read from memory/cache\n input logic [31:0] instr_rdata_alu_i, // instruction read from memory/cache\n // replicated to ease fan-out)\n\n input logic illegal_c_insn_i, // compressed instruction decode failed\n\n // immediates\n output ibex_pkg::imm_a_sel_e imm_a_mux_sel_o, // immediate selection for operand a\n output ibex_pkg::imm_b_sel_e imm_b_mux_sel_o, // immediate selection for operand b\n output ibex_pkg::op_a_sel_e bt_a_mux_sel_o, // branch target selection operand a\n output ibex_pkg::imm_b_sel_e bt_b_mux_sel_o, // branch target selection 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_pkg::rf_wd_sel_e rf_wdata_sel_o, // RF write data selection\n output logic rf_we_o, // write enable for regfile\n output logic [4:0] rf_raddr_a_o,\n output logic [4:0] rf_raddr_b_o,\n output logic [4:0] rf_waddr_o,\n output logic rf_ren_a_o, // Instruction reads from RF addr A\n output logic rf_ren_b_o, // Instruction reads from RF addr B\n\n // ALU\n output ibex_pkg::alu_op_e alu_operator_o, // ALU operation selection\n output ibex_pkg::op_a_sel_e alu_op_a_mux_sel_o, // operand a selection: reg value, PC,\n // immediate or zero\n output ibex_pkg::op_b_sel_e alu_op_b_mux_sel_o, // operand b selection: reg value or\n // immediate\n output logic alu_multicycle_o, // ternary bitmanip instruction\n\n // MULT & DIV\n output logic mult_en_o, // perform integer multiplication\n output logic div_en_o, // perform integer division or remainder\n output logic mult_sel_o, // as above but static, for data muxes\n output logic div_sel_o, // as above but static, for data muxes\n\n output ibex_pkg::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_pkg::csr_op_e csr_op_o, // operation to perform on 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\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_pkg::*;\n\n logic illegal_insn;\n logic illegal_reg_rv32e;\n logic csr_illegal;\n logic rf_we;\n\n logic [31:0] instr;\n logic [31:0] instr_alu;\n // Source/Destination register instruction index\n logic [4:0] instr_rs1;\n logic [4:0] instr_rs2;\n logic [4:0] instr_rs3;\n logic [4:0] instr_rd;\n\n logic use_rs3_d;\n logic use_rs3_q;\n\n csr_op_e csr_op;\n\n opcode_e opcode;\n opcode_e opcode_alu;\n\n // To help timing the flops containing the current instruction are replicated to reduce fan-out.\n // instr_alu is used to determine the ALU control logic and associated operand/imm select signals\n // as the ALU is often on the more critical timing paths. instr is used for everything else.\n assign instr = instr_rdata_i;\n assign instr_alu = instr_rdata_alu_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_rs1 }; // rs1\n\n // the use of rs3 is known one cycle ahead.\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n use_rs3_q <= 1'b0;\n end else begin\n use_rs3_q <= use_rs3_d;\n end\n end\n\n // source registers\n assign instr_rs1 = instr[19:15];\n assign instr_rs2 = instr[24:20];\n assign instr_rs3 = instr[31:27];\n assign rf_raddr_a_o = (use_rs3_q & ~instr_first_cycle_i) ? instr_rs3 : instr_rs1; // rs3 / rs1\n assign rf_raddr_b_o = instr_rs2; // rs2\n\n // destination register\n assign instr_rd = instr[11:7];\n assign rf_waddr_o = instr_rd; // rd\n\n ////////////////////\n // Register check //\n ////////////////////\n if (RV32E) begin : gen_rv32e_reg_check_active\n assign illegal_reg_rv32e = ((rf_raddr_a_o[4] & (alu_op_a_mux_sel_o == OP_A_REG_A)) |\n (rf_raddr_b_o[4] & (alu_op_b_mux_sel_o == OP_B_REG_B)) |\n (rf_waddr_o[4] & rf_we));\n end else begin : gen_rv32e_reg_check_inactive\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_rs1 == '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 icache_inval_o = 1'b0;\n\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n\n rf_wdata_sel_o = RF_WD_EX;\n rf_we = 1'b0;\n rf_ren_a_o = 1'b0;\n rf_ren_b_o = 1'b0;\n\n csr_access_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_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\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n jump_in_dec_o = 1'b1;\n\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n if (instr[14:12] != 3'b0) begin\n illegal_insn = 1'b1;\n end\n\n rf_ren_a_o = 1'b1;\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,\n 3'b001,\n 3'b100,\n 3'b101,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n default: illegal_insn = 1'b1;\n endcase\n\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n end\n\n ////////////////\n // Load/store //\n ////////////////\n\n OPCODE_STORE: begin\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n data_req_o = 1'b1;\n data_we_o = 1'b1;\n\n if (instr[14]) begin\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: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_LOAD: begin\n rf_ren_a_o = 1'b1;\n data_req_o = 1'b1;\n data_type_o = 2'b00;\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(u)\n 2'b01: data_type_o = 2'b01; // lh(u)\n 2'b10: begin\n data_type_o = 2'b00; // lw\n if (instr[14]) begin\n illegal_insn = 1'b1; // lwu does not exist\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n /////////\n // ALU //\n /////////\n\n OPCODE_LUI: begin // Load Upper Immediate\n rf_we = 1'b1;\n end\n\n OPCODE_AUIPC: begin // Add Upper Immediate to PC\n rf_we = 1'b1;\n end\n\n OPCODE_OP_IMM: begin // Register-Immediate ALU Operations\n rf_ren_a_o = 1'b1;\n rf_we = 1'b1;\n\n unique case (instr[14:12])\n 3'b000,\n 3'b010,\n 3'b011,\n 3'b100,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n\n 3'b001: begin\n unique case (instr[31:27])\n 5'b0_0000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // slli\n 5'b0_0100, // sloi\n 5'b0_1001, // sbclri\n 5'b0_0101, // sbseti\n 5'b0_1101: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sbinvi\n 5'b0_0001: if (instr[26] == 1'b0) begin\n illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // shfl\n end else begin\n illegal_insn = 1'b1;\n end\n 5'b0_1100: begin\n unique case(instr[26:20])\n 7'b000_0000, // clz\n 7'b000_0001, // ctz\n 7'b000_0010, // pcnt\n 7'b000_0100, // sext.b\n 7'b000_0101: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sext.h\n 7'b001_0000, // crc32.b\n 7'b001_0001, // crc32.h\n 7'b001_0010, // crc32.w\n 7'b001_1000, // crc32c.b\n 7'b001_1001, // crc32c.h\n 7'b001_1010: illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // crc32c.w\n\n default: illegal_insn = 1'b1;\n endcase\n end\n default : illegal_insn = 1'b1;\n endcase\n end\n\n 3'b101: begin\n if (instr[26]) begin\n illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // fsri\n end else begin\n unique case (instr[31:27])\n 5'b0_0000, // srli\n 5'b0_1000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // srai\n\n 5'b0_0100, // sroi\n 5'b0_1100, // rori\n 5'b0_1001: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sbexti\n\n 5'b0_1101: begin\n if ((RV32B == RV32BFull)) begin\n illegal_insn = 1'b0; // grevi\n end else begin\n unique case (instr[24:20])\n 5'b11111, // rev\n 5'b11000: illegal_insn = (RV32B == RV32BBalanced) ? 1'b0 : 1'b1; // rev8\n\n default: illegal_insn = 1'b1;\n endcase\n end\n end\n 5'b0_0101: begin\n if ((RV32B == RV32BFull)) begin\n illegal_insn = 1'b0; // gorci\n end else if (instr[24:20] == 5'b00111) begin\n illegal_insn = (RV32B == RV32BBalanced) ? 1'b0 : 1'b1; // orc.b\n end\n end\n 5'b0_0001: begin\n if (instr[26] == 1'b0) begin\n illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // unshfl\n end else begin\n illegal_insn = 1'b1;\n end\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_OP: begin // Register-Register ALU operation\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n rf_we = 1'b1;\n if ({instr[26], instr[13:12]} == {1'b1, 2'b01}) begin\n illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // cmix / cmov / fsl / fsr\n end else begin\n unique case ({instr[31:25], instr[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000},\n {7'b010_0000, 3'b000},\n {7'b000_0000, 3'b010},\n {7'b000_0000, 3'b011},\n {7'b000_0000, 3'b100},\n {7'b000_0000, 3'b110},\n {7'b000_0000, 3'b111},\n {7'b000_0000, 3'b001},\n {7'b000_0000, 3'b101},\n {7'b010_0000, 3'b101}: illegal_insn = 1'b0;\n\n // RV32B zbb\n {7'b010_0000, 3'b111}, // andn\n {7'b010_0000, 3'b110}, // orn\n {7'b010_0000, 3'b100}, // xnor\n {7'b001_0000, 3'b001}, // slo\n {7'b001_0000, 3'b101}, // sro\n {7'b011_0000, 3'b001}, // rol\n {7'b011_0000, 3'b101}, // ror\n {7'b000_0101, 3'b100}, // min\n {7'b000_0101, 3'b101}, // max\n {7'b000_0101, 3'b110}, // minu\n {7'b000_0101, 3'b111}, // maxu\n {7'b000_0100, 3'b100}, // pack\n {7'b010_0100, 3'b100}, // packu\n {7'b000_0100, 3'b111}, // packh\n // RV32B zbs\n {7'b010_0100, 3'b001}, // sbclr\n {7'b001_0100, 3'b001}, // sbset\n {7'b011_0100, 3'b001}, // sbinv\n {7'b010_0100, 3'b101}, // sbext\n // RV32B zbf\n {7'b010_0100, 3'b111}: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // bfp\n // RV32B zbe\n {7'b010_0100, 3'b110}, // bdep\n {7'b000_0100, 3'b110}, // bext\n // RV32B zbp\n {7'b011_0100, 3'b101}, // grev\n {7'b001_0100, 3'b101}, // gorc\n {7'b000_0100, 3'b001}, // shfl\n {7'b000_0100, 3'b101}, // unshfl\n // RV32B zbc\n {7'b000_0101, 3'b001}, // clmul\n {7'b000_0101, 3'b010}, // clmulr\n {7'b000_0101, 3'b011}: illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // clmulh\n\n // RV32M instructions\n {7'b000_0001, 3'b000}: begin // mul\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b01;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b100}: begin // div\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b101}: begin // divu\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b110}: begin // rem\n multdiv_operator_o = MD_OP_REM;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b111}: begin // remu\n multdiv_operator_o = MD_OP_REM;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = (RV32M == RV32MNone) ? 1'b1 : 1'b0;\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 unique case (instr[14:12])\n 3'b000: begin\n // FENCE is treated as a NOP since all memory operations are already strictly ordered.\n rf_we = 1'b0;\n end\n 3'b001: begin\n // FENCE.I is implemented as a jump to the next PC, this gives the required flushing\n // behaviour (iside prefetch buffer flushed and response to any outstanding iside\n // requests will be ignored).\n // If present, the ICache will also be flushed.\n jump_in_dec_o = 1'b1;\n\n rf_we = 1'b0;\n\n if (instr_first_cycle_i) begin\n jump_set_o = 1'b1;\n icache_inval_o = 1'b1;\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr[14:12] == 3'b000) begin\n // non CSR related SYSTEM instructions\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_rs1 != 5'b0 || instr_rd != 5'b0) 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 rf_wdata_sel_o = RF_WD_CSR;\n rf_we = 1'b1;\n\n if (~instr[14]) begin\n rf_ren_a_o = 1'b1;\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 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, PC\n // NOTE: instructions can also be detected to be illegal inside the CSRs (upon accesses with\n // insufficient privileges), or when accessing non-available registers in RV32E,\n // these cases are not handled here\n if (illegal_insn) begin\n rf_we = 1'b0;\n data_req_o = 1'b0;\n data_we_o = 1'b0;\n jump_in_dec_o = 1'b0;\n jump_set_o = 1'b0;\n branch_in_dec_o = 1'b0;\n csr_access_o = 1'b0;\n end\n end\n\n /////////////////////////////\n // Decoder for ALU control //\n /////////////////////////////\n\n always_comb begin\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 bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_I;\n\n\n opcode_alu = opcode_e'(instr_alu[6:0]);\n\n use_rs3_d = 1'b0;\n alu_multicycle_o = 1'b0;\n mult_sel_o = 1'b0;\n div_sel_o = 1'b0;\n\n unique case (opcode_alu)\n\n ///////////\n // Jumps //\n ///////////\n\n OPCODE_JAL: begin // Jump and Link\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_J;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_REG_A;\n bt_b_mux_sel_o = IMM_B_I;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_BRANCH: begin // Branch\n // Check branch condition selection\n unique case (instr_alu[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: ;\n endcase\n\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n // Not-taken branch will jump to next instruction (used in secure mode)\n bt_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n end\n\n // Without branch target ALU, a branch is a two-stage operation using the Main ALU in both\n // stages\n if (instr_first_cycle_i) begin\n // First evaluate the 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 // Then calculate jump target\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n // Not-taken branch will jump to next instruction (used in secure mode)\n imm_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n alu_operator_o = ALU_ADD;\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 alu_operator_o = ALU_ADD;\n\n if (!instr_alu[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\n end\n\n OPCODE_LOAD: begin\n alu_op_a_mux_sel_o = OP_A_REG_A;\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 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 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 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\n unique case (instr_alu[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 if (RV32B != RV32BNone) begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n 5'b0_0100: alu_operator_o = ALU_SLO; // Shift Left Ones by Immediate\n 5'b0_1001: alu_operator_o = ALU_SBCLR; // Clear bit specified by immediate\n 5'b0_0101: alu_operator_o = ALU_SBSET; // Set bit specified by immediate\n 5'b0_1101: alu_operator_o = ALU_SBINV; // Invert bit specified by immediate.\n // Shuffle with Immediate Control Value\n 5'b0_0001: if (instr_alu[26] == 0) alu_operator_o = ALU_SHFL;\n 5'b0_1100: begin\n unique case (instr_alu[26:20])\n 7'b000_0000: alu_operator_o = ALU_CLZ; // clz\n 7'b000_0001: alu_operator_o = ALU_CTZ; // ctz\n 7'b000_0010: alu_operator_o = ALU_PCNT; // pcnt\n 7'b000_0100: alu_operator_o = ALU_SEXTB; // sext.b\n 7'b000_0101: alu_operator_o = ALU_SEXTH; // sext.h\n 7'b001_0000: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_B; // crc32.b\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_0001: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_H; // crc32.h\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_0010: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_W; // crc32.w\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1000: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_B; // crc32c.b\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1001: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_H; // crc32c.h\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1010: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_W; // crc32c.w\n alu_multicycle_o = 1'b1;\n end\n end\n default: ;\n endcase\n end\n\n default: ;\n endcase\n end else begin\n alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n end\n end\n\n 3'b101: begin\n if (RV32B != RV32BNone) begin\n if (instr_alu[26] == 1'b1) begin\n alu_operator_o = ALU_FSR;\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end else begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n 5'b0_1000: alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n 5'b0_0100: alu_operator_o = ALU_SRO; // Shift Right Ones by Immediate\n 5'b0_1001: alu_operator_o = ALU_SBEXT; // Extract bit specified by immediate.\n 5'b0_1100: begin\n alu_operator_o = ALU_ROR; // Rotate Right by Immediate\n alu_multicycle_o = 1'b1;\n end\n 5'b0_1101: alu_operator_o = ALU_GREV; // General Reverse with Imm Control Val\n 5'b0_0101: alu_operator_o = ALU_GORC; // General Or-combine with Imm Control Val\n // Unshuffle with Immediate Control Value\n 5'b0_0001: begin\n if (RV32B == RV32BFull) begin\n if (instr_alu[26] == 1'b0) alu_operator_o = ALU_UNSHFL;\n end\n end\n default: ;\n endcase\n end\n\n end else begin\n if (instr_alu[31:27] == 5'b0_0000) begin\n alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n end else if (instr_alu[31:27] == 5'b0_1000) begin\n alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n end\n end\n end\n\n default: ;\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\n if (instr_alu[26]) begin\n if (RV32B != RV32BNone) begin\n unique case ({instr_alu[26:25], instr_alu[14:12]})\n {2'b11, 3'b001}: begin\n alu_operator_o = ALU_CMIX; // cmix\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b11, 3'b101}: begin\n alu_operator_o = ALU_CMOV; // cmov\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b10, 3'b001}: begin\n alu_operator_o = ALU_FSL; // fsl\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b10, 3'b101}: begin\n alu_operator_o = ALU_FSR; // fsr\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n default: ;\n endcase\n end\n end else begin\n unique case ({instr_alu[31:25], instr_alu[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000}: alu_operator_o = ALU_ADD; // Add\n {7'b010_0000, 3'b000}: alu_operator_o = ALU_SUB; // Sub\n {7'b000_0000, 3'b010}: alu_operator_o = ALU_SLT; // Set Lower Than\n {7'b000_0000, 3'b011}: alu_operator_o = ALU_SLTU; // Set Lower Than Unsigned\n {7'b000_0000, 3'b100}: alu_operator_o = ALU_XOR; // Xor\n {7'b000_0000, 3'b110}: alu_operator_o = ALU_OR; // Or\n {7'b000_0000, 3'b111}: alu_operator_o = ALU_AND; // And\n {7'b000_0000, 3'b001}: alu_operator_o = ALU_SLL; // Shift Left Logical\n {7'b000_0000, 3'b101}: alu_operator_o = ALU_SRL; // Shift Right Logical\n {7'b010_0000, 3'b101}: alu_operator_o = ALU_SRA; // Shift Right Arithmetic\n\n // RV32B ALU Operations\n {7'b001_0000, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SLO; // slo\n {7'b001_0000, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_SRO; // sro\n {7'b011_0000, 3'b001}: begin\n if (RV32B != RV32BNone) begin\n alu_operator_o = ALU_ROL; // rol\n alu_multicycle_o = 1'b1;\n end\n end\n {7'b011_0000, 3'b101}: begin\n if (RV32B != RV32BNone) begin\n alu_operator_o = ALU_ROR; // ror\n alu_multicycle_o = 1'b1;\n end\n end\n\n {7'b000_0101, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_MIN; // min\n {7'b000_0101, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_MAX; // max\n {7'b000_0101, 3'b110}: if (RV32B != RV32BNone) alu_operator_o = ALU_MINU; // minu\n {7'b000_0101, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_MAXU; // maxu\n\n {7'b000_0100, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACK; // pack\n {7'b010_0100, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACKU; // packu\n {7'b000_0100, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACKH; // packh\n\n {7'b010_0000, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_XNOR; // xnor\n {7'b010_0000, 3'b110}: if (RV32B != RV32BNone) alu_operator_o = ALU_ORN; // orn\n {7'b010_0000, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_ANDN; // andn\n\n // RV32B zbs\n {7'b010_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBCLR; // sbclr\n {7'b001_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBSET; // sbset\n {7'b011_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBINV; // sbinv\n {7'b010_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBEXT; // sbext\n\n // RV32B zbf\n {7'b010_0100, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_BFP; // bfp\n\n // RV32B zbp\n {7'b011_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_GREV; // grev\n {7'b001_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_GORC; // grev\n {7'b000_0100, 3'b001}: if (RV32B == RV32BFull) alu_operator_o = ALU_SHFL; // shfl\n {7'b000_0100, 3'b101}: if (RV32B == RV32BFull) alu_operator_o = ALU_UNSHFL; // unshfl\n\n // RV32B zbc\n {7'b000_0101, 3'b001}: if (RV32B == RV32BFull) alu_operator_o = ALU_CLMUL; // clmul\n {7'b000_0101, 3'b010}: if (RV32B == RV32BFull) alu_operator_o = ALU_CLMULR; // clmulr\n {7'b000_0101, 3'b011}: if (RV32B == RV32BFull) alu_operator_o = ALU_CLMULH; // clmulh\n\n // RV32B zbe\n {7'b010_0100, 3'b110}: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_BDEP; // bdep\n alu_multicycle_o = 1'b1;\n end\n end\n {7'b000_0100, 3'b110}: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_BEXT; // bext\n alu_multicycle_o = 1'b1;\n end\n end\n\n // RV32M instructions, all use the same ALU operation\n {7'b000_0001, 3'b000}: begin // mul\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n alu_operator_o = ALU_ADD;\n mult_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b100}: begin // div\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b101}: begin // divu\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b110}: begin // rem\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b111}: begin // remu\n alu_operator_o = ALU_ADD;\n div_sel_o = (RV32M == RV32MNone) ? 1'b0 : 1'b1;\n end\n\n default: ;\n endcase\n end\n end\n\n /////////////\n // Special //\n /////////////\n\n OPCODE_MISC_MEM: begin\n unique case (instr_alu[14:12])\n 3'b000: begin\n // FENCE is treated as a NOP since all memory operations are already strictly ordered.\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 end\n 3'b001: begin\n // FENCE.I will flush the IF stage, prefetch buffer and ICache if present.\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_INCR_PC;\n end else begin\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 end\n end\n default: ;\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr_alu[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 end else begin\n // instruction to read/modify CSR\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_alu[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 end\n\n end\n default: ;\n endcase\n end\n\n // do not enable multdiv in case of illegal instruction exceptions\n assign mult_en_o = illegal_insn ? 1'b0 : mult_sel_o;\n assign div_en_o = illegal_insn ? 1'b0 : div_sel_o;\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 rf_we_o = rf_we & ~illegal_reg_rv32e;\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT(IbexRegImmAluOpKnown, (opcode == OPCODE_OP_IMM) |->\n !$isunknown(instr[14:12]))\nendmodule // controller\n", "selected_doc_paths": ["doc/instruction_decode_execute.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1136, "lang": "sv", "rtl_files": ["rtl/ibex_cs_registers.sv"], "spec": "# Behavioral Design Specification: Ibex CSR Register File\n\n## 1. Overview\n\nThe CSR register file implements all Control and Status Registers (CSRs) defined in the RISC-V Privileged Specification version 1.11, along with additional custom CSRs for CPU control and security. It manages machine-level interrupt and exception handling, privilege level transitions, debug functionality, physical memory protection (PMP), and performance counters.\n\nThe module shall interface with the processor pipeline to accept CSR read/write requests, generate trap-vector addresses, and provide status signals to other units (e.g., privilege mode, interrupt pending). It shall also capture program counters during exceptions and restore them upon return.\n\n## 2. CSR Access\n\n### 2.1 Read/Write Operations\n\n- The module shall decode an incoming CSR address and operation type (read, write, set, clear).\n- For write-type operations (write, set, clear), the module shall compute the effective write data as follows:\n - **Write**: the operand data is written directly.\n - **Set**: the final value equals the current value bitwise ORed with the operand.\n - **Clear**: the final value equals the current value bitwise ANDed with the complement of the operand.\n- The module shall perform read-modify-write atomically for set/clear operations.\n- The module shall output the read data for the addressed CSR on the same cycle as the access request.\n- A write shall only be performed when the operation is a write type and the access is not illegal (see below).\n\n### 2.2 Access Protection and Illegal CSR Detection\n\n- The module shall generate an `illegal_csr_insn` error if any of the following conditions hold:\n - The addressed CSR does not exist (including reserved addresses).\n - The current privilege mode is lower than the privilege level encoded in the CSR address bits (bits [9:8]).\n - The operation is a write to a read-only CSR (identified by the two most significant address bits being 2'b11).\n- When an illegal access is detected, the module shall not update any CSR and shall assert the illegal instruction indication to the pipeline.\n\n### 2.3 Misaligned and Reserved Addresses\n\n- The module shall treat any access to an unimplemented or reserved CSR address as illegal (read returns zero, write ignored, `illegal_csr_insn` asserted).\n- The module shall ignore writes to all reserved fields within CSRs; reserved fields must always read as zero.\n\n## 3. Privilege Level Management\n\nThe module shall maintain the current privilege level of the hart (Machine Mode or User Mode). Initial privilege after reset is Machine Mode.\n\n- On any exception (interrupt, trap, or debug entry), the privilege level shall transition to Machine Mode.\n- On execution of an MRET instruction, the privilege level shall be restored from the `mstatus.MPP` field.\n- On execution of a DRET instruction, the privilege level shall be restored from the `dcsr.prv` field.\n- The module shall output the current privilege level to the decoder, the instruction fetch unit, and the load-store unit.\n- For load/store operations, the module shall support the `mstatus.MPRV` feature: when `MPRV` is set, the privilege level used for address checking (e.g., PMP) shall be taken from `mstatus.MPP` instead of the current privilege level.\n\n## 4. Interrupts and Exceptions\n\n### 4.1 Interrupt Controllers\n\n- The module shall combine incoming interrupt requests (`irq_software`, `irq_timer`, `irq_external`, `irq_fast[14:0]`) with the corresponding enable bits in the `mie` CSR to produce a set of qualified interrupt requests.\n- An interrupt is considered pending if its input signal is high *and* the corresponding `mie` bit is set.\n- The module shall output the aggregated interrupt pending signal as a single bit (any interrupt pending) and a qualified interrupt vector (mip & mie) to the interrupt controller.\n- The global interrupt enable (`mstatus.MIE`) shall be respected: interrupts are only taken when `MIE` = 1, unless the core is in Debug Mode.\n\n### 4.2 Exception/Trap Entry\n\nWhen the pipeline signals an exception (including interrupts), the module shall perform the following atomically:\n\n1. **Save program counter**: The exception program counter shall be saved into `mepc` (for machine-level exceptions) or `depc` (for debug-related events). The source PC is determined by the pipeline stage that encountered the exception:\n - IF stage: current instruction address.\n - ID stage: address of the instruction being decoded.\n - WB stage: address of the instruction that completed.\n The saved PC shall be aligned to 16-bit (i.e., bit [0] forced to zero in the CSR).\n\n2. **Save exception cause**: The exception cause code (including interrupt bit) shall be written to `mcause` (or to `dcsr.cause` for debug events).\n\n3. **Save trap value**: The trap value (`mtval`) shall be updated with the address of the faulting memory transaction (for load/store faults) or the instruction word (for illegal instruction). For all other exceptions, `mtval` shall be set to zero.\n\n4. **Save privilege state and disable interrupts**:\n - `mstatus.MPIE` shall be set to the previous value of `mstatus.MIE`.\n - `mstatus.MPP` shall be set to the current privilege level before the exception.\n - `mstatus.MIE` shall be cleared (0), disabling further interrupts (except non-maskable interrupts during NMI handling).\n - The privilege level shall transition to Machine Mode.\n\n5. **Backup for recoverable NMI**: The module shall additionally copy `mstatus.MPIE`, `mstatus.MPP`, `mepc`, and `mcause` into dedicated non-standard shadow registers (`mstack`) to enable recovery from an NMI that occurs during exception handling. These shadow registers are not software-accessible.\n\n### 4.3 Exception/Return Operations (MRET, DRET)\n\n- **MRET**:\n - Restore `mstatus.MIE` from `mstatus.MPIE`.\n - Restore privilege level from `mstatus.MPP`.\n - Set `mstatus.MPIE` to 1 (as per spec).\n - Set `mstatus.MPP` to User Mode.\n - If the processor is in NMI mode, the restore shall instead use the values from the shadow `mstack` CSRs (`mstack.mpie`, `mstack.mpp`, `mstack_epc`, `mstack_cause`) and then clear NMI mode.\n\n- **DRET**:\n - Restore privilege level from `dcsr.prv`.\n\n### 4.4 Non-Maskable Interrupt (NMI)\n\n- The module shall support a non-maskable interrupt (NMI) that is always enabled, regardless of `mstatus.MIE` or `mie`.\n- The NMI is not visible in the `mip` CSR.\n- When an NMI occurs:\n - The core shall enter Machine Mode.\n - The cause shall be set to interrupt ID 31.\n - All interrupts (including NMI) shall be ignored while handling the NMI (nested NMIs not supported).\n - The recovery shadow registers (`mstack`) shall capture the state that existed before the NMI, allowing the core to recover the original exception handler state after the NMI is serviced.\n\n### 4.5 Priority and Vectored Mode\n\n- Interrupts shall be prioritized according to the RISC-V Privileged Spec: highest ID first, except timer interrupts (ID 7) which have the lowest priority.\n- The module shall operate in vectored mode: the trap handler base address is taken from `mtvec` bits [31:2] (aligned to 256 bytes), and the vector offset is 4 × interrupt ID. For exceptions (non-interrupt traps), the offset is zero.\n- The `mtvec.MODE` field shall be hard-wired to 2'b01 (vectored).\n\n## 5. Debug Support\n\n### 5.1 Debug Registers\n\n- The module shall provide the following debug-only CSRs:\n - `dcsr` (Debug Control and Status)\n - `dpc` (Debug PC)\n - `dscratch0`, `dscratch1` (scratch registers)\n- All debug CSRs shall be accessible only in Debug Mode. Any access from non-debug mode shall cause an illegal instruction exception.\n- `dcsr` fields:\n - `xdebugver` (read-only): always returns 4 (external spec-compliant debug support).\n - `ebreakm`, `ebreaku` (RW): control whether EBREAK in M-Mode/U-Mode enters Debug Mode or behaves as per Privileged Spec.\n - `step` (RW): when set, the core shall execute a single instruction and then re-enter Debug Mode.\n - `cause` (read-only): set by hardware on entry to Debug Mode (1=EBREAK, 2=trigger, 3=halt, 4=step).\n - `prv` (WARL): privilege level when Debug Mode was entered. Writes support transitions to M-Mode or U-Mode only.\n - Other fields (e.g., `nmip`, `mprven`, `stopcount`, `stoptime`) are read-only zero.\n- `dpc` shall store the return address when entering Debug Mode and shall be restored on DRET.\n- `dscratch0/1` are general-purpose scratch registers for debug software.\n\n### 5.2 Debug Entry\n\n- When the pipeline signals a debug entry (via `debug_csr_save`), the module shall:\n - Save the current privilege level into `dcsr.prv`.\n - Save the debug cause into `dcsr.cause` (from `debug_cause_i`).\n - Save the current program counter into `depc`.\n - Do **not** update `mstatus`, `mepc`, `mcause`, or `mtval` — the non-debug exception state is preserved (per Debug Spec).\n- All interrupts (including NMI) are ignored while in Debug Mode.\n\n### 5.3 Debug Triggers (Optional)\n\n- If debug triggers are enabled (`DbgTriggerEn` parameter), the module shall implement the following additional CSRs:\n - `tselect`: always reads as zero (single trigger).\n - `tdata1`: returns a fixed type (address/data match trigger) with `dmode=1` (only Debug Mode can write), `execute` bit RW, most fields hard-wired.\n - `tdata2`: stores the address match value (RW in Debug Mode).\n - `tdata3`, `mcontext`, `scontext`: always read as zero; writes ignored.\n- The module shall compare the instruction fetch PC against the value in `tdata2`. When `tdata1.execute` is set and the PC matches, a trigger match signal shall be asserted.\n- Accesses to trigger CSRs from M-Mode (non-debug) shall be illegal, except that reads may be permitted; writes shall be ignored.\n- Access from Debug Mode is fully permitted.\n\n## 6. Physical Memory Protection (PMP)\n\n- If PMP is enabled (`PMPEnable` parameter), the module shall implement up to 16 PMP regions.\n- PMP configuration is stored in four `pmpcfg` registers (`pmpcfg0`–`pmpcfg3`), each controlling four regions, and up to sixteen `pmpaddr` registers.\n- Each region's configuration byte includes `lock`, `mode` (OFF/TOR/NA4/NAPOT), `exec`, `write`, `read`. The combination `write=1, read=0` shall be treated as `write=0`.\n- The module shall output the decoded PMP configuration and address for each region to the PMP checker.\n- Lock behavior: When the lock bit is set, writes to both the corresponding `pmpcfg` field and `pmpaddr` register shall be ignored until reset.\n- Address granularity: The parameter `PMPGranularity` defines the minimum region size (2^(G+2) bytes). For G>0, NA4 mode is not available and shall be treated as OFF. Read data is modified accordingly (bits [G-1:0] forced zero in TOR/OFF modes; bits [G-2:0] forced one in NAPOT mode).\n- If PMP is disabled, all PMP CSRs shall read as zero and the output addresses/configurations shall be zero.\n\n## 7. Performance Counters\n\n### 7.1 Counter Registers\n\n- The module shall implement a mandatory cycle counter `mcycle` (64-bit) and an instruction retired counter `minstret` (64-bit), accessible via low (`mcycle`/`minstret`) and high (`mcycleh`/`minstreth`) 32-bit halves.\n- Optionally, up to 29 event counters `mhpmcounter3`–`mhpmcounter31` may be present, with programmable width (parameter `MHPMCounterWidth`, default 40 bits). The number of implemented counters is controlled by parameter `MHPMCounterNum`.\n- Counter increments are controlled by hardware event signals (e.g., cycles, instruction retirement, LSU wait states, branches, jumps, multiply/divide waits, etc.). Each counter has a hard-wired event mapping, defined by the reset value of the corresponding `mhpmevent` selector.\n- The `mcountinhibit` CSR shall allow disabling any counter by setting the corresponding bit. Bit 1 is reserved and always reads as 0.\n- Counters may be written by software via the CSR interface (low and high parts).\n\n### 7.2 Event Selectors\n\n- CSRs `mhpmevent3`–`mhpmevent31` (if implemented) are hard-wired to a specific event mapping. For example, `mhpmevent3` defaults to counting event ID 3 (LSU wait cycles). Software can change the mapping by writing to these registers, but the default is such that each counter counts a single distinct event.\n- Unimplemented event selectors read as zero.\n\n### 7.3 Counting Rules\n\n- Each counter increments by 1 on every clock cycle where the associated event condition is true AND the corresponding `mcountinhibit` bit is 0.\n- `mcycle` increments every cycle unless inhibited.\n- `minstret` increments once per retired instruction (including compressed).\n- Counter updates are synchronous to the core clock.\n\n## 8. CPU Control Register\n\nA custom CSR `cpuctrl` (address 0x7C0) shall provide runtime configuration:\n\n- **icache_enable** (bit 0): If the instruction cache is configured (`ICache` parameter = 1), this bit controls cache enable (1=enabled). Otherwise, it reads as zero.\n- **data_ind_timing** (bit 1): If `DataIndTiming` parameter is set, this bit enables data-independent timing (1=timing independent of data). Otherwise, reads zero.\n- **dummy_instr_en** (bit 2): If `DummyInstructions` parameter is set, this bit enables dummy instruction insertion. Otherwise, reads zero.\n- **dummy_instr_mask** (bits 5:3): If dummy instructions are enabled, this field controls the mask/frequency of insertion. Otherwise, reads zero.\n- All other bits read as zero; writes to reserved bits are ignored.\n\nA second custom CSR `secureseed` (address 0x7C1) shall be write-only; reading always returns zero. A write to this register shall trigger a reseeding of the hardware pseudo-random number generator(s) used for security features. The actual seed is not stored in a CSR; it is passed directly to the relevant logic.\n\n## 9. Miscellaneous Fixed Registers\n\n- **mhartid** (0xF14): Shall return the value of the Hart ID input signal (read-only).\n- **misa** (0x301): Returns a hard-wired value indicating supported ISA extensions (I, C, E, M, U). Writes are ignored.\n- **mip** (0x344): Read-only register showing raw pending interrupts (not qualified by mie). Each bit reflects the corresponding interrupt input.\n\n## 10. Reset and Boot\n\n- On system reset:\n - All CSRs shall be initialized to their reset values as specified in the documentation.\n - Privilege level shall be Machine Mode.\n - The `mtvec` CSR shall be initialized with the boot address (input `boot_addr_i`) aligned to 256 bytes and with `MODE=01` (vectored).\n - The instruction fetch unit shall start at the boot address with the least significant byte set to 0x80 (i.e., boot_addr[31:8] concatenated with 0x80).\n- During a subsequent `csr_mtvec_init_i` pulse (e.g., after boot), the `mtvec` may be re-initialized from the boot address. Otherwise, normal CSR writes to `mtvec` shall be allowed, maintaining 256-byte alignment and forced vectored mode.\n\n## 11. Output Signals\n\nThe module shall provide the following critical behavioral outputs:\n\n- **Privilege mode** to the decoder, instruction fetch, and load-store unit.\n- **`csr_mtvec`**: current trap vector base address (aligned).\n- **`csr_mepc`**: last saved exception PC.\n- **`csr_depc`**: last saved debug PC.\n- **`csr_mstatus_mie`**: current global interrupt enable.\n- **`csr_mstatus_tw`**: Timeout Wait bit (controls if WFI in User Mode traps to Machine Mode).\n- **`irq_pending`**: combinatorial OR of qualified interrupts (mip & mie).\n- **`irqs`**: vector of qualified interrupts (mip & mie).\n- **`debug_single_step`**: single-step enable from `dcsr.step`.\n- **`debug_ebreakm`, `debug_ebreaku`**: control whether EBREAK in M/U mode enters debug.\n- **`trigger_match`**: asserted when a debug trigger address match occurs (if triggers enabled).\n- **`data_ind_timing`**, **`dummy_instr_en`**, **`dummy_instr_mask`**, **`icache_enable`**: CPU control bits for timing, dummy instructions, and cache.\n- **`dummy_instr_seed_en`** and **`dummy_instr_seed`**: strobe and data to seed the pseudorandom generator (triggered by writes to `secureseed`).\n- **PMP configuration** and **address** arrays (one per region, up to 16).\n- **`illegal_csr_insn`**: indicates that the current CSR access was illegal and the pipeline should raise an illegal instruction exception.", "commit_id": "1a9545baaf973c361d4ee5ac7b715d5957a4ceef", "timestamp": "2020-10-14T16:35:01+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "dbd92c5d4b5c47d408741a881c249d3cb4f9346d", "pr_title": "[rtl] Fix illegal write to DCSR cause field", "pr_body": "- This field is read-only to software, and so should retain its previous\r\n value on a write. This fixes #1134.\r\n\r\nSigned-off-by: Tom Roberts ", "issue_title": "Access rights - Illegal Write to Read Only Field - DCSR's cause", "issue_body": "#### RISC-V Specification\r\n\r\n> External Debug Support [4.8.1]\r\n\r\n#### Issue Description\r\n\r\nA read only field of `dcsr` is written. \r\n\r\n#### Steps to Reproduce\r\n\r\nAs shown below, while in debug mode, the instruction `csrrwi x17, dcsr, 0x4` updates the value of the `cause` field of `dcsr`, which has a read only access right.\r\n\r\n![dcsr_cause_write](https://user-images.githubusercontent.com/54367010/95985860-6ff77800-0e25-11eb-916e-ab3b01f116b6.PNG)\r\n\r\n---\r\nProduct: OneSpin 360 DV-Verify\r\nApp: Processor Verification App\r\nTool's version: 2020.2.0", "commit_message": "[rtl] Fix illegal write to DCSR cause field\n\n- This field is read-only to software, and so should retain its previous\n value on a write. This fixes #1134.\n\nSigned-off-by: Tom Roberts ", "fix_patch": "diff --git a/rtl/ibex_cs_registers.sv b/rtl/ibex_cs_registers.sv\nindex 9651e748fb..64fd64dc1b 100644\n--- a/rtl/ibex_cs_registers.sv\n+++ b/rtl/ibex_cs_registers.sv\n@@ -532,6 +532,9 @@ module ibex_cs_registers #(\n dcsr_d.prv = PRIV_LVL_M;\n end\n \n+ // Read-only for SW\n+ dcsr_d.cause = dcsr_q.cause;\n+\n // currently not supported:\n dcsr_d.nmip = 1'b0;\n dcsr_d.mprven = 1'b0;\n", "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 * Control and Status Registers\n *\n * Control and Status Registers (CSRs) following the RISC-V Privileged\n * Specification, draft version 1.11\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_cs_registers #(\n parameter bit DbgTriggerEn = 0,\n parameter bit DataIndTiming = 1'b0,\n parameter bit DummyInstructions = 1'b0,\n parameter bit ICache = 1'b0,\n parameter int unsigned MHPMCounterNum = 10,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit PMPEnable = 0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter bit RV32E = 0,\n parameter ibex_pkg::rv32m_e RV32M = ibex_pkg::RV32MFast\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n // Hart ID\n input logic [31:0] hart_id_i,\n\n // Privilege mode\n output ibex_pkg::priv_lvl_e priv_mode_id_o,\n output ibex_pkg::priv_lvl_e priv_mode_if_o,\n output ibex_pkg::priv_lvl_e priv_mode_lsu_o,\n output logic csr_mstatus_tw_o,\n\n // mtvec\n output logic [31:0] csr_mtvec_o,\n input logic csr_mtvec_init_i,\n input logic [31:0] boot_addr_i,\n\n // Interface to registers (SRAM like)\n input logic csr_access_i,\n input ibex_pkg::csr_num_e csr_addr_i,\n input logic [31:0] csr_wdata_i,\n input ibex_pkg::csr_op_e csr_op_i,\n input csr_op_en_i,\n output logic [31:0] csr_rdata_o,\n\n // interrupts\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 nmi_mode_i,\n output logic irq_pending_o, // interrupt request pending\n output ibex_pkg::irqs_t irqs_o, // interrupt requests qualified with mie\n output logic csr_mstatus_mie_o,\n output logic [31:0] csr_mepc_o,\n\n // PMP\n output ibex_pkg::pmp_cfg_t csr_pmp_cfg_o [PMPNumRegions],\n output logic [33:0] csr_pmp_addr_o [PMPNumRegions],\n\n // debug\n input logic debug_mode_i,\n input ibex_pkg::dbg_cause_e debug_cause_i,\n input logic debug_csr_save_i,\n output logic [31:0] csr_depc_o,\n output logic debug_single_step_o,\n output logic debug_ebreakm_o,\n output logic debug_ebreaku_o,\n output logic trigger_match_o,\n\n input logic [31:0] pc_if_i,\n input logic [31:0] pc_id_i,\n input logic [31:0] pc_wb_i,\n\n // CPU control bits\n output logic data_ind_timing_o,\n output logic dummy_instr_en_o,\n output logic [2:0] dummy_instr_mask_o,\n output logic dummy_instr_seed_en_o,\n output logic [31:0] dummy_instr_seed_o,\n output logic icache_enable_o,\n\n // Exception save/restore\n input logic csr_save_if_i,\n input logic csr_save_id_i,\n input logic csr_save_wb_i,\n input logic csr_restore_mret_i,\n input logic csr_restore_dret_i,\n input logic csr_save_cause_i,\n input ibex_pkg::exc_cause_e csr_mcause_i,\n input logic [31:0] csr_mtval_i,\n output logic illegal_csr_insn_o, // access to non-existent CSR,\n // with wrong priviledge level, or\n // missing write permissions\n // Performance Counters\n input logic instr_ret_i, // instr retired in ID/EX stage\n input logic instr_ret_compressed_i, // compressed instr retired\n input logic iside_wait_i, // core waiting for the iside\n input logic jump_i, // jump instr seen (j, jr, jal, jalr)\n input logic branch_i, // branch instr seen (bf, bnf)\n input logic branch_taken_i, // branch was taken\n input logic mem_load_i, // load from memory in this cycle\n input logic mem_store_i, // store to memory in this cycle\n input logic dside_wait_i, // core waiting for the dside\n input logic mul_wait_i, // core waiting for multiply\n input logic div_wait_i // core waiting for divide\n);\n\n import ibex_pkg::*;\n\n localparam int unsigned RV32MEnabled = (RV32M == RV32MNone) ? 0 : 1;\n\n // misa\n localparam logic [31:0] MISA_VALUE =\n (0 << 0) // A - Atomic Instructions extension\n | (1 << 2) // C - Compressed extension\n | (0 << 3) // D - Double precision floating-point extension\n | (32'(RV32E) << 4) // E - RV32E base ISA\n | (0 << 5) // F - Single precision floating-point extension\n | (32'(!RV32E) << 8) // I - RV32I/64I/128I base ISA\n | (RV32MEnabled << 12) // M - Integer Multiply/Divide extension\n | (0 << 13) // N - User level interrupts supported\n | (0 << 18) // S - Supervisor mode implemented\n | (1 << 20) // U - User mode implemented\n | (0 << 23) // X - Non-standard extensions present\n | (32'(CSR_MISA_MXL) << 30); // M-XLEN\n\n typedef struct packed {\n logic mie;\n logic mpie;\n priv_lvl_e mpp;\n logic mprv;\n logic tw;\n } status_t;\n\n typedef struct packed {\n logic mpie;\n priv_lvl_e mpp;\n } status_stk_t;\n\n typedef struct packed {\n x_debug_ver_e xdebugver;\n logic [11:0] zero2;\n logic ebreakm;\n logic zero1;\n logic ebreaks;\n logic ebreaku;\n logic stepie;\n logic stopcount;\n logic stoptime;\n dbg_cause_e cause;\n logic zero0;\n logic mprven;\n logic nmip;\n logic step;\n priv_lvl_e prv;\n } dcsr_t;\n\n // CPU control register fields\n typedef struct packed {\n logic [2:0] dummy_instr_mask;\n logic dummy_instr_en;\n logic data_ind_timing;\n logic icache_enable;\n } cpu_ctrl_t;\n\n // Interrupt and exception control signals\n logic [31:0] exception_pc;\n\n // CSRs\n priv_lvl_e priv_lvl_q, priv_lvl_d;\n status_t mstatus_q, mstatus_d;\n logic mstatus_en;\n irqs_t mie_q, mie_d;\n logic mie_en;\n logic [31:0] mscratch_q;\n logic mscratch_en;\n logic [31:0] mepc_q, mepc_d;\n logic mepc_en;\n logic [5:0] mcause_q, mcause_d;\n logic mcause_en;\n logic [31:0] mtval_q, mtval_d;\n logic mtval_en;\n logic [31:0] mtvec_q, mtvec_d;\n logic mtvec_en;\n irqs_t mip;\n dcsr_t dcsr_q, dcsr_d;\n logic dcsr_en;\n logic [31:0] depc_q, depc_d;\n logic depc_en;\n logic [31:0] dscratch0_q;\n logic [31:0] dscratch1_q;\n logic dscratch0_en, dscratch1_en;\n\n // CSRs for recoverable NMIs\n // NOTE: these CSRS are nonstandard, see https://github.com/riscv/riscv-isa-manual/issues/261\n status_stk_t mstack_q, mstack_d;\n logic mstack_en;\n logic [31:0] mstack_epc_q, mstack_epc_d;\n logic [5:0] mstack_cause_q, mstack_cause_d;\n\n // PMP Signals\n logic [31:0] pmp_addr_rdata [PMP_MAX_REGIONS];\n logic [PMP_CFG_W-1:0] pmp_cfg_rdata [PMP_MAX_REGIONS];\n\n // Hardware performance monitor signals\n logic [31:0] mcountinhibit;\n // Only have mcountinhibit flops for counters that actually exist\n logic [MHPMCounterNum+3-1:0] mcountinhibit_d, mcountinhibit_q;\n logic mcountinhibit_we;\n\n // mhpmcounter flops are elaborated below providing only the precise number that is required based\n // on MHPMCounterNum/MHPMCounterWidth. This signal connects to the Q output of these flops\n // where they exist and is otherwise 0.\n logic [63:0] mhpmcounter [32];\n logic [31:0] mhpmcounter_we;\n logic [31:0] mhpmcounterh_we;\n logic [31:0] mhpmcounter_incr;\n logic [31:0] mhpmevent [32];\n logic [4:0] mhpmcounter_idx;\n\n // Debug / trigger registers\n logic [31:0] tselect_rdata;\n logic [31:0] tmatch_control_rdata;\n logic [31:0] tmatch_value_rdata;\n\n // CPU control bits\n cpu_ctrl_t cpuctrl_q, cpuctrl_d, cpuctrl_wdata;\n logic cpuctrl_we;\n\n // CSR update logic\n logic [31:0] csr_wdata_int;\n logic [31:0] csr_rdata_int;\n logic csr_we_int;\n logic csr_wreq;\n\n // Access violation signals\n logic illegal_csr;\n logic illegal_csr_priv;\n logic illegal_csr_write;\n\n logic [7:0] unused_boot_addr;\n logic [2:0] unused_csr_addr;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n\n /////////////\n // CSR reg //\n /////////////\n\n logic [$bits(csr_num_e)-1:0] csr_addr;\n assign csr_addr = {csr_addr_i};\n assign unused_csr_addr = csr_addr[7:5];\n assign mhpmcounter_idx = csr_addr[4:0];\n\n // See RISC-V Privileged Specification, version 1.11, Section 2.1\n assign illegal_csr_priv = (csr_addr[9:8] > {priv_lvl_q});\n assign illegal_csr_write = (csr_addr[11:10] == 2'b11) && csr_wreq;\n assign illegal_csr_insn_o = csr_access_i & (illegal_csr | illegal_csr_write | illegal_csr_priv);\n\n // mip CSR is purely combinational - must be able to re-enable the clock upon WFI\n assign mip.irq_software = irq_software_i;\n assign mip.irq_timer = irq_timer_i;\n assign mip.irq_external = irq_external_i;\n assign mip.irq_fast = irq_fast_i;\n\n // read logic\n always_comb begin\n csr_rdata_int = '0;\n illegal_csr = 1'b0;\n\n unique case (csr_addr_i)\n // mhartid: unique hardware thread id\n CSR_MHARTID: csr_rdata_int = hart_id_i;\n\n // mstatus: always M-mode, contains IE bit\n CSR_MSTATUS: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSTATUS_MIE_BIT] = mstatus_q.mie;\n csr_rdata_int[CSR_MSTATUS_MPIE_BIT] = mstatus_q.mpie;\n csr_rdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW] = mstatus_q.mpp;\n csr_rdata_int[CSR_MSTATUS_MPRV_BIT] = mstatus_q.mprv;\n csr_rdata_int[CSR_MSTATUS_TW_BIT] = mstatus_q.tw;\n end\n\n // misa\n CSR_MISA: csr_rdata_int = MISA_VALUE;\n\n // interrupt enable\n CSR_MIE: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mie_q.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mie_q.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mie_q.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mie_q.irq_fast;\n end\n\n CSR_MSCRATCH: csr_rdata_int = mscratch_q;\n\n // mtvec: trap-vector base address\n CSR_MTVEC: csr_rdata_int = mtvec_q;\n\n // mepc: exception program counter\n CSR_MEPC: csr_rdata_int = mepc_q;\n\n // mcause: exception cause\n CSR_MCAUSE: csr_rdata_int = {mcause_q[5], 26'b0, mcause_q[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: csr_rdata_int = mtval_q;\n\n // mip: interrupt pending\n CSR_MIP: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mip.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mip.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mip.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mip.irq_fast;\n end\n\n // PMP registers\n CSR_PMPCFG0: csr_rdata_int = {pmp_cfg_rdata[3], pmp_cfg_rdata[2],\n pmp_cfg_rdata[1], pmp_cfg_rdata[0]};\n CSR_PMPCFG1: csr_rdata_int = {pmp_cfg_rdata[7], pmp_cfg_rdata[6],\n pmp_cfg_rdata[5], pmp_cfg_rdata[4]};\n CSR_PMPCFG2: csr_rdata_int = {pmp_cfg_rdata[11], pmp_cfg_rdata[10],\n pmp_cfg_rdata[9], pmp_cfg_rdata[8]};\n CSR_PMPCFG3: csr_rdata_int = {pmp_cfg_rdata[15], pmp_cfg_rdata[14],\n pmp_cfg_rdata[13], pmp_cfg_rdata[12]};\n CSR_PMPADDR0: csr_rdata_int = pmp_addr_rdata[0];\n CSR_PMPADDR1: csr_rdata_int = pmp_addr_rdata[1];\n CSR_PMPADDR2: csr_rdata_int = pmp_addr_rdata[2];\n CSR_PMPADDR3: csr_rdata_int = pmp_addr_rdata[3];\n CSR_PMPADDR4: csr_rdata_int = pmp_addr_rdata[4];\n CSR_PMPADDR5: csr_rdata_int = pmp_addr_rdata[5];\n CSR_PMPADDR6: csr_rdata_int = pmp_addr_rdata[6];\n CSR_PMPADDR7: csr_rdata_int = pmp_addr_rdata[7];\n CSR_PMPADDR8: csr_rdata_int = pmp_addr_rdata[8];\n CSR_PMPADDR9: csr_rdata_int = pmp_addr_rdata[9];\n CSR_PMPADDR10: csr_rdata_int = pmp_addr_rdata[10];\n CSR_PMPADDR11: csr_rdata_int = pmp_addr_rdata[11];\n CSR_PMPADDR12: csr_rdata_int = pmp_addr_rdata[12];\n CSR_PMPADDR13: csr_rdata_int = pmp_addr_rdata[13];\n CSR_PMPADDR14: csr_rdata_int = pmp_addr_rdata[14];\n CSR_PMPADDR15: csr_rdata_int = pmp_addr_rdata[15];\n\n CSR_DCSR: begin\n csr_rdata_int = dcsr_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DPC: begin\n csr_rdata_int = depc_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH0: begin\n csr_rdata_int = dscratch0_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH1: begin\n csr_rdata_int = dscratch1_q;\n illegal_csr = ~debug_mode_i;\n end\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: csr_rdata_int = mcountinhibit;\n CSR_MHPMEVENT3,\n CSR_MHPMEVENT4, CSR_MHPMEVENT5, CSR_MHPMEVENT6, CSR_MHPMEVENT7,\n CSR_MHPMEVENT8, CSR_MHPMEVENT9, CSR_MHPMEVENT10, CSR_MHPMEVENT11,\n CSR_MHPMEVENT12, CSR_MHPMEVENT13, CSR_MHPMEVENT14, CSR_MHPMEVENT15,\n CSR_MHPMEVENT16, CSR_MHPMEVENT17, CSR_MHPMEVENT18, CSR_MHPMEVENT19,\n CSR_MHPMEVENT20, CSR_MHPMEVENT21, CSR_MHPMEVENT22, CSR_MHPMEVENT23,\n CSR_MHPMEVENT24, CSR_MHPMEVENT25, CSR_MHPMEVENT26, CSR_MHPMEVENT27,\n CSR_MHPMEVENT28, CSR_MHPMEVENT29, CSR_MHPMEVENT30, CSR_MHPMEVENT31: begin\n csr_rdata_int = mhpmevent[mhpmcounter_idx];\n end\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][31:0];\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][63:32];\n end\n\n // Debug triggers\n CSR_TSELECT: begin\n csr_rdata_int = tselect_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA1: begin\n csr_rdata_int = tmatch_control_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA2: begin\n csr_rdata_int = tmatch_value_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA3: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_MCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_SCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n\n // Custom CSR for controlling CPU features\n CSR_CPUCTRL: begin\n csr_rdata_int = {{32-$bits(cpu_ctrl_t){1'b0}},cpuctrl_q};\n end\n\n // Custom CSR for LFSR re-seeding (cannot be read)\n CSR_SECURESEED: begin\n csr_rdata_int = '0;\n end\n\n default: begin\n illegal_csr = 1'b1;\n end\n endcase\n end\n\n // write logic\n always_comb begin\n exception_pc = pc_id_i;\n\n priv_lvl_d = priv_lvl_q;\n mstatus_en = 1'b0;\n mstatus_d = mstatus_q;\n mie_en = 1'b0;\n mscratch_en = 1'b0;\n mepc_en = 1'b0;\n mepc_d = {csr_wdata_int[31:1], 1'b0};\n mcause_en = 1'b0;\n mcause_d = {csr_wdata_int[31], csr_wdata_int[4:0]};\n mtval_en = 1'b0;\n mtval_d = csr_wdata_int;\n mtvec_en = csr_mtvec_init_i;\n // mtvec.MODE set to vectored\n // mtvec.BASE must be 256-byte aligned\n mtvec_d = csr_mtvec_init_i ? {boot_addr_i[31:8], 6'b0, 2'b01} :\n {csr_wdata_int[31:8], 6'b0, 2'b01};\n dcsr_en = 1'b0;\n dcsr_d = dcsr_q;\n depc_d = {csr_wdata_int[31:1], 1'b0};\n depc_en = 1'b0;\n dscratch0_en = 1'b0;\n dscratch1_en = 1'b0;\n\n mstack_en = 1'b0;\n mstack_d.mpie = mstatus_q.mpie;\n mstack_d.mpp = mstatus_q.mpp;\n mstack_epc_d = mepc_q;\n mstack_cause_d = mcause_q;\n\n mcountinhibit_we = 1'b0;\n mhpmcounter_we = '0;\n mhpmcounterh_we = '0;\n\n cpuctrl_we = 1'b0;\n\n if (csr_we_int) begin\n unique case (csr_addr_i)\n // mstatus: IE bit\n CSR_MSTATUS: begin\n mstatus_en = 1'b1;\n mstatus_d = '{\n mie: csr_wdata_int[CSR_MSTATUS_MIE_BIT],\n mpie: csr_wdata_int[CSR_MSTATUS_MPIE_BIT],\n mpp: priv_lvl_e'(csr_wdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW]),\n mprv: csr_wdata_int[CSR_MSTATUS_MPRV_BIT],\n tw: csr_wdata_int[CSR_MSTATUS_TW_BIT]\n };\n // Convert illegal values to M-mode\n if ((mstatus_d.mpp != PRIV_LVL_M) && (mstatus_d.mpp != PRIV_LVL_U)) begin\n mstatus_d.mpp = PRIV_LVL_M;\n end\n end\n\n // interrupt enable\n CSR_MIE: mie_en = 1'b1;\n\n CSR_MSCRATCH: mscratch_en = 1'b1;\n\n // mepc: exception program counter\n CSR_MEPC: mepc_en = 1'b1;\n\n // mcause\n CSR_MCAUSE: mcause_en = 1'b1;\n\n // mtval: trap value\n CSR_MTVAL: mtval_en = 1'b1;\n\n // mtvec\n CSR_MTVEC: mtvec_en = 1'b1;\n\n CSR_DCSR: begin\n dcsr_d = csr_wdata_int;\n dcsr_d.xdebugver = XDEBUGVER_STD;\n // Change to PRIV_LVL_M if software writes an unsupported value\n if ((dcsr_d.prv != PRIV_LVL_M) && (dcsr_d.prv != PRIV_LVL_U)) begin\n dcsr_d.prv = PRIV_LVL_M;\n end\n\n // Read-only for SW\n dcsr_d.cause = dcsr_q.cause;\n\n // currently not supported:\n dcsr_d.nmip = 1'b0;\n dcsr_d.mprven = 1'b0;\n dcsr_d.stopcount = 1'b0;\n dcsr_d.stoptime = 1'b0;\n\n // forced to be zero\n dcsr_d.zero0 = 1'b0;\n dcsr_d.zero1 = 1'b0;\n dcsr_d.zero2 = 12'h0;\n dcsr_en = 1'b1;\n end\n\n // dpc: debug program counter\n CSR_DPC: depc_en = 1'b1;\n\n CSR_DSCRATCH0: dscratch0_en = 1'b1;\n CSR_DSCRATCH1: dscratch1_en = 1'b1;\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: mcountinhibit_we = 1'b1;\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n mhpmcounter_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n mhpmcounterh_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_CPUCTRL: cpuctrl_we = 1'b1;\n\n default:;\n endcase\n end\n\n // exception controller gets priority over other writes\n unique case (1'b1)\n\n csr_save_cause_i: begin\n unique case (1'b1)\n csr_save_if_i: begin\n exception_pc = pc_if_i;\n end\n csr_save_id_i: begin\n exception_pc = pc_id_i;\n end\n csr_save_wb_i: begin\n exception_pc = pc_wb_i;\n end\n default:;\n endcase\n\n // Any exception, including debug mode, causes a switch to M-mode\n priv_lvl_d = PRIV_LVL_M;\n\n if (debug_csr_save_i) begin\n // all interrupts are masked\n // do not update cause, epc, tval, epc and status\n dcsr_d.prv = priv_lvl_q;\n dcsr_d.cause = debug_cause_i;\n dcsr_en = 1'b1;\n depc_d = exception_pc;\n depc_en = 1'b1;\n end else if (!debug_mode_i) begin\n // In debug mode, \"exceptions do not update any registers. That\n // includes cause, epc, tval, dpc and mstatus.\" [Debug Spec v0.13.2, p.39]\n mtval_en = 1'b1;\n mtval_d = csr_mtval_i;\n mstatus_en = 1'b1;\n mstatus_d.mie = 1'b0; // disable interrupts\n // save current status\n mstatus_d.mpie = mstatus_q.mie;\n mstatus_d.mpp = priv_lvl_q;\n mepc_en = 1'b1;\n mepc_d = exception_pc;\n mcause_en = 1'b1;\n mcause_d = {csr_mcause_i};\n // save previous status for recoverable NMI\n mstack_en = 1'b1;\n end\n end // csr_save_cause_i\n\n csr_restore_dret_i: begin // DRET\n priv_lvl_d = dcsr_q.prv;\n end // csr_restore_dret_i\n\n csr_restore_mret_i: begin // MRET\n priv_lvl_d = mstatus_q.mpp;\n mstatus_en = 1'b1;\n mstatus_d.mie = mstatus_q.mpie; // re-enable interrupts\n\n if (nmi_mode_i) begin\n // when returning from an NMI restore state from mstack CSR\n mstatus_d.mpie = mstack_q.mpie;\n mstatus_d.mpp = mstack_q.mpp;\n mepc_en = 1'b1;\n mepc_d = mstack_epc_q;\n mcause_en = 1'b1;\n mcause_d = mstack_cause_q;\n end else begin\n // otherwise just set mstatus.MPIE/MPP\n // See RISC-V Privileged Specification, version 1.11, Section 3.1.6.1\n mstatus_d.mpie = 1'b1;\n mstatus_d.mpp = PRIV_LVL_U;\n end\n end // csr_restore_mret_i\n\n default:;\n endcase\n end\n\n // Update current priv level\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n priv_lvl_q <= PRIV_LVL_M;\n end else begin\n priv_lvl_q <= priv_lvl_d;\n end\n end\n\n // Send current priv level to the decoder\n assign priv_mode_id_o = priv_lvl_q;\n // New instruction fetches need to account for updates to priv_lvl_q this cycle\n assign priv_mode_if_o = priv_lvl_d;\n // Load/store instructions must factor in MPRV for PMP checking\n assign priv_mode_lsu_o = mstatus_q.mprv ? mstatus_q.mpp : priv_lvl_q;\n\n // CSR operation logic\n always_comb begin\n unique case (csr_op_i)\n CSR_OP_WRITE: csr_wdata_int = csr_wdata_i;\n CSR_OP_SET: csr_wdata_int = csr_wdata_i | csr_rdata_o;\n CSR_OP_CLEAR: csr_wdata_int = ~csr_wdata_i & csr_rdata_o;\n CSR_OP_READ: csr_wdata_int = csr_wdata_i;\n default: csr_wdata_int = csr_wdata_i;\n endcase\n end\n\n assign csr_wreq = csr_op_en_i &\n (csr_op_i inside {CSR_OP_WRITE,\n CSR_OP_SET,\n CSR_OP_CLEAR});\n\n // only write CSRs during one clock cycle\n assign csr_we_int = csr_wreq & ~illegal_csr_insn_o;\n\n assign csr_rdata_o = csr_rdata_int;\n\n // directly output some registers\n assign csr_mepc_o = mepc_q;\n assign csr_depc_o = depc_q;\n assign csr_mtvec_o = mtvec_q;\n\n assign csr_mstatus_mie_o = mstatus_q.mie;\n assign csr_mstatus_tw_o = mstatus_q.tw;\n assign debug_single_step_o = dcsr_q.step;\n assign debug_ebreakm_o = dcsr_q.ebreakm;\n assign debug_ebreaku_o = dcsr_q.ebreaku;\n\n // Qualify incoming interrupt requests in mip CSR with mie CSR for controller and to re-enable\n // clock upon WFI (must be purely combinational).\n assign irqs_o = mip & mie_q;\n assign irq_pending_o = |irqs_o;\n\n ////////////////////////\n // CSR instantiations //\n ////////////////////////\n\n // MSTATUS\n localparam status_t MSTATUS_RST_VAL = '{mie: 1'b0,\n mpie: 1'b1,\n mpp: PRIV_LVL_U,\n mprv: 1'b0,\n tw: 1'b0};\n ibex_csr #(\n .Width ($bits(status_t)),\n .ShadowCopy (1'b0),\n .ResetValue ({MSTATUS_RST_VAL})\n ) u_mstatus_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mstatus_d}),\n .wr_en_i (mstatus_en),\n .rd_data_o (mstatus_q),\n .rd_error_o ()\n );\n\n // MEPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mepc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mepc_d),\n .wr_en_i (mepc_en),\n .rd_data_o (mepc_q),\n .rd_error_o ()\n );\n\n // MIE\n assign mie_d.irq_software = csr_wdata_int[CSR_MSIX_BIT];\n assign mie_d.irq_timer = csr_wdata_int[CSR_MTIX_BIT];\n assign mie_d.irq_external = csr_wdata_int[CSR_MEIX_BIT];\n assign mie_d.irq_fast = csr_wdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW];\n ibex_csr #(\n .Width ($bits(irqs_t)),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mie_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mie_d}),\n .wr_en_i (mie_en),\n .rd_data_o (mie_q),\n .rd_error_o ()\n );\n\n // MSCRATCH\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mscratch_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (mscratch_en),\n .rd_data_o (mscratch_q),\n .rd_error_o ()\n );\n\n // MCAUSE\n ibex_csr #(\n .Width (6),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mcause_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mcause_d),\n .wr_en_i (mcause_en),\n .rd_data_o (mcause_q),\n .rd_error_o ()\n );\n\n // MTVAL\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mtval_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mtval_d),\n .wr_en_i (mtval_en),\n .rd_data_o (mtval_q),\n .rd_error_o ()\n );\n\n // MTVEC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue (32'd1)\n ) u_mtvec_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mtvec_d),\n .wr_en_i (mtvec_en),\n .rd_data_o (mtvec_q),\n .rd_error_o ()\n );\n\n // DCSR\n localparam dcsr_t DCSR_RESET_VAL = '{\n xdebugver: XDEBUGVER_STD,\n cause: DBG_CAUSE_NONE, // 3'h0\n prv: PRIV_LVL_M,\n default: '0\n };\n ibex_csr #(\n .Width ($bits(dcsr_t)),\n .ShadowCopy (1'b0),\n .ResetValue ({DCSR_RESET_VAL})\n ) u_dcsr_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({dcsr_d}),\n .wr_en_i (dcsr_en),\n .rd_data_o (dcsr_q),\n .rd_error_o ()\n );\n\n // DEPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_depc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (depc_d),\n .wr_en_i (depc_en),\n .rd_data_o (depc_q),\n .rd_error_o ()\n );\n\n // DSCRATCH0\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_dscratch0_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (dscratch0_en),\n .rd_data_o (dscratch0_q),\n .rd_error_o ()\n );\n\n // DSCRATCH1\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_dscratch1_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (dscratch1_en),\n .rd_data_o (dscratch1_q),\n .rd_error_o ()\n );\n\n // MSTACK\n localparam status_stk_t MSTACK_RESET_VAL = '{\n mpie: 1'b1,\n mpp: PRIV_LVL_U\n };\n ibex_csr #(\n .Width ($bits(status_stk_t)),\n .ShadowCopy (1'b0),\n .ResetValue ({MSTACK_RESET_VAL})\n ) u_mstack_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mstack_d}),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_q),\n .rd_error_o ()\n );\n\n // MSTACK_EPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mstack_epc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mstack_epc_d),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_epc_q),\n .rd_error_o ()\n );\n\n // MSTACK_CAUSE\n ibex_csr #(\n .Width (6),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mstack_cause_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mstack_cause_d),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_cause_q),\n .rd_error_o ()\n );\n\n // -----------------\n // PMP registers\n // -----------------\n\n if (PMPEnable) begin : g_pmp_registers\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n logic [31:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n logic [PMPNumRegions-1:0] pmp_addr_we;\n\n // Expanded / qualified register read data\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_exp_rd_data\n if (i < PMPNumRegions) begin : g_implemented_regions\n // Add in zero padding for reserved fields\n assign pmp_cfg_rdata[i] = {pmp_cfg[i].lock, 2'b00, pmp_cfg[i].mode,\n pmp_cfg[i].exec, pmp_cfg[i].write, pmp_cfg[i].read};\n\n // Address field read data depends on the current programmed mode and the granularity\n // See RISC-V Privileged Specification, version 1.11, Section 3.6.1\n if (PMPGranularity == 0) begin : g_pmp_g0\n // If G == 0, read data is unmodified\n assign pmp_addr_rdata[i] = pmp_addr[i];\n\n end else if (PMPGranularity == 1) begin : g_pmp_g1\n // If G == 1, bit [G-1] reads as zero in TOR or OFF mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n\n end else begin : g_pmp_g2\n // For G >= 2, bits are masked to one or zero depending on the mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n // In TOR or OFF mode, bits [G-1:0] must read as zero\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end else if (pmp_cfg[i].mode == PMP_MODE_NAPOT) begin\n // In NAPOT mode, bits [G-2:0] must read as one\n pmp_addr_rdata[i][PMPGranularity-2:0] = '1;\n end\n end\n end\n\n end else begin : g_other_regions\n // Non-implemented regions read as zero\n assign pmp_cfg_rdata[i] = '0;\n assign pmp_addr_rdata[i] = '0;\n end\n end\n\n // Write data calculation\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_pmp_csrs\n // -------------------------\n // Instantiate cfg registers\n // -------------------------\n assign pmp_cfg_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_CFG + (i[11:0] >> 2)));\n\n // Select the correct WDATA (each CSR contains 4 CFG fields, each with 2 RES bits)\n assign pmp_cfg_wdata[i].lock = csr_wdata_int[(i%4)*PMP_CFG_W+7];\n // NA4 mode is not selectable when G > 0, mode is treated as OFF\n always_comb begin\n unique case (csr_wdata_int[(i%4)*PMP_CFG_W+3+:2])\n 2'b00 : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n 2'b01 : pmp_cfg_wdata[i].mode = PMP_MODE_TOR;\n 2'b10 : pmp_cfg_wdata[i].mode = (PMPGranularity == 0) ? PMP_MODE_NA4:\n PMP_MODE_OFF;\n 2'b11 : pmp_cfg_wdata[i].mode = PMP_MODE_NAPOT;\n default : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n endcase\n end\n assign pmp_cfg_wdata[i].exec = csr_wdata_int[(i%4)*PMP_CFG_W+2];\n // W = 1, R = 0 is a reserved combination. For now, we force W to 0 if R == 0\n assign pmp_cfg_wdata[i].write = &csr_wdata_int[(i%4)*PMP_CFG_W+:2];\n assign pmp_cfg_wdata[i].read = csr_wdata_int[(i%4)*PMP_CFG_W];\n\n ibex_csr #(\n .Width ($bits(pmp_cfg_t)),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_pmp_cfg_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({pmp_cfg_wdata[i]}),\n .wr_en_i (pmp_cfg_we[i]),\n .rd_data_o (pmp_cfg[i]),\n .rd_error_o ()\n );\n\n // --------------------------\n // Instantiate addr registers\n // --------------------------\n if (i < PMPNumRegions - 1) begin : g_lower\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (~pmp_cfg[i+1].lock | (pmp_cfg[i+1].mode != PMP_MODE_TOR)) &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end else begin : g_upper\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end\n\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_pmp_addr_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (pmp_addr_we[i]),\n .rd_data_o (pmp_addr[i]),\n .rd_error_o ()\n );\n\n assign csr_pmp_cfg_o[i] = pmp_cfg[i];\n assign csr_pmp_addr_o[i] = {pmp_addr[i],2'b00};\n end\n\n end else begin : g_no_pmp_tieoffs\n // Generate tieoffs when PMP is not configured\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_rdata\n assign pmp_addr_rdata[i] = '0;\n assign pmp_cfg_rdata[i] = '0;\n end\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_outputs\n assign csr_pmp_cfg_o[i] = pmp_cfg_t'(1'b0);\n assign csr_pmp_addr_o[i] = '0;\n end\n end\n\n //////////////////////////\n // Performance monitor //\n //////////////////////////\n\n // update enable signals\n always_comb begin : mcountinhibit_update\n if (mcountinhibit_we == 1'b1) begin\n // bit 1 must always be 0\n mcountinhibit_d = {csr_wdata_int[MHPMCounterNum+2:2], 1'b0, csr_wdata_int[0]};\n end else begin\n mcountinhibit_d = mcountinhibit_q;\n end\n end\n\n // event selection (hardwired) & control\n always_comb begin : gen_mhpmcounter_incr\n\n // Assign inactive counters (first to prevent latch inference)\n for (int unsigned i=0; i<32; i++) begin : gen_mhpmcounter_incr_inactive\n mhpmcounter_incr[i] = 1'b0;\n end\n\n // When adding or altering performance counter meanings and default\n // mappings please update dv/verilator/pcount/cpp/ibex_pcounts.cc\n // appropriately.\n //\n // active counters\n mhpmcounter_incr[0] = 1'b1; // mcycle\n mhpmcounter_incr[1] = 1'b0; // reserved\n mhpmcounter_incr[2] = instr_ret_i; // minstret\n mhpmcounter_incr[3] = dside_wait_i; // cycles waiting for data memory\n mhpmcounter_incr[4] = iside_wait_i; // cycles waiting for instr fetches\n mhpmcounter_incr[5] = mem_load_i; // num of loads\n mhpmcounter_incr[6] = mem_store_i; // num of stores\n mhpmcounter_incr[7] = jump_i; // num of jumps (unconditional)\n mhpmcounter_incr[8] = branch_i; // num of branches (conditional)\n mhpmcounter_incr[9] = branch_taken_i; // num of taken branches (conditional)\n mhpmcounter_incr[10] = instr_ret_compressed_i; // num of compressed instr\n mhpmcounter_incr[11] = mul_wait_i; // cycles waiting for multiply\n mhpmcounter_incr[12] = div_wait_i; // cycles waiting for divide\n end\n\n // event selector (hardwired, 0 means no event)\n always_comb begin : gen_mhpmevent\n\n // activate all\n for (int i=0; i<32; i++) begin : gen_mhpmevent_active\n mhpmevent[i] = '0;\n mhpmevent[i][i] = 1'b1;\n end\n\n // deactivate\n mhpmevent[1] = '0; // not existing, reserved\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmevent_inactive\n mhpmevent[i] = '0;\n end\n end\n\n // mcycle\n ibex_counter #(\n .CounterWidth(64)\n ) mcycle_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[0] & ~mcountinhibit[0]),\n .counterh_we_i(mhpmcounterh_we[0]),\n .counter_we_i(mhpmcounter_we[0]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[0])\n );\n\n // minstret\n ibex_counter #(\n .CounterWidth(64)\n ) minstret_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[2] & ~mcountinhibit[2]),\n .counterh_we_i(mhpmcounterh_we[2]),\n .counter_we_i(mhpmcounter_we[2]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[2])\n );\n\n // reserved:\n assign mhpmcounter[1] = '0;\n\n for (genvar cnt=0; cnt < MHPMCounterNum; cnt++) begin : gen_cntrs\n ibex_counter #(\n .CounterWidth(MHPMCounterWidth)\n ) mcounters_variable_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[cnt+3] & ~mcountinhibit[cnt+3]),\n .counterh_we_i(mhpmcounterh_we[cnt+3]),\n .counter_we_i(mhpmcounter_we[cnt+3]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[cnt+3])\n );\n end\n\n if(MHPMCounterNum < 29) begin : g_mcountinhibit_reduced\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounterh_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_incr;\n\n assign mcountinhibit = {{29-MHPMCounterNum{1'b1}}, mcountinhibit_q};\n // Lint tieoffs for unused bits\n assign unused_mhphcounter_we = mhpmcounter_we[31:MHPMCounterNum+3];\n assign unused_mhphcounterh_we = mhpmcounterh_we[31:MHPMCounterNum+3];\n assign unused_mhphcounter_incr = mhpmcounter_incr[31:MHPMCounterNum+3];\n end else begin : g_mcountinhibit_full\n assign mcountinhibit = mcountinhibit_q;\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n mcountinhibit_q <= '0;\n end else begin\n mcountinhibit_q <= mcountinhibit_d;\n end\n end\n\n /////////////////////////////\n // Debug trigger registers //\n /////////////////////////////\n\n if (DbgTriggerEn) begin : gen_trigger_regs\n // Register values\n logic tmatch_control_d, tmatch_control_q;\n logic [31:0] tmatch_value_d, tmatch_value_q;\n // Write enables\n logic tmatch_control_we;\n logic tmatch_value_we;\n\n // Write select\n assign tmatch_control_we = csr_we_int & debug_mode_i & (csr_addr_i == CSR_TDATA1);\n assign tmatch_value_we = csr_we_int & debug_mode_i & (csr_addr_i == CSR_TDATA2);\n\n // tmatch_control is enabled when the execute bit is set\n assign tmatch_control_d = csr_wdata_int[2];\n assign tmatch_value_d = csr_wdata_int[31:0];\n\n // Registers\n ibex_csr #(\n .Width (1),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_tmatch_control_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tmatch_control_d),\n .wr_en_i (tmatch_control_we),\n .rd_data_o (tmatch_control_q),\n .rd_error_o ()\n );\n\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_tmatch_value_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tmatch_value_d),\n .wr_en_i (tmatch_value_we),\n .rd_data_o (tmatch_value_q),\n .rd_error_o ()\n );\n\n // Assign read data\n // TSELECT - only one supported\n assign tselect_rdata = 'b0;\n // TDATA0 - only support simple address matching\n assign tmatch_control_rdata = {4'h2, // type : address/data match\n 1'b1, // dmode : access from D mode only\n 6'h00, // maskmax : exact match only\n 1'b0, // hit : not supported\n 1'b0, // select : address match only\n 1'b0, // timing : match before execution\n 2'b00, // sizelo : match any access\n 4'h1, // action : enter debug mode\n 1'b0, // chain : not supported\n 4'h0, // match : simple match\n 1'b1, // m : match in m-mode\n 1'b0, // 0 : zero\n 1'b0, // s : not supported\n 1'b1, // u : match in u-mode\n tmatch_control_q, // execute : match instruction address\n 1'b0, // store : not supported\n 1'b0}; // load : not supported\n // TDATA1 - address match value only\n assign tmatch_value_rdata = tmatch_value_q;\n\n // Breakpoint matching\n // We match against the next address, as the breakpoint must be taken before execution\n assign trigger_match_o = tmatch_control_q & (pc_if_i[31:0] == tmatch_value_q[31:0]);\n\n end else begin : gen_no_trigger_regs\n assign tselect_rdata = 'b0;\n assign tmatch_control_rdata = 'b0;\n assign tmatch_value_rdata = 'b0;\n assign trigger_match_o = 'b0;\n end\n\n //////////////////////////\n // CPU control register //\n //////////////////////////\n\n // Cast register write data\n assign cpuctrl_wdata = cpu_ctrl_t'(csr_wdata_int[$bits(cpu_ctrl_t)-1:0]);\n\n // Generate fixed time execution bit\n if (DataIndTiming) begin : gen_dit\n assign cpuctrl_d.data_ind_timing = cpuctrl_wdata.data_ind_timing;\n\n end else begin : gen_no_dit\n // tieoff for the unused bit\n logic unused_dit;\n assign unused_dit = cpuctrl_wdata.data_ind_timing;\n\n // field will always read as zero if not configured\n assign cpuctrl_d.data_ind_timing = 1'b0;\n end\n\n assign data_ind_timing_o = cpuctrl_q.data_ind_timing;\n\n // Generate dummy instruction signals\n if (DummyInstructions) begin : gen_dummy\n assign cpuctrl_d.dummy_instr_en = cpuctrl_wdata.dummy_instr_en;\n assign cpuctrl_d.dummy_instr_mask = cpuctrl_wdata.dummy_instr_mask;\n\n // Signal a write to the seed register\n assign dummy_instr_seed_en_o = csr_we_int && (csr_addr == CSR_SECURESEED);\n assign dummy_instr_seed_o = csr_wdata_int;\n\n end else begin : gen_no_dummy\n // tieoff for the unused bit\n logic unused_dummy_en;\n logic [2:0] unused_dummy_mask;\n assign unused_dummy_en = cpuctrl_wdata.dummy_instr_en;\n assign unused_dummy_mask = cpuctrl_wdata.dummy_instr_mask;\n\n // field will always read as zero if not configured\n assign cpuctrl_d.dummy_instr_en = 1'b0;\n assign cpuctrl_d.dummy_instr_mask = 3'b000;\n assign dummy_instr_seed_en_o = 1'b0;\n assign dummy_instr_seed_o = '0;\n end\n\n assign dummy_instr_en_o = cpuctrl_q.dummy_instr_en;\n assign dummy_instr_mask_o = cpuctrl_q.dummy_instr_mask;\n\n // Generate icache enable bit\n if (ICache) begin : gen_icache_enable\n assign cpuctrl_d.icache_enable = cpuctrl_wdata.icache_enable;\n end else begin : gen_no_icache\n // tieoff for the unused icen bit\n logic unused_icen;\n assign unused_icen = cpuctrl_wdata.icache_enable;\n\n // icen field will always read as zero if ICache not configured\n assign cpuctrl_d.icache_enable = 1'b0;\n end\n\n assign icache_enable_o = cpuctrl_q.icache_enable;\n\n ibex_csr #(\n .Width ($bits(cpu_ctrl_t)),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_cpuctrl_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({cpuctrl_d}),\n .wr_en_i (cpuctrl_we),\n .rd_data_o (cpuctrl_q),\n .rd_error_o ()\n );\n\n ////////////////\n // Assertions //\n ////////////////\n\n `ASSERT(IbexCsrOpEnRequiresAccess, csr_op_en_i |-> csr_access_i)\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/cs_registers.rst", "doc/03_reference/pmp.rst", "doc/03_reference/debug.rst", "doc/03_reference/performance_counters.rst", "doc/03_reference/exception_interrupts.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1002, "lang": "sv", "rtl_files": ["rtl/gift_pkg.sv"], "spec": "# Behavioral Design Specification for `gift_pkg`\n\n## Overview\n\nThe `gift_pkg` package provides the primitive building blocks for the GIFT block cipher. GIFT is a lightweight 64‑bit block cipher with a 128‑bit key. This package encapsulates the substitution–permutation network (SPN) components, round constants, and auxiliary rotation functions. The package is intended as a reusable resource for any module implementing GIFT encryption or decryption.\n\n## Functional Requirements\n\n### 1. Constants\n\nThe package shall define the following constant arrays:\n\n- **S‑box (GSBOX)** \n A 16‑entry lookup table mapping a 4‑bit nibble to another 4‑bit nibble. The mapping follows the GIFT S‑box specification. \n *Behavior*: For every possible 4‑bit input value (0 through 15), the S‑box shall return a unique 4‑bit output value.\n\n- **Bit Permutation (P_PERMUT)** \n A 64‑entry lookup table that defines how each bit of a 64‑bit state is rearranged. Each entry is a 6‑bit index (0–63) indicating the destination position of the corresponding input bit. The permutation must implement the GIFT bit‑permutation layer. \n *Behavior*: When applied, the bit at position `i` of the input state shall be moved to position `P_PERMUT[i]` of the output state.\n\n- **Round Constants (RC)** \n A 28‑entry array of 6‑bit round constants used during the GIFT key schedule or state update. The sequence is defined by the GIFT cipher specification. \n *Behavior*: Each round constant shall be a unique value in the range 0–63, and the sequence shall be exactly as specified for 28 rounds.\n\n### 2. Enumerated Types\n\n- **`round_index_e`** \n Defines four named round indices: `BASE_INPUT`, `BASE_1`, `BASE_2`, `BASE_3`. This type is used to parameterize round‑based operations.\n\n- **`round_op_e`** \n Defines two operation modes: `ROUND_FWD` (forward/encryption) and `ROUND_INV` (inverse/decryption). \n\nThese types shall be used by consuming modules to select the appropriate round index or direction. They shall not be directly interpreted by this package but are provided for interface consistency.\n\n### 3. Rotation Functions\n\nThe package shall provide two independent functions that perform right‑rotation of a 16‑bit word.\n\n- **`rot_right_16_2`** \n Rotates a 16‑bit input word to the right by exactly 2 bit positions. \n *Behavior*: The two least significant bits of the input shall become the two most significant bits of the output; all other bits shift right by 2.\n\n- **`rot_right_16_12`** \n Rotates a 16‑bit input word to the right by exactly 12 bit positions. \n *Behavior*: The twelve least significant bits of the input shall become the twelve most significant bits of the output; the four most significant bits shall become the four least significant bits of the output. \n (Equivalently, this is a left rotation by 4 positions.)\n\nBoth functions shall be purely combinational: the output shall be a deterministic function of the input with no side effects.\n\n### 4. Substitution Layer (S‑box Layer)\n\n- **`sbox_layer`** \n Applies the GIFT S‑box to every 4‑bit nibble of a 64‑bit input state. \n *Behavior*: The input state is partitioned into 16 consecutive 4‑bit nibbles (nibble 0 corresponds to bits [3:0], nibble 1 to bits [7:4], …, nibble 15 to bits [63:60]). For each nibble, the S‑box mapping (see constant `GSBOX`) shall be applied, producing a new nibble. The output state is formed by concatenating the transformed nibbles in the same order. \n The function shall be purely combinational and shall not alter the relative ordering of nibbles beyond the substitution itself.\n\n### 5. Permutation Layer\n\n- **`permut_layer`** \n Applies the GIFT bit‑permutation to a 64‑bit input state. \n *Behavior*: Each bit of the input state (indexed 0 for LSB, 63 for MSB) shall be moved to a new bit position in the output state as defined by the `P_PERMUT` array. Specifically, the bit from input position `k` shall become the bit at output position `P_PERMUT[k]`. All 64 bits shall be permuted in parallel. \n The function shall be purely combinational.\n\n### 6. Composability\n\nThe functions and constants are designed to be used together to implement the complete GIFT round transformation. For a forward round, the sequence is typically:\n1. (Optionally) XOR round key and round constant.\n2. Apply `sbox_layer`.\n3. Apply `permut_layer`.\n\nFor an inverse round, the sequence is reversed with the inverse of the permutation (not provided here) and the inverse S‑box.\n\n## Interface\n\nThe package does not expose ports, clocks, or resets; it provides only pure functions and constant data. Any module that includes this package may call the functions at any time. The functions shall be synthesizable (purely combinational) and suitable for both simulation and hardware synthesis.\n\n## Assumptions and Constraints\n\n- The package assumes a 64‑bit data path for the state.\n- All functions operate on logic or equivalent unsigned vectors. No signed arithmetic is used.\n- The S‑box and permutation tables are fixed and must not be altered after compilation.\n\n## Normative Statements\n\n- The package **must** be `include`‑ed or imported by any module that needs GIFT cryptographic primitives.\n- The S‑box lookup **must** be applied identically to all 16 nibbles of a 64‑bit state.\n- The bit permutation **must** follow the exact mapping defined in `P_PERMUT`.\n- The rotation functions **must** perform only the specified bit‑shift and must not introduce any data dependency beyond the input word.\n- The round constant array **must** be exactly 28 entries, each 6‑bits wide, in the stated order.\n\n## References\n\nThis package implements the GIFT block cipher as specified in the original GIFT paper (S. Banik et al., “GIFT: A Small Present – Towards Reaching the Limit of Lightweight Encryption,” CHES 2017). For complete cipher operation (key schedule, addition of round keys, inverse operations) designers should refer to that specification.", "commit_id": "7eedd7f4a14824897c727b5768ff4623ae58ce52", "timestamp": "2020-07-03T13:15:05+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "de133d516c299aa88ddbcbb851ec685875f1ab65", "pr_title": "Unpack and reduce Gift package arrays", "pr_body": "As requested in #993 .\r\n\r\nUnpacked arrays have been reversed to keep the same order.", "issue_title": "Hook up real Gift cipher core", "issue_body": "I hook up real gift cipher core. Currently there are some line errors in the gift module, but I will fix it in another PR.", "commit_message": "Improved Gift package", "fix_patch": "diff --git a/rtl/gift_pkg.sv b/rtl/gift_pkg.sv\nindex 4ee76d17f3..3becc1bae9 100644\n--- a/rtl/gift_pkg.sv\n+++ b/rtl/gift_pkg.sv\n@@ -4,26 +4,24 @@\n \n package gift_pkg;\n \n- localparam logic [15:0][3:0] GSBOX = {\n- 4'hE, 4'h8, 4'h0, 4'h5, 4'h7, 4'hB, 4'hD, 4'h2, 4'h9, 4'h3, 4'hF, 4'h6, 4'hC, 4'h4, 4'hA,\n- 4'h1};\n-\n- localparam logic [63:0][5:0] P_PERMUT = {\n- 6'd15, 6'd62, 6'd45, 6'd28, 6'd31, 6'd14, 6'd61, 6'd44, 6'd47, 6'd30, 6'd13, 6'd60, 6'd63,\n- 6'd46, 6'd29, 6'd12, 6'd11, 6'd58, 6'd41, 6'd24, 6'd27, 6'd10, 6'd57, 6'd40, 6'd43, 6'd26,\n- 6'd9 , 6'd56, 6'd59, 6'd42, 6'd25, 6'd8 , 6'd7 , 6'd54, 6'd37, 6'd20, 6'd23, 6'd6 , 6'd53,\n- 6'd36, 6'd39, 6'd22, 6'd5 , 6'd52, 6'd55, 6'd38, 6'd21, 6'd4 , 6'd3 , 6'd50, 6'd33, 6'd16,\n- 6'd19, 6'd2 , 6'd49, 6'd32, 6'd35, 6'd18, 6'd1 , 6'd48, 6'd51, 6'd34, 6'd17, 6'd0\n+ localparam logic [3:0] GSBOX[16] = '{\n+ 4'h1, 4'hA, 4'h4, 4'hC, 4'h6, 4'hF, 4'h3, 4'h9, 4'h2, 4'hD, 4'hB, 4'h7, 4'h5, 4'h0, 4'h8, 4'hE\n };\n \n- localparam logic [31:0][5:0] RC = {\n- 6'h20, 6'h10, 6'h28, 6'h14, 6'h2a, 6'h15, 6'h0a, 6'h25, 6'h32, 6'h19, 6'h0c, 6'h26, 6'h13,\n- 6'h09, 6'h04, 6'h22, 6'h11, 6'h08, 6'h24, 6'h12, 6'h29, 6'h34, 6'h1A, 6'h2D, 6'h36, 6'h1B,\n- 6'h0D, 6'h06, 6'h23, 6'h31, 6'h38, 6'h1C, 6'h2E, 6'h17, 6'h0B, 6'h05, 6'h02, 6'h21, 6'h30,\n- 6'h18, 6'h2C, 6'h16, 6'h2B, 6'h35, 6'h3A, 6'h1D, 6'h0E, 6'h27, 6'h33, 6'h39, 6'h3C, 6'h1E,\n- 6'h2F, 6'h37, 6'h3B, 6'h3D, 6'h3E, 6'h1F, 6'h0F, 6'h07, 6'h03, 6'h01\n+ localparam logic [5:0] P_PERMUT[64] = '{\n+ 6'd0, 6'd17, 6'd34, 6'd51, 6'd48, 6'd1, 6'd18, 6'd35, 6'd32, 6'd49, 6'd2, 6'd19, 6'd16, 6'd33,\n+ 6'd50, 6'd3, 6'd4, 6'd21, 6'd38, 6'd55, 6'd52, 6'd5, 6'd22, 6'd39, 6'd36, 6'd53, 6'd6, 6'd23,\n+ 6'd20, 6'd37, 6'd54, 6'd7, 6'd8, 6'd25, 6'd42, 6'd59, 6'd56, 6'd9, 6'd26, 6'd43, 6'd40, 6'd57,\n+ 6'd10, 6'd27, 6'd24, 6'd41, 6'd58, 6'd11, 6'd12, 6'd29, 6'd46, 6'd63, 6'd60, 6'd13, 6'd30,\n+ 6'd47, 6'd44, 6'd61, 6'd14, 6'd31, 6'd28, 6'd45, 6'd62, 6'd15\n };\n \n+ localparam logic [5:0] RC[28] = '{\n+ 6'h01, 6'h03, 6'h07, 6'h0F, 6'h1F, 6'h3E, 6'h3D, 6'h3B, 6'h37, 6'h2F, 6'h1E, 6'h3C, 6'h39,\n+ 6'h33, 6'h27, 6'h0E, 6'h1D, 6'h3A, 6'h35, 6'h2B, 6'h16, 6'h2C, 6'h18, 6'h30, 6'h21, 6'h02,\n+ 6'h05, 6'h0B\n+ };\n+ \n typedef enum logic [1:0] {\n BASE_INPUT,\n BASE_1,\n", "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\npackage gift_pkg;\n\n localparam logic [3:0] GSBOX[16] = '{\n 4'h1, 4'hA, 4'h4, 4'hC, 4'h6, 4'hF, 4'h3, 4'h9, 4'h2, 4'hD, 4'hB, 4'h7, 4'h5, 4'h0, 4'h8, 4'hE\n };\n\n localparam logic [5:0] P_PERMUT[64] = '{\n 6'd0, 6'd17, 6'd34, 6'd51, 6'd48, 6'd1, 6'd18, 6'd35, 6'd32, 6'd49, 6'd2, 6'd19, 6'd16, 6'd33,\n 6'd50, 6'd3, 6'd4, 6'd21, 6'd38, 6'd55, 6'd52, 6'd5, 6'd22, 6'd39, 6'd36, 6'd53, 6'd6, 6'd23,\n 6'd20, 6'd37, 6'd54, 6'd7, 6'd8, 6'd25, 6'd42, 6'd59, 6'd56, 6'd9, 6'd26, 6'd43, 6'd40, 6'd57,\n 6'd10, 6'd27, 6'd24, 6'd41, 6'd58, 6'd11, 6'd12, 6'd29, 6'd46, 6'd63, 6'd60, 6'd13, 6'd30,\n 6'd47, 6'd44, 6'd61, 6'd14, 6'd31, 6'd28, 6'd45, 6'd62, 6'd15\n };\n\n localparam logic [5:0] RC[28] = '{\n 6'h01, 6'h03, 6'h07, 6'h0F, 6'h1F, 6'h3E, 6'h3D, 6'h3B, 6'h37, 6'h2F, 6'h1E, 6'h3C, 6'h39,\n 6'h33, 6'h27, 6'h0E, 6'h1D, 6'h3A, 6'h35, 6'h2B, 6'h16, 6'h2C, 6'h18, 6'h30, 6'h21, 6'h02,\n 6'h05, 6'h0B\n };\n \n typedef enum logic [1:0] {\n BASE_INPUT,\n BASE_1,\n BASE_2,\n BASE_3\n } round_index_e;\n\n typedef enum logic {\n ROUND_FWD,\n ROUND_INV\n } round_op_e;\n\n function automatic logic [15:0] rot_right_16_2(logic [15:0] data_in);\n logic [15:0] data_out;\n for (int k = 0; k < 14; k++) begin\n data_out[k] = data_in[k+2];\n end\n\n data_out[14] = data_in[0];\n data_out[15] = data_in[1];\n\n return data_out;\n endfunction : rot_right_16_2\n\n function automatic logic [15:0] rot_right_16_12(logic [15:0] data_in);\n logic [15:0] data_out;\n for (int k = 0; k < 4; k++) begin\n data_out[k] = data_in[k+12];\n end\n\n for (int k = 0; k < 12; k++) begin\n data_out[k+4] = data_in[k];\n end\n\n return data_out;\n endfunction : rot_right_16_12\n\n function automatic logic [63:0] sbox_layer(logic [63:0] state_in);\n logic [63:0] state_out;\n for (int k = 0; k < 16; k++) begin\n state_out[k * 4 +: 4] = GSBOX[state_in[k * 4 +: 4]];\n end\n return state_out;\n endfunction : sbox_layer\n\n function automatic logic [63:0] permut_layer(logic [63:0] state_in);\n logic [63:0] state_out;\n for (int k = 0; k < 64; k++) begin\n state_out[P_PERMUT[k]] = state_in[k];\n end\n return state_out;\n endfunction : permut_layer\n\nendpackage : gift_pkg\n", "selected_doc_paths": []}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1054, "lang": "sv", "rtl_files": ["rtl/ibex_cs_registers.sv"], "spec": "# Behavioral Design Specification: `ibex_cs_registers`\n\n## 1. Overview\n\nThe `ibex_cs_registers` module implements all Control and Status Registers (CSRs) required by the RISC‑V Privileged Specification (version 1.11) for a single‑hart machine‑mode core with optional user mode and debug features. It also provides custom CSRs for runtime CPU configuration and security features.\n\nThe module is the central repository for machine‑level state used during exception and interrupt handling, debug, physical memory protection (PMP), performance monitoring, and CPU feature control.\n\n## 2. CSR Interface\n\n### 2.1 Access Protocol\n\nCSRs are accessed through a synchronous, SRAM‑like interface. Each access specifies:\n\n- An address (12‑bit CSR number)\n- Write data\n- An operation (read, write, set, clear)\n- An access enable signal\n\nThe module interprets the operation and applies the appropriate read or write logic. Write operations are combined with illegal‑access detection before updating any register.\n\n### 2.2 Illegal Access Detection\n\nThe module must detect three classes of illegal CSR access:\n\n1. **Address not implemented** – any CSR address that does not correspond to a defined register.\n2. **Insufficient privilege** – accessing a CSR whose address encoding requires a privilege level higher than the current machine privilege mode.\n3. **Write to read‑only register** – attempting to write a CSR whose address encoding indicates it is read‑only (e.g. `mip`).\n\nWhen an illegal access is detected, the module asserts an illegal‑instruction signal to the core pipeline, and no CSR state is modified. The access itself does not cause a trap; it is the core’s responsibility to raise an illegal instruction exception.\n\n### 2.3 Read‑Modify‑Write Operations\n\nThe module supports the `set` and `clear` operations defined by the RISC‑V instruction set:\n\n- **Set (CSRRS)**: The final write value is the bitwise OR of the current CSR value and the supplied data.\n- **Clear (CSRRC)**: The final write value is the current CSR value bitwise‑AND with the complement of the supplied data.\n- **Write (CSRRW)**: The supplied data is written directly.\n\nThese operations are performed before the write qualification (illegal checks, WARL constraints).\n\n## 3. Privilege Modes\n\nThe module maintains the current machine privilege level (`mstatus.MPP` for exception handling, and a dedicated internal register for the current running mode). Two privilege levels are supported:\n\n- **Machine Mode (M‑Mode)**: `0b11`\n- **User Mode (U‑Mode)**: `0b00`\n\nThe privilege level is broadcast to the instruction fetch, execute, and load‑store units. It is also used by the PMP and trigger logic.\n\nUpon reset, the core starts in M‑Mode.\n\n## 4. Interrupt and Exception Handling\n\n### 4.1 Save on Trap (Exception or Interrupt)\n\nWhen the core signals a trap (exception or interrupt) the module must:\n\n- Save the program counter (PC) of the appropriate pipeline stage into the `mepc` CSR.\n- Save the current privilege level into `mstatus.MPP`.\n- Save the previous `mstatus.MIE` into `mstatus.MPIE`.\n- Clear `mstatus.MIE` (disable interrupts).\n- Store the cause (exception code plus interrupt bit) into `mcause`.\n- Store the trap value into `mtval`.\n\nIf the trap is an interrupt (including NMI) the cause has the interrupt bit set.\n\nIf the trap is a debug entry (e.g. single‑step, debug request, trigger), the module must:\n\n- Save the privilege level at the time of entry into `dcsr.prv`.\n- Store the debug cause in `dcsr.cause`.\n- Save the PC into `dpc`.\n- **Not** modify `mepc`, `mcause`, `mtval`, or `mstatus`.\n\nAll traps cause a switch to M‑Mode, independent of the current mode.\n\n### 4.2 Save for Recoverable NMI\n\nWhen a non‑maskable interrupt (NMI) occurs while the core is already in an exception handler, the previous machine state (`mepc`, `mcause`, `mstatus.MPIE`, `mstatus.MPP`) is automatically saved into internal, non‑software‑accessible CSRs. This allows the NMI handler to return transparently after handling the NMI, without losing the original trap context.\n\n### 4.3 Return from Trap (MRET, DRET)\n\nOn execution of the MRET instruction:\n\n- The privilege level is restored from `mstatus.MPP`.\n- Interrupts are re‑enabled by copying `mstatus.MPIE` back to `mstatus.MIE`.\n- `mstatus.MPIE` is set to 1.\n- `mstatus.MPP` is set to U‑Mode (if returning from a normal exception).\n- If the core is in NMI mode, the saved non‑standard NMI state is restored into `mepc`, `mcause`, and `mstatus` instead.\n\nOn execution of the DRET instruction:\n\n- The privilege level is restored from `dcsr.prv`.\n- No modification is made to `mstatus` or other machine CSRs.\n\n### 4.4 Interrupt Pending and Enable\n\nThe module continuously qualifies incoming interrupt requests:\n\n- The `mip` CSR reflects the current state of all interrupt inputs (including fast interrupts) – it is purely combinational.\n- The `mie` CSR holds the enable bits for each interrupt source.\n- An interrupt is considered pending (and may be taken) when the corresponding bit in both `mip` and `mie` is set.\n- An aggregated “interrupt pending” output is provided for clock gating and early wake‑up from WFI.\n- A qualified interrupt vector is output for the core’s interrupt controller.\n\nAll interrupts (including NMI) are ignored when the core is in Debug Mode.\n\n### 4.5 NMI Handling\n\nThe NMI input has the highest interrupt priority (ID 31) and is not gated by `mstatus.MIE` or `mie`. It is, however, masked during Debug Mode. While servicing an NMI, all other interrupts are disabled. Nested NMIs are not supported.\n\n## 5. Debug Support\n\n### 5.1 Debug CSRs\n\nThe module implements the following debug‑specific CSRs:\n\n- `dcsr` (Debug Control and Status) – controls single‑step, EBREAK behavior, and records the entry cause and previous privilege level.\n- `dpc` (Debug PC) – holds the PC at the point of debug entry; updated on debug entry and restored on DRET.\n- `dscratch0`, `dscratch1` – general purpose scratch registers for the debug module.\n\nAll debug CSRs are only accessible when the core is in Debug Mode. Attempted access from any other mode triggers an illegal instruction exception.\n\n### 5.2 Debug Triggers (Optional)\n\nWhen enabled via the `DbgTriggerEn` parameter, the module provides:\n\n- `tselect` – trigger select register (only one trigger, always reads 0).\n- `tdata1` – trigger data register 1, indicating address/data match trigger type, debug‑only access, and an `execute` bit that enables instruction address matching.\n- `tdata2` – holds the instruction address to match.\n- `tdata3`, `mcontext`, `scontext` – present but always read 0 and ignore writes.\n\nA `trigger_match` output is asserted when the instruction fetch address matches the value in `tdata2` and the `execute` bit in `tdata1` is set. The match is performed before instruction execution.\n\nDebug‑only access is enforced: writes from M‑Mode (non‑debug) are ignored.\n\n## 6. Physical Memory Protection (PMP)\n\n### 6.1 Configuration\n\nWhen the `PMPEnable` parameter is set, the module instantiates PMP configuration and address registers for up to 16 regions (controlled by `PMPNumRegions`). Each region has:\n\n- A configuration byte (lock, mode, exec, write, read) stored in one of the `pmpcfg0`–`pmpcfg3` registers.\n- An address register (`pmpaddr0`–`pmpaddr15`).\n\nThe address field holds bits [33:2] of the region boundary. Read data may be masked according to the PMP granularity parameter (`PMPGranularity`):\n\n- If granularity is 0, the address is read unchanged.\n- If granularity ≥ 1, certain low‑order bits are forced to 0 or 1 depending on the address‑matching mode (TOR, NA4, NAPOT). NA4 mode is not available when granularity > 0 (it is treated as OFF).\n\n### 6.2 Locking\n\nWhen the `lock` bit of a configuration register is set, further writes to that configuration register are ignored. Additionally, writes to the associated address register may be blocked if the adjacent higher‑numbered region is locked and uses TOR mode.\n\n### 6.3 Tie‑offs When Disabled\n\nIf `PMPEnable` is 0, all PMP registers read as zero and all PMP outputs are tied low.\n\n## 7. Performance Counters\n\n### 7.1 Base Counters\n\nTwo counters are always present:\n\n- `mcycle` / `mcycleh` – counts every clock cycle (64‑bit).\n- `minstret` / `minstreth` – counts retired instructions (64‑bit).\n\nBoth can be written and read via CSR accesses.\n\n### 7.2 Event Counters (Optional)\n\nUp to 29 additional performance counters `mhpmcounter3`–`mhpmcounter31` (and their upper halves) are available, controlled by the `MHPMCounterNum` parameter. Each counter increment is gated by a corresponding bit in the `mcountinhibit` CSR.\n\nThe counting events are hardwired and include:\n\n- Cycles waiting for data memory\n- Cycles waiting for instruction fetches\n- Number of loads and stores\n- Number of jumps and branches (taken/not taken)\n- Number of compressed instructions retired\n- Cycles waiting for multiply or divide\n\nThe event selector CSRs `mhpmevent3`–`mhpmevent31` are fixed to reflect the hardwired mapping; they can be read but writes are ignored.\n\n### 7.3 Counter Control\n\nThe `mcountinhibit` CSR (address 0x320) controls which counters are enabled:\n\n- Bit 0 inhibits `mcycle`\n- Bit 2 inhibits `minstret`\n- Bits 3–31 inhibit counters `mhpmcounter3`–`mhpmcounter31`\n\nWhen a counter is inhibited, it stops incrementing. Writes to `mcountinhibit` affect the inhibit register, but bit 1 is forced to 0 and shall be read as 0.\n\nUnavailable counters (those beyond the configured number) always read zero and inhibit bits in `mcountinhibit` for those counters are forced to 1.\n\n### 7.4 Counter Width\n\nThe event counters are parameterizable in width (1–64 bits). Upper‑half registers (`mhpmcounterXh`) provide access to the high 32 bits when the counter width exceeds 32. For widths ≤ 32, the upper halves read zero.\n\n## 8. CPU Control and Security Features\n\n### 8.1 CPU Control Register (`cpuctrl`)\n\nA custom CSR at address 0x7C0 provides runtime control of optional CPU features:\n\n| Bit(s) | Field | Behaviour |\n|--------|-------|-----------|\n| 0 | `icache_enable` | Enables/disables the instruction cache (if `ICache` parameter set). |\n| 1 | `data_ind_timing` | Enables data‑independent timing for certain instructions (if `DataIndTiming` parameter set). |\n| 2 | `dummy_instr_en` | Enables insertion of dummy instructions (if `DummyInstructions` parameter set). |\n| 5:3 | `dummy_instr_mask` | Controls the maximum interval between dummy instructions (larger mask → more spread). |\n| 31:6 | Reserved | Read as zero. |\n\nIf a feature is not configured, the corresponding field reads as zero and writes are ignored.\n\n### 8.2 Secure Seed Register (`secureseed`)\n\nA custom CSR at address 0x7C1. Writes to this register trigger a re‑seeding of the internal LFSR used for dummy instruction insertion. Reads always return zero. This register is only writable when the `DummyInstructions` feature is enabled.\n\n## 9. Miscellaneous CSRs\n\n### 9.1 `mhartid`\n\nRead‑only CSR that returns the value of the hart ID input signal.\n\n### 9.2 `misa`\n\nWARL register that describes supported ISA extensions. All bits are hard‑wired based on configuration parameters (e.g. `RV32E`, `RV32M`). Writes have no effect.\n\n### 9.3 `mtvec`\n\nThe trap‑vector base address register. The lower two bits are fixed to `01` (vectored mode). The base address must be 256‑byte aligned (bits 7:2 forced to 0). On reset, `mtvec` is initialized to the boot address with the vectored mode indicator.\n\n### 9.4 `mscratch`\n\nGeneral purpose scratch register for machine mode.\n\n## 10. Reset Initialization\n\nAfter reset, the module initializes its state as follows:\n\n- Privilege mode: M‑Mode\n- `mstatus`: MIE = 0, MPIE = 1, MPP = U‑Mode, MPRV = 0, TW = 0\n- `mie`: all interrupt enables cleared\n- `mepc`, `mcause`, `mtval`: zero\n- `mtvec`: boot address with vectored mode (0x??00_0001)\n- `mscratch`: zero\n- `dcsr`: xdebugver = standard, cause = 0, prv = M‑Mode, step = 0, ebreakm/ebreaku = 0, other fields zero\n- `dpc`, `dscratch0`, `dscratch1`: zero\n- Non‑standard NMI backup CSRs: MPIE = 1, MPP = U‑Mode, epc and cause = 0\n- All PMP registers: zero\n- `mcountinhibit`: all zero (all counters enabled)\n- `mhpmevent` selectors: hardwired according to the event mapping table.\n- Debug trigger registers: zero\n- `cpuctrl` fields: zero (all features disabled)\n- Other reserved or unused fields: zero.\n\n## 11. Outputs to the Core Pipeline\n\nThe module provides the following status signals to other pipeline stages, reflecting the current CSR state:\n\n- Current privilege level (for ID, IF, and LSU stages)\n- `mstatus` TW and MIE bits\n- `mtvec` base address\n- `mepc` value\n- PMP configuration and address for each region\n- Debug control fields: single‑step enable, EBREAK‑in‑M/U‑Mode\n- Trigger match indication\n- Data independent timing enable\n- Dummy instruction enable and mask\n- ICache enable\n- Qualified interrupt vector and pending indication\n\nThese outputs must update synchronously with CSR writes and trap/return operations.\n\n## 12. Summary of WARL Constraints\n\nThe following CSRs have write‑any‑read‑legal behavior:\n\n- `mstatus`: Only supported MPP values (M‑Mode and U‑Mode); other values are converted to M‑Mode.\n- `mie`: Writes to unsupported interrupt bits are ignored; those bits always read 0.\n- `mtvec`: Lower 2 bits forced to `01`; bits 7:2 forced to 0.\n- `mepc`: LSB (bit 0) forced to 0.\n- `mcause`: Bits [5:4] are read‑only; only the interrupt bit and exception code bits [4:0] are writable.\n- `mtval`: No constraints.\n- PMP CFG registers: W = 1, R = 0 is reserved and treated as W = 0.\n- `dcsr`: xdebugver read‑only; nmip, mprven, stopcount, stoptime forced to 0; unsupported prv values converted to M‑Mode.\n- `tdata1`: All fields except `execute` are read‑only.\n- Debug trigger registers: accessible only in Debug Mode; otherwise write‑ignored and raise illegal insn.\n- `cpuctrl`: Feature bits conditional on parameters; reserved bits always read 0.\n\nWrites that violate these constraints are safe – the register value is updated with the legalized value, not ignored (unless explicitly stated otherwise, e.g. `tdata1` writes from M‑Mode).", "commit_id": "ac51db259d7ba09616b47cb372e528d45358d6db", "timestamp": "2020-08-05T08:17:34+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "7eaf0e4a6eba22c8e498de56174fbcbe2347ecd6", "pr_title": "[ibex/rtl] Fix pmpaddr write enable signal", "pr_body": "Updates the write enable for `pmpaddr[i]` CSRs to deny writes if\r\n`pmpcfg[i+1].lock == 1` and `pmpcfg[i+1].mode == TOR`, as per the\r\nspec.\r\nRelates to #1044.", "issue_title": "PMP TOR writes and behavior", "issue_body": "1. There appears to be a functional difference between [spike](https://github.com/riscv/riscv-isa-sim/blob/67b7edd0270d5d074136eb45474477d15aeee725/riscv/processor.cc#L809) and [ibex](https://github.com/lowRISC/ibex/blob/d7c13aa9045838e7b9751e87b6b4630e7893db39/rtl/ibex_cs_registers.sv#L828) in the interaction between L and A=TOR; riscv/riscv-isa-manual#545 endorsed the spike interpretation.\r\n\r\n2. Should https://github.com/lowRISC/ibex/blob/master/rtl/ibex_pmp.sv#L92-L93 be generating both ends of the TOR range from the same pmpaddr?", "commit_message": "[ibex/rtl] Fix pmpaddr write enable signal\n\nUpdates the write enable for `pmpaddr[i]` CSRs to deny writes if\n`pmpcfg[i+1].lock == 1` and `pmpcfg[i+1].mode == TOR`, as per the\nspec.", "fix_patch": "diff --git a/rtl/ibex_cs_registers.sv b/rtl/ibex_cs_registers.sv\nindex 6e5eaf4dc8..50d11073ac 100644\n--- a/rtl/ibex_cs_registers.sv\n+++ b/rtl/ibex_cs_registers.sv\n@@ -825,7 +825,7 @@ module ibex_cs_registers #(\n // --------------------------\n if (i < PMPNumRegions - 1) begin : g_lower\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n- (pmp_cfg[i+1].mode != PMP_MODE_TOR) &\n+ (~pmp_cfg[i+1].lock | (pmp_cfg[i+1].mode != PMP_MODE_TOR)) &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end else begin : g_upper\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n", "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 * Control and Status Registers\n *\n * Control and Status Registers (CSRs) following the RISC-V Privileged\n * Specification, draft version 1.11\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_cs_registers #(\n parameter bit DbgTriggerEn = 0,\n parameter bit DataIndTiming = 1'b0,\n parameter bit DummyInstructions = 1'b0,\n parameter bit ICache = 1'b0,\n parameter int unsigned MHPMCounterNum = 10,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit PMPEnable = 0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter bit RV32E = 0,\n parameter bit RV32M = 0\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n // Hart ID\n input logic [31:0] hart_id_i,\n\n // Privilege mode\n output ibex_pkg::priv_lvl_e priv_mode_id_o,\n output ibex_pkg::priv_lvl_e priv_mode_if_o,\n output ibex_pkg::priv_lvl_e priv_mode_lsu_o,\n output logic csr_mstatus_tw_o,\n\n // mtvec\n output logic [31:0] csr_mtvec_o,\n input logic csr_mtvec_init_i,\n input logic [31:0] boot_addr_i,\n\n // Interface to registers (SRAM like)\n input logic csr_access_i,\n input ibex_pkg::csr_num_e csr_addr_i,\n input logic [31:0] csr_wdata_i,\n input ibex_pkg::csr_op_e csr_op_i,\n input csr_op_en_i,\n output logic [31:0] csr_rdata_o,\n\n // interrupts\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 nmi_mode_i,\n output logic irq_pending_o, // interrupt request pending\n output ibex_pkg::irqs_t irqs_o, // interrupt requests qualified with mie\n output logic csr_mstatus_mie_o,\n output logic [31:0] csr_mepc_o,\n\n // PMP\n output ibex_pkg::pmp_cfg_t csr_pmp_cfg_o [PMPNumRegions],\n output logic [33:0] csr_pmp_addr_o [PMPNumRegions],\n\n // debug\n input logic debug_mode_i,\n input ibex_pkg::dbg_cause_e debug_cause_i,\n input logic debug_csr_save_i,\n output logic [31:0] csr_depc_o,\n output logic debug_single_step_o,\n output logic debug_ebreakm_o,\n output logic debug_ebreaku_o,\n output logic trigger_match_o,\n\n input logic [31:0] pc_if_i,\n input logic [31:0] pc_id_i,\n input logic [31:0] pc_wb_i,\n\n // CPU control bits\n output logic data_ind_timing_o,\n output logic dummy_instr_en_o,\n output logic [2:0] dummy_instr_mask_o,\n output logic dummy_instr_seed_en_o,\n output logic [31:0] dummy_instr_seed_o,\n output logic icache_enable_o,\n\n // Exception save/restore\n input logic csr_save_if_i,\n input logic csr_save_id_i,\n input logic csr_save_wb_i,\n input logic csr_restore_mret_i,\n input logic csr_restore_dret_i,\n input logic csr_save_cause_i,\n input ibex_pkg::exc_cause_e csr_mcause_i,\n input logic [31:0] csr_mtval_i,\n output logic illegal_csr_insn_o, // access to non-existent CSR,\n // with wrong priviledge level, or\n // missing write permissions\n // Performance Counters\n input logic instr_ret_i, // instr retired in ID/EX stage\n input logic instr_ret_compressed_i, // compressed instr retired\n input logic iside_wait_i, // core waiting for the iside\n input logic jump_i, // jump instr seen (j, jr, jal, jalr)\n input logic branch_i, // branch instr seen (bf, bnf)\n input logic branch_taken_i, // branch was taken\n input logic mem_load_i, // load from memory in this cycle\n input logic mem_store_i, // store to memory in this cycle\n input logic dside_wait_i, // core waiting for the dside\n input logic mul_wait_i, // core waiting for multiply\n input logic div_wait_i // core waiting for divide\n);\n\n import ibex_pkg::*;\n\n // misa\n localparam logic [31:0] MISA_VALUE =\n (0 << 0) // A - Atomic Instructions extension\n | (1 << 2) // C - Compressed extension\n | (0 << 3) // D - Double precision floating-point extension\n | (32'(RV32E) << 4) // E - RV32E base ISA\n | (0 << 5) // F - Single precision floating-point extension\n | (32'(!RV32E) << 8) // I - RV32I/64I/128I base ISA\n | (32'(RV32M) << 12) // M - Integer Multiply/Divide extension\n | (0 << 13) // N - User level interrupts supported\n | (0 << 18) // S - Supervisor mode implemented\n | (1 << 20) // U - User mode implemented\n | (0 << 23) // X - Non-standard extensions present\n | (32'(CSR_MISA_MXL) << 30); // M-XLEN\n\n typedef struct packed {\n logic mie;\n logic mpie;\n priv_lvl_e mpp;\n logic mprv;\n logic tw;\n } status_t;\n\n typedef struct packed {\n logic mpie;\n priv_lvl_e mpp;\n } status_stk_t;\n\n typedef struct packed {\n x_debug_ver_e xdebugver;\n logic [11:0] zero2;\n logic ebreakm;\n logic zero1;\n logic ebreaks;\n logic ebreaku;\n logic stepie;\n logic stopcount;\n logic stoptime;\n dbg_cause_e cause;\n logic zero0;\n logic mprven;\n logic nmip;\n logic step;\n priv_lvl_e prv;\n } dcsr_t;\n\n // CPU control register fields\n typedef struct packed {\n logic [31:6] unused_ctrl;\n logic [2:0] dummy_instr_mask;\n logic dummy_instr_en;\n logic data_ind_timing;\n logic icache_enable;\n } cpu_ctrl_t;\n\n // Interrupt and exception control signals\n logic [31:0] exception_pc;\n\n // CSRs\n priv_lvl_e priv_lvl_q, priv_lvl_d;\n status_t mstatus_q, mstatus_d;\n irqs_t mie_q, mie_d;\n logic [31:0] mscratch_q, mscratch_d;\n logic [31:0] mepc_q, mepc_d;\n logic [5:0] mcause_q, mcause_d;\n logic [31:0] mtval_q, mtval_d;\n logic [31:0] mtvec_q, mtvec_d;\n irqs_t mip;\n dcsr_t dcsr_q, dcsr_d;\n logic [31:0] depc_q, depc_d;\n logic [31:0] dscratch0_q, dscratch0_d;\n logic [31:0] dscratch1_q, dscratch1_d;\n\n // CSRs for recoverable NMIs\n // NOTE: these CSRS are nonstandard, see https://github.com/riscv/riscv-isa-manual/issues/261\n status_stk_t mstack_q, mstack_d;\n logic [31:0] mstack_epc_q, mstack_epc_d;\n logic [5:0] mstack_cause_q, mstack_cause_d;\n\n // PMP Signals\n logic [31:0] pmp_addr_rdata [PMP_MAX_REGIONS];\n logic [PMP_CFG_W-1:0] pmp_cfg_rdata [PMP_MAX_REGIONS];\n\n // Hardware performance monitor signals\n logic [31:0] mcountinhibit;\n // Only have mcountinhibit flops for counters that actually exist\n logic [MHPMCounterNum+3-1:0] mcountinhibit_d, mcountinhibit_q;\n logic mcountinhibit_we;\n\n // mhpmcounter flops are elaborated below providing only the precise number that is required based\n // on MHPMCounterNum/MHPMCounterWidth. This signal connects to the Q output of these flops\n // where they exist and is otherwise 0.\n logic [63:0] mhpmcounter [32];\n logic [31:0] mhpmcounter_we;\n logic [31:0] mhpmcounterh_we;\n logic [31:0] mhpmcounter_incr;\n logic [31:0] mhpmevent [32];\n logic [4:0] mhpmcounter_idx;\n\n // Debug / trigger registers\n logic [31:0] tselect_rdata;\n logic [31:0] tmatch_control_rdata;\n logic [31:0] tmatch_value_rdata;\n\n // CPU control bits\n cpu_ctrl_t cpuctrl_rdata, cpuctrl_wdata;\n\n // CSR update logic\n logic [31:0] csr_wdata_int;\n logic [31:0] csr_rdata_int;\n logic csr_we_int;\n logic csr_wreq;\n\n // Access violation signals\n logic illegal_csr;\n logic illegal_csr_priv;\n logic illegal_csr_write;\n\n logic [7:0] unused_boot_addr;\n logic [2:0] unused_csr_addr;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n\n /////////////\n // CSR reg //\n /////////////\n\n logic [$bits(csr_num_e)-1:0] csr_addr;\n assign csr_addr = {csr_addr_i};\n assign unused_csr_addr = csr_addr[7:5];\n assign mhpmcounter_idx = csr_addr[4:0];\n\n // See RISC-V Privileged Specification, version 1.11, Section 2.1\n assign illegal_csr_priv = (csr_addr[9:8] > {priv_lvl_q});\n assign illegal_csr_write = (csr_addr[11:10] == 2'b11) && csr_wreq;\n assign illegal_csr_insn_o = csr_access_i & (illegal_csr | illegal_csr_write | illegal_csr_priv);\n\n // mip CSR is purely combinational - must be able to re-enable the clock upon WFI\n assign mip.irq_software = irq_software_i;\n assign mip.irq_timer = irq_timer_i;\n assign mip.irq_external = irq_external_i;\n assign mip.irq_fast = irq_fast_i;\n\n // read logic\n always_comb begin\n csr_rdata_int = '0;\n illegal_csr = 1'b0;\n\n unique case (csr_addr_i)\n // mhartid: unique hardware thread id\n CSR_MHARTID: csr_rdata_int = hart_id_i;\n\n // mstatus: always M-mode, contains IE bit\n CSR_MSTATUS: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSTATUS_MIE_BIT] = mstatus_q.mie;\n csr_rdata_int[CSR_MSTATUS_MPIE_BIT] = mstatus_q.mpie;\n csr_rdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW] = mstatus_q.mpp;\n csr_rdata_int[CSR_MSTATUS_MPRV_BIT] = mstatus_q.mprv;\n csr_rdata_int[CSR_MSTATUS_TW_BIT] = mstatus_q.tw;\n end\n\n // misa\n CSR_MISA: csr_rdata_int = MISA_VALUE;\n\n // interrupt enable\n CSR_MIE: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mie_q.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mie_q.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mie_q.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mie_q.irq_fast;\n end\n\n CSR_MSCRATCH: csr_rdata_int = mscratch_q;\n\n // mtvec: trap-vector base address\n CSR_MTVEC: csr_rdata_int = mtvec_q;\n\n // mepc: exception program counter\n CSR_MEPC: csr_rdata_int = mepc_q;\n\n // mcause: exception cause\n CSR_MCAUSE: csr_rdata_int = {mcause_q[5], 26'b0, mcause_q[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: csr_rdata_int = mtval_q;\n\n // mip: interrupt pending\n CSR_MIP: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mip.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mip.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mip.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mip.irq_fast;\n end\n\n // PMP registers\n CSR_PMPCFG0: csr_rdata_int = {pmp_cfg_rdata[3], pmp_cfg_rdata[2],\n pmp_cfg_rdata[1], pmp_cfg_rdata[0]};\n CSR_PMPCFG1: csr_rdata_int = {pmp_cfg_rdata[7], pmp_cfg_rdata[6],\n pmp_cfg_rdata[5], pmp_cfg_rdata[4]};\n CSR_PMPCFG2: csr_rdata_int = {pmp_cfg_rdata[11], pmp_cfg_rdata[10],\n pmp_cfg_rdata[9], pmp_cfg_rdata[8]};\n CSR_PMPCFG3: csr_rdata_int = {pmp_cfg_rdata[15], pmp_cfg_rdata[14],\n pmp_cfg_rdata[13], pmp_cfg_rdata[12]};\n CSR_PMPADDR0: csr_rdata_int = pmp_addr_rdata[0];\n CSR_PMPADDR1: csr_rdata_int = pmp_addr_rdata[1];\n CSR_PMPADDR2: csr_rdata_int = pmp_addr_rdata[2];\n CSR_PMPADDR3: csr_rdata_int = pmp_addr_rdata[3];\n CSR_PMPADDR4: csr_rdata_int = pmp_addr_rdata[4];\n CSR_PMPADDR5: csr_rdata_int = pmp_addr_rdata[5];\n CSR_PMPADDR6: csr_rdata_int = pmp_addr_rdata[6];\n CSR_PMPADDR7: csr_rdata_int = pmp_addr_rdata[7];\n CSR_PMPADDR8: csr_rdata_int = pmp_addr_rdata[8];\n CSR_PMPADDR9: csr_rdata_int = pmp_addr_rdata[9];\n CSR_PMPADDR10: csr_rdata_int = pmp_addr_rdata[10];\n CSR_PMPADDR11: csr_rdata_int = pmp_addr_rdata[11];\n CSR_PMPADDR12: csr_rdata_int = pmp_addr_rdata[12];\n CSR_PMPADDR13: csr_rdata_int = pmp_addr_rdata[13];\n CSR_PMPADDR14: csr_rdata_int = pmp_addr_rdata[14];\n CSR_PMPADDR15: csr_rdata_int = pmp_addr_rdata[15];\n\n CSR_DCSR: begin\n csr_rdata_int = dcsr_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DPC: begin\n csr_rdata_int = depc_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH0: begin\n csr_rdata_int = dscratch0_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH1: begin\n csr_rdata_int = dscratch1_q;\n illegal_csr = ~debug_mode_i;\n end\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: csr_rdata_int = mcountinhibit;\n CSR_MHPMEVENT3,\n CSR_MHPMEVENT4, CSR_MHPMEVENT5, CSR_MHPMEVENT6, CSR_MHPMEVENT7,\n CSR_MHPMEVENT8, CSR_MHPMEVENT9, CSR_MHPMEVENT10, CSR_MHPMEVENT11,\n CSR_MHPMEVENT12, CSR_MHPMEVENT13, CSR_MHPMEVENT14, CSR_MHPMEVENT15,\n CSR_MHPMEVENT16, CSR_MHPMEVENT17, CSR_MHPMEVENT18, CSR_MHPMEVENT19,\n CSR_MHPMEVENT20, CSR_MHPMEVENT21, CSR_MHPMEVENT22, CSR_MHPMEVENT23,\n CSR_MHPMEVENT24, CSR_MHPMEVENT25, CSR_MHPMEVENT26, CSR_MHPMEVENT27,\n CSR_MHPMEVENT28, CSR_MHPMEVENT29, CSR_MHPMEVENT30, CSR_MHPMEVENT31: begin\n csr_rdata_int = mhpmevent[mhpmcounter_idx];\n end\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][31:0];\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][63:32];\n end\n\n // Debug triggers\n CSR_TSELECT: begin\n csr_rdata_int = tselect_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA1: begin\n csr_rdata_int = tmatch_control_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA2: begin\n csr_rdata_int = tmatch_value_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA3: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_MCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_SCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n\n // Custom CSR for controlling CPU features\n CSR_CPUCTRL: begin\n csr_rdata_int = {cpuctrl_rdata};\n end\n\n // Custom CSR for LFSR re-seeding (cannot be read)\n CSR_SECURESEED: begin\n csr_rdata_int = '0;\n end\n\n default: begin\n illegal_csr = 1'b1;\n end\n endcase\n end\n\n // write logic\n always_comb begin\n exception_pc = pc_id_i;\n\n priv_lvl_d = priv_lvl_q;\n mstatus_d = mstatus_q;\n mie_d = mie_q;\n mscratch_d = mscratch_q;\n mepc_d = mepc_q;\n mcause_d = mcause_q;\n mtval_d = mtval_q;\n mtvec_d = csr_mtvec_init_i ? {boot_addr_i[31:8], 6'b0, 2'b01} : mtvec_q;\n dcsr_d = dcsr_q;\n depc_d = depc_q;\n dscratch0_d = dscratch0_q;\n dscratch1_d = dscratch1_q;\n\n mstack_d = mstack_q;\n mstack_epc_d = mstack_epc_q;\n mstack_cause_d = mstack_cause_q;\n\n mcountinhibit_we = 1'b0;\n mhpmcounter_we = '0;\n mhpmcounterh_we = '0;\n\n if (csr_we_int) begin\n unique case (csr_addr_i)\n // mstatus: IE bit\n CSR_MSTATUS: begin\n mstatus_d = '{\n mie: csr_wdata_int[CSR_MSTATUS_MIE_BIT],\n mpie: csr_wdata_int[CSR_MSTATUS_MPIE_BIT],\n mpp: priv_lvl_e'(csr_wdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW]),\n mprv: csr_wdata_int[CSR_MSTATUS_MPRV_BIT],\n tw: csr_wdata_int[CSR_MSTATUS_TW_BIT]\n };\n // Convert illegal values to M-mode\n if ((mstatus_d.mpp != PRIV_LVL_M) && (mstatus_d.mpp != PRIV_LVL_U)) begin\n mstatus_d.mpp = PRIV_LVL_M;\n end\n end\n\n // interrupt enable\n CSR_MIE: begin\n mie_d.irq_software = csr_wdata_int[CSR_MSIX_BIT];\n mie_d.irq_timer = csr_wdata_int[CSR_MTIX_BIT];\n mie_d.irq_external = csr_wdata_int[CSR_MEIX_BIT];\n mie_d.irq_fast = csr_wdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW];\n end\n\n CSR_MSCRATCH: mscratch_d = csr_wdata_int;\n\n // mepc: exception program counter\n CSR_MEPC: mepc_d = {csr_wdata_int[31:1], 1'b0};\n\n // mcause\n CSR_MCAUSE: mcause_d = {csr_wdata_int[31], csr_wdata_int[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: mtval_d = csr_wdata_int;\n\n // mtvec\n // mtvec.MODE set to vectored\n // mtvec.BASE must be 256-byte aligned\n CSR_MTVEC: mtvec_d = {csr_wdata_int[31:8], 6'b0, 2'b01};\n\n CSR_DCSR: begin\n dcsr_d = csr_wdata_int;\n dcsr_d.xdebugver = XDEBUGVER_STD;\n // Change to PRIV_LVL_M if software writes an unsupported value\n if ((dcsr_d.prv != PRIV_LVL_M) && (dcsr_d.prv != PRIV_LVL_U)) begin\n dcsr_d.prv = PRIV_LVL_M;\n end\n\n // currently not supported:\n dcsr_d.nmip = 1'b0;\n dcsr_d.mprven = 1'b0;\n dcsr_d.stopcount = 1'b0;\n dcsr_d.stoptime = 1'b0;\n\n // forced to be zero\n dcsr_d.zero0 = 1'b0;\n dcsr_d.zero1 = 1'b0;\n dcsr_d.zero2 = 12'h0;\n end\n\n // dpc: debug program counter\n CSR_DPC: depc_d = {csr_wdata_int[31:1], 1'b0};\n\n CSR_DSCRATCH0: dscratch0_d = csr_wdata_int;\n CSR_DSCRATCH1: dscratch1_d = csr_wdata_int;\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: mcountinhibit_we = 1'b1;\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n mhpmcounter_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n mhpmcounterh_we[mhpmcounter_idx] = 1'b1;\n end\n\n default:;\n endcase\n end\n\n // exception controller gets priority over other writes\n unique case (1'b1)\n\n csr_save_cause_i: begin\n unique case (1'b1)\n csr_save_if_i: begin\n exception_pc = pc_if_i;\n end\n csr_save_id_i: begin\n exception_pc = pc_id_i;\n end\n csr_save_wb_i: begin\n exception_pc = pc_wb_i;\n end\n default:;\n endcase\n\n // Any exception, including debug mode, causes a switch to M-mode\n priv_lvl_d = PRIV_LVL_M;\n\n if (debug_csr_save_i) begin\n // all interrupts are masked\n // do not update cause, epc, tval, epc and status\n dcsr_d.prv = priv_lvl_q;\n dcsr_d.cause = debug_cause_i;\n depc_d = exception_pc;\n end else if (!debug_mode_i) begin\n // In debug mode, \"exceptions do not update any registers. That\n // includes cause, epc, tval, dpc and mstatus.\" [Debug Spec v0.13.2, p.39]\n mtval_d = csr_mtval_i;\n mstatus_d.mie = 1'b0; // disable interrupts\n // save current status\n mstatus_d.mpie = mstatus_q.mie;\n mstatus_d.mpp = priv_lvl_q;\n mepc_d = exception_pc;\n mcause_d = {csr_mcause_i};\n // save previous status for recoverable NMI\n mstack_d.mpie = mstatus_q.mpie;\n mstack_d.mpp = mstatus_q.mpp;\n mstack_epc_d = mepc_q;\n mstack_cause_d = mcause_q;\n end\n end // csr_save_cause_i\n\n csr_restore_dret_i: begin // DRET\n priv_lvl_d = dcsr_q.prv;\n end // csr_restore_dret_i\n\n csr_restore_mret_i: begin // MRET\n priv_lvl_d = mstatus_q.mpp;\n mstatus_d.mie = mstatus_q.mpie; // re-enable interrupts\n\n if (nmi_mode_i) begin\n // when returning from an NMI restore state from mstack CSR\n mstatus_d.mpie = mstack_q.mpie;\n mstatus_d.mpp = mstack_q.mpp;\n mepc_d = mstack_epc_q;\n mcause_d = mstack_cause_q;\n end else begin\n // otherwise just set mstatus.MPIE/MPP\n // See RISC-V Privileged Specification, version 1.11, Section 3.1.6.1\n mstatus_d.mpie = 1'b1;\n mstatus_d.mpp = PRIV_LVL_U;\n end\n end // csr_restore_mret_i\n\n default:;\n endcase\n end\n\n // CSR operation logic\n always_comb begin\n unique case (csr_op_i)\n CSR_OP_WRITE: csr_wdata_int = csr_wdata_i;\n CSR_OP_SET: csr_wdata_int = csr_wdata_i | csr_rdata_o;\n CSR_OP_CLEAR: csr_wdata_int = ~csr_wdata_i & csr_rdata_o;\n CSR_OP_READ: csr_wdata_int = csr_wdata_i;\n default: csr_wdata_int = csr_wdata_i;\n endcase\n end\n\n assign csr_wreq = csr_op_en_i &\n (csr_op_i inside {CSR_OP_WRITE,\n CSR_OP_SET,\n CSR_OP_CLEAR});\n\n // only write CSRs during one clock cycle\n assign csr_we_int = csr_wreq & ~illegal_csr_insn_o;\n\n assign csr_rdata_o = csr_rdata_int;\n\n // directly output some registers\n assign csr_mepc_o = mepc_q;\n assign csr_depc_o = depc_q;\n assign csr_mtvec_o = mtvec_q;\n\n assign csr_mstatus_mie_o = mstatus_q.mie;\n assign csr_mstatus_tw_o = mstatus_q.tw;\n assign debug_single_step_o = dcsr_q.step;\n assign debug_ebreakm_o = dcsr_q.ebreakm;\n assign debug_ebreaku_o = dcsr_q.ebreaku;\n\n // Qualify incoming interrupt requests in mip CSR with mie CSR for controller and to re-enable\n // clock upon WFI (must be purely combinational).\n assign irqs_o = mip & mie_q;\n assign irq_pending_o = |irqs_o;\n\n // actual registers\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n priv_lvl_q <= PRIV_LVL_M;\n mstatus_q <= '{\n mie: 1'b0,\n mpie: 1'b1,\n mpp: PRIV_LVL_U,\n mprv: 1'b0,\n tw: 1'b0\n };\n mie_q <= '0;\n mscratch_q <= '0;\n mepc_q <= '0;\n mcause_q <= '0;\n mtval_q <= '0;\n mtvec_q <= 32'h0000_0001;\n dcsr_q <= '{\n xdebugver: XDEBUGVER_STD,\n cause: DBG_CAUSE_NONE, // 3'h0\n prv: PRIV_LVL_M,\n default: '0\n };\n depc_q <= '0;\n dscratch0_q <= '0;\n dscratch1_q <= '0;\n\n mstack_q <= '{\n mpie: 1'b1,\n mpp: PRIV_LVL_U\n };\n mstack_epc_q <= '0;\n mstack_cause_q <= '0;\n\n end else begin\n // update CSRs\n priv_lvl_q <= priv_lvl_d;\n mstatus_q <= mstatus_d;\n mie_q <= mie_d;\n mscratch_q <= mscratch_d;\n mepc_q <= mepc_d;\n mcause_q <= mcause_d;\n mtval_q <= mtval_d;\n mtvec_q <= mtvec_d;\n dcsr_q <= dcsr_d;\n depc_q <= depc_d;\n dscratch0_q <= dscratch0_d;\n dscratch1_q <= dscratch1_d;\n\n mstack_q <= mstack_d;\n mstack_epc_q <= mstack_epc_d;\n mstack_cause_q <= mstack_cause_d;\n\n end\n end\n\n // Send current priv level to the decoder\n assign priv_mode_id_o = priv_lvl_q;\n // New instruction fetches need to account for updates to priv_lvl_q this cycle\n assign priv_mode_if_o = priv_lvl_d;\n // Load/store instructions must factor in MPRV for PMP checking\n assign priv_mode_lsu_o = mstatus_q.mprv ? mstatus_q.mpp : priv_lvl_q;\n\n // -----------------\n // PMP registers\n // -----------------\n\n if (PMPEnable) begin : g_pmp_registers\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n logic [31:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n logic [PMPNumRegions-1:0] pmp_addr_we;\n\n // Expanded / qualified register read data\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_exp_rd_data\n if (i < PMPNumRegions) begin : g_implemented_regions\n // Add in zero padding for reserved fields\n assign pmp_cfg_rdata[i] = {pmp_cfg[i].lock, 2'b00, pmp_cfg[i].mode,\n pmp_cfg[i].exec, pmp_cfg[i].write, pmp_cfg[i].read};\n\n // Address field read data depends on the current programmed mode and the granularity\n // See RISC-V Privileged Specification, version 1.11, Section 3.6.1\n if (PMPGranularity == 0) begin : g_pmp_g0\n // If G == 0, read data is unmodified\n assign pmp_addr_rdata[i] = pmp_addr[i];\n\n end else if (PMPGranularity == 1) begin : g_pmp_g1\n // If G == 1, bit [G-1] reads as zero in TOR or OFF mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n\n end else begin : g_pmp_g2\n // For G >= 2, bits are masked to one or zero depending on the mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n // In TOR or OFF mode, bits [G-1:0] must read as zero\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end else if (pmp_cfg[i].mode == PMP_MODE_NAPOT) begin\n // In NAPOT mode, bits [G-2:0] must read as one\n pmp_addr_rdata[i][PMPGranularity-2:0] = '1;\n end\n end\n end\n\n end else begin : g_other_regions\n // Non-implemented regions read as zero\n assign pmp_cfg_rdata[i] = '0;\n assign pmp_addr_rdata[i] = '0;\n end\n end\n\n // Write data calculation\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_pmp_csrs\n // -------------------------\n // Instantiate cfg registers\n // -------------------------\n assign pmp_cfg_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_CFG + (i[11:0] >> 2)));\n\n // Select the correct WDATA (each CSR contains 4 CFG fields, each with 2 RES bits)\n assign pmp_cfg_wdata[i].lock = csr_wdata_int[(i%4)*PMP_CFG_W+7];\n // NA4 mode is not selectable when G > 0, mode is treated as OFF\n always_comb begin\n unique case (csr_wdata_int[(i%4)*PMP_CFG_W+3+:2])\n 2'b00 : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n 2'b01 : pmp_cfg_wdata[i].mode = PMP_MODE_TOR;\n 2'b10 : pmp_cfg_wdata[i].mode = (PMPGranularity == 0) ? PMP_MODE_NA4:\n PMP_MODE_OFF;\n 2'b11 : pmp_cfg_wdata[i].mode = PMP_MODE_NAPOT;\n default : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n endcase\n end\n assign pmp_cfg_wdata[i].exec = csr_wdata_int[(i%4)*PMP_CFG_W+2];\n // W = 1, R = 0 is a reserved combination. For now, we force W to 0 if R == 0\n assign pmp_cfg_wdata[i].write = &csr_wdata_int[(i%4)*PMP_CFG_W+:2];\n assign pmp_cfg_wdata[i].read = csr_wdata_int[(i%4)*PMP_CFG_W];\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pmp_cfg[i] <= pmp_cfg_t'('b0);\n end else if (pmp_cfg_we[i]) begin\n pmp_cfg[i] <= pmp_cfg_wdata[i];\n end\n end\n\n // --------------------------\n // Instantiate addr registers\n // --------------------------\n if (i < PMPNumRegions - 1) begin : g_lower\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (~pmp_cfg[i+1].lock | (pmp_cfg[i+1].mode != PMP_MODE_TOR)) &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end else begin : g_upper\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pmp_addr[i] <= 'b0;\n end else if (pmp_addr_we[i]) begin\n pmp_addr[i] <= csr_wdata_int;\n end\n end\n assign csr_pmp_cfg_o[i] = pmp_cfg[i];\n assign csr_pmp_addr_o[i] = {pmp_addr[i],2'b00};\n end\n\n end else begin : g_no_pmp_tieoffs\n // Generate tieoffs when PMP is not configured\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_rdata\n assign pmp_addr_rdata[i] = '0;\n assign pmp_cfg_rdata[i] = '0;\n end\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_outputs\n assign csr_pmp_cfg_o[i] = pmp_cfg_t'(1'b0);\n assign csr_pmp_addr_o[i] = '0;\n end\n end\n\n //////////////////////////\n // Performance monitor //\n //////////////////////////\n\n // update enable signals\n always_comb begin : mcountinhibit_update\n if (mcountinhibit_we == 1'b1) begin\n // bit 1 must always be 0\n mcountinhibit_d = {csr_wdata_int[MHPMCounterNum+2:2], 1'b0, csr_wdata_int[0]};\n end else begin\n mcountinhibit_d = mcountinhibit_q;\n end\n end\n\n // event selection (hardwired) & control\n always_comb begin : gen_mhpmcounter_incr\n\n // Assign inactive counters (first to prevent latch inference)\n for (int unsigned i=0; i<32; i++) begin : gen_mhpmcounter_incr_inactive\n mhpmcounter_incr[i] = 1'b0;\n end\n\n // When adding or altering performance counter meanings and default\n // mappings please update dv/verilator/pcount/cpp/ibex_pcounts.cc\n // appropriately.\n //\n // active counters\n mhpmcounter_incr[0] = 1'b1; // mcycle\n mhpmcounter_incr[1] = 1'b0; // reserved\n mhpmcounter_incr[2] = instr_ret_i; // minstret\n mhpmcounter_incr[3] = dside_wait_i; // cycles waiting for data memory\n mhpmcounter_incr[4] = iside_wait_i; // cycles waiting for instr fetches\n mhpmcounter_incr[5] = mem_load_i; // num of loads\n mhpmcounter_incr[6] = mem_store_i; // num of stores\n mhpmcounter_incr[7] = jump_i; // num of jumps (unconditional)\n mhpmcounter_incr[8] = branch_i; // num of branches (conditional)\n mhpmcounter_incr[9] = branch_taken_i; // num of taken branches (conditional)\n mhpmcounter_incr[10] = instr_ret_compressed_i; // num of compressed instr\n mhpmcounter_incr[11] = mul_wait_i; // cycles waiting for multiply\n mhpmcounter_incr[12] = div_wait_i; // cycles waiting for divide\n end\n\n // event selector (hardwired, 0 means no event)\n always_comb begin : gen_mhpmevent\n\n // activate all\n for (int i=0; i<32; i++) begin : gen_mhpmevent_active\n mhpmevent[i] = '0;\n mhpmevent[i][i] = 1'b1;\n end\n\n // deactivate\n mhpmevent[1] = '0; // not existing, reserved\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmevent_inactive\n mhpmevent[i] = '0;\n end\n end\n\n // mcycle\n ibex_counter #(\n .CounterWidth(64)\n ) mcycle_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[0] & ~mcountinhibit[0]),\n .counterh_we_i(mhpmcounterh_we[0]),\n .counter_we_i(mhpmcounter_we[0]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[0])\n );\n\n // minstret\n ibex_counter #(\n .CounterWidth(64)\n ) minstret_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[2] & ~mcountinhibit[2]),\n .counterh_we_i(mhpmcounterh_we[2]),\n .counter_we_i(mhpmcounter_we[2]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[2])\n );\n\n // reserved:\n assign mhpmcounter[1] = '0;\n\n for (genvar cnt=0; cnt < MHPMCounterNum; cnt++) begin : gen_cntrs\n ibex_counter #(\n .CounterWidth(MHPMCounterWidth)\n ) mcounters_variable_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[cnt+3] & ~mcountinhibit[cnt+3]),\n .counterh_we_i(mhpmcounterh_we[cnt+3]),\n .counter_we_i(mhpmcounter_we[cnt+3]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[cnt+3])\n );\n end\n\n if(MHPMCounterNum < 29) begin : g_mcountinhibit_reduced\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounterh_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_incr;\n\n assign mcountinhibit = {{29-MHPMCounterNum{1'b1}}, mcountinhibit_q};\n // Lint tieoffs for unused bits\n assign unused_mhphcounter_we = mhpmcounter_we[31:MHPMCounterNum+3];\n assign unused_mhphcounterh_we = mhpmcounterh_we[31:MHPMCounterNum+3];\n assign unused_mhphcounter_incr = mhpmcounter_incr[31:MHPMCounterNum+3];\n end else begin : g_mcountinhibit_full\n assign mcountinhibit = mcountinhibit_q;\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n mcountinhibit_q <= '0;\n end else begin\n mcountinhibit_q <= mcountinhibit_d;\n end\n end\n\n /////////////////////////////\n // Debug trigger registers //\n /////////////////////////////\n\n if (DbgTriggerEn) begin : gen_trigger_regs\n // Register values\n logic tmatch_control_d, tmatch_control_q;\n logic [31:0] tmatch_value_d, tmatch_value_q;\n // Write enables\n logic tmatch_control_we;\n logic tmatch_value_we;\n\n // Write select\n assign tmatch_control_we = csr_we_int & debug_mode_i & (csr_addr_i == CSR_TDATA1);\n assign tmatch_value_we = csr_we_int & debug_mode_i & (csr_addr_i == CSR_TDATA2);\n\n // tmatch_control is enabled when the execute bit is set\n assign tmatch_control_d = tmatch_control_we ? csr_wdata_int[2] :\n tmatch_control_q;\n // tmatch_value has its own clock gate\n assign tmatch_value_d = csr_wdata_int[31:0];\n\n // Registers\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n tmatch_control_q <= 'b0;\n end else begin\n tmatch_control_q <= tmatch_control_d;\n end\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n tmatch_value_q <= 'b0;\n end else if (tmatch_value_we) begin\n tmatch_value_q <= tmatch_value_d;\n end\n end\n\n // Assign read data\n // TSELECT - only one supported\n assign tselect_rdata = 'b0;\n // TDATA0 - only support simple address matching\n assign tmatch_control_rdata = {4'h2, // type : address/data match\n 1'b1, // dmode : access from D mode only\n 6'h00, // maskmax : exact match only\n 1'b0, // hit : not supported\n 1'b0, // select : address match only\n 1'b0, // timing : match before execution\n 2'b00, // sizelo : match any access\n 4'h1, // action : enter debug mode\n 1'b0, // chain : not supported\n 4'h0, // match : simple match\n 1'b1, // m : match in m-mode\n 1'b0, // 0 : zero\n 1'b0, // s : not supported\n 1'b1, // u : match in u-mode\n tmatch_control_q, // execute : match instruction address\n 1'b0, // store : not supported\n 1'b0}; // load : not supported\n // TDATA1 - address match value only\n assign tmatch_value_rdata = tmatch_value_q;\n\n // Breakpoint matching\n // We match against the next address, as the breakpoint must be taken before execution\n assign trigger_match_o = tmatch_control_q & (pc_if_i[31:0] == tmatch_value_q[31:0]);\n\n end else begin : gen_no_trigger_regs\n assign tselect_rdata = 'b0;\n assign tmatch_control_rdata = 'b0;\n assign tmatch_value_rdata = 'b0;\n assign trigger_match_o = 'b0;\n end\n\n // CPU control fields\n assign cpuctrl_rdata.unused_ctrl = '0;\n // Cast register write data\n assign cpuctrl_wdata = cpu_ctrl_t'(csr_wdata_int);\n\n // Generate fixed time execution bit\n if (DataIndTiming) begin : gen_dit\n logic data_ind_timing_d, data_ind_timing_q;\n\n assign data_ind_timing_d = (csr_we_int && (csr_addr == CSR_CPUCTRL)) ?\n cpuctrl_wdata.data_ind_timing : data_ind_timing_q;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n data_ind_timing_q <= 1'b0; // disabled on reset\n end else begin\n data_ind_timing_q <= data_ind_timing_d;\n end\n end\n\n assign cpuctrl_rdata.data_ind_timing = data_ind_timing_q;\n\n end else begin : gen_no_dit\n // tieoff for the unused bit\n logic unused_dit;\n assign unused_dit = cpuctrl_wdata.data_ind_timing;\n\n // field will always read as zero if not configured\n assign cpuctrl_rdata.data_ind_timing = 1'b0;\n end\n\n assign data_ind_timing_o = cpuctrl_rdata.data_ind_timing;\n\n // Generate dummy instruction signals\n if (DummyInstructions) begin : gen_dummy\n logic dummy_instr_en_d, dummy_instr_en_q;\n logic [2:0] dummy_instr_mask_d, dummy_instr_mask_q;\n\n assign dummy_instr_en_d = (csr_we_int && (csr_addr == CSR_CPUCTRL)) ?\n cpuctrl_wdata.dummy_instr_en : dummy_instr_en_q;\n\n assign dummy_instr_mask_d = (csr_we_int && (csr_addr == CSR_CPUCTRL)) ?\n cpuctrl_wdata.dummy_instr_mask : dummy_instr_mask_q;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n dummy_instr_en_q <= 1'b0; // disabled on reset\n dummy_instr_mask_q <= 3'b000;\n end else begin\n dummy_instr_en_q <= dummy_instr_en_d;\n dummy_instr_mask_q <= dummy_instr_mask_d;\n end\n end\n\n assign cpuctrl_rdata.dummy_instr_en = dummy_instr_en_q;\n assign cpuctrl_rdata.dummy_instr_mask = dummy_instr_mask_q;\n // Signal a write to the seed register\n assign dummy_instr_seed_en_o = csr_we_int && (csr_addr == CSR_SECURESEED);\n assign dummy_instr_seed_o = csr_wdata_int;\n\n end else begin : gen_no_dummy\n // tieoff for the unused bit\n logic unused_dummy_en;\n logic [2:0] unused_dummy_mask;\n assign unused_dummy_en = cpuctrl_wdata.dummy_instr_en;\n assign unused_dummy_mask = cpuctrl_wdata.dummy_instr_mask;\n\n // field will always read as zero if not configured\n assign cpuctrl_rdata.dummy_instr_en = 1'b0;\n assign cpuctrl_rdata.dummy_instr_mask = 3'b000;\n assign dummy_instr_seed_en_o = 1'b0;\n assign dummy_instr_seed_o = '0;\n end\n\n assign dummy_instr_en_o = cpuctrl_rdata.dummy_instr_en;\n assign dummy_instr_mask_o = cpuctrl_rdata.dummy_instr_mask;\n\n // Generate icache enable bit\n if (ICache) begin : gen_icache_enable\n logic icache_enable_d, icache_enable_q;\n\n // Update the value when cpuctrl register is written\n assign icache_enable_d = (csr_we_int & (csr_addr == CSR_CPUCTRL)) ?\n cpuctrl_wdata.icache_enable : icache_enable_q;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n icache_enable_q <= 1'b0; // disabled on reset\n end else begin\n icache_enable_q <= icache_enable_d;\n end\n end\n\n assign cpuctrl_rdata.icache_enable = icache_enable_q;\n\n end else begin : gen_no_icache\n // tieoff for the unused icen bit\n logic unused_icen;\n assign unused_icen = cpuctrl_wdata.icache_enable;\n\n // icen field will always read as zero if ICache not configured\n assign cpuctrl_rdata.icache_enable = 1'b0;\n end\n\n assign icache_enable_o = cpuctrl_rdata.icache_enable;\n\n // tieoff for the currently unused bits of cpuctrl\n logic [31:6] unused_cpuctrl;\n assign unused_cpuctrl = {cpuctrl_wdata[31:6]};\n\n\n ////////////////\n // Assertions //\n ////////////////\n\n `ASSERT(IbexCsrOpEnRequiresAccess, csr_op_en_i |-> csr_access_i)\n\nendmodule\n", "selected_doc_paths": ["doc/cs_registers.rst", "doc/exception_interrupts.rst", "doc/debug.rst", "doc/pmp.rst", "doc/performance_counters.rst", "doc/security.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1037, "lang": "sv", "rtl_files": ["dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv"], "spec": "# Behavioral Specification: `core_ibex_instr_monitor_if`\n\n## Overview\n\nThis interface provides a non‑intrusive observation point into the Ibex core’s instruction pipeline. It exposes the state of the instruction currently present in the **ID stage** (Instruction Decode & Execute) on every rising edge of the system clock. The primary purpose is to enable simulation‑based monitors (e.g., in a UVM environment) to capture instruction flow, PC values, branch decisions, and error conditions without modifying the core’s internal logic.\n\nThe interface is designed to be instantiated in the testbench and connected directly to the core’s ID‑stage signals. It does **not** drive any signals into the core – it is purely an observation interface.\n\n## Functional Behavior\n\n### Clocking and Sampling\n\n- All observed signals shall be sampled synchronously on the **rising edge** of the supplied clock (`clk`).\n- The interface defines a clocking block (`instr_cb`) that defines the sampling point. All inputs to the monitor shall be evaluated at the positive clock edge.\n\n### Observed Signals\n\nThe following information is made available by the interface:\n\n1. **Instruction Valid** \n Indicates whether the instruction currently in the ID stage is valid. When asserted, the other fields (instruction word, PC, etc.) represent a meaningful instruction. When de‑asserted, the remaining fields may be invalid or stale.\n\n2. **Fetch Error** \n Signals whether the instruction fetch for this instruction encountered an error (e.g., a bus error on the instruction‑side memory interface). When asserted, the instruction is not executed; the core handles the error exception.\n\n3. **Compressed Instruction Flag** \n Indicates whether the original instruction fetched from memory was a 16‑bit compressed instruction (RISC‑V C‑extension). The core internally expands compressed instructions to 32‑bit form before decode, but the original compressed encoding is preserved for diagnostic purposes (e.g., to report in `mtval` on an illegal instruction exception).\n\n4. **Original Compressed Instruction** \n If the instruction was compressed, this field holds the original 16‑bit instruction word. For 32‑bit (uncompressed) instructions, the value of this field is undefined or zero.\n\n5. **Decompressed / Full Instruction** \n The 32‑bit instruction after any expansion (for compressed instructions) or the original 32‑bit word (for uncompressed instructions). This is the actual instruction that the decode and execute logic processes.\n\n6. **Program Counter (PC)** \n The address of the instruction as it enters the ID stage. This is the PC that was used when the instruction was fetched.\n\n7. **Branch Taken Indicator** \n For branch instructions, this flag is asserted when the branch condition was evaluated as **taken** (i.e., the core will redirect fetch to the branch target). For all other instruction types the value of this flag is not meaningful.\n\n8. **Branch Target Address** \n When a branch is taken (or for any control‑transfer instruction such as `jal` or `jalr`), this field holds the target address calculated by the branch/jump logic. For non‑taken branches and other instructions, the value is undefined.\n\n### Parameterisation\n\nThe interface is parameterised by a single value, `DATA_WIDTH` (default = 32). All address‑related fields (PC, branch target) and the decompressed instruction field shall have that width. The width of the compressed instruction field is always 16 bits, independent of `DATA_WIDTH`.\n\n## Usage Constraints\n\n- The interface is intended for **simulation and verification** only. It is not synthesizable.\n- It does **not** support the observation of **dummy instructions** that may be inserted into the pipeline (e.g., during stall handling or exception injection). If the core implements dummy instruction insertion, those instructions will **not** be captured by this monitor. The monitor will only reflect real instructions that reach the ID stage.\n\n## Connection Requirements\n\nTo function correctly, the interface must be connected to the following internal signals of the Ibex core (all within the ID stage):\n\n- Valid indicator\n- Fetch error status\n- Compressed instruction flag\n- Original compressed instruction (16‑bit)\n- Full decompressed instruction (DATA_WIDTH bits)\n- Program counter (DATA_WIDTH bits)\n- Branch taken flag\n- Branch target address (DATA_WIDTH bits)\n\nThese signals shall be driven by the core every cycle. The interface does not require any reset or enable signals; its outputs are combinational or registered depending on the core’s implementation, but the clocking block ensures they are sampled at the correct time.\n\n## Limitations\n\n- As noted, dummy instruction insertion is not tracked.\n- The interface only monitors the ID stage. It does **not** provide visibility into the IF stage, prefetch buffer, LSU, or writeback stage.\n- The monitor does **not** perform any filtering or qualification of instructions – it presents the raw state of the ID stage every cycle, even during stalls or multi‑cycle instruction execution. It is the responsibility of the testbench logic to interpret the data (e.g., only consider cycles where the valid indicator is asserted).", "commit_id": "7f9e704f362776ea544c318d82a33af5540c0145", "timestamp": "2020-07-17T18:15:14+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "1619ea2bc76e76e604f1b19710fdad208af95cbd", "pr_title": "[dv/ibex] Enhance riscv_debug_single_step test", "pr_body": "As pointed out by @tomroberts-lowrisc in #983, the current\r\nimplementation of riscv_debug_single_step_test cannot handle\r\nsingle-stepping over instructions that change the PC.\r\nThis PR aims to introduce this functionality, utilizing the\r\nnew instr_monitor_if.\r\n\r\nNow, if the core single-steps onto a branch/jump instruction, the\r\ntestbench will log the new target PC and compare it against the actual\r\ntarget address stored in `dpc`.\r\n\"Normal\" instructions are checked as usual by incrementing the\r\ninstruction's PC by either 2 or 4 (depending whether it is compressed)\r\nand comparing that against `dpc`.\r\n\r\nThis test passes successfully when combined with the RTL patch in #1034.", "issue_title": "[rtl] remove lsu_req_in_id signal", "issue_body": "This signal aimed to ensure loads/stores completed succesfully when an\r\ninterrupt or debug request appeared at the same time they were being\r\nexecuted when the writeback stage is present. However other stall logic\r\nsuffices for this purpose (debug/interrupt will wait for instruction to\r\nunstall in ID/EX which only happens once request has been sent out, then\r\nfirst instruction of debug/interrupt handler will stall until load/store\r\nresponse has been seen based on the generic stall logic for lsu requests\r\nin the writeback stage).\r\n\r\nWith this signal in place debug single stepping was broken around loads\r\nand stores.\r\n\r\nFixes #1029\r\n\r\nThis half undoes the fix from this PR: https://github.com/lowRISC/ibex/pull/928 which was in response to this OT issue: https://github.com/lowRISC/opentitan/issues/2405\r\n\r\nI'm happy to accept this is not the correct fix but I did have a play with interrupts appearing the same cycle as a load in simple system with various delays on gnt/rvalid and it all seems to work fine. The DV interrupt tests all looked fine. The test in OT that found the original bug was broken on main yesterday (chip_uart_tx_rx) but looking at the latest nightly it seems to be fixed, so I'll have another play with that. Also realised there's some other timing scenarios I can check out with simple system.\r\n", "commit_message": "[dv/ibex] Enhance riscv_debug_single_step test\n\nAs pointed out by @tomroberts-lowrisc in #983, the current\nimplementation of riscv_debug_single_step_test cannot handle\nsingle-stepping over instructions that change the PC.\nThis PR aims to introduce this functionality, utilizing the\nnew instr_monitor_if.\n\nNow, if the core single-steps onto a branch/jump instruction, the\ntestbench will log the new target PC and compare it against the actual\ntarget address stored in `dpc`.\n\"Normal\" instructions are checked as usual by incrementing the\ninstruction's PC by either 2 or 4 (depending whether it is compressed)\nand comparing that against `dpc`.", "fix_patch": "diff --git a/dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv b/dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv\nindex 2ad60ef3a7..171d0f593e 100644\n--- a/dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv\n+++ b/dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv\n@@ -6,7 +6,11 @@\n //\n // TODO: does not support dummy instruction insertion right now,\n // might have to revisit and update.\n-interface core_ibex_instr_monitor_if #(parameter DATA_WIDTH = 32);\n+interface core_ibex_instr_monitor_if #(\n+ parameter DATA_WIDTH = 32\n+) (\n+ input clk\n+);\n \n // ID stage\n logic valid_id;\n@@ -14,5 +18,19 @@ interface core_ibex_instr_monitor_if #(parameter DATA_WIDTH = 32);\n logic is_compressed_id;\n logic [15:0] instr_compressed_id;\n logic [DATA_WIDTH-1:0] instr_id;\n+ logic [DATA_WIDTH-1:0] pc_id;\n+ logic branch_taken_id;\n+ logic [DATA_WIDTH-1:0] branch_target_id;\n+\n+ clocking instr_cb @(posedge clk);\n+ input valid_id;\n+ input err_id;\n+ input is_compressed_id;\n+ input instr_compressed_id;\n+ input instr_id;\n+ input pc_id;\n+ input branch_taken_id;\n+ input branch_target_id;\n+ endclocking\n \n endinterface\n", "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 the instruction moving through the pipeline\n//\n// TODO: does not support dummy instruction insertion right now,\n// might have to revisit and update.\ninterface core_ibex_instr_monitor_if #(\n parameter DATA_WIDTH = 32\n) (\n input clk\n);\n\n // ID stage\n logic valid_id;\n logic err_id;\n logic is_compressed_id;\n logic [15:0] instr_compressed_id;\n logic [DATA_WIDTH-1:0] instr_id;\n logic [DATA_WIDTH-1:0] pc_id;\n logic branch_taken_id;\n logic [DATA_WIDTH-1:0] branch_target_id;\n\n clocking instr_cb @(posedge clk);\n input valid_id;\n input err_id;\n input is_compressed_id;\n input instr_compressed_id;\n input instr_id;\n input pc_id;\n input branch_taken_id;\n input branch_target_id;\n endclocking\n\nendinterface\n", "selected_doc_paths": ["doc/pipeline_details.rst", "doc/instruction_fetch.rst", "doc/instruction_decode_execute.rst", "doc/tracer.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1036, "lang": "sv", "rtl_files": ["rtl/ibex_decoder.sv"], "spec": "# Behavioral Specification: `ibex_decoder`\n\n## Overview\n\nThe `ibex_decoder` is a fully combinational module (with the exception of a single flip-flop for internal pipeline tracking) that decodes a 32-bit RISC-V instruction (already decompressed if necessary) and generates all control signals required by the processor’s execute stage. It determines the operation to perform, selects operands (register file, immediate values, PC), controls the ALU, multiplier/divider, load-store unit, CSR access, and branch/jump logic. It also identifies illegal instructions and asserts the appropriate exception signals.\n\nThe decoder shall operate in parallel with the execution pipeline and must be capable of completing its decoding within a single cycle. Multi-cycle instructions (e.g., certain bit-manipulation operations, multiplication, division) are flagged so that the controller can stall appropriately.\n\n## Configuration Parameters\n\nThe module behavior is parameterized by the following compile‑time values:\n\n- **RV32E** – When set, the register file is limited to 16 registers (x0–x15). The decoder must detect any instruction that uses a register address with bit 4 set (x16–x31) and treat it as illegal.\n- **RV32M** – When set, the M‑extension (multiply/divide) instructions are permitted; otherwise they are illegal.\n- **BranchTargetALU** – When set, the processor contains a separate adder for computing branch/jump targets in parallel with the main ALU. The decoder shall adjust its control signals accordingly to allow branch target calculation in the same cycle as condition evaluation.\n- **RV32B** – Determines the level of bit‑manipulation extension support: `RV32BNone` (disabled), `RV32BBalanced`, or `RV32BFull`. The decoder shall gate the legality of bit‑manipulation instructions based on this setting.\n\n## Instruction Decoding and Illegal Instruction Detection\n\nThe decoder examines the 7‑bit opcode (`instruction[6:0]`) and the `funct3`/`funct7` fields to identify the instruction type and its specific operation. For each valid instruction, it sets the appropriate control signals. If the instruction does not match any legal encoding (or is disabled by a parameter), an **illegal instruction** flag shall be asserted.\n\nThe decoder also receives a side‑input `illegal_c_insn_i`, which indicates that a preceding compressed instruction decoder already determined that the compressed instruction is illegal. When that input is asserted, the decoder shall unconditionally raise the illegal instruction flag.\n\nAdditionally, if **RV32E** is enabled and an instruction attempts to read or write a register with address ≥ 16 (i.e., bit 4 set), the decoder shall assert the illegal instruction flag and disable all write‑enable signals to the register file.\n\n## Immediate Generation\n\nThe decoder shall produce six immediate values, each derived from the current instruction word as defined by the RISC‑V specification:\n\n- **I‑type immediate** – sign‑extended to 32 bits from `inst[31:20]`.\n- **S‑type immediate** – sign‑extended from `{inst[31:25], inst[11:7]}`.\n- **B‑type immediate** – sign‑extended from `{inst[31], inst[7], inst[30:25], inst[11:8], 1'b0}`.\n- **U‑type immediate** – upper 20 bits from `inst[31:12]` placed in bits 31:12, lower bits zero.\n- **J‑type immediate** – sign‑extended from `{inst[19:12], inst[20], inst[30:21], 1'b0}`.\n- **Zimm (zero‑extended immediate)** – zero‑extended `rs1` field (`inst[19:15]`) used for CSR immediate operations.\n\n## Register File Control\n\nThe decoder controls two read ports and one write port of the register file:\n\n- **Read addresses** – The first read address (`rs1`) is normally `inst[19:15]`. However, for certain bit‑manipulation instructions that require a third source operand (`rs3`, `inst[31:27]`), the decoder shall select `rs3` instead of `rs1` in the second cycle of a multi‑cycle operation. This selection is pipelined using a single flip‑flop controlled by a `use_rs3` signal. The second read address is always `rs2` (`inst[24:20]`).\n- **Read enables** – The decoder shall assert read enables only when the instruction actually reads a register (i.e., whenever `rs1` or `rs2` is needed). For CSR‑immediate instructions that read from `x0` (which is always zero), the enable for `rs1` may be suppressed.\n- **Write address** – The destination register `rd` (`inst[11:7]`).\n- **Write enable** – Asserted for instructions that produce a result (e.g., ALU operations, loads, jumps that save PC+4). The write enable shall be suppressed if the instruction is illegal or if it would write to a non‑existent register in RV32E mode.\n\n## ALU Control\n\nThe decoder selects the ALU operation and its two operands:\n\n- **Operand A** – Can be a register value (`rs1`), the current PC, an immediate (zero or the `zimm`), or the `rs3` value (for multi‑cycle bit‑manip instructions).\n- **Operand B** – Can be a register value (`rs2`) or one of several immediate types (I, S, B, J, U, or the increment‑PC constant).\n- **ALU operation** – The decoder shall choose from the set of ALU functions (`ADD`, `SUB`, `SLL`, `SLT`, `SLTU`, `XOR`, `SRL`, `SRA`, `OR`, `AND`, `EQ`, `NE`, `LT`, `GE`, `LTU`, `GEU`, and all bit‑manipulation operations such as `SLO`, `ROL`, `ROR`, `CLZ`, `CTZ`, `PCNT`, `SEXTB`, `SEXTH`, `PACK`, `BFP`, `SHFL`, `UNSHFL`, `CMIX`, `CMOV`, `FSL`, `FSR`, `CRC32*`, `CLMUL*`, `BDEP`, `BEXT`, etc. – all as defined by the RV32I and RV32B specifications).\n- **Multi‑cycle flag** – For bit‑manipulation operations that require two cycles (e.g., rotations, CRC, bit‑deposit/extract, ternary operations), the decoder shall assert a multi‑cycle signal. During these operations, the controller must stall the pipeline for an extra cycle.\n\nFor instructions that use the ALU only for address calculation (loads, stores) the decoder sets the ALU to perform an addition of the base register and an immediate offset.\n\n## Branch and Jump Control\n\n- **Jump** – For `JAL` and `JALR` instructions, the decoder asserts a jump‑in‑decode signal. In the first cycle it may compute the jump target using the ALU (or a dedicated branch‑target ALU if `BranchTargetALU` is enabled). The jump target is used to set the PC. In the subsequent cycle, it computes PC+4 for the link register. If the branch‑target ALU is available, the target calculation occurs in the second cycle, and the link address is stored in the first cycle.\n- **Branch** – For `BEQ`, `BNE`, `BLT`, `BGE`, `BLTU`, `BGEU`, the decoder asserts a branch‑in‑decode signal. In the first cycle it evaluates the condition using the ALU. If the branch is taken (`branch_taken_i` input), in the second cycle it computes the target address (PC + B‑type immediate). Without a branch‑target ALU, both steps use the main ALU. With a branch‑target ALU, the target may be computed in parallel with condition evaluation, reducing the branch penalty.\n- **`FENCE.I`** – Implemented as an unconditional jump to the next PC (PC+2 or PC+4) after flushing the instruction cache and prefetch buffer. The decoder shall assert the jump signals and an `icache_inval` flag in the first cycle.\n\n## Load/Store Unit Control\n\n- **Store** – The decoder asserts `data_req` and `data_we`. It sets the data size according to `funct3` (byte, halfword, word). If `funct3[2]` is set (reserved encoding), the instruction is illegal. The address is computed by the ALU as `rs1 + S‑type immediate`.\n- **Load** – The decoder asserts `data_req` and selects the data size. Sign extension is controlled by `funct3[2]` (0 = sign‑extend, 1 = zero‑extend). For `lw` with `funct3[2]=1` (`lwu`), the instruction is illegal. The address is always `rs1 + I‑type immediate`.\n\n## Multiplier/Divider Control\n\nFor multiply and divide instructions (`MUL`, `MULH`, `MULHSU`, `MULHU`, `DIV`, `DIVU`, `REM`, `REMU`), the decoder shall compute the operation type and signed mode and output them to the multiplier/divider block. It also generates an enable signal (`mult_en` or `div_en`) that is asserted only if the instruction is legal and **RV32M** is enabled. These enable signals are suppressed when an illegal instruction is detected.\n\n## CSR Access\n\n- **CSR read/write/modify** – When the opcode is `SYSTEM` and `funct3` is non‑zero, the decoder shall assert `csr_access`. It selects the operation (`OP_READ`, `OP_WRITE`, `OP_SET`, `OP_CLEAR`) based on `funct3`. If the operation is `SET` or `CLEAR` and the immediate (`rs1`) is zero, the operation is silently reduced to a read (no write). If `funct3` is invalid, a `csr_illegal` flag is raised, which causes the instruction to be treated as illegal.\n- **System instructions** – For `funct3` == 0, the decoder decodes the 12‑bit `funct12` field to identify `ECALL`, `EBREAK`, `MRET`, `DRET`, `WFI`. These instructions are all privileged and shall set the corresponding exception or mode‑change flags. If `funct12` is not one of those, or if `rs1` or `rd` are non‑zero, the instruction is illegal.\n\n## Handling of Illegal Instructions\n\nWhen the decoder determines that an instruction is illegal (either by encoding, parameter enforcement, RV32E register violation, or compressed illegal input), it shall:\n\n- Suppress all write‑enable signals to the register file.\n- Suppress any load/store request.\n- Suppress any jump or branch signals.\n- Suppress any CSR access.\n- Suppress the multiplier/divider enable.\n- Assert the `illegal_insn_o` output.\n\nThe processor shall then take an illegal instruction exception.\n\n## Output Signal Summary\n\nThe decoder produces the following categories of outputs (signal names are intentionally omitted per specification style):\n\n- **Exception/mode flags** – `illegal_insn`, `ebrk_insn`, `mret_insn`, `dret_insn`, `ecall_insn`, `wfi_insn`.\n- **Jump/branch control** – Signals indicating a jump or branch is being processed, and a set signal to update the PC. Also a flag to invalidate the instruction cache.\n- **Immediates** – Six 32‑bit immediate values (I, S, B, U, J, Zimm).\n- **Register file** – Two read addresses, one write address, read enables, write enable, and a selection mux for write‑data source (ALU result, CSR read data, or load data).\n- **ALU** – Operation, operand source selects (A and B), immediate selects for ALU operands, and a multi‑cycle flag.\n- **Multiplier/Divider** – Operation, signed mode, and enables (multiply and divide).\n- **CSR** – Access flag and operation type.\n- **Load/Store** – Request, write enable, data type (size), sign extension.\n\n## Timing and Pipeline Considerations\n\nThe decoder is purely combinatorial except for a single register that remembers whether the next cycle should use `rs3` instead of `rs1`. This register is updated on every clock edge. All other outputs shall be stable within a single cycle and are intended to be used directly by the execution stage without additional pipeline delays. The decoder shall interpret the `instr_first_cycle_i` input to distinguish between the first and second cycles of multi‑cycle instructions (e.g., jumps, branches, and certain bit‑manipulation operations). For single‑cycle instructions, `instr_first_cycle_i` is asserted.\n\n## Compliance\n\nThe decoder must implement the RV32I base integer instruction set (including privileged `ECALL`, `EBREAK`, `MRET`, `DRET`, `WFI`), and conditionally the M‑extension (RV32M), and the B‑extension (RV32B at three levels). It shall comply with the ordering and behavior described in the RISC‑V Unprivileged and Privileged specifications, as well as the draft bit‑manipulation specification (version 0.92). All unused or reserved encodings must be treated as illegal.", "commit_id": "03a8ae70d68159d2b4a1c53d1d896a5751625a89", "timestamp": "2020-07-17T15:05:37+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "7f9e704f362776ea544c318d82a33af5540c0145", "pr_title": "[rtl] Make sure decoder also checks bits 26 and 25 for slli, srli, srai", "pr_body": "Previously, these bits were not checked when decoding `slli`, `srli` and `srai`, causing some illegal instruction encodings not to trigger an illegal instructions exception.\r\n\r\nThis resolves lowRISC/Ibex#1018.", "issue_title": "Illegal Instruction Exception not Raised - Shift Instructions", "issue_body": "**RISC-V Specification:**\r\n\r\n- _\"Chapter 2.4 of Unprivileged ISA\"_\r\n\r\n**Issue Description:**\r\n\r\nAn illegal instruction updates the register file and the associated csrs and executes normally without raising an illegal instruction exception.\r\n\r\n**Example:**\r\n\r\nThe instruction 32'h02005913 is decoded at time point t##0 with no illegal instruction being flagged, as illegal_insn_did is de-asserted.\r\n\r\n![Issue_0](https://user-images.githubusercontent.com/54367010/86763358-913b1200-c047-11ea-9bfd-afd69a9bbd53.PNG)\r\n\r\n---\r\n\r\nProduct: OneSpin 360 DV-Verify\r\nApp: RVV\r\nTool's version: 2020.1.3", "commit_message": "[rtl] Make sure decoder also checks bits 26 and 25 for slli, srli, srai\n\nPreviously, these bits were not checked when decoding slli, srli and\nsrai, causing some illegal instruction encodings not to trigger an\nillegal instructions exception.\n\nThis resolves lowRISC/Ibex#1018.\n\nSigned-off-by: Pirmin Vogel ", "fix_patch": "diff --git a/rtl/ibex_decoder.sv b/rtl/ibex_decoder.sv\nindex 3b2807eb8f..5788f8d59e 100644\n--- a/rtl/ibex_decoder.sv\n+++ b/rtl/ibex_decoder.sv\n@@ -348,7 +348,7 @@ module ibex_decoder #(\n \n 3'b001: begin\n unique case (instr[31:27])\n- 5'b0_0000: illegal_insn = 1'b0; // slli\n+ 5'b0_0000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // slli\n 5'b0_0100, // sloi\n 5'b0_1001, // sbclri\n 5'b0_0101, // sbseti\n@@ -385,7 +385,7 @@ module ibex_decoder #(\n end else begin\n unique case (instr[31:27])\n 5'b0_0000, // srli\n- 5'b0_1000: illegal_insn = 1'b0; // srai\n+ 5'b0_1000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // srai\n \n 5'b0_0100, // sroi\n 5'b0_1100, // rori\n", "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 * Instruction decoder\n *\n * This module is fully combinatorial, clock and reset are used for\n * assertions only.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_decoder #(\n parameter bit RV32E = 0,\n parameter bit RV32M = 1,\n parameter bit BranchTargetALU = 0,\n parameter ibex_pkg::rv32b_e RV32B = ibex_pkg::RV32BNone\n) (\n input logic clk_i,\n input logic rst_ni,\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 input logic branch_taken_i, // registered branch decision\n output logic icache_inval_o,\n\n // from IF-ID pipeline register\n input logic instr_first_cycle_i, // instruction read is in its first cycle\n input logic [31:0] instr_rdata_i, // instruction read from memory/cache\n input logic [31:0] instr_rdata_alu_i, // instruction read from memory/cache\n // replicated to ease fan-out)\n\n input logic illegal_c_insn_i, // compressed instruction decode failed\n\n // immediates\n output ibex_pkg::imm_a_sel_e imm_a_mux_sel_o, // immediate selection for operand a\n output ibex_pkg::imm_b_sel_e imm_b_mux_sel_o, // immediate selection for operand b\n output ibex_pkg::op_a_sel_e bt_a_mux_sel_o, // branch target selection operand a\n output ibex_pkg::imm_b_sel_e bt_b_mux_sel_o, // branch target selection 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_pkg::rf_wd_sel_e rf_wdata_sel_o, // RF write data selection\n output logic rf_we_o, // write enable for regfile\n output logic [4:0] rf_raddr_a_o,\n output logic [4:0] rf_raddr_b_o,\n output logic [4:0] rf_waddr_o,\n output logic rf_ren_a_o, // Instruction reads from RF addr A\n output logic rf_ren_b_o, // Instruction reads from RF addr B\n\n // ALU\n output ibex_pkg::alu_op_e alu_operator_o, // ALU operation selection\n output ibex_pkg::op_a_sel_e alu_op_a_mux_sel_o, // operand a selection: reg value, PC,\n // immediate or zero\n output ibex_pkg::op_b_sel_e alu_op_b_mux_sel_o, // operand b selection: reg value or\n // immediate\n output logic alu_multicycle_o, // ternary bitmanip instruction\n\n // MULT & DIV\n output logic mult_en_o, // perform integer multiplication\n output logic div_en_o, // perform integer division or remainder\n output logic mult_sel_o, // as above but static, for data muxes\n output logic div_sel_o, // as above but static, for data muxes\n\n output ibex_pkg::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_pkg::csr_op_e csr_op_o, // operation to perform on 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\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_pkg::*;\n\n logic illegal_insn;\n logic illegal_reg_rv32e;\n logic csr_illegal;\n logic rf_we;\n\n logic [31:0] instr;\n logic [31:0] instr_alu;\n // Source/Destination register instruction index\n logic [4:0] instr_rs1;\n logic [4:0] instr_rs2;\n logic [4:0] instr_rs3;\n logic [4:0] instr_rd;\n\n logic use_rs3_d;\n logic use_rs3_q;\n\n csr_op_e csr_op;\n\n opcode_e opcode;\n opcode_e opcode_alu;\n\n // To help timing the flops containing the current instruction are replicated to reduce fan-out.\n // instr_alu is used to determine the ALU control logic and associated operand/imm select signals\n // as the ALU is often on the more critical timing paths. instr is used for everything else.\n assign instr = instr_rdata_i;\n assign instr_alu = instr_rdata_alu_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_rs1 }; // rs1\n\n // the use of rs3 is known one cycle ahead.\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n use_rs3_q <= 1'b0;\n end else begin\n use_rs3_q <= use_rs3_d;\n end\n end\n\n // source registers\n assign instr_rs1 = instr[19:15];\n assign instr_rs2 = instr[24:20];\n assign instr_rs3 = instr[31:27];\n assign rf_raddr_a_o = (use_rs3_q & ~instr_first_cycle_i) ? instr_rs3 : instr_rs1; // rs3 / rs1\n assign rf_raddr_b_o = instr_rs2; // rs2\n\n // destination register\n assign instr_rd = instr[11:7];\n assign rf_waddr_o = instr_rd; // rd\n\n ////////////////////\n // Register check //\n ////////////////////\n if (RV32E) begin : gen_rv32e_reg_check_active\n assign illegal_reg_rv32e = ((rf_raddr_a_o[4] & (alu_op_a_mux_sel_o == OP_A_REG_A)) |\n (rf_raddr_b_o[4] & (alu_op_b_mux_sel_o == OP_B_REG_B)) |\n (rf_waddr_o[4] & rf_we));\n end else begin : gen_rv32e_reg_check_inactive\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_rs1 == '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 icache_inval_o = 1'b0;\n\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n\n rf_wdata_sel_o = RF_WD_EX;\n rf_we = 1'b0;\n rf_ren_a_o = 1'b0;\n rf_ren_b_o = 1'b0;\n\n csr_access_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_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\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n jump_in_dec_o = 1'b1;\n\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n if (instr[14:12] != 3'b0) begin\n illegal_insn = 1'b1;\n end\n\n rf_ren_a_o = 1'b1;\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,\n 3'b001,\n 3'b100,\n 3'b101,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n default: illegal_insn = 1'b1;\n endcase\n\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n end\n\n ////////////////\n // Load/store //\n ////////////////\n\n OPCODE_STORE: begin\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n data_req_o = 1'b1;\n data_we_o = 1'b1;\n\n if (instr[14]) begin\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: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_LOAD: begin\n rf_ren_a_o = 1'b1;\n data_req_o = 1'b1;\n data_type_o = 2'b00;\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(u)\n 2'b01: data_type_o = 2'b01; // lh(u)\n 2'b10: begin\n data_type_o = 2'b00; // lw\n if (instr[14]) begin\n illegal_insn = 1'b1; // lwu does not exist\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n /////////\n // ALU //\n /////////\n\n OPCODE_LUI: begin // Load Upper Immediate\n rf_we = 1'b1;\n end\n\n OPCODE_AUIPC: begin // Add Upper Immediate to PC\n rf_we = 1'b1;\n end\n\n OPCODE_OP_IMM: begin // Register-Immediate ALU Operations\n rf_ren_a_o = 1'b1;\n rf_we = 1'b1;\n\n unique case (instr[14:12])\n 3'b000,\n 3'b010,\n 3'b011,\n 3'b100,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n\n 3'b001: begin\n unique case (instr[31:27])\n 5'b0_0000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // slli\n 5'b0_0100, // sloi\n 5'b0_1001, // sbclri\n 5'b0_0101, // sbseti\n 5'b0_1101: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sbinvi\n 5'b0_0001: if (instr[26] == 1'b0) begin\n illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // shfl\n end else begin\n illegal_insn = 1'b1;\n end\n 5'b0_1100: begin\n unique case(instr[26:20])\n 7'b000_0000, // clz\n 7'b000_0001, // ctz\n 7'b000_0010, // pcnt\n 7'b000_0100, // sext.b\n 7'b000_0101: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sext.h\n 7'b001_0000, // crc32.b\n 7'b001_0001, // crc32.h\n 7'b001_0010, // crc32.w\n 7'b001_1000, // crc32c.b\n 7'b001_1001, // crc32c.h\n 7'b001_1010: illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // crc32c.w\n\n default: illegal_insn = 1'b1;\n endcase\n end\n default : illegal_insn = 1'b1;\n endcase\n end\n\n 3'b101: begin\n if (instr[26]) begin\n illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // fsri\n end else begin\n unique case (instr[31:27])\n 5'b0_0000, // srli\n 5'b0_1000: illegal_insn = (instr[26:25] == 2'b00) ? 1'b0 : 1'b1; // srai\n\n 5'b0_0100, // sroi\n 5'b0_1100, // rori\n 5'b0_1001: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // sbexti\n\n 5'b0_1101: begin\n if ((RV32B == RV32BFull)) begin\n illegal_insn = 1'b0; // grevi\n end else begin\n unique case (instr[24:20])\n 5'b11111, // rev\n 5'b11000: illegal_insn = (RV32B == RV32BBalanced) ? 1'b0 : 1'b1; // rev8\n\n default: illegal_insn = 1'b1;\n endcase\n end\n end\n 5'b0_0101: begin\n if ((RV32B == RV32BFull)) begin\n illegal_insn = 1'b0; // gorci\n end else if (instr[24:20] == 5'b00111) begin\n illegal_insn = (RV32B == RV32BBalanced) ? 1'b0 : 1'b1; // orc.b\n end\n end\n 5'b0_0001: begin\n if (instr[26] == 1'b0) begin\n illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // unshfl\n end else begin\n illegal_insn = 1'b1;\n end\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_OP: begin // Register-Register ALU operation\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n rf_we = 1'b1;\n if ({instr[26], instr[13:12]} == {1'b1, 2'b01}) begin\n illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // cmix / cmov / fsl / fsr\n end else begin\n unique case ({instr[31:25], instr[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000},\n {7'b010_0000, 3'b000},\n {7'b000_0000, 3'b010},\n {7'b000_0000, 3'b011},\n {7'b000_0000, 3'b100},\n {7'b000_0000, 3'b110},\n {7'b000_0000, 3'b111},\n {7'b000_0000, 3'b001},\n {7'b000_0000, 3'b101},\n {7'b010_0000, 3'b101}: illegal_insn = 1'b0;\n\n // RV32B zbb\n {7'b010_0000, 3'b111}, // andn\n {7'b010_0000, 3'b110}, // orn\n {7'b010_0000, 3'b100}, // xnor\n {7'b001_0000, 3'b001}, // slo\n {7'b001_0000, 3'b101}, // sro\n {7'b011_0000, 3'b001}, // rol\n {7'b011_0000, 3'b101}, // ror\n {7'b000_0101, 3'b100}, // min\n {7'b000_0101, 3'b101}, // max\n {7'b000_0101, 3'b110}, // minu\n {7'b000_0101, 3'b111}, // maxu\n {7'b000_0100, 3'b100}, // pack\n {7'b010_0100, 3'b100}, // packu\n {7'b000_0100, 3'b111}, // packh\n // RV32B zbs\n {7'b010_0100, 3'b001}, // sbclr\n {7'b001_0100, 3'b001}, // sbset\n {7'b011_0100, 3'b001}, // sbinv\n {7'b010_0100, 3'b101}, // sbext\n // RV32B zbf\n {7'b010_0100, 3'b111}: illegal_insn = (RV32B != RV32BNone) ? 1'b0 : 1'b1; // bfp\n // RV32B zbe\n {7'b010_0100, 3'b110}, // bdep\n {7'b000_0100, 3'b110}, // bext\n // RV32B zbp\n {7'b011_0100, 3'b101}, // grev\n {7'b001_0100, 3'b101}, // gorc\n {7'b000_0100, 3'b001}, // shfl\n {7'b000_0100, 3'b101}, // unshfl\n // RV32B zbc\n {7'b000_0101, 3'b001}, // clmul\n {7'b000_0101, 3'b010}, // clmulr\n {7'b000_0101, 3'b011}: illegal_insn = (RV32B == RV32BFull) ? 1'b0 : 1'b1; // clmulh\n\n // RV32M instructions\n {7'b000_0001, 3'b000}: begin // mul\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b01;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b100}: begin // div\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b101}: begin // divu\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b110}: begin // rem\n multdiv_operator_o = MD_OP_REM;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b111}: begin // remu\n multdiv_operator_o = MD_OP_REM;\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. This may not be correct\n // in a system with caches and should be revisited.\n // FENCE.I will flush the IF stage and prefetch buffer (or ICache) but nothing else.\n unique case (instr[14:12])\n 3'b000: begin\n rf_we = 1'b0;\n end\n 3'b001: begin\n // FENCE.I is implemented as a jump to the next PC, this gives the required flushing\n // behaviour (iside prefetch buffer flushed and response to any outstanding iside\n // requests will be ignored).\n // If present, the ICache will also be flushed.\n jump_in_dec_o = 1'b1;\n\n rf_we = 1'b0;\n\n if (instr_first_cycle_i) begin\n jump_set_o = 1'b1;\n icache_inval_o = 1'b1;\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr[14:12] == 3'b000) begin\n // non CSR related SYSTEM instructions\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_rs1 != 5'b0 || instr_rd != 5'b0) 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 rf_wdata_sel_o = RF_WD_CSR;\n rf_we = 1'b1;\n\n if (~instr[14]) begin\n rf_ren_a_o = 1'b1;\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 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, PC\n // NOTE: instructions can also be detected to be illegal inside the CSRs (upon accesses with\n // insufficient privileges), or when accessing non-available registers in RV32E,\n // these cases are not handled here\n if (illegal_insn) begin\n rf_we = 1'b0;\n data_req_o = 1'b0;\n data_we_o = 1'b0;\n jump_in_dec_o = 1'b0;\n jump_set_o = 1'b0;\n branch_in_dec_o = 1'b0;\n csr_access_o = 1'b0;\n end\n end\n\n /////////////////////////////\n // Decoder for ALU control //\n /////////////////////////////\n\n always_comb begin\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 bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_I;\n\n\n opcode_alu = opcode_e'(instr_alu[6:0]);\n\n use_rs3_d = 1'b0;\n alu_multicycle_o = 1'b0;\n mult_sel_o = 1'b0;\n div_sel_o = 1'b0;\n\n unique case (opcode_alu)\n\n ///////////\n // Jumps //\n ///////////\n\n OPCODE_JAL: begin // Jump and Link\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_J;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_REG_A;\n bt_b_mux_sel_o = IMM_B_I;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_BRANCH: begin // Branch\n // Check branch condition selection\n unique case (instr_alu[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: ;\n endcase\n\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n // Not-taken branch will jump to next instruction (used in secure mode)\n bt_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n end\n\n // Without branch target ALU, a branch is a two-stage operation using the Main ALU in both\n // stages\n if (instr_first_cycle_i) begin\n // First evaluate the 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 // Then calculate jump target\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n // Not-taken branch will jump to next instruction (used in secure mode)\n imm_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n alu_operator_o = ALU_ADD;\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 alu_operator_o = ALU_ADD;\n\n if (!instr_alu[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\n end\n\n OPCODE_LOAD: begin\n alu_op_a_mux_sel_o = OP_A_REG_A;\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 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 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 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\n unique case (instr_alu[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 if (RV32B != RV32BNone) begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n 5'b0_0100: alu_operator_o = ALU_SLO; // Shift Left Ones by Immediate\n 5'b0_1001: alu_operator_o = ALU_SBCLR; // Clear bit specified by immediate\n 5'b0_0101: alu_operator_o = ALU_SBSET; // Set bit specified by immediate\n 5'b0_1101: alu_operator_o = ALU_SBINV; // Invert bit specified by immediate.\n // Shuffle with Immediate Control Value\n 5'b0_0001: if (instr_alu[26] == 0) alu_operator_o = ALU_SHFL;\n 5'b0_1100: begin\n unique case (instr_alu[26:20])\n 7'b000_0000: alu_operator_o = ALU_CLZ; // clz\n 7'b000_0001: alu_operator_o = ALU_CTZ; // ctz\n 7'b000_0010: alu_operator_o = ALU_PCNT; // pcnt\n 7'b000_0100: alu_operator_o = ALU_SEXTB; // sext.b\n 7'b000_0101: alu_operator_o = ALU_SEXTH; // sext.h\n 7'b001_0000: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_B; // crc32.b\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_0001: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_H; // crc32.h\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_0010: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32_W; // crc32.w\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1000: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_B; // crc32c.b\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1001: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_H; // crc32c.h\n alu_multicycle_o = 1'b1;\n end\n end\n 7'b001_1010: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_CRC32C_W; // crc32c.w\n alu_multicycle_o = 1'b1;\n end\n end\n default: ;\n endcase\n end\n\n default: ;\n endcase\n end else begin\n alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n end\n end\n\n 3'b101: begin\n if (RV32B != RV32BNone) begin\n if (instr_alu[26] == 1'b1) begin\n alu_operator_o = ALU_FSR;\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end else begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n 5'b0_1000: alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n 5'b0_0100: alu_operator_o = ALU_SRO; // Shift Right Ones by Immediate\n 5'b0_1001: alu_operator_o = ALU_SBEXT; // Extract bit specified by immediate.\n 5'b0_1100: begin\n alu_operator_o = ALU_ROR; // Rotate Right by Immediate\n alu_multicycle_o = 1'b1;\n end\n 5'b0_1101: alu_operator_o = ALU_GREV; // General Reverse with Imm Control Val\n 5'b0_0101: alu_operator_o = ALU_GORC; // General Or-combine with Imm Control Val\n // Unshuffle with Immediate Control Value\n 5'b0_0001: begin\n if (RV32B == RV32BFull) begin\n if (instr_alu[26] == 1'b0) alu_operator_o = ALU_UNSHFL;\n end\n end\n default: ;\n endcase\n end\n\n end else begin\n if (instr_alu[31:27] == 5'b0_0000) begin\n alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n end else if (instr_alu[31:27] == 5'b0_1000) begin\n alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n end\n end\n end\n\n default: ;\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\n if (instr_alu[26]) begin\n if (RV32B != RV32BNone) begin\n unique case ({instr_alu[26:25], instr_alu[14:12]})\n {2'b11, 3'b001}: begin\n alu_operator_o = ALU_CMIX; // cmix\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b11, 3'b101}: begin\n alu_operator_o = ALU_CMOV; // cmov\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b10, 3'b001}: begin\n alu_operator_o = ALU_FSL; // fsl\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n {2'b10, 3'b101}: begin\n alu_operator_o = ALU_FSR; // fsr\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3_d = 1'b1;\n end else begin\n use_rs3_d = 1'b0;\n end\n end\n default: ;\n endcase\n end\n end else begin\n unique case ({instr_alu[31:25], instr_alu[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000}: alu_operator_o = ALU_ADD; // Add\n {7'b010_0000, 3'b000}: alu_operator_o = ALU_SUB; // Sub\n {7'b000_0000, 3'b010}: alu_operator_o = ALU_SLT; // Set Lower Than\n {7'b000_0000, 3'b011}: alu_operator_o = ALU_SLTU; // Set Lower Than Unsigned\n {7'b000_0000, 3'b100}: alu_operator_o = ALU_XOR; // Xor\n {7'b000_0000, 3'b110}: alu_operator_o = ALU_OR; // Or\n {7'b000_0000, 3'b111}: alu_operator_o = ALU_AND; // And\n {7'b000_0000, 3'b001}: alu_operator_o = ALU_SLL; // Shift Left Logical\n {7'b000_0000, 3'b101}: alu_operator_o = ALU_SRL; // Shift Right Logical\n {7'b010_0000, 3'b101}: alu_operator_o = ALU_SRA; // Shift Right Arithmetic\n\n // RV32B ALU Operations\n {7'b001_0000, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SLO; // slo\n {7'b001_0000, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_SRO; // sro\n {7'b011_0000, 3'b001}: begin\n if (RV32B != RV32BNone) begin\n alu_operator_o = ALU_ROL; // rol\n alu_multicycle_o = 1'b1;\n end\n end\n {7'b011_0000, 3'b101}: begin\n if (RV32B != RV32BNone) begin\n alu_operator_o = ALU_ROR; // ror\n alu_multicycle_o = 1'b1;\n end\n end\n\n {7'b000_0101, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_MIN; // min\n {7'b000_0101, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_MAX; // max\n {7'b000_0101, 3'b110}: if (RV32B != RV32BNone) alu_operator_o = ALU_MINU; // minu\n {7'b000_0101, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_MAXU; // maxu\n\n {7'b000_0100, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACK; // pack\n {7'b010_0100, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACKU; // packu\n {7'b000_0100, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_PACKH; // packh\n\n {7'b010_0000, 3'b100}: if (RV32B != RV32BNone) alu_operator_o = ALU_XNOR; // xnor\n {7'b010_0000, 3'b110}: if (RV32B != RV32BNone) alu_operator_o = ALU_ORN; // orn\n {7'b010_0000, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_ANDN; // andn\n\n // RV32B zbs\n {7'b010_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBCLR; // sbclr\n {7'b001_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBSET; // sbset\n {7'b011_0100, 3'b001}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBINV; // sbinv\n {7'b010_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_SBEXT; // sbext\n\n // RV32B zbf\n {7'b010_0100, 3'b111}: if (RV32B != RV32BNone) alu_operator_o = ALU_BFP; // bfp\n\n // RV32B zbp\n {7'b011_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_GREV; // grev\n {7'b001_0100, 3'b101}: if (RV32B != RV32BNone) alu_operator_o = ALU_GORC; // grev\n {7'b000_0100, 3'b001}: if (RV32B == RV32BFull) alu_operator_o = ALU_SHFL; // shfl\n {7'b000_0100, 3'b101}: if (RV32B == RV32BFull) alu_operator_o = ALU_UNSHFL; // unshfl\n\n // RV32B zbc\n {7'b000_0101, 3'b001}: if (RV32B == RV32BFull) alu_operator_o = ALU_CLMUL; // clmul\n {7'b000_0101, 3'b010}: if (RV32B == RV32BFull) alu_operator_o = ALU_CLMULR; // clmulr\n {7'b000_0101, 3'b011}: if (RV32B == RV32BFull) alu_operator_o = ALU_CLMULH; // clmulh\n\n // RV32B zbe\n {7'b010_0100, 3'b110}: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_BDEP; // bdep\n alu_multicycle_o = 1'b1;\n end\n end\n {7'b000_0100, 3'b110}: begin\n if (RV32B == RV32BFull) begin\n alu_operator_o = ALU_BEXT; // bext\n alu_multicycle_o = 1'b1;\n end\n end\n\n // RV32M instructions, all use the same ALU operation\n {7'b000_0001, 3'b000}: begin // mul\n alu_operator_o = ALU_ADD;\n mult_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n alu_operator_o = ALU_ADD;\n mult_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n alu_operator_o = ALU_ADD;\n mult_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n alu_operator_o = ALU_ADD;\n mult_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b100}: begin // div\n alu_operator_o = ALU_ADD;\n div_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b101}: begin // divu\n alu_operator_o = ALU_ADD;\n div_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b110}: begin // rem\n alu_operator_o = ALU_ADD;\n div_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b111}: begin // remu\n alu_operator_o = ALU_ADD;\n div_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n\n default: ;\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. This may not be correct\n // in a system with caches and should be revisited.\n // FENCE.I will flush the IF stage and prefetch buffer but nothing else.\n unique case (instr_alu[14:12])\n 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 end\n 3'b001: begin\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_INCR_PC;\n end else begin\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 end\n end\n default: ;\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr_alu[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 end else begin\n // instruction to read/modify CSR\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_alu[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 end\n\n end\n default: ;\n endcase\n end\n\n // do not enable multdiv in case of illegal instruction exceptions\n assign mult_en_o = illegal_insn ? 1'b0 : mult_sel_o;\n assign div_en_o = illegal_insn ? 1'b0 : div_sel_o;\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 rf_we_o = rf_we & ~illegal_reg_rv32e;\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT(IbexRegImmAluOpKnown, (opcode == OPCODE_OP_IMM) |->\n !$isunknown(instr[14:12]))\nendmodule // controller\n", "selected_doc_paths": ["doc/instruction_decode_execute.rst", "doc/pipeline_details.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1182, "lang": "sv", "rtl_files": ["rtl/ibex_cs_registers.sv"], "spec": "# Behavioral Design Specification: Ibex Control and Status Registers (CSR) Module\n\n## 1. Overview\n\nThe Ibex CSR module implements all machine-level, debug, and custom control and status registers as required by the RISC-V Privileged Specification version 1.11 and the RISC-V Debug Specification version 0.13.2. It manages trap handling (exceptions and interrupts), privilege mode transitions, debug entry/exit, physical memory protection (PMP) configuration, performance monitoring counters, and runtime control of security features. The module provides the interface between the core's pipeline and the CSR register file.\n\n## 2. Interfaces\n\nThe module communicates with the core pipeline through the following interfaces (signal names omitted for brevity):\n\n- **CSR access port**: Accepts a request to read or write a CSR. The request includes a 12-bit address, 32-bit write data, an operation type (read, write, set, clear), and an enable signal. Returns 32-bit read data and a signal indicating an illegal CSR instruction.\n- **Interrupt inputs**: Receives five interrupt sources: software, timer, external, fast (15 signals), and a non-maskable interrupt (NMI). Outputs a qualified interrupt vector (masked by `mie`) and a combined interrupt pending indicator.\n- **Debug interface**: Receives debug mode status, debug cause, and a save signal. Outputs debug PC, single-step enable, ebreak-mode configuration, and breakpoint trigger match.\n- **Exception/handling interface**: Receives save and restore requests for exceptions, MRET, and DRET. Receives cause, trap value, and program counter from each pipeline stage (IF, ID, WB). Controls privilege mode output to the decoder, IF, and LSU.\n- **PMP interface**: Outputs configuration and address for each PMP region.\n- **Performance counter inputs**: Receives event signals such as instruction retired, cycles waiting for memory, jumps, branches, loads, stores, etc.\n- **CPU control outputs**: Drives data-independent timing enable, dummy instruction enable/mask/seed, icache enable, and aggregated shadow CSR error status.\n- **Hart ID**: Reads a 32-bit hardware thread ID input.\n\n## 3. Functional Description\n\n### 3.1 CSR Access and Illegal Detection\n\nThe module supports CSR read and write operations (including atomic set and clear). For a CSR write to succeed, all of the following must hold:\n- The CSR address must be implemented (non‑illegal address).\n- The privilege level of the access must be sufficient: bits [9:8] of the CSR address specify the required privilege; user mode can access only addresses with bits [9:8] ≤ current privilege level.\n- The CSR must be writeable (bits [11:10] must not be `2'b11` for write operations).\n\nIf any condition fails, the access is illegal and the write is suppressed. The illegal CSR instruction output is asserted in the same cycle as the access.\n\nRead data for each CSR is as defined in the RISC‑V specifications and the Ibex custom extension.\n\n#### 3.1.1 Standard Machine CSRs\n\n- **`mstatus`**: Contains machine status fields (MIE, MPIE, MPP, MPRV, TW). All fields are WARL. Any write with an unsupported privilege value for MPP is converted to Machine mode. Reset value: MIE=0, MPIE=1, MPP=User, MPRV=0, TW=0.\n- **`misa`**: Hardwired read-only value indicating the supported ISA extensions (RV32I or RV32E, C, M, U). Writes have no effect.\n- **`mie`**: Machine interrupt enable register. Masks individual interrupt sources. Reset value: all zeros.\n- **`mtvec`**: Trap vector base address. The lower two bits are forced to `01` (vectored mode). Bits [7:2] are always zero (256‑byte alignment). The initial value is taken from the boot address input; it can be written by software after reset.\n- **`mscratch`**: General‑purpose scratch register. Reset value: zero.\n- **`mepc`**: Exception program counter. Stores the return address on exception entry. LSB forced to zero. Reset value: zero.\n- **`mcause`**: Exception cause register. Interrupt bit (bit 31) and exception code (bits 4:0). Reset value: zero.\n- **`mtval`**: Trap value. Holds faulting address, instruction, or zero. Reset value: zero.\n- **`mip`**: Read‑only interrupt pending register. Reflects the raw interrupt inputs ANDed with the corresponding enable bits in `mie`.\n- **`mhartid`**: Read‑only. Returns the hardware thread ID input.\n\n#### 3.1.2 Debug CSRs\n\nAll debug CSRs are accessible only in Debug Mode. Access from any other privilege level causes an illegal instruction exception.\n\n- **`dcsr`**: Debug control and status. Fields: `xdebugver` (read‑only, 4), `ebreakm`, `ebreaku`, `cause` (read‑only), `step`, `prv`. Unsupported fields (`nmip`, `mprven`, `stopcount`, `stoptime`) are forced to zero on write. The `cause` field is not writable by software.\n- **`dpc`**: Debug PC. Stores the address to resume from. LSB forced to zero.\n- **`dscratch0`, `dscratch1`**: Scratch registers for debugger use.\n\n#### 3.1.3 Debug Trigger Registers\n\nWhen the hardware trigger feature is enabled (parameter `DbgTriggerEn` set), the following CSRs are available. Access from Debug Mode is allowed; from M‑mode writes are ignored.\n\n- **`tselect`**: Selects the current trigger (0 to `DbgHwBreakNum`-1). Writing a value greater than or equal to the number of triggers wraps to the highest index.\n- **`tdata1`**: Trigger data 1. Most bits are read‑only, reflecting the supported trigger type (address/data match, exact match, enter debug mode). The `execute` bit is writable; it enables matching on instruction address.\n- **`tdata2`**: Instruction address value for match.\n- **`tdata3`**: Always reads zero; writes ignored.\n- **`mcontext`, `scontext`**: Always read zero; writes ignored.\n\nBreakpoint matching: when a trigger’s `execute` bit is set and the instruction fetch address equals the value in `tdata2`, a trigger match output is asserted. The match uses the PC from the IF stage.\n\n#### 3.1.4 PMP Registers\n\nPhysical Memory Protection registers are present only when `PMPEnable` is set. The number of regions is defined by `PMPNumRegions` (1–16). Granularity is controlled by `PMPGranularity`.\n\n- **`pmpcfg0`–`pmpcfg3`**: Each 32‑bit register configures four PMP regions. Each region’s 8‑bit field contains: L (lock), reserved (zeros), mode (OFF, TOR, NA4, NAPOT), executable, write, and read. The combination write=1, read=0 is treated as all permissions disabled.\n- **`pmpaddr0`–`pmpaddr15`**: Address registers. The width is 33‑PMPGranularity bits (zero‑padded to 32 bits for read). Read data is masked according to mode and granularity.\n\nWrites to locked regions are ignored. The address register of region *i* is also protected from write if region *i+1* is locked and in TOR mode.\n\n#### 3.1.5 Performance Monitor CSRs\n\n- **`mcountinhibit`**: 32‑bit register; each bit enables (0) or inhibits (1) the corresponding counter. Bit 0 controls `mcycle`, bit 2 controls `minstret`, bits 3–31 control `mhpmcounter3`–`mhpmcounter31`. Bit 1 is reserved and forced to 0. Writable only for implemented counters; unavailable bits are tied to 1.\n- **`mhpmevent3`–`mhpmevent31`**: Hardwired event selectors. For each counter, the event selector contains a single bit set at the position equal to the event ID. Non‑implemented selectors are all‑zero.\n- **`mcycle` / `mcycleh`**: 64‑bit cycle counter. Lower and upper halves separately addressable.\n- **`minstret` / `minstreth`**: 64‑bit instruction retired counter.\n- **`mhpmcounter3(h)`–`mhpmcounter31(h)`**: Event counters, width configurable (`MHPMCounterWidth`). The number of implemented counters is `MHPMCounterNum` (0–29). Unimplemented counters read zero.\n\nCounters increment each cycle when the corresponding event occurs and the inhibit bit is cleared. They can be written directly by CSR writes to the low or high halves, and are readable non‑destructively.\n\n#### 3.1.6 Custom CSRs\n\n- **`cpuctrl`** (address 0x7C0): WARL, reset zero. Fields:\n - Bits 5:3 – `dummy_instr_mask`: controls dummy instruction insertion interval.\n - Bit 2 – `dummy_instr_en`: enables dummy instruction insertion.\n - Bit 1 – `data_ind_timing`: enables data‑independent timing.\n - Bit 0 – `icache_enable`: enables instruction cache.\n\n Fields that are not configured by the corresponding parameter (`DummyInstructions`, `DataIndTiming`, `ICache`) are forced to zero and reads return zero.\n\n- **`secureseed`** (address 0x7C1): Write‑only. A write to this CSR re‑seeds the LFSR used for dummy instruction randomization. Reads always return zero.\n\n### 3.2 Privilege Mode and Trap Handling\n\nThe module maintains the current privilege level (Machine or User). The output privilege to the decoder reflects the current level; the instruction fetch stage receives the *next* level (updated immediately on a trap or MRET/DRET). The LSU privilege depends on the `mprv` bit: when `mprv` is set, loads and stores use the privilege level stored in `mpp`; otherwise, they use the current privilege level.\n\n#### 3.2.1 Exception Entry\n\nWhen a save request arrives (caused by an interrupt, exception, or debug entry):\n\n1. The program counter is captured from the appropriate pipeline stage (IF for instruction access faults, ID for most synchronous exceptions, WB for load/store faults).\n2. The privilege level is set to Machine mode.\n3. If the request comes from debug mode (debug save enabled but not a normal exception), the debug registers are updated:\n - `dcsr.prv` = current privilege level\n - `dcsr.cause` = debug cause\n - `dpc` = exception PC\n4. If the request is a normal exception (not in debug mode):\n - `mepc` = exception PC (LSB aligned to even address)\n - `mcause` = cause value (bit 31 indicates interrupt, bits 4:0 exception code)\n - `mtval` = trap value\n - `mstatus.mie` = 0, `mstatus.mpie` = previous `mie`, `mstatus.mpp` = previous privilege level\n - The `mstack` CSRs (non‑standard) are also saved: `mstack.mpie` / `mstack.mpp` = same as `mstatus` fields, `mstack_epc` = `mepc`, `mstack_cause` = `mcause`. This backup enables recoverable NMI handling.\n\nAll interrupts are disabled during exception handling (MIE cleared). In debug mode, no normal exception modifies registers.\n\n#### 3.2.2 Exception Return (MRET)\n\nOn an MRET instruction:\n- Privilege level is restored from `mstatus.mpp`.\n- If the core is in NMI mode (handling a non‑maskable interrupt), the backup `mstack` values are used to restore `mstatus.mpie`, `mstatus.mpp`, `mepc`, and `mcause` to the state before the NMI.\n- Otherwise, `mstatus.mie` is set to `mstatus.mpie`, and `mstatus.mpie` is set to 1, `mstatus.mpp` is set to User mode.\n\n#### 3.2.3 Debug Return (DRET)\n\nOn a DRET instruction:\n- Privilege level is restored from `dcsr.prv`. No other CSR state is modified.\n\n#### 3.2.4 Interrupt Qualification\n\nThe module combines incoming interrupt requests with the `mie` CSR to produce qualified interrupts. The interrupt pending output is set if any qualified interrupt is active. The module also outputs the raw `mip` CSR (unqualified) to the pipeline. The `mstatus_mie` output reflects the global interrupt enable.\n\n### 3.3 Debug and Trigger Behavior\n\n- **Debug single-stepping**: When `dcsr.step` is set and the core is not in debug mode, the core executes a single instruction and then enters debug mode (triggered by a step cause).\n- **EBREAK behavior**: Controlled by `dcsr.ebreakm` (in M‑mode) and `dcsr.ebreaku` (in U‑mode). When set, EBREAK enters debug mode; otherwise, it behaves as defined in the Privileged Spec.\n- **Trigger match**: The module compares the IF stage PC against each enabled trigger’s address. If any match occurs, the trigger match output is asserted. The core then takes a breakpoint trap.\n\n### 3.4 PMP Address and Configuration\n\nFor each implemented PMP region, the module outputs:\n- Configuration fields (lock, reserved, mode, executable, write, read).\n- Address field (33-bit, with lower two bits zero). The address read data is adjusted according to PMP granularity and current mode.\n\nWhen PMP is disabled, all outputs are zero.\n\n### 3.5 Performance Counters\n\n- **mcycle** increments every cycle when `mcountinhibit[0]` is clear.\n- **minstret** increments when an instruction is retired (signal active) and `mcountinhibit[2]` is clear.\n- Event counters 3–31 increment when the corresponding event signal is high and the inhibit bit is clear. The event mapping is hardwired (see event table in documentation).\n- The counters are writable – a CSR write to the low or high half loads the value. Reading is non‑destructive.\n- When a counter is not implemented, it reads zero and any write is ignored.\n\n### 3.6 CPU Control Outputs\n\n- `data_ind_timing_o`: driven from `cpuctrl.data_ind_timing` (or zero if not configured).\n- `dummy_instr_en_o`, `dummy_instr_mask_o`: driven from `cpuctrl` (or zero if not configured).\n- `dummy_instr_seed_en_o`: asserted on any write to `secureseed` CSR; the seed value is the written data.\n- `icache_enable_o`: driven from `cpuctrl.icache_enable` (or zero if ICache not configured).\n- `csr_shadow_err_o`: OR of shadow copy error signals from `mstatus`, `mtvec`, PMP configuration, PMP address, and `cpuctrl`. (Only relevant when shadow CSR feature is enabled.)\n\n### 3.7 Reset Behavior\n\nUpon reset (active low), all CSRs are initialized to their defined reset values:\n- Privilege level: Machine mode.\n- `mstatus`: MIE=0, MPIE=1, MPP=User, MPRV=0, TW=0.\n- `mtvec`: 0x00000001 (base zero, vectored mode).\n- All other standard machine CSRs: zero.\n- Debug CSRs: `dcsr`=0x40000003 (xdebugver=4, cause=0, prv=M), `dpc`=0, `dscratch0`=0, `dscratch1`=0.\n- PMP registers: all zero.\n- Performance counters: all zero.\n- `mcountinhibit`: all zero (all counters enabled).\n- `cpuctrl`: zero.\n- `mstack` triple: MPIE=1, MPP=User, EPC=0, cause=0.\n\n## 4. Parameterization\n\nThe module’s behavior is configured through the following parameters:\n\n- **DbgTriggerEn** (0/1): Enable debug trigger CSRs.\n- **DbgHwBreakNum** (1+): Number of hardware breakpoints/triggers.\n- **DataIndTiming** (0/1): Enable data‑independent timing control.\n- **DummyInstructions** (0/1): Enable dummy instruction insertion.\n- **ShadowCSR** (0/1): Enable shadow copies for critical CSRs (error detection).\n- **ICache** (0/1): Enable instruction cache control.\n- **MHPMCounterNum** (0..29): Number of implemented event counters.\n- **MHPMCounterWidth** (1..64): Width of event counters.\n- **PMPEnable** (0/1): Enable PMP registers.\n- **PMPGranularity** (0..31): PMP address granularity (2^(G+2) bytes).\n- **PMPNumRegions** (1..16): Number of PMP regions (only used when PMPEnable=1).\n- **RV32E** (0/1): Select RV32E base ISA (16 registers).\n- **RV32M** (None/Fast/SingleCycle): Multiplier implementation.\n\n## 5. Constraints and Exceptions\n\n- All CSR read operations complete in one cycle.\n- CSR write operations also complete in one cycle (no wait states).\n- The module does **not** implement supervisor‑level CSRs or time(h) registers. Access to unimplemented CSRs results in an illegal instruction.\n- NMI nesting is not supported; the `mstack` backup is overwritten when a second NMI occurs before an MRET.\n- Debug mode overrides all normal exception save operations; the core does not update `mepc`/`mcause`/`mstatus` while in debug mode.\n- The trigger matching mechanism uses the **instruction fetch** PC, not the execute or writeback stage. This ensures the breakpoint is acted upon before the instruction executes.", "commit_id": "9b0d78cf97fd4bd22db8b2479f30ed135f761a13", "timestamp": "2020-11-09T14:49:07+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "6fb378c40c2a5fa917caec4a4425fdefa68d9cee", "pr_title": "[rtl] Reduce size of PMP addr CSRs to minimum", "pr_body": "- Reduce the size of the PMP address configuration registers to the permissible minimum depending on granularity.\r\n- Ensure consistency between PMP address CSR reads and the addresses forwarded to the PMP module.\r\n- Follow the specification more strictly, by returning bits pmpaddr[G-2:0] as all ones when pmpcfg.A[1] is set (i.e. mode is NAPOT or NA4, though the latter is invalid for G > 0) and bits pmpaddr[G-1:0] as all zeros when pmpcfg.A[0] is clear (i.e. mode is OFF or TOR).\r\n- Fixes #1181", "issue_title": "PMP CSR enhancement / bug", "issue_body": "Looking PMP granularity as part of #1178 I noticed we always keep the PMP address CSRs as 32bits despite the granularity. At best this is inefficient as we're missing out on area savings, at worst it's a bug since we use the raw address in the matching logic (which doesn't match the modified version the user sees on a CSR read).", "commit_message": "[rtl] Reduce size of PMP addr CSRs to minimum\n\n- Reduce the size of the PMP address configuration registers to the\n permissible minimum depending on granularity.\n- Ensure consistency between PMP address CSR reads and the addresses\n forwarded to the PMP module.\n- Follow the specification more strictly, by returning bits\n pmpaddr[G-2:0] as all ones when pmpcfg.A[1] is set (i.e. mode is\n NAPOT or NA4, though the latter is invalid for G > 0) and bits\n pmpaddr[G-1:0] as all zeros when pmpcfg.A[0] is clear (i.e. mode is\n OFF or TOR).\n- Fixes #1181", "fix_patch": "diff --git a/rtl/ibex_cs_registers.sv b/rtl/ibex_cs_registers.sv\nindex 36d1f793e1..16a8acd3fc 100644\n--- a/rtl/ibex_cs_registers.sv\n+++ b/rtl/ibex_cs_registers.sv\n@@ -120,6 +120,7 @@ module ibex_cs_registers #(\n import ibex_pkg::*;\n \n localparam int unsigned RV32MEnabled = (RV32M == RV32MNone) ? 0 : 1;\n+ localparam int unsigned PMPAddrWidth = (PMPGranularity > 0) ? 33 - PMPGranularity : 32;\n \n // misa\n localparam logic [31:0] MISA_VALUE =\n@@ -954,7 +955,7 @@ module ibex_cs_registers #(\n if (PMPEnable) begin : g_pmp_registers\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n- logic [31:0] pmp_addr [PMPNumRegions];\n+ logic [PMPAddrWidth-1:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n logic [PMPNumRegions-1:0] pmp_cfg_err;\n logic [PMPNumRegions-1:0] pmp_addr_we;\n@@ -985,13 +986,12 @@ module ibex_cs_registers #(\n end else begin : g_pmp_g2\n // For G >= 2, bits are masked to one or zero depending on the mode\n always_comb begin\n- pmp_addr_rdata[i] = pmp_addr[i];\n+ // In NAPOT mode, bits [G-2:0] must read as one\n+ pmp_addr_rdata[i] = {pmp_addr[i], {PMPGranularity-1{1'b1}}};\n+\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n // In TOR or OFF mode, bits [G-1:0] must read as zero\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n- end else if (pmp_cfg[i].mode == PMP_MODE_NAPOT) begin\n- // In NAPOT mode, bits [G-2:0] must read as one\n- pmp_addr_rdata[i][PMPGranularity-2:0] = '1;\n end\n end\n end\n@@ -1055,20 +1055,20 @@ module ibex_cs_registers #(\n end\n \n ibex_csr #(\n- .Width (32),\n+ .Width (PMPAddrWidth),\n .ShadowCopy (ShadowCSR),\n .ResetValue ('0)\n ) u_pmp_addr_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n- .wr_data_i (csr_wdata_int),\n+ .wr_data_i (csr_wdata_int[31-:PMPAddrWidth]),\n .wr_en_i (pmp_addr_we[i]),\n .rd_data_o (pmp_addr[i]),\n .rd_error_o (pmp_addr_err[i])\n );\n \n assign csr_pmp_cfg_o[i] = pmp_cfg[i];\n- assign csr_pmp_addr_o[i] = {pmp_addr[i],2'b00};\n+ assign csr_pmp_addr_o[i] = {pmp_addr_rdata[i], 2'b00};\n end\n \n assign pmp_csr_err = (|pmp_cfg_err) | (|pmp_addr_err);\n", "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 * Control and Status Registers\n *\n * Control and Status Registers (CSRs) following the RISC-V Privileged\n * Specification, draft version 1.11\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_cs_registers #(\n parameter bit DbgTriggerEn = 0,\n parameter int unsigned DbgHwBreakNum = 1,\n parameter bit DataIndTiming = 1'b0,\n parameter bit DummyInstructions = 1'b0,\n parameter bit ShadowCSR = 1'b0,\n parameter bit ICache = 1'b0,\n parameter int unsigned MHPMCounterNum = 10,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit PMPEnable = 0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter bit RV32E = 0,\n parameter ibex_pkg::rv32m_e RV32M = ibex_pkg::RV32MFast\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n // Hart ID\n input logic [31:0] hart_id_i,\n\n // Privilege mode\n output ibex_pkg::priv_lvl_e priv_mode_id_o,\n output ibex_pkg::priv_lvl_e priv_mode_if_o,\n output ibex_pkg::priv_lvl_e priv_mode_lsu_o,\n output logic csr_mstatus_tw_o,\n\n // mtvec\n output logic [31:0] csr_mtvec_o,\n input logic csr_mtvec_init_i,\n input logic [31:0] boot_addr_i,\n\n // Interface to registers (SRAM like)\n input logic csr_access_i,\n input ibex_pkg::csr_num_e csr_addr_i,\n input logic [31:0] csr_wdata_i,\n input ibex_pkg::csr_op_e csr_op_i,\n input csr_op_en_i,\n output logic [31:0] csr_rdata_o,\n\n // interrupts\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 nmi_mode_i,\n output logic irq_pending_o, // interrupt request pending\n output ibex_pkg::irqs_t irqs_o, // interrupt requests qualified with mie\n output logic csr_mstatus_mie_o,\n output logic [31:0] csr_mepc_o,\n\n // PMP\n output ibex_pkg::pmp_cfg_t csr_pmp_cfg_o [PMPNumRegions],\n output logic [33:0] csr_pmp_addr_o [PMPNumRegions],\n\n // debug\n input logic debug_mode_i,\n input ibex_pkg::dbg_cause_e debug_cause_i,\n input logic debug_csr_save_i,\n output logic [31:0] csr_depc_o,\n output logic debug_single_step_o,\n output logic debug_ebreakm_o,\n output logic debug_ebreaku_o,\n output logic trigger_match_o,\n\n input logic [31:0] pc_if_i,\n input logic [31:0] pc_id_i,\n input logic [31:0] pc_wb_i,\n\n // CPU control bits\n output logic data_ind_timing_o,\n output logic dummy_instr_en_o,\n output logic [2:0] dummy_instr_mask_o,\n output logic dummy_instr_seed_en_o,\n output logic [31:0] dummy_instr_seed_o,\n output logic icache_enable_o,\n output logic csr_shadow_err_o,\n\n // Exception save/restore\n input logic csr_save_if_i,\n input logic csr_save_id_i,\n input logic csr_save_wb_i,\n input logic csr_restore_mret_i,\n input logic csr_restore_dret_i,\n input logic csr_save_cause_i,\n input ibex_pkg::exc_cause_e csr_mcause_i,\n input logic [31:0] csr_mtval_i,\n output logic illegal_csr_insn_o, // access to non-existent CSR,\n // with wrong priviledge level, or\n // missing write permissions\n // Performance Counters\n input logic instr_ret_i, // instr retired in ID/EX stage\n input logic instr_ret_compressed_i, // compressed instr retired\n input logic iside_wait_i, // core waiting for the iside\n input logic jump_i, // jump instr seen (j, jr, jal, jalr)\n input logic branch_i, // branch instr seen (bf, bnf)\n input logic branch_taken_i, // branch was taken\n input logic mem_load_i, // load from memory in this cycle\n input logic mem_store_i, // store to memory in this cycle\n input logic dside_wait_i, // core waiting for the dside\n input logic mul_wait_i, // core waiting for multiply\n input logic div_wait_i // core waiting for divide\n);\n\n import ibex_pkg::*;\n\n localparam int unsigned RV32MEnabled = (RV32M == RV32MNone) ? 0 : 1;\n localparam int unsigned PMPAddrWidth = (PMPGranularity > 0) ? 33 - PMPGranularity : 32;\n\n // misa\n localparam logic [31:0] MISA_VALUE =\n (0 << 0) // A - Atomic Instructions extension\n | (1 << 2) // C - Compressed extension\n | (0 << 3) // D - Double precision floating-point extension\n | (32'(RV32E) << 4) // E - RV32E base ISA\n | (0 << 5) // F - Single precision floating-point extension\n | (32'(!RV32E) << 8) // I - RV32I/64I/128I base ISA\n | (RV32MEnabled << 12) // M - Integer Multiply/Divide extension\n | (0 << 13) // N - User level interrupts supported\n | (0 << 18) // S - Supervisor mode implemented\n | (1 << 20) // U - User mode implemented\n | (0 << 23) // X - Non-standard extensions present\n | (32'(CSR_MISA_MXL) << 30); // M-XLEN\n\n typedef struct packed {\n logic mie;\n logic mpie;\n priv_lvl_e mpp;\n logic mprv;\n logic tw;\n } status_t;\n\n typedef struct packed {\n logic mpie;\n priv_lvl_e mpp;\n } status_stk_t;\n\n typedef struct packed {\n x_debug_ver_e xdebugver;\n logic [11:0] zero2;\n logic ebreakm;\n logic zero1;\n logic ebreaks;\n logic ebreaku;\n logic stepie;\n logic stopcount;\n logic stoptime;\n dbg_cause_e cause;\n logic zero0;\n logic mprven;\n logic nmip;\n logic step;\n priv_lvl_e prv;\n } dcsr_t;\n\n // CPU control register fields\n typedef struct packed {\n logic [2:0] dummy_instr_mask;\n logic dummy_instr_en;\n logic data_ind_timing;\n logic icache_enable;\n } cpu_ctrl_t;\n\n // Interrupt and exception control signals\n logic [31:0] exception_pc;\n\n // CSRs\n priv_lvl_e priv_lvl_q, priv_lvl_d;\n status_t mstatus_q, mstatus_d;\n logic mstatus_err;\n logic mstatus_en;\n irqs_t mie_q, mie_d;\n logic mie_en;\n logic [31:0] mscratch_q;\n logic mscratch_en;\n logic [31:0] mepc_q, mepc_d;\n logic mepc_en;\n logic [5:0] mcause_q, mcause_d;\n logic mcause_en;\n logic [31:0] mtval_q, mtval_d;\n logic mtval_en;\n logic [31:0] mtvec_q, mtvec_d;\n logic mtvec_err;\n logic mtvec_en;\n irqs_t mip;\n dcsr_t dcsr_q, dcsr_d;\n logic dcsr_en;\n logic [31:0] depc_q, depc_d;\n logic depc_en;\n logic [31:0] dscratch0_q;\n logic [31:0] dscratch1_q;\n logic dscratch0_en, dscratch1_en;\n\n // CSRs for recoverable NMIs\n // NOTE: these CSRS are nonstandard, see https://github.com/riscv/riscv-isa-manual/issues/261\n status_stk_t mstack_q, mstack_d;\n logic mstack_en;\n logic [31:0] mstack_epc_q, mstack_epc_d;\n logic [5:0] mstack_cause_q, mstack_cause_d;\n\n // PMP Signals\n logic [31:0] pmp_addr_rdata [PMP_MAX_REGIONS];\n logic [PMP_CFG_W-1:0] pmp_cfg_rdata [PMP_MAX_REGIONS];\n logic pmp_csr_err;\n\n // Hardware performance monitor signals\n logic [31:0] mcountinhibit;\n // Only have mcountinhibit flops for counters that actually exist\n logic [MHPMCounterNum+3-1:0] mcountinhibit_d, mcountinhibit_q;\n logic mcountinhibit_we;\n\n // mhpmcounter flops are elaborated below providing only the precise number that is required based\n // on MHPMCounterNum/MHPMCounterWidth. This signal connects to the Q output of these flops\n // where they exist and is otherwise 0.\n logic [63:0] mhpmcounter [32];\n logic [31:0] mhpmcounter_we;\n logic [31:0] mhpmcounterh_we;\n logic [31:0] mhpmcounter_incr;\n logic [31:0] mhpmevent [32];\n logic [4:0] mhpmcounter_idx;\n logic unused_mhpmcounter_we_1;\n logic unused_mhpmcounterh_we_1;\n logic unused_mhpmcounter_incr_1;\n\n // Debug / trigger registers\n logic [31:0] tselect_rdata;\n logic [31:0] tmatch_control_rdata;\n logic [31:0] tmatch_value_rdata;\n\n // CPU control bits\n cpu_ctrl_t cpuctrl_q, cpuctrl_d, cpuctrl_wdata;\n logic cpuctrl_we;\n logic cpuctrl_err;\n\n // CSR update logic\n logic [31:0] csr_wdata_int;\n logic [31:0] csr_rdata_int;\n logic csr_we_int;\n logic csr_wreq;\n\n // Access violation signals\n logic illegal_csr;\n logic illegal_csr_priv;\n logic illegal_csr_write;\n\n logic [7:0] unused_boot_addr;\n logic [2:0] unused_csr_addr;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n\n /////////////\n // CSR reg //\n /////////////\n\n logic [$bits(csr_num_e)-1:0] csr_addr;\n assign csr_addr = {csr_addr_i};\n assign unused_csr_addr = csr_addr[7:5];\n assign mhpmcounter_idx = csr_addr[4:0];\n\n // See RISC-V Privileged Specification, version 1.11, Section 2.1\n assign illegal_csr_priv = (csr_addr[9:8] > {priv_lvl_q});\n assign illegal_csr_write = (csr_addr[11:10] == 2'b11) && csr_wreq;\n assign illegal_csr_insn_o = csr_access_i & (illegal_csr | illegal_csr_write | illegal_csr_priv);\n\n // mip CSR is purely combinational - must be able to re-enable the clock upon WFI\n assign mip.irq_software = irq_software_i;\n assign mip.irq_timer = irq_timer_i;\n assign mip.irq_external = irq_external_i;\n assign mip.irq_fast = irq_fast_i;\n\n // read logic\n always_comb begin\n csr_rdata_int = '0;\n illegal_csr = 1'b0;\n\n unique case (csr_addr_i)\n // mhartid: unique hardware thread id\n CSR_MHARTID: csr_rdata_int = hart_id_i;\n\n // mstatus: always M-mode, contains IE bit\n CSR_MSTATUS: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSTATUS_MIE_BIT] = mstatus_q.mie;\n csr_rdata_int[CSR_MSTATUS_MPIE_BIT] = mstatus_q.mpie;\n csr_rdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW] = mstatus_q.mpp;\n csr_rdata_int[CSR_MSTATUS_MPRV_BIT] = mstatus_q.mprv;\n csr_rdata_int[CSR_MSTATUS_TW_BIT] = mstatus_q.tw;\n end\n\n // misa\n CSR_MISA: csr_rdata_int = MISA_VALUE;\n\n // interrupt enable\n CSR_MIE: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mie_q.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mie_q.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mie_q.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mie_q.irq_fast;\n end\n\n CSR_MSCRATCH: csr_rdata_int = mscratch_q;\n\n // mtvec: trap-vector base address\n CSR_MTVEC: csr_rdata_int = mtvec_q;\n\n // mepc: exception program counter\n CSR_MEPC: csr_rdata_int = mepc_q;\n\n // mcause: exception cause\n CSR_MCAUSE: csr_rdata_int = {mcause_q[5], 26'b0, mcause_q[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: csr_rdata_int = mtval_q;\n\n // mip: interrupt pending\n CSR_MIP: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mip.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mip.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mip.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mip.irq_fast;\n end\n\n // PMP registers\n CSR_PMPCFG0: csr_rdata_int = {pmp_cfg_rdata[3], pmp_cfg_rdata[2],\n pmp_cfg_rdata[1], pmp_cfg_rdata[0]};\n CSR_PMPCFG1: csr_rdata_int = {pmp_cfg_rdata[7], pmp_cfg_rdata[6],\n pmp_cfg_rdata[5], pmp_cfg_rdata[4]};\n CSR_PMPCFG2: csr_rdata_int = {pmp_cfg_rdata[11], pmp_cfg_rdata[10],\n pmp_cfg_rdata[9], pmp_cfg_rdata[8]};\n CSR_PMPCFG3: csr_rdata_int = {pmp_cfg_rdata[15], pmp_cfg_rdata[14],\n pmp_cfg_rdata[13], pmp_cfg_rdata[12]};\n CSR_PMPADDR0: csr_rdata_int = pmp_addr_rdata[0];\n CSR_PMPADDR1: csr_rdata_int = pmp_addr_rdata[1];\n CSR_PMPADDR2: csr_rdata_int = pmp_addr_rdata[2];\n CSR_PMPADDR3: csr_rdata_int = pmp_addr_rdata[3];\n CSR_PMPADDR4: csr_rdata_int = pmp_addr_rdata[4];\n CSR_PMPADDR5: csr_rdata_int = pmp_addr_rdata[5];\n CSR_PMPADDR6: csr_rdata_int = pmp_addr_rdata[6];\n CSR_PMPADDR7: csr_rdata_int = pmp_addr_rdata[7];\n CSR_PMPADDR8: csr_rdata_int = pmp_addr_rdata[8];\n CSR_PMPADDR9: csr_rdata_int = pmp_addr_rdata[9];\n CSR_PMPADDR10: csr_rdata_int = pmp_addr_rdata[10];\n CSR_PMPADDR11: csr_rdata_int = pmp_addr_rdata[11];\n CSR_PMPADDR12: csr_rdata_int = pmp_addr_rdata[12];\n CSR_PMPADDR13: csr_rdata_int = pmp_addr_rdata[13];\n CSR_PMPADDR14: csr_rdata_int = pmp_addr_rdata[14];\n CSR_PMPADDR15: csr_rdata_int = pmp_addr_rdata[15];\n\n CSR_DCSR: begin\n csr_rdata_int = dcsr_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DPC: begin\n csr_rdata_int = depc_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH0: begin\n csr_rdata_int = dscratch0_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH1: begin\n csr_rdata_int = dscratch1_q;\n illegal_csr = ~debug_mode_i;\n end\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: csr_rdata_int = mcountinhibit;\n CSR_MHPMEVENT3,\n CSR_MHPMEVENT4, CSR_MHPMEVENT5, CSR_MHPMEVENT6, CSR_MHPMEVENT7,\n CSR_MHPMEVENT8, CSR_MHPMEVENT9, CSR_MHPMEVENT10, CSR_MHPMEVENT11,\n CSR_MHPMEVENT12, CSR_MHPMEVENT13, CSR_MHPMEVENT14, CSR_MHPMEVENT15,\n CSR_MHPMEVENT16, CSR_MHPMEVENT17, CSR_MHPMEVENT18, CSR_MHPMEVENT19,\n CSR_MHPMEVENT20, CSR_MHPMEVENT21, CSR_MHPMEVENT22, CSR_MHPMEVENT23,\n CSR_MHPMEVENT24, CSR_MHPMEVENT25, CSR_MHPMEVENT26, CSR_MHPMEVENT27,\n CSR_MHPMEVENT28, CSR_MHPMEVENT29, CSR_MHPMEVENT30, CSR_MHPMEVENT31: begin\n csr_rdata_int = mhpmevent[mhpmcounter_idx];\n end\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][31:0];\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][63:32];\n end\n\n // Debug triggers\n CSR_TSELECT: begin\n csr_rdata_int = tselect_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA1: begin\n csr_rdata_int = tmatch_control_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA2: begin\n csr_rdata_int = tmatch_value_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA3: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_MCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_SCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n\n // Custom CSR for controlling CPU features\n CSR_CPUCTRL: begin\n csr_rdata_int = {{32-$bits(cpu_ctrl_t){1'b0}},cpuctrl_q};\n end\n\n // Custom CSR for LFSR re-seeding (cannot be read)\n CSR_SECURESEED: begin\n csr_rdata_int = '0;\n end\n\n default: begin\n illegal_csr = 1'b1;\n end\n endcase\n end\n\n // write logic\n always_comb begin\n exception_pc = pc_id_i;\n\n priv_lvl_d = priv_lvl_q;\n mstatus_en = 1'b0;\n mstatus_d = mstatus_q;\n mie_en = 1'b0;\n mscratch_en = 1'b0;\n mepc_en = 1'b0;\n mepc_d = {csr_wdata_int[31:1], 1'b0};\n mcause_en = 1'b0;\n mcause_d = {csr_wdata_int[31], csr_wdata_int[4:0]};\n mtval_en = 1'b0;\n mtval_d = csr_wdata_int;\n mtvec_en = csr_mtvec_init_i;\n // mtvec.MODE set to vectored\n // mtvec.BASE must be 256-byte aligned\n mtvec_d = csr_mtvec_init_i ? {boot_addr_i[31:8], 6'b0, 2'b01} :\n {csr_wdata_int[31:8], 6'b0, 2'b01};\n dcsr_en = 1'b0;\n dcsr_d = dcsr_q;\n depc_d = {csr_wdata_int[31:1], 1'b0};\n depc_en = 1'b0;\n dscratch0_en = 1'b0;\n dscratch1_en = 1'b0;\n\n mstack_en = 1'b0;\n mstack_d.mpie = mstatus_q.mpie;\n mstack_d.mpp = mstatus_q.mpp;\n mstack_epc_d = mepc_q;\n mstack_cause_d = mcause_q;\n\n mcountinhibit_we = 1'b0;\n mhpmcounter_we = '0;\n mhpmcounterh_we = '0;\n\n cpuctrl_we = 1'b0;\n\n if (csr_we_int) begin\n unique case (csr_addr_i)\n // mstatus: IE bit\n CSR_MSTATUS: begin\n mstatus_en = 1'b1;\n mstatus_d = '{\n mie: csr_wdata_int[CSR_MSTATUS_MIE_BIT],\n mpie: csr_wdata_int[CSR_MSTATUS_MPIE_BIT],\n mpp: priv_lvl_e'(csr_wdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW]),\n mprv: csr_wdata_int[CSR_MSTATUS_MPRV_BIT],\n tw: csr_wdata_int[CSR_MSTATUS_TW_BIT]\n };\n // Convert illegal values to M-mode\n if ((mstatus_d.mpp != PRIV_LVL_M) && (mstatus_d.mpp != PRIV_LVL_U)) begin\n mstatus_d.mpp = PRIV_LVL_M;\n end\n end\n\n // interrupt enable\n CSR_MIE: mie_en = 1'b1;\n\n CSR_MSCRATCH: mscratch_en = 1'b1;\n\n // mepc: exception program counter\n CSR_MEPC: mepc_en = 1'b1;\n\n // mcause\n CSR_MCAUSE: mcause_en = 1'b1;\n\n // mtval: trap value\n CSR_MTVAL: mtval_en = 1'b1;\n\n // mtvec\n CSR_MTVEC: mtvec_en = 1'b1;\n\n CSR_DCSR: begin\n dcsr_d = csr_wdata_int;\n dcsr_d.xdebugver = XDEBUGVER_STD;\n // Change to PRIV_LVL_M if software writes an unsupported value\n if ((dcsr_d.prv != PRIV_LVL_M) && (dcsr_d.prv != PRIV_LVL_U)) begin\n dcsr_d.prv = PRIV_LVL_M;\n end\n\n // Read-only for SW\n dcsr_d.cause = dcsr_q.cause;\n\n // currently not supported:\n dcsr_d.nmip = 1'b0;\n dcsr_d.mprven = 1'b0;\n dcsr_d.stopcount = 1'b0;\n dcsr_d.stoptime = 1'b0;\n\n // forced to be zero\n dcsr_d.zero0 = 1'b0;\n dcsr_d.zero1 = 1'b0;\n dcsr_d.zero2 = 12'h0;\n dcsr_en = 1'b1;\n end\n\n // dpc: debug program counter\n CSR_DPC: depc_en = 1'b1;\n\n CSR_DSCRATCH0: dscratch0_en = 1'b1;\n CSR_DSCRATCH1: dscratch1_en = 1'b1;\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: mcountinhibit_we = 1'b1;\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n mhpmcounter_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n mhpmcounterh_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_CPUCTRL: cpuctrl_we = 1'b1;\n\n default:;\n endcase\n end\n\n // exception controller gets priority over other writes\n unique case (1'b1)\n\n csr_save_cause_i: begin\n unique case (1'b1)\n csr_save_if_i: begin\n exception_pc = pc_if_i;\n end\n csr_save_id_i: begin\n exception_pc = pc_id_i;\n end\n csr_save_wb_i: begin\n exception_pc = pc_wb_i;\n end\n default:;\n endcase\n\n // Any exception, including debug mode, causes a switch to M-mode\n priv_lvl_d = PRIV_LVL_M;\n\n if (debug_csr_save_i) begin\n // all interrupts are masked\n // do not update cause, epc, tval, epc and status\n dcsr_d.prv = priv_lvl_q;\n dcsr_d.cause = debug_cause_i;\n dcsr_en = 1'b1;\n depc_d = exception_pc;\n depc_en = 1'b1;\n end else if (!debug_mode_i) begin\n // In debug mode, \"exceptions do not update any registers. That\n // includes cause, epc, tval, dpc and mstatus.\" [Debug Spec v0.13.2, p.39]\n mtval_en = 1'b1;\n mtval_d = csr_mtval_i;\n mstatus_en = 1'b1;\n mstatus_d.mie = 1'b0; // disable interrupts\n // save current status\n mstatus_d.mpie = mstatus_q.mie;\n mstatus_d.mpp = priv_lvl_q;\n mepc_en = 1'b1;\n mepc_d = exception_pc;\n mcause_en = 1'b1;\n mcause_d = {csr_mcause_i};\n // save previous status for recoverable NMI\n mstack_en = 1'b1;\n end\n end // csr_save_cause_i\n\n csr_restore_dret_i: begin // DRET\n priv_lvl_d = dcsr_q.prv;\n end // csr_restore_dret_i\n\n csr_restore_mret_i: begin // MRET\n priv_lvl_d = mstatus_q.mpp;\n mstatus_en = 1'b1;\n mstatus_d.mie = mstatus_q.mpie; // re-enable interrupts\n\n if (nmi_mode_i) begin\n // when returning from an NMI restore state from mstack CSR\n mstatus_d.mpie = mstack_q.mpie;\n mstatus_d.mpp = mstack_q.mpp;\n mepc_en = 1'b1;\n mepc_d = mstack_epc_q;\n mcause_en = 1'b1;\n mcause_d = mstack_cause_q;\n end else begin\n // otherwise just set mstatus.MPIE/MPP\n // See RISC-V Privileged Specification, version 1.11, Section 3.1.6.1\n mstatus_d.mpie = 1'b1;\n mstatus_d.mpp = PRIV_LVL_U;\n end\n end // csr_restore_mret_i\n\n default:;\n endcase\n end\n\n // Update current priv level\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n priv_lvl_q <= PRIV_LVL_M;\n end else begin\n priv_lvl_q <= priv_lvl_d;\n end\n end\n\n // Send current priv level to the decoder\n assign priv_mode_id_o = priv_lvl_q;\n // New instruction fetches need to account for updates to priv_lvl_q this cycle\n assign priv_mode_if_o = priv_lvl_d;\n // Load/store instructions must factor in MPRV for PMP checking\n assign priv_mode_lsu_o = mstatus_q.mprv ? mstatus_q.mpp : priv_lvl_q;\n\n // CSR operation logic\n always_comb begin\n unique case (csr_op_i)\n CSR_OP_WRITE: csr_wdata_int = csr_wdata_i;\n CSR_OP_SET: csr_wdata_int = csr_wdata_i | csr_rdata_o;\n CSR_OP_CLEAR: csr_wdata_int = ~csr_wdata_i & csr_rdata_o;\n CSR_OP_READ: csr_wdata_int = csr_wdata_i;\n default: csr_wdata_int = csr_wdata_i;\n endcase\n end\n\n assign csr_wreq = csr_op_en_i &\n (csr_op_i inside {CSR_OP_WRITE,\n CSR_OP_SET,\n CSR_OP_CLEAR});\n\n // only write CSRs during one clock cycle\n assign csr_we_int = csr_wreq & ~illegal_csr_insn_o;\n\n assign csr_rdata_o = csr_rdata_int;\n\n // directly output some registers\n assign csr_mepc_o = mepc_q;\n assign csr_depc_o = depc_q;\n assign csr_mtvec_o = mtvec_q;\n\n assign csr_mstatus_mie_o = mstatus_q.mie;\n assign csr_mstatus_tw_o = mstatus_q.tw;\n assign debug_single_step_o = dcsr_q.step;\n assign debug_ebreakm_o = dcsr_q.ebreakm;\n assign debug_ebreaku_o = dcsr_q.ebreaku;\n\n // Qualify incoming interrupt requests in mip CSR with mie CSR for controller and to re-enable\n // clock upon WFI (must be purely combinational).\n assign irqs_o = mip & mie_q;\n assign irq_pending_o = |irqs_o;\n\n ////////////////////////\n // CSR instantiations //\n ////////////////////////\n\n // MSTATUS\n localparam status_t MSTATUS_RST_VAL = '{mie: 1'b0,\n mpie: 1'b1,\n mpp: PRIV_LVL_U,\n mprv: 1'b0,\n tw: 1'b0};\n ibex_csr #(\n .Width ($bits(status_t)),\n .ShadowCopy (ShadowCSR),\n .ResetValue ({MSTATUS_RST_VAL})\n ) u_mstatus_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mstatus_d}),\n .wr_en_i (mstatus_en),\n .rd_data_o (mstatus_q),\n .rd_error_o (mstatus_err)\n );\n\n // MEPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mepc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mepc_d),\n .wr_en_i (mepc_en),\n .rd_data_o (mepc_q),\n .rd_error_o ()\n );\n\n // MIE\n assign mie_d.irq_software = csr_wdata_int[CSR_MSIX_BIT];\n assign mie_d.irq_timer = csr_wdata_int[CSR_MTIX_BIT];\n assign mie_d.irq_external = csr_wdata_int[CSR_MEIX_BIT];\n assign mie_d.irq_fast = csr_wdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW];\n ibex_csr #(\n .Width ($bits(irqs_t)),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mie_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mie_d}),\n .wr_en_i (mie_en),\n .rd_data_o (mie_q),\n .rd_error_o ()\n );\n\n // MSCRATCH\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mscratch_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (mscratch_en),\n .rd_data_o (mscratch_q),\n .rd_error_o ()\n );\n\n // MCAUSE\n ibex_csr #(\n .Width (6),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mcause_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mcause_d),\n .wr_en_i (mcause_en),\n .rd_data_o (mcause_q),\n .rd_error_o ()\n );\n\n // MTVAL\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mtval_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mtval_d),\n .wr_en_i (mtval_en),\n .rd_data_o (mtval_q),\n .rd_error_o ()\n );\n\n // MTVEC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (ShadowCSR),\n .ResetValue (32'd1)\n ) u_mtvec_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mtvec_d),\n .wr_en_i (mtvec_en),\n .rd_data_o (mtvec_q),\n .rd_error_o (mtvec_err)\n );\n\n // DCSR\n localparam dcsr_t DCSR_RESET_VAL = '{\n xdebugver: XDEBUGVER_STD,\n cause: DBG_CAUSE_NONE, // 3'h0\n prv: PRIV_LVL_M,\n default: '0\n };\n ibex_csr #(\n .Width ($bits(dcsr_t)),\n .ShadowCopy (1'b0),\n .ResetValue ({DCSR_RESET_VAL})\n ) u_dcsr_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({dcsr_d}),\n .wr_en_i (dcsr_en),\n .rd_data_o (dcsr_q),\n .rd_error_o ()\n );\n\n // DEPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_depc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (depc_d),\n .wr_en_i (depc_en),\n .rd_data_o (depc_q),\n .rd_error_o ()\n );\n\n // DSCRATCH0\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_dscratch0_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (dscratch0_en),\n .rd_data_o (dscratch0_q),\n .rd_error_o ()\n );\n\n // DSCRATCH1\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_dscratch1_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int),\n .wr_en_i (dscratch1_en),\n .rd_data_o (dscratch1_q),\n .rd_error_o ()\n );\n\n // MSTACK\n localparam status_stk_t MSTACK_RESET_VAL = '{\n mpie: 1'b1,\n mpp: PRIV_LVL_U\n };\n ibex_csr #(\n .Width ($bits(status_stk_t)),\n .ShadowCopy (1'b0),\n .ResetValue ({MSTACK_RESET_VAL})\n ) u_mstack_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({mstack_d}),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_q),\n .rd_error_o ()\n );\n\n // MSTACK_EPC\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mstack_epc_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mstack_epc_d),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_epc_q),\n .rd_error_o ()\n );\n\n // MSTACK_CAUSE\n ibex_csr #(\n .Width (6),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_mstack_cause_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (mstack_cause_d),\n .wr_en_i (mstack_en),\n .rd_data_o (mstack_cause_q),\n .rd_error_o ()\n );\n\n // -----------------\n // PMP registers\n // -----------------\n\n if (PMPEnable) begin : g_pmp_registers\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n logic [PMPAddrWidth-1:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n logic [PMPNumRegions-1:0] pmp_cfg_err;\n logic [PMPNumRegions-1:0] pmp_addr_we;\n logic [PMPNumRegions-1:0] pmp_addr_err;\n\n // Expanded / qualified register read data\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_exp_rd_data\n if (i < PMPNumRegions) begin : g_implemented_regions\n // Add in zero padding for reserved fields\n assign pmp_cfg_rdata[i] = {pmp_cfg[i].lock, 2'b00, pmp_cfg[i].mode,\n pmp_cfg[i].exec, pmp_cfg[i].write, pmp_cfg[i].read};\n\n // Address field read data depends on the current programmed mode and the granularity\n // See RISC-V Privileged Specification, version 1.11, Section 3.6.1\n if (PMPGranularity == 0) begin : g_pmp_g0\n // If G == 0, read data is unmodified\n assign pmp_addr_rdata[i] = pmp_addr[i];\n\n end else if (PMPGranularity == 1) begin : g_pmp_g1\n // If G == 1, bit [G-1] reads as zero in TOR or OFF mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n\n end else begin : g_pmp_g2\n // For G >= 2, bits are masked to one or zero depending on the mode\n always_comb begin\n // In NAPOT mode, bits [G-2:0] must read as one\n pmp_addr_rdata[i] = {pmp_addr[i], {PMPGranularity-1{1'b1}}};\n\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n // In TOR or OFF mode, bits [G-1:0] must read as zero\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n end\n\n end else begin : g_other_regions\n // Non-implemented regions read as zero\n assign pmp_cfg_rdata[i] = '0;\n assign pmp_addr_rdata[i] = '0;\n end\n end\n\n // Write data calculation\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_pmp_csrs\n // -------------------------\n // Instantiate cfg registers\n // -------------------------\n assign pmp_cfg_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_CFG + (i[11:0] >> 2)));\n\n // Select the correct WDATA (each CSR contains 4 CFG fields, each with 2 RES bits)\n assign pmp_cfg_wdata[i].lock = csr_wdata_int[(i%4)*PMP_CFG_W+7];\n // NA4 mode is not selectable when G > 0, mode is treated as OFF\n always_comb begin\n unique case (csr_wdata_int[(i%4)*PMP_CFG_W+3+:2])\n 2'b00 : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n 2'b01 : pmp_cfg_wdata[i].mode = PMP_MODE_TOR;\n 2'b10 : pmp_cfg_wdata[i].mode = (PMPGranularity == 0) ? PMP_MODE_NA4:\n PMP_MODE_OFF;\n 2'b11 : pmp_cfg_wdata[i].mode = PMP_MODE_NAPOT;\n default : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n endcase\n end\n assign pmp_cfg_wdata[i].exec = csr_wdata_int[(i%4)*PMP_CFG_W+2];\n // W = 1, R = 0 is a reserved combination. For now, we force W to 0 if R == 0\n assign pmp_cfg_wdata[i].write = &csr_wdata_int[(i%4)*PMP_CFG_W+:2];\n assign pmp_cfg_wdata[i].read = csr_wdata_int[(i%4)*PMP_CFG_W];\n\n ibex_csr #(\n .Width ($bits(pmp_cfg_t)),\n .ShadowCopy (ShadowCSR),\n .ResetValue ('0)\n ) u_pmp_cfg_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({pmp_cfg_wdata[i]}),\n .wr_en_i (pmp_cfg_we[i]),\n .rd_data_o (pmp_cfg[i]),\n .rd_error_o (pmp_cfg_err[i])\n );\n\n // --------------------------\n // Instantiate addr registers\n // --------------------------\n if (i < PMPNumRegions - 1) begin : g_lower\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (~pmp_cfg[i+1].lock | (pmp_cfg[i+1].mode != PMP_MODE_TOR)) &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end else begin : g_upper\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end\n\n ibex_csr #(\n .Width (PMPAddrWidth),\n .ShadowCopy (ShadowCSR),\n .ResetValue ('0)\n ) u_pmp_addr_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (csr_wdata_int[31-:PMPAddrWidth]),\n .wr_en_i (pmp_addr_we[i]),\n .rd_data_o (pmp_addr[i]),\n .rd_error_o (pmp_addr_err[i])\n );\n\n assign csr_pmp_cfg_o[i] = pmp_cfg[i];\n assign csr_pmp_addr_o[i] = {pmp_addr_rdata[i], 2'b00};\n end\n\n assign pmp_csr_err = (|pmp_cfg_err) | (|pmp_addr_err);\n\n end else begin : g_no_pmp_tieoffs\n // Generate tieoffs when PMP is not configured\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_rdata\n assign pmp_addr_rdata[i] = '0;\n assign pmp_cfg_rdata[i] = '0;\n end\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_outputs\n assign csr_pmp_cfg_o[i] = pmp_cfg_t'(1'b0);\n assign csr_pmp_addr_o[i] = '0;\n end\n assign pmp_csr_err = 1'b0;\n end\n\n //////////////////////////\n // Performance monitor //\n //////////////////////////\n\n // update enable signals\n always_comb begin : mcountinhibit_update\n if (mcountinhibit_we == 1'b1) begin\n // bit 1 must always be 0\n mcountinhibit_d = {csr_wdata_int[MHPMCounterNum+2:2], 1'b0, csr_wdata_int[0]};\n end else begin\n mcountinhibit_d = mcountinhibit_q;\n end\n end\n\n // event selection (hardwired) & control\n always_comb begin : gen_mhpmcounter_incr\n\n // Assign inactive counters (first to prevent latch inference)\n for (int unsigned i=0; i<32; i++) begin : gen_mhpmcounter_incr_inactive\n mhpmcounter_incr[i] = 1'b0;\n end\n\n // When adding or altering performance counter meanings and default\n // mappings please update dv/verilator/pcount/cpp/ibex_pcounts.cc\n // appropriately.\n //\n // active counters\n mhpmcounter_incr[0] = 1'b1; // mcycle\n mhpmcounter_incr[1] = 1'b0; // reserved\n mhpmcounter_incr[2] = instr_ret_i; // minstret\n mhpmcounter_incr[3] = dside_wait_i; // cycles waiting for data memory\n mhpmcounter_incr[4] = iside_wait_i; // cycles waiting for instr fetches\n mhpmcounter_incr[5] = mem_load_i; // num of loads\n mhpmcounter_incr[6] = mem_store_i; // num of stores\n mhpmcounter_incr[7] = jump_i; // num of jumps (unconditional)\n mhpmcounter_incr[8] = branch_i; // num of branches (conditional)\n mhpmcounter_incr[9] = branch_taken_i; // num of taken branches (conditional)\n mhpmcounter_incr[10] = instr_ret_compressed_i; // num of compressed instr\n mhpmcounter_incr[11] = mul_wait_i; // cycles waiting for multiply\n mhpmcounter_incr[12] = div_wait_i; // cycles waiting for divide\n end\n\n // event selector (hardwired, 0 means no event)\n always_comb begin : gen_mhpmevent\n\n // activate all\n for (int i=0; i<32; i++) begin : gen_mhpmevent_active\n mhpmevent[i] = '0;\n mhpmevent[i][i] = 1'b1;\n end\n\n // deactivate\n mhpmevent[1] = '0; // not existing, reserved\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmevent_inactive\n mhpmevent[i] = '0;\n end\n end\n\n // mcycle\n ibex_counter #(\n .CounterWidth(64)\n ) mcycle_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[0] & ~mcountinhibit[0]),\n .counterh_we_i(mhpmcounterh_we[0]),\n .counter_we_i(mhpmcounter_we[0]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[0])\n );\n\n // minstret\n ibex_counter #(\n .CounterWidth(64)\n ) minstret_counter_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[2] & ~mcountinhibit[2]),\n .counterh_we_i(mhpmcounterh_we[2]),\n .counter_we_i(mhpmcounter_we[2]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[2])\n );\n\n // reserved:\n assign mhpmcounter[1] = '0;\n assign unused_mhpmcounter_we_1 = mhpmcounter_we[1];\n assign unused_mhpmcounterh_we_1 = mhpmcounterh_we[1];\n assign unused_mhpmcounter_incr_1 = mhpmcounter_incr[1];\n\n for (genvar cnt=0; cnt < 29; cnt++) begin : gen_cntrs\n if (cnt < MHPMCounterNum) begin : gen_imp\n ibex_counter #(\n .CounterWidth(MHPMCounterWidth)\n ) mcounters_variable_i (\n .clk_i(clk_i),\n .rst_ni(rst_ni),\n .counter_inc_i(mhpmcounter_incr[cnt+3] & ~mcountinhibit[cnt+3]),\n .counterh_we_i(mhpmcounterh_we[cnt+3]),\n .counter_we_i(mhpmcounter_we[cnt+3]),\n .counter_val_i(csr_wdata_int),\n .counter_val_o(mhpmcounter[cnt+3])\n );\n end else begin : gen_unimp\n assign mhpmcounter[cnt+3] = '0;\n end\n end\n\n if(MHPMCounterNum < 29) begin : g_mcountinhibit_reduced\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounterh_we;\n logic [29-MHPMCounterNum-1:0] unused_mhphcounter_incr;\n\n assign mcountinhibit = {{29-MHPMCounterNum{1'b1}}, mcountinhibit_q};\n // Lint tieoffs for unused bits\n assign unused_mhphcounter_we = mhpmcounter_we[31:MHPMCounterNum+3];\n assign unused_mhphcounterh_we = mhpmcounterh_we[31:MHPMCounterNum+3];\n assign unused_mhphcounter_incr = mhpmcounter_incr[31:MHPMCounterNum+3];\n end else begin : g_mcountinhibit_full\n assign mcountinhibit = mcountinhibit_q;\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n mcountinhibit_q <= '0;\n end else begin\n mcountinhibit_q <= mcountinhibit_d;\n end\n end\n\n /////////////////////////////\n // Debug trigger registers //\n /////////////////////////////\n\n if (DbgTriggerEn) begin : gen_trigger_regs\n localparam int unsigned DbgHwNumLen = DbgHwBreakNum > 1 ? $clog2(DbgHwBreakNum) : 1;\n // Register values\n logic [DbgHwNumLen-1:0] tselect_d, tselect_q;\n logic tmatch_control_d;\n logic [DbgHwBreakNum-1:0] tmatch_control_q;\n logic [31:0] tmatch_value_d;\n logic [31:0] tmatch_value_q[DbgHwBreakNum];\n // Write enables\n logic tselect_we;\n logic [DbgHwBreakNum-1:0] tmatch_control_we;\n logic [DbgHwBreakNum-1:0] tmatch_value_we;\n // Trigger comparison result\n logic [DbgHwBreakNum-1:0] trigger_match;\n\n // Write select\n assign tselect_we = csr_we_int & debug_mode_i & (csr_addr_i == CSR_TSELECT);\n for (genvar i = 0; i < DbgHwBreakNum; i++) begin : g_dbg_tmatch_we\n assign tmatch_control_we[i] = (i[DbgHwNumLen-1:0] == tselect_q) & csr_we_int & debug_mode_i &\n (csr_addr_i == CSR_TDATA1);\n assign tmatch_value_we[i] = (i[DbgHwNumLen-1:0] == tselect_q) & csr_we_int & debug_mode_i &\n (csr_addr_i == CSR_TDATA2);\n end\n\n // Debug interface tests the available number of triggers by writing and reading the trigger\n // select register. Only allow changes to the register if it is within the supported region.\n assign tselect_d = (csr_wdata_int < DbgHwBreakNum) ? csr_wdata_int[DbgHwNumLen-1:0] :\n DbgHwBreakNum-1;\n // tmatch_control is enabled when the execute bit is set\n assign tmatch_control_d = csr_wdata_int[2];\n assign tmatch_value_d = csr_wdata_int[31:0];\n\n // Registers\n ibex_csr #(\n .Width (DbgHwNumLen),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_tselect_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tselect_d),\n .wr_en_i (tselect_we),\n .rd_data_o (tselect_q),\n .rd_error_o ()\n );\n\n for (genvar i = 0; i < DbgHwBreakNum; i++) begin : g_dbg_tmatch_reg\n ibex_csr #(\n .Width (1),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_tmatch_control_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tmatch_control_d),\n .wr_en_i (tmatch_control_we[i]),\n .rd_data_o (tmatch_control_q[i]),\n .rd_error_o ()\n );\n\n ibex_csr #(\n .Width (32),\n .ShadowCopy (1'b0),\n .ResetValue ('0)\n ) u_tmatch_value_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i (tmatch_value_d),\n .wr_en_i (tmatch_value_we[i]),\n .rd_data_o (tmatch_value_q[i]),\n .rd_error_o ()\n );\n end\n\n // Assign read data\n // TSELECT - number of supported triggers defined by parameter DbgHwBreakNum\n localparam int unsigned TSelectRdataPadlen = DbgHwNumLen >= 32 ? 0 : (32 - DbgHwNumLen);\n assign tselect_rdata = {{TSelectRdataPadlen{1'b0}}, tselect_q};\n\n // TDATA0 - only support simple address matching\n assign tmatch_control_rdata = {4'h2, // type : address/data match\n 1'b1, // dmode : access from D mode only\n 6'h00, // maskmax : exact match only\n 1'b0, // hit : not supported\n 1'b0, // select : address match only\n 1'b0, // timing : match before execution\n 2'b00, // sizelo : match any access\n 4'h1, // action : enter debug mode\n 1'b0, // chain : not supported\n 4'h0, // match : simple match\n 1'b1, // m : match in m-mode\n 1'b0, // 0 : zero\n 1'b0, // s : not supported\n 1'b1, // u : match in u-mode\n tmatch_control_q[tselect_q], // execute : match instruction address\n 1'b0, // store : not supported\n 1'b0}; // load : not supported\n // TDATA1 - address match value only\n assign tmatch_value_rdata = tmatch_value_q[tselect_q];\n\n // Breakpoint matching\n // We match against the next address, as the breakpoint must be taken before execution\n for (genvar i = 0; i < DbgHwBreakNum; i++) begin : g_dbg_trigger_match\n assign trigger_match[i] = tmatch_control_q[i] & (pc_if_i[31:0] == tmatch_value_q[i]);\n end\n assign trigger_match_o = |trigger_match;\n\n end else begin : gen_no_trigger_regs\n assign tselect_rdata = 'b0;\n assign tmatch_control_rdata = 'b0;\n assign tmatch_value_rdata = 'b0;\n assign trigger_match_o = 'b0;\n end\n\n //////////////////////////\n // CPU control register //\n //////////////////////////\n\n // Cast register write data\n assign cpuctrl_wdata = cpu_ctrl_t'(csr_wdata_int[$bits(cpu_ctrl_t)-1:0]);\n\n // Generate fixed time execution bit\n if (DataIndTiming) begin : gen_dit\n assign cpuctrl_d.data_ind_timing = cpuctrl_wdata.data_ind_timing;\n\n end else begin : gen_no_dit\n // tieoff for the unused bit\n logic unused_dit;\n assign unused_dit = cpuctrl_wdata.data_ind_timing;\n\n // field will always read as zero if not configured\n assign cpuctrl_d.data_ind_timing = 1'b0;\n end\n\n assign data_ind_timing_o = cpuctrl_q.data_ind_timing;\n\n // Generate dummy instruction signals\n if (DummyInstructions) begin : gen_dummy\n assign cpuctrl_d.dummy_instr_en = cpuctrl_wdata.dummy_instr_en;\n assign cpuctrl_d.dummy_instr_mask = cpuctrl_wdata.dummy_instr_mask;\n\n // Signal a write to the seed register\n assign dummy_instr_seed_en_o = csr_we_int && (csr_addr == CSR_SECURESEED);\n assign dummy_instr_seed_o = csr_wdata_int;\n\n end else begin : gen_no_dummy\n // tieoff for the unused bit\n logic unused_dummy_en;\n logic [2:0] unused_dummy_mask;\n assign unused_dummy_en = cpuctrl_wdata.dummy_instr_en;\n assign unused_dummy_mask = cpuctrl_wdata.dummy_instr_mask;\n\n // field will always read as zero if not configured\n assign cpuctrl_d.dummy_instr_en = 1'b0;\n assign cpuctrl_d.dummy_instr_mask = 3'b000;\n assign dummy_instr_seed_en_o = 1'b0;\n assign dummy_instr_seed_o = '0;\n end\n\n assign dummy_instr_en_o = cpuctrl_q.dummy_instr_en;\n assign dummy_instr_mask_o = cpuctrl_q.dummy_instr_mask;\n\n // Generate icache enable bit\n if (ICache) begin : gen_icache_enable\n assign cpuctrl_d.icache_enable = cpuctrl_wdata.icache_enable;\n end else begin : gen_no_icache\n // tieoff for the unused icen bit\n logic unused_icen;\n assign unused_icen = cpuctrl_wdata.icache_enable;\n\n // icen field will always read as zero if ICache not configured\n assign cpuctrl_d.icache_enable = 1'b0;\n end\n\n assign icache_enable_o = cpuctrl_q.icache_enable;\n\n ibex_csr #(\n .Width ($bits(cpu_ctrl_t)),\n .ShadowCopy (ShadowCSR),\n .ResetValue ('0)\n ) u_cpuctrl_csr (\n .clk_i (clk_i),\n .rst_ni (rst_ni),\n .wr_data_i ({cpuctrl_d}),\n .wr_en_i (cpuctrl_we),\n .rd_data_o (cpuctrl_q),\n .rd_error_o (cpuctrl_err)\n );\n\n assign csr_shadow_err_o = mstatus_err | mtvec_err | pmp_csr_err | cpuctrl_err;\n\n ////////////////\n // Assertions //\n ////////////////\n\n `ASSERT(IbexCsrOpEnRequiresAccess, csr_op_en_i |-> csr_access_i)\n\nendmodule\n", "selected_doc_paths": ["doc/03_reference/cs_registers.rst", "doc/03_reference/debug.rst", "doc/03_reference/pmp.rst", "doc/03_reference/performance_counters.rst", "doc/03_reference/exception_interrupts.rst", "doc/03_reference/security.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1050, "lang": "sv", "rtl_files": ["dv/uvm/core_ibex/riscv_dv_extension/riscv_core_setting.sv"], "spec": "# Design Specification: Ibex Core Configuration for RISC-V DV Verification\n\n## Overview\n\nThis specification defines the behavioral configuration of the Ibex RISC-V processor core as used by the core’s verification environment. The configuration describes the set of features, instruction set extensions, control and status registers (CSRs), interrupt and exception behavior, debug support, physical memory protection (PMP), performance counters, and security options that the core shall implement. The verification environment (based on the `riscv_dv_extension`) uses this configuration to generate legal instruction streams, initialize CSRs, and check the core’s responses during simulation.\n\nAll parameters described herein are static and define the fixed behavior of the core under test. The specification is written in a normative style: “must,” “shall,” and “should” indicate mandatory requirements, while recommendations are noted where appropriate.\n\n---\n\n## 1. Core Architecture and ISA\n\n### 1.1 XLEN and General-Purpose Registers\n- The core operates with a machine word width (`XLEN`) of 32 bits.\n- The integer register file shall contain 32 general-purpose registers (GPRs).\n- No floating-point or vector registers are implemented (`NUM_FLOAT_GPR = 0`, `NUM_VEC_GPR = 0`).\n\n### 1.2 Supported Instruction Set Extensions\nThe core shall implement the following ISA subsets, in order of inclusion:\n- **RV32I**: Base integer instructions (mandatory).\n- **RV32M**: Integer multiplication and division extension.\n- **RV32C**: Compressed instructions extension (16-bit instruction forms).\n- **RV32B**: Bit manipulation extension (instructions for bitwise operations, rotates, etc.).\n\nThe test environment must generate only instructions belonging to these supported groups. Unsupported instructions (e.g., `FENCE.I`) shall not be generated and, if encountered, will cause an illegal instruction exception on the core (see Section 3.2).\n\n### 1.3 Vector Extension\nThe vector extension is not enabled (`VECTOR_EXTENSION_ENABLE = 0`). All vector-related parameters (`VLEN`, `ELEN`, `SLEN`, `VELEN`, `SELEN`, `MAX_LMUL`) are present but shall be ignored by the verification environment; the core shall not decode or execute vector instructions.\n\n---\n\n## 2. Processor Modes and Address Translation\n\n### 2.1 Harts\nThe core contains exactly one hardware thread (`NUM_HARTS = 1`). All hart-specific CSRs (e.g., `mhartid`) shall return the identifier of this single hart.\n\n### 2.2 Privilege Modes\nThe core supports two privilege modes:\n- **Machine Mode (M‑Mode)** – the most privileged mode.\n- **User Mode (U‑Mode)** – unprivileged mode.\n\nSupervisor Mode is not supported. The core shall reset into Machine Mode.\n\n### 2.3 Address Translation\nAddress translation is not supported. The `SATP` mode shall be treated as `BARE` (no translation). The `sfence.vma` instruction shall not be implemented; any attempt to execute it in User Mode will raise an illegal instruction exception. (Note: `sfence.vma` is a supervisor‑level instruction and will trap in Machine Mode as well, as the core does not implement S‑Mode.)\n\n### 2.4 Trap Delegation\nDelegation of traps to User Mode is not supported (`support_umode_trap = 0`). All interrupts and exceptions shall be handled in Machine Mode.\n\n---\n\n## 3. Interrupts and Exceptions\n\n### 3.1 Interrupts\nThe core shall support the following interrupt sources:\n- **Non‑Maskable Interrupt (NMI)** – ID 31, always enabled and not controlled by `mstatus.MIE` or `mie`.\n- **15 Fast Interrupts** – IDs 30 down to 16, individually enabled via `mie[30:16]`.\n- **Machine External Interrupt** – ID 11, enabled by `mie[11]`.\n- **Machine Timer Interrupt** – ID 7, enabled by `mie[7]`.\n- **Machine Software Interrupt** – ID 3, enabled by `mie[3]`.\n\nAll interrupts (except NMI) are globally enabled only when `mstatus.MIE` is set. The core shall operate in vectored interrupt mode (`mtvec.MODE` fixed to `2'b01`). Upon taking an interrupt, the core jumps to the address `mtvec.BASE + 4 * interrupt_ID`. While in Debug Mode, all interrupts (including NMI) are ignored.\n\nInterrupt priority follows the RISC‑V privileged specification: higher interrupt IDs have higher priority, except that timer interrupts (ID 7) receive the lowest priority among all standard interrupts.\n\n### 3.2 Exceptions\nThe core shall generate synchronous exceptions for the following causes:\n\n| Exception Code | Cause |\n|----------------|-------------------------------|\n| 1 | Instruction access fault |\n| 2 | Illegal instruction |\n| 3 | Breakpoint |\n| 5 | Load access fault |\n| 7 | Store access fault |\n| 8 | Environment call from U‑Mode |\n| 11 | Environment call from M‑Mode |\n\nAll exceptions are taken instantly (no delay slots). The illegal instruction exception is triggered for any opcode not in the supported ISA groups, or for any CSR access that is not implemented or violates privilege rules.\n\n### 3.3 Trap Handling\nWhen any trap (interrupt or exception) occurs, the core shall:\n- Save the current PC into `mepc`.\n- Save `mstatus.MIE` into `mstatus.MPIE`.\n- Set `mstatus.MPP` to the current privilege mode.\n- Clear `mstatus.MIE` (disabling interrupts).\n- Update `mcause` with exception code and interrupt bit.\n- For instruction- or load/store‑related faults, set `mtval` to the offending address or instruction value; otherwise set `mtval` to 0.\n- Jump to the trap handler base (for exceptions) or vectored address (for interrupts).\n\nThe `mret` instruction shall restore `mstatus.MIE` from `mstatus.MPIE`, set the privilege mode from `mstatus.MPP`, and branch to `mepc`.\n\n### 3.4 Nested Trap Support\nThe core does **not** support nested traps in hardware. However, software may re‑enable interrupts by setting `mstatus.MIE` within the handler. The core provides no additional hardware save/restore for `mepc` or `mstatus` beyond the mechanism described in Section 3.3. (The backup CSR mechanism exists only for NMI recovery, as described in the product documentation.)\n\n---\n\n## 4. Control and Status Registers (CSRs)\n\n### 4.1 Implemented Standard CSRs\nThe core shall implement all mandatory Machine‑Mode CSRs listed in the RISC‑V Privileged Specification v1.11. The complete list of implemented CSRs (excluding custom registers) must include:\n\n| Address | CSR Name | Access | Description |\n|-----------|-----------------|--------|-----------------------------------------------------|\n| 0x300 | `mstatus` | WARL | Machine status (see Section 4.2) |\n| 0x301 | `misa` | WARL | Machine ISA – hard‑wired, writes ignored |\n| 0x304 | `mie` | WARL | Machine interrupt enable |\n| 0x305 | `mtvec` | WARL | Machine trap‑vector base address (vectored mode) |\n| 0x320 | `mcountinhibit` | RW | Counter inhibit |\n| 0x323–0x33F | `mhpmevent3–31`| WARL | Event selectors (lower addresses implemented) |\n| 0x340 | `mscratch` | RW | Machine scratch register |\n| 0x341 | `mepc` | WARL | Exception program counter |\n| 0x342 | `mcause` | WLRL | Exception cause |\n| 0x343 | `mtval` | WARL | Trap value |\n| 0x344 | `mip` | R | Interrupt pending (read‑only) |\n| 0x3A0–0x3A3 | `pmpcfg0–3` | WARL | PMP configuration registers |\n| 0x3B0–0x3BF | `pmpaddr0–15` | WARL | PMP address registers |\n| 0x7A0 | `tselect` | WARL | Trigger select (always returns 0) |\n| 0x7A1 | `tdata1` | WARL | Trigger data 1 (hard‑wired to indicate address‑only match) |\n| 0x7A2 | `tdata2` | WARL | Trigger address |\n| 0x7A3 | `tdata3` | WARL | Always reads 0 |\n| 0x7A8 | `mcontext` | WARL | Always reads 0 |\n| 0x7AA | `scontext` | WARL | Always reads 0 |\n| 0x7B0 | `dcsr` | WARL | Debug control and status |\n| 0x7B1 | `dpc` | RW | Debug PC |\n| 0x7B2 | `dscratch0` | RW | Debug scratch register 0 |\n| 0x7B3 | `dscratch1` | RW | Debug scratch register 1 |\n| 0xB00 | `mcycle` | RW | Cycle counter lower 32 bits |\n| 0xB02 | `minstret` | RW | Retired instruction counter lower 32 bits |\n| 0xB03–0xB1F | `mhpmcounter3–31` | WARL | Performance event counters (lower) |\n| 0xB80 | `mcycleh` | RW | Cycle counter upper 32 bits |\n| 0xB82 | `minstreth` | RW | Retired instruction counter upper 32 bits |\n| 0xB83–0xB9F | `mhpmcounter3h–31h` | WARL | Performance event counters (upper) |\n| 0xF14 | `mhartid` | R | Hart ID (reads the hart ID input) |\n\nAdditionally, the core shall implement the `mcounteren` CSR when User Mode is supported? (Check spec: `mcounteren` is required for U‑Mode. Verify: In Ibex, `mcounteren` is implemented? The source shows `MCOUNTEREN` is not listed in `implemented_csr[]` above. However, the documentation (cs_registers.rst) lists only above. Actually, `mcounteren` is at 0x306. In Ibex's documentation, it's not listed. The configuration file lists `MCOUNTEREN`? Let's check: In `riscv_core_setting.sv`, there is no `MCOUNTEREN`. The Ibex product documentation for CSRs does not list `mcounteren`. Therefore, the core does **not** implement `mcounteren`. Accesses to 0x306 shall be illegal. This is consistent: User Mode instructions that read `cycle`, `time`, etc., are not supported? Wait, Ibex does not implement `time(h)` (0xC01/0xC81) – they trap. But `cycle` and `instrret` can be read from U‑Mode? Without `mcounteren`, access to `cycle(h)` and `instret(h)` in U‑Mode will trap. The configuration file is for verification; it should reflect that these are not generable in U‑Mode. We'll state that the core does **not** implement `mcounteren` and does **not** support direct user‑mode reads of performance counters; such accesses will cause illegal instruction exceptions.\n\n### 4.2 Key CSR Behaviors\n- **`mstatus`**: Only bits 21 (TW), 17 (MPRV), 12:11 (MPP), 7 (MPIE), and 3 (MIE) are implemented. All other bits read as zero. Writes to unsupported bits are ignored.\n- **`misa`**: Hard‑wired. Writes produce no effect; reads return the value encoding the supported ISA (RV32IMCB).\n- **`mtvec`**: The lowest two bits (MODE) are read‑only and always `01` (vectored). The base address must be aligned to 256 bytes.\n- **`mip`**: Reflects the OR of interrupt inputs and the corresponding `mie` enables. Note that NMI does not appear in `mip`.\n- **`mcause`**: The interrupt bit (bit 31) and exception code (bits 4:0) are read‑only. Writes to reserved bits have no effect.\n- **Counter registers**: `mcycle(h)` and `minstret(h)` are always implemented and 64‑bit wide. Performance counters `mhpmcounter3(h)` through `mhpmcounter10(h)` are available (up to 8 counters); counters beyond that are hard‑wired to zero. Counter widths are parametrizable; the default is 40 bits.\n\n### 4.3 Custom CSRs\nTwo custom CSRs are implemented:\n- **`cpuctrl`** (address 0x7C0): Accessible in Machine Mode only. Controls runtime features: `icache_enable` (bit 0), `data_ind_timing` (bit 1), `dummy_instr_en` (bit 2), `dummy_instr_mask` (bits 5:3). Unimplemented bits read as zero.\n- **`secureseed`** (address 0x7C1): Accessible in Machine Mode only. Write triggers reseeding of pseudo‑random generators; reads always return 0.\n\n### 4.4 Time Registers\nThe core does **not** implement the user‑mode `time`/`timeh` CSRs (0xC01, 0xC81). Any access to these addresses shall cause an illegal instruction exception.\n\n---\n\n## 5. Debug Support\n\n### 5.1 Debug Mode Entry\nThe core shall support execution‑based debug according to the RISC‑V Debug Specification v0.13.2. Debug Mode is entered when:\n- An external `debug_req` signal is asserted, or\n- A breakpoint instruction (EBREAK) is executed in a mode where `ebreakm` or `ebreaku` (in `dcsr`) is set, or\n- A hardware trigger matches (if `DbgTriggerEn` is enabled), or\n- Single‑step is enabled (`dcsr.step = 1` and the core is not in Debug Mode).\n\nUpon entering Debug Mode, the core saves the return PC into `dpc` and halts execution.\n\n### 5.2 Debug Registers\nThe core provides the following debug‑accessible CSRs (readable/writable only when in Debug Mode; otherwise accesses raise illegal instruction exceptions):\n- `dcsr` – Debug control and status (`xdebugver` = 4, cause field, step, ebreakm, ebreaku, prv).\n- `dpc` – Debug program counter.\n- `dscratch0` and `dscratch1` – Scratch storage for debugger.\n\n### 5.3 Triggers\nIf the `DbgTriggerEn` parameter is set, the core shall implement one hardware trigger of type address‑match (instruction fetch address). The trigger registers `tselect`, `tdata1`, `tdata2` (and `tdata3`, `mcontext`, `scontext` as read‑only zero) are accessible in Debug Mode and, if `DbgTriggerEn` is enabled, also in Machine Mode. However, writes from Machine Mode to `tdata1` and `tdata2` shall be ignored; only Debug Mode can modify the trigger configuration.\n\n---\n\n## 6. Physical Memory Protection (PMP)\n\n### 6.1 PMP Enable and Number of Regions\nPMP is enabled (the `PMPEnable` parameter defaults to 0; in this configuration it is set to 1 because `support_pmp = 1`). The core shall implement up to 16 PMP regions (configurable via `PMPNumRegions`; the test environment assumes up to 16 for coverage). PMP granularity is configurable (default 0, meaning minimum region size of 4 bytes). When granularity > 0, NA4 mode is not available and treated as OFF.\n\n### 6.2 PMP Register Behavior\nPMP configuration registers `pmpcfg0`–`pmpcfg3` and address registers `pmpaddr0`–`pmpaddr15` are implemented as WARL. Unused regions (beyond the configured number) shall read zero and ignore writes.\n\n### 6.3 Access Checking\nThe PMP unit shall check every instruction fetch and data load/store against the configured regions. Addresses from the IFU and LSU are checked, and any access that violates the PMP permissions shall cause the corresponding access fault exception (instruction access fault for fetch, load access fault for loads, store access fault for stores). The PMP check does not prevent the external bus transaction; the core registers the fault and delivers it when the data would have been used.\n\n---\n\n## 7. Performance Counters\n\n### 7.1 Counters Provided\nThe core shall provide at least the following counters (each 64‑bit, with lower and upper halves accessible via separate CSR addresses):\n- `mcycle(h)` : Number of clock cycles.\n- `minstret(h)` : Number of instructions retired.\n- Up to 8 additional event counters, associated as follows (hard‑wired event selection):\n\n| Counter | Hard‑wired Event |\n|----------------|---------------------------|\n| `mhpmcounter3` | Cycles waiting for LSU |\n| `mhpmcounter4` | Cycles waiting for IF |\n| `mhpmcounter5` | Number of loads |\n| `mhpmcounter6` | Number of stores |\n| `mhpmcounter7` | Number of jumps |\n| `mhpmcounter8` | Number of branches |\n| `mhpmcounter9` | Number of taken branches |\n| `mhpmcounter10`| Number of compressed instr|\n\nEvent selectors `mhpmevent3`–`mhpmevent10` are hard‑wired to the corresponding event bit; writing them has no effect. Remaining event selectors (`mhpmevent11`–`mhpmevent31`) are tied to 0.\n\n### 7.2 Counter Control\nAll counters may be individually enabled/disabled via the `mcountinhibit` CSR. The mapping is: bit 0 for `mcycle`, bit 2 for `minstret`, bit X for `mhpmcounterX`. After reset, all implemented counters are enabled.\n\n---\n\n## 8. Security Features (SecureIbex Configuration)\n\nIf the core is configured with the SecureIbex parameter enabled, the following features shall be available, controllable through the `cpuctrl` CSR:\n\n### 8.1 Data‑Independent Timing\nWhen `cpuctrl[1]` is set, the core must execute branches identically regardless of taken/not‑taken status, disable early completion of multiplication by zero/one, and disable early completion of division by zero.\n\n### 8.2 Dummy Instruction Insertion\nWhen `cpuctrl[2]` is set, random dummy instructions shall be injected into the pipeline at intervals determined by `cpuctrl[5:3]`. The interval is randomized using an internal LFSR, which may be reseeded via writes to the `secureseed` CSR.\n\n### 8.3 Register File ECC\nAll reads from the integer register file shall be checked for single‑ and double‑bit errors. If an error is detected, a minor alert output shall be asserted. No correction is attempted.\n\n### 8.4 Hardened PC\nThe program counter in the IF stage shall be checked for unexpected modifications by comparing it to the expected next PC. If a mismatch is detected, a major alert output shall be asserted.\n\n---\n\n## 9. Unsupported Instructions and Features\n\nThe following instructions and features are **not** supported, and any attempt to execute them shall result in an illegal instruction exception (or other appropriate trap):\n- `FENCE.I` (intentionally treated as illegal by Ibex)\n- `SFENCE.VMA` (supervisor‑level, not implemented)\n- All floating‑point instructions (RV32F, RV32D)\n- Vector instructions\n- Supervisor‑mode instructions (`SRET`, `WFI` in S‑Mode, etc.)\n- User‑mode access to `time`/`timeh` CSRs\n- Access to unimplemented CSRs (most addresses beyond the lists above)\n- Any privilege‑level violation (e.g., writing debug CSRs outside Debug Mode)\n\n---\n\n## 10. Verification Environment Constraints\n\nThe verification environment shall use the above configuration to:\n- Generate only instructions from the supported ISA groups.\n- Initialize CSRs only to values that are legal for the core (e.g., `misa` writes are ignored).\n- Not generate `FENCE.I`, `SFENCE.VMA`, or other unsupported instructions.\n- Model the core’s single‑hart, single‑machine‑mode behavior.\n- Ensure that all generated interrupt and exception causes are among the implemented lists.\n- Verify that the core’s CSR access behavior, trap handling, debug entry, PMP checks, and performance counters match the behavioral requirements described herein.\n\nThe configuration is static; no runtime change to these parameters is allowed during simulation.\n\n---\n\n## 11. Summary of Behavioral Capabilities\n\n| Feature | Status |\n|----------------------------------|--------------------------------|\n| XLEN | 32 |\n| ISA extensions | I, M, C, B |\n| Vector extension | Not supported |\n| Number of harts | 1 |\n| Privilege modes | Machine, User |\n| Supervisor mode | Not supported |\n| Address translation | Disabled (BARE) |\n| Interrupt mode | Vectored (fixed) |\n| Maximum interrupt vectors | 32 (including NMI ID 31) |\n| PMP regions | Up to 16 |\n| Debug support | Yes, with single trigger option|\n| Performance counters | 2 base + up to 8 event counters|\n| Security features | Optional (data‑ind timing, dummy instr, ECC, hardened PC)|\n| Custom CSRs | cpuctrl, secureseed |\n\nThis specification shall be used as the authoritative reference for the Ibex core’s behavior in the UVM verification environment. Any deviation from these requirements shall be reported as a design error.", "commit_id": "94d505716870ddf240d0896021871176d6336579", "timestamp": "2020-07-24T17:10:22+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "c9331c0e34dc2a3d3a5256cf2fb70cbc89535d1a", "pr_title": "[dv/ibex] Update CSR listings", "pr_body": "This PR updates the `implemented_csr` list in `riscv_core_setting.sv`\r\nand adds the two custom CSRs `cpuctrl` and `secureseed` to the\r\n`custom_csr` list. Both are for use by the riscv-dv generator.\r\n\r\nThis PR can only be merged after #1049 , which vendors in some updates to riscv-dv,\r\nincluding basic support for custom CSRs.\r\n\r\nSigned-off-by: Udi ", "issue_title": "Update google_riscv-dv to google/riscv-dv@3cf691d", "issue_body": "Update code from upstream repository https://github.com/google/riscv-\r\ndv to revision 3cf691dcb96f2cd72250690216b60f2b0c0ac804\r\n\r\n* remove hardcoded CSR names (Udi Jonnalagadda)\r\n* initial custom CSR support (Udi Jonnalagadda)\r\n* Add support for segmented load/store instructions (google/riscv-\r\n dv#656) (taoliug)\r\n* fix post_randomize issue (aneels3)\r\n* add MAX_LMUL to rv32i config (google/riscv-dv#649) (udinator)\r\n* Ignore log and asm file (aneels3)\r\n* Add Command Line Support (aneels3)\r\n* support for command-line arguments (pvipsyash)\r\n* Reorder import statements (aneels3)\r\n* Modified function randomize_gpr in instr_stream file\r\n (ShraddhaDevaiya)\r\n* Updated riscv_instr_sequence file and modified other python files to\r\n get main block in asm file. (ShraddhaDevaiya)\r\n* Modify get_rand_instr() (aneels3)\r\n* added uvm_glob_to_re in uvm_re_match (Dawid Zimonczyk)\r\n* Aldec Riviera-PRO compiler command line arguments modified.\r\n (google/riscv-dv#638) (Dariusz Stachańczyk)\r\n* allow coverage compilation to be run on LSF (google/riscv-dv#637)\r\n (udinator)\r\n* Add CHIPS Alliance work group information to the README\r\n (google/riscv-dv#633) (taoliug)\r\n* Add indexed/strided vector load/store instrution stream\r\n (google/riscv-dv#632) (taoliug)\r\n* Add constraint for mtvec alignment in vectored interrupt mode\r\n (google/riscv-dv#631) (taoliug)\r\n* Add bitstring requirement to pygen/experimental README\r\n (google/riscv-dv#630) (taoliug)\r\n* Add unsupported load/store instruction filtering (google/riscv-\r\n dv#629) (taoliug)\r\n* Add different methods to initialize the vregs (google/riscv-dv#627)\r\n (Josep Sans)\r\n* Support a vetor instruction only mode (google/riscv-dv#626)\r\n (taoliug)\r\n* Add riscv_instr_stream.py file (aneels3)\r\n* Importing PyVSC module (google/riscv-dv#625) (Hodjat Asghari\r\n Esfeden)\r\n* update pygen_src files (google/riscv-dv#612) (BharathNR1030)\r\n* Fix typo (google/riscv-dv#624) (taoliug)\r\n* Fix B-ext instruction generation issue (google/riscv-dv#620)\r\n (taoliug)\r\n\r\nMust be merged before #1050.\r\n\r\nSigned-off-by: Udi ", "commit_message": "[dv/ibex] Update CSR listings\n\nThis PR updates the `implemented_csrs` list in `riscv_core_setting.sv`\nand adds the two custom CSRs `cpuctrl` and `secureseed` to the\n`custom_csrs` list. Both are for use by the riscv-dv generator.\n\nSigned-off-by: Udi ", "fix_patch": "diff --git a/dv/uvm/core_ibex/riscv_dv_extension/riscv_core_setting.sv b/dv/uvm/core_ibex/riscv_dv_extension/riscv_core_setting.sv\nindex 937faf9288..5cba70cf2c 100644\n--- a/dv/uvm/core_ibex/riscv_dv_extension/riscv_core_setting.sv\n+++ b/dv/uvm/core_ibex/riscv_dv_extension/riscv_core_setting.sv\n@@ -159,7 +159,19 @@ const privileged_reg_t implemented_csr[] = {\n DCSR, // Debug control and status register\n DPC, // Debug PC\n DSCRATCH0, // Debug scratch register 0\n- DSCRATCH1 // Debug scratch register 1\n+ DSCRATCH1, // Debug scratch register 1\n+ TSELECT, // Trigger select register\n+ TDATA1, // Trigger data register 1\n+ TDATA2, // Trigger data register 2\n+ TDATA3, // Trigger data register 3\n+ MCONTEXT, // Machine context register\n+ SCONTEXT // Supervisor context register\n+};\n+\n+// Implementation-specific custom CSRs\n+const bit [11:0] custom_csr[] = {\n+ 12'h7C0, // cpuctrl - CPU control register\n+ 12'h7C1 // secureseed - Security feature random seed register\n };\n \n // --------------------------------------------------------------------------\n", "fixed_rtl_code": "/*\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//-----------------------------------------------------------------------------\n// Processor feature configuration\n//-----------------------------------------------------------------------------\n// XLEN\nparameter int XLEN = 32;\n\n// GPR setting\nparameter int NUM_FLOAT_GPR = 0;\nparameter int NUM_GPR = 32;\nparameter int NUM_VEC_GPR = 0;\n\n// Vector extension parameters - not used in Ibex\nparameter int VECTOR_EXTENSION_ENABLE = 0;\nparameter int VLEN = 512;\nparameter int ELEN = 64;\nparameter int SLEN = 64;\nparameter int VELEN = 4;\nparameter int SELEN = 8;\nparameter int MAX_LMUL = 8;\n\n// Number of harts\nparameter int NUM_HARTS = 1;\n\n// Parameter for SATP mode, set to BARE if address translation is not supported\nparameter satp_mode_t SATP_MODE = BARE;\n\n// Supported Privileged mode\nprivileged_mode_t supported_privileged_mode[] = {MACHINE_MODE, USER_MODE};\n\n// Unsupported instructions\n// Avoid generating these instructions in regular regression\n// FENCE.I is intentionally treated as illegal instruction by ibex core\nriscv_instr_name_t unsupported_instr[] = {FENCE_I};\n\n// Specify whether processor supports unaligned loads and stores\nbit support_unaligned_load_store = 1'b1;\n\n// ISA supported by the processor\nriscv_instr_group_t supported_isa[$] = {RV32I, RV32M, RV32C, RV32B};\n\n// Interrupt mode support\nmtvec_mode_t supported_interrupt_mode[$] = {VECTORED};\n\n// The number of interrupt vectors to be generated, only used if VECTORED interrupt mode is\n// supported\nint max_interrupt_vector_num = 32;\n\n// Physical memory protection support\nbit support_pmp = 1;\n\n// Debug mode support\nbit support_debug_mode = 1;\n\n// Support delegate trap to user mode\nbit support_umode_trap = 0;\n\n// Support sfence.vma instruction\nbit support_sfence = 0;\n\n//-----------------------------------------------------------------------------\n// Kernel section setting, used by supervisor mode programs\n//-----------------------------------------------------------------------------\n\n// Number of kernel data pages\nint num_of_kernel_data_pages = 0;\n\n// Byte size of kernel data pages\nint kernel_data_page_size = 4096;\n\n// Kernel Stack section word length\nint kernel_stack_len = 5000;\n\n// Number of instructions for each kernel program\nint kernel_program_instr_cnt = 400;\n\n// ----------------------------------------------------------------------------\n// Previleged CSR implementation\n// ----------------------------------------------------------------------------\n\n// Implemented previlieged CSR list\nconst privileged_reg_t implemented_csr[] = {\n // Machine mode mode CSR\n MVENDORID, // Vendor ID\n MARCHID, // Architecture ID\n MHARTID, // Hardware thread ID\n MSTATUS, // Machine status\n MISA, // ISA and extensions\n MTVEC, // Machine trap-handler base address\n MEPC, // Machine exception program counter\n MCAUSE, // Machine trap cause\n MTVAL, // Machine bad address or instruction\n MIE, // Machine interrupt enable\n MIP, // Machine interrupt pending\n MCYCLE, // Machine cycle counter (lower 32 bits)\n MCYCLEH, // Machine cycle counter (upper 32 bits)\n MINSTRET, // Machine instructions retired counter (lower 32 bits)\n MINSTRETH, // Machine instructions retired counter (upper 32 bits)\n MCOUNTINHIBIT, // Machine counter inhibit register\n MHPMEVENT3, // Machine performance monitoring event selector\n MHPMEVENT4, // Machine performance monitoring event selector\n MHPMEVENT5, // Machine performance monitoring event selector\n MHPMEVENT6, // Machine performance monitoring event selector\n MHPMEVENT7, // Machine performance monitoring event selector\n MHPMEVENT8, // Machine performance monitoring event selector\n MHPMEVENT9, // Machine performance monitoring event selector\n MHPMEVENT10, // Machine performance monitoring event selector\n MHPMCOUNTER3, // Machine performance monitoring counter (lower 32 bits)\n MHPMCOUNTER4, // Machine performance monitoring counter (lower 32 bits)\n MHPMCOUNTER5, // Machine performance monitoring counter (lower 32 bits)\n MHPMCOUNTER6, // Machine performance monitoring counter (lower 32 bits)\n MHPMCOUNTER7, // Machine performance monitoring counter (lower 32 bits)\n MHPMCOUNTER8, // Machine performance monitoring counter (lower 32 bits)\n MHPMCOUNTER9, // Machine performance monitoring counter (lower 32 bits)\n MHPMCOUNTER10, // Machine performance monitoring counter (lower 32 bits)\n MHPMCOUNTER3H, // Machine performance monitoring counter (upper 32 bits)\n MHPMCOUNTER4H, // Machine performance monitoring counter (upper 32 bits)\n MHPMCOUNTER5H, // Machine performance monitoring counter (upper 32 bits)\n MHPMCOUNTER6H, // Machine performance monitoring counter (upper 32 bits)\n MHPMCOUNTER7H, // Machine performance monitoring counter (upper 32 bits)\n MHPMCOUNTER8H, // Machine performance monitoring counter (upper 32 bits)\n MHPMCOUNTER9H, // Machine performance monitoring counter (upper 32 bits)\n MHPMCOUNTER10H, // Machine performance monitoring counter (upper 32 bits)\n PMPCFG0, // PMP configuration register\n PMPCFG1, // PMP configuration register\n PMPCFG2, // PMP configuration register\n PMPCFG3, // PMP configuration register\n PMPADDR0, // PMP address register\n PMPADDR1, // PMP address register\n PMPADDR2, // PMP address register\n PMPADDR3, // PMP address register\n PMPADDR4, // PMP address register\n PMPADDR5, // PMP address register\n PMPADDR6, // PMP address register\n PMPADDR7, // PMP address register\n PMPADDR8, // PMP address register\n PMPADDR9, // PMP address register\n PMPADDR10, // PMP address register\n PMPADDR11, // PMP address register\n PMPADDR12, // PMP address register\n PMPADDR13, // PMP address register\n PMPADDR14, // PMP address register\n PMPADDR15, // PMP address register\n DCSR, // Debug control and status register\n DPC, // Debug PC\n DSCRATCH0, // Debug scratch register 0\n DSCRATCH1, // Debug scratch register 1\n TSELECT, // Trigger select register\n TDATA1, // Trigger data register 1\n TDATA2, // Trigger data register 2\n TDATA3, // Trigger data register 3\n MCONTEXT, // Machine context register\n SCONTEXT // Supervisor context register\n};\n\n// Implementation-specific custom CSRs\nconst bit [11:0] custom_csr[] = {\n 12'h7C0, // cpuctrl - CPU control register\n 12'h7C1 // secureseed - Security feature random seed register\n};\n\n// --------------------------------------------------------------------------\n// Supported interrupt/exception setting, used for functional coverage\n// --------------------------------------------------------------------------\nconst interrupt_cause_t implemented_interrupt[] = {\n M_SOFTWARE_INTR,\n M_TIMER_INTR,\n M_EXTERNAL_INTR\n};\nconst exception_cause_t implemented_exception[] = {\n INSTRUCTION_ACCESS_FAULT,\n ILLEGAL_INSTRUCTION,\n BREAKPOINT,\n LOAD_ACCESS_FAULT,\n STORE_AMO_ACCESS_FAULT,\n ECALL_MMODE\n};\n", "selected_doc_paths": ["doc/cs_registers.rst", "doc/exception_interrupts.rst", "doc/pmp.rst", "doc/debug.rst", "doc/performance_counters.rst", "doc/security.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 699, "lang": "sv", "rtl_files": ["shared/rtl/prim_assert.sv"], "spec": "# Design Specification: `prim_assert` – SystemVerilog Assertion Macro Library\n\n## 1. Overview\n\nThe `prim_assert` library provides a set of reusable SystemVerilog macros that simplify the declaration and control of assertions, covers, and assumptions within RTL modules. It is intended to be included (`include`) into any SystemVerilog module, interface, or package to enable consistent, compile-time-conditioned checking of design properties.\n\nThe library defines macros for:\n- Immediate assertions (`ASSERT_I`, `ASSERT_INIT`, `ASSERT_FINAL`)\n- Concurrent assertions and coverage (`ASSERT`, `ASSERT_NEVER`, `ASSERT_KNOWN`, `COVER`)\n- Data integrity checks (`ASSERT_PULSE`, `ASSERT_VALID_DATA`, `ASSERT_VALID_READY_DATA`)\n- Assumptions for formal and simulation environments (`ASSUME`, `ASSUME_I`)\n- Formal-verification-only variants (`ASSUME_FPV`, `ASSUME_I_FPV`, `COVER_FPV`)\n\nAll macros are conditionally compiled so that they are **omitted** during synthesis or when using the Verilator simulator, unless explicitly overridden. This ensures no impact on the synthesized hardware and no simulation overhead in Verilator flows.\n\n## 2. Conditional Compilation\n\nThe library must automatically disable all assertion and coverage constructs when either `VERILATOR` or `SYNTHESIS` is defined. In those cases, the macros expand to nothing (or to empty statements that do not affect simulation or synthesis). This behavior is the default; it may be overridden by defining `INC_ASSERT` before the file is included.\n\nWhen `UVM` is defined, the macro `ASSERT_RPT` (used by the library) reports assertion failures through the UVM infrastructure (calling `uvm_error`). Otherwise, failures are reported using `$error` with a formatted message containing the module instance name, the assertion name, and the file/line number.\n\n## 3. Default Clock and Reset\n\nAll concurrent assertion macros (e.g., `ASSERT`, `ASSERT_NEVER`, `COVER`, `ASSUME`) accept optional clock and reset arguments. If not provided, they use a **global default clock** and **global default reset** that must be defined at the point of inclusion. Common practice is to define them as:\n\n- Default clock: the positive edge of the main module clock.\n- Default reset: an active-low reset signal (i.e., assertions are disabled when the reset is asserted low).\n\nThe reset condition is checked as `(reset != '0)` – this ensures the assertion is **disabled** whenever the reset value is **not** all-zeros (including X or high-impedance). This behavior prevents false failures during the initial unknown state of the reset signal.\n\n## 4. Assertion and Coverage Macros\n\n### 4.1 Immediate Assertions\n\n| Macro | Behavior |\n|-------|----------|\n| `ASSERT_I(name, property)` | Evaluates `property` at the current simulation time (immediate check). If false, an error is reported. No clock or reset dependency. |\n| `ASSERT_INIT(name, property)` | Evaluated only once at the start of simulation, inside an initial block. Useful for parameter or static property checks. |\n| `ASSERT_FINAL(name, property)` | Evaluated only at the end of simulation, inside a final block. Reports an error if the property is false, **unless** the `+disable_assert_final_checks` plusarg is supplied. Useful for checking that all credits are returned, queues empty, or state machines are idle at shutdown. |\n\n### 4.2 Concurrent Assertions\n\nAll concurrent assertions are evaluated on every positive edge of the provided (or default) clock and are disabled while reset is asserted (according to the default reset semantics). They generate an error on failure.\n\n| Macro | Behavioral Description |\n|-------|------------------------|\n| `ASSERT(name, property [, clk, rst])` | Asserts that `property` holds **at all clock cycles** (after reset deassertion). |\n| `ASSERT_NEVER(name, property [, clk, rst])` | Asserts that `property` **never** occurs (i.e., it is always false) after reset deassertion. |\n| `ASSERT_KNOWN(name, signal [, clk, rst])` | Asserts that `signal` contains only known values (each bit is `0` or `1`, no X or Z) on every clock cycle after reset deassertion. Equivalent to `ASSERT(name, !$isunknown(signal))`. |\n| `COVER(name, property [, clk, rst])` | Declares a coverage point that is triggered whenever `property` is true. Does not cause any error, only drives functional coverage. |\n\n### 4.3 Specialized Assertions\n\n| Macro | Behavioral Description |\n|-------|------------------------|\n| `ASSERT_PULSE(name, signal [, clk, rst])` | Asserts that `signal` is a **single-cycle pulse** (exactly one clock wide). Fails if the signal rises and remains high for more than one cycle. |\n| `ASSERT_VALID_DATA(name, valid, data [, clk, rst])` | Combines two checks: (1) `valid` must be known after reset, and (2) whenever `valid` is true, `data` must be known (no X/Z). Each check has its own assertion name derived by appending `KnownValid` and `KnownData` to the given name. |\n| `ASSERT_VALID_READY_DATA(name, valid, ready, data [, clk, rst])` | Extends the previous by also asserting that `ready` is known after reset. Checks: `valid` known, `ready` known, and `data` known when `valid` is true. |\n\n## 5. Assumption Macros\n\nAssumptions are used to constrain the environment for formal verification or simulation. They have the same clock/reset semantics as concurrent assertions but express what the design **assumes** about its inputs or environment.\n\n| Macro | Behavioral Description |\n|-------|------------------------|\n| `ASSUME(name, property [, clk, rst])` | Assumes `property` holds on every clock cycle (after reset). If violated, an error is reported (or a UVM error when `UVM` is defined). |\n| `ASSUME_I(name, property)` | Immediate assumption evaluated at the current simulation time. |\n| `ASSUME_FPV(name, property [, clk, rst])` | Concurrent assumption active **only when `FPV_ON` is defined**. Intended for formal property verification; ignored in simulation. |\n| `ASSUME_I_FPV(name, property)` | Immediate assumption active only when `FPV_ON` is defined. |\n| `COVER_FPV(name, property [, clk, rst])` | Concurrent cover active only when `FPV_ON` is defined. Intended for formal coverage. |\n\n## 6. Error Reporting Behavior\n\nWhen an assertion (or assumption) fails, the macro `ASSERT_RPT` is called. The specific behavior depends on the presence of the `UVM` preprocessor symbol:\n\n- **If `UVM` is defined**: the failure is reported using `uvm_error` from the UVM package, with a message that includes the assertion name, file name, and line number. This allows UVM-style hierarchical message processing and severity overrides.\n- **If `UVM` is not defined**: a `$error` system call is issued with a formatted string containing `\"[ASSERT FAILED]\"`, the full hierarchical instance path (`%m`), the assertion name, file, and line.\n\nThe reporting mechanism is **independent** of the type of assertion (immediate, concurrent, or assumption). All failures are reported via this single mechanism.\n\n## 7. Formal Verification Support\n\nAll concurrent assertion and assumption macros are designed to be used in formal verification flows without modification. Additionally, three macros (`ASSUME_FPV`, `ASSUME_I_FPV`, `COVER_FPV`) are provided that are **only active** when the preprocessor symbol `FPV_ON` is defined. This enables the creation of assumptions and covers that are meaningful exclusively in formal analysis and should not be applied during simulation.\n\n## 8. Constraints and Guarantees\n\n- **Synthesis safety**: The library must never produce any logic or simulation side-effects when `SYNTHESIS` or `VERILATOR` is defined (unless `INC_ASSERT` is forced). This ensures that the same source code can be used for both simulation and synthesis.\n- **Reset handling**: All concurrent assertions and assumptions must be disabled when the reset signal is not in its deasserted state (i.e., when `reset != '0`). This properly masks X-propagation during reset sequences.\n- **Name uniqueness**: Each assertion or cover instance must be given a unique name (the first argument to the macro). The library does not enforce uniqueness at compile time; it is the responsibility of the user to avoid duplicate names within the same scope.\n- **Compilation order**: The macro `ASSERT_DEFAULT_CLK` and `ASSERT_DEFAULT_RST` should be defined before the library is included to override the default values. If not defined, the library provides a fallback default (typically `clk_i` and `!rst_ni`), but this is implementation-specific and should be documented locally.\n\n## 9. File Inclusion\n\nThe library is provided as a single include file (`prim_assert.sv`). It shall be included at the top of any SystemVerilog module or interface that wishes to use the assertion macros. The file is itself guarded by a conditional (`ifndef PRIM_ASSERT_SV`) to allow multiple inclusions without error.\n\n---\n\n*This specification describes the functional behavior of the `prim_assert` macro library. Any usage that deviates from these requirements should be considered outside the intended scope.*", "commit_id": "39ce39e33241833b4e5212e8e65f4ee99d48a49e", "timestamp": "2020-03-13T10:47:42+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "1c82c20132b4e9fb1ba5e28c0a5d19686589d02e", "pr_title": "Remove property from assert message", "pr_body": "Assert macros in prim_assert.sv report the asserted property as part of\nthe error message if the assertion fails. Doing that requires us to\nstringify the property. If the property is multi-line in the source\ncode, this produces a multi-line string. According to the\nSystemVerilog standard, a multi-line string requires a backslash (`\\`)\nat the end of a line. Adding this backslash through a macro is not\npossible (at least to my knowledge), giving us no way to produce a\nstandards-compliant implementation of the `ASSERT` macros that report\nthe property as string.\n\nThis commit therefore removes the property from the error message if an\nassertion fails. It makes these messages less useful, but the\ninformation can still be recovered in a less convenient way through the\nname of the assertion, and the file and line numbers.\n\nFixes #669", "issue_title": "Questa complains about newlines in ASSERT macros", "issue_body": "(Spin-off from #622 by @danghai)\r\n\r\nCompiling Ibex with Questa gives the following warning:\r\n\r\n```\r\n** Warning: ** while parsing macro expansion: 'ASSERT' starting at /home/danghai/hhoangda/ibex/rtl/ibex_compressed_decoder.sv(286)\r\n** at /home/danghai/hhoangda/ibex/rtl/ibex_compressed_decoder.sv(286): (vlog-2643) Unterminated string literal continues onto next line.\r\n```\r\n\r\nThe code in question is\r\n\r\n```verilog\r\n// in ibex_compressed_decoder.sv\r\n `ASSERT(IbexInstrLSBsKnown, valid_i |->\r\n !$isunknown(instr_i[1:0]))\r\n\r\n// in prim_assert.sv\r\n`define ASSERT(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\r\n`ifdef INC_ASSERT \\\r\n __name: assert property (@(posedge __clk) disable iff (__rst !== '0) (__prop)) \\\r\n else `ASSERT_RPT(`PRIM_STRINGIFY(__name), `PRIM_STRINGIFY(__prop)) \\\r\n`endif\r\n\r\n// Converts an arbitrary block of code into a Verilog string\r\n`define PRIM_STRINGIFY(__x) `\"__x`\"\r\n\r\n`define ASSERT_RPT(__name, __msg) \\\r\n`ifdef UVM \\\r\n assert_rpt_pkg::assert_rpt($sformatf(\"[%m] %s: %s (%s:%0d)\", \\\r\n __name, __msg, `__FILE__, `__LINE__)); \\\r\n`else \\\r\n $error(\"[ASSERT FAILED] [%m] %s: %s\", __name, __msg); \\\r\n`endif\r\n\r\n```\r\n\r\nGiven this code, I'm assuming the error message actually comes from the fact that `prop` (the second argument to `ASSERT`) is converted to a string before being used in `ASSERT_RPT`, and this use of `prop` with newlines isn't liked by Questa.\r\n\r\nAccording to SV2017, the definition of a string literal is \r\n\r\n![image](https://user-images.githubusercontent.com/1467123/76232809-2a375900-621f-11ea-9b3e-19b839f6469f.png)\r\n\r\nWhich indicates our code is actually wrong. I see a couple of options:\r\n- Remove the reporting of the property in `ASSERT_RPT`, and only report the message.\r\n- Add backslashes to the end-of-line of each multi-line property. I'm not sure if that's actually valid for the non-string case?\r\n- Avoid newlines in properties when writing `ASSERT` macros.\r\n\r\n\r\n@danghai:\r\n- First, let's check if the hypothesis holds: Does the warning go away if you remove the `ASSERT_RPT()` call from the definition of the `ASSERT` macro?\r\n- Can you try to add a backslash at the end of the property in `ibex_compressed_decoder.sv`, e.g. \r\n\r\n ```systemverilog\r\n `ASSERT(IbexInstrLSBsKnown, valid_i |-> \\\r\n !$isunknown(instr_i[1:0]))\r\n ```\r\n\r\n\r\nQuesta version info: QuestaSim-64 qrun 2019.4 Utility 2019.10 Oct 15 2019\r\n\r\n\r\nCC @msfschaffner @sriyerg ", "commit_message": "Remove property from assert message\n\nAssert macros in prim_assert.sv report the asserted property as part of\nthe error message if the assertion fails. Doing that requires us to\nstringify the property. If the property is multi-line in the source\ncode, this produces a multi-line string. According to the\nSystemVerilog standard, a multi-line string requires a backslash (`\\`)\nat the end of a line. Adding this backslash through a macro is not\npossible (at least to my knowledge), giving us no way to produce a\nstandards-compliant implementation of the `ASSERT` macros that report\nthe property as string.\n\nThis commit therefore removes the property from the error message if an\nassertion fails. It makes these messages less useful, but the\ninformation can still be recovered in a less convenient way through the\nname of the assertion, and the file and line numbers. File and line\nnumber were missing from the non-UVM code path before, this commit adds\nthem there as well.\n\nFixes #669", "fix_patch": "diff --git a/shared/rtl/prim_assert.sv b/shared/rtl/prim_assert.sv\nindex f569292c09..1e536bf84e 100644\n--- a/shared/rtl/prim_assert.sv\n+++ b/shared/rtl/prim_assert.sv\n@@ -34,13 +34,13 @@\n // Converts an arbitrary block of code into a Verilog string\n `define PRIM_STRINGIFY(__x) `\"__x`\"\n \n- // ASSERT_RPT is available to change the reporting mechanism when an assert fails\n-`define ASSERT_RPT(__name, __msg) \\\n-`ifdef UVM \\\n- assert_rpt_pkg::assert_rpt($sformatf(\"[%m] %s: %s (%s:%0d)\", \\\n- __name, __msg, `__FILE__, `__LINE__)); \\\n-`else \\\n- $error(\"[ASSERT FAILED] [%m] %s: %s\", __name, __msg); \\\n+// ASSERT_RPT is available to change the reporting mechanism when an assert fails\n+`define ASSERT_RPT(__name) \\\n+`ifdef UVM \\\n+ assert_rpt_pkg::assert_rpt($sformatf(\"[%m] %s (%s:%0d)\", \\\n+ __name, `__FILE__, `__LINE__)); \\\n+`else \\\n+ $error(\"[ASSERT FAILED] [%m] %s (%s:%0d)\", __name, `__FILE__, `__LINE__); \\\n `endif\n \n ///////////////////////////////////////\n@@ -53,18 +53,18 @@\n \n // Immediate assertion\n // Note that immediate assertions are sensitive to simulation glitches.\n-`define ASSERT_I(__name, __prop) \\\n-`ifdef INC_ASSERT \\\n- __name: assert (__prop) \\\n- else `ASSERT_RPT(`PRIM_STRINGIFY(__name), `PRIM_STRINGIFY(__prop)) \\\n+`define ASSERT_I(__name, __prop) \\\n+`ifdef INC_ASSERT \\\n+ __name: assert (__prop) \\\n+ else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n `endif\n \n // Assertion in initial block. Can be used for things like parameter checking.\n-`define ASSERT_INIT(__name, __prop) \\\n-`ifdef INC_ASSERT \\\n- initial \\\n- __name: assert (__prop) \\\n- else `ASSERT_RPT(`PRIM_STRINGIFY(__name), `PRIM_STRINGIFY(__prop)) \\\n+`define ASSERT_INIT(__name, __prop) \\\n+`ifdef INC_ASSERT \\\n+ initial \\\n+ __name: assert (__prop) \\\n+ else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n `endif\n \n // Assertion in final block. Can be used for things like queues being empty\n@@ -74,15 +74,15 @@\n `ifdef INC_ASSERT \\\n final \\\n __name: assert (__prop || $test$plusargs(\"disable_assert_final_checks\")) \\\n- else `ASSERT_RPT(`PRIM_STRINGIFY(__name), `PRIM_STRINGIFY(__prop)) \\\n+ else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n `endif\n \n // Assert a concurrent property directly.\n // It can be called as a module (or interface) body item.\n `define ASSERT(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n `ifdef INC_ASSERT \\\n- __name: assert property (@(posedge __clk) disable iff (__rst !== '0) (__prop)) \\\n- else `ASSERT_RPT(`PRIM_STRINGIFY(__name), `PRIM_STRINGIFY(__prop)) \\\n+ __name: assert property (@(posedge __clk) disable iff ((__rst) !== '0) (__prop)) \\\n+ else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n `endif\n // Note: Above we use (__rst !== '0) in the disable iff statements instead of\n // (__rst == '1). This properly disables the assertion in cases when reset is X at\n@@ -92,8 +92,8 @@\n // Assert a concurrent property NEVER happens\n `define ASSERT_NEVER(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n `ifdef INC_ASSERT \\\n- __name: assert property (@(posedge __clk) disable iff (__rst !== '0) not (__prop)) \\\n- else `ASSERT_RPT(`PRIM_STRINGIFY(__name), `PRIM_STRINGIFY(__prop)) \\\n+ __name: assert property (@(posedge __clk) disable iff ((__rst) !== '0) not (__prop)) \\\n+ else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n `endif\n \n // Assert that signal has a known value (each bit is either '0' or '1') after reset.\n@@ -106,7 +106,7 @@\n // Cover a concurrent property\n `define COVER(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n `ifdef INC_ASSERT \\\n- __name: cover property (@(posedge __clk) disable iff (__rst !== '0) (__prop)); \\\n+ __name: cover property (@(posedge __clk) disable iff ((__rst) !== '0) (__prop)); \\\n `endif\n \n //////////////////////////////\n@@ -141,15 +141,15 @@\n // Assume a concurrent property\n `define ASSUME(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n `ifdef INC_ASSERT \\\n- __name: assume property (@(posedge __clk) disable iff (__rst !== '0) (__prop)) \\\n- else begin `ASSERT_RPT(`PRIM_STRINGIFY(__name), `PRIM_STRINGIFY(__prop)) end \\\n+ __name: assume property (@(posedge __clk) disable iff ((__rst) !== '0) (__prop)) \\\n+ else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n `endif\n \n // Assume an immediate property\n-`define ASSUME_I(__name, __prop) \\\n-`ifdef INC_ASSERT \\\n- __name: assume (__prop) \\\n- else `ASSERT_RPT(`PRIM_STRINGIFY(__name), `PRIM_STRINGIFY(__prop)) \\\n+`define ASSUME_I(__name, __prop) \\\n+`ifdef INC_ASSERT \\\n+ __name: assume (__prop) \\\n+ else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n `endif\n \n //////////////////////////////////\n", "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// Macros and helper code for using assertions.\n// - Provides default clk and rst options to simplify code\n// - Provides boiler plate template for common assertions\n\n`ifndef PRIM_ASSERT_SV\n`define PRIM_ASSERT_SV\n\n`ifdef UVM\n // report assertion error with UVM if compiled\n package assert_rpt_pkg;\n import uvm_pkg::*;\n `include \"uvm_macros.svh\"\n function void assert_rpt(string msg);\n `uvm_error(\"ASSERT FAILED\", msg)\n endfunction\n endpackage\n`endif\n\n///////////////////\n// Helper macros //\n///////////////////\n\n// local helper macro to reduce code clutter. undefined at the end of this file\n`ifndef VERILATOR\n`ifndef SYNTHESIS\n`define INC_ASSERT\n`endif\n`endif\n\n// Converts an arbitrary block of code into a Verilog string\n`define PRIM_STRINGIFY(__x) `\"__x`\"\n\n// ASSERT_RPT is available to change the reporting mechanism when an assert fails\n`define ASSERT_RPT(__name) \\\n`ifdef UVM \\\n assert_rpt_pkg::assert_rpt($sformatf(\"[%m] %s (%s:%0d)\", \\\n __name, `__FILE__, `__LINE__)); \\\n`else \\\n $error(\"[ASSERT FAILED] [%m] %s (%s:%0d)\", __name, `__FILE__, `__LINE__); \\\n`endif\n\n///////////////////////////////////////\n// Simple assertion and cover macros //\n///////////////////////////////////////\n\n// Default clk and reset signals used by assertion macros below.\n`define ASSERT_DEFAULT_CLK clk_i\n`define ASSERT_DEFAULT_RST !rst_ni\n\n// Immediate assertion\n// Note that immediate assertions are sensitive to simulation glitches.\n`define ASSERT_I(__name, __prop) \\\n`ifdef INC_ASSERT \\\n __name: assert (__prop) \\\n else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n`endif\n\n// Assertion in initial block. Can be used for things like parameter checking.\n`define ASSERT_INIT(__name, __prop) \\\n`ifdef INC_ASSERT \\\n initial \\\n __name: assert (__prop) \\\n else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n`endif\n\n// Assertion in final block. Can be used for things like queues being empty\n// at end of sim, all credits returned at end of sim, state machines in idle\n// at end of sim.\n`define ASSERT_FINAL(__name, __prop) \\\n`ifdef INC_ASSERT \\\n final \\\n __name: assert (__prop || $test$plusargs(\"disable_assert_final_checks\")) \\\n else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n`endif\n\n// Assert a concurrent property directly.\n// It can be called as a module (or interface) body item.\n`define ASSERT(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef INC_ASSERT \\\n __name: assert property (@(posedge __clk) disable iff ((__rst) !== '0) (__prop)) \\\n else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n`endif\n// Note: Above we use (__rst !== '0) in the disable iff statements instead of\n// (__rst == '1). This properly disables the assertion in cases when reset is X at\n// the beginning of a simulation. For that case, (reset == '1) does not disable the\n// assertion.\n\n// Assert a concurrent property NEVER happens\n`define ASSERT_NEVER(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef INC_ASSERT \\\n __name: assert property (@(posedge __clk) disable iff ((__rst) !== '0) not (__prop)) \\\n else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n`endif\n\n// Assert that signal has a known value (each bit is either '0' or '1') after reset.\n// It can be called as a module (or interface) body item.\n`define ASSERT_KNOWN(__name, __sig, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef INC_ASSERT \\\n `ASSERT(__name, !$isunknown(__sig), __clk, __rst) \\\n`endif\n\n// Cover a concurrent property\n`define COVER(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef INC_ASSERT \\\n __name: cover property (@(posedge __clk) disable iff ((__rst) !== '0) (__prop)); \\\n`endif\n\n//////////////////////////////\n// Complex assertion macros //\n//////////////////////////////\n\n// Assert that signal is an active-high pulse with pulse length of 1 clock cycle\n`define ASSERT_PULSE(__name, __sig, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef INC_ASSERT \\\n `ASSERT(__name, $rose(__sig) |=> !(__sig), __clk, __rst) \\\n`endif\n\n// Assert that valid is known after reset and data is known when valid == 1\n`define ASSERT_VALID_DATA(__name, __valid, __dat, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef INC_ASSERT \\\n `ASSERT_KNOWN(__name``KnownValid, __valid, __clk, __rst) \\\n `ASSERT_NEVER(__name``KnownData, (__valid) && $isunknown(__dat), __clk, __rst) \\\n`endif\n\n// Same as ASSERT_VALID_DATA, but also assert that ready is known after reset\n`define ASSERT_VALID_READY_DATA(__name, __valid, __ready, __dat, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef INC_ASSERT \\\n `ASSERT_KNOWN(__name``KnownValid, __valid, __clk, __rst) \\\n `ASSERT_KNOWN(__name``KnownReady, __ready, __clk, __rst) \\\n `ASSERT_NEVER(__name``KnownData, (__valid) && $isunknown(__dat), __clk, __rst) \\\n`endif\n\n///////////////////////\n// Assumption macros //\n///////////////////////\n\n// Assume a concurrent property\n`define ASSUME(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef INC_ASSERT \\\n __name: assume property (@(posedge __clk) disable iff ((__rst) !== '0) (__prop)) \\\n else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n`endif\n\n// Assume an immediate property\n`define ASSUME_I(__name, __prop) \\\n`ifdef INC_ASSERT \\\n __name: assume (__prop) \\\n else `ASSERT_RPT(`PRIM_STRINGIFY(__name)) \\\n`endif\n\n//////////////////////////////////\n// For formal verification only //\n//////////////////////////////////\n\n// Note that the existing set of ASSERT macros specified above shall be used for FPV,\n// thereby ensuring that the assertions are evaluated during DV simulations as well.\n\n// ASSUME_FPV\n// Assume a concurrent property during formal verification only.\n`define ASSUME_FPV(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef FPV_ON \\\n `ASSUME(__name, __prop, __clk, __rst) \\\n`endif\n\n// ASSUME_I_FPV\n// Assume a concurrent property during formal verification only.\n`define ASSUME_I_FPV(__name, __prop) \\\n`ifdef FPV_ON \\\n `ASSUME_I(__name, __prop) \\\n`endif\n\n// COVER_FPV\n// Cover a concurrent property during formal verification\n`define COVER_FPV(__name, __prop, __clk = `ASSERT_DEFAULT_CLK, __rst = `ASSERT_DEFAULT_RST) \\\n`ifdef FPV_ON \\\n `COVER(__name, __prop, __clk, __rst) \\\n`endif\n\n`endif // PRIM_ASSERT_SV\n", "selected_doc_paths": ["doc/verification.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 855, "lang": "sv", "rtl_files": ["dv/uvm/icache/dv/ibex_icache_core_agent/ibex_icache_core_driver.sv"], "spec": "# Ibex ICache Core Driver Behavioral Specification\n\n## Overview\n\nThe Ibex ICache Core Driver is a verification component that drives the core-facing interface of the instruction cache (I$). It is responsible for translating abstract transaction items from a sequence into actual signal transitions on the DUT’s side of the bus. The driver emulates the behavior of the CPU core, controlling the cache’s input ports and observing its outputs. It supports two types of transactions: branch and request.\n\nThe driver interacts with the DUT via a set of signals that represent the standard handshaking protocol defined for the I$ core interface. It ensures that transactions are driven in a timely and legal manner, and it returns response items that report whether an error was observed during the transaction.\n\n## Interface Driven by the Driver\n\nThe driver manipulates the following interface signals (conceptual ports):\n\n- **Enable**: Switches the cache’s enable state between enabled and disabled. The driver maintains an internal mirror of this state, toggling it only when the transaction requests a toggle.\n- **Request**: Indicates that the core is active and may start fetching instructions. The driver can lower this signal for a configurable number of cycles to simulate idle or sleep periods.\n- **Branch**: When asserted for one cycle with an associated address, causes the cache to redirect its internal address counter to the given target.\n- **Address**: The target address supplied during a branch transaction. Must be halfword‑aligned.\n- **Invalidate**: A pulse that triggers cache invalidation. The driver generates a pulse of random positive duration when the transaction specifies invalidation.\n- **Ready**: Part of the instruction read handshake. The core asserts ready when it is prepared to accept an instruction. The driver typically delays ready assertion by a random number of cycles and holds it until the cache asserts valid.\n- **Valid**: Driven by the DUT; indicates that instruction data and error flags are stable.\n- **Error**: Driven by the DUT; indicates an error (bus error or PMP error) on the current fetch.\n- **Instruction Data**: 32‑bit instruction word returned by the DUT.\n\nThe driver does not directly drive `valid` or `error`; it only observes them to determine whether to stop reading early.\n\n## Transaction Types\n\nEach transaction received from the sequencer has a type field:\n\n### Branch Transaction\n\nThe driver performs the following actions concurrently:\n\n1. Asserts the request line high (this is a no‑op if it is already high).\n2. Toggles the enable state if the transaction requests it.\n3. Asserts the branch line for one cycle with the supplied branch address.\n4. If the transaction requests invalidation, the driver asserts the invalidate line for a random number of cycles (between 1 and 20, with a bias toward short pulses).\n5. Reads the requested number of instructions (zero or more) from the cache using the ready/valid handshake.\n\nAll five actions happen in parallel. The branch and invalidate pulses are completed within the same cycle that the instruction reading begins.\n\n### Request Transaction\n\nThis transaction models a period where the core is active but is not necessarily branching. It consists of three phases:\n\n**Phase 1 – Setup**: The driver toggles the enable state if requested.\n\n**Phase 2 – Lowering request line**: The driver lowers the request line for a random number of cycles. The number of low cycles is randomized with the following distribution:\n\n- If instructions will be read after this phase, there is a 20% chance of zero low cycles; otherwise zero cycles are not allowed.\n- Low cycles between 1 and 33 occur with a moderate weight.\n- Low cycles between 100 and 200 occur with a smaller weight.\n- Low cycles between 1000 and 1200 occur with a very small weight.\n\nDuring these low cycles the cache should stop making new memory requests (consistent with the DUT’s specification). Concurrently, if the transaction requests invalidation, the driver asserts the invalidate line for a random positive number of cycles (1 to 20).\n\n**Phase 3 – Read instructions**: After the request line has been raised again (if it was lowered), the driver reads the specified number of instructions using the ready/valid handshake.\n\n## Instruction Read Handshake\n\nThe driver reads instructions one at a time from the cache. It implements the ready side of the ready/valid protocol:\n\n- After all concurrent actions (branch/invalidate/request‑lowering) are complete, the driver introduces a random delay (0 to 3 cycles) before asserting ready.\n- It then asserts ready and waits for the cache to assert valid.\n- Once valid is high, the driver samples the instruction data and error flag, then deasserts ready.\n- If the error flag is high during any instruction read, the driver stops reading further instructions for the current transaction and sets an error flag in the response item.\n\nThe driver does not enforce any particular order of ready/valid for the first instruction; it may wait for valid before asserting ready, but this is currently not exercised.\n\n## Response Generation\n\nAfter processing a transaction, the driver creates a response item and sends it back to the sequencer. The response contains:\n\n- A flag indicating whether a bus error or PMP error was observed during the instruction reads.\n- The transaction identifier (copied from the request).\n\nThe response is sent after all instructions have been read or after an early stop due to error.\n\n## Reset Behavior\n\nWhen the driver receives a reset signal (from the testbench environment), it performs the following:\n\n- Resets all driven signals to their inactive values.\n- Clears the internal enable state to disabled.\n\n## Constraints and Timing\n\n- The driver ensures that the branch address is halfword‑aligned (bit 0 must be zero). The sequence should respect this; the driver does not enforce it.\n- The driver does not impose any timing constraints on the DUT’s valid signal; it waits indefinitely for valid after asserting ready.\n- The driver does not assert ready when the enable state is changed or when the request line is low. It only reads instructions after the request line has been raised and any concurrent invalidate pulse has completed.\n- The driver does not read instructions in the middle of a branch pulse; the branch pulse lasts exactly one cycle and the instruction reading starts at the beginning of that same cycle.\n- The driver may read zero instructions at the end of a transaction (if `num_insns` is zero). In that case, no ready/valid handshake occurs.\n\n## Error Handling\n\nIf the DUT asserts the error signal during an instruction read, the driver:\n\n- Records the error in the response.\n- Stops reading further instructions for the current transaction.\n- Does not attempt to read any more instructions.\n\nThe driver does not inject errors; it only observes the DUT’s error output.\n\n## Summary of Functional Requirements\n\n1. **Transaction Execution**: The driver must accept a transaction and execute all specified actions (branch or request, with optional invalidation, toggling enable, and instruction reading) within the constraints described.\n2. **Randomization**: The driver must randomize delays (request low cycles, invalidate pulse length, ready assertion delay) according to the specified distributions.\n3. **Concurrency**: All actions that are marked as concurrent must be started simultaneously.\n4. **Instruction Reading**: The driver must read exactly the requested number of instructions unless an error occurs, in which case it must stop early and report the error.\n5. **Stateful Enable**: The driver must maintain the enable state across transactions and toggle only when the transaction requests it.\n6. **Reset**: On reset, all signals must return to inactive state and enable must be cleared.\n7. **Reporting**: The driver must produce a response item for each transaction containing the saw‑error flag and the transaction identifier.", "commit_id": "863fb56eb166dc8d6e25f4e98b7319f0c7088564", "timestamp": "2020-05-11T15:28:49+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "ff5c0c582314d9a36dd931502bb99e0bdc01619f", "pr_title": "Always assert ready in core driver for ICache UVM testbench", "pr_body": "This works around a bug tracked in issue #850.", "issue_title": "ICache <-> core valid signal depends on ready", "issue_body": "As it currently stands, the documentation (that I wrote) suggests this shouldn't be the case. We either need to fix the documentation or change the code.", "commit_message": "Always assert ready in core driver for ICache UVM testbench\n\nThis works around a bug tracked in issue #850.", "fix_patch": "diff --git a/dv/uvm/icache/dv/ibex_icache_core_agent/ibex_icache_core_driver.sv b/dv/uvm/icache/dv/ibex_icache_core_agent/ibex_icache_core_driver.sv\nindex 87474e2488..d6e0d8ea19 100644\n--- a/dv/uvm/icache/dv/ibex_icache_core_agent/ibex_icache_core_driver.sv\n+++ b/dv/uvm/icache/dv/ibex_icache_core_agent/ibex_icache_core_driver.sv\n@@ -112,9 +112,15 @@ class ibex_icache_core_driver\n virtual task automatic read_insn();\n int unsigned delay;\n \n- // Maybe (1 time in 10) wait for a valid signal before even considering asserting ready.\n- if ($urandom_range(9) == 0)\n- wait (cfg.vif.driver_cb.valid);\n+ // TODO: The icache sometimes currently requires the ready signal before it asserts valid. This\n+ // is tracked by issue #850.\n+ if (0) begin\n+\n+ // Maybe (1 time in 10) wait for a valid signal before even considering asserting ready.\n+ if ($urandom_range(9) == 0)\n+ wait (cfg.vif.driver_cb.valid);\n+\n+ end\n \n // Then pick how long we wait before asserting that we are ready.\n //\n", "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 ibex_icache_core_driver\n extends dv_base_driver #(.ITEM_T (ibex_icache_core_req_item),\n .RSP_ITEM_T (ibex_icache_core_rsp_item),\n .CFG_T (ibex_icache_core_agent_cfg));\n `uvm_component_utils(ibex_icache_core_driver)\n `uvm_component_new\n\n // The current state of the enable pin: this is toggled by sequence items, but the current state\n // is stored on the driver.\n bit enable;\n\n // reset signals\n virtual task automatic reset_signals();\n cfg.vif.reset();\n enable = 1'b0;\n endtask\n\n // drive trans received from sequencer\n virtual task automatic get_and_drive();\n ibex_icache_core_rsp_item rsp;\n\n forever begin\n seq_item_port.get_next_item(req);\n `uvm_info(`gfn, $sformatf(\"rcvd item:\\n%0s\", req.sprint()), UVM_HIGH)\n\n rsp = ibex_icache_core_rsp_item::type_id::create(\"rsp\");\n rsp.set_id_info(req);\n\n rsp.saw_error = 1'b0;\n\n case (req.trans_type)\n ICacheCoreTransTypeBranch: drive_branch_trans(rsp, req);\n ICacheCoreTransTypeReq: drive_req_trans(rsp, req);\n default: `uvm_fatal(`gfn, \"Unknown transaction type\")\n endcase\n\n `uvm_info(`gfn, \"item sent\", UVM_HIGH)\n seq_item_port.item_done(rsp);\n end\n endtask\n\n // Drive the cache for a \"branch\" transaction.\n //\n // This concurrently asserts branch with a given address for a cycle while doing the usual\n // (enable/disable, invalidate, read instructions).\n task automatic drive_branch_trans(ibex_icache_core_rsp_item rsp,\n ibex_icache_core_req_item req);\n // Make sure that req is enabled (has no effect unless this is the first transaction)\n cfg.vif.driver_cb.req <= 1'b1;\n\n // Toggle the enable state if necessary and drive its pin\n if (req.toggle_enable)\n enable = ~enable;\n cfg.vif.driver_cb.enable <= enable;\n\n fork\n cfg.vif.branch_to(req.branch_addr);\n if (req.invalidate) invalidate();\n read_insns(rsp, req.num_insns);\n join\n endtask\n\n // Drive the cache for a \"req transaction\".\n //\n // This lowers req for zero or more cycles, at the same time as setting the enable pin and (maybe)\n // pulsing the invalidate line. Once that is done, it reads zero or more instructions.\n task automatic drive_req_trans(ibex_icache_core_rsp_item rsp,\n ibex_icache_core_req_item req);\n int unsigned req_low_cycles;\n bit allow_no_low_cycles;\n\n // How many cycles should we lower the request line? If there aren't any instructions to read,\n // this is constrained to be positive (to avoid a confusing zero-time transaction).\n allow_no_low_cycles = req.num_insns > 0;\n `DV_CHECK_STD_RANDOMIZE_WITH_FATAL(req_low_cycles,\n req_low_cycles dist {\n 0 :/ (allow_no_low_cycles ? 20 : 0),\n [1:33] :/ 5,\n [100:200] :/ 2,\n [1000:1200] :/ 1 };)\n\n // Toggle the enable state if necessary and drive its pin\n if (req.toggle_enable)\n enable = ~enable;\n cfg.vif.driver_cb.enable <= enable;\n\n fork\n if (req_low_cycles > 0) lower_req(req_low_cycles);\n if (req.invalidate) invalidate();\n join\n read_insns(rsp, req.num_insns);\n endtask\n\n // Read up to num_insns instructions from the cache, stopping early on an error. If there was an\n // error, fill in the saw_error flag in rsp (which will be passed back to the sequence).\n task automatic read_insns(ibex_icache_core_rsp_item rsp, int num_insns);\n for (int i = 0; i < num_insns; i++) begin\n read_insn();\n // Spot any error and exit early\n if (cfg.vif.driver_cb.err) begin\n rsp.saw_error = 1'b1;\n break;\n end\n end\n endtask\n\n // Read a single instruction from the cache\n virtual task automatic read_insn();\n int unsigned delay;\n\n // TODO: The icache sometimes currently requires the ready signal before it asserts valid. This\n // is tracked by issue #850.\n if (0) begin\n\n // Maybe (1 time in 10) wait for a valid signal before even considering asserting ready.\n if ($urandom_range(9) == 0)\n wait (cfg.vif.driver_cb.valid);\n\n end\n\n // Then pick how long we wait before asserting that we are ready.\n //\n // TODO: Make this configurable and weight 0 more heavily.\n cfg.vif.wait_clks($urandom_range(3));\n\n // Assert ready and then wait until valid\n cfg.vif.driver_cb.ready <= 1'b1;\n while (1'b1) begin\n @(cfg.vif.driver_cb);\n if (cfg.vif.driver_cb.valid)\n break;\n end\n\n cfg.vif.driver_cb.ready <= 1'b0;\n endtask\n\n // Lower the req line for the given number of cycles\n virtual task automatic lower_req(int unsigned num_cycles);\n cfg.vif.driver_cb.req <= 1'b0;\n repeat (num_cycles) @(cfg.vif.driver_cb);\n cfg.vif.driver_cb.req <= 1'b1;\n endtask\n\n // Raise the invalidate line for a randomly chosen number of cycles > 0.\n virtual task automatic invalidate();\n int unsigned num_cycles;\n `DV_CHECK_STD_RANDOMIZE_WITH_FATAL(num_cycles,\n num_cycles dist { 1 :/ 10, [2:20] :/ 1 };)\n cfg.vif.invalidate_pulse(num_cycles);\n endtask\n\nendclass\n", "selected_doc_paths": ["doc/icache.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 969, "lang": "sv", "rtl_files": ["rtl/ibex_decoder.sv"], "spec": "## Behavioral Design Specification: Instruction Decoder (ibex_decoder)\n\n### 1. Overview\n\nThe instruction decoder is a purely combinational module that interprets a 32-bit uncompressed RISC-V instruction and generates all control signals required for execution in the ID/EX pipeline stage. It operates as a single-cycle unit for most instructions, but can handle multi-cycle sequences for jumps, branches, and certain bit-manipulation instructions by using a cycle indicator.\n\nThe decoder must:\n\n- Decode the opcode, funct3, funct7, and register fields.\n- Produce immediate values for all R-type, I-type, S-type, B-type, U-type, and J-type immediates, as well as a zero-extended CSR immediate.\n- Select register file read addresses (rs1, rs2, rs3) and write address (rd).\n- Generate register file read enables and write enable.\n- Control ALU operation, operand multiplexers, and immediate multiplexers.\n- Control the multiplier/divider block (multiply and divide enables, operation, signed mode).\n- Control load/store unit (request, write enable, size, sign extension).\n- Control CSR access (read/write operation).\n- Control branch and jump signals (including branch target ALU selection).\n- Flag illegal instructions and system instructions (ECALL, EBREAK, MRET, DRET, WFI).\n- Invalidate the instruction cache (FENCE.I).\n- Respect the RV32E configuration by checking register addresses.\n\nThe decoder must produce stable outputs within one clock cycle; timing closure is assisted by replicating the instruction data bus to reduce fan-out.\n\n### 2. Inputs and Outputs (Functional Summary)\n\n#### 2.1 Inputs\n\n- **Instruction Data**: Two copies of the 32-bit instruction word, one used for decoder control and one for ALU control (to reduce fan-out).\n- **First Cycle Indicator**: A signal indicating whether the current instruction is in its first cycle of execution (used for multi-cycle instructions).\n- **Branch Taken Flag**: A registered decision from a previous branch condition evaluation (used to select branch target or increment).\n- **Illegal Compressed Instruction Flag**: Set by the compressed instruction decoder when a compressed instruction cannot be decoded.\n\n#### 2.2 Outputs (Grouped by Function)\n\n- **Illegal / Special Instructions**:\n - Illegal instruction flag.\n - EBREAK, MRET, DRET, ECALL, WFI flags.\n - Instruction cache invalidation signal.\n\n- **Immediates**:\n - Six immediate outputs: I-type, S-type, B-type, U-type, J-type, and ZIMM (for CSR).\n - Control signals to select which immediate is used as operand A or B.\n\n- **Register File**:\n - Read addresses A and B (rs1/rs3 and rs2).\n - Write address (rd).\n - Read enable for address A and B.\n - Write enable (qualified by illegal instruction and RV32E).\n - Write data selection (from ALU, CSR, or load data).\n\n- **ALU**:\n - ALU operation (arithmetic/logic/shift/compare).\n - Operand A and B mux selects (register, PC, immediate, zero).\n - Multi-cycle indicator for bit-manipulation instructions that require two cycles.\n\n- **Multiplier / Divider**:\n - Multiply and divide enable signals.\n - Static mux selects to route multiplier/divider output.\n - Multiply/divide operation (MUL, MULH, MULHSU, MULHU, DIV, DIVU, REM, REMU).\n - Signed mode (both signed, unsigned, or mixed).\n\n- **CSR**:\n - CSR access enable.\n - CSR operation (read, write, set, clear).\n\n- **Load/Store Unit**:\n - Data request and write enable.\n - Data size (byte, halfword, word).\n - Sign extension on load.\n\n- **Jump / Branch**:\n - Jump in decoder (instruction is a jump).\n - Jump set (initiate jump on next cycle).\n - Branch in decoder.\n - Branch target operand A/B selection (PC or register, immediate type).\n\n### 3. Decoding Behavior per Opcode\n\nThe decoder must classify each instruction by its 7-bit opcode (bits 6:0). For each opcode, the following behaviors must be observed.\n\n#### 3.1 Jumps (JAL, JALR)\n\n- **JAL**: Jump and Link.\n - Must set jump_in_dec and jump_set on the first cycle.\n - If `BranchTargetALU` is enabled, must write PC+4 to register file on the first cycle; otherwise must write PC+4 on the second cycle.\n - ALU must compute jump target (PC + J-immediate) on first cycle if no branch-target ALU, and PC+4 on second cycle.\n - Must read no register (except JALR always reads rs1).\n\n- **JALR**: Jump and Link Register.\n - Must set jump_in_dec and jump_set on the first cycle.\n - Write back behavior similar to JAL.\n - Must read register rs1 (operand A).\n - If funct3 (bits 14:12) is not zero, instruction must be flagged illegal.\n\n#### 3.2 Branches (BEQ, BNE, BLT, BGE, BLTU, BGEU)\n\n- Must decode funct3 to select ALU comparator: equal, not-equal, less-than (signed), greater-or-equal (signed), less-than (unsigned), greater-or-equal (unsigned).\n- On the first cycle, must evaluate branch condition (ALU with rs1 and rs2).\n- On the second cycle, must compute branch target (PC + B-immediate) if `BranchTargetALU` is not present.\n- If `BranchTargetALU` is present, the branch target is computed in parallel and must be used for the next PC; the main ALU only evaluates the condition.\n- Must enable reads of both rs1 and rs2.\n- Invalid funct3 values must cause an illegal instruction.\n\n#### 3.3 Loads (LB, LH, LW, LBU, LHU)\n\n- Must read rs1 (address base) and use I-immediate for offset.\n- Must request data from memory (data_req_o) with read (data_we_o = 0) on the first cycle.\n- Must output appropriate data size: byte, halfword, or word.\n- Sign extension must be enabled for LB and LH, disabled for LBU and LHU.\n- LW (word) must have sign extension disabled; funct3 encoding with bit 14 set (LBU, LHU, LWU) must be illegal – LWU is not supported.\n- Loads always take at least one cycle (data response may cause stalls, but those are handled outside the decoder).\n\n#### 3.4 Stores (SB, SH, SW)\n\n- Must read both rs1 (base) and rs2 (data).\n- Must request a write to memory (data_we_o = 1).\n- Must output the correct store size (byte, halfword, word).\n- Offset is S-immediate.\n- Bit 14 of the instruction must be zero; otherwise illegal.\n\n#### 3.5 ALU Immediate Operations (ADDI, SLTI, SLTIU, XORI, ORI, ANDI, SLLI, SRLI, SRAI, and RV32B immediate variants)\n\n- Must read rs1 and write rd.\n- Must select I-immediate as operand B.\n- ALU operation is determined by funct3 and, for shifts and bit-manipulation, by further encoding (bits 31:27, 26:20).\n- For base RV32I:\n - ADDI, SLTI, SLTIU, XORI, ORI, ANDI are direct.\n - SLLI, SRLI, SRAI are decoded from funct3 and shift type bits.\n- For RV32B extension:\n - Additional immediate operations must be enabled only when `RV32B` parameter is 1.\n - These include shifts with ones, bit set/clear/invert, shuffle, rotate, bit extraction, CRC (multi-cycle), etc.\n - The `alu_multicycle_o` flag must be set for CRC instructions and for those that use rs3 in a second cycle (e.g., FSR with immediate).\n- Any unsupported encoding within the opcode must be flagged illegal.\n\n#### 3.6 Register-Register ALU Operations (ADD, SUB, SLT, SLTU, XOR, OR, AND, SLL, SRL, SRA, and RV32M/RV32B variants)\n\n- Must read both rs1 and rs2 and write rd.\n- ALU operation is decoded from funct7 (bits 31:25) and funct3 (bits 14:12).\n- For RV32M (multiply/divide):\n - Each sub-operation (mul, mulh, mulhsu, mulhu, div, divu, rem, remu) must set the appropriate multiplier/divider select signals and signed mode.\n - The ALU operation must be set to ALU_ADD (used internally by the mult/div block).\n - Must be enabled only when `RV32M` parameter is 1.\n- For RV32B:\n - All defined bit-manipulation operations (Zbb, Zbs, Zbp, Zbe, Zbf, Zbc) must be enabled only when `RV32B` is 1.\n - Ternary operations (cmix, cmov, fsl, fsr) require two cycles: first cycle uses rs1 and rs2, second cycle uses rs3. The `alu_multicycle_o` flag and the `use_rs3` selection must be controlled accordingly.\n- Any unsupported combination must be illegal.\n\n#### 3.7 LUI and AUIPC\n\n- **LUI**: Load Upper Immediate. Must write register rd with U-immediate shifted left by 12 bits (no register read). ALU must add zero + U-immediate.\n- **AUIPC**: Add Upper Immediate to PC. Must write register rd with PC + U-immediate.\n\n#### 3.8 System Instructions (ECALL, EBREAK, MRET, DRET, WFI)\n\n- Decoded from opcode SYSTEM with funct3=000.\n- The instruction field bits 31:20 select which system instruction:\n - ECALL: ecall_insn_o must be set.\n - EBREAK: ebrk_insn_o must be set.\n - MRET: mret_insn_o must be set.\n - DRET: dret_insn_o must be set.\n - WFI: wfi_insn_o must be set.\n- All other encodings (including those with rs1 or rd non-zero) must be illegal.\n- No register file writes, no ALU operation required (except possibly NOP).\n\n#### 3.9 CSR Instructions (CSRRW, CSRRS, CSRRC, CSRRWI, CSRRSI, CSRRCI)\n\n- Decoded from opcode SYSTEM with funct3 bits [1:0] (set, clear, write) and bit 2 (immediate form).\n- Must enable CSR access (csr_access_o).\n- Write data selection must be RF_WD_CSR.\n- For register forms (bits [14]=0), rs1 must be read.\n- For immediate forms (bits [14]=1), the rs1 field is used as a zero-extended immediate (ZIMM).\n- CSR operation: write, set, clear based on funct2.\n- If the CSR operation is set or clear and the rs1 immediate is zero, the operation must be downgraded to read-only (CSR_OP_READ) to avoid unintended writes.\n- Illegal if funct2 is invalid (00 maps to read-only, which is legal but may be a NOP depending on implementation not to trigger illegal).\n\n#### 3.10 FENCE and FENCE.I\n\n- **FENCE**: (funct3=000) Must behave as a NOP – no register write, no memory request.\n- **FENCE.I**: (funct3=001) Must flush the pipeline and invalidate the instruction cache (icache_inval_o) on the first cycle. Implemented internally as a jump to the next PC: must set jump_in_dec and jump_set on the first cycle. If `BranchTargetALU` is present, use the branch target ALU to compute PC+4; otherwise use main ALU.\n\n### 4. Multi-Cycle Instruction Handling\n\nThe decoder uses the `instr_first_cycle_i` input to differentiate between the first and second cycle of a multi-cycle instruction. The following instructions or sequences require two cycles:\n\n- **Jumps (JAL, JALR)** without `BranchTargetALU`: first cycle computes target, second cycle computes PC+4 write-back.\n- **Branches** without `BranchTargetALU`: first cycle evaluates condition, second cycle computes target (or PC+4 if not taken).\n- **Branches with `BranchTargetALU`**: first cycle evaluates condition; target is computed in parallel.\n- **Ternary bit-manipulation instructions (cmix, cmov, fsl, fsr)** and **FSRI** (immediate form): \n - First cycle: use rs1 and rs2 (or immediate for FSRI). \n - Second cycle: retrieve rs3, compute final result. \n - The `alu_multicycle_o` output must be asserted. \n - The `use_rs3` control (internal) must select rs3 on the second cycle.\n- **CRC32 instructions**: Must assert `alu_multicycle_o` (the ALU internally uses multiple cycles, but the decoder only marks them as multi-cycle for stalling).\n- **Rotate instructions (ror, rol)** when RV32B is enabled: must assert `alu_multicycle_o`.\n\nIn the first cycle, the decoder must assert `instr_first_cycle_i` as input. In subsequent cycles (for multi-cycle instructions), it must be deasserted. The decoder must use this to control register write enables, jump_set, and operand multiplexers appropriately.\n\n### 5. Illegal Instruction Detection\n\nThe decoder must detect illegal instructions in the following cases:\n\n- Any opcode not matching defined ones.\n- Invalid funct3 or funct7 encodings for a given opcode.\n- Unsupported instructions when optional extensions are disabled (RV32M, RV32B).\n- Compressed instructions that were not successfully decoded (via `illegal_c_insn_i` input).\n- Register accesses to x16–x31 when RV32E is enabled and the instruction reads or writes such registers (only actual register file accesses count; immediate-based instructions that do not read rs1/rs2 are not affected).\n- CSR instructions with invalid funct2.\n- JALR with non-zero funct3.\n- Store with bit 14 set.\n- Load with bit 14 set for word (LWU not supported).\n- System instructions with non-zero rs1 or rd.\n\nWhen an illegal instruction is detected:\n\n- The `illegal_insn_o` output must be asserted.\n- Register file write enable must be suppressed.\n- Data request, jump, branch, and CSR access must be suppressed (set to 0).\n- Multiplier/divider enables must be forced to 0 (to avoid side effects).\n- All other outputs may remain at their default values (they will be ignored by downstream logic).\n\n### 6. RV32E Register File Constraint\n\nIf the `RV32E` parameter is 1, the processor supports only 16 registers (x0–x15). The decoder must check:\n\n- Whether register file read address A (which may be rs1 or rs3) has bit 4 set and the ALU operand A mux selects a register value (OP_A_REG_A).\n- Whether register file read address B (rs2) has bit 4 set and the ALU operand B mux selects a register value (OP_B_REG_B).\n- Whether register file write address (rd) has bit 4 set and the write enable is active.\n\nIf any of these conditions holds, the `illegal_reg_rv32e` flag must be asserted and combined with the main `illegal_insn` to produce the final `illegal_insn_o`. Additionally, the register file write enable must be gated with the negation of this flag to prevent writes to high registers.\n\n### 7. CSR Operand Special Case\n\nFor CSR set/clear instructions (CSRRS/CSRRC and their immediate variants), if the rs1 field (or the immediate from rs1) is zero, the write to the CSR must be suppressed. The decoder must change the CSR operation to read-only (CSR_OP_READ) in that case, ensuring no modification to the CSR occurs.\n\n### 8. Immediate Generation\n\nThe decoder must generate the following immediates from the instruction word and drive them to dedicated outputs:\n\n- **I-immediate**: `{ {20{instr[31]}}, instr[31:20] }`\n- **S-immediate**: `{ {20{instr[31]}}, instr[31:25], instr[11:7] }`\n- **B-immediate**: `{ {19{instr[31]}}, instr[31], instr[7], instr[30:25], instr[11:8], 1'b0 }`\n- **U-immediate**: `{ instr[31:12], 12'b0 }`\n- **J-immediate**: `{ {12{instr[31]}}, instr[19:12], instr[20], instr[30:21], 1'b0 }`\n- **Zimm**: `{ 27'b0, rs1 }` (zero-extended rs1 field for CSR immediate forms)\n\nThese immediates must be available on the corresponding output ports each cycle, regardless of instruction type (they are always combinational). The selection of which immediate to use is handled by the mux selects `imm_a_mux_sel_o`, `imm_b_mux_sel_o`, `bt_a_mux_sel_o`, `bt_b_mux_sel_o`.\n\n### 9. Output Defaults\n\nThe decoder must drive all outputs to a defined default state when no valid decode is active. Defaults are:\n\n- jump_in_dec, jump_set, branch_in_dec, icache_inval = 0.\n- Multdiv_operator = MD_OP_MULL, signed_mode = 00.\n- Register file write data select = RF_WD_EX, write enable = 0, read enables = 0.\n- CSR access = 0, CSR operation = read.\n- Data request = 0, data write enable = 0, data type = 00, sign extension = 0.\n- ALU operator = ALU_SLTU, operand a mux = OP_A_IMM, operand b mux = OP_B_IMM, immediate muxes = appropriate defaults (IMM_A_ZERO, IMM_B_I).\n- Branch target muxes: a = OP_A_CURRPC, b = IMM_B_I.\n- Illegal, ebreak, ecall, mret, dret, wfi = 0.\n- Alu_multicycle = 0.\n- Mult_sel, div_sel = 0.\n\n### 10. Assertions (Non-Functional)\n\nThe decoder must include assertions to verify that when the opcode is OPCODE_OP_IMM, the funct3 field (bits 14:12) is not unknown (X). This is a design verification assertion, not an operational requirement.\n\n### 11. Configuration Parameters\n\nThe decoder’s behavior is parameterized by:\n\n- **RV32E**: Enables checking for register numbers > 15.\n- **RV32M**: Enables decoding of multiply/divide instructions.\n- **RV32B**: Enables decoding of bit-manipulation instructions (Zbb, Zbs, Zbp, Zbe, Zbf, Zbc, Zbr, Zbt).\n- **BranchTargetALU**: When 1, branch and jump targets are computed by a separate unit, allowing one-cycle-reduced latency compared to main ALU usage. The decoder must adjust its multi-cycle sequencing accordingly: jumps and branches no longer use the main ALU for target calculation, only for condition evaluation (branches) or PC+4 writeback (jumps). The branch target ALU mux selects must be set appropriately.\n\n### 12. Summary of Functional Behavior\n\nThe decoder transforms an instruction word into a complete set of control signals that govern the operation of the ALU, register file, memory subsystem, and CSR block. It must:\n\n- Correctly decode all base RV32I instructions.\n- Optionally decode RV32M and RV32B extensions based on parameters.\n- Handle sequential multi-cycle execution for jumps, branches, and some bit-manipulation instructions.\n- Detect and suppress all illegal instruction conditions, including RV32E register violations.\n- Generate all necessary immediates and mux selects.\n- Ensure that no side effects (write enables, memory requests) occur for illegal instructions.\n- Provide a stable combinatorial path from instruction input to all outputs within a single clock cycle.", "commit_id": "356fb55f7eac9be9ce39e06ebc1f81eee35d13db", "timestamp": "2020-06-18T14:38:06+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "4eece98875d05d3c7c99422f36c34dadcb0569f1", "pr_title": "fix for #30", "pr_body": "Signed-off-by: Bert Pieters \r\n\r\nfor fox issue https://github.com/lowRISC/ibex/issues/30", "issue_title": "Cleanup: Remove REG_* defines from ibex_id_stage", "issue_body": "Can we get rid of those defines and replace them by parameters or structs?", "commit_message": "[rtl] Remove use of `define in decoder\n\nFixes #30\n\nSigned-off-by: Bert Pieters ", "fix_patch": "diff --git a/rtl/ibex_decoder.sv b/rtl/ibex_decoder.sv\nindex 96acd3d368..b8952754ba 100644\n--- a/rtl/ibex_decoder.sv\n+++ b/rtl/ibex_decoder.sv\n@@ -3,11 +3,6 @@\n // Licensed under the Apache License, Version 2.0, see LICENSE for details.\n // SPDX-License-Identifier: Apache-2.0\n \n-// Source/Destination register instruction index\n-`define REG_S1 19:15\n-`define REG_S2 24:20\n-`define REG_S3 31:27\n-`define REG_D 11:07\n \n /**\n * Instruction decoder\n@@ -111,6 +106,11 @@ module ibex_decoder #(\n \n logic [31:0] instr;\n logic [31:0] instr_alu;\n+ // Source/Destination register instruction index\n+ logic [4:0] instr_rs1;\n+ logic [4:0] instr_rs2;\n+ logic [4:0] instr_rs3;\n+ logic [4:0] instr_rd;\n \n logic use_rs3;\n \n@@ -137,14 +137,18 @@ module ibex_decoder #(\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+ assign zimm_rs1_type_o = { 27'b0, instr_rs1 }; // rs1\n \n // source registers\n- assign rf_raddr_a_o = use_rs3 ? instr[`REG_S3] : instr[`REG_S1]; // rs3 / rs1\n- assign rf_raddr_b_o = instr[`REG_S2]; // rs2\n+ assign instr_rs1 = instr[19:15];\n+ assign instr_rs2 = instr[24:20];\n+ assign instr_rs3 = instr[31:27];\n+ assign rf_raddr_a_o = use_rs3 ? instr_rs3 : instr_rs1; // rs3 / rs1\n+ assign rf_raddr_b_o = instr_rs2; // rs2\n \n // destination register\n- assign rf_waddr_o = instr[`REG_D]; // rd\n+ assign instr_rd = instr[11:7];\n+ assign rf_waddr_o = instr_rd; // rd\n \n ////////////////////\n // Register check //\n@@ -166,7 +170,7 @@ module ibex_decoder #(\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+ instr_rs1 == '0) begin\n csr_op_o = CSR_OP_READ;\n end\n end\n@@ -555,7 +559,7 @@ module ibex_decoder #(\n endcase\n \n // rs1 and rd must be 0\n- if (instr[`REG_S1] != 5'b0 || instr[`REG_D] != 5'b0) begin\n+ if (instr_rs1 != 5'b0 || instr_rd != 5'b0) begin\n illegal_insn = 1'b1;\n end\n end else begin\n", "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 * Instruction decoder\n *\n * This module is fully combinatorial, clock and reset are used for\n * assertions only.\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_decoder #(\n parameter bit RV32E = 0,\n parameter bit RV32M = 1,\n parameter bit RV32B = 0,\n parameter bit BranchTargetALU = 0\n) (\n input logic clk_i,\n input logic rst_ni,\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 input logic branch_taken_i, // registered branch decision\n output logic icache_inval_o,\n\n // from IF-ID pipeline register\n input logic instr_first_cycle_i, // instruction read is in its first cycle\n input logic [31:0] instr_rdata_i, // instruction read from memory/cache\n input logic [31:0] instr_rdata_alu_i, // instruction read from memory/cache\n // replicated to ease fan-out)\n\n input logic illegal_c_insn_i, // compressed instruction decode failed\n\n // immediates\n output ibex_pkg::imm_a_sel_e imm_a_mux_sel_o, // immediate selection for operand a\n output ibex_pkg::imm_b_sel_e imm_b_mux_sel_o, // immediate selection for operand b\n output ibex_pkg::op_a_sel_e bt_a_mux_sel_o, // branch target selection operand a\n output ibex_pkg::imm_b_sel_e bt_b_mux_sel_o, // branch target selection 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_pkg::rf_wd_sel_e rf_wdata_sel_o, // RF write data selection\n output logic rf_we_o, // write enable for regfile\n output logic [4:0] rf_raddr_a_o,\n output logic [4:0] rf_raddr_b_o,\n output logic [4:0] rf_waddr_o,\n output logic rf_ren_a_o, // Instruction reads from RF addr A\n output logic rf_ren_b_o, // Instruction reads from RF addr B\n\n // ALU\n output ibex_pkg::alu_op_e alu_operator_o, // ALU operation selection\n output ibex_pkg::op_a_sel_e alu_op_a_mux_sel_o, // operand a selection: reg value, PC,\n // immediate or zero\n output ibex_pkg::op_b_sel_e alu_op_b_mux_sel_o, // operand b selection: reg value or\n // immediate\n output logic alu_multicycle_o, // ternary bitmanip instruction\n\n // MULT & DIV\n output logic mult_en_o, // perform integer multiplication\n output logic div_en_o, // perform integer division or remainder\n output logic mult_sel_o, // as above but static, for data muxes\n output logic div_sel_o, // as above but static, for data muxes\n\n output ibex_pkg::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_pkg::csr_op_e csr_op_o, // operation to perform on 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\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_pkg::*;\n\n logic illegal_insn;\n logic illegal_reg_rv32e;\n logic csr_illegal;\n logic rf_we;\n\n logic [31:0] instr;\n logic [31:0] instr_alu;\n // Source/Destination register instruction index\n logic [4:0] instr_rs1;\n logic [4:0] instr_rs2;\n logic [4:0] instr_rs3;\n logic [4:0] instr_rd;\n\n logic use_rs3;\n\n csr_op_e csr_op;\n\n opcode_e opcode;\n opcode_e opcode_alu;\n\n // To help timing the flops containing the current instruction are replicated to reduce fan-out.\n // instr_alu is used to determine the ALU control logic and associated operand/imm select signals\n // as the ALU is often on the more critical timing paths. instr is used for everything else.\n assign instr = instr_rdata_i;\n assign instr_alu = instr_rdata_alu_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_rs1 }; // rs1\n\n // source registers\n assign instr_rs1 = instr[19:15];\n assign instr_rs2 = instr[24:20];\n assign instr_rs3 = instr[31:27];\n assign rf_raddr_a_o = use_rs3 ? instr_rs3 : instr_rs1; // rs3 / rs1\n assign rf_raddr_b_o = instr_rs2; // rs2\n\n // destination register\n assign instr_rd = instr[11:7];\n assign rf_waddr_o = instr_rd; // rd\n\n ////////////////////\n // Register check //\n ////////////////////\n if (RV32E) begin : gen_rv32e_reg_check_active\n assign illegal_reg_rv32e = ((rf_raddr_a_o[4] & (alu_op_a_mux_sel_o == OP_A_REG_A)) |\n (rf_raddr_b_o[4] & (alu_op_b_mux_sel_o == OP_B_REG_B)) |\n (rf_waddr_o[4] & rf_we));\n end else begin : gen_rv32e_reg_check_inactive\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_rs1 == '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 icache_inval_o = 1'b0;\n\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n\n rf_wdata_sel_o = RF_WD_EX;\n rf_we = 1'b0;\n rf_ren_a_o = 1'b0;\n rf_ren_b_o = 1'b0;\n\n csr_access_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_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\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n jump_in_dec_o = 1'b1;\n\n if (instr_first_cycle_i) begin\n // Calculate jump target (and store PC + 4 if BranchTargetALU is configured)\n rf_we = BranchTargetALU;\n jump_set_o = 1'b1;\n end else begin\n // Calculate and store PC+4\n rf_we = 1'b1;\n end\n if (instr[14:12] != 3'b0) begin\n illegal_insn = 1'b1;\n end\n\n rf_ren_a_o = 1'b1;\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,\n 3'b001,\n 3'b100,\n 3'b101,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n default: illegal_insn = 1'b1;\n endcase\n\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n end\n\n ////////////////\n // Load/store //\n ////////////////\n\n OPCODE_STORE: begin\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n data_req_o = 1'b1;\n data_we_o = 1'b1;\n\n if (instr[14]) begin\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: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_LOAD: begin\n rf_ren_a_o = 1'b1;\n data_req_o = 1'b1;\n data_type_o = 2'b00;\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(u)\n 2'b01: data_type_o = 2'b01; // lh(u)\n 2'b10: begin\n data_type_o = 2'b00; // lw\n if (instr[14]) begin\n illegal_insn = 1'b1; // lwu does not exist\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n /////////\n // ALU //\n /////////\n\n OPCODE_LUI: begin // Load Upper Immediate\n rf_we = 1'b1;\n end\n\n OPCODE_AUIPC: begin // Add Upper Immediate to PC\n rf_we = 1'b1;\n end\n\n OPCODE_OP_IMM: begin // Register-Immediate ALU Operations\n rf_ren_a_o = 1'b1;\n rf_we = 1'b1;\n\n unique case (instr[14:12])\n 3'b000,\n 3'b010,\n 3'b011,\n 3'b100,\n 3'b110,\n 3'b111: illegal_insn = 1'b0;\n\n 3'b001: begin\n unique case (instr[31:27])\n 5'b0_0000: illegal_insn = 1'b0; // slli\n 5'b0_0100, // sloi\n 5'b0_1001, // sbclri\n 5'b0_0101, // sbseti\n 5'b0_1101: illegal_insn = RV32B ? 1'b0 : 1'b1; // sbinvi\n 5'b0_0001: if (instr[26] == 1'b0) begin\n illegal_insn = RV32B ? 1'b0 : 1'b1; // shfl\n end else begin\n illegal_insn = 1'b1;\n end\n 5'b0_1100: begin\n unique case(instr[26:20])\n 7'b000_0000, // clz\n 7'b000_0001, // ctz\n 7'b000_0010, // pcnt\n 7'b000_0100, // sext.b\n 7'b000_0101, // sext.h\n 7'b001_0000, // crc32.b\n 7'b001_0001, // crc32.h\n 7'b001_0010, // crc32.w\n 7'b001_1000, // crc32c.b\n 7'b001_1001, // crc32c.h\n 7'b001_1010: illegal_insn = RV32B ? 1'b0 : 1'b1; // crc32c.w\n\n default: illegal_insn = 1'b1;\n endcase\n end\n default : illegal_insn = 1'b1;\n endcase\n end\n\n 3'b101: begin\n if (instr[26]) begin\n illegal_insn = RV32B ? 1'b0 : 1'b1; // fsri\n end else begin\n unique case (instr[31:27])\n 5'b0_0000, // srli\n 5'b0_1000: illegal_insn = 1'b0; // srai\n\n 5'b0_0100, // sroi\n 5'b0_1100, // rori\n 5'b0_1001: illegal_insn = RV32B ? 1'b0 : 1'b1; // sbexti\n\n 5'b0_1101, // grevi\n 5'b0_0101: illegal_insn = RV32B ? 1'b0 : 1'b1; // gorci\n 5'b0_0001: if (instr[26] == 1'b0) begin\n illegal_insn = RV32B ? 1'b0 : 1'b1; // unshfl\n end else begin\n illegal_insn = 1'b1;\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n end\n\n default: illegal_insn = 1'b1;\n endcase\n end\n\n OPCODE_OP: begin // Register-Register ALU operation\n rf_ren_a_o = 1'b1;\n rf_ren_b_o = 1'b1;\n rf_we = 1'b1;\n if ({instr[26], instr[13:12]} == {1'b1, 2'b01}) begin\n illegal_insn = RV32B ? 1'b0 : 1'b1; // cmix / cmov / fsl / fsr\n end else begin\n unique case ({instr[31:25], instr[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000},\n {7'b010_0000, 3'b000},\n {7'b000_0000, 3'b010},\n {7'b000_0000, 3'b011},\n {7'b000_0000, 3'b100},\n {7'b000_0000, 3'b110},\n {7'b000_0000, 3'b111},\n {7'b000_0000, 3'b001},\n {7'b000_0000, 3'b101},\n {7'b010_0000, 3'b101}: illegal_insn = 1'b0;\n\n // RV32B zbb\n {7'b010_0000, 3'b111}, // andn\n {7'b010_0000, 3'b110}, // orn\n {7'b010_0000, 3'b100}, // xnor\n {7'b001_0000, 3'b001}, // slo\n {7'b001_0000, 3'b101}, // sro\n {7'b011_0000, 3'b001}, // rol\n {7'b011_0000, 3'b101}, // ror\n {7'b000_0101, 3'b100}, // min\n {7'b000_0101, 3'b101}, // max\n {7'b000_0101, 3'b110}, // minu\n {7'b000_0101, 3'b111}, // maxu\n {7'b000_0100, 3'b100}, // pack\n {7'b010_0100, 3'b100}, // packu\n {7'b000_0100, 3'b111}, // packh\n // RV32B zbs\n {7'b010_0100, 3'b001}, // sbclr\n {7'b001_0100, 3'b001}, // sbset\n {7'b011_0100, 3'b001}, // sbinv\n {7'b010_0100, 3'b101}, // sbext\n // RV32B zbe\n {7'b010_0100, 3'b110}, // bdep\n {7'b000_0100, 3'b110}, // bext\n // RV32B zbp\n {7'b011_0100, 3'b101}, // grev\n {7'b001_0100, 3'b101}, // gorc\n {7'b000_0100, 3'b001}, // shfl\n {7'b000_0100, 3'b101}, // unshfl\n // RV32B zbf\n {7'b010_0100, 3'b111}, // bfp\n // RV32B zbc\n {7'b000_0101, 3'b001}, // clmul\n {7'b000_0101, 3'b010}, // clmulr\n {7'b000_0101, 3'b011}: illegal_insn = RV32B ? 1'b0 : 1'b1; // clmulh\n\n // RV32M instructions\n {7'b000_0001, 3'b000}: begin // mul\n multdiv_operator_o = MD_OP_MULL;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b01;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n multdiv_operator_o = MD_OP_MULH;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b100}: begin // div\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b101}: begin // divu\n multdiv_operator_o = MD_OP_DIV;\n multdiv_signed_mode_o = 2'b00;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b110}: begin // rem\n multdiv_operator_o = MD_OP_REM;\n multdiv_signed_mode_o = 2'b11;\n illegal_insn = RV32M ? 1'b0 : 1'b1;\n end\n {7'b000_0001, 3'b111}: begin // remu\n multdiv_operator_o = MD_OP_REM;\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. This may not be correct\n // in a system with caches and should be revisited.\n // FENCE.I will flush the IF stage and prefetch buffer (or ICache) but nothing else.\n unique case (instr[14:12])\n 3'b000: begin\n rf_we = 1'b0;\n end\n 3'b001: begin\n // FENCE.I is implemented as a jump to the next PC, this gives the required flushing\n // behaviour (iside prefetch buffer flushed and response to any outstanding iside\n // requests will be ignored).\n // If present, the ICache will also be flushed.\n jump_in_dec_o = 1'b1;\n\n rf_we = 1'b0;\n\n if (instr_first_cycle_i) begin\n jump_set_o = 1'b1;\n icache_inval_o = 1'b1;\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr[14:12] == 3'b000) begin\n // non CSR related SYSTEM instructions\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_rs1 != 5'b0 || instr_rd != 5'b0) 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 rf_wdata_sel_o = RF_WD_CSR;\n rf_we = 1'b1;\n\n if (~instr[14]) begin\n rf_ren_a_o = 1'b1;\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 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, PC\n // NOTE: instructions can also be detected to be illegal inside the CSRs (upon accesses with\n // insufficient privileges), or when accessing non-available registers in RV32E,\n // these cases are not handled here\n if (illegal_insn) begin\n rf_we = 1'b0;\n data_req_o = 1'b0;\n data_we_o = 1'b0;\n jump_in_dec_o = 1'b0;\n jump_set_o = 1'b0;\n branch_in_dec_o = 1'b0;\n csr_access_o = 1'b0;\n end\n end\n\n /////////////////////////////\n // Decoder for ALU control //\n /////////////////////////////\n\n always_comb begin\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 bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_I;\n\n\n opcode_alu = opcode_e'(instr_alu[6:0]);\n\n use_rs3 = 1'b0;\n alu_multicycle_o = 1'b0;\n mult_sel_o = 1'b0;\n div_sel_o = 1'b0;\n\n unique case (opcode_alu)\n\n ///////////\n // Jumps //\n ///////////\n\n OPCODE_JAL: begin // Jump and Link\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_J;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_JALR: begin // Jump and Link Register\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_REG_A;\n bt_b_mux_sel_o = IMM_B_I;\n end\n\n // Jumps take two cycles without the BTALU\n if (instr_first_cycle_i && !BranchTargetALU) 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 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 end\n end\n\n OPCODE_BRANCH: begin // Branch\n // Check branch condition selection\n unique case (instr_alu[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: ;\n endcase\n\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n // Not-taken branch will jump to next instruction (used in secure mode)\n bt_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n end\n\n // Without branch target ALU, a branch is a two-stage operation using the Main ALU in both\n // stages\n if (instr_first_cycle_i) begin\n // First evaluate the 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 // Then calculate jump target\n alu_op_a_mux_sel_o = OP_A_CURRPC;\n alu_op_b_mux_sel_o = OP_B_IMM;\n // Not-taken branch will jump to next instruction (used in secure mode)\n imm_b_mux_sel_o = branch_taken_i ? IMM_B_B : IMM_B_INCR_PC;\n alu_operator_o = ALU_ADD;\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 alu_operator_o = ALU_ADD;\n\n if (!instr_alu[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\n end\n\n OPCODE_LOAD: begin\n alu_op_a_mux_sel_o = OP_A_REG_A;\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 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 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 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\n unique case (instr_alu[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 if (RV32B) begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n 5'b0_0100: alu_operator_o = ALU_SLO; // Shift Left Ones by Immediate\n 5'b0_1001: alu_operator_o = ALU_SBCLR; // Clear bit specified by immediate\n 5'b0_0101: alu_operator_o = ALU_SBSET; // Set bit specified by immediate\n 5'b0_1101: alu_operator_o = ALU_SBINV; // Invert bit specified by immediate.\n // Shuffle with Immediate Control Value\n 5'b0_0001: if (instr_alu[26] == 0) alu_operator_o = ALU_SHFL;\n 5'b0_1100: begin\n unique case (instr_alu[26:20])\n 7'b000_0000: alu_operator_o = ALU_CLZ; // clz\n 7'b000_0001: alu_operator_o = ALU_CTZ; // ctz\n 7'b000_0010: alu_operator_o = ALU_PCNT; // pcnt\n 7'b000_0100: alu_operator_o = ALU_SEXTB; // sext.b\n 7'b000_0101: alu_operator_o = ALU_SEXTH; // sext.h\n 7'b001_0000: begin\n alu_operator_o = ALU_CRC32_B; // crc32.b\n alu_multicycle_o = 1'b1;\n end\n 7'b001_0001: begin\n alu_operator_o = ALU_CRC32_H; // crc32.h\n alu_multicycle_o = 1'b1;\n end\n 7'b001_0010: begin\n alu_operator_o = ALU_CRC32_W; // crc32.w\n alu_multicycle_o = 1'b1;\n end\n 7'b001_1000: begin\n alu_operator_o = ALU_CRC32C_B; // crc32c.b\n alu_multicycle_o = 1'b1;\n end\n 7'b001_1001: begin\n alu_operator_o = ALU_CRC32C_H; // crc32c.h\n alu_multicycle_o = 1'b1;\n end\n 7'b001_1010: begin\n alu_operator_o = ALU_CRC32C_W; // crc32c.w\n alu_multicycle_o = 1'b1;\n end\n default: ;\n endcase\n end\n\n default: ;\n endcase\n end else begin\n alu_operator_o = ALU_SLL; // Shift Left Logical by Immediate\n end\n end\n\n 3'b101: begin\n if (RV32B) begin\n if (instr_alu[26] == 1'b1) begin\n alu_operator_o = ALU_FSR;\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3 = 1'b0;\n end else begin\n use_rs3 = 1'b1;\n end\n end else begin\n unique case (instr_alu[31:27])\n 5'b0_0000: alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n 5'b0_1000: alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n 5'b0_0100: alu_operator_o = ALU_SRO; // Shift Right Ones by Immediate\n 5'b0_1001: alu_operator_o = ALU_SBEXT; // Extract bit specified by immediate.\n 5'b0_1100: begin\n alu_operator_o = ALU_ROR; // Rotate Right by Immediate\n alu_multicycle_o = 1'b1;\n end\n 5'b0_1101: alu_operator_o = ALU_GREV; // General Reverse with Imm Control Val\n 5'b0_0101: alu_operator_o = ALU_GORC; // General Or-combine with Imm Control Val\n // Unshuffle with Immediate Control Value\n 5'b0_0001: if (instr_alu[26] == 1'b0) alu_operator_o = ALU_UNSHFL;\n default: ;\n endcase\n end\n\n end else begin\n if (instr_alu[31:27] == 5'b0_0000) begin\n alu_operator_o = ALU_SRL; // Shift Right Logical by Immediate\n end else if (instr_alu[31:27] == 5'b0_1000) begin\n alu_operator_o = ALU_SRA; // Shift Right Arithmetically by Immediate\n end\n end\n end\n\n default: ;\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\n if (instr_alu[26]) begin\n if (RV32B) begin\n unique case ({instr_alu[26:25], instr_alu[14:12]})\n {2'b11, 3'b001}: begin\n alu_operator_o = ALU_CMIX; // cmix\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3 = 1'b0;\n end else begin\n use_rs3 = 1'b1;\n end\n end\n {2'b11, 3'b101}: begin\n alu_operator_o = ALU_CMOV; // cmov\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3 = 1'b0;\n end else begin\n use_rs3 = 1'b1;\n end\n end\n {2'b10, 3'b001}: begin\n alu_operator_o = ALU_FSL; // fsl\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3 = 1'b0;\n end else begin\n use_rs3 = 1'b1;\n end\n end\n {2'b10, 3'b101}: begin\n alu_operator_o = ALU_FSR; // fsr\n alu_multicycle_o = 1'b1;\n if (instr_first_cycle_i) begin\n use_rs3 = 1'b0;\n end else begin\n use_rs3 = 1'b1;\n end\n end\n default: ;\n endcase\n end\n end else begin\n unique case ({instr_alu[31:25], instr_alu[14:12]})\n // RV32I ALU operations\n {7'b000_0000, 3'b000}: alu_operator_o = ALU_ADD; // Add\n {7'b010_0000, 3'b000}: alu_operator_o = ALU_SUB; // Sub\n {7'b000_0000, 3'b010}: alu_operator_o = ALU_SLT; // Set Lower Than\n {7'b000_0000, 3'b011}: alu_operator_o = ALU_SLTU; // Set Lower Than Unsigned\n {7'b000_0000, 3'b100}: alu_operator_o = ALU_XOR; // Xor\n {7'b000_0000, 3'b110}: alu_operator_o = ALU_OR; // Or\n {7'b000_0000, 3'b111}: alu_operator_o = ALU_AND; // And\n {7'b000_0000, 3'b001}: alu_operator_o = ALU_SLL; // Shift Left Logical\n {7'b000_0000, 3'b101}: alu_operator_o = ALU_SRL; // Shift Right Logical\n {7'b010_0000, 3'b101}: alu_operator_o = ALU_SRA; // Shift Right Arithmetic\n\n // RV32B ALU Operations\n {7'b001_0000, 3'b001}: if (RV32B) alu_operator_o = ALU_SLO; // slo\n {7'b001_0000, 3'b101}: if (RV32B) alu_operator_o = ALU_SRO; // sro\n {7'b011_0000, 3'b001}: begin\n if (RV32B) begin\n alu_operator_o = ALU_ROL; // rol\n alu_multicycle_o = 1'b1;\n end\n end\n {7'b011_0000, 3'b101}: begin\n if (RV32B) begin\n alu_operator_o = ALU_ROR; // ror\n alu_multicycle_o = 1'b1;\n end\n end\n\n {7'b000_0101, 3'b100}: if (RV32B) alu_operator_o = ALU_MIN; // min\n {7'b000_0101, 3'b101}: if (RV32B) alu_operator_o = ALU_MAX; // max\n {7'b000_0101, 3'b110}: if (RV32B) alu_operator_o = ALU_MINU; // minu\n {7'b000_0101, 3'b111}: if (RV32B) alu_operator_o = ALU_MAXU; // maxu\n\n {7'b000_0100, 3'b100}: if (RV32B) alu_operator_o = ALU_PACK; // pack\n {7'b010_0100, 3'b100}: if (RV32B) alu_operator_o = ALU_PACKU; // packu\n {7'b000_0100, 3'b111}: if (RV32B) alu_operator_o = ALU_PACKH; // packh\n\n {7'b010_0000, 3'b100}: if (RV32B) alu_operator_o = ALU_XNOR; // xnor\n {7'b010_0000, 3'b110}: if (RV32B) alu_operator_o = ALU_ORN; // orn\n {7'b010_0000, 3'b111}: if (RV32B) alu_operator_o = ALU_ANDN; // andn\n\n // RV32B zbp\n {7'b011_0100, 3'b101}: if (RV32B) alu_operator_o = ALU_GREV; // grev\n {7'b001_0100, 3'b101}: if (RV32B) alu_operator_o = ALU_GORC; // grev\n {7'b000_0100, 3'b001}: if (RV32B) alu_operator_o = ALU_SHFL; // shfl\n {7'b000_0100, 3'b101}: if (RV32B) alu_operator_o = ALU_UNSHFL; // unshfl\n\n // RV32B zbs\n {7'b010_0100, 3'b001}: if (RV32B) alu_operator_o = ALU_SBCLR; // sbclr\n {7'b001_0100, 3'b001}: if (RV32B) alu_operator_o = ALU_SBSET; // sbset\n {7'b011_0100, 3'b001}: if (RV32B) alu_operator_o = ALU_SBINV; // sbinv\n {7'b010_0100, 3'b101}: if (RV32B) alu_operator_o = ALU_SBEXT; // sbext\n\n // RV32B zbc\n {7'b000_0101, 3'b001}: if (RV32B) alu_operator_o = ALU_CLMUL; // clmul\n {7'b000_0101, 3'b010}: if (RV32B) alu_operator_o = ALU_CLMULR; // clmulr\n {7'b000_0101, 3'b011}: if (RV32B) alu_operator_o = ALU_CLMULH; // clmulh\n\n // RV32B zbe\n {7'b010_0100, 3'b110}: if (RV32B) alu_operator_o = ALU_BDEP; // bdep\n {7'b000_0100, 3'b110}: if (RV32B) alu_operator_o = ALU_BEXT; // bext\n // RV32B zbf\n {7'b010_0100, 3'b111}: if (RV32B) alu_operator_o = ALU_BFP; // bfp\n\n // RV32M instructions, all use the same ALU operation\n {7'b000_0001, 3'b000}: begin // mul\n alu_operator_o = ALU_ADD;\n mult_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b001}: begin // mulh\n alu_operator_o = ALU_ADD;\n mult_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b010}: begin // mulhsu\n alu_operator_o = ALU_ADD;\n mult_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b011}: begin // mulhu\n alu_operator_o = ALU_ADD;\n mult_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b100}: begin // div\n alu_operator_o = ALU_ADD;\n div_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b101}: begin // divu\n alu_operator_o = ALU_ADD;\n div_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b110}: begin // rem\n alu_operator_o = ALU_ADD;\n div_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n {7'b000_0001, 3'b111}: begin // remu\n alu_operator_o = ALU_ADD;\n div_sel_o = RV32M ? 1'b1 : 1'b0;\n end\n\n default: ;\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. This may not be correct\n // in a system with caches and should be revisited.\n // FENCE.I will flush the IF stage and prefetch buffer but nothing else.\n unique case (instr_alu[14:12])\n 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 end\n 3'b001: begin\n if (BranchTargetALU) begin\n bt_a_mux_sel_o = OP_A_CURRPC;\n bt_b_mux_sel_o = IMM_B_INCR_PC;\n end else begin\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 end\n end\n default: ;\n endcase\n end\n\n OPCODE_SYSTEM: begin\n if (instr_alu[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 end else begin\n // instruction to read/modify CSR\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_alu[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 end\n\n end\n default: ;\n endcase\n end\n\n // do not enable multdiv in case of illegal instruction exceptions\n assign mult_en_o = illegal_insn ? 1'b0 : mult_sel_o;\n assign div_en_o = illegal_insn ? 1'b0 : div_sel_o;\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 rf_we_o = rf_we & ~illegal_reg_rv32e;\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT(IbexRegImmAluOpKnown, (opcode == OPCODE_OP_IMM) |->\n !$isunknown(instr[14:12]))\nendmodule // controller\n", "selected_doc_paths": ["doc/instruction_decode_execute.rst", "doc/pipeline_details.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 1176, "lang": "sv", "rtl_files": ["dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv"], "spec": "# Design Specification: `core_ibex_instr_monitor_if`\n\n## Overview\n\nThis interface provides a synchronous observation point into the **Instruction Decode and Execute (ID/EX)** pipeline stage of the Ibex core. It is intended for use in UVM verification environments to monitor the progress of instructions as they flow through the core. The interface captures key control and data signals from the ID stage on every rising edge of the clock, enabling a testbench to reconstruct the instruction sequence, detect pipeline events, and validate core behavior against a reference model (e.g., an ISS).\n\nThe interface is passive: it only makes internal signals available to the testbench and does not drive any core inputs.\n\n## Functional Description\n\n### Clocking and Synchronization\n\nAll signals are sampled using a clocking block clocked on the **positive edge** of the provided clock signal. The values observed on a given clock edge correspond to the state of the ID stage at that cycle. No explicit reset is required; the monitor may be active at all times.\n\n### Observed Signals\n\nThe interface exposes the following information for each clock cycle. These represent the state of the ID pipeline stage:\n\n| Observed Information | Description |\n|-----------------------------------------------|-----------------------------------------------------------------------------------------------|\n| **Instruction valid** | Indicates whether a valid instruction is present in the ID stage. When asserted, all other signals (except those noted) carry meaningful data for the current instruction. |\n| **Error indicator** | Signals that an error has been detected in the ID stage (e.g., an illegal instruction or a fetch error). |\n| **Compressed instruction** | Indicates whether the instruction currently in ID is a 16‑bit compressed instruction (RV32C). |\n| **Compressed instruction bits** | The raw 16‑bit value of the compressed instruction (only valid when `is_compressed` is true). |\n| **Uncompressed instruction** | The full 32‑bit instruction word (either the original uncompressed instruction or the expanded form of a compressed instruction). |\n| **Program counter (PC)** | The address of the instruction currently in the ID stage. |\n| **Branch taken** | Indicates that the instruction evaluated a branch condition and the branch **was taken** (i.e., the condition was met). |\n| **Branch target address** | The target PC computed for a taken branch instruction. |\n| **Stall** | When asserted, the ID stage is stalled (e.g., waiting for a multi‑cycle operation such as a load, multiply, or divide). No new instruction advances into ID during stall cycles. |\n| **Jump detected** | Indicates that the instruction in ID is performing a jump (unconditional branch, `JAL`, or a similar control‑flow change). This may include jumps caused by exceptions, interrupts, or debug entry. |\n\n### Behavioral Assumptions and Constraints\n\n- **Dummy instruction insertion**: The current version of this interface **does not** support observation of dummy instructions that may be inserted into the pipeline (e.g., during flush or speculation bubble cycles). Future revisions may add this capability.\n- **Multi‑cycle instructions**: During a stall caused by a multi‑cycle instruction (e.g., multiply, divide, load), the `stall` signal will be asserted. The `valid` signal remains asserted for the instruction that caused the stall until it completes.\n- **Branch / jump interactions**: For taken branches, the `branch_taken` and `branch_target` signals are valid in the cycle the instruction is in ID. The `jump_set` signal may be asserted simultaneously for branches that also set a jump target (e.g., `JALR`). For jumps, `jump_set` is asserted and `branch_taken` is typically not asserted (unless the jump is also a branch-like instruction).\n- **Error handling**: When `err` is asserted, the instruction is considered invalid. The remaining signals may not be meaningful and should be ignored by the testbench.\n- **Parameterization**: The width of the PC and instruction data is configurable via the `DATA_WIDTH` parameter (default 32). All addresses and data signals follow this width.\n\n## Usage in Verification\n\nThe interface is typically used in a UVM monitor component that samples the signals on every clock edge and builds a transaction object representing the instruction flow. The monitor can then drive this transaction to scoreboards, coverage collectors, or to a comparison agent that validates core execution against an instruction set simulator.\n\n### Example Use Cases\n\n- **Trace logging**: Record every instruction executed, including PC, instruction word, branch decisions, and stalls.\n- **Coverage collection**: Track which instruction types, branch patterns, and error conditions have been observed.\n- **Golden model comparison**: Compare the sequence of instructions with the trace output of Spike or another ISS to detect mismatches in register updates or control flow.\n- **Post‑silicon validation**: In emulation or FPGA environments, this interface can be used as a lightweight debug hook.\n\n## Interface Parameters\n\n- **DATA_WIDTH** (integer, default = 32): Width of the instruction word, program counter, and branch target address. This shall match the core’s data path width.\n\n## Dependencies\n\nThis interface is instantiated inside the testbench and connected to the corresponding ID‑stage signals of the Ibex core (e.g., from `ibex_id_stage.sv`). It does not interact with any other module.\n\n## Limitations\n\n- As noted above, dummy instruction insertion is not captured.\n- The interface provides no means to distinguish between different stall sources (e.g., load vs. multiply) other than observing the duration of the stall.\n- No support for debugging or forcing values; it is strictly a monitor.\n\n---\n\n*This specification describes the observable behavior and intended usage of the `core_ibex_instr_monitor_if` interface. For detailed implementation and connection guidelines, see the Ibex UVM testbench documentation.*", "commit_id": "5826af8ad924eccdb51b8ea02dfd54a9d4719edf", "timestamp": "2020-11-06T09:25:41+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "1f3b462b9477531a9bf8627a05f92cadfd3c54bb", "pr_title": "[dv] Fix riscv_debug_single_step_test", "pr_body": "Testbench computation of next PC when single stepping was broken. A\r\nbranch may stall before branch_set is asserted and this wasn't being\r\ntaken into account. Where the branch target ALU is present branch_set\r\ncan be set on the first cycle of the branch so this bug wasn't apparent.\r\nEven with the branch target ALU the branch may stall awaiting the result\r\nof a load when the writeback stage is present.\r\n\r\nTo make matters more complicated for a jump the PC being jumped to is\r\nonly available when jump_set is asserted which happens whilst the jump\r\ninstruction is stalling.\r\n\r\nThis alters the riscv_debug_single_step_test so when waiting for a\r\nsingle step it looks for either a branch_set or jump_set signal being\r\nasserted. Otherwise it waits until the instruction has unstalled. This\r\nshould give correct behaviour in all scenarios (potentially further\r\nthought required where exceptions and interrupts occur).\r\n\r\nFixes #1167\r\n\r\nSigned-off-by: Greg Chadwick ", "issue_title": "riscv_debug_single_step_test fail ", "issue_body": "Hi ,\r\nwhen SEED=27754, IBEX_CONFIG=small, ISS=ovpsim, riscv_debug_single_step_test fail because dpc record the branch target address when core executes a branch instruction, but the test bench think the dpc of the core should record the address of the branch instruction address +4, I think the RTL is right, please help double check it.\r\n\r\n\r\nThanks,\r\nLihua", "commit_message": "[dv] Fix riscv_debug_single_step_test\n\nTestbench computation of next PC when single stepping was broken. A\nbranch may stall before branch_set is asserted and this wasn't being\ntaken into account. Where the branch target ALU is present branch_set\ncan be set on the first cycle of the branch so this bug wasn't apparent.\nEven with the branch target ALU the branch may stall awaiting the result\nof a load when the writeback stage is present.\n\nTo make matters more complicated for a jump the PC being jumped to is\nonly available when jump_set is asserted which happens whilst the jump\ninstruction is stalling.\n\nThis alters the riscv_debug_single_step_test so when waiting for a\nsingle step it looks for either a branch_set or jump_set signal being\nasserted. Otherwise it waits until the instruction has unstalled. This\nshould give correct behaviour in all scenarios (potentially further\nthought required where exceptions and interrupts occur).\n\nFixes #1167\n\nSigned-off-by: Greg Chadwick ", "fix_patch": "diff --git a/dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv b/dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv\nindex 171d0f593e..9db8df37e2 100644\n--- a/dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv\n+++ b/dv/uvm/core_ibex/env/core_ibex_instr_monitor_if.sv\n@@ -21,6 +21,8 @@ interface core_ibex_instr_monitor_if #(\n logic [DATA_WIDTH-1:0] pc_id;\n logic branch_taken_id;\n logic [DATA_WIDTH-1:0] branch_target_id;\n+ logic stall_id;\n+ logic jump_set_id;\n \n clocking instr_cb @(posedge clk);\n input valid_id;\n@@ -31,6 +33,8 @@ interface core_ibex_instr_monitor_if #(\n input pc_id;\n input branch_taken_id;\n input branch_target_id;\n+ input stall_id;\n+ input jump_set_id;\n endclocking\n \n endinterface\n", "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 the instruction moving through the pipeline\n//\n// TODO: does not support dummy instruction insertion right now,\n// might have to revisit and update.\ninterface core_ibex_instr_monitor_if #(\n parameter DATA_WIDTH = 32\n) (\n input clk\n);\n\n // ID stage\n logic valid_id;\n logic err_id;\n logic is_compressed_id;\n logic [15:0] instr_compressed_id;\n logic [DATA_WIDTH-1:0] instr_id;\n logic [DATA_WIDTH-1:0] pc_id;\n logic branch_taken_id;\n logic [DATA_WIDTH-1:0] branch_target_id;\n logic stall_id;\n logic jump_set_id;\n\n clocking instr_cb @(posedge clk);\n input valid_id;\n input err_id;\n input is_compressed_id;\n input instr_compressed_id;\n input instr_id;\n input pc_id;\n input branch_taken_id;\n input branch_target_id;\n input stall_id;\n input jump_set_id;\n endclocking\n\nendinterface\n", "selected_doc_paths": ["doc/03_reference/instruction_decode_execute.rst", "doc/03_reference/pipeline_details.rst", "doc/03_reference/verification.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 470, "lang": "sv", "rtl_files": ["shared/rtl/sim/simulator_ctrl.sv"], "spec": "# Simulator Control Module (simulator_ctrl) – Design Specification\n\n## 1. Overview\n\nThe simulator control module provides a memory-mapped interface through which software running on the processor can interact with the host simulator environment. It supports two primary functions:\n\n- **Character output** – software can write individual bytes to a simulation log file.\n- **Simulation termination** – software can request an orderly termination of the simulation.\n\nThe module acts as a simple peripheral on the system bus. It is intended for use in simulation-only environments and is not synthesizable for actual silicon.\n\n## 2. Interface\n\nThe module connects to a typical memory-mapped bus with the following signals:\n\n- **Clock input** – all state changes occur on the rising edge of this clock.\n- **Reset input** – active-low, asynchronously clears internal state.\n- **Bus request** – when asserted, indicates a valid bus transaction (read or write) is present.\n- **Write enable** – when asserted together with the bus request, the transaction is a write; otherwise it is a read.\n- **Byte enables** – a 4-bit mask indicating which bytes of the 32-bit data bus are valid for a write transaction.\n- **Address** – a 32-bit address used to select the internal register. Only a subset of address bits is decoded; the register map is given below.\n- **Write data** – the 32-bit data value for a write transaction.\n- **Read data** – the 32-bit value returned to the bus master for a read transaction.\n- **Read valid** – asserted for one cycle to indicate that the read data is valid.\n\nAll bus responses are registered. The module does not insert wait states; a read or write completes in one clock cycle after the request.\n\n## 3. Register Map\n\nThe module decodes two consecutive word-aligned addresses based on bits [9:2] of the address bus. All other address values are ignored (no write effect, read returns zero).\n\n| Address offset | Register name | Access | Description |\n|----------------|---------------------|--------|-----------------------------------------------|\n| `0x00` | `CHAR_OUT_ADDR` | Write | Output a character to the simulation log. |\n| `0x04` | `SIM_CTRL_ADDR` | Write | Request simulation termination. |\n\nReads from any address always return `0x00000000`.\n\n### 3.1 CHAR_OUT_ADDR (Write-only, offset 0x00)\n\nWhen a write transaction targets this address, the module writes the lowest byte of the write data (bits [7:0]) to the simulation log file. Only the byte with the lowest byte enable (bit `BE[0]`) is written; if this enable is not asserted, no output is generated.\n\nAfter writing the character, the module may optionally flush the log file to disk immediately (see parameter `FlushOnChar`). This is useful for monitoring output while the simulation is running.\n\n### 3.2 SIM_CTRL_ADDR (Write-only, offset 0x04)\n\nA write to this address can trigger an orderly shutdown of the simulation. The termination is initiated only when all of the following conditions are met:\n\n- The byte enable for the lowest byte (`BE[0]`) is asserted.\n- The least significant bit of the write data (`wdata[0]`) is 1.\n- The termination sequence has not already been started by a previous write.\n\nIf these conditions are satisfied, the module begins a fixed-length termination countdown. After a short delay (see Section 5), the simulation finishes via the simulator’s `$finish` mechanism. No further bus transactions are processed during the countdown.\n\nOnce the termination sequence has started, any additional writes to `SIM_CTRL_ADDR` are ignored.\n\n## 4. Read Behavior\n\nAll read transactions return a value of zero. The read valid signal is asserted for one cycle, one clock cycle after the bus request is accepted.\n\n## 5. Timing and Transaction Timing\n\n- The module registers the bus request, write enable, byte enables, address, and write data on the rising clock edge when a transaction is presented.\n- For a write, the effect (character output or termination request) is performed on the same clock edge.\n- The read valid is asserted on the clock cycle following the request and remains high for one cycle. The read data is driven concurrently.\n- No back‑to‑back restrictions exist; the module can accept a new transaction every clock cycle.\n\n### Termination Countdown\n\nWhen a write to `SIM_CTRL_ADDR` triggers termination, the module waits for three clock cycles and then calls the simulator’s `$finish` routine. During these three cycles the module ignores any further bus requests.\n\n## 6. Reset Behavior\n\nWhen the reset input is asserted (low), the module’s internal state is cleared:\n\n- The read valid output is deasserted.\n- Any pending termination countdown is aborted.\n- No characters are written to the log.\n\nAfter reset is deasserted, the module is ready to accept bus transactions.\n\n## 7. Parameters\n\n| Parameter | Type | Default | Description |\n|--------------|--------|------------------|------------------------------------------------------------------|\n| `LogName` | string | `\"ibex_out.log\"` | Name (and path) of the simulation log file written by the module. |\n| `FlushOnChar`| bit | `1` | If set to 1, the log file is flushed after every character write; if 0, flushing is left to the system I/O layer. |\n\n## 8. Error Handling\n\nThe module does not generate any error responses. Unsupported address values, writes with invalid byte enables, or read transactions are handled silently (no effect, read data = 0).", "commit_id": "0927f085ee11f5bcb6a446ebc038e01126123c45", "timestamp": "2019-11-14T11:57:13+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "6be1e8aff36df9969496d1f7de6ae396c8a41b1d", "pr_title": "Delay simulator finish", "pr_body": "The tracer needs time to log the final instruction.\r\nIntroduce a counter to delay calling the simulation finish.\r\n\r\n@imphil is that what you had in mind?", "issue_title": "Trace simulator control", "issue_body": "Using the simple system example:\r\n```\r\n$ fusesoc --cores-root=. run --target=sim --setup --build lowrisc:ibex:ibex_simple_system\r\n$ build/lowrisc_ibex_ibex_simple_system_0/sim-verilator/Vibex_simple_system --raminit=examples/sw/simple_system/hello_test/hello_test.vmem\r\n```\r\nproduces the following trace\r\n```\r\n% tail -n 4 trace_core_00000000.log \r\n 1260 626 00100308 8082 c.jr x1 x1:0x001002b8\r\n 1262 627 001002b8 000202b7 lui x5,0x20 x5=0x00020000\r\n 1264 628 001002bc 00428293 addi x5,x5,4 x5:0x00020000 x5=0x00020004\r\n 1266 629 001002c0 4305 c.li x6,1 x6=0x00000001\r\n```\r\n\r\nFrom `crt0.S`\r\n```\r\n /* Halt simulation */ \r\n li x5, SIM_CTRL_BASE + SIM_CTRL_CTRL \r\n li x6, 1 \r\n sw x6, 0(x5)\r\n```\r\nwe see the last store instruction (which terminates the simulation via `simulator_ctrl.sv +73`) is not part of the trace.\r\nProbably not the highest priority to fix, but wanted to document what I saw.", "commit_message": "Delay simulator finish\n\nThe tracer needs time to log the final instruction.\nIntroduce a counter to delay calling the simulation finish.\n\nFixes lowrisc/ibex#468", "fix_patch": "diff --git a/shared/rtl/sim/simulator_ctrl.sv b/shared/rtl/sim/simulator_ctrl.sv\nindex 9fa8de6615..002845a439 100644\n--- a/shared/rtl/sim/simulator_ctrl.sv\n+++ b/shared/rtl/sim/simulator_ctrl.sv\n@@ -36,6 +36,7 @@ module simulator_ctrl #(\n localparam SIM_CTRL_ADDR = 1;\n \n logic [7:0] ctrl_addr;\n+ logic [2:0] sim_finish;\n \n integer log_fd;\n \n@@ -52,6 +53,7 @@ module simulator_ctrl #(\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (~rst_ni) begin\n rvalid_o <= 0;\n+ sim_finish <= 'b0;\n end else begin\n // Immeditely respond to any request\n rvalid_o <= req_i;\n@@ -68,9 +70,9 @@ module simulator_ctrl #(\n end\n end\n SIM_CTRL_ADDR: begin\n- if (be_i[0] & wdata_i[0]) begin\n+ if ((be_i[0] & wdata_i[0]) && (sim_finish == 'b0)) begin\n $display(\"Terminating simulation by software request.\");\n- $finish;\n+ sim_finish <= 3'b001;\n end\n end\n endcase\n@@ -78,6 +80,14 @@ module simulator_ctrl #(\n end\n end\n \n+ always_ff @(posedge clk_i or negedge rst_ni) begin\n+ if (sim_finish != 'b0) begin\n+ sim_finish <= sim_finish + 1;\n+ end\n+ if (sim_finish >= 3'b010) begin\n+ $finish;\n+ end\n+ end\n assign rdata_o = '0;\n endmodule\n \n", "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 * Module for communicating with the simulator that interfaces via the memory\n * system.\n *\n * Contains two registers\n *\n * * 0x0 - CHAR_OUT_ADDR - [7:0] of write data output via output_char DPI call\n * and SimOutputManager (see dv/common/cpp/sim_output_manager.cc)\n * * 0x4 - SIM_CTRL_ADDR - Write 1 to bit 0 to halt sim\n */\n\nmodule simulator_ctrl #(\n // passed to simulator via log_name of output_char DPI call\n parameter string LogName = \"ibex_out.log\",\n // If set flush on every char (useful for monitoring output whilst\n // simulation is running).\n parameter bit FlushOnChar = 1\n) (\n input clk_i,\n input rst_ni,\n\n input req_i,\n input we_i,\n input [ 3:0] be_i,\n input [31:0] addr_i,\n input [31:0] wdata_i,\n output logic rvalid_o,\n output logic [31:0] rdata_o\n);\n\n localparam CHAR_OUT_ADDR = 0;\n localparam SIM_CTRL_ADDR = 1;\n\n logic [7:0] ctrl_addr;\n logic [2:0] sim_finish;\n\n integer log_fd;\n\n initial begin\n log_fd = $fopen(LogName, \"w\");\n end\n\n final begin\n $fclose(log_fd);\n end\n\n assign ctrl_addr = addr_i[9:2];\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (~rst_ni) begin\n rvalid_o <= 0;\n sim_finish <= 'b0;\n end else begin\n // Immeditely respond to any request\n rvalid_o <= req_i;\n\n if (req_i & we_i) begin\n case (ctrl_addr)\n CHAR_OUT_ADDR: begin\n if (be_i[0]) begin\n $fwrite(log_fd, \"%c\", wdata_i[7:0]);\n\n if(FlushOnChar) begin\n $fflush(log_fd);\n end\n end\n end\n SIM_CTRL_ADDR: begin\n if ((be_i[0] & wdata_i[0]) && (sim_finish == 'b0)) begin\n $display(\"Terminating simulation by software request.\");\n sim_finish <= 3'b001;\n end\n end\n endcase\n end\n end\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (sim_finish != 'b0) begin\n sim_finish <= sim_finish + 1;\n end\n if (sim_finish >= 3'b010) begin\n $finish;\n end\n end\n assign rdata_o = '0;\nendmodule\n\n", "selected_doc_paths": []}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 835, "lang": "sv", "rtl_files": ["rtl/ibex_load_store_unit.sv"], "spec": "# Behavioral Design Specification: Load-Store Unit (LSU)\n\n## 1. Overview\n\nThe Load-Store Unit (LSU) is the core’s interface to the data memory system. It is responsible for executing load and store operations for the full set of RISC‑V data access sizes (byte, half-word, word) with support for misaligned addresses and sign extension. The LSU communicates with the memory via a standard request/grant/response protocol and interacts with the processor’s ID/EX pipeline stage to stall execution until the memory transaction is completed or an error is reported.\n\n## 2. Supported Operations\n\nThe LSU supports the following memory access types:\n\n- **Load Word** (32‑bit, aligned or misaligned) \n- **Load Half-Word** (16‑bit, aligned or misaligned) \n- **Load Byte** (8‑bit, aligned or misaligned) \n- **Store Word** (32‑bit, aligned or misaligned) \n- **Store Half-Word** (16‑bit, aligned or misaligned) \n- **Store Byte** (8‑bit, aligned or misaligned)\n\nEach operation is signalled by the ID/EX stage along with the write‑enable flag, data type, write data, sign‑extension control, and the computed memory address (from the ALU). The LSU reports completion of the transaction and, for loads, returns the correctly aligned and sign‑extended data to the register file.\n\n## 3. Bus Protocol\n\nThe LSU uses a simple handshake protocol with the data memory:\n\n1. **Request** – The LSU drives a valid, word‑aligned address, byte enables, write data (for stores), and asserts a request signal. \n2. **Grant** – The memory side asserts a grant signal when it is ready to accept the request. Grant may be given in the same cycle the request is issued, or after any number of cycles. Once grant is received, the LSU may change the address and all other request signals in the next cycle. \n3. **Response** – The memory side asserts a response valid signal for exactly one cycle to provide read data (for loads) and an error indicator. The response is guaranteed to come in the same order as the requests were granted. The error signal is only valid when response valid is asserted.\n\nThe LSU never issues a new request before the previous one has been granted, but it may have multiple outstanding requests (up to two, for misaligned accesses). When multiple requests are outstanding, the memory must return responses in order.\n\n## 4. Aligned Access Behavior\n\nWhen the ID/EX stage issues a load or store and the address is naturally aligned to the access size (word‑aligned for words, half‑word‑aligned for half‑words, any alignment for bytes), the LSU performs a single memory transaction:\n\n- The request is issued with the address, byte enables, and write data (for stores). \n- The LSU waits for grant, then for the response. \n- The response is captured and, for loads, the read data is aligned and sign‑extended according to the access type and byte offset. \n- The load data (if applicable) and the transaction completion signal are made available to the ID/EX stage. \n\n## 5. Misaligned Access Behavior\n\nIf the address is misaligned for the access size (word with offset ≠ 0, half‑word with offset = 3), the LSU splits the operation into two separate word‑aligned memory transactions:\n\n1. **First transaction** – Uses the original address, but with byte enables that cover only the bytes from the original address upwards to the next word boundary. For stores, write data is rotated accordingly. \n2. **Second transaction** – Uses the address incremented to the next word boundary, with byte enables covering the remaining bytes of the original access. The write data for the second part is again rotated appropriately.\n\nThe LSU ensures that for loads, the first‑returned read data is stored in an internal register, and the final load result is assembled from the two responses. For stores, both transactions are issued and the responses (including any errors) are combined.\n\nThe ID/EX stage is notified that a second address is needed by an address increment request signal. The ID/EX stage must provide an updated address (typically by adding 4 to the original) on the next cycle. The LSU drives the word‑aligned version of this address for the second transaction.\n\n**Error handling for misaligned accesses:** \nIf an error (either bus error or physical memory protection [PMP] error) is detected on the first transaction, the second transaction is still issued and completed. However, the response of the second transaction is ignored and does not affect the final error condition. The final error for the whole operation is based solely on the first transaction’s error (or on any error that occurs on the first part of the split access). The address stored for trap reporting (mtval) is the address of the failing part.\n\n## 6. Error and Exception Handling\n\nThe LSU reports two kinds of errors:\n\n- **Bus errors** – Indicated by the memory side during the response phase (`data_err_i` asserted with `data_rvalid_i`). \n- **PMP errors** – Indicated during the address phase of a request (`data_pmp_err_i`). A PMP error is considered valid for the address phase being initiated, and it prevents the external request from being accepted by the memory (no grant will be sent for that request).\n\nWhen an error is detected:\n\n- For a load, the error is reported immediately when the response valid signal arrives (or when a PMP error is latched). The load data is not used. \n- For a store, the error is reported when the response valid arrives (or when a PMP error is latched). The store is considered to have failed even if no data returns. \n- The LSU drives separate load and store error signals to the core’s exception logic, active only when the response is valid. \n- The last transaction address is saved for use as the trap value (`mtval`). This address is not updated if an error occurs, so that the failing address is retained.\n\nThe LSU does **not** abort a pending second transaction if the first one errors. It waits for the second transaction to finish (ignoring its response) before returning to the idle state and accepting a new request.\n\n## 7. Data Alignment and Sign Extension\n\n### 7.1 Load Data\n\nWhen the memory returns read data, the LSU must produce a correctly aligned and sign‑extended value for the ID/EX stage:\n\n- **Byte load:** The byte at the original address is extracted. If sign extension is enabled, the most significant bit of that byte is propagated to bits 31:8; otherwise zeros are filled. \n- **Half‑word load:** The two bytes at the original address are extracted. The half‑word is placed in the least significant 16 bits of the result, and extension is performed based on bit 15 (sign) or zero. \n- **Word load:** All four bytes are taken, with the correct byte ordering to account for the original misalignment. For example, if the first access returned the high bytes and the second the low bytes, the LSU combines them appropriately. No sign extension is applied to words.\n\nThe alignment and extension logic uses the byte‑offset information stored from the original request, not the current address during the second part.\n\n### 7.2 Store Data\n\nWrite data is rotated such that the least significant byte of the register data ends up at the correct byte lane of the memory word. Rotations are performed based on the lower two bits of the address, separately for each part of a misaligned access. Byte enables are set to select only the bytes that belong to the original store operation.\n\n## 8. Interaction with the ID/EX Stage\n\nThe LSU receives requests from the ID/EX stage and stalls that stage until the transaction is completed:\n\n- **Request acceptance:** A new load or store is signalled by a request signal along with the address, type, write‑enable, write data, and sign‑extension flag. The LSU asserts a “done” indication as soon as it knows the transaction will complete (i.e., when the final grant is obtained for the last part of a misaligned access, or when grant and response are received for a single transaction). \n- **Response valid:** A separate valid signal is pulsed when the final load data (or a write acknowledgment) is ready. For loads, this valid signal is accompanied by the data. \n- **Misaligned address request:** The LSU may ask the ID/EX stage to increment the current address by 4 for the second part of a misaligned access. This request is active only when needed.\n\nThe pipeline is stalled until the response valid is received (or an error is reported). The LSU ensures that no new request is accepted while a previous transaction is still pending.\n\n## 9. Performance Monitoring\n\nThe LSU provides two performance counter events:\n\n- **Load event:** Pulses each time a load transaction is initiated (including both parts of a misaligned load). \n- **Store event:** Pulses each time a store transaction is initiated (including both parts of a misaligned store).\n\n## 10. Busy Indication\n\nThe LSU indicates when it is busy (i.e., not in the idle state). This signal can be used by the core to determine whether the pipeline can be safely stalled or if a new instruction can be issued.\n\n## 11. State Machine Behavior\n\nInternally, the LSU implements a finite state machine with the following logical phases:\n\n- **Idle:** Waiting for a new request from the ID/EX stage. \n- **First request pending:** A request has been issued but not yet granted (or granted and waiting for response). For misaligned accesses, this phase may be subdivided into waiting for the first grant, first response, second grant, second response. \n- **Second request pending:** Only during misaligned accesses, after the first response is received but before the second request is granted (or second response is received). \n- **Completion:** The LSU returns to idle once all response(s) have been received and the results have been forwarded to the ID/EX stage.\n\nThe LSU never enters a state where it loses track of outstanding requests. It always completes every transaction it started before accepting a new one.\n\n## 12. Global Assumptions and Constraints\n\n- The memory system must respect the protocol (grant order, in‑order responses). \n- PMP errors are signalled during the address phase; they prevent any subsequent grant. The LSU treats a PMP error as an immediate error for that address phase. \n- The address output is always word‑aligned. The byte enables and data rotation handle the byte‑level granularity. \n- The LSU does not modify addresses after an error on the first part of a misaligned access; the second part is still performed but its response is discarded. \n- Inputs for instruction validity and illegal instruction flags are provided only for assertion purposes and do not affect functional behavior.\n\n---\n\n*This specification defines the expected behavior of the Load‑Store Unit. The implementation must adhere to these behavioral requirements, but the precise logic used (state encoding, pipeline registers, etc.) is left to the designer.*", "commit_id": "5bcacb876d19c47e1b1461c6fd5b7d568485636b", "timestamp": "2020-05-05T08:26:57+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "15ab023e25469086988165ff49c8ef9b4c8bc81d", "pr_title": "[rtl] Stop regfile writeback for load errors", "pr_body": "- A data or PMP error should stop the register file from being updated\r\n- Fixes #832\r\n\r\nSigned-off-by: Tom Roberts ", "issue_title": "PMP load error qualifies register writeback", "issue_body": "Hi,\r\nI encountered this situation when running some pmp tests on Ibex:\r\n![Screenshot from 2020-04-30 16-52-47](https://user-images.githubusercontent.com/16736281/80769870-68584700-8b03-11ea-8f60-089f23606a27.png)\r\nThe instruction at `PC=0x80002250` is an `lb` instruction that tries to access the address `0x800148e4`. One cycle after this instruction reaches the decode stage, it causes a PMP fault and `pmp_err_q` goes high for two cycles, but `lsu_rdata_valid_o` still goes high to `1'b1` even though the DMEM interface has not sent out a request at all, triggering an incorrect register writeback of of `XXXX_XXXX`.", "commit_message": "[rtl] Stop regfile writeback for load errors\n\n- A data or PMP error should stop the register file from being updated\n- Fixes #832\n\nSigned-off-by: Tom Roberts ", "fix_patch": "diff --git a/rtl/ibex_load_store_unit.sv b/rtl/ibex_load_store_unit.sv\nindex ec69a3a033..219dba5b7c 100644\n--- a/rtl/ibex_load_store_unit.sv\n+++ b/rtl/ibex_load_store_unit.sv\n@@ -476,7 +476,7 @@ module ibex_load_store_unit\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+ assign lsu_rdata_valid_o = (ls_fsm_cs == IDLE) & data_rvalid_i & ~data_or_pmp_err & ~data_we_q;\n \n // output to register file\n assign lsu_rdata_o = data_rdata_ext;\n", "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 = (ls_fsm_cs == IDLE) & data_rvalid_i & ~data_or_pmp_err & ~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", "selected_doc_paths": ["doc/load_store_unit.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 854, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# ibex_controller Design Specification\n\n## Overview\n\nThe controller is the central finite state machine of the Ibex processor. It governs the overall execution flow: fetching instructions, dispatching them to the decode/execute stage, handling pipeline stalls, and managing transitions caused by exceptions, interrupts, debug requests, and special instructions (WFI, MRET, DRET, etc.).\n\nThe controller interacts with the instruction fetch (IF) stage, the instruction decode/execute (ID/EX) stage, the load‑store unit (LSU), and the CSR block. It decides when to:\n\n- Start/resume instruction fetching.\n- Set the program counter (PC) to a new target (branch, jump, exception handler, debug handler, return from trap).\n- Flush or clear the instruction in the IF–ID pipeline register.\n- Save or restore architectural state (CSRs) upon trap entry or return.\n- Assert `ctrl_busy` to indicate the core is actively processing.\n\n## Controller Finite State Machine\n\nThe controller implements a state machine with the following conceptual states. The exact encoding is implementation‑specific, but the behavioral transitions are described below.\n\n### Reset and Boot\n\nUpon reset, the controller waits for an external `fetch_enable` signal. While waiting, it does **not** request instruction fetches and holds the PC at the boot address. Once `fetch_enable` is asserted, it performs a first PC set to the boot address and transitions to a state that initiates the first instruction fetch.\n\n### Normal Execution (DECODE)\n\nAfter the first fetch completes, the controller enters the main execution state. In this state:\n\n- The ID/EX stage is allowed to execute instructions (`controller_run` is asserted).\n- The controller monitors stall signals from the ID/EX stage and the writeback stage (if present). Stalls occur due to multi‑cycle instructions (e.g., loads, stores, multiplies, or memory waits).\n- If the current instruction completes without stalls, the controller signals the IF stage that it is ready to accept the next instruction.\n- The controller also monitors special conditions that require a deviation from normal flow: exceptions (`ecall`, `ebreak`, illegal instruction, instruction fetch error), pipeline‑flushing CSR writes, and explicit trap instructions (`mret`, `dret`, `wfi`).\n\n#### Branch and Jump Handling\n\nWhen a branch or jump instruction is executed and the branch condition is taken (or the jump is unconditional), the controller immediately sets the PC to the target address. This occurs in the same cycle as the instruction is decoded, provided no other special request (exception, etc.) is pending. The controller also asserts performance counter signals for taken branches and jumps.\n\n#### Interrupts and Debug While Executing\n\nWhile in the execution state, if an interrupt or debug request becomes pending, the controller does **not** immediately redirect the PC. Instead it waits until the current instruction finishes (i.e., no stall and no special request is present). During that waiting time, it stalls the IF stage (prevents a new instruction from being fetched) to avoid speculative execution. Once the current instruction completes, it transitions to the interrupt‑taken or debug‑taken state accordingly.\n\n### Pipeline Flush (FLUSH)\n\nWhen any event that requires the pipeline to be emptied and a new PC to be set occurs (exception, special instruction, pipeline‑flushing CSR write), the controller enters the flush state. In this state:\n\n- The IF stage is stalled (`halt_if` asserted).\n- The ID/EX stage is flushed (the valid bit in the IF–ID register is cleared).\n- Based on the cause of the flush, the controller:\n - For **exceptions**: Sets PC to the exception handler address (either `mtvec` or debug exception address if in debug mode). Saves the current PC into `mepc` (or `dpc` for debug exceptions) and the cause into `mcause`. Also may write `mtval` with relevant information (instruction address, faulting instruction, or data address). Flush is performed even for LSU‑generated exceptions that are detected in the writeback stage.\n - For **`mret` instruction**: Re‑establishes the PC from `mepc`, restores `mstatus.MIE` from `mstatus.MPIE`, and returns to the privilege mode stored in `mstatus.MPP`. If the current mode was NMI (`nmi_mode`), that mode is cleared upon `mret`.\n - For **`dret` instruction**: Re‑establishes the PC from `dpc`, clears debug mode (`debug_mode`), and restores the privilege mode from `dcsr.prv`.\n - For **`wfi` instruction**: Transitions to the sleep state (see below).\n - For **CSR pipeline flush** (caused by certain CSR writes)**: If an interrupt is pending, transitions to interrupt‑taken state instead of returning directly to execution.\n- After handling the flush, the controller returns to the execution state.\n\n### Interrupt Taken (IRQ_TAKEN)\n\nWhen an interrupt is to be taken, the controller sets the PC to the address computed as `mtvec` base plus 4× interrupt ID (vectored mode). It also:\n\n- Saves the current PC into `mepc` (from the IF stage).\n- Saves the cause into `mcause` (interrupt bit set, with the appropriate exception code).\n- Saves `mstatus.MIE` into `mstatus.MPIE` and then clears `mstatus.MIE` (disables further interrupts).\n- Sets the privilege mode to machine mode.\n- If the interrupt is a non‑maskable interrupt (NMI), the controller enters NMI mode (`nmi_mode`). While in NMI mode, further interrupts (even NMI) are ignored.\n- The interrupt priorities (highest first) are: NMI, fast interrupts (by descending ID), external interrupt, software interrupt, timer interrupt. Only one interrupt is taken per transition (the highest priority pending).\n- After setting the PC, the controller returns to the execution state.\n\n### Debug Taken (DBG_TAKEN_IF and DBG_TAKEN_ID)\n\nDebug mode can be entered due to:\n\n- An external debug request (`debug_req`).\n- Single‑step mode (`dcsr.step` = 1) after executing one instruction.\n- A trigger match (hardware breakpoint) when enabled.\n\nWhen a debug entry condition is detected during normal execution (DECODE) or during a flush, the controller transitions to debug‑taken states:\n\n- **DBG_TAKEN_IF**: Used for debug entry on a debug request, single‑step, or trigger match. It saves the PC from the IF stage into `dpc`, sets the PC to the debug halt address (`DmHaltAddr`), and enters debug mode. The cause is recorded in `dcsr.cause`.\n- **DBG_TAKEN_ID**: Used when an `ebreak` instruction should enter debug mode (either because the core is already in debug mode, or because `dcsr.ebreakm`/`dcsr.ebreaku` are set). It saves the PC from the ID stage (the address of the `ebreak` itself) into `dpc` and updates `dcsr` accordingly. If already in debug mode, `dpc` and `dcsr` are **not** updated (the `ebreak` in debug mode re‑enters debug mode but does not modify those registers).\n\nAfter entering debug mode, the controller returns to the execution state. While in debug mode, all interrupts (including NMI) are ignored, and debug requests are handled (but already in debug mode, no re‑entry occurs).\n\n### Sleep (WAIT_SLEEP and SLEEP)\n\nWhen a `wfi` instruction is executed, the controller enters the sleep state. In this state:\n\n- The core is not busy (`ctrl_busy` deasserted) to allow clock gating.\n- Instruction fetching is stopped.\n- The pipeline is flushed.\n- The core remains in sleep until an interrupt (including NMI) or a debug request arrives. Additionally, if the core is already in debug mode or single‑step mode, it immediately exits sleep (WFI behaves as a NOP).\n\nUpon wake‑up, it transitions back to the fetch state to restart instruction fetching.\n\n## Special Instruction and Exception Handling Summary\n\nThe controller recognises the following special events, which are qualified by a valid instruction in the ID stage:\n\n### Exceptions\n- **Illegal instruction**: Any instruction that the decoder reports as illegal, plus any `dret` executed outside debug mode, plus any `mret` or `wfi` executed in user mode when `mstatus.TW` is set.\n- **ECALL**: Environment call from machine or user mode.\n- **EBREAK**: Breakpoint instruction. If the core is in debug mode or if the appropriate `dcsr.ebreak*` bit is set, it enters debug mode via DBG_TAKEN_ID. Otherwise, it generates a breakpoint exception.\n- **Instruction access fault**: If the fetched instruction encountered an error (e.g., bus error).\n- **Load/Store access fault**: Errors reported by the LSU.\n\nWhen an exception is taken, the controller saves the PC of the faulting instruction into `mepc` (or `dpc` if in debug mode). For load/store errors, if a writeback stage is present, the PC is saved from the writeback stage; otherwise, from the ID stage.\n\n### Special Instructions\n- **MRET**: Returns from machine‑mode trap. Restores PC from `mepc`, restores `mstatus.MIE`, and changes privilege mode.\n- **DRET**: Returns from debug mode. Restores PC from `dpc`, clears debug mode, and restores privilege mode.\n- **WFI**: Waits for interrupt; puts core into sleep state.\n- **CSR‑related pipeline flush**: Certain CSR writes (e.g., to `mtvec`, `mepc`, `mstatus`) require a pipeline flush. The controller treats them like a flush, and if an interrupt is pending, it immediately takes the interrupt.\n\n## Pipeline Control\n\nThe controller provides two main control signals to the pipeline:\n\n- **IF‑stage stall (`halt_if`)**: When asserted, the IF stage does **not** advance to the next instruction (the current instruction in the IF–ID register remains valid). This is used during flush, interrupt/debug entry waiting, and sleep.\n- **ID‑stage flush (`flush_id`)**: When asserted, the valid bit of the IF–ID register is cleared, effectively discarding the instruction that was in the ID stage. This is used during flush and debug entry.\n\nAdditionally, a combined `instr_valid_clear` signal informs the IF stage whether to clear the instruction valid bit after a stall or flush.\n\n## CSR Save/Restore Control\n\nThe controller generates strobes to the CSR block to save or restore architectural state:\n\n- `csr_save_if`: Save PC from IF stage (for exception/interrupt/debug entry).\n- `csr_save_id`: Save PC from ID stage (for EBREAK in debug entry, or for exceptions when writeback stage not present).\n- `csr_save_wb`: Save PC from writeback stage (for LSU exceptions when writeback stage present).\n- `csr_save_cause`: Save the exception/interrupt cause into `mcause`.\n- `csr_restore_mret_id`: Restore state from `mepc`, `mstatus` on MRET.\n- `csr_restore_dret_id`: Restore state from `dpc`, `dcsr` on DRET.\n- `debug_csr_save`: Save debug cause into `dcsr` on debug entry.\n\n## Performance Monitoring\n\nThe controller outputs pulse signals for:\n- **Taken branch**: Asserted when a branch instruction is taken.\n- **Jump**: Asserted when a jump instruction (JAL, JALR) is executed.\n\n## Reset Behaviour\n\nUpon reset, the controller initialises to a state where:\n- Debug mode is cleared.\n- NMI mode is cleared.\n- All saved exception/debug‑related flip‑flops (load/store error, exception request, illegal instruction) are cleared.\n- The first action is to wait for `fetch_enable` before setting the boot PC.\n\n## Summary of Inputs/Outputs (Conceptual)\n\nThe controller receives:\n- Decoder outputs indicating instruction type (illegal, ecall, mret, dret, wfi, ebreak, CSR flush).\n- IF–ID pipeline valid/busy signals and instruction data.\n- LSU error signals (load/store access fault).\n- Branch/jump taken signals.\n- Interrupt lines (NMI, fast, external, timer, software) and global interrupt enable (`mstatus.MIE`).\n- Debug request, single‑step, trigger match, and `ebreak` configuration bits.\n- Stalls from ID/EX and writeback stages.\n- Privilege mode and `mstatus.TW` for user‑mode checks.\n\nThe controller outputs:\n- Instruction fetch request and PC set commands (with mux selectors for boot, normal, exception, debug, return).\n- Pipeline stall and flush signals.\n- CSR save/restore strobes.\n- `mtval` value (exception‑specific information).\n- Core busy indicator.\n- Performance signals for branches and jumps.\n- Debug mode and NMI mode status.\n\n## Behavioural Constraints\n\n- The controller must ensure that only one exception or interrupt is taken per transition. Priority is determined by the RISC‑V specification (interrupts over exceptions when both are pending, and strict ordering among interrupt sources).\n- The controller must not introduce combinational loops via stall signals; it uses a separate `halt_if` signal to avoid cycles.\n- When the writeback stage is present, the controller must handle LSU exceptions that are detected one cycle later (in the writeback stage) by saving the PC from that stage.\n- The controller must correctly handle nested debug entry: an `ebreak` in debug mode re‑enters debug mode without updating `dpc` or `dcsr`.\n- The controller must ignore interrupts while in debug mode or NMI mode.\n- The controller must clear internal exception/debug request flip‑flops once the event is handled to prevent spurious re‑entries.", "commit_id": "863fb56eb166dc8d6e25f4e98b7319f0c7088564", "timestamp": "2020-05-15T10:13:21+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "8934267c78a991ac71f7cbd4eeb27668837f8bf7", "pr_title": "[rtl] Fix instr_valid_i exception issue", "pr_body": "- The controller state machine could only progress to FLUSH to handle an\r\n exception if instr_valid_i was set\r\n- When the exception comes from a load/store in the Writeback stage, and\r\n no new instruction has been driven into the ID stage, this could cause\r\n exception to be missed\r\n- The instr_valid_i qualification is therefore removed from the state\r\n machine as all relevant signals inside that if block are already\r\n qualified by instr_valid_i anyway\r\n- Fixes #849\r\n\r\nSigned-off-by: Tom Roberts ", "issue_title": "PMP store fault does not jump to exception handler", "issue_body": "Hi Tom,\r\nI ran into this situation when debugging a PMP test (with icache disabled):\r\n![Screenshot from 2020-05-07 15-46-15](https://user-images.githubusercontent.com/16736281/81351754-e4a9d780-9079-11ea-87de-f571cd0a8829.png)\r\nThe instruction at `PC=0x8001fb0a` (under the cursor) is a store instruction to address `0x80031034`, which the PMP detection logic correctly flags as an error for not matching any pmp_cfg CSR in user-mode and prevents a request from being sent to the memory.\r\nDuring this, the controller is in the `DECODE` state, but it does not actually detect `special_req_all` going high because `instr_valid_i` has already gone low by the time it reflects the rising `exc_req_lsu` wire - as a result the core pretends everything is okay and goes on to execute the instruction at the next PC.\r\nI suspect this has to do with how `instr_valid_id_d/q` are set in the IF stage, as they appear to be dropping one cycle too early - additionally, when I enabled the icache and reran this test, this issue did not appear, e.g. `instr_valid_i` in the controller went high at the same time as `special_req_all` to qualify it due to `instr_valid_id_d/q` staying high for an additional cycle:\r\n![Screenshot from 2020-05-07 16-10-02](https://user-images.githubusercontent.com/16736281/81353183-428bee80-907d-11ea-8a52-a78fe0a96360.png)\r\nWe can see that with the icache, `instr_valid_id_d/q` stay high for extra cycles, allowing the controller to correctly qualify the PMP exception and then start fetching the address of the exception handler (`0x80001400`).", "commit_message": "[rtl] Fix instr_valid_i exception issue\n\n- The controller state machine could only progress to FLUSH to handle an\n exception if instr_valid_i was set\n- When the exception comes from a load/store in the Writeback stage, and\n no new instruction has been driven into the ID stage, this could cause\n exception to be missed\n- The instr_valid_i qualification is therefore removed from the state\n machine as all relevant signals inside that if block are already\n qualified by instr_valid_i anyway\n- Fixes #849\n\nSigned-off-by: Tom Roberts ", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex a256a33a34..f73dc2004b 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -182,12 +182,14 @@ module ibex_controller #(\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+ // All terms in this expression are qualified by instr_valid_i\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+ // 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@@ -205,10 +207,13 @@ module ibex_controller #(\n // request reasons that are relevant to a branch.\n \n // generic special request signal, applies to all instructions\n+ // All terms in this expression 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 assign special_req_all = mret_insn | dret_insn | wfi_insn | csr_pipe_flush |\n exc_req_d | exc_req_lsu;\n \n // special request that can specifically occur during branch instructions\n+ // All terms in this expression are qualified by instr_valid_i\n assign special_req_branch = instr_fetch_err & (ctrl_fsm_cs != FLUSH);\n \n `ASSERT(SpecialReqBranchGivesSpecialReqAll,\n@@ -399,31 +404,29 @@ module ibex_controller #(\n // which helps timing.\n pc_mux_o = PC_JUMP;\n \n- if (instr_valid_i) begin\n \n- // get ready for special instructions, exceptions, pipeline flushes\n- if (special_req_all) 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- end\n+ // Get ready for special instructions, exceptions, pipeline flushes\n+ if (special_req_all) 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+ end\n \n- if ((branch_set_i || jump_set_i) && ~special_req_branch) begin\n- pc_set_o = 1'b1;\n+ if ((branch_set_i || jump_set_i) && ~special_req_branch) begin\n+ pc_set_o = 1'b1;\n \n- perf_tbranch_o = branch_set_i;\n- perf_jump_o = jump_set_i;\n- end\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+ // 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 \n if (!stall && !special_req_all) begin\n if (enter_debug_mode) begin\n", "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\nmodule ibex_controller #(\n parameter bit WritebackStage = 0\n ) (\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\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 instr_fetch_err_plus2_i, // instr from IF-ID reg error is x32\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 output logic controller_run_o, // Controller is in standard instruction\n // run mode\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 output logic wb_exception_o, // Instruction in WB taking an exception\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 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_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 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 input logic csr_mstatus_tw_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\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_all;\n logic special_req_branch;\n logic enter_debug_mode;\n logic ebreak_into_debug;\n logic handle_irq;\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, 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 // All terms in this expression are qualified by instr_valid_i\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 // 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\n // special requests: special instructions, pipeline flushes, exceptions...\n\n // To avoid creating a path from data_err_i -> instr_req_o and to help timing the below\n // special_req_all has a version that only applies to branches. For a branch the controller needs\n // to set pc_set_o but only if there is no special request. If the generic special_req_all signal\n // is used then a variety of signals that will never cause a special request during a branch\n // instruction end up factored into pc_set_o. The special_req_branch only considers the special\n // request reasons that are relevant to a branch.\n\n // generic special request signal, applies to all instructions\n // All terms in this expression 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 assign special_req_all = mret_insn | dret_insn | wfi_insn | csr_pipe_flush |\n exc_req_d | exc_req_lsu;\n\n // special request that can specifically occur during branch instructions\n // All terms in this expression are qualified by instr_valid_i\n assign special_req_branch = instr_fetch_err & (ctrl_fsm_cs != FLUSH);\n\n `ASSERT(SpecialReqBranchGivesSpecialReqAll,\n special_req_branch |-> special_req_all)\n\n `ASSERT(SpecialReqAllGivesSpecialReqBranchIfBranchInst,\n special_req_all && (branch_set_i || jump_set_i) |-> special_req_branch)\n\n if (WritebackStage) begin\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\n assign wb_exception_o = 1'b0;\n end\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 // Also enter debug mode on a trigger match (hardware breakpoint)\n assign enter_debug_mode = (debug_req_i | (debug_single_step_i & instr_valid_i) |\n 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 // Interrupts including NMI are ignored,\n // - while in debug mode [Debug Spec v0.13.2, p.39],\n // - while in NMI mode (nested NMIs are not supported, NMI has highest priority and\n // cannot be interrupted by regular interrupts).\n assign handle_irq = ~debug_mode_q & ~nmi_mode_q &\n (irq_nm_i | (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 (irqs_i.irq_fast[14]) mfip_id = 4'd14;\n else if (irqs_i.irq_fast[13]) mfip_id = 4'd13;\n else if (irqs_i.irq_fast[12]) mfip_id = 4'd12;\n else if (irqs_i.irq_fast[11]) mfip_id = 4'd11;\n else if (irqs_i.irq_fast[10]) mfip_id = 4'd10;\n else if (irqs_i.irq_fast[ 9]) mfip_id = 4'd9;\n else if (irqs_i.irq_fast[ 8]) mfip_id = 4'd8;\n else if (irqs_i.irq_fast[ 7]) mfip_id = 4'd7;\n else if (irqs_i.irq_fast[ 6]) mfip_id = 4'd6;\n else if (irqs_i.irq_fast[ 5]) mfip_id = 4'd5;\n else if (irqs_i.irq_fast[ 5]) mfip_id = 4'd5;\n else if (irqs_i.irq_fast[ 4]) mfip_id = 4'd4;\n else if (irqs_i.irq_fast[ 3]) mfip_id = 4'd3;\n else if (irqs_i.irq_fast[ 2]) mfip_id = 4'd2;\n else if (irqs_i.irq_fast[ 1]) mfip_id = 4'd1;\n else mfip_id = 4'd0;\n end\n\n assign unused_irq_timer = irqs_i.irq_timer;\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\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\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 controller_run_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 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 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_all) 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 end\n\n if ((branch_set_i || jump_set_i) && ~special_req_branch) begin\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\n if (!stall && !special_req_all) 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 // 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 (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 EXC_CAUSE_IRQ_FAST_0 = {1'b1, 5'd16}\n exc_cause_o = exc_cause_e'({2'b11, mfip_id});\n end else if (irqs_i.irq_external) begin\n exc_cause_o = EXC_CAUSE_IRQ_EXTERNAL_M;\n end else if (irqs_i.irq_software) begin\n exc_cause_o = EXC_CAUSE_IRQ_SOFTWARE_M;\n end else begin // irqs_i.irq_timer\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 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 if (debug_single_step_i || debug_req_i || trigger_match_i) begin\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 if (trigger_match_i) begin\n debug_cause_o = DBG_CAUSE_TRIGGER;\n end else 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 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\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 // 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 = instr_fetch_err_plus2_i ? (pc_id_i + 32'd2) : 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 begin // load_err_q\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 csr_restore_dret_id_o = 1'b1;\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 = RESET;\n end\n endcase\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;\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\n ////////////////\n // Assertions //\n ////////////////\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\nendmodule\n", "selected_doc_paths": ["doc/exception_interrupts.rst", "doc/debug.rst", "doc/pipeline_details.rst", "doc/instruction_decode_execute.rst", "doc/cs_registers.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 836, "lang": "sv", "rtl_files": ["rtl/ibex_id_stage.sv"], "spec": "# Behavioral Design Specification: Instruction Decode and Execute Stage (ID/EX)\n\n## 1. Overview\n\nThe Instruction Decode and Execute (ID/EX) stage is the core execution engine of the processor. It receives instruction data from the instruction fetch stage, decodes the instruction, reads the register file, performs the required operation (possibly over multiple cycles), writes results back to the register file, and communicates control signals to the program counter, load-store unit, CSR block, and other execution units.\n\nThe stage is responsible for:\n\n- Decoding compressed or uncompressed instructions into control signals.\n- Reading source register operands from the register file.\n- Forwarding data from writeback (if a third pipeline stage exists) to resolve data hazards.\n- Stalling the pipeline for multi-cycle operations (load/store, multiply, divide, branches, jumps, multi-cycle ALU).\n- Handling taken branches and jumps by signaling a new program counter.\n- Detecting illegal instructions, exception conditions, and debug triggers.\n- Coordinating with the controller to handle interrupts, exceptions, and debug entry.\n- Generating performance counter events.\n\n## 2. Interfaces\n\nThe ID/EX stage communicates with:\n\n- **Instruction Fetch (IF) stage** – receives instruction data, compressed flag, and fetch error signals; outputs handshake signals to advance the pipeline and requests to flush the IF-ID pipeline register.\n- **Controller** – receives decoder outputs (illegal instruction, ECALL, MRET, DRET, WFI, EBREAK, branch/jump set) and provides control signals for PC updates, exception handling, interrupt handling, and debug entry.\n- **Register File** – reads two source addresses with data, writes one destination address with data. Forwarding paths from writeback stage (if present) feed read data.\n- **Arithmetic Logic Unit (ALU)** – supplies operand A, operand B, and operation code.\n- **Branch Target ALU** (optional) – supplies operand A and operand B for branch target calculation.\n- **Multiplier/Divider** – provides enable signals, operation, signed mode, operands, and a ready indication.\n- **Load-Store Unit (LSU)** – provides request, write enable, type, sign extension, write data; receives status signals (valid, busy, error, address increment request, last address).\n- **CSR Block** – provides read data, access enable, operation, and save/restore signals.\n- **Writeback Stage** (optional) – outputs instruction type, writeback enable, and receives ready signal and forwarding information.\n- **Performance Counters** – outputs events for jumps, branches, taken branches, memory waits, multiply waits, divide waits, instruction done, compressed instruction done.\n\n## 3. Functional Description\n\n### 3.1 Instruction Decode\n\nThe stage decodes one instruction at a time. Instructions enter in one of two forms:\n\n- **Uncompressed** (32‑bit) – the full instruction from the IF-ID pipeline.\n- **Compressed** (16‑bit) – the compressed instruction is expanded to its 32‑bit uncompressed representation before decoding.\n\nDecoding determines:\n\n- The ALU operation (integer compute, branch comparison, CSRR access, etc.).\n- Immediate values (I‑type, S‑type, B‑type, U‑type, J‑type, Z‑type for CSR).\n- Register file read addresses and write address.\n- Whether the instruction is a load, store, multiply, divide, jump, branch, CSR access, or fence.\n- Whether the instruction is an illegal instruction, ECALL, EBREAK, MRET, DRET, or WFI.\n- For multi-cycle instructions, the number of cycles required.\n\n### 3.2 Register File Access\n\nThe stage reads up to two source registers from the register file via dedicated read ports. If the writeback stage exists, data forwarding resolves read-after-write hazards: a read that matches the write address of a writeback instruction (other than a load) receives the forwarded write data. Load results are not forwarded; a load will stall until the load data is available.\n\nWrite enable and write data are driven to the register file only when the instruction is executing and no illegal CSR access is detected.\n\n### 3.3 Operand Selection\n\nTwo operand paths are provided:\n\n- **Main ALU operands** – operand A is chosen from register file read data, forwarded last LSU address (for misaligned access), current PC, or immediate. Operand B is chosen from an immediate (I, S, B, U, J, or PC increment) or register file read data.\n- **Branch Target ALU operands** (optional) – operand A from register or PC, operand B from immediate (I, B, J, or PC increment). This dedicated ALU computes the branch target in parallel with condition evaluation in the main ALU.\n\nThe selection of the immediate type is derived from the instruction decode.\n\n### 3.4 Multi‑Cycle Instruction State Machine\n\nThe stage contains a two‑state state machine: **FIRST_CYCLE** and **MULTI_CYCLE**.\n\n- **FIRST_CYCLE**: A new instruction is being executed. For single‑cycle instructions the stage completes in this state. For multi‑cycle instructions (load/store, multiply, divide, taken branch, jump, multi‑cycle ALU) the state transitions to MULTI_CYCLE.\n- **MULTI_CYCLE**: The instruction continues execution. The stage remains in this state until the operation is finished and the writeback stage is ready (if present) or until the result is valid.\n\nThe state machine is only active when the instruction is executing (no pending exception, no fetch error, controller is running).\n\n### 3.5 Pipeline Stalls\n\nThe stage stalls (holds the current instruction) for the following reasons:\n\n- **Load/Store stall**: At least one cycle is required to send a request to the LSU and wait for a response (read data or store completion). For misaligned accesses, two requests are made and the stall extends accordingly. If the writeback stage is present, additional stalls occur when the LSU is busy or when an outstanding memory access from a previous instruction must be resolved for precise exceptions.\n- **Multiply/Divide stall**: The multiplier/divider takes multiple cycles (1–37 depending on configuration and operand). The stall persists until the result is valid.\n- **Branch stall**: A taken branch in fixed‑time execution mode or when no branch target ALU is present stalls for one extra cycle (two cycles total) to compute the target. With branch target ALU and without fixed‑timing, a taken branch completes in one cycle.\n- **Jump stall**: Without a branch target ALU, a jump stalls for one cycle (two cycles total).\n- **Multi‑cycle ALU stall**: Some instructions (e.g., ternary operations) require an extra cycle.\n- **Load‑hazard stall** (with writeback stage): A load in writeback creates a hazard with reads in the ID/EX stage if the same register is read. The stage stalls until the load data is available.\n- **Writeback stall** (with writeback stage): If the writeback stage is not ready, the ID/EX stage stalls until it is ready, unless the instruction completes in the same cycle.\n\nA stall prevents the current instruction from advancing to the next stage (or writeback) and blocks a new instruction from entering the ID/EX stage.\n\n### 3.6 Branch and Jump Handling\n\n**Branches**: When a branch instruction is decoded, the condition is evaluated in the main ALU. If the branch is taken:\n\n- The branch set signal is asserted, causing the controller to redirect the PC.\n- If a branch target ALU is present, the target is computed in parallel; the branch completes in one cycle (unless fixed‑timing mode is active).\n- Without a branch target ALU, the target is computed in the main ALU in the next cycle, requiring a two‑cycle execution.\n\nIn fixed‑timing execution mode (DataIndTiming enabled), the branch decision is flopped and used in the second cycle to decide whether to take the branch, ensuring constant timing independent of the branch outcome.\n\n**Jumps**: Unconditional jumps (JAL, JALR) always redirect the PC. With a branch target ALU they complete in one cycle; without it they require two cycles. The jump set signal is provided to the controller.\n\n**Not‑taken branches**: Do not stall the pipeline; the stage proceeds immediately to the next instruction.\n\n### 3.7 Exception and Interrupt Handling\n\nExceptions (illegal instruction, instruction access fault, ECALL, EBREAK, etc.) are detected by the decoder or via the controller. When an exception occurs:\n\n- The controller saves the current PC (to `mepc`), saves `mstatus.MIE` to `mstatus.MPIE`, and changes the privilege mode.\n- The PC is set to the exception handler address (from `mtvec`).\n- Cause and trap value are recorded in CSR registers.\n\nInterrupts (including NMI) are taken if globally enabled and not masked. The controller evaluates pending interrupts and, if an interrupt is taken, saves state and vectors to the appropriate handler (vectored mode).\n\nThe stage provides signals to save CSR state (save IF, save ID, save WB, save cause) and to restore state on MRET/DRET.\n\n**Pipeline flush on CSR writes**: Writes to CSR addresses that affect interrupt enabling (`mstatus`, `mie`) or debug CSRs (`dcsr`, `dpc`, `dscratch0/1`) cause a pipeline flush to ensure the controller sees the new state immediately.\n\n### 3.8 Debug Operation\n\nThe stage supports entering Debug Mode on:\n\n- A debug request input (`debug_req_i`).\n- A single‑step instruction (when `debug_single_step_i` is set and not in Debug Mode).\n- An EBREAK instruction (if `debug_ebreakm_i` or `debug_ebreaku_i` are set).\n- A trigger match (`trigger_match_i`).\n\nWhen entering Debug Mode, the current PC is saved to `dpc` and a debug cause is recorded. The stage outputs `debug_mode_o`, `debug_cause_o`, and `debug_csr_save_o` to indicate the debug state and cause.\n\n### 3.9 Writeback Stage Interaction (Optional)\n\nIf the processor is configured with a third pipeline stage, the ID/EX stage:\n\n- Outputs an instruction type (`WB_INSTR_OTHER`, `WB_INSTR_LOAD`, `WB_INSTR_STORE`) and a writeback enable signal.\n- Waits for the writeback stage to be ready before completing the instruction.\n- Forwards load/store requests to the LSU; the LSU will indicate when the request is done (`lsu_req_done_i`). The instruction can then proceed to writeback.\n- Ensures that a memory access does not start if there is an outstanding memory access that could result in a precise exception.\n\n### 3.10 Performance Counters\n\nThe stage provides the following event outputs for performance monitoring:\n\n- `perf_jump_o`: Asserted when a jump instruction is executed.\n- `perf_branch_o`: Asserted when a branch instruction is executed (taken or not‑taken).\n- `perf_tbranch_o`: Asserted when a taken branch is executed.\n- `perf_dside_wait_o`: Asserted when an instruction in ID/EX is waiting for a memory access to finish.\n- `perf_mul_wait_o`: Asserted when the stage is stalled due to a multiply.\n- `perf_div_wait_o`: Asserted when the stage is stalled due to a division.\n- `instr_id_done_o`: Asserted when an instruction has completed in the ID/EX stage.\n- `instr_id_done_compressed_o`: Asserted when a compressed instruction has completed.\n\n## 4. Behavioral Timing and Sequencing\n\n- The stage expects instruction data, the compressed flag, and fetch error signals to be valid in the same cycle as `instr_valid_i`.\n- The instruction begins execution on the cycle after it is successfully captured (subject to stalls).\n- All ALU and CSR read operations are combinational; the results are available in the same cycle as the operands.\n- Multi-cycle operations are tracked by the internal state machine.\n- The stage outputs the next instruction request and PC set signals in the same cycle a jump or taken branch is resolved.\n- For load/store operations, the request is sent to the LSU and the stage stalls until the LSU completes (via `lsu_valid_i` for two‑stage, or a combination of signals with writeback stage).\n- The register file write occurs at the end of the last cycle of the instruction’s execution (for single‑cycle) or when the result is ready (for multi‑cycle).\n\n## 5. Reset and Initialization\n\nWhen reset is asserted:\n\n- The stage’s internal state machine is reset to the FIRST_CYCLE state.\n- All pipeline registers held within the stage are cleared.\n- The stage becomes ready to accept the next instruction as soon as `fetch_enable_i` is asserted.\n\n## 6. Configuration Parameters\n\nThe stage’s behavior depends on the following configuration parameters (through the module instantiation):\n\n- **RV32E**: When enabled, the register file contains 15 registers instead of 31.\n- **RV32M**: When enabled, multiply and divide instructions are supported.\n- **RV32B**: When enabled, bit manipulation instructions (Zbb, Zbs, Zbp, Zbt) are supported.\n- **DataIndTiming**: When enabled, branch execution takes a constant two cycles independent of branch condition (fixed‑time execution).\n- **BranchTargetALU**: When enabled, a dedicated branch target ALU computes branch/jump targets in parallel with condition evaluation.\n- **WritebackStage**: When enabled, a third pipeline stage exists. The ID/EX stage uses different stall logic, forwarding, and writeback handshake.\n\n## 7. Error and Exception Conditions\n\nThe stage must produce the following behaviors on error/exception:\n\n- **Illegal instruction**: When `illegal_insn_o` is asserted, the controller initiates an illegal instruction exception. The instruction is not executed.\n- **Illegal CSR access**: If a CSR access instruction is decoded but the access is illegal (e.g., wrong privilege level, unimplemented CSR), the instruction behaves as an illegal instruction (the write is suppressed).\n- **Instruction fetch error**: If `instr_fetch_err_i` is asserted with a valid instruction, the stage kills the instruction (it is not executed) and the controller handles the instruction access fault.\n- **Load/Store error**: When the LSU reports an error (`lsu_load_err_i` or `lsu_store_err_i`), the controller triggers a precise exception for the instruction that made the access.\n- **Misaligned access**: The LSU handles misaligned accesses by performing two aligned accesses. The ID/EX stage stalls appropriately and, if an error occurs on the first access, the second is still issued (though its result is ignored).\n\n## 8. Power and Clock Gating Considerations\n\nThe stage is clocked by `clk_i` and reset by `rst_ni`. The internal state machine only toggles when an instruction is being executed. When no instruction is valid or the core is sleeping (WFI), the stage remains idle and does not change state.\n\n(End of specification)", "commit_id": "439513ba68b57ace4e08365da7297caa215e9cf5", "timestamp": "2020-05-04T07:29:00+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "5bcacb876d19c47e1b1461c6fd5b7d568485636b", "pr_title": "[rtl] Fix jump signal stuck high during stall", "pr_body": "- Stalls due to preceding memory accesses in the WB stage shouldn't\r\n cause the jump signal to remain high.\r\n- The jump signal being stuck high causes repeated memory accesses to\r\n the same address, and unnecessary stalling.\r\n- Fixes lowRISC/opentitan#2099\r\n\r\nSigned-off-by: Tom Roberts ", "issue_title": "[dv] Improve instruction trace around faulting instructions", "issue_body": "When an executed instruction generates a fault we suppress its destination register write. On the RVFI interface this mean setting the write register index to 0. On the instruction trace this results in seeing `x0` as the destination register, rather than the actual destination register. This can be confusing. We should improve our trace output to include the actual destination register in the printed instruction along with a note the write is suppressed due to a trap.\r\n\r\nSee https://github.com/lowRISC/opentitan/issues/13134 for an example of this issue.", "commit_message": "[rtl] Fix jump signal stuck high during stall\n\n- Stalls due to preceding memory accesses in the WB stage shouldn't\n cause the jump signal to remain high.\n- The jump signal being stuck high causes repeated memory accesses to\n the same address, and unnecessary stalling.\n- Fixes lowRISC/opentitan#2099\n\nSigned-off-by: Tom Roberts ", "fix_patch": "diff --git a/rtl/ibex_id_stage.sv b/rtl/ibex_id_stage.sv\nindex 57ba30678e..5055859dc3 100644\n--- a/rtl/ibex_id_stage.sv\n+++ b/rtl/ibex_id_stage.sv\n@@ -192,6 +192,7 @@ module ibex_id_stage #(\n logic branch_set, branch_set_d;\n logic branch_taken;\n logic jump_in_dec;\n+ logic jump_set_dec;\n logic jump_set;\n \n logic instr_first_cycle;\n@@ -400,7 +401,7 @@ module ibex_id_stage #(\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+ .jump_set_o ( jump_set_dec ),\n .branch_taken_i ( branch_taken ),\n .icache_inval_o ( icache_inval_o ),\n \n@@ -663,6 +664,7 @@ module ibex_id_stage #(\n // could generate needless prefetch buffer flushes and instruction fetches. ID/EX is designed such\n // that this shouldn't ever happen.\n `ASSERT(NeverDoubleBranch, branch_set |=> ~branch_set)\n+ `ASSERT(NeverDoubleJump, jump_set |=> ~jump_set)\n \n ///////////////\n // ID-EX FSM //\n@@ -692,6 +694,7 @@ module ibex_id_stage #(\n stall_branch = 1'b0;\n stall_alu = 1'b0;\n branch_set_d = 1'b0;\n+ jump_set = 1'b0;\n perf_branch_o = 1'b0;\n \n if (instr_executing) begin\n@@ -733,6 +736,7 @@ module ibex_id_stage #(\n // BTALU means jumps only need one cycle\n id_fsm_d = BranchTargetALU ? FIRST_CYCLE : MULTI_CYCLE;\n stall_jump = ~BranchTargetALU;\n+ jump_set = jump_set_dec;\n end\n alu_multicycle_dec: begin\n stall_alu = 1'b1;\n", "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 RV32B = 0,\n parameter bit DataIndTiming = 1'b0,\n parameter bit BranchTargetALU = 0,\n parameter bit WritebackStage = 0\n) (\n input logic clk_i,\n input logic rst_ni,\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 [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_first_cycle_id_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 output logic icache_inval_o,\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 input logic instr_fetch_err_plus2_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 input logic lsu_load_i, // LSU is performing a load\n input logic lsu_busy_i, // LSU is busy\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 // Multicycle Operation Stage Register\n input logic imd_val_we_ex_i,\n input logic [33:0] imd_val_d_ex_i,\n output logic [33:0] imd_val_q_ex_o,\n\n // Branch target ALU\n output logic [31:0] bt_a_operand_o,\n output logic [31:0] bt_b_operand_o,\n\n // MUL, DIV\n output logic mult_en_ex_o,\n output logic div_en_ex_o,\n output logic mult_sel_ex_o,\n output logic div_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 output logic multdiv_ready_id_o,\n\n // CSR\n output logic csr_access_o,\n output ibex_pkg::csr_op_e csr_op_o,\n output logic csr_op_en_o,\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 input logic csr_mstatus_tw_i,\n input logic illegal_csr_insn_i,\n input logic data_ind_timing_i,\n\n // Interface to load store unit\n output logic lsu_req_o,\n output logic lsu_we_o,\n output logic [1:0] lsu_type_o,\n output logic lsu_sign_ext_o,\n output logic [31:0] lsu_wdata_o,\n\n input logic lsu_req_done_i, // Data req to LSU is complete and\n // instruction can move to writeback\n // (only relevant where writeback stage is\n // present)\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] result_ex_i,\n input logic [31:0] csr_rdata_i,\n\n // Register file read\n output logic [4:0] rf_raddr_a_o,\n input logic [31:0] rf_rdata_a_i,\n output logic [4:0] rf_raddr_b_o,\n input logic [31:0] rf_rdata_b_i,\n\n // Register file write (via writeback)\n output logic [4:0] rf_waddr_id_o,\n output logic [31:0] rf_wdata_id_o,\n output logic rf_we_id_o,\n\n // Register write information from writeback (for resolving data hazards)\n input logic [4:0] rf_waddr_wb_i,\n input logic [31:0] rf_wdata_fwd_wb_i,\n input logic rf_write_wb_i,\n\n output logic en_wb_o,\n output ibex_pkg::wb_instr_type_e instr_type_wb_o,\n input logic ready_wb_i,\n input logic outstanding_load_wb_i,\n input logic outstanding_store_wb_i,\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 perf_dside_wait_o, // instruction in ID/EX is awaiting memory\n // access to finish before proceeding\n output logic perf_mul_wait_o,\n output logic perf_div_wait_o,\n output logic instr_id_done_o,\n output logic instr_id_done_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 wb_exception;\n\n logic branch_in_dec;\n logic branch_set, branch_set_d;\n logic branch_taken;\n logic jump_in_dec;\n logic jump_set_dec;\n logic jump_set;\n\n logic instr_first_cycle;\n logic instr_executing;\n logic instr_done;\n logic controller_run;\n logic stall_ld_hz;\n logic stall_mem;\n logic stall_multdiv;\n logic stall_branch;\n logic stall_jump;\n logic stall_id;\n logic stall_wb;\n logic flush_id;\n logic multicycle_done;\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\n rf_wd_sel_e rf_wdata_sel;\n logic rf_we_dec, rf_we_raw;\n logic rf_ren_a, rf_ren_b;\n\n logic [31:0] rf_rdata_a_fwd;\n logic [31:0] rf_rdata_b_fwd;\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 logic alu_multicycle_dec;\n logic stall_alu;\n\n logic [33:0] imd_val_q;\n\n op_a_sel_e bt_a_mux_sel;\n imm_b_sel_e bt_b_mux_sel;\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_en_dec;\n md_op_e multdiv_operator;\n logic [1:0] multdiv_signed_mode;\n\n // Data Memory Control\n logic lsu_we;\n logic [1:0] lsu_type;\n logic lsu_sign_ext;\n logic lsu_req, lsu_req_dec;\n logic data_req_allowed;\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 MUXES //\n ///////////////////\n\n // Main ALU immediate MUX for Operand A\n assign imm_a = (imm_a_mux_sel == IMM_A_Z) ? zimm_rs1_type : '0;\n\n // Main 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 = rf_rdata_a_fwd;\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 if (BranchTargetALU) begin : g_btalu_muxes\n // Branch target ALU operand A mux\n always_comb begin : bt_operand_a_mux\n unique case (bt_a_mux_sel)\n OP_A_REG_A: bt_a_operand_o = rf_rdata_a_fwd;\n OP_A_CURRPC: bt_a_operand_o = pc_id_i;\n default: bt_a_operand_o = pc_id_i;\n endcase\n end\n\n // Branch target ALU operand B mux\n always_comb begin : bt_immediate_b_mux\n unique case (bt_b_mux_sel)\n IMM_B_I: bt_b_operand_o = imm_i_type;\n IMM_B_B: bt_b_operand_o = imm_b_type;\n IMM_B_J: bt_b_operand_o = imm_j_type;\n IMM_B_INCR_PC: bt_b_operand_o = instr_is_compressed_i ? 32'h2 : 32'h4;\n default: bt_b_operand_o = instr_is_compressed_i ? 32'h2 : 32'h4;\n endcase\n end\n\n // Reduced main ALU 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_U: imm_b = imm_u_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 end else begin : g_nobtalu\n op_a_sel_e unused_a_mux_sel;\n imm_b_sel_e unused_b_mux_sel;\n\n assign unused_a_mux_sel = bt_a_mux_sel;\n assign unused_b_mux_sel = bt_b_mux_sel;\n assign bt_a_operand_o = '0;\n assign bt_b_operand_o = '0;\n\n // Full main ALU 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 end\n\n // ALU MUX for Operand B\n assign alu_operand_b = (alu_op_b_mux_sel == OP_B_IMM) ? imm_b : rf_rdata_b_fwd;\n\n /////////////////////////////////////////\n // Multicycle Operation Stage Register //\n /////////////////////////////////////////\n\n always_ff @(posedge clk_i or negedge rst_ni) begin : intermediate_val_reg\n if (!rst_ni) begin\n imd_val_q <= '0;\n end else if (imd_val_we_ex_i) begin\n imd_val_q <= imd_val_d_ex_i;\n end\n end\n\n assign imd_val_q_ex_o = imd_val_q;\n\n ///////////////////////\n // Register File MUX //\n ///////////////////////\n\n // Suppress register write if there is an illegal CSR access or instruction is not executing\n assign rf_we_id_o = rf_we_raw & instr_executing & ~illegal_csr_insn_i;\n\n // Register file write data mux\n always_comb begin : rf_wdata_id_mux\n unique case (rf_wdata_sel)\n RF_WD_EX: rf_wdata_id_o = result_ex_i;\n RF_WD_CSR: rf_wdata_id_o = csr_rdata_i;\n default: rf_wdata_id_o = result_ex_i;\n endcase;\n end\n\n /////////////\n // Decoder //\n /////////////\n\n ibex_decoder #(\n .RV32E ( RV32E ),\n .RV32M ( RV32M ),\n .RV32B ( RV32B ),\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_dec ),\n .branch_taken_i ( branch_taken ),\n .icache_inval_o ( icache_inval_o ),\n\n // from IF-ID pipeline register\n .instr_first_cycle_i ( instr_first_cycle ),\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 .bt_a_mux_sel_o ( bt_a_mux_sel ),\n .bt_b_mux_sel_o ( bt_b_mux_sel ),\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 .rf_wdata_sel_o ( rf_wdata_sel ),\n .rf_we_o ( rf_we_dec ),\n\n .rf_raddr_a_o ( rf_raddr_a_o ),\n .rf_raddr_b_o ( rf_raddr_b_o ),\n .rf_waddr_o ( rf_waddr_id_o ),\n .rf_ren_a_o ( rf_ren_a ),\n .rf_ren_b_o ( rf_ren_b ),\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 .alu_multicycle_o ( alu_multicycle_dec ),\n\n // MULT & DIV\n .mult_en_o ( mult_en_dec ),\n .div_en_o ( div_en_dec ),\n .mult_sel_o ( mult_sel_ex_o ),\n .div_sel_o ( div_sel_ex_o ),\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\n // LSU\n .data_req_o ( lsu_req_dec ),\n .data_we_o ( lsu_we ),\n .data_type_o ( lsu_type ),\n .data_sign_extension_o ( lsu_sign_ext ),\n\n // jump/branches\n .jump_in_dec_o ( jump_in_dec ),\n .branch_in_dec_o ( branch_in_dec )\n );\n\n /////////////////////////////////\n // CSR-related pipline flushes //\n /////////////////////////////////\n always_comb begin : csr_pipeline_flushes\n csr_pipe_flush = 1'b0;\n\n // A pipeline flush is needed to let the controller react after modifying certain CSRs:\n // - When enabling interrupts, pending IRQs become visible to the controller only during\n // the next cycle. If during that cycle the core disables interrupts again, it does not\n // see any pending IRQs and consequently does not start to handle interrupts.\n // - When modifying debug CSRs - TODO: Check if this is really needed\n if (csr_op_en_o == 1'b1 && (csr_op_o == CSR_OP_WRITE || csr_op_o == CSR_OP_SET)) begin\n if (csr_num_e'(instr_rdata_i[31:20]) == CSR_MSTATUS ||\n csr_num_e'(instr_rdata_i[31:20]) == CSR_MIE) begin\n csr_pipe_flush = 1'b1;\n end\n end else if (csr_op_en_o == 1'b1 && csr_op_o != CSR_OP_READ) begin\n if (csr_num_e'(instr_rdata_i[31:20]) == CSR_DCSR ||\n csr_num_e'(instr_rdata_i[31:20]) == CSR_DPC ||\n csr_num_e'(instr_rdata_i[31:20]) == CSR_DSCRATCH0 ||\n csr_num_e'(instr_rdata_i[31:20]) == CSR_DSCRATCH1) begin\n csr_pipe_flush = 1'b1;\n end\n end\n end\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 #(\n .WritebackStage ( WritebackStage )\n ) 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 .instr_fetch_err_plus2_i ( instr_fetch_err_plus2_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 .controller_run_o ( controller_run ),\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 .wb_exception_o ( wb_exception ),\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_save_wb_o ( csr_save_wb_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_id_i ( stall_id ),\n .stall_wb_i ( stall_wb ),\n .flush_id_o ( flush_id ),\n\n // Performance Counters\n .perf_jump_o ( perf_jump_o ),\n .perf_tbranch_o ( perf_tbranch_o )\n );\n\n assign multdiv_en_dec = mult_en_dec | div_en_dec;\n\n assign lsu_req = instr_executing ? data_req_allowed & lsu_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 assign lsu_req_o = lsu_req;\n assign lsu_we_o = lsu_we;\n assign lsu_type_o = lsu_type;\n assign lsu_sign_ext_o = lsu_sign_ext;\n assign lsu_wdata_o = rf_rdata_b_fwd;\n // csr_op_en_o is set when CSR access should actually happen.\n // csv_access_o is set when CSR access instruction is present and is used to compute whether a CSR\n // access is illegal. A combinational loop would be created if csr_op_en_o was used along (as\n // asserting it for an illegal csr access would result in a flush that would need to deassert it).\n assign csr_op_en_o = csr_access_o & instr_executing & instr_id_done_o;\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 assign mult_en_ex_o = mult_en_id;\n assign div_en_ex_o = div_en_id;\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 = rf_rdata_a_fwd;\n assign multdiv_operand_b_ex_o = rf_rdata_b_fwd;\n\n ////////////////////////\n // Branch set control //\n ////////////////////////\n\n if (BranchTargetALU && !DataIndTiming) 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_flop\n // Branch set flopped without branch target ALU, or in fixed time execution mode\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 // Branches always take two cycles in fixed time execution mode, with or without the branch\n // target ALU (to avoid a path from the branch decision into the branch target ALU operand\n // muxing).\n assign branch_set = (BranchTargetALU && !data_ind_timing_i) ? branch_set_d : branch_set_q;\n end\n\n // Branch condition is calculated in the first cycle and flopped for use in the second cycle\n // (only used in fixed time execution mode to determine branch destination).\n if (DataIndTiming) begin : g_sec_branch_taken\n logic branch_taken_q;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n branch_taken_q <= 1'b0;\n end else begin\n branch_taken_q <= branch_decision_i;\n end\n end\n\n assign branch_taken = ~data_ind_timing_i | branch_taken_q;\n\n end else begin : g_nosec_branch_taken\n\n // Signal unused without fixed time execution mode - only taken branches will trigger branch_set\n assign branch_taken = 1'b1;\n\n end\n\n // Holding branch_set/jump_set high for more than one cycle may not cause a functional issue but\n // could generate needless prefetch buffer flushes and instruction fetches. ID/EX is designed such\n // that this shouldn't ever happen.\n `ASSERT(NeverDoubleBranch, branch_set |=> ~branch_set)\n `ASSERT(NeverDoubleJump, jump_set |=> ~jump_set)\n\n ///////////////\n // ID-EX FSM //\n ///////////////\n\n typedef enum logic { FIRST_CYCLE, MULTI_CYCLE } id_fsm_e;\n id_fsm_e id_fsm_q, id_fsm_d;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin : id_pipeline_reg\n if (!rst_ni) begin\n id_fsm_q <= FIRST_CYCLE;\n end else begin\n id_fsm_q <= id_fsm_d;\n end\n end\n\n // ID/EX stage can be in two states, FIRST_CYCLE and MULTI_CYCLE. An instruction enters\n // MULTI_CYCLE if it requires multiple cycles to complete regardless of stalls and other\n // considerations. An instruction may be held in FIRST_CYCLE if it's unable to begin executing\n // (this is controlled by instr_executing).\n\n always_comb begin\n id_fsm_d = id_fsm_q;\n rf_we_raw = rf_we_dec;\n stall_multdiv = 1'b0;\n stall_jump = 1'b0;\n stall_branch = 1'b0;\n stall_alu = 1'b0;\n branch_set_d = 1'b0;\n jump_set = 1'b0;\n perf_branch_o = 1'b0;\n\n if (instr_executing) begin\n unique case (id_fsm_q)\n FIRST_CYCLE: begin\n unique case (1'b1)\n lsu_req_dec: begin\n if (!WritebackStage) begin\n // LSU operation\n id_fsm_d = MULTI_CYCLE;\n end else begin\n if(~lsu_req_done_i) begin\n id_fsm_d = MULTI_CYCLE;\n end\n end\n end\n multdiv_en_dec: begin\n // MUL or DIV operation\n if (~ex_valid_i) begin\n // When single-cycle multiply is configured mul can finish in the first cycle so\n // only enter MULTI_CYCLE state if a result isn't immediately available\n id_fsm_d = MULTI_CYCLE;\n rf_we_raw = 1'b0;\n stall_multdiv = 1'b1;\n end\n end\n branch_in_dec: begin\n // cond branch operation\n // All branches take two cycles in fixed time execution mode, regardless of branch\n // condition.\n id_fsm_d = (data_ind_timing_i || (!BranchTargetALU && branch_decision_i)) ?\n MULTI_CYCLE : FIRST_CYCLE;\n stall_branch = (~BranchTargetALU & branch_decision_i) | data_ind_timing_i;\n branch_set_d = branch_decision_i | data_ind_timing_i;\n perf_branch_o = 1'b1;\n end\n jump_in_dec: begin\n // uncond branch operation\n // BTALU means jumps only need one cycle\n id_fsm_d = BranchTargetALU ? FIRST_CYCLE : MULTI_CYCLE;\n stall_jump = ~BranchTargetALU;\n jump_set = jump_set_dec;\n end\n alu_multicycle_dec: begin\n stall_alu = 1'b1;\n id_fsm_d = MULTI_CYCLE;\n rf_we_raw = 1'b0;\n end\n default: begin\n id_fsm_d = FIRST_CYCLE;\n end\n endcase\n end\n\n MULTI_CYCLE: begin\n if(multdiv_en_dec) begin\n rf_we_raw = rf_we_dec & ex_valid_i;\n end\n\n if (multicycle_done & ready_wb_i) begin\n id_fsm_d = FIRST_CYCLE;\n end else begin\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_fsm_d = FIRST_CYCLE;\n end\n endcase\n end\n end\n\n // Note for the two-stage configuration ready_wb_i is always set\n assign multdiv_ready_id_o = ready_wb_i;\n\n `ASSERT(StallIDIfMulticycle, (id_fsm_q == FIRST_CYCLE) & (id_fsm_d == MULTI_CYCLE) |-> stall_id)\n\n // Stall ID/EX stage for reason that relates to instruction in ID/EX\n assign stall_id = stall_ld_hz | stall_mem | stall_multdiv | stall_jump | stall_branch |\n stall_alu;\n\n assign instr_done = ~stall_id & ~flush_id & instr_executing;\n\n if (WritebackStage) begin\n assign multicycle_done = lsu_req_dec ? ~stall_mem : ex_valid_i;\n end else begin\n assign multicycle_done = lsu_req_dec ? lsu_valid_i : ex_valid_i;\n end\n\n // Signal instruction in ID is in it's first cycle. It can remain in its\n // first cycle if it is stalled.\n assign instr_first_cycle = instr_valid_i & (id_fsm_q == FIRST_CYCLE);\n // Used by RVFI to know when to capture register read data\n // Used by ALU to access RS3 if ternary instruction.\n assign instr_first_cycle_id_o = instr_first_cycle;\n\n if (WritebackStage) begin : gen_stall_mem\n logic unused_lsu_busy;\n\n // Register read address matches write address in WB\n logic rf_rd_a_wb_match;\n logic rf_rd_b_wb_match;\n // Hazard between registers being read and written\n logic rf_rd_a_hz;\n logic rf_rd_b_hz;\n\n logic data_req_complete_d;\n logic data_req_complete_q;\n\n logic outstanding_memory_access;\n\n logic instr_kill;\n\n assign unused_lsu_busy = lsu_busy_i;\n\n assign data_req_complete_d =\n (data_req_complete_q | (lsu_req & lsu_req_done_i)) & ~instr_id_done_o;\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (~rst_ni) begin\n data_req_complete_q <= 1'b0;\n end else begin\n data_req_complete_q <= data_req_complete_d;\n end\n end\n\n // Is a memory access ongoing that isn't finishing this cycle\n assign outstanding_memory_access = (outstanding_load_wb_i | outstanding_store_wb_i) &\n ~lsu_valid_i;\n\n // Can start a new memory access if any previous one has finished or is finishing\n // Don't start a new memory access if this instruction has already done it's request\n assign data_req_allowed = ~outstanding_memory_access & ~data_req_complete_q;\n\n // Instruction won't execute because:\n // - There is a pending exception in writeback\n // The instruction in ID/EX will be flushed and the core will jump to an exception handler\n // - The controller isn't running instructions\n // This either happens in preparation for a flush and jump to an exception handler e.g. in\n // response to an IRQ or debug request or whilst the core is sleeping or resetting/fetching\n // first instruction in which case any valid instruction in ID/EX should be ignored.\n // - There was an error on instruction fetch\n assign instr_kill = instr_fetch_err_i |\n wb_exception |\n ~controller_run;\n\n // With writeback stage instructions must be prevented from executing if there is:\n // - A load hazard\n // - A pending memory access\n // If it receives an error response this results in a precise exception from WB so ID/EX\n // instruction must not execute until error response is known).\n // - A load/store error\n // This will cause a precise exception for the instruction in WB so ID/EX instruction must not\n // execute\n assign instr_executing = instr_valid_i &\n ~instr_kill &\n ~stall_ld_hz &\n ~outstanding_memory_access;\n\n `ASSERT(IbexStallIfValidInstrNotExecuting,\n instr_valid_i & ~instr_kill & ~instr_executing |-> stall_id)\n\n // Stall for reasons related to memory:\n // * Requested by LSU (load/store in ID/EX needs to be held in ID/EX whilst a data request or\n // granted or the second half of a misaligned access is sent out)\n // * LSU access required but data requests aren't currently allowed\n // * There is an outstanding memory access that won't resolve this cycle (need to wait to allow\n // precise exceptions)\n assign stall_mem = instr_valid_i & ((lsu_req_dec & (~data_req_allowed | (~data_req_complete_q & ~lsu_req_done_i))) | outstanding_memory_access);\n\n assign rf_rd_a_wb_match = (rf_waddr_wb_i == rf_raddr_a_o) & |rf_raddr_a_o;\n assign rf_rd_b_wb_match = (rf_waddr_wb_i == rf_raddr_b_o) & |rf_raddr_b_o;\n\n // If instruction is reading register that load will be writing stall in\n // ID until load is complete. No need to stall when reading zero register.\n assign rf_rd_a_hz = rf_rd_a_wb_match & rf_ren_a;\n assign rf_rd_b_hz = rf_rd_b_wb_match & rf_ren_b;\n\n // If instruction is read register that writeback is writing forward writeback data to read\n // data. Note this doesn't factor in load data as it arrives too late, such hazards are\n // resolved via a stall (see above).\n assign rf_rdata_a_fwd = rf_rd_a_wb_match & rf_write_wb_i ? rf_wdata_fwd_wb_i : rf_rdata_a_i;\n assign rf_rdata_b_fwd = rf_rd_b_wb_match & rf_write_wb_i ? rf_wdata_fwd_wb_i : rf_rdata_b_i;\n\n assign stall_ld_hz = outstanding_load_wb_i & lsu_load_i & (rf_rd_a_hz | rf_rd_b_hz) & rf_write_wb_i;\n\n assign instr_type_wb_o = ~lsu_req_dec ? WB_INSTR_OTHER :\n lsu_we ? WB_INSTR_STORE :\n WB_INSTR_LOAD;\n\n assign en_wb_o = instr_done;\n\n assign instr_id_done_o = en_wb_o & ready_wb_i;\n\n // Stall ID/EX as instruction in ID/EX cannot proceed to writeback yet\n assign stall_wb = en_wb_o & ~ready_wb_i;\n\n assign perf_dside_wait_o = instr_valid_i & ~instr_kill & (outstanding_memory_access | stall_ld_hz);\n end else begin\n\n assign data_req_allowed = instr_first_cycle;\n\n // Without Writeback Stage always stall the first cycle of a load/store.\n // Then stall until it is complete\n assign stall_mem = instr_valid_i & (lsu_busy_i | (lsu_req_dec & (~lsu_valid_i | instr_first_cycle)));\n\n // No load hazards without Writeback Stage\n assign stall_ld_hz = 1'b0;\n\n // Without writeback stage any valid instruction that hasn't seen an error will execute\n assign instr_executing = instr_valid_i & ~instr_fetch_err_i & controller_run;\n\n `ASSERT(IbexStallIfValidInstrNotExecuting,\n instr_valid_i & ~instr_fetch_err_i & ~instr_executing & controller_run |-> stall_id)\n\n // No data forwarding without writeback stage so always take source register data direct from\n // register file\n assign rf_rdata_a_fwd = rf_rdata_a_i;\n assign rf_rdata_b_fwd = rf_rdata_b_i;\n\n // Unused Writeback stage only IO & wiring\n // Assign inputs and internal wiring to unused signals to satisfy lint checks\n // Tie-off outputs to constant values\n logic unused_data_req_done_ex;\n logic unused_lsu_load;\n logic [4:0] unused_rf_waddr_wb;\n logic unused_rf_write_wb;\n logic unused_outstanding_load_wb;\n logic unused_outstanding_store_wb;\n logic unused_wb_exception;\n logic unused_rf_ren_a, unused_rf_ren_b;\n logic [31:0] unused_rf_wdata_fwd_wb;\n\n assign unused_data_req_done_ex = lsu_req_done_i;\n assign unused_lsu_load = lsu_load_i;\n assign unused_rf_waddr_wb = rf_waddr_wb_i;\n assign unused_rf_write_wb = rf_write_wb_i;\n assign unused_outstanding_load_wb = outstanding_load_wb_i;\n assign unused_outstanding_store_wb = outstanding_store_wb_i;\n assign unused_wb_exception = wb_exception;\n assign unused_rf_ren_a = rf_ren_a;\n assign unused_rf_ren_b = rf_ren_b;\n assign unused_rf_wdata_fwd_wb = rf_wdata_fwd_wb_i;\n\n assign instr_type_wb_o = WB_INSTR_OTHER;\n assign stall_wb = 1'b0;\n\n assign perf_dside_wait_o = instr_executing & lsu_req_dec & ~lsu_valid_i;\n\n assign en_wb_o = 1'b0;\n assign instr_id_done_o = instr_done;\n end\n\n assign perf_mul_wait_o = stall_multdiv & mult_en_dec;\n assign perf_div_wait_o = stall_multdiv & div_en_dec;\n\n assign instr_id_done_compressed_o = instr_id_done_o & instr_is_compressed_i;\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT_KNOWN_IF(IbexAluOpMuxSelKnown, alu_op_a_mux_sel, instr_valid_i)\n `ASSERT(IbexAluAOpMuxSelValid, instr_valid_i |-> alu_op_a_mux_sel inside {\n OP_A_REG_A,\n OP_A_FWD,\n OP_A_CURRPC,\n OP_A_IMM})\n if (BranchTargetALU) begin : g_btalu_assertions\n `ASSERT(IbexImmBMuxSelValid, instr_valid_i |-> imm_b_mux_sel inside {\n IMM_B_I,\n IMM_B_S,\n IMM_B_U,\n IMM_B_INCR_PC,\n IMM_B_INCR_ADDR})\n end else begin : g_nobtalu_assertions\n `ASSERT(IbexImmBMuxSelValid, instr_valid_i |-> 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 end\n `ASSERT_KNOWN_IF(IbexBTAluAOpMuxSelKnown, bt_a_mux_sel, instr_valid_i)\n `ASSERT(IbexBTAluAOpMuxSelValid, instr_valid_i |-> bt_a_mux_sel inside {\n OP_A_REG_A,\n OP_A_CURRPC})\n `ASSERT_KNOWN_IF(IbexBTAluBOpMuxSelKnown, bt_b_mux_sel, instr_valid_i)\n `ASSERT(IbexBTAluBOpMuxSelValid, instr_valid_i |-> bt_b_mux_sel inside {\n IMM_B_I,\n IMM_B_B,\n IMM_B_J,\n IMM_B_INCR_PC})\n `ASSERT(IbexRegfileWdataSelValid, instr_valid_i |-> rf_wdata_sel inside {\n RF_WD_EX,\n RF_WD_CSR})\n `ASSERT_KNOWN(IbexWbStateKnown, id_fsm_q)\n\n // Branch decision must be valid when jumping.\n `ASSERT_KNOWN_IF(IbexBranchDecisionValid, branch_decision_i, instr_valid_i)\n\n // Instruction delivered to ID stage can not contain X.\n `ASSERT_KNOWN_IF(IbexIdInstrKnown, instr_rdata_i,\n instr_valid_i && !(illegal_c_insn_i || instr_fetch_err_i))\n\n // Instruction delivered to ID stage can not contain X.\n `ASSERT_KNOWN_IF(IbexIdInstrALUKnown, instr_rdata_alu_i,\n instr_valid_i && !(illegal_c_insn_i || instr_fetch_err_i))\n\n // Multicycle enable signals must be unique.\n `ASSERT(IbexMulticycleEnableUnique,\n $onehot0({lsu_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", "selected_doc_paths": ["doc/instruction_decode_execute.rst", "doc/pipeline_details.rst", "doc/register_file.rst", "doc/load_store_unit.rst", "doc/exception_interrupts.rst", "doc/cs_registers.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 507, "lang": "sv", "rtl_files": ["dv/uvm/env/core_ibex_env_cfg.sv"], "spec": "# Behavioral Design Specification: `core_ibex_env_cfg`\n\n## Overview\n\nThe `core_ibex_env_cfg` module is a configuration object used by the Ibex UVM verification environment to control stimulus generation, timing, and handshake behavior during simulation. It provides a centralized way to specify test‑time parameters that influence how the environment drives interrupts, debug requests, and how it performs co‑simulation checks.\n\nThis configuration object is instantiated and initialized once at the start of each simulation. All fields can be set directly in the test code or overridden via simulator plusargs, allowing flexible reuse across different test scenarios.\n\n## Configuration Parameters\n\nThe module defines the following configurable properties. Each property controls a specific aspect of the testbench behavior.\n\n### Interrupt Sequence Enable\n\nA binary flag that determines whether the environment actively drives external interrupts onto the core’s interrupt inputs during the simulation.\n\n- **When set to `1`**: The testbench shall generate interrupt requests (e.g., timer, external, software, fast interrupts, and non‑maskable interrupts) according to the configured stimulus sequence.\n- **When set to `0`**: No external interrupt stimulus shall be driven. The core will only encounter interrupts that arise from its own execution (e.g., timer interrupts toggled by software).\n\n### Debug Stress Sequence Enable\n\nA binary flag that controls whether the environment exerts high‑frequency or back‑to‑back debug requests.\n\n- **When set to `1`**: The testbench shall issue debug requests (`debug_req_i`) repeatedly or in rapid succession, stressing the core’s ability to enter and exit Debug Mode correctly under load.\n- **When set to `0`**: Only a single or no debug request shall be driven (the exact behavior is governed by other debug‑related configuration).\n\n### Debug Single Sequence Enable\n\nA binary flag that controls whether the environment drives a single, isolated debug request.\n\n- **When set to `1`**: The testbench shall assert `debug_req_i` exactly once during the simulation, allowing the core to enter Debug Mode and then resume normal execution.\n- **When set to `0`**: No single debug request shall be issued by this sequence (the core may still receive debug requests from other sources in the environment).\n\n> **Note:** Both debug stress and debug single sequences may be active simultaneously – the environment shall interleave or prioritize them according to its internal scheduling logic.\n\n### Maximum Interval\n\nA 32‑bit unsigned integer that specifies the maximum number of clock cycles between successive external stimulus events (interrupts or debug requests) when the corresponding sequences are enabled.\n\n- The environment shall randomize the actual interval between two events to be any value from 1 up to and including `max_interval`.\n- If `max_interval` is set to 0, the environment may drive events back‑to‑back (i.e., every cycle), subject to the constraints of the core’s responsiveness.\n- This parameter applies uniformly to all enabled stimulus sequences unless overridden by per‑sequence settings.\n\n### Signature Address Enable\n\nA binary flag that indicates whether the test requires a specific memory address to be used for the core‑to‑testbench handshake.\n\n- **When set to `1`**: The environment shall use the address provided by `signature_addr` for the handshake mechanism described in the RISCV‑DV documentation. The test program (compiled by RISCV‑DV) is expected to write handshake data to this address. The environment monitors this address for status updates.\n- **When set to `0`**: The environment shall not require a dedicated handshake address. Any handshake mechanism implemented in the core’s program will use the default address (`0x8ffffffc`), or the address may be taken from the test program directly.\n\n### Signature Address\n\nA 32‑bit unsigned integer that defines the memory address used for the core‑testbench handshake when `require_signature_addr` is asserted.\n\n- The value is derived from a string supplied via plusargs interpreted as a hexadecimal number.\n- The environment must interpret this address as a byte‑aligned location in the simulated memory map.\n- If no override is provided and no default is set, the address shall default to `0x8FFFFFFC` (as documented for the Ibex verification environment).\n\n## Default Behavior\n\nIf no plusargs are supplied at simulation startup, all configurable fields assume a default value of zero, except for `signature_addr` which defaults to `0x8FFFFFFC`. This means:\n\n- No interrupt sequences run.\n- No debug stress or single sequences run.\n- The `max_interval` is effectively zero, but since no sequence is enabled, no stimulus is generated.\n- The environment does not require a signature address (i.e., it uses the default handshake address implicitly, or relies on the test program’s own handshake).\n\nTests that depend on external interrupts, debug intervention, or custom handshake addresses must override the relevant fields.\n\n## Usage in the Testbench\n\nThe `core_ibex_env_cfg` object is typically instantiated in the environment’s base test (`core_ibex_base_test`) and propagated to the UVM components that drive stimulus. The following rules apply:\n\n1. **Initialization at time zero**: All configuration fields must be set before the environment starts any sequence execution. The configuration is read‑only after the `build_phase` is complete.\n2. **Plusarg precedence**: Values supplied via simulator plusargs shall override any hard‑coded values set in the test code. The environment must parse the following plusargs:\n - `enable_irq_seq`\n - `enable_debug_stress_seq`\n - `enable_debug_single_seq`\n - `max_interval`\n - `require_signature_addr`\n - `signature_addr` (as a hex string)\n3. **Signature address conversion**: The `signature_addr` plusarg must be a string containing a hexadecimal number (e.g., “0x8FFFFFFC”). The environment shall parse it and store the corresponding 32‑bit value. If the string is empty or malformed, the behavior is undefined; the environment should fall back to the default value.\n4. **Synchronization with RISCV‑DV**: When `require_signature_addr` is true, the environment must ensure that the memory model initializes the location at `signature_addr` to zero and that the core’s compiled test program writes handshake data to that address. The environment shall monitor writes to detect test completion or failure.\n\n## Relationship to the Core’s Behavior\n\nThe configuration parameters directly influence the core’s observed behavior during simulation:\n\n- **Interrupts**: Enabling `enable_irq_seq` causes the core to receive external interrupt requests. The core must correctly vector to the interrupt handler, save/restore context, and resume the interrupted program. The environment checks compliance by comparing the final register file against the instruction‑set simulator (ISS) trace log.\n- **Debug**: Enabling debug sequences causes the core to enter Debug Mode. The core shall halt execution, jump to the address specified by `DmHaltAddr`, allow debugger communication, and later resume normal execution upon a debug resume request. The environment verifies that register values are preserved correctly across Debug Mode entry/exit.\n- **Handshake**: The signature address is used by the core to signal its status (e.g., “passed”, “failed”, “finished test”) to the testbench. The environment checks these signals to coordinate end‑of‑test and to validate correct behavior during interrupt or debug scenarios.\n\n## Summary\n\nThe `core_ibex_env_cfg` module is a purely passive configuration container. It does not execute any sequences itself; rather, it provides the runtime knobs that determine *what* kind of stimulus the environment produces and *how* it interacts with the core. By using this configuration object, test authors can quickly construct a wide variety of verification scenarios without modifying the underlying stimulus generation logic.", "commit_id": "43268b7604f40d4865a899988638d8c1b8e36dcb", "timestamp": "2019-12-03T16:23:51+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "9c981b198ec97bc7701fbc7dd81baca0b7ff8e47", "pr_title": "Pluseargs parsing fix", "pr_body": "This commit fixes $value$plusargs sytem function error described in #497.", "issue_title": "Cadence simulator plusargs command line argument parsing error", "issue_body": "Verification environment uses SystemVerilog line argument for getting signature address [(core_ibex_env_cfg.sv)](https://github.com/lowRISC/ibex/blob/ce7e38351e28bf54cbc7c2856ce6b65b9d2a3fbb/dv/uvm/env/core_ibex_env_cfg.sv#L30). Value is passed to environment at [(makefile)](https://github.com/lowRISC/ibex/blob/ce7e38351e28bf54cbc7c2856ce6b65b9d2a3fbb/dv/uvm/Makefile#L132) at run_sim step. The problem is Cadence simulator cannot recognize this argument as hexadecimal number:\r\n```\r\nvoid'($value$plusargs(\"signature_addr=%0h\", signature_addr));\r\n |\r\nncsim: *E,SYSFMT (ibex/dv/uvm/env/core_ibex_env_cfg.sv,30|24): $value$plusargs -- value found '0x8ffffffc' for plusarg 'signature_addr=' does not match specified format.\r\n```\r\nThis issue can be fixed with something like atohex() SystemVerilog function (this function should be supported by all simulators).", "commit_message": "Pluseargs parsing was corrected", "fix_patch": "diff --git a/dv/uvm/env/core_ibex_env_cfg.sv b/dv/uvm/env/core_ibex_env_cfg.sv\nindex 988de600ac..dd0e4e9612 100644\n--- a/dv/uvm/env/core_ibex_env_cfg.sv\n+++ b/dv/uvm/env/core_ibex_env_cfg.sv\n@@ -9,6 +9,7 @@ class core_ibex_env_cfg extends uvm_object;\n bit enable_debug_single_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@@ -27,7 +28,8 @@ class core_ibex_env_cfg extends uvm_object;\n void'($value$plusargs(\"enable_debug_single_seq=%0d\", enable_debug_single_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=%0h\", signature_addr));\n+ void'($value$plusargs(\"signature_addr=%s\", signature_addr_str));\n+ signature_addr = signature_addr_str.atohex();\n endfunction\n \n endclass\n", "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_seq;\n bit enable_debug_stress_seq;\n bit enable_debug_single_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_seq, UVM_DEFAULT)\n `uvm_field_int(enable_debug_single_seq, UVM_DEFAULT)\n `uvm_field_int(enable_debug_stress_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_seq=%0d\", enable_irq_seq));\n void'($value$plusargs(\"enable_debug_stress_seq=%0d\", enable_debug_stress_seq));\n void'($value$plusargs(\"enable_debug_single_seq=%0d\", enable_debug_single_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", "selected_doc_paths": ["doc/verification.rst", "doc/debug.rst", "doc/exception_interrupts.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 640, "lang": "sv", "rtl_files": ["dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_slave_seq_lib.sv"], "spec": "# Behavioral Design Specification: Ibex Memory Interface Slave Sequence\n\n## 1. Overview\n\nThe `ibex_mem_intf_slave_seq` is a UVM sequence component used in the verification environment for the Ibex core's data-side memory interface. It implements a configurable memory slave model that responds to memory transactions issued by the core's load-store unit (LSU) through a UVM sequencer. The sequence provides realistic timing, error injection, and byte-addressable memory modelling capabilities.\n\nThis specification describes the required behavior of the slave sequence, independent of its internal implementation details. The component shall be used to drive a memory interface signal-level agent and must comply with the LSU protocol defined in the `load_store_unit.rst` documentation.\n\n## 2. Interface\n\nThe sequence interacts with the testbench through:\n\n- A UVM sequencer that receives requested transaction items (address, read/write type, data, byte enables) from the core’s LSU.\n- A memory model object that provides storage for the simulated data memory.\n- Configuration parameters (defined below) that control timing, error injection, and memory access granularity.\n\nNo direct hardware signals are driven by this sequence; instead, it creates and sends UVM sequence items to the agent, which then translates them into signal-level transactions on the DUT interface.\n\n## 3. Operational Behavior\n\n### 3.1 Basic Transaction Handling\n\nUpon starting, the sequence shall enter an infinite loop. In each iteration, it shall:\n\n1. **Obtain a pending transaction** from the sequencer. The transaction provides the address, read/write direction, data to write (for stores), and byte enables.\n\n2. **Create a response sequence item** that represents the slave’s acknowledgment and data delivery. The response shall be randomized with the following constraints:\n\n - The address, read/write direction, data, and byte enables must match the received request.\n - The response valid delay (`rvalid_delay`) shall be chosen randomly from a user-configurable distribution (see Section 5).\n - An error indication (`error`) shall be set if error injection is enabled at the time of randomization (see Section 4).\n\n3. After randomization, the sequence shall **perform a memory operation**:\n\n - **For read transactions:** If no error is indicated, the data from the memory model at the given address (with byte enable masking) shall be read and placed in the response. If an error is indicated, the data field shall be filled with a random value (any value is acceptable, as it will be ignored by the core).\n - **For write transactions:** After sending the response, the sequence shall write the data (again respecting byte enables) to the memory model. This is done regardless of whether an error is indicated, but the core shall treat an error response for a store as a write that did not complete normally.\n\n4. **Send the response** through the sequencer’s driver by calling `start_item` and `finish_item`. The time at which the response’s `rvalid` signal would be asserted is determined by the `rvalid_delay` field. The response shall be generated as a UVM sequence item and passed to the agent, which then drives the actual interface signals.\n\n### 3.2 Memory Access Granularity\n\nThe sequence supports two modes of memory access, controlled by a configuration bit (`is_dmem_seq`):\n\n- **Word‑aligned mode (default):** Memory reads and writes are performed on full word boundaries. The address is word‑aligned by clearing the two lowest bits. Byte enables are ignored for the actual memory store — the full 32‑bit word is read or written. This mode is used for instruction‑side or generic memory interfaces.\n\n- **Byte‑granular mode (D‐side memory mode):** The sequence reads and writes individual bytes based on the byte enable signals. Only the enabled bytes are updated in memory (for writes) and only enabled bytes contribute to the read data (for reads). The address is still word‑aligned, but the byte enables determine which bytes within that word are accessed. This mode is required for the data memory interface, where the LSU may perform sub‑word loads and stores.\n\n## 4. Error Injection\n\nThe sequence provides a mechanism to inject single errors into the memory response:\n\n- A **control function** (`inject_error`) shall set an internal flag that causes the very next transaction to be randomized with the error indicator set to true. This flag shall be cleared after that single transaction, so subsequent transactions shall not generate an error unless the function is called again.\n\n- A **synchronization flag** is available to query whether error injection is currently pending (i.e., whether the next transaction will have the error set). This allows higher‑level test sequences to ensure proper timing of error injection.\n\n- When the error is injected, the data returned for a read shall be random; the data for a write is irrelevant (the memory model may still be updated, but the core shall ignore the response data).\n\n- The sequence shall not inject errors when error injection is not explicitly enabled, except as dictated by the test sequence.\n\n## 5. Timing Configuration\n\nThe sequence allows the user to configure the range of the `rvalid_delay` (the number of clock cycles between the grant and the rvalid assertion) via two integer parameters:\n\n- **Minimum delay** (default 0) – the shortest possible delay.\n- **Maximum delay** (default 20) – the longest possible delay.\n\nThe actual delay shall be selected randomly according to a non‑uniform distribution that favors shorter delays, as follows:\n\n| Delay value | Relative weight |\n|----------------------------------------------|-----------------|\n| Exactly the minimum delay | 5 |\n| Between (minimum+1) and (maximum/2 – 1) | 3 |\n| Between (maximum/2) and (maximum – 1) | 1 |\n| Exactly the maximum delay | 1 |\n\nThis distribution models a memory system that is typically fast but occasionally slow, and it can stress the core’s ability to handle variable‑latency responses.\n\n## 6. Protocol Compliance\n\nThe sequence shall be used in conjunction with the actual signal‑level agent that implements the LSU protocol (see `load_store_unit.rst`). The sequence items it produces must be consistent with that protocol:\n\n- Each request from the sequencer corresponds to a single address phase (req + grant). The response’s `rvalid_delay` determines when the response is delivered after that grant.\n- For back‑to‑back transactions (where the host may issue a new request before receiving a response for a previous one), the sequence must return responses in order and with independent delays. The slave model does not need to support outstanding transactions beyond the one being processed; the sequencer ensures ordering.\n- The error indication (if set) shall cause the agent to assert `data_err_i` when `data_rvalid_i` is asserted, in accordance with the protocol.\n\n## 7. Initialization and Memory Model\n\nThe sequence requires a valid memory model instance to be set before execution. If none is provided, the sequence shall terminate with a fatal error. The memory model must support byte‑level read and write operations.\n\n## 8. Summary of Required Behaviors\n\n| Condition | Response |\n|-----------|----------|\n| Normal read (no error) | Return data from memory model, word or byte‑granular as configured, with variable delay. |\n| Normal write (no error) | Update memory model; response delay as configured. |\n| Error injected (read) | Set error high; return random data; memory not read. |\n| Error injected (write) | Set error high; update memory model anyway (consistent with real slave that may complete write before detecting error). |\n| Back‑to‑back transactions | Responses delivered in‑order, each with its own delay. |\n| Unaligned addresses | Address is always word‑aligned by the slave; byte enables control actual bytes accessed. |\n| Out‑of‑range or invalid addresses | Slave does not perform address checking; it simply accesses the memory model at the aligned address. |\n\nThe sequence shall continue servicing transactions indefinitely until the simulation ends. It shall not deadlock or hang waiting for a response that will never come; it is the responsibility of the testbench to always provide request items.", "commit_id": "cb9413e38bc43117a0a5dfd7221bbf8155815478", "timestamp": "2020-03-05T14:59:27+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "88f1a7e38f03bd044453356a84ef803fb06541bf", "pr_title": "Fix qrun compile warning", "pr_body": "Relate to #622 ", "issue_title": "Add support for Qrun Questa", "issue_body": "Hi, I make PR to support for qrun simulator. I try to run; however, I got a lot of warning for compilation, and optimization. I attach the output file. Could you help me take the look? I hope qrun can support for running `ibex`. Thank you\r\n[qrun_compile_optimize.log](https://github.com/lowRISC/ibex/files/4238391/qrun_compile_optimize.log)\r\n", "commit_message": "Fix qrun compile warning", "fix_patch": "diff --git a/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_slave_seq_lib.sv b/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_slave_seq_lib.sv\nindex 681332bfc7..7da6780a8f 100644\n--- a/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_slave_seq_lib.sv\n+++ b/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_slave_seq_lib.sv\n@@ -84,7 +84,7 @@ class ibex_mem_intf_slave_seq extends uvm_sequence #(ibex_mem_intf_seq_item);\n end\n endtask : body\n \n- virtual function inject_error();\n+ virtual function void inject_error();\n this.enable_error = 1'b1;\n endfunction\n \n", "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// SEQUENCE: ibex_mem_intf_slave_seq\n//------------------------------------------------------------------------------\n\nclass ibex_mem_intf_slave_seq extends uvm_sequence #(ibex_mem_intf_seq_item);\n\n int max_rvalid_delay = 20;\n int min_rvalid_delay = 0;\n ibex_mem_intf_seq_item item;\n mem_model m_mem;\n bit enable_error = 1'b0;\n // Used to ensure that whenever inject_error() is called, the very next transaction will inject an\n // error, and that enable_error will not be flipped back to 0 immediately\n bit error_synch = 1'b1;\n bit is_dmem_seq = 1'b0;\n\n `uvm_object_utils(ibex_mem_intf_slave_seq)\n `uvm_declare_p_sequencer(ibex_mem_intf_slave_sequencer)\n `uvm_object_new\n\n virtual task body();\n if(m_mem == null)\n `uvm_fatal(get_full_name(), \"Cannot get memory model\")\n `uvm_info(`gfn, $sformatf(\"is_dmem_seq: 0x%0x\", is_dmem_seq), UVM_LOW)\n forever\n begin\n bit [ADDR_WIDTH-1:0] aligned_addr;\n bit [DATA_WIDTH-1:0] rand_data;\n bit [DATA_WIDTH-1:0] read_data;\n p_sequencer.addr_ph_port.get(item);\n req = ibex_mem_intf_seq_item::type_id::create(\"req\");\n error_synch = 1'b0;\n if (!req.randomize() with {\n addr == item.addr;\n read_write == item.read_write;\n data == item.data;\n be == item.be;\n rvalid_delay dist {\n min_rvalid_delay :/ 5,\n [min_rvalid_delay + 1 : max_rvalid_delay / 2 - 1] :/ 3,\n [max_rvalid_delay / 2 : max_rvalid_delay - 1] :/ 1,\n max_rvalid_delay :/ 1\n };\n error == enable_error;\n }) begin\n `uvm_fatal(`gfn, \"Cannot randomize slave request\")\n end\n enable_error = 1'b0;\n error_synch = 1'b1;\n aligned_addr = {req.addr[DATA_WIDTH-1:2], 2'b0};\n if (req.error) begin\n `DV_CHECK_STD_RANDOMIZE_FATAL(rand_data)\n req.data = rand_data;\n end else begin\n if(req.read_write == READ) begin : READ_block\n if (is_dmem_seq) begin\n for (int i = DATA_WIDTH / 8 - 1; i >= 0; i--) begin\n read_data = read_data << 8;\n if (req.be[i])\n read_data[7:0] = m_mem.read_byte(aligned_addr + i);\n end\n req.data = read_data;\n end else begin\n req.data = m_mem.read(aligned_addr);\n end\n end\n end\n `uvm_info(get_full_name(), $sformatf(\"Response transfer:\\n%0s\", req.sprint()), UVM_HIGH)\n start_item(req);\n finish_item(req);\n if(item.read_write == WRITE) begin : WRITE_block\n bit [DATA_WIDTH-1:0] data;\n data = req.data;\n for (int i = 0; i < DATA_WIDTH / 8; i++) begin\n if (req.be[i])\n m_mem.write_byte(aligned_addr + i, data[7:0]);\n data = data >> 8;\n end\n end\n end\n endtask : body\n\n virtual function void inject_error();\n this.enable_error = 1'b1;\n endfunction\n\n virtual function bit get_error_synch();\n return this.error_synch;\n endfunction\n\nendclass : ibex_mem_intf_slave_seq\n", "selected_doc_paths": ["doc/load_store_unit.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 613, "lang": "sv", "rtl_files": ["rtl/ibex_cs_registers.sv"], "spec": "# Behavioral Design Specification: `ibex_cs_registers`\n\n## Overview\n\nThis module implements the **Control and Status Registers (CSRs)** required by the RISC-V Privileged Specification (v1.11) and the RISC-V Debug Specification (v0.13.2). It provides:\n\n- Machine-mode CSRs for trap handling and configuration.\n- Debug-mode CSRs (accessible only in Debug Mode).\n- Physical Memory Protection (PMP) CSRs.\n- Debug trigger CSRs (optional).\n- Performance monitoring CSRs (counter/inhibit/event select).\n\nThe module interfaces with the core pipeline to allow CSR read/write operations, trap entry/exit, and privilege level management.\n\n---\n\n## Behavioral Requirements\n\n### 1. CSR Access Interface\n\n- The module accepts a CSR address, write data, and an operation (read, write, set, clear) from the pipeline.\n- It returns read data for any valid CSR access.\n- CSR writes occur only when a new instruction is in the ID stage and no access violation is detected.\n- The module shall detect and signal the following access violations:\n - **Privilege level violation**: Access to a CSR whose address bits [9:8] indicate a higher privilege level than the current privilege mode.\n - **Write to read-only CSR**: Access with a write operation to a CSR whose address bits [11:10] are `2'b11` (reserved for read-only).\n - **Non-existent CSR**: Access to an address that does not correspond to any implemented CSR.\n- Any access that meets one of the above conditions shall be treated as illegal and shall suppress the write (if applicable). The illegal instruction exception shall be raised externally.\n\n### 2. Privilege Level Management\n\n- The module tracks the current privilege level (`M-Mode` or `U-Mode`).\n- Reset initializes the core to **Machine Mode (M-Mode)**.\n- The privilege level changes only on:\n - **Trap entry**: All traps (exceptions and interrupts) force the core into M-Mode.\n - **MRET instruction**: Restores the privilege level stored in `mstatus.MPP`.\n - **DRET instruction**: Restores the privilege level stored in `dcsr.prv`.\n- The current privilege level is made available externally for use by the instruction fetch unit (IF), ID stage, and load-store unit (LSU).\n- For LSU privilege checking, the effective privilege is either the current privilege level or the value of `mstatus.MPP` when `mstatus.MPRV` is set.\n\n### 3. Machine-Mode CSRs\n\nAll machine-mode CSRs are accessible from M-Mode (`privilege level ≥ M-Mode`) unless noted otherwise.\n\n#### 3.1 `mstatus` (Machine Status) – Address `0x300`\n- Fields:\n - **MIE** (bit 3): Global interrupt enable.\n - **MPIE** (bit 7): Previous interrupt enable (saved on trap).\n - **MPP** (bits 12:11): Previous privilege mode (saved on trap). Only M-Mode (`2’b11`) and U-Mode (`2’b00`) are supported; writes with other values are clamped to M-Mode.\n - **MPRV** (bit 17): Modify privilege – when set, loads and stores use MPP for privilege checking.\n - **TW** (bit 21): Timeout wait – when set, a `WFI` instruction in U-Mode causes a trap to M-Mode.\n- All fields are Writable-Allowed-Read-Legal (WARL): only legal values can be written; unsupported values are converted to supported ones.\n- Reset value: `0x0000_1800` (MIE=0, MPIE=1, MPP=U-Mode, MPRV=0, TW=0).\n\n#### 3.2 `misa` (ISA and Extensions) – Address `0x301`\n- Read-only, hardwired to a constant value indicating the supported ISA extensions (RV32I, C, M optional, U, etc.).\n- Writes are ignored.\n\n#### 3.3 `mie` (Machine Interrupt Enable) – Address `0x304`\n- Each bit enables a corresponding interrupt (see `mip`).\n- Fields:\n - Bits 30:16: Fast interrupt enables (mapped to `irq_fast_i[14:0]`).\n - Bit 11: Machine External Interrupt Enable (MEIE).\n - Bit 7: Machine Timer Interrupt Enable (MTIE).\n - Bit 3: Machine Software Interrupt Enable (MSIE).\n- All bits are WARL. Reset value: `0x0000_0000`.\n\n#### 3.4 `mtvec` (Machine Trap-Vector Base Address) – Address `0x305`\n- Holds the trap-handler base address and a fixed MODE field.\n- Bits 31:2: BASE – must be 256‑byte aligned (bits 7:2 forced to zero).\n- Bits 1:0: MODE – hardwired to `2’b01` (vectored mode).\n- The initial value is loaded from the boot address (input) when the core boots.\n- Writes overwrite the BASE field; the MODE field remains `2’b01`.\n- Reset value: `0x0000_0001` (BASE=0, MODE=vectored).\n\n#### 3.5 `mscratch` (Machine Scratch) – Address `0x340`\n- Read/Write. General-purpose scratch register for machine-mode software.\n- No special behavior. Reset value: `0x0000_0000`.\n\n#### 3.6 `mepc` (Machine Exception PC) – Address `0x341`\n- On trap entry, the current PC is saved into `mepc` (with the least significant bit forced to 0).\n- On MRET, the core jumps to the address in `mepc`.\n- Writes must align to 2 bytes (LSB ignored). WARL. Reset value: `0x0000_0000`.\n\n#### 3.7 `mcause` (Machine Cause) – Address `0x342`\n- On trap entry, the exception/interrupt cause is saved.\n- Bit 31: Interrupt flag (1 for interrupts, 0 for exceptions).\n- Bits 4:0: Exception code (see the table in Section 6).\n- Bits 30:5: Hardwired to 0. WARL. Reset value: `0x0000_0000`.\n\n#### 3.8 `mtval` (Machine Trap Value) – Address `0x343`\n- On trap entry, exception-specific information is saved:\n - For load/store address faults: the faulting virtual address.\n - For illegal instruction: the instruction word itself.\n - For other traps: 0.\n- Read/Write. WARL. Reset value: `0x0000_0000`.\n\n#### 3.9 `mip` (Machine Interrupt Pending) – Address `0x344`\n- Read-only register that shows the logical AND of the incoming interrupt signals and the corresponding `mie` bits.\n- Fields correspond to `mie`: fast interrupts (bits 30:16), external (bit 11), timer (bit 7), software (bit 3).\n- The value is purely combinational; no storage.\n- This register is used externally to detect pending interrupts (e.g., for WFI wake‑up).\n\n### 4. Debug-Mode CSRs\n\nAll debug CSRs are accessible **only when the core is in Debug Mode**. Access from any other mode shall cause an illegal instruction exception.\n\n#### 4.1 `dcsr` (Debug Control and Status) – Address `0x7B0`\n- Fields:\n - Bits 31:28 (`xdebugver`): Hardwired to `4’b0100` (external debug support).\n - Bit 15 (`ebreakm`): Controls behavior of `EBREAK` in M-Mode (0 = trap to M-Mode, 1 = enter Debug Mode).\n - Bit 12 (`ebreaku`): Controls behavior of `EBREAK` in U-Mode (0 = trap to M-Mode, 1 = enter Debug Mode). WARL.\n - Bits 8:6 (`cause`): Read-only; indicates reason for entering Debug Mode (1=EBREAK, 3=halt, 4=step).\n - Bit 2 (`step`): When set, single-step an instruction and re‑enter Debug Mode.\n - Bits 1:0 (`prv`): Privilege level at debug entry. Can be modified by debugger (WARL, only M-Mode and U-Mode allowed).\n - Other bits are reserved and read as 0; writes to them are ignored.\n- Reset value: `0x4000_0003` (xdebugver=4, step=0, prv=M-Mode).\n\n#### 4.2 `dpc` (Debug PC) – Address `0x7B1`\n- On Debug Mode entry, the PC of the next instruction to be executed is saved (LSB forced to 0).\n- On Debug Mode exit (DRET), the core jumps to the address in `dpc`.\n- Read/Write. Writes must align to 2 bytes. Reset value: `0x0000_0000`.\n\n#### 4.3 `dscratch0` and `dscratch1` (Debug Scratch Registers) – Addresses `0x7B2` and `0x7B3`\n- General-purpose scratch registers for use by the debug module.\n- Read/Write. No special behavior. Reset value: `0x0000_0000`.\n\n### 5. PMP (Physical Memory Protection) CSRs\n\nIf the PMP feature is enabled, the module implements up to 16 PMP regions.\n\n#### 5.1 PMP Configuration Registers (`pmpcfg0`–`pmpcfg3`) – Addresses `0x3A0`–`0x3A3`\n- Each register packs four 8‑bit configuration fields (one per region).\n- For each region the fields are: L (lock, bit 7), reserved (bits 6:5, read‑as‑0), A (mode, bits 4:3), X (execute, bit 2), W (write, bit 1), R (read, bit 0).\n- Modes: OFF (00), TOR (01), NA4 (10, only if granularity=0), NAPOT (11). Unsupported modes are treated as OFF.\n- The combination W=1,R=0 is illegal; the core forces W to 0 if R=0.\n- Write to a locked region is ignored.\n- All fields are WARL. Reset value: `0x0000_0000`.\n\n#### 5.2 PMP Address Registers (`pmpaddr0`–`pmpaddr15`) – Addresses `0x3B0`–`0x3BF`\n- Store the upper 32 bits of a 34‑bit physical address (bits 33:2).\n- Read data is influenced by the region’s mode and the PMP granularity parameter (bits masked accordingly).\n- Write to a locked region is ignored.\n- Write from a lower region is inhibited if the next higher region is in TOR mode (to avoid overlapping ranges).\n- Reset value: `0x0000_0000`.\n\n#### 5.3 Outputs\n- The module outputs the configuration and address for each implemented region (with address zero‑extended to 34 bits) to the PMP checker.\n\n### 6. Debug Trigger CSRs (Optional)\n\nIf debug triggers are enabled, the module supports a single trigger (address match).\n\n- **`tselect`** (Address `0x7A0`): Selects trigger index (always reads 0; only one trigger). Writes are ignored.\n- **`tdata1`** (Address `0x7A1`): Trigger data register 1. Most fields are read-only to reflect capabilities: type=2 (address/data match), dmode=1 (only Debug Mode writes), match=0 (exact address), action=1 (enter Debug Mode), m=1, u=1, etc. The only writable field is bit 2 (`execute`), which enables instruction address matching.\n- **`tdata2`** (Address `0x7A2`): Stores the address to match.\n- **`tdata3`** (Address `0x7A3`): Reads as 0; writes ignored.\n- **`mcontext`** (Address `0x7A8`): Reads as 0; writes ignored.\n- **`scontext`** (Address `0x7AA`): Reads as 0; writes ignored.\n- All trigger CSRs are accessible from Debug Mode (and from M-Mode only if the trigger is not native; writes from M-Mode are ignored). If not enabled, accesses cause illegal instruction exception.\n\n- The module asserts a trigger match output when the next instruction fetch PC matches `tdata2` and the `execute` bit is set. This match can be used to enter Debug Mode.\n\n### 7. Performance Monitoring CSRs\n\nThe module implements performance counters according to the RISC‑V privileged specification.\n\n#### 7.1 `mcountinhibit` (Machine Counter-Inhibit) – Address `0x320`\n- Each bit inhibits the corresponding counter when set.\n- Bit 0: `mcycle`, Bit 1: reserved (always 0), Bit 2: `minstret`, Bits 3–31: `mhpmcounter3..31`.\n- Read/Write. Reset value: `0x0000_0000` (all counters enabled).\n- Bits above the number of implemented counters are forced to 1 (inhibited) when read.\n\n#### 7.2 Machine Cycle and Retired Instruction Counters\n- `mcycle` (0xB00 / 0xB80) and `minstret` (0xB02 / 0xB82) are always 64-bit counters.\n- `mcycle` increments each cycle (unless inhibited).\n- `minstret` increments on each retired instruction (unless inhibited).\n- Both are Read/Write. Reset value: `0x0000_0000_0000_0000`.\n\n#### 7.3 Event Counters `mhpmcounter3..31` and Upper‑32‑bit versions (`mhpmcounter3H..31H`)\n- Number of implemented counters is parameterizable (0 to 29).\n- Each counter width is parameterizable (up to 64 bits). Counters 3 and above have a default width of 40 bits.\n- Unimplemented counters always read 0.\n- Each counter increments when the selected event occurs and the inhibit bit is clear. Event selection is hardwired: each counter monitors its corresponding event ID (ID = counter index; see table below).\n- All counters are Read/Write.\n\n#### 7.4 Event Selectors `mhpmevent3..31` (Addresses `0x323`–`0x33F`)\n- Read/Write but hardwired: each selector has a single bit set corresponding to its own index. Writes are ignored.\n- Reset value for selector `mhpmevent3`: `0x0000_0008` (bit 3); for selector `mhpmevent4`: `0x0000_0010`, etc.\n\n#### 7.5 Performance Events (fixed mapping)\n\n| Event ID | Event Name | Description |\n|----------|---------------------|----------------------------------------------|\n| 0 | NumCycles | Cycle count (via `mcycle`) |\n| 1 | (reserved) | Not used |\n| 2 | NumInstrRet | Instructions retired (via `minstret`) |\n| 3 | NumCyclesLSU | Cycles waiting for data memory |\n| 4 | NumCyclesIF | Cycles waiting for instruction fetches |\n| 5 | NumLoads | Number of data memory loads |\n| 6 | NumStores | Number of data memory stores |\n| 7 | NumJumps | Number of unconditional jumps |\n| 8 | NumBranches | Number of conditional branches |\n| 9 | NumBranchesTaken | Number of taken branches |\n| 10 | NumInstrRetC | Number of compressed instructions retired |\n| 11–31 | (unused) | Hardwired to 0 (no increment) |\n\n### 8. Trap Entry and Exit Behavior\n\n#### 8.1 Saving State on Trap\nWhen a trap (interrupt or exception) occurs, the module performs the following atomically:\n\n1. **Savemode**:\n - The current privilege level is saved into `mstatus.MPP`.\n - The current `mstatus.MIE` is saved into `mstatus.MPIE`.\n - `mstatus.MIE` is cleared (interrupts disabled).\n - The PC of the trapping instruction is saved into `mepc` (LSB cleared).\n - The cause is saved into `mcause`.\n - Additional information is saved into `mtval`.\n2. **Debug‑mode override**: If the trap is a debug entry (e.g., breakpoint, single‑step, halt), the above applies only to `dcsr` and `dpc`:\n - `dcsr.cause` is set to the debug cause.\n - `dcsr.prv` is set to the current privilege level.\n - `dpc` is set to the PC of the next instruction to be executed after debug entry.\n - No machine CSRs (`mepc`, `mcause`, `mtval`, `mstatus`) are modified.\n3. **Recoverable NMI support**: When entering an exception (not an interrupt) and not in Debug Mode, the module also saves the previous `mstatus.MPIE` and `mstatus.MPP` into non‑architectural internal registers, along with the current `mepc` and `mcause`. These internal registers are restored on MRET when returning from an NMI.\n\n#### 8.2 Restoring State on MRET\nOn execution of the `MRET` instruction:\n\n1. `mstatus.MIE` is set to `mstatus.MPIE`.\n2. The privilege level is set to `mstatus.MPP`.\n3. `mstatus.MPIE` is set to 1.\n4. `mstatus.MPP` is set to U-Mode.\n5. If the core is returning from an NMI (indicated by the NMI mode signal), the internal NMI backup registers are restored into `mepc`, `mcause`, `mstatus.MPIE`, and `mstatus.MPP`.\n\n#### 8.3 Restoring State on DRET\nOn execution of the `DRET` instruction:\n\n1. The privilege level is set to `dcsr.prv`.\n2. The PC is set to `dpc`.\n\n### 9. Interrupt Qualification\n\nThe module generates:\n\n- An `irq_pending` output indicating the logical OR of all qualified interrupts.\n- A qualified interrupt vector output: `mip` ANDed with `mie`.\n- The highest‑priority pending interrupt is handled by the core according to standard RISC‑V priority (higher interrupt ID = higher priority, except timer has lowest).\n\nAll interrupts are level‑sensitive. In Debug Mode, all interrupts (including NMI) are ignored.\n\n### 10. Reset and Initialization\n\n- On reset, all stateful registers are initialized to their reset values.\n- The privilege level is set to M-Mode.\n- The `mtvec` register is loaded with the boot address input, with bits [7:2] forced to zero and MODE set to vectored (`2’b01`).\n- The NMI backup internal registers are initialized to a known state (MPIE=1, MPP=U-Mode, `mepc`=0, `mcause`=0).\n\n### 11. Hart ID\n\n- The `mhartid` CSR (address `0xF14`) returns the value of the `hart_id_i` input signal.\n- Read-only. Reset value is the input value.\n\n### 12. Additional Outputs\n\n- `csr_mstatus_mie`: The current value of `mstatus.MIE`.\n- `csr_mstatus_tw`: The current value of `mstatus.TW`.\n- `debug_single_step`: The current value of `dcsr.step`.\n- `debug_ebreakm`, `debug_ebreaku`: The current values of `dcsr.ebreakm` and `dcsr.ebreaku`.\n- `csr_mtvec`: The current value of `mtvec`.\n- `csr_mepc`: The current value of `mepc`.\n- `csr_depc`: The current value of `dpc`.\n\n---\n\n## Compliance\n\nThis module is compliant with:\n\n- RISC‑V Privileged Specification v1.11 (machine‑level CSRs, PMP, performance counters).\n- RISC‑V Debug Specification v0.13.2 (debug CSRs and triggers).\n- The non‑standard recoverable NMI extension (see RISC‑V ISA Manual issue #261).\n\nAll behavior described above shall be observed from the perspective of software and external debug logic. Parametric options (PMP enable, number of regions, granularity, debug trigger enable, number and width of performance counters) may affect the presence and behavior of certain registers but shall not alter the fundamental access policies or state‑saving mechanisms.", "commit_id": "f90faa6ca365e02047d456ac3ad084ecc457ada0", "timestamp": "2020-02-20T14:29:33+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "7c9c7599d2ce54fafcc9544f5d479dce7fc91695", "pr_title": "[rtl] Change misa for RV32E", "pr_body": "Following RISC-V privileged architecture version 1.11,\r\nthe \"E\" bit of misa should return the complement of the \"I\" bit.\r\n\r\nSet the \"I\" bit only if RV32E is not used.\r\n\r\nCloses lowRISC/ibex#612.", "issue_title": "CSR misa \"I\" bit value for \"E\" extension", "issue_body": "The \"I\" bit of the CSR misa is always set:\r\nhttps://github.com/lowRISC/ibex/blob/f90faa6ca365e02047d456ac3ad084ecc457ada0/rtl/ibex_cs_registers.sv#L113\r\n\r\nBut I think it should no be set if RV32E is used.\r\nThe priv spec says it 3.1.1 p. 16\r\n\r\n> The “I” bit will be set for RV32I, RV64I, RV128I base ISAs, and the “E” bit will be set for RV32E.\r\n\r\nand\r\n\r\n>The “E” bit is read-only.\r\n>Unless misa is hardwired to zero, the “E” bit always reads as the\r\n>complement of the “I” bit. An implementation that supports both RV32E and RV32I can select\r\n>RV32E by clearing the “I” bit.\r\n\r\nAny objections to the following change?\r\n```verilog\r\n| 32'(!RV32E) << 8)\r\n```", "commit_message": "[rtl] Change misa for RV32E\n\nFollowing RISC-V privileged architecture version 1.11,\nthe \"E\" bit of misa should return the complement of the \"I\" bit.\n\nSet the \"I\" bit only if RV32E is not used.\n\nCloses lowRISC/ibex#612.", "fix_patch": "diff --git a/rtl/ibex_cs_registers.sv b/rtl/ibex_cs_registers.sv\nindex 8ce5e6640a..3e8f13a72f 100644\n--- a/rtl/ibex_cs_registers.sv\n+++ b/rtl/ibex_cs_registers.sv\n@@ -105,18 +105,18 @@ module ibex_cs_registers #(\n // misa\n localparam logic [1:0] MXL = 2'd1; // M-XLEN: XLEN in M-Mode for RV32\n localparam logic [31:0] MISA_VALUE =\n- (0 << 0) // A - Atomic Instructions extension\n- | (1 << 2) // C - Compressed extension\n- | (0 << 3) // D - Double precision floating-point extension\n- | (32'(RV32E) << 4) // E - RV32E base ISA\n- | (0 << 5) // F - Single precision floating-point extension\n- | (1 << 8) // I - RV32I/64I/128I base ISA\n- | (32'(RV32M) << 12) // M - Integer Multiply/Divide extension\n- | (0 << 13) // N - User level interrupts supported\n- | (0 << 18) // S - Supervisor mode implemented\n- | (1 << 20) // U - User mode implemented\n- | (0 << 23) // X - Non-standard extensions present\n- | (32'(MXL) << 30); // M-XLEN\n+ (0 << 0) // A - Atomic Instructions extension\n+ | (1 << 2) // C - Compressed extension\n+ | (0 << 3) // D - Double precision floating-point extension\n+ | (32'(RV32E) << 4) // E - RV32E base ISA\n+ | (0 << 5) // F - Single precision floating-point extension\n+ | (32'(!RV32E) << 8) // I - RV32I/64I/128I base ISA\n+ | (32'(RV32M) << 12) // M - Integer Multiply/Divide extension\n+ | (0 << 13) // N - User level interrupts supported\n+ | (0 << 18) // S - Supervisor mode implemented\n+ | (1 << 20) // U - User mode implemented\n+ | (0 << 23) // X - Non-standard extensions present\n+ | (32'(MXL) << 30); // M-XLEN\n \n typedef struct packed {\n logic mie;\n", "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 * Control and Status Registers\n *\n * Control and Status Registers (CSRs) following the RISC-V Privileged\n * Specification, draft version 1.11\n */\n\n`include \"prim_assert.sv\"\n\nmodule ibex_cs_registers #(\n parameter bit DbgTriggerEn = 0,\n parameter int unsigned MHPMCounterNum = 8,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit PMPEnable = 0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter bit RV32E = 0,\n parameter bit RV32M = 0\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n // Hart ID\n input logic [31:0] hart_id_i,\n\n // Privilege mode\n output ibex_pkg::priv_lvl_e priv_mode_id_o,\n output ibex_pkg::priv_lvl_e priv_mode_if_o,\n output ibex_pkg::priv_lvl_e priv_mode_lsu_o,\n output logic csr_mstatus_tw_o,\n\n // mtvec\n output logic [31:0] csr_mtvec_o,\n input logic csr_mtvec_init_i,\n input logic [31:0] boot_addr_i,\n\n // Interface to registers (SRAM like)\n input logic csr_access_i,\n input ibex_pkg::csr_num_e csr_addr_i,\n input logic [31:0] csr_wdata_i,\n input ibex_pkg::csr_op_e csr_op_i,\n output logic [31:0] csr_rdata_o,\n\n // interrupts\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 nmi_mode_i,\n output logic irq_pending_o, // interrupt request pending\n output ibex_pkg::irqs_t irqs_o, // interrupt requests qualified with mie\n output logic csr_mstatus_mie_o,\n output logic [31:0] csr_mepc_o,\n\n // PMP\n output ibex_pkg::pmp_cfg_t csr_pmp_cfg_o [PMPNumRegions],\n output logic [33:0] csr_pmp_addr_o [PMPNumRegions],\n\n // debug\n input logic debug_mode_i,\n input ibex_pkg::dbg_cause_e debug_cause_i,\n input logic debug_csr_save_i,\n output logic [31:0] csr_depc_o,\n output logic debug_single_step_o,\n output logic debug_ebreakm_o,\n output logic debug_ebreaku_o,\n output logic trigger_match_o,\n\n input logic [31:0] pc_if_i,\n input logic [31:0] pc_id_i,\n\n input logic csr_save_if_i,\n input logic csr_save_id_i,\n input logic csr_restore_mret_i,\n input logic csr_restore_dret_i,\n input logic csr_save_cause_i,\n input ibex_pkg::exc_cause_e csr_mcause_i,\n input logic [31:0] csr_mtval_i,\n output logic illegal_csr_insn_o, // access to non-existent CSR,\n // with wrong priviledge level, or\n // missing write permissions\n input logic instr_new_id_i, // ID stage sees a new instr\n\n // Performance Counters\n input logic instr_ret_i, // instr retired in ID/EX stage\n input logic instr_ret_compressed_i, // compressed instr retired\n input logic imiss_i, // instr fetch\n input logic pc_set_i, // PC was set to a new value\n input logic jump_i, // jump instr seen (j, jr, jal, jalr)\n input logic branch_i, // branch instr seen (bf, bnf)\n input logic branch_taken_i, // branch was taken\n input logic mem_load_i, // load from memory in this cycle\n input logic mem_store_i, // store to memory in this cycle\n input logic lsu_busy_i\n);\n\n import ibex_pkg::*;\n\n // misa\n localparam logic [1:0] MXL = 2'd1; // M-XLEN: XLEN in M-Mode for RV32\n localparam logic [31:0] MISA_VALUE =\n (0 << 0) // A - Atomic Instructions extension\n | (1 << 2) // C - Compressed extension\n | (0 << 3) // D - Double precision floating-point extension\n | (32'(RV32E) << 4) // E - RV32E base ISA\n | (0 << 5) // F - Single precision floating-point extension\n | (32'(!RV32E) << 8) // I - RV32I/64I/128I base ISA\n | (32'(RV32M) << 12) // M - Integer Multiply/Divide extension\n | (0 << 13) // N - User level interrupts supported\n | (0 << 18) // S - Supervisor mode implemented\n | (1 << 20) // U - User mode implemented\n | (0 << 23) // X - Non-standard extensions present\n | (32'(MXL) << 30); // M-XLEN\n\n typedef struct packed {\n logic mie;\n logic mpie;\n priv_lvl_e mpp;\n logic mprv;\n logic tw;\n } Status_t;\n\n typedef struct packed {\n logic mpie;\n priv_lvl_e mpp;\n } StatusStk_t;\n\n typedef struct packed {\n x_debug_ver_e xdebugver;\n logic [11:0] zero2;\n logic ebreakm;\n logic zero1;\n logic ebreaks;\n logic ebreaku;\n logic stepie;\n logic stopcount;\n logic stoptime;\n dbg_cause_e cause;\n logic zero0;\n logic mprven;\n logic nmip;\n logic step;\n priv_lvl_e prv;\n } Dcsr_t;\n\n // Interrupt and exception control signals\n logic [31:0] exception_pc;\n\n // CSRs\n priv_lvl_e priv_lvl_q, priv_lvl_d;\n Status_t mstatus_q, mstatus_d;\n irqs_t mie_q, mie_d;\n logic [31:0] mscratch_q, mscratch_d;\n logic [31:0] mepc_q, mepc_d;\n logic [5:0] mcause_q, mcause_d;\n logic [31:0] mtval_q, mtval_d;\n logic [31:0] mtvec_q, mtvec_d;\n irqs_t mip;\n Dcsr_t dcsr_q, dcsr_d;\n logic [31:0] depc_q, depc_d;\n logic [31:0] dscratch0_q, dscratch0_d;\n logic [31:0] dscratch1_q, dscratch1_d;\n\n // CSRs for recoverable NMIs\n // NOTE: these CSRS are nonstandard, see https://github.com/riscv/riscv-isa-manual/issues/261\n StatusStk_t mstack_q, mstack_d;\n logic [31:0] mstack_epc_q, mstack_epc_d;\n logic [5:0] mstack_cause_q, mstack_cause_d;\n\n // PMP Signals\n logic [31:0] pmp_addr_rdata [PMP_MAX_REGIONS];\n logic [PMP_CFG_W-1:0] pmp_cfg_rdata [PMP_MAX_REGIONS];\n\n // Hardware performance monitor signals\n logic [31:0] mcountinhibit;\n // Only have mcountinhibit flops for counters that actually exist\n logic [MHPMCounterNum+3-1:0] mcountinhibit_d, mcountinhibit_q;\n logic mcountinhibit_we;\n\n logic [63:0] mhpmcounter_d [32];\n // mhpmcounter flops are elaborated below providing only the precise number that is required based\n // on MHPMCounterNum/MHPMCounterWidth. This signal connects to the Q output of these flops\n // where they exist and is otherwise 0.\n logic [63:0] mhpmcounter [32];\n logic [31:0] mhpmcounter_we;\n logic [31:0] mhpmcounterh_we;\n logic [31:0] mhpmcounter_incr;\n logic [31:0] mhpmevent [32];\n logic [4:0] mhpmcounter_idx;\n\n // Debug / trigger registers\n logic [31:0] tselect_rdata;\n logic [31:0] tmatch_control_rdata;\n logic [31:0] tmatch_value_rdata;\n\n // CSR update logic\n logic [31:0] csr_wdata_int;\n logic [31:0] csr_rdata_int;\n logic csr_we_int;\n logic csr_wreq;\n\n // Access violation signals\n logic illegal_csr;\n logic illegal_csr_priv;\n logic illegal_csr_write;\n\n logic [7:0] unused_boot_addr;\n logic [2:0] unused_csr_addr;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n\n /////////////\n // CSR reg //\n /////////////\n\n logic [$bits(csr_num_e)-1:0] csr_addr;\n assign csr_addr = {csr_addr_i};\n assign unused_csr_addr = csr_addr[7:5];\n assign mhpmcounter_idx = csr_addr[4:0];\n\n // See RISC-V Privileged Specification, version 1.11, Section 2.1\n assign illegal_csr_priv = (csr_addr[9:8] > {priv_lvl_q});\n assign illegal_csr_write = (csr_addr[11:10] == 2'b11) && csr_wreq;\n assign illegal_csr_insn_o = csr_access_i & (illegal_csr | illegal_csr_write | illegal_csr_priv);\n\n // mip CSR is purely combinational - must be able to re-enable the clock upon WFI\n assign mip.irq_software = irq_software_i;\n assign mip.irq_timer = irq_timer_i;\n assign mip.irq_external = irq_external_i;\n assign mip.irq_fast = irq_fast_i;\n\n // read logic\n always_comb begin\n csr_rdata_int = '0;\n illegal_csr = 1'b0;\n\n unique case (csr_addr_i)\n // mhartid: unique hardware thread id\n CSR_MHARTID: csr_rdata_int = hart_id_i;\n\n // mstatus: always M-mode, contains IE bit\n CSR_MSTATUS: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSTATUS_MIE_BIT] = mstatus_q.mie;\n csr_rdata_int[CSR_MSTATUS_MPIE_BIT] = mstatus_q.mpie;\n csr_rdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW] = mstatus_q.mpp;\n csr_rdata_int[CSR_MSTATUS_MPRV_BIT] = mstatus_q.mprv;\n csr_rdata_int[CSR_MSTATUS_TW_BIT] = mstatus_q.tw;\n end\n\n // misa\n CSR_MISA: csr_rdata_int = MISA_VALUE;\n\n // interrupt enable\n CSR_MIE: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mie_q.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mie_q.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mie_q.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mie_q.irq_fast;\n end\n\n CSR_MSCRATCH: csr_rdata_int = mscratch_q;\n\n // mtvec: trap-vector base address\n CSR_MTVEC: csr_rdata_int = mtvec_q;\n\n // mepc: exception program counter\n CSR_MEPC: csr_rdata_int = mepc_q;\n\n // mcause: exception cause\n CSR_MCAUSE: csr_rdata_int = {mcause_q[5], 26'b0, mcause_q[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: csr_rdata_int = mtval_q;\n\n // mip: interrupt pending\n CSR_MIP: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mip.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mip.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mip.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mip.irq_fast;\n end\n\n // PMP registers\n CSR_PMPCFG0: csr_rdata_int = {pmp_cfg_rdata[3], pmp_cfg_rdata[2],\n pmp_cfg_rdata[1], pmp_cfg_rdata[0]};\n CSR_PMPCFG1: csr_rdata_int = {pmp_cfg_rdata[7], pmp_cfg_rdata[6],\n pmp_cfg_rdata[5], pmp_cfg_rdata[4]};\n CSR_PMPCFG2: csr_rdata_int = {pmp_cfg_rdata[11], pmp_cfg_rdata[10],\n pmp_cfg_rdata[9], pmp_cfg_rdata[8]};\n CSR_PMPCFG3: csr_rdata_int = {pmp_cfg_rdata[15], pmp_cfg_rdata[14],\n pmp_cfg_rdata[13], pmp_cfg_rdata[12]};\n CSR_PMPADDR0: csr_rdata_int = pmp_addr_rdata[0];\n CSR_PMPADDR1: csr_rdata_int = pmp_addr_rdata[1];\n CSR_PMPADDR2: csr_rdata_int = pmp_addr_rdata[2];\n CSR_PMPADDR3: csr_rdata_int = pmp_addr_rdata[3];\n CSR_PMPADDR4: csr_rdata_int = pmp_addr_rdata[4];\n CSR_PMPADDR5: csr_rdata_int = pmp_addr_rdata[5];\n CSR_PMPADDR6: csr_rdata_int = pmp_addr_rdata[6];\n CSR_PMPADDR7: csr_rdata_int = pmp_addr_rdata[7];\n CSR_PMPADDR8: csr_rdata_int = pmp_addr_rdata[8];\n CSR_PMPADDR9: csr_rdata_int = pmp_addr_rdata[9];\n CSR_PMPADDR10: csr_rdata_int = pmp_addr_rdata[10];\n CSR_PMPADDR11: csr_rdata_int = pmp_addr_rdata[11];\n CSR_PMPADDR12: csr_rdata_int = pmp_addr_rdata[12];\n CSR_PMPADDR13: csr_rdata_int = pmp_addr_rdata[13];\n CSR_PMPADDR14: csr_rdata_int = pmp_addr_rdata[14];\n CSR_PMPADDR15: csr_rdata_int = pmp_addr_rdata[15];\n\n CSR_DCSR: begin\n csr_rdata_int = dcsr_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DPC: begin\n csr_rdata_int = depc_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH0: begin\n csr_rdata_int = dscratch0_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH1: begin\n csr_rdata_int = dscratch1_q;\n illegal_csr = ~debug_mode_i;\n end\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: csr_rdata_int = mcountinhibit;\n CSR_MHPMEVENT3,\n CSR_MHPMEVENT4, CSR_MHPMEVENT5, CSR_MHPMEVENT6, CSR_MHPMEVENT7,\n CSR_MHPMEVENT8, CSR_MHPMEVENT9, CSR_MHPMEVENT10, CSR_MHPMEVENT11,\n CSR_MHPMEVENT12, CSR_MHPMEVENT13, CSR_MHPMEVENT14, CSR_MHPMEVENT15,\n CSR_MHPMEVENT16, CSR_MHPMEVENT17, CSR_MHPMEVENT18, CSR_MHPMEVENT19,\n CSR_MHPMEVENT20, CSR_MHPMEVENT21, CSR_MHPMEVENT22, CSR_MHPMEVENT23,\n CSR_MHPMEVENT24, CSR_MHPMEVENT25, CSR_MHPMEVENT26, CSR_MHPMEVENT27,\n CSR_MHPMEVENT28, CSR_MHPMEVENT29, CSR_MHPMEVENT30, CSR_MHPMEVENT31: begin\n csr_rdata_int = mhpmevent[mhpmcounter_idx];\n end\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][31:0];\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n csr_rdata_int = mhpmcounter[mhpmcounter_idx][63:32];\n end\n\n // Debug triggers\n CSR_TSELECT: begin\n csr_rdata_int = tselect_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA1: begin\n csr_rdata_int = tmatch_control_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA2: begin\n csr_rdata_int = tmatch_value_rdata;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_TDATA3: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_MCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n CSR_SCONTEXT: begin\n csr_rdata_int = '0;\n illegal_csr = ~DbgTriggerEn;\n end\n\n default: begin\n illegal_csr = 1'b1;\n end\n endcase\n end\n\n // write logic\n always_comb begin\n exception_pc = pc_id_i;\n\n priv_lvl_d = priv_lvl_q;\n mstatus_d = mstatus_q;\n mie_d = mie_q;\n mscratch_d = mscratch_q;\n mepc_d = mepc_q;\n mcause_d = mcause_q;\n mtval_d = mtval_q;\n mtvec_d = csr_mtvec_init_i ? {boot_addr_i[31:8], 6'b0, 2'b01} : mtvec_q;\n dcsr_d = dcsr_q;\n depc_d = depc_q;\n dscratch0_d = dscratch0_q;\n dscratch1_d = dscratch1_q;\n\n mstack_d = mstack_q;\n mstack_epc_d = mstack_epc_q;\n mstack_cause_d = mstack_cause_q;\n\n mcountinhibit_we = 1'b0;\n mhpmcounter_we = '0;\n mhpmcounterh_we = '0;\n\n if (csr_we_int) begin\n unique case (csr_addr_i)\n // mstatus: IE bit\n CSR_MSTATUS: begin\n mstatus_d = '{\n mie: csr_wdata_int[CSR_MSTATUS_MIE_BIT],\n mpie: csr_wdata_int[CSR_MSTATUS_MPIE_BIT],\n mpp: priv_lvl_e'(csr_wdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW]),\n mprv: csr_wdata_int[CSR_MSTATUS_MPRV_BIT],\n tw: csr_wdata_int[CSR_MSTATUS_TW_BIT]\n };\n // Convert illegal values to M-mode\n if ((mstatus_d.mpp != PRIV_LVL_M) && (mstatus_d.mpp != PRIV_LVL_U)) begin\n mstatus_d.mpp = PRIV_LVL_M;\n end\n end\n\n // interrupt enable\n CSR_MIE: begin\n mie_d.irq_software = csr_wdata_int[CSR_MSIX_BIT];\n mie_d.irq_timer = csr_wdata_int[CSR_MTIX_BIT];\n mie_d.irq_external = csr_wdata_int[CSR_MEIX_BIT];\n mie_d.irq_fast = csr_wdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW];\n end\n\n CSR_MSCRATCH: mscratch_d = csr_wdata_int;\n\n // mepc: exception program counter\n CSR_MEPC: mepc_d = {csr_wdata_int[31:1], 1'b0};\n\n // mcause\n CSR_MCAUSE: mcause_d = {csr_wdata_int[31], csr_wdata_int[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: mtval_d = csr_wdata_int;\n\n // mtvec\n // mtvec.MODE set to vectored\n // mtvec.BASE must be 256-byte aligned\n CSR_MTVEC: mtvec_d = {csr_wdata_int[31:8], 6'b0, 2'b01};\n\n CSR_DCSR: begin\n dcsr_d = csr_wdata_int;\n dcsr_d.xdebugver = XDEBUGVER_STD;\n // Change to PRIV_LVL_M if software writes an unsupported value\n if ((dcsr_d.prv != PRIV_LVL_M) && (dcsr_d.prv != PRIV_LVL_U)) begin\n dcsr_d.prv = PRIV_LVL_M;\n end\n\n // currently not supported:\n dcsr_d.nmip = 1'b0;\n dcsr_d.mprven = 1'b0;\n dcsr_d.stopcount = 1'b0;\n dcsr_d.stoptime = 1'b0;\n\n // forced to be zero\n dcsr_d.zero0 = 1'b0;\n dcsr_d.zero1 = 1'b0;\n dcsr_d.zero2 = 12'h0;\n end\n\n // dpc: debug program counter\n CSR_DPC: depc_d = {csr_wdata_int[31:1], 1'b0};\n\n CSR_DSCRATCH0: dscratch0_d = csr_wdata_int;\n CSR_DSCRATCH1: dscratch1_d = csr_wdata_int;\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: mcountinhibit_we = 1'b1;\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n mhpmcounter_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n mhpmcounterh_we[mhpmcounter_idx] = 1'b1;\n end\n\n default:;\n endcase\n end\n\n // exception controller gets priority over other writes\n unique case (1'b1)\n\n csr_save_cause_i: begin\n unique case (1'b1)\n csr_save_if_i: begin\n exception_pc = pc_if_i;\n end\n csr_save_id_i: begin\n exception_pc = pc_id_i;\n end\n default:;\n endcase\n\n // Any exception, including debug mode, causes a switch to M-mode\n priv_lvl_d = PRIV_LVL_M;\n\n if (debug_csr_save_i) begin\n // all interrupts are masked\n // do not update cause, epc, tval, epc and status\n dcsr_d.prv = priv_lvl_q;\n dcsr_d.cause = debug_cause_i;\n depc_d = exception_pc;\n end else if (!debug_mode_i) begin\n // In debug mode, \"exceptions do not update any registers. That\n // includes cause, epc, tval, dpc and mstatus.\" [Debug Spec v0.13.2, p.39]\n mtval_d = csr_mtval_i;\n mstatus_d.mie = 1'b0; // disable interrupts\n // save current status\n mstatus_d.mpie = mstatus_q.mie;\n mstatus_d.mpp = priv_lvl_q;\n mepc_d = exception_pc;\n mcause_d = {csr_mcause_i};\n // save previous status for recoverable NMI\n mstack_d.mpie = mstatus_q.mpie;\n mstack_d.mpp = mstatus_q.mpp;\n mstack_epc_d = mepc_q;\n mstack_cause_d = mcause_q;\n end\n end // csr_save_cause_i\n\n csr_restore_dret_i: begin // DRET\n priv_lvl_d = dcsr_q.prv;\n end // csr_restore_dret_i\n\n csr_restore_mret_i: begin // MRET\n priv_lvl_d = mstatus_q.mpp;\n mstatus_d.mie = mstatus_q.mpie; // re-enable interrupts\n\n if (nmi_mode_i) begin\n // when returning from an NMI restore state from mstack CSR\n mstatus_d.mpie = mstack_q.mpie;\n mstatus_d.mpp = mstack_q.mpp;\n mepc_d = mstack_epc_q;\n mcause_d = mstack_cause_q;\n end else begin\n // otherwise just set mstatus.MPIE/MPP\n // See RISC-V Privileged Specification, version 1.11, Section 3.1.6.1\n mstatus_d.mpie = 1'b1;\n mstatus_d.mpp = PRIV_LVL_U;\n end\n end // csr_restore_mret_i\n\n default:;\n endcase\n end\n\n // CSR operation logic\n always_comb begin\n csr_wreq = 1'b1;\n\n unique case (csr_op_i)\n CSR_OP_WRITE: csr_wdata_int = csr_wdata_i;\n CSR_OP_SET: csr_wdata_int = csr_wdata_i | csr_rdata_o;\n CSR_OP_CLEAR: csr_wdata_int = ~csr_wdata_i & csr_rdata_o;\n CSR_OP_READ: begin\n csr_wdata_int = csr_wdata_i;\n csr_wreq = 1'b0;\n end\n default: begin\n csr_wdata_int = csr_wdata_i;\n csr_wreq = 1'b0;\n end\n endcase\n end\n\n // only write CSRs during one clock cycle\n assign csr_we_int = csr_wreq & ~illegal_csr_insn_o & instr_new_id_i;\n\n assign csr_rdata_o = csr_rdata_int;\n\n // directly output some registers\n assign csr_mepc_o = mepc_q;\n assign csr_depc_o = depc_q;\n assign csr_mtvec_o = mtvec_q;\n\n assign csr_mstatus_mie_o = mstatus_q.mie;\n assign csr_mstatus_tw_o = mstatus_q.tw;\n assign debug_single_step_o = dcsr_q.step;\n assign debug_ebreakm_o = dcsr_q.ebreakm;\n assign debug_ebreaku_o = dcsr_q.ebreaku;\n\n // Qualify incoming interrupt requests in mip CSR with mie CSR for controller and to re-enable\n // clock upon WFI (must be purely combinational).\n assign irqs_o = mip & mie_q;\n assign irq_pending_o = |irqs_o;\n\n // actual registers\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n priv_lvl_q <= PRIV_LVL_M;\n mstatus_q <= '{\n mie: 1'b0,\n mpie: 1'b1,\n mpp: PRIV_LVL_U,\n mprv: 1'b0,\n tw: 1'b0\n };\n mie_q <= '0;\n mscratch_q <= '0;\n mepc_q <= '0;\n mcause_q <= '0;\n mtval_q <= '0;\n mtvec_q <= 32'b01;\n dcsr_q <= '{\n xdebugver: XDEBUGVER_STD,\n cause: DBG_CAUSE_NONE, // 3'h0\n prv: PRIV_LVL_M,\n default: '0\n };\n depc_q <= '0;\n dscratch0_q <= '0;\n dscratch1_q <= '0;\n\n mstack_q <= '{\n mpie: 1'b1,\n mpp: PRIV_LVL_U\n };\n mstack_epc_q <= '0;\n mstack_cause_q <= '0;\n\n end else begin\n // update CSRs\n priv_lvl_q <= priv_lvl_d;\n mstatus_q <= mstatus_d;\n mie_q <= mie_d;\n mscratch_q <= mscratch_d;\n mepc_q <= mepc_d;\n mcause_q <= mcause_d;\n mtval_q <= mtval_d;\n mtvec_q <= mtvec_d;\n dcsr_q <= dcsr_d;\n depc_q <= depc_d;\n dscratch0_q <= dscratch0_d;\n dscratch1_q <= dscratch1_d;\n\n mstack_q <= mstack_d;\n mstack_epc_q <= mstack_epc_d;\n mstack_cause_q <= mstack_cause_d;\n\n end\n end\n\n // Send current priv level to the decoder\n assign priv_mode_id_o = priv_lvl_q;\n // New instruction fetches need to account for updates to priv_lvl_q this cycle\n assign priv_mode_if_o = priv_lvl_d;\n // Load/store instructions must factor in MPRV for PMP checking\n assign priv_mode_lsu_o = mstatus_q.mprv ? mstatus_q.mpp : priv_lvl_q;\n\n // -----------------\n // PMP registers\n // -----------------\n\n if (PMPEnable) begin : g_pmp_registers\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n logic [31:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n logic [PMPNumRegions-1:0] pmp_addr_we;\n\n // Expanded / qualified register read data\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_exp_rd_data\n if (i < PMPNumRegions) begin : g_implemented_regions\n // Add in zero padding for reserved fields\n assign pmp_cfg_rdata[i] = {pmp_cfg[i].lock, 2'b00, pmp_cfg[i].mode,\n pmp_cfg[i].exec, pmp_cfg[i].write, pmp_cfg[i].read};\n\n // Address field read data depends on the current programmed mode and the granularity\n // See RISC-V Privileged Specification, version 1.11, Section 3.6.1\n if (PMPGranularity == 0) begin : g_pmp_g0\n // If G == 0, read data is unmodified\n assign pmp_addr_rdata[i] = pmp_addr[i];\n\n end else if (PMPGranularity == 1) begin : g_pmp_g1\n // If G == 1, bit [G-1] reads as zero in TOR or OFF mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n\n end else begin : g_pmp_g2\n // For G >= 2, bits are masked to one or zero depending on the mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n // In TOR or OFF mode, bits [G-1:0] must read as zero\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end else if (pmp_cfg[i].mode == PMP_MODE_NAPOT) begin\n // In NAPOT mode, bits [G-2:0] must read as one\n pmp_addr_rdata[i][PMPGranularity-2:0] = '1;\n end\n end\n end\n\n end else begin : g_other_regions\n // Non-implemented regions read as zero\n assign pmp_cfg_rdata[i] = '0;\n assign pmp_addr_rdata[i] = '0;\n end\n end\n\n // Write data calculation\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_pmp_csrs\n // -------------------------\n // Instantiate cfg registers\n // -------------------------\n assign pmp_cfg_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_CFG + (i[11:0] >> 2)));\n\n // Select the correct WDATA (each CSR contains 4 CFG fields, each with 2 RES bits)\n assign pmp_cfg_wdata[i].lock = csr_wdata_int[(i%4)*PMP_CFG_W+7];\n // NA4 mode is not selectable when G > 0, mode is treated as OFF\n always_comb begin\n unique case (csr_wdata_int[(i%4)*PMP_CFG_W+3+:2])\n 2'b00 : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n 2'b01 : pmp_cfg_wdata[i].mode = PMP_MODE_TOR;\n 2'b10 : pmp_cfg_wdata[i].mode = (PMPGranularity == 0) ? PMP_MODE_NA4:\n PMP_MODE_OFF;\n 2'b11 : pmp_cfg_wdata[i].mode = PMP_MODE_NAPOT;\n default : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n endcase\n end\n assign pmp_cfg_wdata[i].exec = csr_wdata_int[(i%4)*PMP_CFG_W+2];\n // W = 1, R = 0 is a reserved combination. For now, we force W to 0 if R == 0\n assign pmp_cfg_wdata[i].write = &csr_wdata_int[(i%4)*PMP_CFG_W+:2];\n assign pmp_cfg_wdata[i].read = csr_wdata_int[(i%4)*PMP_CFG_W];\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pmp_cfg[i] <= pmp_cfg_t'('b0);\n end else if (pmp_cfg_we[i]) begin\n pmp_cfg[i] <= pmp_cfg_wdata[i];\n end\n end\n\n // --------------------------\n // Instantiate addr registers\n // --------------------------\n if (i < PMPNumRegions - 1) begin : g_lower\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (pmp_cfg[i+1].mode != PMP_MODE_TOR) &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end else begin : g_upper\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pmp_addr[i] <= 'b0;\n end else if (pmp_addr_we[i]) begin\n pmp_addr[i] <= csr_wdata_int;\n end\n end\n assign csr_pmp_cfg_o[i] = pmp_cfg[i];\n assign csr_pmp_addr_o[i] = {pmp_addr[i],2'b00};\n end\n\n end else begin : g_no_pmp_tieoffs\n // Generate tieoffs when PMP is not configured\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_rdata\n assign pmp_addr_rdata[i] = '0;\n assign pmp_cfg_rdata[i] = '0;\n end\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_outputs\n assign csr_pmp_cfg_o[i] = pmp_cfg_t'(1'b0);\n assign csr_pmp_addr_o[i] = '0;\n end\n end\n\n //////////////////////////\n // Performance monitor //\n //////////////////////////\n\n // update enable signals\n always_comb begin : mcountinhibit_update\n if (mcountinhibit_we == 1'b1) begin\n mcountinhibit_d = {csr_wdata_int[MHPMCounterNum+2:2], 1'b0, csr_wdata_int[0]}; // bit 1 must always be 0\n end else begin\n mcountinhibit_d = mcountinhibit_q;\n end\n end\n\n // event selection (hardwired) & control\n always_comb begin : gen_mhpmcounter_incr\n\n // When adding or altering performance counter meanings and default\n // mappings please update dv/verilator/pcount/cpp/ibex_pcounts.cc\n // appropriately.\n //\n // active counters\n mhpmcounter_incr[0] = 1'b1; // mcycle\n mhpmcounter_incr[1] = 1'b0; // reserved\n mhpmcounter_incr[2] = instr_ret_i; // minstret\n mhpmcounter_incr[3] = lsu_busy_i; // cycles waiting for data memory\n mhpmcounter_incr[4] = imiss_i & ~pc_set_i; // cycles waiting for instr fetches\n // excl. jump and branch set cycles\n mhpmcounter_incr[5] = mem_load_i; // num of loads\n mhpmcounter_incr[6] = mem_store_i; // num of stores\n mhpmcounter_incr[7] = jump_i; // num of jumps (unconditional)\n mhpmcounter_incr[8] = branch_i; // num of branches (conditional)\n mhpmcounter_incr[9] = branch_taken_i; // num of taken branches (conditional)\n mhpmcounter_incr[10] = instr_ret_compressed_i; // num of compressed instr\n\n // inactive counters\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmcounter_incr_inactive\n mhpmcounter_incr[i] = 1'b0;\n end\n end\n\n // event selector (hardwired, 0 means no event)\n always_comb begin : gen_mhpmevent\n\n // activate all\n for (int i=0; i<32; i++) begin : gen_mhpmevent_active\n mhpmevent[i] = '0;\n mhpmevent[i][i] = 1'b1;\n end\n\n // deactivate\n mhpmevent[1] = '0; // not existing, reserved\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmevent_inactive\n mhpmevent[i] = '0;\n end\n end\n\n // update\n always_comb begin : mhpmcounter_update\n mhpmcounter_d = mhpmcounter;\n\n for (int i=0; i<32; i++) begin : gen_mhpmcounter_update\n\n // increment\n if (mhpmcounter_incr[i] & ~mcountinhibit[i]) begin\n mhpmcounter_d[i] = mhpmcounter[i] + 64'h1;\n end\n\n // write\n if (mhpmcounter_we[i]) begin\n mhpmcounter_d[i][31: 0] = csr_wdata_int;\n end else if (mhpmcounterh_we[i]) begin\n mhpmcounter_d[i][63:32] = csr_wdata_int;\n end\n end\n end\n\n // Performance monitor registers\n // Only elaborate flops that are needed from the given MHPMCounterWidth and MHPMCounterNum\n // parameters\n for (genvar i = 0; i < 32; i++) begin : g_mhpmcounter\n // First 3 counters (cycle, time, instret) must always be elaborated\n if (i < 3 + MHPMCounterNum) begin : g_mhpmcounter_exists\n // First 3 counters must be 64-bit the rest have parameterisable width\n localparam int unsigned IMHPMCounterWidth = i < 3 ? 64 : MHPMCounterWidth;\n\n logic [IMHPMCounterWidth-1:0] mhpmcounter_q;\n\n always @(posedge clk_i or negedge rst_ni) begin\n if(~rst_ni) begin\n mhpmcounter_q <= '0;\n end else begin\n mhpmcounter_q <= mhpmcounter_d[i][IMHPMCounterWidth-1:0];\n end\n end\n\n if (IMHPMCounterWidth < 64) begin : g_mhpmcounter_narrow\n assign mhpmcounter[i][IMHPMCounterWidth-1:0] = mhpmcounter_q;\n assign mhpmcounter[i][63:IMHPMCounterWidth] = '0;\n end else begin : g_mhpmcounter_full\n assign mhpmcounter[i] = mhpmcounter_q;\n end\n end else begin : g_no_mhpmcounter\n assign mhpmcounter[i] = '0;\n end\n end\n\n if(MHPMCounterNum < 29) begin : g_mcountinhibit_reduced\n assign mcountinhibit = {{29-MHPMCounterNum{1'b1}}, mcountinhibit_q};\n end else begin : g_mcountinhibit_full\n assign mcountinhibit = mcountinhibit_q;\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n mcountinhibit_q <= '0;\n end else begin\n mcountinhibit_q <= mcountinhibit_d;\n end\n end\n\n /////////////////////////////\n // Debug trigger registers //\n /////////////////////////////\n\n if (DbgTriggerEn) begin : gen_trigger_regs\n // Register values\n logic tmatch_control_d, tmatch_control_q;\n logic [31:0] tmatch_value_d, tmatch_value_q;\n // Write enables\n logic tmatch_control_we;\n logic tmatch_value_we;\n\n // Write select\n assign tmatch_control_we = csr_we_int & debug_mode_i & (csr_addr_i == CSR_TDATA1);\n assign tmatch_value_we = csr_we_int & debug_mode_i & (csr_addr_i == CSR_TDATA2);\n\n // tmatch_control is enabled when the execute bit is set\n assign tmatch_control_d = tmatch_control_we ? csr_wdata_int[2] :\n tmatch_control_q;\n // tmatch_value has its own clock gate\n assign tmatch_value_d = csr_wdata_int[31:0];\n\n // Registers\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n tmatch_control_q <= 'b0;\n end else begin\n tmatch_control_q <= tmatch_control_d;\n end\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n tmatch_value_q <= 'b0;\n end else if (tmatch_value_we) begin\n tmatch_value_q <= tmatch_value_d;\n end\n end\n\n // Assign read data\n // TSELECT - only one supported\n assign tselect_rdata = 'b0;\n // TDATA0 - only support simple address matching\n assign tmatch_control_rdata = {4'h2, // type : address/data match\n 1'b1, // dmode : access from D mode only\n 6'h00, // maskmax : exact match only\n 1'b0, // hit : not supported\n 1'b0, // select : address match only\n 1'b0, // timing : match before execution\n 2'b00, // sizelo : match any access\n 4'h1, // action : enter debug mode\n 1'b0, // chain : not supported\n 4'h0, // match : simple match\n 1'b1, // m : match in m-mode\n 1'b0, // 0 : zero\n 1'b0, // s : not supported\n 1'b1, // u : match in u-mode\n tmatch_control_q, // execute : match instruction address\n 1'b0, // store : not supported\n 1'b0}; // load : not supported\n // TDATA1 - address match value only\n assign tmatch_value_rdata = tmatch_value_q;\n\n // Breakpoint matching\n // We match against the next address, as the breakpoint must be taken before execution\n assign trigger_match_o = tmatch_control_q & (pc_if_i[31:0] == tmatch_value_q[31:0]);\n\n end else begin : gen_no_trigger_regs\n assign tselect_rdata = 'b0;\n assign tmatch_control_rdata = 'b0;\n assign tmatch_value_rdata = 'b0;\n assign trigger_match_o = 'b0;\n end\n\n ////////////////\n // Assertions //\n ////////////////\n\n // Selectors must be known/valid.\n `ASSERT(IbexCsrOpValid, csr_op_i inside {\n CSR_OP_READ,\n CSR_OP_WRITE,\n CSR_OP_SET,\n CSR_OP_CLEAR\n })\n `ASSERT_KNOWN(IbexCsrWdataIntKnown, csr_wdata_int)\n\nendmodule\n", "selected_doc_paths": ["doc/cs_registers.rst", "doc/exception_interrupts.rst", "doc/debug.rst", "doc/pmp.rst", "doc/performance_counters.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 408, "lang": "sv", "rtl_files": ["rtl/ibex_tracer.sv"], "spec": "# ibex_tracer Behavioral Specification\n\n## Overview\n\nThe `ibex_tracer` module observes the execution of instructions in a RISC-V core via the RISC-V Formal Interface (RVFI) and produces a human-readable trace log file during simulation. The trace output, formatted similarly to an objdump disassembly, facilitates debugging and performance analysis by correlating static program information with runtime values of registers and memory.\n\nThe module is intended for simulation environments only and is not required to be synthesizable.\n\n## Inputs\n\nThe tracer receives the following information for each instruction, as defined by the [RISC-V Formal Interface (RVFI)](https://github.com/SymbioticEDA/riscv-formal/blob/master/docs/rvfi.md):\n\n- **Clock and reset** – Standard synchronous reset and clock.\n- **Hart identifier** – A 32‑bit value identifying the core (hart) being traced.\n- **Instruction validity** – A signal that indicates when all other RVFI signals are valid for a retired instruction.\n- **Instruction word** – The 32‑bit encoding of the executed instruction.\n- **Program counters** – The PC of the instruction (`pc_rdata`) and the next PC (`pc_wdata`).\n- **Source register addresses and data** – Addresses and values of up to two source registers (`rs1`, `rs2`).\n- **Destination register address and data** – Address and written value of the destination register (`rd`).\n- **Memory access information** – Address, read mask, write mask, read data, and write data for the instruction’s memory operation (if any).\n- **Additional RVFI fields** – Order, trap, halt, interrupt, and privilege mode signals (currently unused but defined for future compatibility).\n\n## Output\n\nThe tracer produces a single text file per simulation run. The file is written to disk during simulation and closed upon simulation termination.\n\n### File Naming\n\nThe default file name is:\n\n```\ntrace_core_.log\n```\n\nwhere `` is the 8‑digit hexadecimal representation of the `hart_id` input.\n\nThe file name base (the part before the underscore) can be overridden by the simulation plusarg `ibex_tracer_file_base`. For example:\n\n```\n+ibex_tracer_file_base=my_trace\n```\n\nwould produce `my_trace_.log`.\n\n### Output Format\n\nThe trace file contains tab‑separated columns. A header line is written at the beginning of the file:\n\n```\nTime\tCycle\tPC\tInsn\tDecoded instruction\tRegister and memory contents\n```\n\nEach subsequent line corresponds to one retired instruction. The columns are:\n\n| Column | Description |\n|--------|-------------|\n| **Time** | Simulation time at which the instruction was retired. |\n| **Cycle** | Number of clock cycles elapsed since the last reset of the core (rising edge after reset deassertion). |\n| **PC** | Program counter of the instruction, shown in hexadecimal. |\n| **Insn** | The instruction encoding in hexadecimal. Compressed (16‑bit) instructions are displayed as four hex digits; uncompressed (32‑bit) instructions as eight hex digits. |\n| **Decoded instruction** | Disassembly of the instruction in a format equivalent to `objdump -Mnumeric -Mno-aliases -D`. Unsigned immediate values are shown in hexadecimal (prefixed with `0x`), signed values as decimal numbers. Register names use the numeric `x` prefix (e.g., `x1`, `x2`). CSR addresses are replaced with their standard names when available. Jump and branch targets are shown as absolute addresses (PC + immediate) when the target can be determined. |\n| **Register and memory contents** | For each register accessed: reads are shown as `:`, writes as `=`. For memory accesses: the physical address is prefixed with `PA:`, followed by either `store:` (for writes) or `load:` (for reads). For instructions that perform both a store and a load, both are shown. All values are in 8‑digit hexadecimal. |\n\n#### Example Lines\n\n```\n 130 61 00000150 4481 c.li x9,0 x9=0x00000000\n 142 67 0000015c c622 c.swsp x8,12(x2) x2:0x00002000 x8:0x00000000 PA:0x0000200c store:0x00000000 load:0xffffffff\n```\n\n## Functional Behavior\n\n### Activation\n\nThe tracer writes a trace line for every clock cycle in which the instruction validity signal is asserted. No line is written when the validity signal is low, even if other RVFI signals change.\n\n### Decoding Rules\n\nThe tracer shall decode every valid instruction according to the RISC‑V instruction set (RV32I and RV32C base, plus the M extension for multiplication/division). The following instructions are explicitly recognized:\n\n- **Loads and stores** – All standard width variants (byte, halfword, word, unsigned byte/halfword). Decoded as `lb`, `lh`, `lw`, `lbu`, `lhu`, `sb`, `sh`, `sw`.\n- **Arithmetic and logical** – `add`, `sub`, `sll`, `slt`, `sltu`, `xor`, `srl`, `sra`, `or`, `and`, `addi`, `slti`, `sltiu`, `xori`, `ori`, `andi`, `slli`, `srli`, `srai`.\n- **Immediate-wide** – `lui`, `auipc`.\n- **Jumps and branches** – `jal`, `jalr`, `beq`, `bne`, `blt`, `bge`, `bltu`, `bgeu`.\n- **CSR access** – `csrrw`, `csrrs`, `csrrc`, `csrrwi`, `csrrsi`, `csrrci`. CSR addresses are decoded to their standard names (e.g., `mstatus`, `mepc`, `cycle`, etc.). Unrecognized CSR addresses are shown in hex.\n- **System instructions** – `ecall`, `ebreak`, `mret`, `dret`, `wfi`.\n- **Fence instructions** – `fence` (with predecessor/successor set descriptions), `fence.i`.\n- **Multiplication/Division (M extension)** – `mul`, `mulh`, `mulhsu`, `mulhu`, `div`, `divu`, `rem`, `remu`.\n- **Compressed instructions** – All standard RV32C instructions are decoded: `c.addi4spn`, `c.lw`, `c.sw`, `c.addi`, `c.jal`, `c.j`, `c.li`, `c.lui` / `c.addi16sp`, `c.srli`, `c.srai`, `c.andi`, `c.sub`, `c.xor`, `c.or`, `c.and`, `c.beqz`, `c.bnez`, `c.slli`, `c.lwsp`, `c.swsp`, `c.jr`, `c.mv`, `c.jalr`, `c.add`, `c.ebreak`. Invalid compressed encodings produce `c.unimp` or `INVALID` as appropriate.\n\nAny instruction pattern that does not match a known encoding shall be decoded as `INVALID`.\n\nFor `addi` with immediate zero and destination register zero (`x0`), the decoder currently produces `addi x0,x0,0` rather than a `nop` mnemonic.\n\n### Registers and Memory Access Indicators\n\nThe tracer determines which items (registers and memory) were accessed during an instruction based on the instruction type. The displayed content includes:\n\n- **All source registers** that are read.\n- **The destination register** that is written.\n- **Memory address and data** when a load or store occurs.\n\nFor compressed instructions where the destination and a source register are the same (e.g., `c.add` writes to a register that is also read), both read and write values are shown.\n\n### Cycle Counter\n\nThe tracer maintains a cycle counter that increments on every rising clock edge when reset is not asserted. It resets to zero when reset is asserted. The cycle count is reported in the second column of the trace.\n\n### File Management\n\n- The output file is opened on the first valid instruction received after reset or simulation start. At that point the header line is written.\n- The file is closed once the simulation ends (via the SystemVerilog `final` block). No further writes occur after file closure.\n- If the file cannot be opened, the tracer shall issue a user‑visible message indicating the file name being written.\n\n## Configuration\n\nThe simulation plusarg `ibex_tracer_file_base` sets the base name of the trace file. It defaults to `\"trace_core\"` if not provided. The plusarg is read once at the time the first instruction is traced. Changing the plusarg after the first transaction has no effect.\n\n## Constraints and Limitations\n\n- The tracer is a simulation‑only module. It must not be mapped into a synthesized netlist.\n- It assumes that the RVFI signals are valid for exactly one clock cycle per retired instruction and that they remain stable during that cycle.\n- The tracer does not perform formal verification; it only logs information for debug and analysis.\n- Instruction decoding follows the RV32I base ISA with the C and M extensions. No other extensions (e.g., A, F, D) are supported. Instructions from unsupported extensions will be decoded as `INVALID`.\n- The cycle counter is a simple incrementer; it may wrap around after `2^32` cycles.\n- The output file format uses tab separators. Fields containing spaces (e.g., the decoded instruction) may contain tabs if the disassembly includes spaces, but this is not expected in the current implementation.", "commit_id": "edb33cca5679415d8fb838b7697c6d7f48c373cd", "timestamp": "2019-10-17T12:48:31+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "1c3903e2cea1b30e9ab7cc3a0dc5a249e1922739", "pr_title": "Tracer: Decode an all-zero instruction as INVALID", "pr_body": "Fixes #396", "issue_title": "[ibex_tracer] Ibex tracer improvements", "issue_body": "This is an issue to collect points that could be improved or \"beautified\" in the instruction tracer. Please feel free to modify/add to this list.\r\n\r\n1) Improve printout alignment of the trace (see example below).\r\n2) Correctly handle invalid instructions (see example below).\r\n3) Add more information about exceptions.\r\n\r\nExample snippet where an all-zero instruction is interpreted as `c.addi4spn` instead of marking it as INVALID:\r\n```\r\n23688 11839 1a110354 00000013 addi x0,x0,0 x0:0x00000000 x0=0x00000000\r\n23696 11843 1a110358 7b302573 csrrs x10,0x7b3,x0 x0:0x00000000 x10=0x00000032\r\n23700 11845 1a11035c 00100073 ebreak \r\n23708 11849 1a110360 0000 c.addi4spn x0,x2,0 x0=0x00000000\r\n23726 11858 1a110808 04c0006f jal x0,1a110854 x0=0x00000000\r\n23736 11863 1a110854 7b351073 csrrw x0,0x7b3,x10 x10:0x00000032 x0=0x00000000\r\n23744 11867 1a110858 00000517 auipc x10,0x0 x10=0x1a110858\r\n23748 11869 1a11085c 00c55513 srli x10,x10,0xc x10:0x1a110858 x10=0x0001a110\r\n``` \r\n\r\nNote: there exist other opensource RISC-V cores that have a tracer (such as [Ariane](https://github.com/pulp-platform/ariane/blob/master/src/util/)). Maybe some synergy could be leveraged here and/or the format could be aligned...\r\n\r\n\r\n\r\n", "commit_message": "Tracer: Decode an all-zero instruction as c.unimp\n\nFixes #396", "fix_patch": "diff --git a/rtl/ibex_tracer.sv b/rtl/ibex_tracer.sv\nindex 423b76d6bf..deba8e549f 100644\n--- a/rtl/ibex_tracer.sv\n+++ b/rtl/ibex_tracer.sv\n@@ -721,7 +721,14 @@ module ibex_tracer (\n end else begin\n unique casez (rvfi_insn[15:0])\n // C0 Opcodes\n- INSN_CADDI4SPN: decode_ciw_insn(\"c.addi4spn\");\n+ INSN_CADDI4SPN: begin\n+ if (rvfi_insn[12:2] == 11'h0) begin\n+ // Align with pseudo-mnemonic used by GNU binutils and LLVM's MC layer\n+ decode_mnemonic(\"c.unimp\");\n+ end else begin\n+ decode_ciw_insn(\"c.addi4spn\");\n+ end\n+ end\n INSN_CLW: decode_compressed_load_insn(\"c.lw\");\n INSN_CSW: decode_compressed_store_insn(\"c.sw\");\n // C1 Opcodes\n", "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 * Trace executed instructions in simulation\n *\n * This tracer takes execution information from the RISC-V Verification Interface (RVFI) and\n * produces a text file with a human-readable trace.\n *\n * All traced instructions are written to a log file. By default, the log file is named\n * trace_core_.log, with being the 8 digit hart ID of the core being traced.\n *\n * The file name base, defaulting to \"trace_core\" can be set using the \"ibex_tracer_file_base\"\n * plusarg passed to the simulation, e.g. \"+ibex_tracer_file_base=ibex_my_trace\". The exact syntax\n * of passing plusargs to a simulation depends on the simulator.\n *\n * The trace contains six columns, separated by tabs:\n * - The simulation time\n * - The clock cycle count since reset\n * - The program counter (PC)\n * - The instruction\n * - The decoded instruction in the same format as objdump, together with the accessed registers and\n * read/written memory values. Jumps and branches show the target address.\n * This column may be omitted if the instruction does not decode into a long form.\n * - Accessed registers and memory locations.\n *\n * Significant effort is spent to make the decoding produced by this tracer as similar as possible\n * to the one produced by objdump. This simplifies the correlation between the static program\n * information from the objdump-generated disassembly, and the runtime information from this tracer.\n */\nmodule ibex_tracer (\n input logic clk_i,\n input logic rst_ni,\n\n input logic [31:0] hart_id_i,\n\n // RVFI as described at https://github.com/SymbioticEDA/riscv-formal/blob/master/docs/rvfi.md\n // The standard interface does not have _i/_o suffixes. For consistency with the standard the\n // signals in this module don't have the suffixes either.\n input logic rvfi_valid,\n input logic [63:0] rvfi_order,\n input logic [31:0] rvfi_insn,\n input logic rvfi_trap,\n input logic rvfi_halt,\n input logic rvfi_intr,\n input logic [ 1:0] rvfi_mode,\n input logic [ 4:0] rvfi_rs1_addr,\n input logic [ 4:0] rvfi_rs2_addr,\n input logic [31:0] rvfi_rs1_rdata,\n input logic [31:0] rvfi_rs2_rdata,\n input logic [ 4:0] rvfi_rd_addr,\n input logic [31:0] rvfi_rd_wdata,\n input logic [31:0] rvfi_pc_rdata,\n input logic [31:0] rvfi_pc_wdata,\n input logic [31:0] rvfi_mem_addr,\n input logic [ 3:0] rvfi_mem_rmask,\n input logic [ 3:0] rvfi_mem_wmask,\n input logic [31:0] rvfi_mem_rdata,\n input logic [31:0] rvfi_mem_wdata\n);\n\n // These signals are part of RVFI, but not used in this module currently.\n // Keep them as part of the interface to change the tracer more easily in the future. Assigning\n // these signals to unused_* signals marks them explicitly as unused, an annotation picked up by\n // linters, including Verilator lint.\n logic [63:0] unused_rvfi_order = rvfi_order;\n logic unused_rvfi_trap = rvfi_trap;\n logic unused_rvfi_halt = rvfi_halt;\n logic unused_rvfi_intr = rvfi_intr;\n logic [ 1:0] unused_rvfi_mode = rvfi_mode;\n\n import ibex_pkg::*;\n import ibex_tracer_pkg::*;\n\n int file_handle;\n string file_name;\n\n int unsigned cycle;\n string decoded_str;\n logic insn_is_compressed;\n\n // Data items accessed during this instruction\n localparam RS1 = (1 << 0);\n localparam RS2 = (1 << 1);\n localparam RD = (1 << 2);\n localparam MEM = (1 << 3);\n logic [3:0] data_accessed;\n\n function void printbuffer_dumpline();\n string rvfi_insn_str;\n\n if (file_handle == 32'h0) begin\n string file_name_base = \"trace_core\";\n $value$plusargs(\"ibex_tracer_file_base=%s\", file_name_base);\n $sformat(file_name, \"%s_%h.log\", file_name_base, hart_id_i);\n\n $display(\"%m: Writing execution trace to %s\", file_name);\n file_handle = $fopen(file_name, \"w\");\n $fwrite(file_handle, \"Time\\tCycle\\tPC\\tInsn\\tDecoded instruction\\tRegister and memory contents\\n\");\n end\n\n // Write compressed instructions as four hex digits (16 bit word), and\n // uncompressed ones as 8 hex digits (32 bit words).\n if (insn_is_compressed) begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn[15:0]);\n end else begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn);\n end\n\n $fwrite(file_handle, \"%15t\\t%d\\t%h\\t%s\\t%s\\t\", $time, cycle, rvfi_pc_rdata, rvfi_insn_str, decoded_str);\n\n if ((data_accessed & RS1) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs1_addr), rvfi_rs1_rdata);\n end\n if ((data_accessed & RS2) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs2_addr), rvfi_rs2_rdata);\n end\n if ((data_accessed & RD) != 0) begin\n $fwrite(file_handle, \" %s=0x%08x\", reg_addr_to_str(rvfi_rd_addr), rvfi_rd_wdata);\n end\n if ((data_accessed & MEM) != 0) begin\n $fwrite(file_handle, \" PA:0x%08x\", rvfi_mem_addr);\n\n if (rvfi_mem_rmask != 4'b000) begin\n $fwrite(file_handle, \" store:0x%08x\", rvfi_mem_wdata);\n end\n if (rvfi_mem_wmask != 4'b000) begin\n $fwrite(file_handle, \" load:0x%08x\", rvfi_mem_rdata);\n end\n end\n\n $fwrite(file_handle, \"\\n\");\n endfunction\n\n\n // Format register address with \"x\" prefix, left-aligned to a fixed width of 3 characters.\n function string reg_addr_to_str(input logic [4:0] addr);\n if (addr < 10) begin\n return $sformatf(\" x%0d\", addr);\n end else begin\n return $sformatf(\"x%0d\", addr);\n end\n endfunction\n\n // Get a CSR name for a CSR address.\n function string get_csr_name(input logic [11:0] csr_addr);\n unique case (csr_addr)\n 12'd0: return \"ustatus\";\n 12'd4: return \"uie\";\n 12'd5: return \"utvec\";\n 12'd64: return \"uscratch\";\n 12'd65: return \"uepc\";\n 12'd66: return \"ucause\";\n 12'd67: return \"utval\";\n 12'd68: return \"uip\";\n 12'd1: return \"fflags\";\n 12'd2: return \"frm\";\n 12'd3: return \"fcsr\";\n 12'd3072: return \"cycle\";\n 12'd3073: return \"time\";\n 12'd3074: return \"instret\";\n 12'd3075: return \"hpmcounter3\";\n 12'd3076: return \"hpmcounter4\";\n 12'd3077: return \"hpmcounter5\";\n 12'd3078: return \"hpmcounter6\";\n 12'd3079: return \"hpmcounter7\";\n 12'd3080: return \"hpmcounter8\";\n 12'd3081: return \"hpmcounter9\";\n 12'd3082: return \"hpmcounter10\";\n 12'd3083: return \"hpmcounter11\";\n 12'd3084: return \"hpmcounter12\";\n 12'd3085: return \"hpmcounter13\";\n 12'd3086: return \"hpmcounter14\";\n 12'd3087: return \"hpmcounter15\";\n 12'd3088: return \"hpmcounter16\";\n 12'd3089: return \"hpmcounter17\";\n 12'd3090: return \"hpmcounter18\";\n 12'd3091: return \"hpmcounter19\";\n 12'd3092: return \"hpmcounter20\";\n 12'd3093: return \"hpmcounter21\";\n 12'd3094: return \"hpmcounter22\";\n 12'd3095: return \"hpmcounter23\";\n 12'd3096: return \"hpmcounter24\";\n 12'd3097: return \"hpmcounter25\";\n 12'd3098: return \"hpmcounter26\";\n 12'd3099: return \"hpmcounter27\";\n 12'd3100: return \"hpmcounter28\";\n 12'd3101: return \"hpmcounter29\";\n 12'd3102: return \"hpmcounter30\";\n 12'd3103: return \"hpmcounter31\";\n 12'd3200: return \"cycleh\";\n 12'd3201: return \"timeh\";\n 12'd3202: return \"instreth\";\n 12'd3203: return \"hpmcounter3h\";\n 12'd3204: return \"hpmcounter4h\";\n 12'd3205: return \"hpmcounter5h\";\n 12'd3206: return \"hpmcounter6h\";\n 12'd3207: return \"hpmcounter7h\";\n 12'd3208: return \"hpmcounter8h\";\n 12'd3209: return \"hpmcounter9h\";\n 12'd3210: return \"hpmcounter10h\";\n 12'd3211: return \"hpmcounter11h\";\n 12'd3212: return \"hpmcounter12h\";\n 12'd3213: return \"hpmcounter13h\";\n 12'd3214: return \"hpmcounter14h\";\n 12'd3215: return \"hpmcounter15h\";\n 12'd3216: return \"hpmcounter16h\";\n 12'd3217: return \"hpmcounter17h\";\n 12'd3218: return \"hpmcounter18h\";\n 12'd3219: return \"hpmcounter19h\";\n 12'd3220: return \"hpmcounter20h\";\n 12'd3221: return \"hpmcounter21h\";\n 12'd3222: return \"hpmcounter22h\";\n 12'd3223: return \"hpmcounter23h\";\n 12'd3224: return \"hpmcounter24h\";\n 12'd3225: return \"hpmcounter25h\";\n 12'd3226: return \"hpmcounter26h\";\n 12'd3227: return \"hpmcounter27h\";\n 12'd3228: return \"hpmcounter28h\";\n 12'd3229: return \"hpmcounter29h\";\n 12'd3230: return \"hpmcounter30h\";\n 12'd3231: return \"hpmcounter31h\";\n 12'd256: return \"sstatus\";\n 12'd258: return \"sedeleg\";\n 12'd259: return \"sideleg\";\n 12'd260: return \"sie\";\n 12'd261: return \"stvec\";\n 12'd262: return \"scounteren\";\n 12'd320: return \"sscratch\";\n 12'd321: return \"sepc\";\n 12'd322: return \"scause\";\n 12'd323: return \"stval\";\n 12'd324: return \"sip\";\n 12'd384: return \"satp\";\n 12'd3857: return \"mvendorid\";\n 12'd3858: return \"marchid\";\n 12'd3859: return \"mimpid\";\n 12'd3860: return \"mhartid\";\n 12'd768: return \"mstatus\";\n 12'd769: return \"misa\";\n 12'd770: return \"medeleg\";\n 12'd771: return \"mideleg\";\n 12'd772: return \"mie\";\n 12'd773: return \"mtvec\";\n 12'd774: return \"mcounteren\";\n 12'd832: return \"mscratch\";\n 12'd833: return \"mepc\";\n 12'd834: return \"mcause\";\n 12'd835: return \"mtval\";\n 12'd836: return \"mip\";\n 12'd928: return \"pmpcfg0\";\n 12'd929: return \"pmpcfg1\";\n 12'd930: return \"pmpcfg2\";\n 12'd931: return \"pmpcfg3\";\n 12'd944: return \"pmpaddr0\";\n 12'd945: return \"pmpaddr1\";\n 12'd946: return \"pmpaddr2\";\n 12'd947: return \"pmpaddr3\";\n 12'd948: return \"pmpaddr4\";\n 12'd949: return \"pmpaddr5\";\n 12'd950: return \"pmpaddr6\";\n 12'd951: return \"pmpaddr7\";\n 12'd952: return \"pmpaddr8\";\n 12'd953: return \"pmpaddr9\";\n 12'd954: return \"pmpaddr10\";\n 12'd955: return \"pmpaddr11\";\n 12'd956: return \"pmpaddr12\";\n 12'd957: return \"pmpaddr13\";\n 12'd958: return \"pmpaddr14\";\n 12'd959: return \"pmpaddr15\";\n 12'd2816: return \"mcycle\";\n 12'd2818: return \"minstret\";\n 12'd2819: return \"mhpmcounter3\";\n 12'd2820: return \"mhpmcounter4\";\n 12'd2821: return \"mhpmcounter5\";\n 12'd2822: return \"mhpmcounter6\";\n 12'd2823: return \"mhpmcounter7\";\n 12'd2824: return \"mhpmcounter8\";\n 12'd2825: return \"mhpmcounter9\";\n 12'd2826: return \"mhpmcounter10\";\n 12'd2827: return \"mhpmcounter11\";\n 12'd2828: return \"mhpmcounter12\";\n 12'd2829: return \"mhpmcounter13\";\n 12'd2830: return \"mhpmcounter14\";\n 12'd2831: return \"mhpmcounter15\";\n 12'd2832: return \"mhpmcounter16\";\n 12'd2833: return \"mhpmcounter17\";\n 12'd2834: return \"mhpmcounter18\";\n 12'd2835: return \"mhpmcounter19\";\n 12'd2836: return \"mhpmcounter20\";\n 12'd2837: return \"mhpmcounter21\";\n 12'd2838: return \"mhpmcounter22\";\n 12'd2839: return \"mhpmcounter23\";\n 12'd2840: return \"mhpmcounter24\";\n 12'd2841: return \"mhpmcounter25\";\n 12'd2842: return \"mhpmcounter26\";\n 12'd2843: return \"mhpmcounter27\";\n 12'd2844: return \"mhpmcounter28\";\n 12'd2845: return \"mhpmcounter29\";\n 12'd2846: return \"mhpmcounter30\";\n 12'd2847: return \"mhpmcounter31\";\n 12'd2944: return \"mcycleh\";\n 12'd2946: return \"minstreth\";\n 12'd2947: return \"mhpmcounter3h\";\n 12'd2948: return \"mhpmcounter4h\";\n 12'd2949: return \"mhpmcounter5h\";\n 12'd2950: return \"mhpmcounter6h\";\n 12'd2951: return \"mhpmcounter7h\";\n 12'd2952: return \"mhpmcounter8h\";\n 12'd2953: return \"mhpmcounter9h\";\n 12'd2954: return \"mhpmcounter10h\";\n 12'd2955: return \"mhpmcounter11h\";\n 12'd2956: return \"mhpmcounter12h\";\n 12'd2957: return \"mhpmcounter13h\";\n 12'd2958: return \"mhpmcounter14h\";\n 12'd2959: return \"mhpmcounter15h\";\n 12'd2960: return \"mhpmcounter16h\";\n 12'd2961: return \"mhpmcounter17h\";\n 12'd2962: return \"mhpmcounter18h\";\n 12'd2963: return \"mhpmcounter19h\";\n 12'd2964: return \"mhpmcounter20h\";\n 12'd2965: return \"mhpmcounter21h\";\n 12'd2966: return \"mhpmcounter22h\";\n 12'd2967: return \"mhpmcounter23h\";\n 12'd2968: return \"mhpmcounter24h\";\n 12'd2969: return \"mhpmcounter25h\";\n 12'd2970: return \"mhpmcounter26h\";\n 12'd2971: return \"mhpmcounter27h\";\n 12'd2972: return \"mhpmcounter28h\";\n 12'd2973: return \"mhpmcounter29h\";\n 12'd2974: return \"mhpmcounter30h\";\n 12'd2975: return \"mhpmcounter31h\";\n 12'd803: return \"mhpmevent3\";\n 12'd804: return \"mhpmevent4\";\n 12'd805: return \"mhpmevent5\";\n 12'd806: return \"mhpmevent6\";\n 12'd807: return \"mhpmevent7\";\n 12'd808: return \"mhpmevent8\";\n 12'd809: return \"mhpmevent9\";\n 12'd810: return \"mhpmevent10\";\n 12'd811: return \"mhpmevent11\";\n 12'd812: return \"mhpmevent12\";\n 12'd813: return \"mhpmevent13\";\n 12'd814: return \"mhpmevent14\";\n 12'd815: return \"mhpmevent15\";\n 12'd816: return \"mhpmevent16\";\n 12'd817: return \"mhpmevent17\";\n 12'd818: return \"mhpmevent18\";\n 12'd819: return \"mhpmevent19\";\n 12'd820: return \"mhpmevent20\";\n 12'd821: return \"mhpmevent21\";\n 12'd822: return \"mhpmevent22\";\n 12'd823: return \"mhpmevent23\";\n 12'd824: return \"mhpmevent24\";\n 12'd825: return \"mhpmevent25\";\n 12'd826: return \"mhpmevent26\";\n 12'd827: return \"mhpmevent27\";\n 12'd828: return \"mhpmevent28\";\n 12'd829: return \"mhpmevent29\";\n 12'd830: return \"mhpmevent30\";\n 12'd831: return \"mhpmevent31\";\n 12'd1952: return \"tselect\";\n 12'd1953: return \"tdata1\";\n 12'd1954: return \"tdata2\";\n 12'd1955: return \"tdata3\";\n 12'd1968: return \"dcsr\";\n 12'd1969: return \"dpc\";\n 12'd1970: return \"dscratch\";\n 12'd512: return \"hstatus\";\n 12'd514: return \"hedeleg\";\n 12'd515: return \"hideleg\";\n 12'd516: return \"hie\";\n 12'd517: return \"htvec\";\n 12'd576: return \"hscratch\";\n 12'd577: return \"hepc\";\n 12'd578: return \"hcause\";\n 12'd579: return \"hbadaddr\";\n 12'd580: return \"hip\";\n 12'd896: return \"mbase\";\n 12'd897: return \"mbound\";\n 12'd898: return \"mibase\";\n 12'd899: return \"mibound\";\n 12'd900: return \"mdbase\";\n 12'd901: return \"mdbound\";\n 12'd800: return \"mucounteren\";\n 12'd801: return \"mscounteren\";\n 12'd802: return \"mhcounteren\";\n default: return $sformatf(\"0x%x\", csr_addr);\n endcase\n endfunction\n\n function void decode_mnemonic(input string mnemonic);\n decoded_str = mnemonic;\n endfunction\n\n function void decode_r_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr, rvfi_rs2_addr);\n endfunction\n\n function void decode_i_insn(input string mnemonic);\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}));\n endfunction\n\n function void decode_i_shift_insn(input string mnemonic);\n // SLLI, SRLI, SRAI\n logic [4:0] shamt;\n shamt = {rvfi_insn[24:20]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,0x%0x\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr, shamt);\n endfunction\n\n function void decode_i_jalr_insn(input string mnemonic);\n // JALR\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function void decode_u_insn(input string mnemonic);\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, {rvfi_insn[31:12]});\n endfunction\n\n function void decode_j_insn(input string mnemonic);\n // JAL\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rd_addr, rvfi_pc_wdata);\n endfunction\n\n function void decode_b_insn(input string mnemonic);\n logic [31:0] branch_target;\n logic [31:0] imm;\n\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = $signed({ {19 {rvfi_insn[31]}}, rvfi_insn[31], rvfi_insn[7],\n rvfi_insn[30:25], rvfi_insn[11:8], 1'b0 });\n branch_target = rvfi_pc_rdata + imm;\n\n data_accessed = RS1 | RS2 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0x\", mnemonic, rvfi_rs1_addr, rvfi_rs2_addr, branch_target);\n endfunction\n\n function void decode_csr_insn(input string mnemonic);\n logic [11:0] csr;\n string csr_name;\n csr = rvfi_insn[31:20];\n csr_name = get_csr_name(csr);\n\n data_accessed = RD;\n\n if (!rvfi_insn[14]) begin\n data_accessed |= RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%s,x%0d\", mnemonic, rvfi_rd_addr, csr_name, rvfi_rs1_addr);\n end else begin\n decoded_str = $sformatf(\"%s\\tx%0d,%s,%0d\", mnemonic, rvfi_rd_addr, csr_name, { 27'b0, rvfi_insn[19:15]});\n end\n endfunction\n\n function void decode_cr_insn(input string mnemonic);\n if (rvfi_rs2_addr == 5'b0) begin\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d\", mnemonic, rvfi_rs1_addr);\n end else begin\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n end\n endfunction\n\n function void decode_ci_cli_insn(input string mnemonic);\n logic [5:0] imm;\n imm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n endfunction\n\n function void decode_ci_caddi_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function void decode_ci_caddi16sp_insn(input string mnemonic);\n logic [9:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[4:3], rvfi_insn[5], rvfi_insn[2], rvfi_insn[6], 4'b0};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function void decode_ci_clui_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, 20'($signed(nzimm)));\n endfunction\n\n function void decode_ci_cslli_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, shamt);\n endfunction\n\n function void decode_ciw_insn(input string mnemonic);\n // C.ADDI4SPN\n logic [9:0] nzuimm;\n nzuimm = {rvfi_insn[10:7], rvfi_insn[12:11], rvfi_insn[5], rvfi_insn[6], 2'b00};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x2,%0d\", mnemonic, rvfi_rd_addr, nzuimm);\n endfunction\n\n function void decode_cb_sr_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, shamt);\n endfunction\n\n function void decode_cb_insn(input string mnemonic);\n logic [7:0] imm;\n logic [31:0] jump_target;\n if (rvfi_insn[15:13] == 3'b110 || rvfi_insn[15:13] == 3'b111) begin\n // C.BNEZ and C.BEQZ\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = {rvfi_insn[12], rvfi_insn[6:5], rvfi_insn[2], rvfi_insn[11:10], rvfi_insn[4:3]};\n jump_target = rvfi_pc_rdata + 32'($signed({imm, 1'b0}));\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rs1_addr, jump_target);\n end else if (rvfi_insn[15:13] == 3'b100) begin\n // C.ANDI\n imm = {{2{rvfi_insn[12]}}, rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n end else begin\n imm = {rvfi_insn[12], rvfi_insn[6:2], 2'b00};\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, imm);\n end\n endfunction\n\n function void decode_cs_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n endfunction\n\n function void decode_cj_insn(input string mnemonic);\n decoded_str = $sformatf(\"%s\\t%0x\", mnemonic, rvfi_pc_wdata);\n endfunction\n\n function void decode_compressed_load_insn(input string mnemonic);\n logic [7:0] imm;\n\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.LW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.LWSP\n imm = {rvfi_insn[3:2], rvfi_insn[12], rvfi_insn[6:4], 2'b00};\n end\n data_accessed = RS1 | RD | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function void decode_compressed_store_insn(input string mnemonic);\n logic [7:0] imm;\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.SW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.SWSP\n imm = {rvfi_insn[8:7], rvfi_insn[12:9], 2'b00};\n end\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rs2_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function void decode_load_insn();\n string mnemonic;\n\n /*\n Gives wrong results in Verilator < 4.020.\n See https://github.com/lowRISC/ibex/issues/372 and\n https://www.veripool.org/issues/1536-Verilator-Misoptimization-in-if-and-case-with-default-statement-inside-a-function\n\n unique case (rvfi_insn[14:12])\n 3'b000: mnemonic = \"lb\";\n 3'b001: mnemonic = \"lh\";\n 3'b010: mnemonic = \"lw\";\n 3'b100: mnemonic = \"lbu\";\n 3'b101: mnemonic = \"lhu\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n */\n logic [2:0] size;\n size = rvfi_insn[14:12];\n if (size == 3'b000) begin\n mnemonic = \"lb\";\n end else if (size == 3'b001) begin\n mnemonic = \"lh\";\n end else if (size == 3'b010) begin\n mnemonic = \"lw\";\n end else if (size == 3'b100) begin\n mnemonic = \"lbu\";\n end else if (size == 3'b101) begin\n mnemonic = \"lhu\";\n end else begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n\n\n data_accessed = RD | RS1 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function void decode_store_insn();\n string mnemonic;\n\n unique case (rvfi_insn[13:12])\n 2'b00: mnemonic = \"sb\";\n 2'b01: mnemonic = \"sh\";\n 2'b10: mnemonic = \"sw\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n\n if (!rvfi_insn[14]) begin\n // regular store\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rs2_addr,\n $signed({ {20 {rvfi_insn[31]}}, rvfi_insn[31:25], rvfi_insn[11:7] }), rvfi_rs1_addr);\n end else begin\n decode_mnemonic(\"INVALID\");\n end\n endfunction\n\n function string get_fence_description(logic [3:0] bits);\n string desc = \"\";\n if (bits[3]) begin\n desc = {desc, \"i\"};\n end\n if (bits[2]) begin\n desc = {desc, \"o\"};\n end\n if (bits[1]) begin\n desc = {desc, \"r\"};\n end\n if (bits[0]) begin\n desc = {desc, \"w\"};\n end\n return desc;\n endfunction\n\n function void decode_fence();\n string predecessor;\n string successor;\n predecessor = get_fence_description(rvfi_insn[27:24]);\n successor = get_fence_description(rvfi_insn[23:20]);\n decoded_str = $sformatf(\"fence\\t%s,%s\", predecessor, successor);\n endfunction\n\n // cycle counter\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n cycle <= 0;\n end else begin\n cycle <= cycle + 1;\n end\n end\n\n // close output file for writing\n final begin\n if (file_handle != 32'h0) begin\n $fclose(file_handle);\n end\n end\n\n // log execution\n always_ff @(posedge clk_i) begin\n if (rvfi_valid) begin\n printbuffer_dumpline();\n end\n end\n\n always_comb begin\n decoded_str = \"\";\n data_accessed = 4'h0;\n insn_is_compressed = 0;\n\n // Check for compressed instructions\n if (rvfi_insn[1:0] != 2'b11) begin\n insn_is_compressed = 1;\n // Separate case to avoid overlapping decoding\n if (rvfi_insn[15:13] == 3'b100 && rvfi_insn[1:0] == 2'b10) begin\n if (rvfi_insn[12]) begin\n if (rvfi_insn[11:2] == 10'h0) begin\n decode_mnemonic(\"c.ebreak\");\n end else if (rvfi_insn[6:2] == 5'b0) begin\n decode_cr_insn(\"c.jalr\");\n end else begin\n decode_cr_insn(\"c.add\");\n end\n end else begin\n if (rvfi_insn[6:2] == 5'h0) begin\n decode_cr_insn(\"c.jr\");\n end else begin\n decode_cr_insn(\"c.mv\");\n end\n end\n end else begin\n unique casez (rvfi_insn[15:0])\n // C0 Opcodes\n INSN_CADDI4SPN: begin\n if (rvfi_insn[12:2] == 11'h0) begin\n // Align with pseudo-mnemonic used by GNU binutils and LLVM's MC layer\n decode_mnemonic(\"c.unimp\");\n end else begin\n decode_ciw_insn(\"c.addi4spn\");\n end\n end\n INSN_CLW: decode_compressed_load_insn(\"c.lw\");\n INSN_CSW: decode_compressed_store_insn(\"c.sw\");\n // C1 Opcodes\n INSN_CADDI: decode_ci_caddi_insn(\"c.addi\");\n INSN_CJAL: decode_cj_insn(\"c.jal\");\n INSN_CJ: decode_cj_insn(\"c.j\");\n INSN_CLI: decode_ci_cli_insn(\"c.li\");\n INSN_CLUI: begin\n // These two instructions share opcode\n if (rvfi_insn[11:7] == 5'd2) begin\n decode_ci_caddi16sp_insn(\"c.addi16sp\");\n end else begin\n decode_ci_clui_insn(\"c.lui\");\n end\n end\n INSN_CSRLI: decode_cb_sr_insn(\"c.srli\");\n INSN_CSRAI: decode_cb_sr_insn(\"c.srai\");\n INSN_CANDI: decode_cb_insn(\"c.andi\");\n INSN_CSUB: decode_cs_insn(\"c.sub\");\n INSN_CXOR: decode_cs_insn(\"c.xor\");\n INSN_COR: decode_cs_insn(\"c.or\");\n INSN_CAND: decode_cs_insn(\"c.and\");\n INSN_CBEQZ: decode_cb_insn(\"c.beqz\");\n INSN_CBNEZ: decode_cb_insn(\"c.bnez\");\n // C2 Opcodes\n INSN_CSLLI: decode_ci_cslli_insn(\"c.slli\");\n INSN_CLWSP: decode_compressed_load_insn(\"c.lwsp\");\n INSN_SWSP: decode_compressed_store_insn(\"c.swsp\");\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end else begin\n unique casez (rvfi_insn)\n // Regular opcodes\n INSN_LUI: decode_u_insn(\"lui\");\n INSN_AUIPC: decode_u_insn(\"auipc\");\n INSN_JAL: decode_j_insn(\"jal\");\n INSN_JALR: decode_i_jalr_insn(\"jalr\");\n // BRANCH\n INSN_BEQ: decode_b_insn(\"beq\");\n INSN_BNE: decode_b_insn(\"bne\");\n INSN_BLT: decode_b_insn(\"blt\");\n INSN_BGE: decode_b_insn(\"bge\");\n INSN_BLTU: decode_b_insn(\"bltu\");\n INSN_BGEU: decode_b_insn(\"bgeu\");\n // OPIMM\n INSN_ADDI: begin\n if (rvfi_insn == 32'h00_00_00_13) begin\n // TODO: objdump doesn't decode this as nop currently, even though it would be helpful\n // Decide what to do here: diverge from objdump, or make the trace less readable to\n // users.\n //decode_mnemonic(\"nop\");\n decode_i_insn(\"addi\");\n end else begin\n decode_i_insn(\"addi\");\n end\n end\n INSN_SLTI: decode_i_insn(\"slti\");\n INSN_SLTIU: decode_i_insn(\"sltiu\");\n INSN_XORI: decode_i_insn(\"xori\");\n INSN_ORI: decode_i_insn(\"ori\");\n INSN_ANDI: decode_i_insn(\"andi\");\n INSN_SLLI: decode_i_shift_insn(\"slli\");\n INSN_SRLI: decode_i_shift_insn(\"srli\");\n INSN_SRAI: decode_i_shift_insn(\"srai\");\n // OP\n INSN_ADD: decode_r_insn(\"add\");\n INSN_SUB: decode_r_insn(\"sub\");\n INSN_SLL: decode_r_insn(\"sll\");\n INSN_SLT: decode_r_insn(\"slt\");\n INSN_SLTU: decode_r_insn(\"sltu\");\n INSN_XOR: decode_r_insn(\"xor\");\n INSN_SRL: decode_r_insn(\"srl\");\n INSN_SRA: decode_r_insn(\"sra\");\n INSN_OR: decode_r_insn(\"or\");\n INSN_AND: decode_r_insn(\"and\");\n // SYSTEM (CSR manipulation)\n INSN_CSRRW: decode_csr_insn(\"csrrw\");\n INSN_CSRRS: decode_csr_insn(\"csrrs\");\n INSN_CSRRC: decode_csr_insn(\"csrrc\");\n INSN_CSRRWI: decode_csr_insn(\"csrrwi\");\n INSN_CSRRSI: decode_csr_insn(\"csrrsi\");\n INSN_CSRRCI: decode_csr_insn(\"csrrci\");\n // SYSTEM (others)\n INSN_ECALL: decode_mnemonic(\"ecall\");\n INSN_EBREAK: decode_mnemonic(\"ebreak\");\n INSN_MRET: decode_mnemonic(\"mret\");\n INSN_DRET: decode_mnemonic(\"dret\");\n INSN_WFI: decode_mnemonic(\"wfi\");\n // RV32M\n INSN_PMUL: decode_r_insn(\"mul\");\n INSN_PMUH: decode_r_insn(\"mulh\");\n INSN_PMULHSU: decode_r_insn(\"mulhsu\");\n INSN_PMULHU: decode_r_insn(\"mulhu\");\n INSN_DIV: decode_r_insn(\"div\");\n INSN_DIVU: decode_r_insn(\"divu\");\n INSN_REM: decode_r_insn(\"rem\");\n INSN_REMU: decode_r_insn(\"remu\");\n // LOAD & STORE\n INSN_LOAD: decode_load_insn();\n INSN_STORE: decode_store_insn();\n // MISC-MEM\n INSN_FENCE: decode_fence();\n INSN_FENCEI: decode_mnemonic(\"fence.i\");\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end\n\nendmodule\n", "selected_doc_paths": ["doc/tracer.rst", "doc/rvfi.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 377, "lang": "sv", "rtl_files": ["rtl/ibex_load_store_unit.sv"], "spec": "# Load-Store Unit (LSU) Behavioral Specification\n\n## Overview\n\nThe Load-Store Unit (LSU) is the interface between the processor core and the data memory system. It handles all load and store operations of words (32-bit), half-words (16-bit), and bytes (8-bit). The LSU is designed to support both aligned and misaligned memory accesses, with misaligned accesses transparently split into two word-aligned transactions. The LSU also integrates with the Physical Memory Protection (PMP) unit; PMP errors are detected and handled consistently with bus errors.\n\nThe LSU stalls the execution pipeline until the memory transaction completes (or an error is signaled). After a transaction finishes, the core’s ID/EX stage is allowed to proceed.\n\n## Supported Operations\n\n- **Load**: Read data from memory. Depending on the access size and alignment, the returned data is realigned and optionally sign-extended to 32 bits.\n- **Store**: Write data to memory. Write data and byte enables are aligned to the memory word.\n\nThe access size and type (load/store) are provided by the core together with the address and data. The LSU distinguishes between word, half-word, and byte accesses. For half-word and byte loads, sign extension is performed according to a signal from the core (unsigned or signed extension).\n\n## Interface Protocol\n\nThe LSU uses a request-grant-valid protocol to communicate with the memory system:\n\n1. **Request**: The LSU asserts a request signal and presents a word-aligned address, write enable, byte enables, and write data (for stores). All outputs remain stable until the request is granted.\n\n2. **Grant**: The memory system responds with a grant signal, indicating it has accepted the request. The grant may arrive in the same cycle as the request or in a later cycle. After the grant, the LSU is free to change the address and data outputs for the next cycle.\n\n3. **Response**: For each granted request, the memory system eventually asserts a response-valid signal for exactly one cycle, along with an error flag and read data (for loads). The response may come one or more cycles after the grant.\n\nThe LSU supports multiple outstanding requests; the memory system must return responses in the order the requests were granted. The LSU pipelines its internal state to track up to two transactions for misaligned accesses.\n\n## Address Alignment and Byte Enables\n\nThe LSU always presents a **word-aligned address** (lower two bits zero) on the memory interface. For normal (aligned) accesses, the address is simply the original address truncated to word alignment. For misaligned accesses, two separate word-aligned addresses are used.\n\nByte enables are generated according to:\n- The access size (word, half-word, byte).\n- The original address offset (the least significant two bits of the address).\n- Whether the current transaction is the first or second part of a misaligned access.\n\nThe byte enables ensure that only the intended bytes are read or written.\n\n## Misaligned Access Handling\n\nWhen the core requests a misaligned access (word crossing a word boundary, or half-word crossing a half-word boundary), the LSU automatically splits it into two word-aligned transactions. This is transparent to the core; the core provides the original address and the LSU internally sequences the two bus transactions.\n\n- For a misaligned word load/store, the first transaction covers the bytes from the original address up to the end of that word, and the second transaction covers the remaining bytes from the next word.\n- For a misaligned half-word load/store (address ending with `11`), the first transaction covers the lower part and the second covers the remaining byte/half-word.\n\nThe LSU performs the second transaction even if the first transaction resulted in an error. In that case, the second transaction is issued but its response is ignored (unless the core issues a new request while waiting for the second part – see below). The error from the first part is recorded and reported when the second part completes.\n\nWhen waiting for the completion of the second part of a misaligned access, the LSU will not accept a new request from the core until it returns to the idle state.\n\n## Byte, Half-word, and Word Handling\n\n### Store Data Alignment\n\nWrite data from the core is rotated based on the original address offset so that the correct bytes appear on the memory word-aligned data bus. The byte enables ensure only the proper bytes are written.\n\n### Load Data Realignment and Sign Extension\n\nRead data returned from memory is realigned (byte-swapped) according to the original address offset, which is stored internally when the transaction was initiated. The resulting 32-bit value is then optionally sign-extended:\n\n- For a **word** load: No sign extension; the full 32-bit realigned value is used.\n- For a **half-word** load: The selected 16-bit half-word is extended to 32 bits. If unsigned, zeros are inserted in the upper 16 bits; if signed, the most significant bit of the half-word is replicated.\n- For a **byte** load: The selected 8-bit byte is extended to 32 bits. If unsigned, zeros are inserted in the upper 24 bits; if signed, the most significant bit of the byte is replicated.\n\nThe sign extension mode (signed/unsigned) is provided by the core and stored along with the address offset until the response is processed.\n\n## Error Handling\n\nThe LSU detects two types of errors:\n\n- **Bus error** (`data_err`): Indicated by the memory system during the response-valid cycle.\n- **PMP error** (`data_pmp_err`): Indicated by the Physical Memory Protection unit during the address phase. The PMP error signal is valid only when the request is being granted (or could be granted). If a PMP error occurs, the LSU records it and treats it like a bus error; however, the external request may be blocked (i.e., no grant may arrive), so the LSU relies on the registered PMP error to proceed.\n\nErrors are recorded per transaction part. For misaligned accesses, errors from either the first or second part cause a final error status. The error is reported to the core as:\n\n- **Load error**: asserted when the final transaction of a load results in an error (bus or PMP).\n- **Store error**: asserted when the final transaction of a store results in an error.\n\nThe error signals are valid at the same time as the data-valid signal to the core.\n\nWhen an error occurs, the last address computed (original address) is captured and retained for the core’s exception handling (`mtval`). This address is not updated after an error.\n\n## Busy and Pipeline Interaction\n\nThe LSU asserts a busy signal whenever it is not in the idle state. The core uses this to stall the pipeline.\n\nWhen the core issues a request, the LSU immediately starts the transaction. The core is stalled until the LSU signals that the transaction is complete (data-valid). For loads, the read data is presented together with the data-valid. For stores, the data-valid indicates the store has completed (or errored).\n\nThe LSU also outputs an address-increment request signal to the core’s address generation unit. This signal is used during misaligned accesses to request the core to compute the address for the second part. It is also used to ensure the correct address is captured for PMP checking and exception reporting.\n\n## Last Address Storage\n\nThe LSU stores the address of the last transaction that was issued (including the first transaction of a misaligned access). This stored address is provided to the core for:\n- Exception handling (`mtval`).\n- Address generation for misaligned accesses.\n\nThe address is updated only when a new request is granted and no error has occurred on the current transaction. In case of an error, the stored address retains the address of the failing transaction.\n\n## Physical Memory Protection (PMP) Integration\n\nThe PMP check is performed on the address provided by the LSU. If a PMP error occurs, the LSU does not proceed with the external request (the grant may not come), but it records the PMP error and proceeds as if the grant had been received. The error is consumed when the core would otherwise have consumed the data.\n\nFor misaligned accesses, the PMP check is performed separately for each word-aligned part. A PMP error on the first part does not prevent the second part from being issued; the second part is still sent, but its response is ignored if the first part already caused an error. The LSU uses the PMP error signal associated with each part’s address phase.\n\n## Ordering Guarantees\n\n- The LSU issues transactions to the memory in order (first part before second part for misaligned accesses).\n- The memory system must return responses in the order the transactions were granted.\n- Between the response of one transaction and the next request, the LSU returns to idle and can accept a new request from the core.\n\n## Summary of Key Behaviors\n\n| Feature | Requirement |\n|---------|-------------|\n| Supported sizes | Word, half-word, byte |\n| Misaligned split | Two word-aligned bus transactions; transparent to core |\n| Address output | Always word-aligned |\n| Byte enables | Dynamically generated per access size, address offset, and split part |\n| Write data alignment | Rotated based on address offset |\n| Read data realignment | Rotated back per stored address offset |\n| Sign extension | For half-word and byte loads; configurable signed/unsigned |\n| Bus errors | Detected on response-valid; reported as load/store error |\n| PMP errors | Detected on address phase; treated equivalently to bus errors |\n| Error on first part of misaligned | Second part still issued; error reported when second completes |\n| Busy indication | High from request until final data-valid |\n| Last address storage | Retained until next grant; frozen on error |\n| Data-valid to core | One cycle, coincident with error flags and read data |\n| Pipeline stall | Core stalled from request until data-valid |\n\n## Exceptions and Reset\n\nUpon reset, the LSU enters an idle state. All internal state is cleared, and no transactions are outstanding. After reset, the LSU must be idle and ready to accept the first request.", "commit_id": "4a1806f16ffd87bded3201bc923da5317aec8210", "timestamp": "2019-10-09T09:07:08+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "c33525ae804e5c6200bab582f7e5d80da2aebbf9", "pr_title": "[RTL LSU] Change unaligned error behaviour", "pr_body": "- If an error is signalled in the first part of an unaligned\r\n transaction, the second part is issued anyway (to avoid a\r\n timing loop from data_err_i -> data_req_o)\r\n- Previously, the error was signalled and an exception was taken\r\n as soon as the first transaction completed. This commits makes\r\n the core wait until both transactions have completed.\r\n- This prevents strange behaviour caused by the lsu and controller\r\n being out of sync (fixes #374).", "issue_title": "DMEM fault during misaligned memory access", "issue_body": "Hi all,\r\nWhen running this set of instructions:\r\n![Screenshot from 2019-10-04 16-43-38](https://user-images.githubusercontent.com/16736281/66245995-26c70100-e6c6-11e9-8347-b284c658e62c.png)\r\nThe following waves were generated:\r\n![Screenshot from 2019-10-04 16-47-11](https://user-images.githubusercontent.com/16736281/66246078-a1901c00-e6c6-11e9-839a-a188fce292f5.png)\r\nThe `sw` instructions at `PC=0x800058d0` has a misaligned memory address, and is thus split into two internal memory transactions. In the waves, around 395,800,000ps corresponds to the memory response to the first of these two transactions, which is when the testbench randomly asserts a memory fault here. According to Ibex documentation for this situation, the second memory transaction should continue as normal, ignoring the response data, and then the core needs to also jump to the corresponding fault handler (located at `PC=0x80014000` in our case). The LSU's FSM transitions to it's error handling states from the misaligned transaction states, and the core jumps to `0x80014000` (which encodes the instruction `j 80014080`) directly after `0x800058d0`, but while executing this jump instruction, the core jumps to `0x8001e112` instead, throwing an illegal instruction exception, and then proceeds to wait for the `rvalid` corresponding to the second part of the original misaligned transaction. This occurs around 395,835,000ps, and after this, the core jumps back to the fault handler, and fully executes it. This intermediate PC of `0x8001e112` is calculated as the incorrect jump address from load address data that's already in the execution pipeline, and is muxed through due to `lsu_addr_incr_req_i` going high while waiting for the second half of the misaligned memory transaction to complete. Maybe a potential solution for this would be to only jump to the fault handler after the second part of the misaligned transactions has completed?\r\nBest,\r\nUdi", "commit_message": "[RTL LSU] Change unaligned error behaviour\n\n- If an error is signalled in the first part of an unaligned\n transaction, the second part is issued anyway (to avoid a\n timing loop from data_err_i -> data_req_o)\n- Previously, the error was signalled and an exception was taken\n as soon as the first transaction completed. This commits makes\n the core wait until both transactions have completed.\n- This prevents strange behaviour caused by the lsu and controller\n being out of sync (fixes #374).", "fix_patch": "diff --git a/rtl/ibex_load_store_unit.sv b/rtl/ibex_load_store_unit.sv\nindex c959ce2ddb..2c08892e0e 100644\n--- a/rtl/ibex_load_store_unit.sv\n+++ b/rtl/ibex_load_store_unit.sv\n@@ -42,7 +42,7 @@ module ibex_load_store_unit (\n output logic [31:0] addr_last_o, // address of last transaction -> to controller\n // -> mtval\n // -> AGU for misaligned accesses\n- output logic data_valid_o, // LSU has completed transaction -> to\n+ output logic data_valid_o, // LSU has completed transaction -> to ID/EX\n \n // exception signals\n output logic load_err_o,\n@@ -53,14 +53,16 @@ module ibex_load_store_unit (\n \n logic [31:0] data_addr;\n logic [31:0] data_addr_w_aligned;\n- logic [31:0] addr_last_q, addr_last_d;\n+ logic [31:0] addr_last_q;\n \n- logic data_update;\n- logic [31:0] rdata_q, rdata_d;\n- logic [1:0] rdata_offset_q, rdata_offset_d;\n- logic [1:0] data_type_q, data_type_d;\n- logic data_sign_ext_q, data_sign_ext_d;\n- logic data_we_q, data_we_d;\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] wdata_offset; // mux control for data to be written to memory\n \n@@ -76,13 +78,13 @@ module ibex_load_store_unit (\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_d;\n- logic pmp_err_q;\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, WAIT_RVALID,\n- WAIT_GNT_ERR, WAIT_RVALID_ERR, WAIT_RVALID_DONE\n+ WAIT_RVALID_DONE\n } ls_fsm_e;\n \n ls_fsm_e ls_fsm_cs, ls_fsm_ns;\n@@ -165,40 +167,37 @@ module ibex_load_store_unit (\n // RData alignment //\n /////////////////////\n \n- // rdata_q holds data returned from memory for first part of misaligned loads\n- always_comb begin\n- rdata_d = rdata_q;\n- if (data_rvalid_i & ~data_we_q & handle_misaligned_q) begin\n- rdata_d = data_rdata_i;\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- // update control signals for next read data upon receiving grant\n- // This must also be set for a pmp error (which might not actually be granted) to force\n- // data_we_q to update in order to signal the correct exception type (load or store)\n- // Note that we can use the registered pmp_err_q here since we will always take an\n- // extra cycle to progress to the RVALID state\n- assign data_update = data_gnt_i | pmp_err_q;\n-\n- assign rdata_offset_d = data_update ? data_addr[1:0] : rdata_offset_q;\n- assign data_type_d = data_update ? data_type_ex_i : data_type_q;\n- assign data_sign_ext_d = data_update ? data_sign_ext_ex_i : data_sign_ext_q;\n- assign data_we_d = data_update ? data_we_ex_i : data_we_q;\n-\n- // registers for rdata alignment and sign-extension\n+ // registers for transaction control\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n- rdata_q <= '0;\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 begin\n- rdata_q <= rdata_d;\n- rdata_offset_q <= rdata_offset_d;\n- data_type_q <= data_type_d;\n- data_sign_ext_q <= data_sign_ext_d;\n- data_we_q <= data_we_d;\n+ end else if (ctrl_update) begin\n+ rdata_offset_q <= data_addr[1:0];\n+ data_type_q <= data_type_ex_i;\n+ data_sign_ext_q <= data_sign_ext_ex_i;\n+ data_we_q <= data_we_ex_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@@ -324,6 +323,11 @@ module ibex_load_store_unit (\n handle_misaligned_d = handle_misaligned_q;\n data_or_pmp_err = 1'b0;\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 unique case (ls_fsm_cs)\n \n@@ -331,7 +335,10 @@ module ibex_load_store_unit (\n if (data_req_ex_i) begin\n data_req_o = 1'b1;\n pmp_err_d = data_pmp_err_i;\n+ lsu_err_d = 1'b0;\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 : WAIT_RVALID;\n end else begin\n@@ -347,6 +354,8 @@ module ibex_load_store_unit (\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@@ -362,18 +371,14 @@ module ibex_load_store_unit (\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- if (pmp_err_q || data_err_i) begin\n- // first part created an error, abort transaction\n- data_valid_o = 1'b1;\n- data_or_pmp_err = 1'b1;\n- handle_misaligned_d = 1'b0;\n- // If already granted, wait for second rvalid\n- ls_fsm_ns = data_gnt_i ? WAIT_RVALID_ERR : WAIT_GNT_ERR;\n-\n- end else begin\n- // No error in first part, proceed with second part\n- ls_fsm_ns = data_gnt_i ? WAIT_RVALID : WAIT_GNT;\n- end\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 ? WAIT_RVALID : 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 \n end else begin\n // first part rvalid is NOT received\n@@ -389,15 +394,18 @@ module ibex_load_store_unit (\n addr_incr_req_o = handle_misaligned_q;\n data_req_o = 1'b1;\n if (data_gnt_i || pmp_err_q) begin\n- ls_fsm_ns = WAIT_RVALID;\n+ ctrl_update = 1'b1;\n+ // Update the address, unless there was an error\n+ addr_update = ~lsu_err_q;\n+ ls_fsm_ns = WAIT_RVALID;\n end\n end\n \n WAIT_RVALID: begin\n- data_req_o = 1'b0;\n if (data_rvalid_i || pmp_err_q) begin\n data_valid_o = 1'b1;\n- data_or_pmp_err = data_err_i | pmp_err_q;\n+ // Data error from either part\n+ data_or_pmp_err = lsu_err_q | data_err_i | pmp_err_q;\n handle_misaligned_d = 1'b0;\n ls_fsm_ns = IDLE;\n end else begin\n@@ -405,41 +413,22 @@ module ibex_load_store_unit (\n end\n end\n \n- WAIT_GNT_ERR: begin\n- // Wait for the grant of the abandoned second access\n- data_req_o = 1'b1;\n- // tell ID/EX stage to update the address\n- addr_incr_req_o = 1'b1;\n- if (pmp_err_q) begin\n- // The second part was suppressed by a PMP error\n- ls_fsm_ns = IDLE;\n- end else if (data_gnt_i) begin\n- ls_fsm_ns = WAIT_RVALID_ERR;\n- end\n- end\n-\n- WAIT_RVALID_ERR: begin\n- // Wait for the rvalid, but do nothing with it\n- if (data_rvalid_i || pmp_err_q) begin\n- ls_fsm_ns = IDLE;\n- end\n- end\n-\n WAIT_RVALID_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- if (data_err_i) begin\n- // first part created an error, abort transaction and wait for second rvalid\n- data_valid_o = 1'b1;\n- data_or_pmp_err = 1'b1;\n- handle_misaligned_d = 1'b0;\n- ls_fsm_ns = WAIT_RVALID_ERR;\n- end else begin\n- ls_fsm_ns = WAIT_RVALID;\n- end\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 = WAIT_RVALID;\n end\n end\n \n@@ -449,28 +438,18 @@ module ibex_load_store_unit (\n endcase\n end\n \n- // store last address for mtval + AGU for misaligned transactions:\n- // - misaligned address needed for correct generation of data_be and data_rdata_ext\n- // - do not update in case of errors, mtval needs the failing address\n- always_comb begin\n- addr_last_d = addr_last_q;\n- if (data_req_o & data_gnt_i & ~(load_err_o | store_err_o)) begin\n- addr_last_d = data_addr;\n- end\n- end\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- addr_last_q <= '0;\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- addr_last_q <= addr_last_d;\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", "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 * Load Store Unit\n *\n * Load Store Unit, used to eliminate multiple access during processor stalls,\n * and to align bytes and halfwords.\n */\nmodule ibex_load_store_unit (\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 data_we_ex_i, // write enable -> from ID/EX\n input logic [1:0] data_type_ex_i, // data type: word, half word, byte -> from ID/EX\n input logic [31:0] data_wdata_ex_i, // data to write to memory -> from ID/EX\n input logic data_sign_ext_ex_i, // sign extension -> from ID/EX\n\n output logic [31:0] data_rdata_ex_o, // requested data -> to ID/EX\n input logic data_req_ex_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 output logic data_valid_o, // LSU has completed transaction -> to ID/EX\n\n // exception signals\n output logic load_err_o,\n output logic store_err_o,\n\n output logic busy_o\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] wdata_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, WAIT_RVALID,\n WAIT_RVALID_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\n ///////////////////\n // BE generation //\n ///////////////////\n\n always_comb begin\n unique case (data_type_ex_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_addr[1:0])\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 = 'X;\n endcase // case (data_addr[1:0])\n end else begin // second part of misaligned transaction\n unique case (data_addr[1:0])\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 = 'X;\n endcase // case (data_addr[1:0])\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_addr[1:0])\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 = 'X;\n endcase // case (data_addr[1:0])\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_addr[1:0])\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 = 'X;\n endcase // case (data_addr[1:0])\n end\n\n default: data_be = 'X;\n endcase // case (data_type_ex_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 assign wdata_offset = data_addr[1:0];\n always_comb begin\n unique case (wdata_offset)\n 2'b00: data_wdata = data_wdata_ex_i[31:0];\n 2'b01: data_wdata = {data_wdata_ex_i[23:0], data_wdata_ex_i[31:24]};\n 2'b10: data_wdata = {data_wdata_ex_i[15:0], data_wdata_ex_i[31:16]};\n 2'b11: data_wdata = {data_wdata_ex_i[ 7:0], data_wdata_ex_i[31: 8]};\n default: data_wdata = 'X;\n endcase // case (wdata_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_addr[1:0];\n data_type_q <= data_type_ex_i;\n data_sign_ext_q <= data_sign_ext_ex_i;\n data_we_q <= data_we_ex_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 = 'X;\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 = 'X;\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 = 'X;\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 = 'X;\n endcase //~case(rdata_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 ((data_type_ex_i == 2'b00) && (data_addr[1:0] != 2'b00)) || // misaligned word access\n ((data_type_ex_i == 2'b01) && (data_addr[1:0] == 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 data_valid_o = 1'b0;\n addr_incr_req_o = 1'b0;\n handle_misaligned_d = handle_misaligned_q;\n data_or_pmp_err = 1'b0;\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 unique case (ls_fsm_cs)\n\n IDLE: begin\n if (data_req_ex_i) begin\n data_req_o = 1'b1;\n pmp_err_d = data_pmp_err_i;\n lsu_err_d = 1'b0;\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 : WAIT_RVALID;\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 ? WAIT_RVALID : 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\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_DONE;\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 = WAIT_RVALID;\n end\n end\n\n WAIT_RVALID: begin\n if (data_rvalid_i || pmp_err_q) begin\n data_valid_o = 1'b1;\n // Data error from either part\n data_or_pmp_err = lsu_err_q | data_err_i | pmp_err_q;\n handle_misaligned_d = 1'b0;\n ls_fsm_ns = IDLE;\n end else begin\n ls_fsm_ns = WAIT_RVALID;\n end\n end\n\n WAIT_RVALID_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 = WAIT_RVALID;\n end\n end\n\n default: begin\n ls_fsm_ns = ls_fsm_e'(1'bX);\n end\n endcase\n end\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 // output to register file\n assign data_rdata_ex_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 = data_we_ex_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;\n assign store_err_o = data_or_pmp_err & data_we_q;\n\n assign busy_o = (ls_fsm_cs != IDLE);\n\n ////////////////\n // Assertions //\n ////////////////\n\n`ifndef VERILATOR\n // make sure there is no new request when the old one is not yet completely done\n // i.e. it should not be possible to get a grant without an rvalid for the\n // last request\n assert property (\n @(posedge clk_i)\n ((ls_fsm_cs == WAIT_RVALID) && (data_gnt_i == 1'b1)) |-> (data_rvalid_i == 1'b1) ) else\n $display(\"Data grant set while LSU keeps waiting for rvalid\");\n\n // there should be no rvalid when we are in IDLE\n assert property (\n @(posedge clk_i) (ls_fsm_cs == IDLE) |-> (data_rvalid_i == 1'b0) ) else\n $display(\"Data rvalid set while LSU idle\");\n\n // assert that errors are only sent at the same time as rvalid\n assert property (\n @(posedge clk_i) (data_err_i) |-> (data_rvalid_i) ) else\n $display(\"Data error not sent with rvalid\");\n\n // assert that the address does not contain X when request is sent\n assert property (\n @(posedge clk_i) (data_req_o) |-> (!$isunknown(data_addr_o)) ) else\n $display(\"Data address not valid\");\n\n // assert that the address is word aligned when request is sent\n assert property (\n @(posedge clk_i) (data_req_o) |-> (data_addr_o[1:0] == 2'b00) ) else\n $display(\"Data address not word aligned\");\n`endif\nendmodule\n", "selected_doc_paths": ["doc/load_store_unit.rst", "doc/pmp.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 461, "lang": "sv", "rtl_files": ["rtl/ibex_cs_registers.sv"], "spec": "# Behavioral Design Specification: Ibex Control and Status Registers (CSR) Module\n\n## 1. Overview\n\nThis module implements the Control and Status Registers (CSRs) for the Ibex RISC-V processor core, conforming to the RISC-V Privileged Specification version 1.11. It manages the machine-level CSRs, interrupt and exception handling state, debug registers, physical memory protection (PMP) configuration, and hardware performance counters. The module provides the following key functions:\n\n- Stores and updates all machine-mode CSRs (`mstatus`, `misa`, `mie`, `mtvec`, `mscratch`, `mepc`, `mcause`, `mtval`, `mip`).\n- Maintains the current privilege level (Machine or User) and provides it to other pipeline stages.\n- Captures exception and interrupt context (program counter, cause, trap value, privilege level) into appropriate CSRs when a trap occurs.\n- Restores machine state on execution of the `MRET` instruction.\n- Supports debug-mode CSRs (`dcsr`, `dpc`, `dscratch0`, `dscratch1`) accessible only from debug mode.\n- Implements up to 16 PMP configuration and address registers, with granularity support.\n- Provides up to 8 hardware performance counters, plus the fixed `mcycle` and `minstret` counters, with event selection and inhibit control.\n- Detects and signals illegal CSR accesses (privilege violation, write to read-only register, or access to non-existent CSR).\n- Generates a combined interrupt pending signal and separate pending flags for software, timer, external, and fast interrupts.\n\nThe module operates synchronously on the rising edge of the clock and resets asynchronously with active-low reset.\n\n## 2. CSR Access Interface\n\nThe module accepts a single CSR request per cycle, consisting of:\n\n- A valid access signal.\n- A 12-bit CSR address.\n- A 32-bit write data value.\n- An operation type: read, write, set bits, or clear bits.\n\nFor read operations, the module returns the current value of the addressed CSR. For write, set, or clear operations, the module updates the internal register based on the operation (write: replace value; set: bitwise OR; clear: bitwise AND with complement of write data) and returns the old value (using the same read logic) as the read data output.\n\nThe update of a CSR happens only when:\n\n- The access is valid.\n- The access is not illegal (see Section 9).\n- A new instruction is being processed in the ID stage.\n\nAll CSR fields are defined as WARL (Write Any Read Legal) unless otherwise noted. The module enforces legal values by converting unsupported writes to the nearest legal state (e.g., unsupported privilege mode values are mapped to Machine mode).\n\n## 3. Machine-Level CSRs\n\n### 3.1 `mstatus` (Machine Status, address 0x300)\n\nReset value: 0x0000_1800 (MIE=0, MPIE=1, MPP=11b (Machine), MPRV=0, TW=0)\n\n| Field | Bit(s) | Description |\n|-------|--------|-------------|\n| MIE | 3 | Global interrupt enable. When 0, all interrupts are masked. |\n| MPIE | 7 | Previous interrupt enable. Saved value of MIE when a trap is taken. |\n| MPP | 12:11 | Previous privilege mode (2 bits). Saved privilege level when a trap is taken. Only Machine (11) and User (00) are supported. Any unsupported value written is forced to Machine mode. |\n| MPRV | 17 | Modify privilege. When set, loads and stores use the privilege level stored in MPP for PMP checking instead of the current privilege level. |\n| TW | 21 | Timeout wait. When set, executing a WFI instruction in User mode causes an illegal instruction exception. |\n\nOn trap entry:\n- MIE is copied to MPIE.\n- MIE is cleared (interrupts disabled).\n- The current privilege level is saved in MPP.\n\nOn `MRET`:\n- MPIE is restored to MIE.\n- The privilege level is restored from MPP.\n- Additionally, a separate non-standard mechanism (see Section 3.8) restores the previous MPIE and MPP from backup CSRs.\n\n### 3.2 `misa` (Machine ISA, address 0x301)\n\nRead-only, hardwired to reflect the implemented ISA extensions. For Ibex it encodes:\n- I extension (base integer)\n- C extension (compressed)\n- M extension (if configured)\n- E extension (if configured, RV32E)\n- MXLEN = 1 (RV32)\n\nWrites to `misa` have no effect.\n\n### 3.3 `mie` (Machine Interrupt Enable, address 0x304)\n\nReset: 0x0000_0000 (all interrupts disabled)\n\n| Bit(s) | Interrupt |\n|--------|-----------|\n| 3 | MSIE: Software interrupt enable |\n| 7 | MTIE: Timer interrupt enable |\n| 11 | MEIE: External interrupt enable |\n| 30:16 | MFIE[14:0]: Fast interrupt enable (bit 16 enables fast interrupt 0, etc.) |\n\nEach bit independently enables the corresponding interrupt source when both the global MIE in `mstatus` is set and the specific enable is 1.\n\n### 3.4 `mtvec` (Machine Trap-Vector Base Address, address 0x305)\n\nReset: 0x0000_0001 (BASE = 0, MODE = vectored)\n\n| Field | Bit(s) | Description |\n|-------|--------|-------------|\n| BASE | 31:8 | Trap vector base address. Must be 256-byte aligned; bits [7:2] are forced to 0. |\n| MODE | 1:0 | Always 2'b01 (vectored mode). Read-only. |\n\nThe module handles trap redirection:\n- For exceptions, the core jumps to BASE.\n- For interrupts, the core jumps to BASE + (interrupt_ID × 4).\n\nOn reset, the base address is taken from the boot address input. After reset, the register can be written by software, but only the upper 24 bits are writable; the mode bits remain fixed.\n\n### 3.5 `mscratch` (Machine Scratch, address 0x340)\n\nReset: 0x0000_0000\n\nProvides a general-purpose register for machine-mode software (e.g., to store a pointer to the trap handler's stack). Fully readable and writable.\n\n### 3.6 `mepc` (Machine Exception Program Counter, address 0x341)\n\nReset: 0x0000_0000\n\nOn trap, the current PC is stored in `mepc`. The least significant bit is forced to 0 (instruction alignment). On `MRET`, the value in `mepc` is used as the return address (updated internally with a backup restore mechanism; see Section 3.8).\n\n### 3.7 `mcause` (Machine Cause, address 0x342)\n\nReset: 0x0000_0000\n\n| Field | Bit(s) | Description |\n|-------|--------|-------------|\n| Interrupt | 31 | 1 if trap is due to an interrupt, 0 if due to an exception. |\n| Exception Code | 4:0 | 5-bit cause code. |\n\nWritten automatically on trap entry. Writable by software (WARL). Only bits 31 and 4:0 are modifiable; bits [30:5] are read-only zero.\n\n### 3.8 Backup CSRs for Recoverable NMIs (Non-Standard)\n\nThe module contains three additional CSRs to support recovery from a non-maskable interrupt (NMI) occurring during a trap handler:\n\n- `mstack` (backup of `mstatus.MPIE` and `mstatus.MPP`)\n- `mstack_epc` (backup of `mepc`)\n- `mstack_cause` (backup of `mcause`)\n\nThese registers are **not accessible** to software. They are automatically updated on every trap and restored on `MRET`:\n\n- **On trap**: The values of `mstatus.MPIE`, `mstatus.MPP`, `mepc`, and `mcause` are copied into the corresponding backup registers *before* they are overwritten by the new trap. This ensures that the state of the interrupted handler is preserved.\n- **On `MRET`**: The backup values are restored into `mstatus.MPIE`, `mstatus.MPP`, `mepc`, and `mcause`, and the backup registers themselves are reset to a known safe state (MPIE=1, MPP=User).\n\n### 3.9 `mtval` (Machine Trap Value, address 0x343)\n\nReset: 0x0000_0000\n\nHolds additional trap-specific information:\n- For load/store access faults: the faulting virtual address.\n- For illegal instruction exceptions: the instruction encoding.\n- For all other traps: zero.\n\nUpdated automatically on trap entry and writable by software.\n\n### 3.10 `mip` (Machine Interrupt Pending, address 0x344)\n\nRead-only. Reflects the logical AND of the incoming interrupt request lines with their respective enable bits in `mie`.\n\n| Bit(s) | Interrupt |\n|--------|-----------|\n| 3 | MSIP: Software interrupt pending |\n| 7 | MTIP: Timer interrupt pending |\n| 11 | MEIP: External interrupt pending |\n| 30:16 | MFIP[14:0]: Fast interrupt pending |\n\nA combined pending signal is also output, equal to the OR of all pending bits.\n\n## 4. Debug-Mode CSRs\n\nThese CSRs are accessible only when the core is in debug mode. Any access attempt from non-debug mode is treated as an illegal access.\n\n### 4.1 `dcsr` (Debug Control and Status, address 0x7B0)\n\nReset: 0x0000_0000 (except `xdebugver` = standard)\n\n| Field | Bit(s) | Description |\n|-------|--------|-------------|\n| xdebugver | 31:28 | Debug specification version. Read-only, set to 1 (standard). |\n| ebreakm | 15 | When set, `ebreak` in Machine mode enters debug mode. |\n| ebreaku | 13 | When set, `ebreak` in User mode enters debug mode. |\n| stepie | 11 | (Not supported in Ibex) |\n| stopcount | 9 | (Not supported) |\n| stoptime | 8 | (Not supported) |\n| cause | 7:6 | Reason for entering debug mode (set on entry). |\n| mprven | 4 | (Not supported) |\n| nmip | 3 | (Not supported, always 0) |\n| step | 2 | Single-step enable. When set, each instruction retires into debug mode. |\n| prv | 1:0 | Privilege level when entering debug mode. Written by hardware on entry; software writes are mapped to Machine if unsupported. |\n\nWrites must set `xdebugver` appropriately; the module forces it to the correct value.\n\n### 4.2 `dpc` (Debug Program Counter, address 0x7B1)\n\nReset: 0x0000_0000\n\nOn entry to debug mode, the current PC is saved here. The least significant bit is forced to 0. Executing `dret` returns to this address.\n\n### 4.3 `dscratch0` and `dscratch1` (Debug Scratch Registers, addresses 0x7B2 and 0x7B3)\n\nReset: 0x0000_0000\n\nGeneral-purpose registers for use by debug software.\n\n## 5. Physical Memory Protection (PMP) Registers\n\nWhen PMP is enabled (parameter `PMPEnable` = 1), the module implements:\n\n- Up to 16 PMP configuration registers (`pmpcfg0`–`pmpcfg3`, addresses 0x3A0–0x3A3)\n- Up to 16 PMP address registers (`pmpaddr0`–`pmpaddr15`, addresses 0x3B0–0x3BF)\n\nEach PMP configuration register contains four 8-bit configuration fields (one per region). The fields are:\n\n| Bit | Field | Description |\n|-----|-------|-------------|\n| 7 | L | Lock: when set, subsequent writes to the configuration and its associated address register are ignored. |\n| 6:5 | - | Reserved, read as zero. |\n| 4:3 | A | Address matching mode: OFF (00), TOR (01), NA4 (10, only when granularity=0), NAPOT (11). |\n| 2 | X | Execute permission. |\n| 1 | W | Write permission. If W=1 and R=0, the combination is reserved and treated as W=0. |\n| 0 | R | Read permission. |\n\nThe address registers store bits [33:2] of the physical address. The effective address is {pmpaddr, 2'b00}. \n\nAddress read data is modified based on the programmed mode and granularity parameter:\n- In TOR or OFF mode, the lower G bits read as zero (where G = PMPGranularity).\n- In NAPOT mode, the lower G-1 bits read as one.\n- NA4 mode is not available when granularity > 0 (treated as OFF).\n\nPMP region i+1's address register is protected from write when region i's configuration uses TOR mode and region i is not locked. If PMP is disabled, all PMP registers read as zero and output zero.\n\n## 6. Performance Counters\n\nThe module implements fixed and configurable performance counters as per the RISC-V Privileged Specification.\n\n### 6.1 Counter Registers\n\n- `mcycle` (0xB00) / `mcycleh` (0xB80): 64-bit cycle counter. Increments every cycle unless inhibited.\n- `minstret` (0xB02) / `minstreth` (0xB82): 64-bit instruction retired counter. Increments each time an instruction retires (except when inhibited).\n- `mhpmcounter3`–`mhpmcounter31` (0xB03–0xB1F) and their upper halves (0xB83–0xB9F): up to 29 event counters, only a subset (up to 8) are implemented. The number and width are parameterizable.\n\n### 6.2 Event Selection (`mhpmevent3`–`mhpmevent31`, addresses 0x323–0x33F)\n\nEach event selector is a 32-bit WARL register. The event counters are hardwired to specific events:\n- Counter 3: cycles waiting for data memory (`lsu_busy`)\n- Counter 4: cycles waiting for instruction fetches (excluding jumps/branches)\n- Counter 5: number of loads\n- Counter 6: number of stores\n- Counter 7: number of unconditional jumps\n- Counter 8: number of branches (conditional)\n- Counter 9: number of taken branches\n- Counter 10: number of compressed instructions retired\n\nOnly the bit corresponding to the hardwired event is writable (set to 1); other bits are read-only 0. The event selector for unused counters is tied to 0.\n\n### 6.3 `mcountinhibit` (Machine Counter Inhibit, address 0x320)\n\nReset: 0x0000_0000\n\nEach bit controls the corresponding counter: when bit X is 1, counter X is inhibited (does not increment). Bit 1 is always read as 0 (reserved). Unused counters (beyond the number implemented) are forced to 1 via an internal mask, so they never increment.\n\n### 6.4 Counter Width\n\n- `mcycle` and `minstret` are always 64 bits wide.\n- Event counters have a configurable width (default 40 bits). Bits above the configured width are hardwired to 0 and reads/writes to those upper bits are ignored.\n\n## 7. Privilege Mode\n\nThe module tracks the current privilege level (Machine or User) and outputs it to the ID, IF, and LSU stages. The privilege level can be changed only by:\n\n- **Reset**: Initialized to Machine mode.\n- **Trap**: Changed to Machine mode on entry.\n- **`MRET`**: Restored to the value saved in `mstatus.MPP` (and then further overwritten by the backup restore mechanism; see Section 3.8).\n- **Debug entry**: The current privilege is saved in `dcsr.prv`; the core enters debug mode (a separate debug state, not Machine/User).\n\nFor load/store operations, the privilege level used for PMP checking depends on `mstatus.MPRV`: if MPRV=1, the MPP value is used; otherwise, the current privilege level is used.\n\n## 8. Interrupt and Exception Handling\n\n### 8.1 Trap Entry\n\nWhen a trap occurs (exception or interrupt), the module performs the following actions in a single cycle (controlled by the `csr_save_cause_i` signal):\n\n1. Save the current PC to `mepc`. The PC source depends on whether the fault is in the IF or ID stage.\n2. Save the trap cause to `mcause` (with interrupt bit set if applicable).\n3. Save the trap value to `mtval` (supplied externally).\n4. Save the current privilege level to `mstatus.MPP`.\n5. Save the current `mstatus.MIE` to `mstatus.MPIE`.\n6. Clear `mstatus.MIE` (disable interrupts).\n7. Set the privilege level to Machine mode (if the trap is not a debug entry).\n\nFor debug entry (debug request or single-step), the behavior is slightly different:\n- The current privilege level is saved in `dcsr.prv`.\n- The cause is saved in `dcsr.cause`.\n- The PC is saved in `dpc`.\n- The `mepc` and `mstatus` are **not** modified.\n- Interrupts remain disabled (debug mode masks all interrupts).\n\n### 8.2 Trap Return (`MRET`)\n\nOn execution of `MRET`, the module restores:\n- The privilege level from the backed-up `mstack.MPP` (original handler's MPP).\n- `mstatus.MIE` from `mstack.MPIE`.\n- `mstatus.MPIE` and `mstatus.MPP` from `mstack`.\n- `mepc` from `mstack_epc`.\n- `mcause` from `mstack_cause`.\n- The backup registers are then reset to safe values (MPIE=1, MPP=User).\n\n### 8.3 Interrupt Masking During Debug\n\nWhile in debug mode, all interrupts (including NMI) are ignored. This is independent of `mstatus.MIE` and `mie`.\n\n## 9. Illegal CSR Access Detection\n\nThe module asserts an illegal access signal when a CSR access is attempted under any of the following conditions:\n\n- The CSR address belongs to a non-existent CSR (not implemented).\n- The requested privilege level is insufficient (bits [9:8] of the address indicate required privilege; a program in a lower privilege cannot access a higher-privilege CSR).\n- A write is attempted to a read-only CSR (address bits [11:10] = 2'b11 indicate read-only, unless the access is to a debug CSR and the core is in debug mode, which overrides this rule).\n\nThe illegal access signal is generated in the same cycle as the access and is used to prevent CSR update and to cause an illegal instruction exception in the core.\n\n## 10. Reset Behavior\n\nOn asynchronous active-low reset:\n\n- Privilege level is set to Machine mode.\n- `mstatus` is initialized as described in Section 3.1 (MPIE=1, MPP=Machine, others 0).\n- `mie`, `mscratch`, `mepc`, `mcause`, `mtval`, `mcountinhibit`, all PMP registers, all debug registers (`dcsr`, `dpc`, `dscratch0`, `dscratch1`), and all performance counters are set to 0.\n- `mtvec` is set to 0x0000_0001 (vectored mode with zero base address; the base is overridden after reset via a dedicated initialization signal that loads the boot address).\n- Backup CSRs are initialized: MPIE=1, MPP=User, `mstack_epc`=0, `mstack_cause`=0.\n\n## 11. Outputs Provided to Other Modules\n\nThe module outputs:\n\n- Current privilege level (for ID, IF, and LSU stages, with IF using the *next* privilege level to account for updates this cycle).\n- `mstatus.TW` for time-out wait handling.\n- `mtvec` base address to the fetch unit.\n- Interrupt pending signals: combined `irq_pending`, and individual `msip`, `mtip`, `meip`, `mfip` to the interrupt controller.\n- `mstatus.MIE` for interrupt enable.\n- `mepc` and `depc` for trap return and debug return.\n- PMP configuration and address arrays to the PMP checker.\n- Debug control signals: single-step enable, `ebreakm`, `ebreaku`.\n- Illegal CSR instruction indicator.\n\nAll outputs reflect the current state of the registers and are updated synchronously with changes.", "commit_id": "9b390c5d4ed83bb426d8a3f047d9998572309fab", "timestamp": "2019-11-13T12:11:23+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "d538261c7857183e45bb525c4b513d5b27dfc24f", "pr_title": "[rtl] Ignore LSB only for writes to `dpc`", "pr_body": "Without this PR, writes to `dpc` with the LSB set are completely ignored. This PR changes the implementation to ignore the LSB only. This is the same behavior as seen required for `mepc`. This resolves lowRISC/ibex#444.", "issue_title": "Writing unaligned addresses to `dpc` CSR", "issue_body": "Currently, writes to the `dpc` CSR are simply ignored if the address is unaligned. The debug spec does not specify what should happen if an unaligned address is written to `dpc`. In contrast, the privileged spec says that `xepc` can only hold aligned addresses.\r\n\r\nI suggest to align the behavior of these two registers, i.e., to make the LSB of `dpc` to be always 0 instead of ignoring writes with non-zero LSB completely.", "commit_message": "[rtl] Ignore LSB only for writes to `dpc`\n\nWithout this commit, writes to `dpc` with the LSB set are completely\nignored. This commit changes the implementation to ignore the LSB only.\nThis is the same behavior as seen required for `mepc`. This resolves\nlowRISC/ibex#444.\n\nSigned-off-by: Pirmin Vogel ", "fix_patch": "diff --git a/rtl/ibex_cs_registers.sv b/rtl/ibex_cs_registers.sv\nindex caecdc756f..16b5f8b986 100644\n--- a/rtl/ibex_cs_registers.sv\n+++ b/rtl/ibex_cs_registers.sv\n@@ -459,12 +459,8 @@ module ibex_cs_registers #(\n dcsr_d.zero2 = 12'h0;\n end\n \n- CSR_DPC: begin\n- // Only valid PC addresses are allowed (half-word aligned with C ext.)\n- if (csr_wdata_int[0] == 1'b0) begin\n- depc_d = csr_wdata_int;\n- end\n- end\n+ // dpc: debug program counter\n+ CSR_DPC: depc_d = {csr_wdata_int[31:1], 1'b0};\n \n CSR_DSCRATCH0: dscratch0_d = csr_wdata_int;\n CSR_DSCRATCH1: dscratch1_d = csr_wdata_int;\n", "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 * Control and Status Registers\n *\n * Control and Status Registers (CSRs) following the RISC-V Privileged\n * Specification, draft version 1.11\n */\nmodule ibex_cs_registers #(\n parameter int unsigned MHPMCounterNum = 8,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit PMPEnable = 0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter bit RV32E = 0,\n parameter bit RV32M = 0\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n // Hart ID\n input logic [31:0] hart_id_i,\n\n // Privilege mode\n output ibex_pkg::priv_lvl_e priv_mode_id_o,\n output ibex_pkg::priv_lvl_e priv_mode_if_o,\n output ibex_pkg::priv_lvl_e priv_mode_lsu_o,\n output logic csr_mstatus_tw_o,\n\n // mtvec\n output logic [31:0] csr_mtvec_o,\n input logic csr_mtvec_init_i,\n input logic [31:0] boot_addr_i,\n\n // Interface to registers (SRAM like)\n input logic csr_access_i,\n input ibex_pkg::csr_num_e csr_addr_i,\n input logic [31:0] csr_wdata_i,\n input ibex_pkg::csr_op_e csr_op_i,\n output logic [31:0] csr_rdata_o,\n\n // interrupts\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 output logic irq_pending_o, // interupt request pending\n output logic csr_msip_o, // software interrupt pending\n output logic csr_mtip_o, // timer interrupt pending\n output logic csr_meip_o, // external interrupt pending\n output logic [14:0] csr_mfip_o, // fast interrupt pending\n output logic csr_mstatus_mie_o,\n output logic [31:0] csr_mepc_o,\n\n // PMP\n output ibex_pkg::pmp_cfg_t csr_pmp_cfg_o [PMPNumRegions],\n output logic [33:0] csr_pmp_addr_o [PMPNumRegions],\n\n // debug\n input logic debug_mode_i,\n input ibex_pkg::dbg_cause_e debug_cause_i,\n input logic debug_csr_save_i,\n output logic [31:0] csr_depc_o,\n output logic debug_single_step_o,\n output logic debug_ebreakm_o,\n output logic debug_ebreaku_o,\n\n input logic [31:0] pc_if_i,\n input logic [31:0] pc_id_i,\n\n input logic csr_save_if_i,\n input logic csr_save_id_i,\n input logic csr_restore_mret_i,\n input logic csr_save_cause_i,\n input ibex_pkg::exc_cause_e csr_mcause_i,\n input logic [31:0] csr_mtval_i,\n output logic illegal_csr_insn_o, // access to non-existent CSR,\n // with wrong priviledge level, or\n // missing write permissions\n input logic instr_new_id_i, // ID stage sees a new instr\n\n // Performance Counters\n input logic instr_ret_i, // instr retired in ID/EX stage\n input logic instr_ret_compressed_i, // compressed instr retired\n input logic imiss_i, // instr fetch\n input logic pc_set_i, // PC was set to a new value\n input logic jump_i, // jump instr seen (j, jr, jal, jalr)\n input logic branch_i, // branch instr seen (bf, bnf)\n input logic branch_taken_i, // branch was taken\n input logic mem_load_i, // load from memory in this cycle\n input logic mem_store_i, // store to memory in this cycle\n input logic lsu_busy_i\n);\n\n import ibex_pkg::*;\n\n // misa\n localparam logic [1:0] MXL = 2'd1; // M-XLEN: XLEN in M-Mode for RV32\n localparam logic [31:0] MISA_VALUE =\n (0 << 0) // A - Atomic Instructions extension\n | (1 << 2) // C - Compressed extension\n | (0 << 3) // D - Double precision floating-point extension\n | (32'(RV32E) << 4) // E - RV32E base ISA\n | (0 << 5) // F - Single precision floating-point extension\n | (1 << 8) // I - RV32I/64I/128I base ISA\n | (32'(RV32M) << 12) // M - Integer Multiply/Divide extension\n | (0 << 13) // N - User level interrupts supported\n | (0 << 18) // S - Supervisor mode implemented\n | (0 << 20) // U - User mode implemented\n | (0 << 23) // X - Non-standard extensions present\n | (32'(MXL) << 30); // M-XLEN\n\n typedef struct packed {\n logic mie;\n logic mpie;\n priv_lvl_e mpp;\n logic mprv;\n logic tw;\n } Status_t;\n\n typedef struct packed {\n logic mpie;\n priv_lvl_e mpp;\n } StatusStk_t;\n\n // struct for mip/mie CSRs\n typedef struct packed {\n logic irq_software;\n logic irq_timer;\n logic irq_external;\n logic [14:0] irq_fast; // 15 fast interrupts,\n // one interrupt is reserved for NMI (not visible through mip/mie)\n } Interrupts_t;\n\n typedef struct packed {\n x_debug_ver_e xdebugver;\n logic [11:0] zero2;\n logic ebreakm;\n logic zero1;\n logic ebreaks;\n logic ebreaku;\n logic stepie;\n logic stopcount;\n logic stoptime;\n dbg_cause_e cause;\n logic zero0;\n logic mprven;\n logic nmip;\n logic step;\n priv_lvl_e prv;\n } Dcsr_t;\n\n // Interrupt and exception control signals\n logic [31:0] exception_pc;\n\n // CSRs\n priv_lvl_e priv_lvl_q, priv_lvl_d;\n Status_t mstatus_q, mstatus_d;\n Interrupts_t mie_q, mie_d;\n logic [31:0] mscratch_q, mscratch_d;\n logic [31:0] mepc_q, mepc_d;\n logic [5:0] mcause_q, mcause_d;\n logic [31:0] mtval_q, mtval_d;\n logic [31:0] mtvec_q, mtvec_d;\n Interrupts_t mip;\n Dcsr_t dcsr_q, dcsr_d;\n logic [31:0] depc_q, depc_d;\n logic [31:0] dscratch0_q, dscratch0_d;\n logic [31:0] dscratch1_q, dscratch1_d;\n\n // CSRs for recoverable NMIs\n // NOTE: these CSRS are nonstandard, see https://github.com/riscv/riscv-isa-manual/issues/261\n StatusStk_t mstack_q, mstack_d;\n logic [31:0] mstack_epc_q, mstack_epc_d;\n logic [5:0] mstack_cause_q, mstack_cause_d;\n\n // PMP Signals\n logic [31:0] pmp_addr_rdata [PMP_MAX_REGIONS];\n logic [PMP_CFG_W-1:0] pmp_cfg_rdata [PMP_MAX_REGIONS];\n\n // Hardware performance monitor signals\n logic [31:0] mcountinhibit_d, mcountinhibit_q, mcountinhibit;\n logic [31:0] mcountinhibit_force;\n logic mcountinhibit_we;\n logic [63:0] mhpmcounter_mask [32];\n logic [63:0] mhpmcounter_d [32];\n logic [63:0] mhpmcounter_q [32];\n logic [31:0] mhpmcounter_we;\n logic [31:0] mhpmcounterh_we;\n logic [31:0] mhpmcounter_incr;\n logic [31:0] mhpmevent [32];\n logic [4:0] mhpmcounter_idx;\n\n // CSR update logic\n logic [31:0] csr_wdata_int;\n logic [31:0] csr_rdata_int;\n logic csr_we_int;\n logic csr_wreq;\n\n // Access violation signals\n logic illegal_csr;\n logic illegal_csr_priv;\n logic illegal_csr_write;\n\n logic [7:0] unused_boot_addr;\n logic [2:0] unused_csr_addr;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n\n /////////////\n // CSR reg //\n /////////////\n\n logic [$bits(csr_num_e)-1:0] csr_addr;\n assign csr_addr = {csr_addr_i};\n assign unused_csr_addr = csr_addr[7:5];\n assign mhpmcounter_idx = csr_addr[4:0];\n\n // See RISC-V Privileged Specification, version 1.11, Section 2.1\n assign illegal_csr_priv = (csr_addr[9:8] > {priv_lvl_q});\n assign illegal_csr_write = (csr_addr[11:10] == 2'b11) && csr_wreq;\n assign illegal_csr_insn_o = csr_access_i & (illegal_csr | illegal_csr_write | illegal_csr_priv);\n\n // mip CSR is purely combinational - must be able to re-enable the clock upon WFI\n assign mip.irq_software = irq_software_i & mie_q.irq_software;\n assign mip.irq_timer = irq_timer_i & mie_q.irq_timer;\n assign mip.irq_external = irq_external_i & mie_q.irq_external;\n assign mip.irq_fast = irq_fast_i & mie_q.irq_fast;\n\n // read logic\n always_comb begin\n csr_rdata_int = '0;\n illegal_csr = 1'b0;\n\n unique case (csr_addr_i)\n // mhartid: unique hardware thread id\n CSR_MHARTID: csr_rdata_int = hart_id_i;\n\n // mstatus: always M-mode, contains IE bit\n CSR_MSTATUS: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSTATUS_MIE_BIT] = mstatus_q.mie;\n csr_rdata_int[CSR_MSTATUS_MPIE_BIT] = mstatus_q.mpie;\n csr_rdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW] = mstatus_q.mpp;\n csr_rdata_int[CSR_MSTATUS_MPRV_BIT] = mstatus_q.mprv;\n csr_rdata_int[CSR_MSTATUS_TW_BIT] = mstatus_q.tw;\n end\n\n // misa\n CSR_MISA: csr_rdata_int = MISA_VALUE;\n\n // interrupt enable\n CSR_MIE: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mie_q.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mie_q.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mie_q.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mie_q.irq_fast;\n end\n\n CSR_MSCRATCH: csr_rdata_int = mscratch_q;\n\n // mtvec: trap-vector base address\n CSR_MTVEC: csr_rdata_int = mtvec_q;\n\n // mepc: exception program counter\n CSR_MEPC: csr_rdata_int = mepc_q;\n\n // mcause: exception cause\n CSR_MCAUSE: csr_rdata_int = {mcause_q[5], 26'b0, mcause_q[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: csr_rdata_int = mtval_q;\n\n // mip: interrupt pending\n CSR_MIP: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mip.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mip.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mip.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mip.irq_fast;\n end\n\n // PMP registers\n CSR_PMPCFG0: csr_rdata_int = {pmp_cfg_rdata[3], pmp_cfg_rdata[2],\n pmp_cfg_rdata[1], pmp_cfg_rdata[0]};\n CSR_PMPCFG1: csr_rdata_int = {pmp_cfg_rdata[7], pmp_cfg_rdata[6],\n pmp_cfg_rdata[5], pmp_cfg_rdata[4]};\n CSR_PMPCFG2: csr_rdata_int = {pmp_cfg_rdata[11], pmp_cfg_rdata[10],\n pmp_cfg_rdata[9], pmp_cfg_rdata[8]};\n CSR_PMPCFG3: csr_rdata_int = {pmp_cfg_rdata[15], pmp_cfg_rdata[14],\n pmp_cfg_rdata[13], pmp_cfg_rdata[12]};\n CSR_PMPADDR0: csr_rdata_int = pmp_addr_rdata[0];\n CSR_PMPADDR1: csr_rdata_int = pmp_addr_rdata[1];\n CSR_PMPADDR2: csr_rdata_int = pmp_addr_rdata[2];\n CSR_PMPADDR3: csr_rdata_int = pmp_addr_rdata[3];\n CSR_PMPADDR4: csr_rdata_int = pmp_addr_rdata[4];\n CSR_PMPADDR5: csr_rdata_int = pmp_addr_rdata[5];\n CSR_PMPADDR6: csr_rdata_int = pmp_addr_rdata[6];\n CSR_PMPADDR7: csr_rdata_int = pmp_addr_rdata[7];\n CSR_PMPADDR8: csr_rdata_int = pmp_addr_rdata[8];\n CSR_PMPADDR9: csr_rdata_int = pmp_addr_rdata[9];\n CSR_PMPADDR10: csr_rdata_int = pmp_addr_rdata[10];\n CSR_PMPADDR11: csr_rdata_int = pmp_addr_rdata[11];\n CSR_PMPADDR12: csr_rdata_int = pmp_addr_rdata[12];\n CSR_PMPADDR13: csr_rdata_int = pmp_addr_rdata[13];\n CSR_PMPADDR14: csr_rdata_int = pmp_addr_rdata[14];\n CSR_PMPADDR15: csr_rdata_int = pmp_addr_rdata[15];\n\n CSR_DCSR: begin\n csr_rdata_int = dcsr_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DPC: begin\n csr_rdata_int = depc_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH0: begin\n csr_rdata_int = dscratch0_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH1: begin\n csr_rdata_int = dscratch1_q;\n illegal_csr = ~debug_mode_i;\n end\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: csr_rdata_int = mcountinhibit;\n CSR_MHPMEVENT3,\n CSR_MHPMEVENT4, CSR_MHPMEVENT5, CSR_MHPMEVENT6, CSR_MHPMEVENT7,\n CSR_MHPMEVENT8, CSR_MHPMEVENT9, CSR_MHPMEVENT10, CSR_MHPMEVENT11,\n CSR_MHPMEVENT12, CSR_MHPMEVENT13, CSR_MHPMEVENT14, CSR_MHPMEVENT15,\n CSR_MHPMEVENT16, CSR_MHPMEVENT17, CSR_MHPMEVENT18, CSR_MHPMEVENT19,\n CSR_MHPMEVENT20, CSR_MHPMEVENT21, CSR_MHPMEVENT22, CSR_MHPMEVENT23,\n CSR_MHPMEVENT24, CSR_MHPMEVENT25, CSR_MHPMEVENT26, CSR_MHPMEVENT27,\n CSR_MHPMEVENT28, CSR_MHPMEVENT29, CSR_MHPMEVENT30, CSR_MHPMEVENT31: begin\n csr_rdata_int = mhpmevent[mhpmcounter_idx];\n end\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n csr_rdata_int = mhpmcounter_q[mhpmcounter_idx][31:0];\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n csr_rdata_int = mhpmcounter_q[mhpmcounter_idx][63:32];\n end\n\n default: begin\n illegal_csr = 1'b1;\n end\n endcase\n end\n\n // write logic\n always_comb begin\n exception_pc = pc_id_i;\n\n priv_lvl_d = priv_lvl_q;\n mstatus_d = mstatus_q;\n mie_d = mie_q;\n mscratch_d = mscratch_q;\n mepc_d = mepc_q;\n mcause_d = mcause_q;\n mtval_d = mtval_q;\n mtvec_d = csr_mtvec_init_i ? {boot_addr_i[31:8], 6'b0, 2'b01} : mtvec_q;\n dcsr_d = dcsr_q;\n depc_d = depc_q;\n dscratch0_d = dscratch0_q;\n dscratch1_d = dscratch1_q;\n\n mstack_d = mstack_q;\n mstack_epc_d = mstack_epc_q;\n mstack_cause_d = mstack_cause_q;\n\n mcountinhibit_we = 1'b0;\n mhpmcounter_we = '0;\n mhpmcounterh_we = '0;\n\n if (csr_we_int) begin\n unique case (csr_addr_i)\n // mstatus: IE bit\n CSR_MSTATUS: begin\n mstatus_d = '{\n mie: csr_wdata_int[CSR_MSTATUS_MIE_BIT],\n mpie: csr_wdata_int[CSR_MSTATUS_MPIE_BIT],\n mpp: priv_lvl_e'(csr_wdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW]),\n mprv: csr_wdata_int[CSR_MSTATUS_MPRV_BIT],\n tw: csr_wdata_int[CSR_MSTATUS_TW_BIT]\n };\n // Convert illegal values to M-mode\n if ((mstatus_d.mpp != PRIV_LVL_M) && (mstatus_d.mpp != PRIV_LVL_U)) begin\n mstatus_d.mpp = PRIV_LVL_M;\n end\n end\n\n // interrupt enable\n CSR_MIE: begin\n mie_d.irq_software = csr_wdata_int[CSR_MSIX_BIT];\n mie_d.irq_timer = csr_wdata_int[CSR_MTIX_BIT];\n mie_d.irq_external = csr_wdata_int[CSR_MEIX_BIT];\n mie_d.irq_fast = csr_wdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW];\n end\n\n CSR_MSCRATCH: mscratch_d = csr_wdata_int;\n\n // mepc: exception program counter\n CSR_MEPC: mepc_d = {csr_wdata_int[31:1], 1'b0};\n\n // mcause\n CSR_MCAUSE: mcause_d = {csr_wdata_int[31], csr_wdata_int[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: mtval_d = csr_wdata_int;\n\n // mtvec\n // mtvec.MODE set to vectored\n // mtvec.BASE must be 256-byte aligned\n CSR_MTVEC: mtvec_d = {csr_wdata_int[31:8], 6'b0, 2'b01};\n\n CSR_DCSR: begin\n dcsr_d = csr_wdata_int;\n dcsr_d.xdebugver = XDEBUGVER_STD;\n // Change to PRIV_LVL_M if sofware writes an unsupported value\n if ((dcsr_d.prv != PRIV_LVL_M) && (dcsr_d.prv != PRIV_LVL_U)) begin\n dcsr_d.prv = PRIV_LVL_M;\n end\n\n // currently not supported:\n dcsr_d.nmip = 1'b0;\n dcsr_d.mprven = 1'b0;\n dcsr_d.stopcount = 1'b0;\n dcsr_d.stoptime = 1'b0;\n\n // forced to be zero\n dcsr_d.zero0 = 1'b0;\n dcsr_d.zero1 = 1'b0;\n dcsr_d.zero2 = 12'h0;\n end\n\n // dpc: debug program counter\n CSR_DPC: depc_d = {csr_wdata_int[31:1], 1'b0};\n\n CSR_DSCRATCH0: dscratch0_d = csr_wdata_int;\n CSR_DSCRATCH1: dscratch1_d = csr_wdata_int;\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: mcountinhibit_we = 1'b1;\n\n CSR_MCYCLE,\n CSR_MINSTRET,\n CSR_MHPMCOUNTER3,\n CSR_MHPMCOUNTER4, CSR_MHPMCOUNTER5, CSR_MHPMCOUNTER6, CSR_MHPMCOUNTER7,\n CSR_MHPMCOUNTER8, CSR_MHPMCOUNTER9, CSR_MHPMCOUNTER10, CSR_MHPMCOUNTER11,\n CSR_MHPMCOUNTER12, CSR_MHPMCOUNTER13, CSR_MHPMCOUNTER14, CSR_MHPMCOUNTER15,\n CSR_MHPMCOUNTER16, CSR_MHPMCOUNTER17, CSR_MHPMCOUNTER18, CSR_MHPMCOUNTER19,\n CSR_MHPMCOUNTER20, CSR_MHPMCOUNTER21, CSR_MHPMCOUNTER22, CSR_MHPMCOUNTER23,\n CSR_MHPMCOUNTER24, CSR_MHPMCOUNTER25, CSR_MHPMCOUNTER26, CSR_MHPMCOUNTER27,\n CSR_MHPMCOUNTER28, CSR_MHPMCOUNTER29, CSR_MHPMCOUNTER30, CSR_MHPMCOUNTER31: begin\n mhpmcounter_we[mhpmcounter_idx] = 1'b1;\n end\n\n CSR_MCYCLEH,\n CSR_MINSTRETH,\n CSR_MHPMCOUNTER3H,\n CSR_MHPMCOUNTER4H, CSR_MHPMCOUNTER5H, CSR_MHPMCOUNTER6H, CSR_MHPMCOUNTER7H,\n CSR_MHPMCOUNTER8H, CSR_MHPMCOUNTER9H, CSR_MHPMCOUNTER10H, CSR_MHPMCOUNTER11H,\n CSR_MHPMCOUNTER12H, CSR_MHPMCOUNTER13H, CSR_MHPMCOUNTER14H, CSR_MHPMCOUNTER15H,\n CSR_MHPMCOUNTER16H, CSR_MHPMCOUNTER17H, CSR_MHPMCOUNTER18H, CSR_MHPMCOUNTER19H,\n CSR_MHPMCOUNTER20H, CSR_MHPMCOUNTER21H, CSR_MHPMCOUNTER22H, CSR_MHPMCOUNTER23H,\n CSR_MHPMCOUNTER24H, CSR_MHPMCOUNTER25H, CSR_MHPMCOUNTER26H, CSR_MHPMCOUNTER27H,\n CSR_MHPMCOUNTER28H, CSR_MHPMCOUNTER29H, CSR_MHPMCOUNTER30H, CSR_MHPMCOUNTER31H: begin\n mhpmcounterh_we[mhpmcounter_idx] = 1'b1;\n end\n\n default:;\n endcase\n end\n\n // exception controller gets priority over other writes\n unique case (1'b1)\n\n csr_save_cause_i: begin\n unique case (1'b1)\n csr_save_if_i: begin\n exception_pc = pc_if_i;\n end\n csr_save_id_i: begin\n exception_pc = pc_id_i;\n end\n default:;\n endcase\n\n if (debug_csr_save_i) begin\n // all interrupts are masked\n // do not update cause, epc, tval, epc and status\n dcsr_d.prv = priv_lvl_q;\n dcsr_d.cause = debug_cause_i;\n depc_d = exception_pc;\n end else begin\n priv_lvl_d = PRIV_LVL_M;\n mtval_d = csr_mtval_i;\n mstatus_d.mie = 1'b0; // disable interrupts\n // save current status\n mstatus_d.mpie = mstatus_q.mie;\n mstatus_d.mpp = priv_lvl_q;\n mepc_d = exception_pc;\n mcause_d = {csr_mcause_i};\n // save previous status for recoverable NMI\n mstack_d.mpie = mstatus_q.mpie;\n mstack_d.mpp = mstatus_q.mpp;\n mstack_epc_d = mepc_q;\n mstack_cause_d = mcause_q;\n end\n end // csr_save_cause_i\n\n csr_restore_mret_i: begin // MRET\n priv_lvl_d = mstatus_q.mpp;\n mstatus_d.mie = mstatus_q.mpie; // re-enable interrupts\n // restore previous status for recoverable NMI\n mstatus_d.mpie = mstack_q.mpie;\n mstatus_d.mpp = mstack_q.mpp;\n mepc_d = mstack_epc_q;\n mcause_d = mstack_cause_q;\n mstack_d.mpie = 1'b1;\n mstack_d.mpp = PRIV_LVL_U;\n end // csr_restore_mret_i\n\n default:;\n endcase\n end\n\n // CSR operation logic\n always_comb begin\n csr_wreq = 1'b1;\n\n unique case (csr_op_i)\n CSR_OP_WRITE: csr_wdata_int = csr_wdata_i;\n CSR_OP_SET: csr_wdata_int = csr_wdata_i | csr_rdata_o;\n CSR_OP_CLEAR: csr_wdata_int = ~csr_wdata_i & csr_rdata_o;\n CSR_OP_READ: begin\n csr_wdata_int = csr_wdata_i;\n csr_wreq = 1'b0;\n end\n default: begin\n csr_wdata_int = 'X;\n csr_wreq = 1'bX;\n end\n endcase\n end\n\n // only write CSRs during one clock cycle\n assign csr_we_int = csr_wreq & ~illegal_csr_insn_o & instr_new_id_i;\n\n assign csr_rdata_o = csr_rdata_int;\n\n // directly output some registers\n assign csr_msip_o = mip.irq_software;\n assign csr_mtip_o = mip.irq_timer;\n assign csr_meip_o = mip.irq_external;\n assign csr_mfip_o = mip.irq_fast;\n\n assign csr_mepc_o = mepc_q;\n assign csr_depc_o = depc_q;\n assign csr_mtvec_o = mtvec_q;\n\n assign csr_mstatus_mie_o = mstatus_q.mie;\n assign csr_mstatus_tw_o = mstatus_q.tw;\n assign debug_single_step_o = dcsr_q.step;\n assign debug_ebreakm_o = dcsr_q.ebreakm;\n assign debug_ebreaku_o = dcsr_q.ebreaku;\n\n assign irq_pending_o = csr_msip_o | csr_mtip_o | csr_meip_o | (|csr_mfip_o);\n\n // actual registers\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n priv_lvl_q <= PRIV_LVL_M;\n mstatus_q <= '{\n mie: 1'b0,\n mpie: 1'b1,\n mpp: PRIV_LVL_U,\n mprv: 1'b0,\n tw: 1'b0\n };\n mie_q <= '0;\n mscratch_q <= '0;\n mepc_q <= '0;\n mcause_q <= '0;\n mtval_q <= '0;\n mtvec_q <= 32'b01;\n dcsr_q <= '{\n xdebugver: XDEBUGVER_STD,\n cause: DBG_CAUSE_NONE, // 3'h0\n prv: PRIV_LVL_M,\n default: '0\n };\n depc_q <= '0;\n dscratch0_q <= '0;\n dscratch1_q <= '0;\n\n mstack_q <= '{\n mpie: 1'b1,\n mpp: PRIV_LVL_U\n };\n mstack_epc_q <= '0;\n mstack_cause_q <= '0;\n\n end else begin\n // update CSRs\n priv_lvl_q <= priv_lvl_d;\n mstatus_q <= mstatus_d;\n mie_q <= mie_d;\n mscratch_q <= mscratch_d;\n mepc_q <= mepc_d;\n mcause_q <= mcause_d;\n mtval_q <= mtval_d;\n mtvec_q <= mtvec_d;\n dcsr_q <= dcsr_d;\n depc_q <= depc_d;\n dscratch0_q <= dscratch0_d;\n dscratch1_q <= dscratch1_d;\n\n mstack_q <= mstack_d;\n mstack_epc_q <= mstack_epc_d;\n mstack_cause_q <= mstack_cause_d;\n\n end\n end\n\n // Send current priv level to the decoder\n assign priv_mode_id_o = priv_lvl_q;\n // New instruction fetches need to account for updates to priv_lvl_q this cycle\n assign priv_mode_if_o = priv_lvl_d;\n // Load/store instructions must factor in MPRV for PMP checking\n assign priv_mode_lsu_o = mstatus_q.mprv ? mstatus_q.mpp : priv_lvl_q;\n\n // -----------------\n // PMP registers\n // -----------------\n\n if (PMPEnable) begin : g_pmp_registers\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n logic [31:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n logic [PMPNumRegions-1:0] pmp_addr_we;\n\n // Expanded / qualified register read data\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_exp_rd_data\n if (i < PMPNumRegions) begin : g_implemented_regions\n // Add in zero padding for reserved fields\n assign pmp_cfg_rdata[i] = {pmp_cfg[i].lock, 2'b00, pmp_cfg[i].mode,\n pmp_cfg[i].exec, pmp_cfg[i].write, pmp_cfg[i].read};\n\n // Address field read data depends on the current programmed mode and the granularity\n // See RISC-V Privileged Specification, version 1.11, Section 3.6.1\n if (PMPGranularity == 0) begin : g_pmp_g0\n // If G == 0, read data is unmodified\n assign pmp_addr_rdata[i] = pmp_addr[i];\n\n end else if (PMPGranularity == 1) begin : g_pmp_g1\n // If G == 1, bit [G-1] reads as zero in TOR or OFF mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n\n end else begin : g_pmp_g2\n // For G >= 2, bits are masked to one or zero depending on the mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n // In TOR or OFF mode, bits [G-1:0] must read as zero\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end else if (pmp_cfg[i].mode == PMP_MODE_NAPOT) begin\n // In NAPOT mode, bits [G-2:0] must read as one\n pmp_addr_rdata[i][PMPGranularity-2:0] = '1;\n end\n end\n end\n\n end else begin : g_other_regions\n // Non-implemented regions read as zero\n assign pmp_cfg_rdata[i] = '0;\n assign pmp_addr_rdata[i] = '0;\n end\n end\n\n // Write data calculation\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_pmp_csrs\n // -------------------------\n // Instantiate cfg registers\n // -------------------------\n assign pmp_cfg_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_CFG + (i[11:0] >> 2)));\n\n // Select the correct WDATA (each CSR contains 4 CFG fields, each with 2 RES bits)\n assign pmp_cfg_wdata[i].lock = csr_wdata_int[(i%4)*PMP_CFG_W+7];\n // NA4 mode is not selectable when G > 0, mode is treated as OFF\n always_comb begin\n unique case (csr_wdata_int[(i%4)*PMP_CFG_W+3+:2])\n 2'b00 : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n 2'b01 : pmp_cfg_wdata[i].mode = PMP_MODE_TOR;\n 2'b10 : pmp_cfg_wdata[i].mode = (PMPGranularity == 0) ? PMP_MODE_NA4:\n PMP_MODE_OFF;\n 2'b11 : pmp_cfg_wdata[i].mode = PMP_MODE_NAPOT;\n default : pmp_cfg_wdata[i].mode = pmp_cfg_mode_e'('X);\n endcase\n end\n assign pmp_cfg_wdata[i].exec = csr_wdata_int[(i%4)*PMP_CFG_W+2];\n // W = 1, R = 0 is a reserved combination. For now, we force W to 0 if R == 0\n assign pmp_cfg_wdata[i].write = &csr_wdata_int[(i%4)*PMP_CFG_W+:2];\n assign pmp_cfg_wdata[i].read = csr_wdata_int[(i%4)*PMP_CFG_W];\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pmp_cfg[i] <= pmp_cfg_t'('b0);\n end else if (pmp_cfg_we[i]) begin\n pmp_cfg[i] <= pmp_cfg_wdata[i];\n end\n end\n\n // --------------------------\n // Instantiate addr registers\n // --------------------------\n if (i < PMPNumRegions - 1) begin : g_lower\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (pmp_cfg[i+1].mode != PMP_MODE_TOR) &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end else begin : g_upper\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pmp_addr[i] <= 'b0;\n end else if (pmp_addr_we[i]) begin\n pmp_addr[i] <= csr_wdata_int;\n end\n end\n assign csr_pmp_cfg_o[i] = pmp_cfg[i];\n assign csr_pmp_addr_o[i] = {pmp_addr[i],2'b00};\n end\n\n end else begin : g_no_pmp_tieoffs\n // Generate tieoffs when PMP is not configured\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_rdata\n assign pmp_addr_rdata[i] = '0;\n assign pmp_cfg_rdata[i] = '0;\n end\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_outputs\n assign csr_pmp_cfg_o[i] = pmp_cfg_t'(1'b0);\n assign csr_pmp_addr_o[i] = '0;\n end\n end\n\n //////////////////////////\n // Performance monitor //\n //////////////////////////\n\n // update enable signals\n always_comb begin : mcountinhibit_update\n if (mcountinhibit_we == 1'b1) begin\n mcountinhibit_d = {csr_wdata_int[31:2], 1'b0, csr_wdata_int[0]}; // bit 1 must always be 0\n end else begin\n mcountinhibit_d = mcountinhibit_q;\n end\n end\n\n assign mcountinhibit_force = {{29-MHPMCounterNum{1'b1}}, {MHPMCounterNum{1'b0}}, 3'b000};\n assign mcountinhibit = mcountinhibit_q | mcountinhibit_force;\n\n // event selection (hardwired) & control\n always_comb begin : gen_mhpmcounter_incr\n\n // When adding or altering performance counter meanings and default\n // mappings please update dv/verilator/pcount/cpp/ibex_pcounts.cc\n // appropriately.\n //\n // active counters\n mhpmcounter_incr[0] = 1'b1; // mcycle\n mhpmcounter_incr[1] = 1'b0; // reserved\n mhpmcounter_incr[2] = instr_ret_i; // minstret\n mhpmcounter_incr[3] = lsu_busy_i; // cycles waiting for data memory\n mhpmcounter_incr[4] = imiss_i & ~pc_set_i; // cycles waiting for instr fetches\n // excl. jump and branch set cycles\n mhpmcounter_incr[5] = mem_load_i; // num of loads\n mhpmcounter_incr[6] = mem_store_i; // num of stores\n mhpmcounter_incr[7] = jump_i; // num of jumps (unconditional)\n mhpmcounter_incr[8] = branch_i; // num of branches (conditional)\n mhpmcounter_incr[9] = branch_taken_i; // num of taken branches (conditional)\n mhpmcounter_incr[10] = instr_ret_compressed_i; // num of compressed instr\n\n // inactive counters\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmcounter_incr_inactive\n mhpmcounter_incr[i] = 1'b0;\n end\n end\n\n // event selector (hardwired, 0 means no event)\n always_comb begin : gen_mhpmevent\n\n // activate all\n for (int i=0; i<32; i++) begin : gen_mhpmevent_active\n mhpmevent[i] = '0;\n mhpmevent[i][i] = 1'b1;\n end\n\n // deactivate\n mhpmevent[1] = '0; // not existing, reserved\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmevent_inactive\n mhpmevent[i] = '0;\n end\n end\n\n // mask, controls effective counter width\n always_comb begin : gen_mask\n\n for (int i=0; i<3; i++) begin : gen_mask_fixed\n // mcycle, mtime, minstret are always 64 bit wide\n mhpmcounter_mask[i] = {64{1'b1}};\n end\n\n for (int unsigned i=3; i<3+MHPMCounterNum; i++) begin : gen_mask_configurable\n // mhpmcounters have a configurable width\n mhpmcounter_mask[i] = {{64-MHPMCounterWidth{1'b0}}, {MHPMCounterWidth{1'b1}}};\n end\n\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mask_inactive\n // mask inactive mhpmcounters\n mhpmcounter_mask[i] = '0;\n end\n end\n\n // update\n always_comb begin : mhpmcounter_update\n mhpmcounter_d = mhpmcounter_q;\n\n for (int i=0; i<32; i++) begin : gen_mhpmcounter_update\n\n // increment\n if (mhpmcounter_incr[i] & ~mcountinhibit[i]) begin\n mhpmcounter_d[i] = mhpmcounter_mask[i] & (mhpmcounter_q[i] + 64'h1);\n end\n\n // write\n if (mhpmcounter_we[i]) begin\n mhpmcounter_d[i][31: 0] = mhpmcounter_mask[i][31: 0] & csr_wdata_int;\n end else if (mhpmcounterh_we[i]) begin\n mhpmcounter_d[i][63:32] = mhpmcounter_mask[i][63:32] & csr_wdata_int;\n end\n end\n end\n\n // performance monitor registers\n always_ff @(posedge clk_i or negedge rst_ni) begin : perf_counter_registers\n if (!rst_ni) begin\n mcountinhibit_q <= '0;\n for (int i=0; i<32; i++) begin\n mhpmcounter_q[i] <= '0;\n end\n end else begin\n mhpmcounter_q <= mhpmcounter_d;\n mcountinhibit_q <= mcountinhibit_d;\n end\n end\n\nendmodule\n", "selected_doc_paths": ["doc/cs_registers.rst", "doc/debug.rst", "doc/exception_interrupts.rst", "doc/pmp.rst", "doc/performance_counters.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 425, "lang": "sv", "rtl_files": ["rtl/ibex_load_store_unit.sv"], "spec": "# Load-Store Unit (LSU) Behavioral Specification\n\n## Scope and Purpose\n\nThe Load-Store Unit (LSU) manages all data memory accesses for the processor core. It is responsible for:\n- Translating load and store requests from the execution pipeline into word-aligned memory transactions.\n- Handling misaligned accesses by splitting them into two sequential aligned transactions.\n- Providing alignment, byte-enable generation, and data realignment for partial-word accesses (bytes, half words).\n- Managing the handshake protocol with the data memory interface.\n- Collecting error information (bus errors and physical memory protection (PMP) violations) and signalling load/store exceptions to the core.\n\nThe LSU is designed to work with a memory system that supports a request‑grant‑response protocol, with in‑order completion of requests. It is capable of handling a single outstanding misaligned access, but does not support multiple outstanding standard requests (though the memory interface may support pipelining within a single access).\n\n---\n\n## Interface Description\n\n### Pipeline Interface (to/from ID/EX stage)\n\n- **Request from pipeline**: \n A new load or store operation is signalled when the pipeline sends a data request. The request includes:\n - The computed memory address.\n - The data type (word, half-word, byte).\n - For stores, the write data.\n - A sign‑extension indication for loads.\n - A write enable signal (indicating load or store).\n\n- **Response to pipeline**: \n The LSU delivers:\n - The aligned and sign‑extended read data (for loads).\n - A data valid signal indicating that the transaction has completed (either successfully or with an error).\n - An address increment request, used during misaligned accesses to update the address for the second part.\n - The address of the last transaction, which is used for exception handling (mtval) and for the address generation unit during misaligned accesses.\n - Separate load error and store error signals, asserted when the transaction results in a bus error or PMP violation.\n\n- **Busy indication**: \n The LSU signals when it is currently processing a transaction (i.e., not idle). The pipeline must not issue a new request while the LSU is busy.\n\n### Data Memory Interface\n\n- **Request**: \n The LSU issues a memory request with:\n - A word‑aligned address.\n - A write enable signal (high for stores, low for loads).\n - Byte enables indicating which bytes are valid (derived from the original address and access size).\n - Write data (for stores, rotated to align with the word‑aligned address).\n\n- **Grant**: \n The memory interface may accept the request in the same cycle or later. Once granted, the LSU may change the request signals in the next cycle for a new request.\n\n- **Response**: \n For each granted request, the memory interface returns a single‑cycle valid signal together with read data (for loads) and an error flag. Responses are returned in the same order as requests.\n\n- **Error**: \n The error signal indicates a bus error or a PMP violation. The LSU treats both as equivalent – i.e., any active error at the time a response is consumed causes an exception.\n\n---\n\n## Supported Access Types\n\nThe LSU supports the following operations:\n\n| Operation | Size | Natural alignment |\n|-----------|--------|-------------------|\n| Load word | 32‑bit | 4‑byte boundary |\n| Store word | 32‑bit | 4‑byte boundary |\n| Load half‑word | 16‑bit | 2‑byte boundary |\n| Store half‑word| 16‑bit | 2‑byte boundary |\n| Load byte | 8‑bit | 1‑byte boundary |\n| Store byte | 8‑bit | 1‑byte boundary |\n\nAll loads and stores shall complete in at least one cycle (plus any wait cycles for the memory interface).\n\n---\n\n## Misaligned Access Handling\n\nAn access is considered **misaligned** when the address is not aligned to the natural boundary of the access size. Specifically:\n- A word access with address bits [1:0] not equal to `00`.\n- A half‑word access with address bit [0] equal to `1` (i.e., address modulo 2 not zero).\n\nThe LSU shall handle such misaligned accesses transparently by splitting them into two word‑aligned transactions:\n\n1. **First transaction**: begins at the given misaligned address, but with the address forced to a word‑aligned base. The byte enables are set to cover only the bytes that are part of the original access (first part).\n2. **Second transaction**: begins at the next word‑aligned address (the address of the first transaction plus 4). The byte enables cover the remaining bytes of the original access.\n\nFor a misaligned **load**, the read data from the two transactions are merged and realigned before being presented to the pipeline.\n\nFor a misaligned **store**, the write data is split into two parts and presented on the two transactions with appropriate byte enables.\n\nWhile a misaligned access is in progress, the LSU must not accept a new request from the pipeline. The pipeline is stalled until both transactions have completed.\n\nIf an error occurs on the first transaction, the LSU shall still issue the second transaction (following the normal bus protocol) but then ignore its response and data. The error from the first transaction shall be reported to the pipeline after both transactions have completed.\n\n---\n\n## Protocol Behaviour\n\nThe LSU operates according to the following protocol with the memory interface:\n\n1. **Request phase**: \n When the pipeline issues a request and the LSU is idle, it asserts the memory request signals with the appropriate address, write enable, byte enables, and write data (for stores). The request remains asserted until the memory grants it.\n\n2. **Grant phase**: \n The memory may grant the request in the same cycle or after any number of idle cycles. After grant, the LSU may change all request signals in the following cycle for the next request.\n\n3. **Response phase**: \n After grant, the memory returns a valid signal (for exactly one cycle) together with read data (for loads) and an error flag. The response may come one or more cycles after the grant.\n\n4. **Ordering**: \n The memory must return responses in the same order as the requests were granted. The LSU assumes this ordering.\n\n5. **Completion**: \n When the response is received, the LSU:\n - For loads: outputs the aligned, sign‑extended read data and asserts the data valid signal.\n - For stores: asserts the data valid signal.\n - If an error is signalled, it additionally asserts the appropriate load or store error signal.\n\nAfter completing a transaction (including both parts of a misaligned access), the LSU returns to idle and can accept a new pipeline request.\n\n---\n\n## Error Handling\n\nErrors can arise from two sources:\n- **Bus error** (data_err): indicates a memory access fault (e.g., address mismatch, protection violation).\n- **PMP error** (data_pmp_err): indicates a Physical Memory Protection violation.\n\nBoth are considered **access exceptions**. The LSU shall:\n\n- Register the error status at the time a request is made or a response is received.\n- If an error occurs on a transaction, the core will raise an exception after the LSU completes the entire access (including aborted second parts of misaligned accesses).\n- For loads, the error shall be signalled as `load_err`; for stores, as `store_err`.\n- In case of a misaligned access where the first part encounters an error, the second part is still issued (as required by the bus protocol), but its response and data are ignored. The error from the first part will be reported.\n\nThe LSU does not suppress the error for the second part; instead, the registered error from the first part overrides any later responses.\n\n---\n\n## Data Alignment and Sign Extension\n\nThe LSU shall:\n\n- **For loads**: realign the data returned from memory according to the original address offset. That is, the least‑significant byte of the returned 32‑bit word may be rotated to match the alignment of the original misaligned address.\n- **For stores**: rotate the write data so that the bytes that should be stored are placed in the correct positions relative to the word‑aligned memory address.\n- **Sign extension**: For signed byte and half‑word loads, the data shall be sign‑extended to 32 bits. For unsigned loads, zero‑extension shall be performed.\n- **Byte enables**: For each transaction, correct byte enables shall be generated based on the original access size, the current address, and whether it is the first or second part of a misaligned access.\n\n---\n\n## Address Increment Request\n\nDuring a misaligned access, after receiving the grant for the first part, the LSU shall request the pipeline to increment the address for the second part. This request stays active until the second part is granted. The pipeline uses this request to update the address register used for the next memory transaction.\n\n---\n\n## Last Address for Exceptions\n\nThe LSU shall store the address of the last completed transaction (the address that was used for the final request of the access). This address is provided to the core for use as `mtval` when an exception occurs. The stored address shall not be updated if an error is detected during the access; instead, it shall retain the address of the failing transaction.\n\nIf a misaligned access fails on the first part, the stored address shall be the address of the first transaction (the original misaligned address). If it fails on the second part, it shall be the address of the second transaction.\n\n---\n\n## Busy Indication\n\nThe LSU shall assert `busy` whenever it is not in the idle state. While busy, the pipeline shall not issue a new request. The busysignal is de‑asserted when the LSU returns to idle after completing an access.\n\n---\n\n## Reset and Initial State\n\nAfter reset, the LSU shall be in idle state with no pending transactions, all internal state cleared, and all output signals de‑asserted (or at defined values where appropriate, such as the last address set to zero).\n\n---\n\n## Constraints and Assumptions\n\n- The memory interface must guarantee that responses are returned in order and that each granted request eventually produces exactly one response.\n- The memory interface may insert any number of wait cycles between grant and response, and between successive grants.\n- The pipeline must not issue a new request while the LSU is busy.\n- The LSU assumes that the PMP checking is performed on the address before the request is sent; a PMP error signal may be asserted together with the address, and the LSU must treat it as an error after the grant phase (if the request is granted) or report it immediately if the grant never arrives.\n\n---\n\n*This specification defines the functional behaviour of the Load-Store Unit. The implementation must satisfy all conditions described here, but may choose internal micro‑architecture (FSM states, pipelining, etc.) as long as the external protocol and requirements are met.*", "commit_id": "294849bb18e27c0487b7317f53ca878217712ffd", "timestamp": "2019-10-26T13:51:20+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "36ce999fbb8f843035f1cb82f1235dbf9d6c3698", "pr_title": "[rtl/lsu] Rework assertion checking response valid", "pr_body": "This commit replaces an obsolete assertion with one checking that response valid is received only if the LSU is ready to handle it.\r\n\r\nThis resolves lowRISC/ibex#421 reported by @udinator.", "issue_title": "LSU: Remove/correct obsolete assertion", "issue_body": "Inside `ibex_load_store_unit.sv`, we have an assertion checking that in the RVALID state, a grant can only be received while also getting the rvalid. This assertion has become obsolete in the process of adding PMP support. Currently, the RVALID state is only entered when a grant is no longer expected.\r\n\r\nThis assertion should be removed or corrected. ", "commit_message": "[rtl/lsu] Rework assertion checking response valid\n\nThis commit replaces an obsolete assertion with one checking that\nresponse valid is received only if the LSU is ready to handle it.\n\nThis resolves lowRISC/ibex#421 reported by @udinator.", "fix_patch": "diff --git a/rtl/ibex_load_store_unit.sv b/rtl/ibex_load_store_unit.sv\nindex 2c08892e0e..d823938ead 100644\n--- a/rtl/ibex_load_store_unit.sv\n+++ b/rtl/ibex_load_store_unit.sv\n@@ -483,18 +483,11 @@ module ibex_load_store_unit (\n ////////////////\n \n `ifndef VERILATOR\n- // make sure there is no new request when the old one is not yet completely done\n- // i.e. it should not be possible to get a grant without an rvalid for the\n- // last request\n+ // there should not be an rvalid unless the FSM is handlling it\n assert property (\n- @(posedge clk_i)\n- ((ls_fsm_cs == WAIT_RVALID) && (data_gnt_i == 1'b1)) |-> (data_rvalid_i == 1'b1) ) else\n- $display(\"Data grant set while LSU keeps waiting for rvalid\");\n-\n- // there should be no rvalid when we are in IDLE\n- assert property (\n- @(posedge clk_i) (ls_fsm_cs == IDLE) |-> (data_rvalid_i == 1'b0) ) else\n- $display(\"Data rvalid set while LSU idle\");\n+ @(posedge clk_i) (data_rvalid_i) |-> ((ls_fsm_cs == WAIT_RVALID) ||\n+ (ls_fsm_cs == WAIT_RVALID_MIS) || (ls_fsm_cs == WAIT_RVALID_DONE)) ) else\n+ $display(\"Data response valid received without expecting it\");\n \n // assert that errors are only sent at the same time as rvalid\n assert property (\n", "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 * Load Store Unit\n *\n * Load Store Unit, used to eliminate multiple access during processor stalls,\n * and to align bytes and halfwords.\n */\nmodule ibex_load_store_unit (\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 data_we_ex_i, // write enable -> from ID/EX\n input logic [1:0] data_type_ex_i, // data type: word, half word, byte -> from ID/EX\n input logic [31:0] data_wdata_ex_i, // data to write to memory -> from ID/EX\n input logic data_sign_ext_ex_i, // sign extension -> from ID/EX\n\n output logic [31:0] data_rdata_ex_o, // requested data -> to ID/EX\n input logic data_req_ex_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 output logic data_valid_o, // LSU has completed transaction -> to ID/EX\n\n // exception signals\n output logic load_err_o,\n output logic store_err_o,\n\n output logic busy_o\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] wdata_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, WAIT_RVALID,\n WAIT_RVALID_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\n ///////////////////\n // BE generation //\n ///////////////////\n\n always_comb begin\n unique case (data_type_ex_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_addr[1:0])\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 = 'X;\n endcase // case (data_addr[1:0])\n end else begin // second part of misaligned transaction\n unique case (data_addr[1:0])\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 = 'X;\n endcase // case (data_addr[1:0])\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_addr[1:0])\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 = 'X;\n endcase // case (data_addr[1:0])\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_addr[1:0])\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 = 'X;\n endcase // case (data_addr[1:0])\n end\n\n default: data_be = 'X;\n endcase // case (data_type_ex_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 assign wdata_offset = data_addr[1:0];\n always_comb begin\n unique case (wdata_offset)\n 2'b00: data_wdata = data_wdata_ex_i[31:0];\n 2'b01: data_wdata = {data_wdata_ex_i[23:0], data_wdata_ex_i[31:24]};\n 2'b10: data_wdata = {data_wdata_ex_i[15:0], data_wdata_ex_i[31:16]};\n 2'b11: data_wdata = {data_wdata_ex_i[ 7:0], data_wdata_ex_i[31: 8]};\n default: data_wdata = 'X;\n endcase // case (wdata_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_addr[1:0];\n data_type_q <= data_type_ex_i;\n data_sign_ext_q <= data_sign_ext_ex_i;\n data_we_q <= data_we_ex_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 = 'X;\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 = 'X;\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 = 'X;\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 = 'X;\n endcase //~case(rdata_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 ((data_type_ex_i == 2'b00) && (data_addr[1:0] != 2'b00)) || // misaligned word access\n ((data_type_ex_i == 2'b01) && (data_addr[1:0] == 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 data_valid_o = 1'b0;\n addr_incr_req_o = 1'b0;\n handle_misaligned_d = handle_misaligned_q;\n data_or_pmp_err = 1'b0;\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 unique case (ls_fsm_cs)\n\n IDLE: begin\n if (data_req_ex_i) begin\n data_req_o = 1'b1;\n pmp_err_d = data_pmp_err_i;\n lsu_err_d = 1'b0;\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 : WAIT_RVALID;\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 ? WAIT_RVALID : 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\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_DONE;\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 = WAIT_RVALID;\n end\n end\n\n WAIT_RVALID: begin\n if (data_rvalid_i || pmp_err_q) begin\n data_valid_o = 1'b1;\n // Data error from either part\n data_or_pmp_err = lsu_err_q | data_err_i | pmp_err_q;\n handle_misaligned_d = 1'b0;\n ls_fsm_ns = IDLE;\n end else begin\n ls_fsm_ns = WAIT_RVALID;\n end\n end\n\n WAIT_RVALID_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 = WAIT_RVALID;\n end\n end\n\n default: begin\n ls_fsm_ns = ls_fsm_e'(1'bX);\n end\n endcase\n end\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 // output to register file\n assign data_rdata_ex_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 = data_we_ex_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;\n assign store_err_o = data_or_pmp_err & data_we_q;\n\n assign busy_o = (ls_fsm_cs != IDLE);\n\n ////////////////\n // Assertions //\n ////////////////\n\n`ifndef VERILATOR\n // there should not be an rvalid unless the FSM is handlling it\n assert property (\n @(posedge clk_i) (data_rvalid_i) |-> ((ls_fsm_cs == WAIT_RVALID) ||\n (ls_fsm_cs == WAIT_RVALID_MIS) || (ls_fsm_cs == WAIT_RVALID_DONE)) ) else\n $display(\"Data response valid received without expecting it\");\n\n // assert that errors are only sent at the same time as rvalid\n assert property (\n @(posedge clk_i) (data_err_i) |-> (data_rvalid_i) ) else\n $display(\"Data error not sent with rvalid\");\n\n // assert that the address does not contain X when request is sent\n assert property (\n @(posedge clk_i) (data_req_o) |-> (!$isunknown(data_addr_o)) ) else\n $display(\"Data address not valid\");\n\n // assert that the address is word aligned when request is sent\n assert property (\n @(posedge clk_i) (data_req_o) |-> (data_addr_o[1:0] == 2'b00) ) else\n $display(\"Data address not word aligned\");\n`endif\nendmodule\n", "selected_doc_paths": ["doc/load_store_unit.rst", "doc/pmp.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 295, "lang": "sv", "rtl_files": ["dv/uvm/common/ibex_mem_intf_agent/ibex_mem_intf_slave_driver.sv"], "spec": "# Behavioral Specification: Ibex Memory Interface Slave Driver\n\n## Overview\n\nThis module implements a memory slave driver for the Ibex core’s memory interface (used for both instruction fetch and load/store unit). It acts as a simulated memory device that responds to requests from the Ibex core. The driver is part of a UVM testbench; its behavior is purely functional and deterministic (no random delays unless explicitly configured).\n\nThe driver drives three output signals on the bus interface:\n- grant (acknowledgment of the request)\n- rvalid (indicates that read data is valid)\n- rdata (the read data)\n\nIt observes the request, address, and reset signals from the core. The driver does **not** generate error responses; it assumes all transactions complete successfully (error signal remains deasserted).\n\n---\n\n## Interface Signals\n\nThe driver interacts with a virtual interface that contains the following signals:\n\n| Signal direction (from driver perspective) | Description |\n|-------------------------------------------|-------------|\n| Output (driven) | grant – Indicates that the memory has accepted the request. Asserted for exactly one cycle. |\n| Output (driven) | rvalid – Indicates that read data is valid. Asserted for exactly one cycle per read request. |\n| Output (driven) | rdata – Read data bus. Must be stable when rvalid is asserted. |\n| Input (observed) | request – Request from the core. When high, a transaction is initiated. |\n| Input (observed) | address – The address associated with the request. |\n| Input (observed) | clock – Clock for synchronous operation. |\n| Input (observed) | reset – Active-low reset signal. |\n\n---\n\n## Behavior\n\n### 1. Reset\n\nWhen the reset signal is asserted (low), the driver shall immediately:\n- Deassert grant and rvalid.\n- Set rdata to an undefined value (all bits unknown).\n\nThe driver shall remain in this inactive state until reset is deasserted (reset goes high). After reset deassertion, the driver shall wait for the first positive clock edge before beginning any operation.\n\n### 2. Grant Response\n\nThe driver provides a grant for every request it observes. The grant behavior is as follows:\n\n- The driver continuously monitors the request signal.\n- In every clock cycle where request is high and reset is deasserted, the driver shall assert grant for exactly one cycle (starting in the same cycle or the next? Based on typical protocol and the RTL: grant is asserted on the same cycle when request is high, but only at the negative edge of clock? Actually from the code: it waits until request is 1, then at the next negative edge of clock it sets grant high. However the spec should state: The driver asserts grant in the first clock cycle after the request is observed high, and deasserts it one cycle later. This matches the typical protocol where grant can be given in the same cycle if the memory is ready. Since the driver always grants immediately (no random delays), grant will be asserted on the next clock edge after request is seen. For clarity: The driver shall assert grant for one clock cycle in response to every rising edge of request, provided reset is deasserted.\n\n- If request remains high for multiple cycles, the driver shall issue grant only once per request, not repeatedly. The core expects grant to be high for only one cycle per request.\n\n- Grant shall not be asserted during reset (reset low).\n\n- The driver does not add any delay between request and grant; it is always ready to accept the request in the next cycle.\n\n### 3. Read Data Response\n\nAfter granting a read request, the driver must return read data later with a valid signal. The response timing is configurable per transaction:\n\n- Each read request is associated with a delay (number of clock cycles) between the grant cycle and the assertion of rvalid. This delay is specified for each transaction in the sequence item provided to the driver.\n- The driver shall wait the specified number of positive clock edges after the grant cycle, and then assert rvalid for exactly one cycle. During that cycle, rdata shall be driven with the data value from the transaction.\n- The driver shall not assert rvalid while reset is asserted. If reset occurs during the delay, the count shall be discarded and the pending response shall be cancelled (the transaction is effectively dropped). After reset, the driver resumes normal operation with new requests.\n- The data returned must be the data associated with that specific request. The address at the time of grant is not directly used by the driver; it obtains the data from the sequence item. (Out-of-scope: The core expects the returned data to correspond to the address that was valid when grant was given; this is guaranteed by the testbench sequencing.)\n\n### 4. Transaction Ordering\n\nThe driver maintains the order of requests it receives. Responses shall be returned in the exact same order as the corresponding grants were issued. Specifically:\n- A mailbox (or equivalent queue) stores the response information (data, delay) for each granted request.\n- When a read request is granted, its response details are enqueued.\n- The driver processes the queue sequentially: for each enqueued item, it waits the specified delay and then drives rvalid/rdata. It does not skip or reorder responses.\n- This ordering applies even if multiple requests are granted in consecutive cycles (back-to-back requests). The driver will service them one after another.\n\n### 5. Handling of Multiple Outstanding Requests\n\nThe driver supports multiple outstanding requests (the core may send a new request before receiving the rvalid of the previous one). The driver must:\n- Accept and grant each new request as it occurs (subject to the grant behavior above).\n- Queue the response details for each granted request.\n- Continue to process the queue, servicing each response in order, one at a time. While waiting for the delay of a response, it may still receive new requests and grant them, but it will not start a new rvalid until the current response is complete.\n\nThe driver does **not** impose any limit on the number of outstanding requests; it will continue to accept requests indefinitely.\n\n### 6. Write Transactions\n\nThe driver is solely a read response driver. It does not model write behavior (the memory interface for writes does not produce grant or rvalid in the same way). The driver will still observe write requests (identified by the core's write-enable signal if present), but it shall ignore them – it will not assert grant for write transactions. The responsibility of handling write responses lies elsewhere in the testbench.\n\n### 7. Configuration Parameters\n\nThe driver has a single configurable parameter per transaction:\n- **rvalid_delay**: Number of clock cycles between the cycle in which grant is driven high and the cycle in which rvalid is driven high. This value must be non-negative. If zero, rvalid may be asserted in the same cycle as grant (subject to clock edge alignment; typically the next cycle).\n\nNo other delays are configurable; grant is always immediate.\n\n---\n\n## Assumptions\n\n- The interface is synchronous and operates on the positive edge of the clock.\n- The virtual interface provides a clean, glitch-free request signal.\n- The driver is used only for read transactions (instruction fetch and load operations). Write transactions are handled separately.\n- The driver does not need to model error responses; the error signal is driven low by the testbench or left floating.\n- The reset signal is active-low and asserted asynchronously (or synchronously, but the driver uses negative edge detection for reset to avoid race conditions).\n\n---\n\n## Summary of Key Behaviors\n\n| Condition | Driver Action |\n|-----------|---------------|\n| Reset low | Deassert grant and rvalid; invalidate rdata |\n| Request high, reset high after reset deassertion | Assert grant for one cycle at next clock edge; queue response |\n| After grant, during rvalid delay count | Wait specified number of clock cycles; ignore request until count reached? (No, it can accept new requests during delay) |\n| After delay expires, reset still high | Assert rvalid for one cycle; drive rdata with transaction data |\n| Back-to-back requests | Grant each in consecutive cycles; responses queued and returned in order |\n| New request while previous response delayed | Can grant new request immediately; response added to queue and serviced after current response finishes |\n| Reset occurs during pending delay | Abort pending response; discard queue; reset all outputs |\n\nThis specification defines the correct observable behavior of the Ibex memory interface slave driver, independent of its internal implementation.", "commit_id": "8d3d87ae53254f7716852e944caffa788b473253", "timestamp": "2019-09-09T21:31:30+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "ac22439374a0bafd6fc2f9d38aefc02e44fa2abb", "pr_title": "Update slave_driver grant timing to pass Ibex assertion checks", "pr_body": "Update the timing of when the testbench sends grants to Ibex, partially addresses the assertion failures mentioned in #293.", "issue_title": "[I-side] - Fix issues found in tracing example", "issue_body": "- Fixes #288\r\n- Add missing grant qualification to stop spurious address updates\r\n- Make RTL robust to spurious rvalid signalling", "commit_message": "Update slave_driver grant timing to pass Ibex assertion checks", "fix_patch": "diff --git a/dv/uvm/common/ibex_mem_intf_agent/ibex_mem_intf_slave_driver.sv b/dv/uvm/common/ibex_mem_intf_agent/ibex_mem_intf_slave_driver.sv\nindex e57803ddab..2a48b9d8be 100644\n--- a/dv/uvm/common/ibex_mem_intf_agent/ibex_mem_intf_slave_driver.sv\n+++ b/dv/uvm/common/ibex_mem_intf_agent/ibex_mem_intf_slave_driver.sv\n@@ -10,9 +10,6 @@ class ibex_mem_intf_slave_driver extends uvm_driver #(ibex_mem_intf_seq_item);\n \n protected virtual ibex_mem_intf vif;\n \n- int unsigned min_grant_delay = 0;\n- int unsigned max_grant_delay = 10;\n-\n `uvm_component_utils(ibex_mem_intf_slave_driver)\n `uvm_component_new\n \n@@ -58,20 +55,15 @@ class ibex_mem_intf_slave_driver extends uvm_driver #(ibex_mem_intf_seq_item);\n join_none\n endtask : get_and_drive\n \n+ // TODO(udinator) - this direct send_grant logic is temporary until instruction fetch protocol\n+ // issue is clarified (https://github.com/lowRISC/ibex/pull/293). After resolution, will re-add\n+ // random delays insertion before driving grant to the ibex core.\n virtual protected task send_grant();\n int gnt_delay;\n forever begin\n while(vif.request !== 1'b1) begin\n @(negedge vif.clock);\n end\n- std::randomize(gnt_delay) with {\n- gnt_delay dist {\n- min_grant_delay :/ 1,\n- [min_grant_delay+1 : max_grant_delay-1] :/ 1,\n- max_grant_delay :/ 1\n- };\n- };\n- repeat(gnt_delay) @(negedge vif.clock);\n if(~vif.reset) begin\n vif.grant = 1'b1;\n @(negedge vif.clock);\n", "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// CLASS: ibex_mem_intf_slave_driver\n//------------------------------------------------------------------------------\n\nclass ibex_mem_intf_slave_driver extends uvm_driver #(ibex_mem_intf_seq_item);\n\n protected virtual ibex_mem_intf vif;\n\n `uvm_component_utils(ibex_mem_intf_slave_driver)\n `uvm_component_new\n\n mailbox #(ibex_mem_intf_seq_item) grant_queue;\n mailbox #(ibex_mem_intf_seq_item) rdata_queue;\n\n function void build_phase(uvm_phase phase);\n super.build_phase(phase);\n grant_queue = new();\n rdata_queue = new();\n if(!uvm_config_db#(virtual ibex_mem_intf)::get(this, \"\", \"vif\", vif))\n `uvm_fatal(\"NOVIF\",{\"virtual interface must be set for: \",get_full_name(),\".vif\"});\n endfunction: build_phase\n\n virtual task run_phase(uvm_phase phase);\n reset_signals();\n fork\n send_grant();\n join_none\n get_and_drive();\n endtask : run_phase\n\n virtual protected task reset_signals();\n vif.rvalid <= 1'b0;\n vif.grant <= 1'b0;\n vif.rdata <= 'b0;\n endtask : reset_signals\n\n virtual protected task get_and_drive();\n @(negedge vif.reset);\n fork\n forever begin\n ibex_mem_intf_seq_item req, req_c;\n @(posedge vif.clock);\n seq_item_port.get_next_item(req);\n $cast(req_c, req.clone());\n if(~vif.reset) begin\n rdata_queue.put(req_c);\n end\n seq_item_port.item_done();\n end\n send_read_data();\n join_none\n endtask : get_and_drive\n\n // TODO(udinator) - this direct send_grant logic is temporary until instruction fetch protocol\n // issue is clarified (https://github.com/lowRISC/ibex/pull/293). After resolution, will re-add\n // random delays insertion before driving grant to the ibex core.\n virtual protected task send_grant();\n int gnt_delay;\n forever begin\n while(vif.request !== 1'b1) begin\n @(negedge vif.clock);\n end\n if(~vif.reset) begin\n vif.grant = 1'b1;\n @(negedge vif.clock);\n vif.grant = 1'b0;\n end\n end\n endtask : send_grant\n\n virtual protected task send_read_data();\n ibex_mem_intf_seq_item tr;\n forever begin\n @(posedge vif.clock);\n vif.rvalid <= 1'b0;\n vif.rdata <= 'x;\n rdata_queue.get(tr);\n if(vif.reset) continue;\n repeat(tr.rvalid_delay) @(posedge vif.clock);\n if(~vif.reset) begin\n vif.rvalid <= 1'b1;\n vif.rdata <= tr.data;\n end\n end\n endtask : send_read_data\n\nendclass : ibex_mem_intf_slave_driver\n", "selected_doc_paths": ["doc/instruction_fetch.rst", "doc/load_store_unit.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 375, "lang": "sv", "rtl_files": ["rtl/ibex_tracer.sv"], "spec": "# Behavioral Design Specification for `ibex_tracer`\n\n## 1. Overview\n\nThe `ibex_tracer` module generates a human-readable log of instructions executed by an Ibex core during simulation. It monitors the RISC‑V Formal Interface (RVFI) signals emitted by the core and, for every valid instruction, writes a formatted trace line to a plain‑text file. The trace is written in a six‑column, tab‑separated format that includes simulation time, cycle count, program counter, raw instruction, a disassembled instruction string, and the values of accessed registers or memory locations.\n\nThe tracer is intended for simulation and debug use only; it has no impact on the functional behavior of the core and is not synthesizable. It is explicitly not used in production silicon.\n\n## 2. Interface\n\nThe module is driven by the following top‑level signals:\n\n- **Clock and reset** – A single‑clock domain with an active‑low asynchronous reset.\n- **Hart ID** – A 32‑bit value that identifies the core instance being traced.\n- **RVFI signals** – Standard RVFI signals as defined in the [RISC‑V Formal Interface specification](https://github.com/SymbioticEDA/riscv-formal/blob/master/docs/rvfi.md). These include:\n - `rvfi_valid` – Indicates that the current instruction is committed and the remaining RVFI fields hold meaningful data.\n - Instruction word, program counter, register addresses and data, memory address and data, and status flags (trap, halt, interrupt, privilege mode).\n\nThe tracer ignores the `rvfi_order`, `rvfi_trap`, `rvfi_halt`, `rvfi_intr`, and `rvfi_mode` signals; these are included in the interface for future flexibility but do not influence trace output.\n\n## 3. Functional Behaviour\n\n### 3.1 File Creation and Naming\n\nWhen the first valid instruction is logged (i.e., the first assertion of `rvfi_valid` after reset), the module opens a log file for writing. The file is named with the following pattern:\n\n```\n_.log\n```\n\n- `` defaults to `trace_core`.\n- `` may be overridden by passing the plusarg `+ibex_tracer_file_base=` to the simulator (e.g., `+ibex_tracer_file_base=my_trace`).\n- `` is the value of `hart_id_i`, formatted as an 8‑digit uppercase hexadecimal number (zero‑padded if necessary).\n\nIf the file cannot be opened, the module continues operation but no trace output is produced. A simulation message displays the path of the opened log file.\n\nThe log file remains open for the entire simulation. At the end of simulation (in a `final` block), the file handle is closed.\n\n### 3.2 Cycle Counter\n\nThe module maintains an internal unsigned integer cycle counter. The counter:\n\n- Resets to 0 on asynchronous reset.\n- Increments by 1 on every rising clock edge, regardless of `rvfi_valid`.\n\nThe cycle counter is included in each trace line.\n\n### 3.3 Trace Line Generation\n\nOn every rising clock edge where `rvfi_valid` is asserted (high), the module performs the following steps:\n\n1. **Format the time** – The current simulation time (as returned by the `$time` system function) is captured.\n2. **Format the cycle count** – The current value of the cycle counter is used.\n3. **Extract the program counter** – The `rvfi_pc_rdata` field provides the PC of the executed instruction.\n4. **Extract the instruction word** – The `rvfi_insn` field provides the raw instruction encoding.\n - If the instruction is a 16‑bit compressed instruction (determined by the low two bits being other than `2'b11`), only the lower 16 bits of the instruction are printed in the trace (four hex digits).\n - Otherwise, the full 32‑bit instruction is printed (eight hex digits).\n5. **Decode the instruction** – The module performs a combinatorial decode of the instruction word to produce a human‑readable string. The decoding shall match the output of `objdump -Mnumeric -Mno-aliases -D` as closely as possible (see Section 4 – Decoding Rules).\n6. **Format register and memory accesses** – The module identifies which source and destination registers and/or memory locations were accessed during the instruction execution. For each accessed entity, the following information is appended to the trace line:\n - **Register reads** – `:` (value before execution, 32‑bit hexadecimal).\n - **Register writes** – `=` (value after execution, 32‑bit hexadecimal).\n - **Memory accesses** – `PA:
` if either a load or store occurred. Then, if a store (write mask non‑zero), append ` store:`; if a load (read mask non‑zero), append ` load:`. Both values are 32‑bit hexadecimal.\n\nThe trace line is written to the log file. The line ends with a newline character.\n\n### 3.4 Reset Behaviour\n\nWhen reset is asserted, the cycle counter is cleared. No trace lines are written while reset is asserted.\n\n### 3.5 Simulation End\n\nIn the `final` block (or equivalent end‑of‑simulation callback), if the log file was opened, it is flushed and closed.\n\n## 4. Output Format\n\nThe log file contains a header line followed by one trace line per valid instruction. All columns are separated by a single tab character.\n\n**Header:**\n```\nTime\tCycle\tPC\tInsn\tDecoded instruction\tRegister and memory contents\n```\n\n**Trace line columns:**\n\n| Column | Content | Format |\n|--------|---------|--------|\n| 1. Time | Simulation time | `%15t` (fixed width) |\n| 2. Cycle | Cycle count since reset | Decimal |\n| 3. PC | Program counter of executed instruction | Lower‑case hexadecimal, no prefix |\n| 4. Insn | Instruction encoding (16‑ or 32‑bit) | Lower‑case hexadecimal, no prefix |\n| 5. Decoded instruction | Disassembly string (see Section 5) | Plain text |\n| 6. Register and memory contents | Zero or more space‑separated items | See Section 3.3 |\n\n**Example (taken from the official documentation):**\n\n```\nTime Cycle PC Insn Decoded instruction Register and memory contents\n 130 61 00000150 4481 c.li x9,0 x9=0x00000000\n 132 62 00000152 00008437 lui x8,0x8 x8=0x00008000\n 134 63 00000156 fff40413 addi x8,x8,-1 x8:0x00008000 x8=0x00007fff\n 136 64 0000015a 8c65 c.and x8,x9 x8:0x00007fff x9:0x00000000 x8=0x00000000\n 142 67 0000015c c622 c.swsp x8,12(x2) x2:0x00002000 x8:0x00000000 PA:0x0000200c store:0x00000000 load:0xffffffff\n```\n\n## 5. Decoding Rules\n\nThe decoded instruction string shall conform to the following rules:\n\n1. **Mnemonic** – The standard RISC‑V mnemonic (all lower‑case) is used, including compressed instruction mnemonics (e.g., `c.li`, `c.add`).\n2. **Register names** – All general‑purpose registers are referenced using the numeric `x`‑prefix format (e.g., `x1`, `x31`). The register address zero (`x0`) is shown when it appears as an operand.\n3. **CSR names** – Control and status registers are displayed using their symbolic names defined in the RISC‑V privileged specification (e.g., `mstatus`, `mepc`, `cycle`). If a CSR address does not match a known name, it is printed as `0x
`.\n4. **Immediates** – Signed immediates are printed as decimal numbers (with a leading minus sign if negative). Unsigned immediates are printed as hexadecimal numbers prefixed with `0x`. Immediate fields that represent shift amounts or small constants are also printed as decimal or hex as appropriate.\n5. **Jump and branch targets** – The target address is computed as `PC + immediate` and printed as an absolute hexadecimal address (without prefix). For unconditional jumps (`jal`) this target is the same as `rvfi_pc_wdata`; for conditional branches it is recomputed from the instruction encoding.\n6. **Load/Store offsets** – Printed as a signed decimal offset with the base register in parentheses, e.g., `-4(x2)`.\n7. **Fence** – The fence instruction is decoded as `fence\t,` where the predecessor and successor are strings composed of the bits `i`, `o`, `r`, `w` in that order for the corresponding fields.\n8. **Invalid or unsupported instructions** – If the instruction does not match any known opcode, the decoded string shall be `INVALID`. No register/memory access items are printed for invalid instructions.\n9. **Compressed instructions** – All compressed instructions defined in the RVC extension are decoded using the same rules as their 32‑bit counterparts, but with the compressed mnemonic prefix `c.`.\n10. **Special pseudo‑instructions** – The `nop` is *not* explicitly decoded; it is treated as `addi x0,x0,0`. The `ebreak` and `ecall` instructions are decoded as `ebreak` and `ecall` respectively. `mret`, `dret`, and `wfi` are decoded as their mnemonics.\n\n## 6. Special Cases\n\n- **Multiple instructions per cycle** – The tracer expects at most one instruction per clock cycle. If `rvfi_valid` is asserted for more than one cycle for the same instruction (e.g., multi‑cycle instructions), each assertion produces a separate trace line; this behaviour may be simulator‑dependent and is not guaranteed to be correct for all implementations.\n- **Reset during trace** – When the core is reset, the cycle counter resets. No trace is written while reset is asserted. After reset deassertion, the next valid instruction resumes logging.\n- **File not opened** – If the first valid instruction occurs and the file cannot be opened (e.g., due to permissions), the module continues silently with no output. No error is reported beyond the initial `$display` message.\n- **Plusarg override** – The `ibex_tracer_file_base` plusarg is evaluated only at the first valid instruction. Changing the plusarg during simulation has no effect.\n- **End of simulation** – The log file is closed automatically in a `final` block. If simulation is terminated abnormally (e.g., `$finish` not called), the file may not be closed properly.\n\n## 7. Constraints and Assumptions\n\n- The module is intended for simulation only and is not required to be synthesizable.\n- The RVFI signals are assumed to be glitch‑free and stable when `rvfi_valid` is high.\n- The core’s instruction set must be RV32I with the C extension at a minimum; the tracer also decodes the RV32M extensions as well as CSR accesses. Other extensions (e.g., A, F, D) are not decoded and will produce `INVALID`.\n- The tracer does not check for legal instruction encodings beyond the ones explicitly listed. It does not validate against illegal instructions (e.g., those with reserved opcode spaces).", "commit_id": "d8e4852f769c197330199a7356694baaef1b1a82", "timestamp": "2019-10-06T11:56:00+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "ee1098f9afb1a63a34d613a8949c00e5b0c75b47", "pr_title": "Tracer: Reference Verilator bug for miscompilation", "pr_body": "This miscompilation is now reported and fixed, mention it in the code to\nrefer back to it when we can revert back to the old code (which will\ntake a couple months until we can require a newer Verilator version).\n\nFixes #372", "issue_title": "Tracer: Debug miscompilation in decode_load_insn()", "issue_body": "In https://github.com/lowRISC/ibex/blob/2acb497d22a5da877a9c4350ef5693d0c767cc61/rtl/ibex_tracer.sv#L584-L613 we switched from case to if statements to get around potentially wrong behavior in Verilator. Note that the `return` in the default statement hides that the default statement is always taken; the output without the return looks even more confusing.\r\n\r\nUpstream bug report at https://www.veripool.org/issues/1536-Verilator-Misoptimization-in-if-and-case-with-default-statement-inside-a-function", "commit_message": "Tracer: Reference Verilator bug for miscompilation\n\nThis miscompilation is now reported and fixed, mention it in the code to\nrefer back to it when we can revert back to the old code (which will\ntake a couple months until we can require a newer Verilator version).\n\nFixes #372", "fix_patch": "diff --git a/rtl/ibex_tracer.sv b/rtl/ibex_tracer.sv\nindex 5d42905607..423b76d6bf 100644\n--- a/rtl/ibex_tracer.sv\n+++ b/rtl/ibex_tracer.sv\n@@ -583,7 +583,10 @@ module ibex_tracer (\n string mnemonic;\n \n /*\n- TODO: Gives wrong results in Verilator for unknown reasons. Debug what's going on.\n+ Gives wrong results in Verilator < 4.020.\n+ See https://github.com/lowRISC/ibex/issues/372 and\n+ https://www.veripool.org/issues/1536-Verilator-Misoptimization-in-if-and-case-with-default-statement-inside-a-function\n+\n unique case (rvfi_insn[14:12])\n 3'b000: mnemonic = \"lb\";\n 3'b001: mnemonic = \"lh\";\n", "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 * Trace executed instructions in simulation\n *\n * This tracer takes execution information from the RISC-V Verification Interface (RVFI) and\n * produces a text file with a human-readable trace.\n *\n * All traced instructions are written to a log file. By default, the log file is named\n * trace_core_.log, with being the 8 digit hart ID of the core being traced.\n *\n * The file name base, defaulting to \"trace_core\" can be set using the \"ibex_tracer_file_base\"\n * plusarg passed to the simulation, e.g. \"+ibex_tracer_file_base=ibex_my_trace\". The exact syntax\n * of passing plusargs to a simulation depends on the simulator.\n *\n * The trace contains six columns, separated by tabs:\n * - The simulation time\n * - The clock cycle count since reset\n * - The program counter (PC)\n * - The instruction\n * - The decoded instruction in the same format as objdump, together with the accessed registers and\n * read/written memory values. Jumps and branches show the target address.\n * This column may be omitted if the instruction does not decode into a long form.\n * - Accessed registers and memory locations.\n *\n * Significant effort is spent to make the decoding produced by this tracer as similar as possible\n * to the one produced by objdump. This simplifies the correlation between the static program\n * information from the objdump-generated disassembly, and the runtime information from this tracer.\n */\nmodule ibex_tracer (\n input logic clk_i,\n input logic rst_ni,\n\n input logic [31:0] hart_id_i,\n\n // RVFI as described at https://github.com/SymbioticEDA/riscv-formal/blob/master/docs/rvfi.md\n // The standard interface does not have _i/_o suffixes. For consistency with the standard the\n // signals in this module don't have the suffixes either.\n input logic rvfi_valid,\n input logic [63:0] rvfi_order,\n input logic [31:0] rvfi_insn,\n input logic rvfi_trap,\n input logic rvfi_halt,\n input logic rvfi_intr,\n input logic [ 1:0] rvfi_mode,\n input logic [ 4:0] rvfi_rs1_addr,\n input logic [ 4:0] rvfi_rs2_addr,\n input logic [31:0] rvfi_rs1_rdata,\n input logic [31:0] rvfi_rs2_rdata,\n input logic [ 4:0] rvfi_rd_addr,\n input logic [31:0] rvfi_rd_wdata,\n input logic [31:0] rvfi_pc_rdata,\n input logic [31:0] rvfi_pc_wdata,\n input logic [31:0] rvfi_mem_addr,\n input logic [ 3:0] rvfi_mem_rmask,\n input logic [ 3:0] rvfi_mem_wmask,\n input logic [31:0] rvfi_mem_rdata,\n input logic [31:0] rvfi_mem_wdata\n);\n\n // These signals are part of RVFI, but not used in this module currently.\n // Keep them as part of the interface to change the tracer more easily in the future. Assigning\n // these signals to unused_* signals marks them explicitly as unused, an annotation picked up by\n // linters, including Verilator lint.\n logic [63:0] unused_rvfi_order = rvfi_order;\n logic unused_rvfi_trap = rvfi_trap;\n logic unused_rvfi_halt = rvfi_halt;\n logic unused_rvfi_intr = rvfi_intr;\n logic [ 1:0] unused_rvfi_mode = rvfi_mode;\n\n import ibex_pkg::*;\n import ibex_tracer_pkg::*;\n\n int file_handle;\n string file_name;\n\n int unsigned cycle;\n string decoded_str;\n logic insn_is_compressed;\n\n // Data items accessed during this instruction\n localparam RS1 = (1 << 0);\n localparam RS2 = (1 << 1);\n localparam RD = (1 << 2);\n localparam MEM = (1 << 3);\n logic [3:0] data_accessed;\n\n function void printbuffer_dumpline();\n string rvfi_insn_str;\n\n if (file_handle == 32'h0) begin\n string file_name_base = \"trace_core\";\n $value$plusargs(\"ibex_tracer_file_base=%s\", file_name_base);\n $sformat(file_name, \"%s_%h.log\", file_name_base, hart_id_i);\n\n $display(\"%m: Writing execution trace to %s\", file_name);\n file_handle = $fopen(file_name, \"w\");\n $fwrite(file_handle, \"Time\\tCycle\\tPC\\tInsn\\tDecoded instruction\\tRegister and memory contents\\n\");\n end\n\n // Write compressed instructions as four hex digits (16 bit word), and\n // uncompressed ones as 8 hex digits (32 bit words).\n if (insn_is_compressed) begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn[15:0]);\n end else begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn);\n end\n\n $fwrite(file_handle, \"%15t\\t%d\\t%h\\t%s\\t%s\\t\", $time, cycle, rvfi_pc_rdata, rvfi_insn_str, decoded_str);\n\n if ((data_accessed & RS1) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs1_addr), rvfi_rs1_rdata);\n end\n if ((data_accessed & RS2) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs2_addr), rvfi_rs2_rdata);\n end\n if ((data_accessed & RD) != 0) begin\n $fwrite(file_handle, \" %s=0x%08x\", reg_addr_to_str(rvfi_rd_addr), rvfi_rd_wdata);\n end\n if ((data_accessed & MEM) != 0) begin\n $fwrite(file_handle, \" PA:0x%08x\", rvfi_mem_addr);\n\n if (rvfi_mem_rmask != 4'b000) begin\n $fwrite(file_handle, \" store:0x%08x\", rvfi_mem_wdata);\n end\n if (rvfi_mem_wmask != 4'b000) begin\n $fwrite(file_handle, \" load:0x%08x\", rvfi_mem_rdata);\n end\n end\n\n $fwrite(file_handle, \"\\n\");\n endfunction\n\n\n // Format register address with \"x\" prefix, left-aligned to a fixed width of 3 characters.\n function string reg_addr_to_str(input logic [4:0] addr);\n if (addr < 10) begin\n return $sformatf(\" x%0d\", addr);\n end else begin\n return $sformatf(\"x%0d\", addr);\n end\n endfunction\n\n // Get a CSR name for a CSR address.\n function string get_csr_name(input logic [11:0] csr_addr);\n unique case (csr_addr)\n 12'd0: return \"ustatus\";\n 12'd4: return \"uie\";\n 12'd5: return \"utvec\";\n 12'd64: return \"uscratch\";\n 12'd65: return \"uepc\";\n 12'd66: return \"ucause\";\n 12'd67: return \"utval\";\n 12'd68: return \"uip\";\n 12'd1: return \"fflags\";\n 12'd2: return \"frm\";\n 12'd3: return \"fcsr\";\n 12'd3072: return \"cycle\";\n 12'd3073: return \"time\";\n 12'd3074: return \"instret\";\n 12'd3075: return \"hpmcounter3\";\n 12'd3076: return \"hpmcounter4\";\n 12'd3077: return \"hpmcounter5\";\n 12'd3078: return \"hpmcounter6\";\n 12'd3079: return \"hpmcounter7\";\n 12'd3080: return \"hpmcounter8\";\n 12'd3081: return \"hpmcounter9\";\n 12'd3082: return \"hpmcounter10\";\n 12'd3083: return \"hpmcounter11\";\n 12'd3084: return \"hpmcounter12\";\n 12'd3085: return \"hpmcounter13\";\n 12'd3086: return \"hpmcounter14\";\n 12'd3087: return \"hpmcounter15\";\n 12'd3088: return \"hpmcounter16\";\n 12'd3089: return \"hpmcounter17\";\n 12'd3090: return \"hpmcounter18\";\n 12'd3091: return \"hpmcounter19\";\n 12'd3092: return \"hpmcounter20\";\n 12'd3093: return \"hpmcounter21\";\n 12'd3094: return \"hpmcounter22\";\n 12'd3095: return \"hpmcounter23\";\n 12'd3096: return \"hpmcounter24\";\n 12'd3097: return \"hpmcounter25\";\n 12'd3098: return \"hpmcounter26\";\n 12'd3099: return \"hpmcounter27\";\n 12'd3100: return \"hpmcounter28\";\n 12'd3101: return \"hpmcounter29\";\n 12'd3102: return \"hpmcounter30\";\n 12'd3103: return \"hpmcounter31\";\n 12'd3200: return \"cycleh\";\n 12'd3201: return \"timeh\";\n 12'd3202: return \"instreth\";\n 12'd3203: return \"hpmcounter3h\";\n 12'd3204: return \"hpmcounter4h\";\n 12'd3205: return \"hpmcounter5h\";\n 12'd3206: return \"hpmcounter6h\";\n 12'd3207: return \"hpmcounter7h\";\n 12'd3208: return \"hpmcounter8h\";\n 12'd3209: return \"hpmcounter9h\";\n 12'd3210: return \"hpmcounter10h\";\n 12'd3211: return \"hpmcounter11h\";\n 12'd3212: return \"hpmcounter12h\";\n 12'd3213: return \"hpmcounter13h\";\n 12'd3214: return \"hpmcounter14h\";\n 12'd3215: return \"hpmcounter15h\";\n 12'd3216: return \"hpmcounter16h\";\n 12'd3217: return \"hpmcounter17h\";\n 12'd3218: return \"hpmcounter18h\";\n 12'd3219: return \"hpmcounter19h\";\n 12'd3220: return \"hpmcounter20h\";\n 12'd3221: return \"hpmcounter21h\";\n 12'd3222: return \"hpmcounter22h\";\n 12'd3223: return \"hpmcounter23h\";\n 12'd3224: return \"hpmcounter24h\";\n 12'd3225: return \"hpmcounter25h\";\n 12'd3226: return \"hpmcounter26h\";\n 12'd3227: return \"hpmcounter27h\";\n 12'd3228: return \"hpmcounter28h\";\n 12'd3229: return \"hpmcounter29h\";\n 12'd3230: return \"hpmcounter30h\";\n 12'd3231: return \"hpmcounter31h\";\n 12'd256: return \"sstatus\";\n 12'd258: return \"sedeleg\";\n 12'd259: return \"sideleg\";\n 12'd260: return \"sie\";\n 12'd261: return \"stvec\";\n 12'd262: return \"scounteren\";\n 12'd320: return \"sscratch\";\n 12'd321: return \"sepc\";\n 12'd322: return \"scause\";\n 12'd323: return \"stval\";\n 12'd324: return \"sip\";\n 12'd384: return \"satp\";\n 12'd3857: return \"mvendorid\";\n 12'd3858: return \"marchid\";\n 12'd3859: return \"mimpid\";\n 12'd3860: return \"mhartid\";\n 12'd768: return \"mstatus\";\n 12'd769: return \"misa\";\n 12'd770: return \"medeleg\";\n 12'd771: return \"mideleg\";\n 12'd772: return \"mie\";\n 12'd773: return \"mtvec\";\n 12'd774: return \"mcounteren\";\n 12'd832: return \"mscratch\";\n 12'd833: return \"mepc\";\n 12'd834: return \"mcause\";\n 12'd835: return \"mtval\";\n 12'd836: return \"mip\";\n 12'd928: return \"pmpcfg0\";\n 12'd929: return \"pmpcfg1\";\n 12'd930: return \"pmpcfg2\";\n 12'd931: return \"pmpcfg3\";\n 12'd944: return \"pmpaddr0\";\n 12'd945: return \"pmpaddr1\";\n 12'd946: return \"pmpaddr2\";\n 12'd947: return \"pmpaddr3\";\n 12'd948: return \"pmpaddr4\";\n 12'd949: return \"pmpaddr5\";\n 12'd950: return \"pmpaddr6\";\n 12'd951: return \"pmpaddr7\";\n 12'd952: return \"pmpaddr8\";\n 12'd953: return \"pmpaddr9\";\n 12'd954: return \"pmpaddr10\";\n 12'd955: return \"pmpaddr11\";\n 12'd956: return \"pmpaddr12\";\n 12'd957: return \"pmpaddr13\";\n 12'd958: return \"pmpaddr14\";\n 12'd959: return \"pmpaddr15\";\n 12'd2816: return \"mcycle\";\n 12'd2818: return \"minstret\";\n 12'd2819: return \"mhpmcounter3\";\n 12'd2820: return \"mhpmcounter4\";\n 12'd2821: return \"mhpmcounter5\";\n 12'd2822: return \"mhpmcounter6\";\n 12'd2823: return \"mhpmcounter7\";\n 12'd2824: return \"mhpmcounter8\";\n 12'd2825: return \"mhpmcounter9\";\n 12'd2826: return \"mhpmcounter10\";\n 12'd2827: return \"mhpmcounter11\";\n 12'd2828: return \"mhpmcounter12\";\n 12'd2829: return \"mhpmcounter13\";\n 12'd2830: return \"mhpmcounter14\";\n 12'd2831: return \"mhpmcounter15\";\n 12'd2832: return \"mhpmcounter16\";\n 12'd2833: return \"mhpmcounter17\";\n 12'd2834: return \"mhpmcounter18\";\n 12'd2835: return \"mhpmcounter19\";\n 12'd2836: return \"mhpmcounter20\";\n 12'd2837: return \"mhpmcounter21\";\n 12'd2838: return \"mhpmcounter22\";\n 12'd2839: return \"mhpmcounter23\";\n 12'd2840: return \"mhpmcounter24\";\n 12'd2841: return \"mhpmcounter25\";\n 12'd2842: return \"mhpmcounter26\";\n 12'd2843: return \"mhpmcounter27\";\n 12'd2844: return \"mhpmcounter28\";\n 12'd2845: return \"mhpmcounter29\";\n 12'd2846: return \"mhpmcounter30\";\n 12'd2847: return \"mhpmcounter31\";\n 12'd2944: return \"mcycleh\";\n 12'd2946: return \"minstreth\";\n 12'd2947: return \"mhpmcounter3h\";\n 12'd2948: return \"mhpmcounter4h\";\n 12'd2949: return \"mhpmcounter5h\";\n 12'd2950: return \"mhpmcounter6h\";\n 12'd2951: return \"mhpmcounter7h\";\n 12'd2952: return \"mhpmcounter8h\";\n 12'd2953: return \"mhpmcounter9h\";\n 12'd2954: return \"mhpmcounter10h\";\n 12'd2955: return \"mhpmcounter11h\";\n 12'd2956: return \"mhpmcounter12h\";\n 12'd2957: return \"mhpmcounter13h\";\n 12'd2958: return \"mhpmcounter14h\";\n 12'd2959: return \"mhpmcounter15h\";\n 12'd2960: return \"mhpmcounter16h\";\n 12'd2961: return \"mhpmcounter17h\";\n 12'd2962: return \"mhpmcounter18h\";\n 12'd2963: return \"mhpmcounter19h\";\n 12'd2964: return \"mhpmcounter20h\";\n 12'd2965: return \"mhpmcounter21h\";\n 12'd2966: return \"mhpmcounter22h\";\n 12'd2967: return \"mhpmcounter23h\";\n 12'd2968: return \"mhpmcounter24h\";\n 12'd2969: return \"mhpmcounter25h\";\n 12'd2970: return \"mhpmcounter26h\";\n 12'd2971: return \"mhpmcounter27h\";\n 12'd2972: return \"mhpmcounter28h\";\n 12'd2973: return \"mhpmcounter29h\";\n 12'd2974: return \"mhpmcounter30h\";\n 12'd2975: return \"mhpmcounter31h\";\n 12'd803: return \"mhpmevent3\";\n 12'd804: return \"mhpmevent4\";\n 12'd805: return \"mhpmevent5\";\n 12'd806: return \"mhpmevent6\";\n 12'd807: return \"mhpmevent7\";\n 12'd808: return \"mhpmevent8\";\n 12'd809: return \"mhpmevent9\";\n 12'd810: return \"mhpmevent10\";\n 12'd811: return \"mhpmevent11\";\n 12'd812: return \"mhpmevent12\";\n 12'd813: return \"mhpmevent13\";\n 12'd814: return \"mhpmevent14\";\n 12'd815: return \"mhpmevent15\";\n 12'd816: return \"mhpmevent16\";\n 12'd817: return \"mhpmevent17\";\n 12'd818: return \"mhpmevent18\";\n 12'd819: return \"mhpmevent19\";\n 12'd820: return \"mhpmevent20\";\n 12'd821: return \"mhpmevent21\";\n 12'd822: return \"mhpmevent22\";\n 12'd823: return \"mhpmevent23\";\n 12'd824: return \"mhpmevent24\";\n 12'd825: return \"mhpmevent25\";\n 12'd826: return \"mhpmevent26\";\n 12'd827: return \"mhpmevent27\";\n 12'd828: return \"mhpmevent28\";\n 12'd829: return \"mhpmevent29\";\n 12'd830: return \"mhpmevent30\";\n 12'd831: return \"mhpmevent31\";\n 12'd1952: return \"tselect\";\n 12'd1953: return \"tdata1\";\n 12'd1954: return \"tdata2\";\n 12'd1955: return \"tdata3\";\n 12'd1968: return \"dcsr\";\n 12'd1969: return \"dpc\";\n 12'd1970: return \"dscratch\";\n 12'd512: return \"hstatus\";\n 12'd514: return \"hedeleg\";\n 12'd515: return \"hideleg\";\n 12'd516: return \"hie\";\n 12'd517: return \"htvec\";\n 12'd576: return \"hscratch\";\n 12'd577: return \"hepc\";\n 12'd578: return \"hcause\";\n 12'd579: return \"hbadaddr\";\n 12'd580: return \"hip\";\n 12'd896: return \"mbase\";\n 12'd897: return \"mbound\";\n 12'd898: return \"mibase\";\n 12'd899: return \"mibound\";\n 12'd900: return \"mdbase\";\n 12'd901: return \"mdbound\";\n 12'd800: return \"mucounteren\";\n 12'd801: return \"mscounteren\";\n 12'd802: return \"mhcounteren\";\n default: return $sformatf(\"0x%x\", csr_addr);\n endcase\n endfunction\n\n function void decode_mnemonic(input string mnemonic);\n decoded_str = mnemonic;\n endfunction\n\n function void decode_r_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr, rvfi_rs2_addr);\n endfunction\n\n function void decode_i_insn(input string mnemonic);\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}));\n endfunction\n\n function void decode_i_shift_insn(input string mnemonic);\n // SLLI, SRLI, SRAI\n logic [4:0] shamt;\n shamt = {rvfi_insn[24:20]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,0x%0x\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr, shamt);\n endfunction\n\n function void decode_i_jalr_insn(input string mnemonic);\n // JALR\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function void decode_u_insn(input string mnemonic);\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, {rvfi_insn[31:12]});\n endfunction\n\n function void decode_j_insn(input string mnemonic);\n // JAL\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rd_addr, rvfi_pc_wdata);\n endfunction\n\n function void decode_b_insn(input string mnemonic);\n logic [31:0] branch_target;\n logic [31:0] imm;\n\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = $signed({ {19 {rvfi_insn[31]}}, rvfi_insn[31], rvfi_insn[7],\n rvfi_insn[30:25], rvfi_insn[11:8], 1'b0 });\n branch_target = rvfi_pc_rdata + imm;\n\n data_accessed = RS1 | RS2 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0x\", mnemonic, rvfi_rs1_addr, rvfi_rs2_addr, branch_target);\n endfunction\n\n function void decode_csr_insn(input string mnemonic);\n logic [11:0] csr;\n string csr_name;\n csr = rvfi_insn[31:20];\n csr_name = get_csr_name(csr);\n\n data_accessed = RD;\n\n if (!rvfi_insn[14]) begin\n data_accessed |= RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%s,x%0d\", mnemonic, rvfi_rd_addr, csr_name, rvfi_rs1_addr);\n end else begin\n decoded_str = $sformatf(\"%s\\tx%0d,%s,%0d\", mnemonic, rvfi_rd_addr, csr_name, { 27'b0, rvfi_insn[19:15]});\n end\n endfunction\n\n function void decode_cr_insn(input string mnemonic);\n if (rvfi_rs2_addr == 5'b0) begin\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d\", mnemonic, rvfi_rs1_addr);\n end else begin\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n end\n endfunction\n\n function void decode_ci_cli_insn(input string mnemonic);\n logic [5:0] imm;\n imm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n endfunction\n\n function void decode_ci_caddi_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function void decode_ci_caddi16sp_insn(input string mnemonic);\n logic [9:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[4:3], rvfi_insn[5], rvfi_insn[2], rvfi_insn[6], 4'b0};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function void decode_ci_clui_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, 20'($signed(nzimm)));\n endfunction\n\n function void decode_ci_cslli_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, shamt);\n endfunction\n\n function void decode_ciw_insn(input string mnemonic);\n // C.ADDI4SPN\n logic [9:0] nzuimm;\n nzuimm = {rvfi_insn[10:7], rvfi_insn[12:11], rvfi_insn[5], rvfi_insn[6], 2'b00};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x2,%0d\", mnemonic, rvfi_rd_addr, nzuimm);\n endfunction\n\n function void decode_cb_sr_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, shamt);\n endfunction\n\n function void decode_cb_insn(input string mnemonic);\n logic [7:0] imm;\n logic [31:0] jump_target;\n if (rvfi_insn[15:13] == 3'b110 || rvfi_insn[15:13] == 3'b111) begin\n // C.BNEZ and C.BEQZ\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = {rvfi_insn[12], rvfi_insn[6:5], rvfi_insn[2], rvfi_insn[11:10], rvfi_insn[4:3]};\n jump_target = rvfi_pc_rdata + 32'($signed({imm, 1'b0}));\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rs1_addr, jump_target);\n end else if (rvfi_insn[15:13] == 3'b100) begin\n // C.ANDI\n imm = {{2{rvfi_insn[12]}}, rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n end else begin\n imm = {rvfi_insn[12], rvfi_insn[6:2], 2'b00};\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, imm);\n end\n endfunction\n\n function void decode_cs_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n endfunction\n\n function void decode_cj_insn(input string mnemonic);\n decoded_str = $sformatf(\"%s\\t%0x\", mnemonic, rvfi_pc_wdata);\n endfunction\n\n function void decode_compressed_load_insn(input string mnemonic);\n logic [7:0] imm;\n\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.LW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.LWSP\n imm = {rvfi_insn[3:2], rvfi_insn[12], rvfi_insn[6:4], 2'b00};\n end\n data_accessed = RS1 | RD | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function void decode_compressed_store_insn(input string mnemonic);\n logic [7:0] imm;\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.SW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.SWSP\n imm = {rvfi_insn[8:7], rvfi_insn[12:9], 2'b00};\n end\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rs2_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function void decode_load_insn();\n string mnemonic;\n\n /*\n Gives wrong results in Verilator < 4.020.\n See https://github.com/lowRISC/ibex/issues/372 and\n https://www.veripool.org/issues/1536-Verilator-Misoptimization-in-if-and-case-with-default-statement-inside-a-function\n\n unique case (rvfi_insn[14:12])\n 3'b000: mnemonic = \"lb\";\n 3'b001: mnemonic = \"lh\";\n 3'b010: mnemonic = \"lw\";\n 3'b100: mnemonic = \"lbu\";\n 3'b101: mnemonic = \"lhu\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n */\n logic [2:0] size;\n size = rvfi_insn[14:12];\n if (size == 3'b000) begin\n mnemonic = \"lb\";\n end else if (size == 3'b001) begin\n mnemonic = \"lh\";\n end else if (size == 3'b010) begin\n mnemonic = \"lw\";\n end else if (size == 3'b100) begin\n mnemonic = \"lbu\";\n end else if (size == 3'b101) begin\n mnemonic = \"lhu\";\n end else begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n\n\n data_accessed = RD | RS1 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function void decode_store_insn();\n string mnemonic;\n\n unique case (rvfi_insn[13:12])\n 2'b00: mnemonic = \"sb\";\n 2'b01: mnemonic = \"sh\";\n 2'b10: mnemonic = \"sw\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n\n if (!rvfi_insn[14]) begin\n // regular store\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rs2_addr,\n $signed({ {20 {rvfi_insn[31]}}, rvfi_insn[31:25], rvfi_insn[11:7] }), rvfi_rs1_addr);\n end else begin\n decode_mnemonic(\"INVALID\");\n end\n endfunction\n\n function string get_fence_description(logic [3:0] bits);\n string desc = \"\";\n if (bits[3]) begin\n desc = {desc, \"i\"};\n end\n if (bits[2]) begin\n desc = {desc, \"o\"};\n end\n if (bits[1]) begin\n desc = {desc, \"r\"};\n end\n if (bits[0]) begin\n desc = {desc, \"w\"};\n end\n return desc;\n endfunction\n\n function void decode_fence();\n string predecessor;\n string successor;\n predecessor = get_fence_description(rvfi_insn[27:24]);\n successor = get_fence_description(rvfi_insn[23:20]);\n decoded_str = $sformatf(\"fence\\t%s,%s\", predecessor, successor);\n endfunction\n\n // cycle counter\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n cycle <= 0;\n end else begin\n cycle <= cycle + 1;\n end\n end\n\n // close output file for writing\n final begin\n if (file_handle != 32'h0) begin\n $fclose(file_handle);\n end\n end\n\n // log execution\n always_ff @(posedge clk_i) begin\n if (rvfi_valid) begin\n printbuffer_dumpline();\n end\n end\n\n always_comb begin\n decoded_str = \"\";\n data_accessed = 4'h0;\n insn_is_compressed = 0;\n\n // Check for compressed instructions\n if (rvfi_insn[1:0] != 2'b11) begin\n insn_is_compressed = 1;\n // Separate case to avoid overlapping decoding\n if (rvfi_insn[15:13] == 3'b100 && rvfi_insn[1:0] == 2'b10) begin\n if (rvfi_insn[12]) begin\n if (rvfi_insn[11:2] == 10'h0) begin\n decode_mnemonic(\"c.ebreak\");\n end else if (rvfi_insn[6:2] == 5'b0) begin\n decode_cr_insn(\"c.jalr\");\n end else begin\n decode_cr_insn(\"c.add\");\n end\n end else begin\n if (rvfi_insn[6:2] == 5'h0) begin\n decode_cr_insn(\"c.jr\");\n end else begin\n decode_cr_insn(\"c.mv\");\n end\n end\n end else begin\n unique casez (rvfi_insn[15:0])\n // C0 Opcodes\n INSN_CADDI4SPN: decode_ciw_insn(\"c.addi4spn\");\n INSN_CLW: decode_compressed_load_insn(\"c.lw\");\n INSN_CSW: decode_compressed_store_insn(\"c.sw\");\n // C1 Opcodes\n INSN_CADDI: decode_ci_caddi_insn(\"c.addi\");\n INSN_CJAL: decode_cj_insn(\"c.jal\");\n INSN_CJ: decode_cj_insn(\"c.j\");\n INSN_CLI: decode_ci_cli_insn(\"c.li\");\n INSN_CLUI: begin\n // These two instructions share opcode\n if (rvfi_insn[11:7] == 5'd2) begin\n decode_ci_caddi16sp_insn(\"c.addi16sp\");\n end else begin\n decode_ci_clui_insn(\"c.lui\");\n end\n end\n INSN_CSRLI: decode_cb_sr_insn(\"c.srli\");\n INSN_CSRAI: decode_cb_sr_insn(\"c.srai\");\n INSN_CANDI: decode_cb_insn(\"c.andi\");\n INSN_CSUB: decode_cs_insn(\"c.sub\");\n INSN_CXOR: decode_cs_insn(\"c.xor\");\n INSN_COR: decode_cs_insn(\"c.or\");\n INSN_CAND: decode_cs_insn(\"c.and\");\n INSN_CBEQZ: decode_cb_insn(\"c.beqz\");\n INSN_CBNEZ: decode_cb_insn(\"c.bnez\");\n // C2 Opcodes\n INSN_CSLLI: decode_ci_cslli_insn(\"c.slli\");\n INSN_CLWSP: decode_compressed_load_insn(\"c.lwsp\");\n INSN_SWSP: decode_compressed_store_insn(\"c.swsp\");\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end else begin\n unique casez (rvfi_insn)\n // Regular opcodes\n INSN_LUI: decode_u_insn(\"lui\");\n INSN_AUIPC: decode_u_insn(\"auipc\");\n INSN_JAL: decode_j_insn(\"jal\");\n INSN_JALR: decode_i_jalr_insn(\"jalr\");\n // BRANCH\n INSN_BEQ: decode_b_insn(\"beq\");\n INSN_BNE: decode_b_insn(\"bne\");\n INSN_BLT: decode_b_insn(\"blt\");\n INSN_BGE: decode_b_insn(\"bge\");\n INSN_BLTU: decode_b_insn(\"bltu\");\n INSN_BGEU: decode_b_insn(\"bgeu\");\n // OPIMM\n INSN_ADDI: begin\n if (rvfi_insn == 32'h00_00_00_13) begin\n // TODO: objdump doesn't decode this as nop currently, even though it would be helpful\n // Decide what to do here: diverge from objdump, or make the trace less readable to\n // users.\n //decode_mnemonic(\"nop\");\n decode_i_insn(\"addi\");\n end else begin\n decode_i_insn(\"addi\");\n end\n end\n INSN_SLTI: decode_i_insn(\"slti\");\n INSN_SLTIU: decode_i_insn(\"sltiu\");\n INSN_XORI: decode_i_insn(\"xori\");\n INSN_ORI: decode_i_insn(\"ori\");\n INSN_ANDI: decode_i_insn(\"andi\");\n INSN_SLLI: decode_i_shift_insn(\"slli\");\n INSN_SRLI: decode_i_shift_insn(\"srli\");\n INSN_SRAI: decode_i_shift_insn(\"srai\");\n // OP\n INSN_ADD: decode_r_insn(\"add\");\n INSN_SUB: decode_r_insn(\"sub\");\n INSN_SLL: decode_r_insn(\"sll\");\n INSN_SLT: decode_r_insn(\"slt\");\n INSN_SLTU: decode_r_insn(\"sltu\");\n INSN_XOR: decode_r_insn(\"xor\");\n INSN_SRL: decode_r_insn(\"srl\");\n INSN_SRA: decode_r_insn(\"sra\");\n INSN_OR: decode_r_insn(\"or\");\n INSN_AND: decode_r_insn(\"and\");\n // SYSTEM (CSR manipulation)\n INSN_CSRRW: decode_csr_insn(\"csrrw\");\n INSN_CSRRS: decode_csr_insn(\"csrrs\");\n INSN_CSRRC: decode_csr_insn(\"csrrc\");\n INSN_CSRRWI: decode_csr_insn(\"csrrwi\");\n INSN_CSRRSI: decode_csr_insn(\"csrrsi\");\n INSN_CSRRCI: decode_csr_insn(\"csrrci\");\n // SYSTEM (others)\n INSN_ECALL: decode_mnemonic(\"ecall\");\n INSN_EBREAK: decode_mnemonic(\"ebreak\");\n INSN_MRET: decode_mnemonic(\"mret\");\n INSN_DRET: decode_mnemonic(\"dret\");\n INSN_WFI: decode_mnemonic(\"wfi\");\n // RV32M\n INSN_PMUL: decode_r_insn(\"mul\");\n INSN_PMUH: decode_r_insn(\"mulh\");\n INSN_PMULHSU: decode_r_insn(\"mulhsu\");\n INSN_PMULHU: decode_r_insn(\"mulhu\");\n INSN_DIV: decode_r_insn(\"div\");\n INSN_DIVU: decode_r_insn(\"divu\");\n INSN_REM: decode_r_insn(\"rem\");\n INSN_REMU: decode_r_insn(\"remu\");\n // LOAD & STORE\n INSN_LOAD: decode_load_insn();\n INSN_STORE: decode_store_insn();\n // MISC-MEM\n INSN_FENCE: decode_fence();\n INSN_FENCEI: decode_mnemonic(\"fence.i\");\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end\n\nendmodule\n", "selected_doc_paths": ["doc/rvfi.rst", "doc/tracer.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 316, "lang": "sv", "rtl_files": ["dv/riscv_compliance/rtl/bus.sv"], "spec": "# Behavioral Design Specification for the Bus Module\n\n## 1. Overview\n\nThis module implements a simple, parameterizable system bus intended for simulation and demonstration purposes only. It is not suitable for use in real silicon. The bus connects multiple master (host) interfaces to multiple slave (device) interfaces, providing a single shared address/data path. Communication is based on a request/grant protocol with strictly priority‑based arbitration and a fixed one‑cycle response latency.\n\n## 2. Functional Requirements\n\n### 2.1 Arbitration\n\n- At any point in time, the bus shall allow only one master to use the shared address/data bus.\n- Arbitration shall be performed in a fixed priority order. The master with the highest priority (lowest index) shall win the bus when multiple masters request simultaneously.\n- The bus shall assert a grant signal only to the selected master for the duration of the request cycle.\n\n### 2.2 Address Decoding\n\n- The bus shall contain a configurable address map for each slave device, consisting of a base address and an address mask.\n- A slave is selected when the address from the currently granted master, ANDed with the slave’s mask, equals the slave’s base address.\n- The address map must be configured so that every address decodes to exactly one slave. If multiple slaves match the same address, the bus behavior is undefined.\n\n### 2.3 Request Transfer\n\n- When a master is granted and a slave is selected, the bus shall forward the following signals from the master to the selected slave:\n - address\n - write enable\n - byte enables\n - write data\n- The request (including the above signals) shall be delivered to the selected slave in the same cycle in which the master’s grant is active.\n- All non‑selected slaves shall have their request signal de‑asserted and the associated address, write enable, byte enable, and write data driven to zero.\n\n### 2.4 Response Handling\n\n- The bus expects that every selected slave will provide a valid response (read data, error flag, and a data valid signal) **exactly one clock cycle after** the request was presented.\n- Upon receiving the response from the selected slave, the bus shall forward it to the master that was served in the previous cycle.\n- The response signals for non‑selected masters shall be driven to zero (read data, error) and the data valid signal de‑asserted.\n- The bus shall register the granted master and selected slave at the time of the request so that the response is correctly routed back.\n\n### 2.5 Reset Behavior\n\n- When the reset is active (low‑active), all internal state relating to which master and slave were selected must be cleared. Consequently, all output signals to masters (grant, read data, error, data valid) shall be driven to their inactive states (zero for grant, zero for data/error, zero for data valid). Outputs to slaves (request, address, etc.) shall also be driven inactive during reset.\n\n## 3. Interface Description\n\nThe bus has separate ports for each master and each slave. The number of masters and slaves is configurable at synthesis time.\n\n### 3.1 Master (Host) Ports\n\nEach master provides:\n\n- **Request** – indicates that the master wants to perform a transaction.\n- **Address** – the target address for the transaction.\n- **Write Enable** – indicates a write operation when asserted, otherwise a read.\n- **Byte Enables** – one bit per byte-wide lane, indicating which bytes are valid for a write.\n- **Write Data** – the data to be written (only used when write enable is asserted).\n\nEach master receives:\n\n- **Grant** – asserted when the bus has granted the master access in the current cycle.\n- **Read Data** – the data read from the selected slave (valid only when read data valid is asserted).\n- **Read Data Valid** – asserted when read data is valid (in the cycle following the request).\n- **Error** – asserted when the selected slave reports an error.\n\n### 3.2 Slave (Device) Ports\n\nEach slave receives:\n\n- **Request** – asserted when the slave is selected and the bus is performing a transaction.\n- **Address** – the target address for the transaction.\n- **Write Enable** – indicates a write operation when asserted.\n- **Byte Enables** – byte lane mask for writes.\n- **Write Data** – the data to be written.\n\nEach slave provides:\n\n- **Read Data** – the data read from the slave (must be valid in the next cycle after request).\n- **Read Data Valid** – asserted when read data is valid.\n- **Error** – asserted when the slave encounters an error for the transaction.\n\n## 4. Timing and Latency\n\n- The bus is clocked on the rising edge of a single clock. An asynchronous low‑active reset is used.\n- The bus is designed under the assumption that all slaves can provide a response exactly one clock cycle after the request is asserted. The bus does not support wait states or multiple‑cycle responses.\n- The grant and request transfer occur in the same cycle. The response is registered and returned one cycle later.\n\n## 5. Configuration Parameters\n\nThe following parameters must be set before elaboration:\n\n- **Number of Masters** (`NrHosts`) – must be at least 1.\n- **Number of Slaves** (`NrDevices`) – must be at least 1.\n- **Data Width** – width of the data bus in bits (default 32).\n- **Address Width** – width of the address bus in bits (default 32).\n\nThe bus also receives configuration inputs for the slave address map:\n\n- **Device Address Base** – one base address per slave.\n- **Device Address Mask** – one mask per slave, used to compare with the master’s address.\n\nThese inputs are combinatorial and can be changed at any time, but changes may cause incoherent behavior during an ongoing transaction. It is recommended to configure them before the first transaction and keep them static during normal operation.\n\n## 6. Constraints and Assumptions\n\n- **One‑cycle latency**: All slaves **must** respond in the cycle immediately following the request. Violating this assumption will lead to incorrect behavior.\n- **Non‑overlapping address map**: The slave address ranges must not overlap. The bus does not check for overlap and will behave unpredictably if two slaves match the same address.\n- **Demo only**: This bus omits many features required for a real system (e.g., address decoding with priority, pipelining, error handling, burst support). It is intended exclusively for simulation and testbench use.\n- **No split or retry**: The bus does not support split transactions, retry, or multiple in‑flight requests.\n- **No inter‑transaction timing**: There is no minimum idle cycle requirement between transactions; back‑to‑back requests are handled normally as long as arbitration and address decoding are stable.\n\n## 7. Summary of Behavior\n\n1. In each clock cycle, the bus examines all master request signals. The highest‑priority requesting master is granted the bus.\n2. Using the address from the granted master, the bus selects the slave whose address range matches (based on base and mask).\n3. The granted master’s transaction signals are forwarded to the selected slave; other slaves receive inactive request signals.\n4. One clock cycle later, the bus captures the response (read data, valid, error) from the selected slave and routes it back to the master that was served in the previous cycle.\n5. Non‑selected masters receive inactive response signals (grant de‑asserted, read data/error/valid zero).\n6. Reset clears all internal selection registers, causing all outputs to become inactive.\n\nThis completes the behavioral specification of the bus module.", "commit_id": "0667c14f15612dd7c4b19aa808aef7acf59a0b21", "timestamp": "2019-09-16T12:36:24+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "9958d300638908a72a8d64e8e5b8f8034bedd6c0", "pr_title": "[DV] Fix latch in simple bus", "pr_body": "", "issue_title": "riscv-compliance test system: Fix arbitration error in bus", "issue_body": "@GregAC mentioned that this code\r\n\r\nhttps://github.com/lowRISC/ibex/blob/ac22439374a0bafd6fc2f9d38aefc02e44fa2abb/dv/riscv_compliance/rtl/bus.sv#L57-L64\r\n\r\ndoesn't work as expected in Verilator and gives out grants to two hosts at the same time. \r\n\r\n@GregAC can you\r\n- Double-check what the standard and other tools say should be the right behavior?\r\n- If this happens to be a bug in Verilator, file a bug report.\r\n- And possibly try to find a workaround?", "commit_message": "[DV] Fix latch in simple bus\n\nFixes #297", "fix_patch": "diff --git a/dv/riscv_compliance/rtl/bus.sv b/dv/riscv_compliance/rtl/bus.sv\nindex 4491e9e1e7..188a2b8312 100644\n--- a/dv/riscv_compliance/rtl/bus.sv\n+++ b/dv/riscv_compliance/rtl/bus.sv\n@@ -104,12 +104,13 @@ module bus #(\n \n always_comb begin\n for (integer host = 0; host < NrHosts; host = host + 1) begin\n+ host_gnt_o[host] = 1'b0;\n+\n if ($clog2(NrHosts)'(host) == host_sel_resp) begin\n host_rvalid_o[host] = device_rvalid_i[device_sel_resp];\n host_err_o[host] = device_err_i[device_sel_resp];\n host_rdata_o[host] = device_rdata_i[device_sel_resp];\n end else begin\n- host_gnt_o[host] = 1'b0;\n host_rvalid_o[host] = 1'b0;\n host_err_o[host] = 1'b0;\n host_rdata_o[host] = 'b0;\n", "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 * Simplistic Ibex bus implementation\n *\n * This module is designed for demo and simulation purposes, do not use it in\n * a real-world system.\n *\n * This implementation doesn't handle the full bus protocol, but makes the\n * following simplifying assumptions.\n *\n * - All devices (slaves) must respond in the next cycle after the request.\n * - Host (master) arbitration is strictly priority based.\n */\nmodule bus #(\n parameter NrDevices,\n parameter NrHosts,\n parameter DataWidth = 32,\n parameter AddressWidth = 32\n) (\n input clk_i,\n input rst_ni,\n\n // Hosts (masters)\n input host_req_i [NrHosts],\n output logic host_gnt_o [NrHosts],\n\n input [AddressWidth-1:0] host_addr_i [NrHosts],\n input host_we_i [NrHosts],\n input [ DataWidth/8-1:0] host_be_i [NrHosts],\n input [ DataWidth-1:0] host_wdata_i [NrHosts],\n output logic host_rvalid_o [NrHosts],\n output logic [ DataWidth-1:0] host_rdata_o [NrHosts],\n output logic host_err_o [NrHosts],\n\n // Devices (slaves)\n output logic device_req_o [NrDevices],\n\n output logic [AddressWidth-1:0] device_addr_o [NrDevices],\n output logic device_we_o [NrDevices],\n output logic [ DataWidth/8-1:0] device_be_o [NrDevices],\n output logic [ DataWidth-1:0] device_wdata_o [NrDevices],\n input device_rvalid_i [NrDevices],\n input [ DataWidth-1:0] device_rdata_i [NrDevices],\n input device_err_i [NrDevices],\n\n // Device address map\n input [AddressWidth-1:0] cfg_device_addr_base [NrDevices],\n input [AddressWidth-1:0] cfg_device_addr_mask [NrDevices]\n);\n\n logic [$clog2(NrHosts)-1:0] host_sel_req, host_sel_resp;\n logic [$clog2(NrDevices)-1:0] device_sel_req, device_sel_resp;\n\n // Master select prio arbiter\n always_comb begin\n for (integer host = NrHosts - 1; host >= 0; host = host - 1) begin\n if (host_req_i[host]) begin\n host_sel_req = $clog2(NrHosts)'(host);\n end\n end\n end\n\n // Device select\n always_comb begin\n for (integer device = 0; device < NrDevices; device = device + 1) begin\n if ((host_addr_i[host_sel_req] & cfg_device_addr_mask[device])\n == cfg_device_addr_base[device]) begin\n device_sel_req = $clog2(NrDevices)'(device);\n end\n end\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n host_sel_resp <= '0;\n device_sel_resp <= '0;\n end else begin\n // Responses are always expected 1 cycle after the request\n device_sel_resp <= device_sel_req;\n host_sel_resp <= host_sel_req;\n end\n end\n\n always_comb begin\n for (integer device = 0; device < NrDevices; device = device + 1) begin\n if ($clog2(NrDevices)'(device) == device_sel_req) begin\n device_req_o[device] = host_req_i[host_sel_req];\n device_we_o[device] = host_we_i[host_sel_req];\n device_addr_o[device] = host_addr_i[host_sel_req];\n device_wdata_o[device] = host_wdata_i[host_sel_req];\n device_be_o[device] = host_be_i[host_sel_req];\n end else begin\n device_req_o[device] = 1'b0;\n device_we_o[device] = 1'b0;\n device_addr_o[device] = 'b0;\n device_wdata_o[device] = 'b0;\n device_be_o[device] = 'b0;\n end\n end\n end\n\n always_comb begin\n for (integer host = 0; host < NrHosts; host = host + 1) begin\n host_gnt_o[host] = 1'b0;\n\n if ($clog2(NrHosts)'(host) == host_sel_resp) begin\n host_rvalid_o[host] = device_rvalid_i[device_sel_resp];\n host_err_o[host] = device_err_i[device_sel_resp];\n host_rdata_o[host] = device_rdata_i[device_sel_resp];\n end else begin\n host_rvalid_o[host] = 1'b0;\n host_err_o[host] = 1'b0;\n host_rdata_o[host] = 'b0;\n end\n end\n host_gnt_o[host_sel_req] = host_req_i[host_sel_req];\n end\nendmodule\n", "selected_doc_paths": ["doc/verification.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 289, "lang": "sv", "rtl_files": ["rtl/ibex_core_tracing.sv"], "spec": "# Behavioral Specification for `ibex_core_tracing`\n\n## 1. Overview\n\n`ibex_core_tracing` is a wrapper module that combines the **Ibex RISC-V core** with an instruction **tracer**. It provides the full functionality of the Ibex core while additionally generating a detailed, human‑readable log of every executed instruction. This tracing capability is intended for debugging, performance analysis, and educational purposes.\n\nThe module is designed to be a direct replacement for `ibex_core` in simulation environments where instruction‑level trace output is desired. It preserves all interfaces and behaviors of the underlying core.\n\n## 2. Functional Description\n\nThe module shall instantiate an Ibex core and, conditionally, a tracer component. The core executes the RISC‑V instruction set architecture (RV32I/E/M, etc.) and supports all standard interfaces (instruction fetch, data memory, interrupts, debug, etc.). The tracer continuously monitors the internal state of the core through an auxiliary interface (the RISC‑V Formal Interface, RVFI) and logs each instruction as it is committed.\n\n### 2.1 Core Operation\n\nThe core behavior is identical to that of `ibex_core`. It implements a 2‑stage pipelined RISC‑V processor with the following key features:\n\n- Fetch, decode, execute, and write‑back of instructions.\n- Support for machine‑level interrupts (software, timer, external) and fast interrupts.\n- Non‑maskable interrupt handling.\n- Debug mode support (external request).\n- Programmable hardware performance counters (mhpmcounter).\n- Configurable support for the RV32E (embedded) and RV32M (multiply/divide) extensions.\n- Bus‑style interfaces for instruction and data memory, each with ready/valid handshake and error reporting.\n\nThe core shall operate correctly regardless of whether tracing is enabled. Tracing must not alter the functional behavior of the core.\n\n### 2.2 Tracer Operation\n\nWhen compiled for simulation (i.e., not using Verilator), the module shall include a tracer component that records and outputs information about each committed instruction. For each instruction the tracer shall log:\n\n- The program counter (PC) value.\n- The instruction word.\n- The values of the source registers (rs1, rs2), if applicable.\n- The destination register address and the value written to it (if any).\n- Memory address and data for load/store operations (including read and write values).\n- The hart ID of the core.\n\nThe tracer **shall** be instantiated only when the simulation tool is **not** Verilator, because the tracer uses SystemVerilog constructs that Verilator does not support. In Verilator‑hosted simulations the tracer shall be omitted, and the module shall function exactly as a plain `ibex_core`.\n\nThe tracer **depends** on the global definition of the `RVFI` preprocessor symbol. The module **must** be compiled with `RVFI` defined. If `RVFI` is not defined, the module shall produce a compilation error (as indicated by the source code's `$fatal` call). This ensures that the RVFI signals are always available for the tracer.\n\n### 2.3 Interface with the Core\n\nThe tracer receives its input from the RISC‑V Formal Interface (RVFI), a set of signals that the core exports for every retired instruction. RVFI is an industry‑standard interface used for formal verification and debugging. The tracer does **not** modify or interfere with these signals; it only reads them.\n\nThe connections between the core and the tracer are made internal to the module. Externally, only the standard core interfaces are visible.\n\n## 3. Interfaces\n\n### 3.1 Clock and Reset\n\n- **Clock input (`clk_i`):** All synchronous logic shall be clocked on the rising edge.\n- **Synchronous active‑low reset (`rst_ni`):** When asserted, the core and tracer shall be reset to their initial states.\n\n### 3.2 Core Control\n\n- **Test enable (`test_en_i`):** When asserted, all clock gates shall be forced open for test purposes.\n- **Hart ID (`hart_id_i`):** A 32‑bit identifier for the core, used for instance identification in multi‑core systems.\n- **Boot address (`boot_addr_i`):** The 32‑bit address from which the core shall start fetching instructions after reset.\n- **Fetch enable (`fetch_enable_i`):** While asserted, the core is allowed to fetch and execute instructions. When de‑asserted, the core shall halt.\n- **Core sleep (`core_sleep_o`):** Indicates that the core is idle (no outstanding memory requests, not executing).\n\n### 3.3 Instruction Memory Interface\n\nStandard request/grant/rvalid handshake plus address, read data, and error signal. Behavior follows the Ibex core specification (not detailed here).\n\n### 3.4 Data Memory Interface\n\nStandard request/grant/rvalid handshake with byte enables, write/read data, address, and error signal. Behaviour identical to `ibex_core`.\n\n### 3.5 Interrupt Inputs\n\n- Software, timer, external (each 1‑bit), plus 15 fast interrupt inputs (`irq_fast_i[14:0]`) and one non‑maskable interrupt (`irq_nm_i`). Level‑sensitive, handled according to the RISC‑V privileged specification.\n\n### 3.6 Debug Interface\n\n- **`debug_req_i`:** External debug request. When asserted, the core shall enter debug mode.\n\n### 3.7 Tracing Output (Simulation Only)\n\nThe tracer typically outputs text through standard simulation mechanisms (e.g., `$display` or file I/O). The exact output format is defined by the `ibex_tracer` module and is **not** a hardware interface. No external output ports are provided for tracing; the log is purely for simulation observability.\n\n## 4. Configuration Parameters\n\nThe module shall accept the same parameters as the underlying `ibex_core`:\n\n| Parameter | Type | Default | Description |\n|-----------------------|-------------|---------|-------------|\n| `MHPMCounterNum` | unsigned int| 8 | Number of hardware performance counters (mhpmcounter). |\n| `MHPMCounterWidth` | unsigned int| 40 | Width of each performance counter in bits. |\n| `RV32E` | bit | 0 | If set, core operates in RV32E mode (16 registers). |\n| `RV32M` | bit | 1 | If set, multiply/divide extension is included. |\n| `DmHaltAddr` | unsigned int| 32'h1A110800 | Address for debug mode halt entry. |\n| `DmExceptionAddr` | unsigned int| 32'h1A110808 | Address for debug mode exception entry. |\n\nThese parameters shall be forwarded directly to the internal core instance.\n\n## 5. Operational Behavior\n\n- **Normal execution:** After reset and with `fetch_enable_i` high, the core fetches and executes instructions. For each instruction that is committed (i.e., completes without being flushed by a branch misprediction, interrupt, or debug entry), the tracer shall output a trace line (if tracer is present).\n- **Interrupts and exceptions:** The core services interrupts according to the RISC‑V machine‑level interrupt handling. Tracing shall include the instruction that was interrupted (if any) and the interrupt‑handler entry (if visible through RVFI). The tracer will log the trap indicator from RVFI.\n- **Debug mode:** When `debug_req_i` is asserted, the core shall enter debug mode. Tracing shall continue for debug‑mode instructions.\n- **Invalid instructions:** If the core encounters an illegal instruction, it shall raise an exception. The tracer shall log the instruction along with the trap flag.\n- **Memory errors:** Instructions that cause bus errors (via `instr_err_i` or `data_err_i`) shall cause appropriate exceptions. The tracer will log the instruction and the associated memory operation (if any).\n- **Reset:** Asserting `rst_ni` shall reset the core and the tracer. After reset, the tracer shall start a new log session (e.g., clear internal state, begin at order 0).\n\n## 6. Limitations and Constraints\n\n- The tracer is **not compatible with Verilator**. In Verilator‑based simulations, the tracer is omitted to avoid simulation errors. This behavior is enforced by a preprocessor guard.\n- The module **requires** the `RVFI` preprocessor macro to be defined globally. Without it, the design will not compile. This is because the core exports RVFI signals that are necessary for the tracer.\n- The tracer output is simulation‑only and has no influence on hardware behavior. It does not add output ports or consume additional FPGA resources when synthesised (the tracer is typically excluded during synthesis via `ifdef`).\n- The tracer’s output format is defined by the `ibex_tracer` module; this specification does not mandate a specific format.\n\n## 7. Relationship to Other Modules\n\n- `ibex_core` – the actual RISC‑V core. All behavioural requirements of `ibex_core` implicitly apply.\n- `ibex_tracer` – the tracer module that formats and outputs trace data.\n- `ibex_pkg` – package containing type definitions used throughout the Ibex design.\n\n## 8. Compliance and Verification\n\nThis module shall be verified as part of the Ibex verification suite. The tracer does not affect functional correctness; verification shall focus on ensuring that:\n\n1. The core behaves identically whether or not the tracer is instantiated.\n2. The tracer correctly receives and logs every committed instruction.\n3. The conditional removal for Verilator does not break the core.\n4. The `RVFI` define requirement is enforced at compile time.", "commit_id": "60de915d6b85b61a4981263c7a7fa8fa922d3f4d", "timestamp": "2019-09-07T09:24:28+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "7ddee54f9f78bc0409933b35a77758992c13178c", "pr_title": "Fix syntax error", "pr_body": "Fix a syntax error introduced by #284, addresses the first part of #287 ", "issue_title": "Add core_sleep_o to ibex interface (fixes #258)", "issue_body": "Signals the core is totally idle (WFI with no outstanding memory\r\ntransactions).", "commit_message": "Fix syntax error", "fix_patch": "diff --git a/rtl/ibex_core_tracing.sv b/rtl/ibex_core_tracing.sv\nindex b3cb53ca6d..7331923346 100644\n--- a/rtl/ibex_core_tracing.sv\n+++ b/rtl/ibex_core_tracing.sv\n@@ -148,7 +148,7 @@ module ibex_core_tracing #(\n .rvfi_mem_rdata,\n .rvfi_mem_wdata,\n \n- .fetch_enable_i\n+ .fetch_enable_i,\n .core_sleep_o\n );\n \n", "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/**\n * Top level module of the ibex RISC-V core with tracing enabled\n */\nmodule ibex_core_tracing #(\n parameter int unsigned MHPMCounterNum = 8,\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 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 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 input logic [31:0] data_rdata_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 // Debug Interface\n input logic debug_req_i,\n\n // CPU Control Signals\n input logic fetch_enable_i,\n output logic core_sleep_o\n\n);\n\n import ibex_pkg::*;\n\n // ibex_tracer relies on the signals from the RISC-V Formal Interface\n `ifndef RVFI\n Fatal error: RVFI needs to be defined globally.\n `endif\n\n logic rvfi_valid;\n logic [63:0] rvfi_order;\n logic [31:0] rvfi_insn;\n logic rvfi_trap;\n logic rvfi_halt;\n logic rvfi_intr;\n logic [ 1:0] rvfi_mode;\n logic [ 4:0] rvfi_rs1_addr;\n logic [ 4:0] rvfi_rs2_addr;\n logic [31:0] rvfi_rs1_rdata;\n logic [31:0] rvfi_rs2_rdata;\n logic [ 4:0] rvfi_rd_addr;\n logic [31:0] rvfi_rd_wdata;\n logic [31:0] rvfi_pc_rdata;\n logic [31:0] rvfi_pc_wdata;\n logic [31:0] rvfi_mem_addr;\n logic [ 3:0] rvfi_mem_rmask;\n logic [ 3:0] rvfi_mem_wmask;\n logic [31:0] rvfi_mem_rdata;\n logic [31:0] rvfi_mem_wdata;\n\n ibex_core #(\n .MHPMCounterNum(MHPMCounterNum),\n .MHPMCounterWidth(MHPMCounterWidth),\n .RV32E(RV32E),\n .RV32M(RV32M),\n .DmHaltAddr(DmHaltAddr),\n .DmExceptionAddr(DmExceptionAddr)\n ) u_ibex_core (\n .clk_i,\n .rst_ni,\n\n .test_en_i,\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,\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,\n .data_rdata_i,\n .data_err_i,\n\n .irq_software_i,\n .irq_timer_i,\n .irq_external_i,\n .irq_fast_i,\n .irq_nm_i,\n\n .debug_req_i,\n\n .rvfi_valid,\n .rvfi_order,\n .rvfi_insn,\n .rvfi_trap,\n .rvfi_halt,\n .rvfi_intr,\n .rvfi_mode,\n .rvfi_rs1_addr,\n .rvfi_rs2_addr,\n .rvfi_rs1_rdata,\n .rvfi_rs2_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\n .fetch_enable_i,\n .core_sleep_o\n );\n\n\n`ifndef VERILATOR\n ibex_tracer u_ibex_tracer (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n .fetch_enable_i ( fetch_enable_i ),\n .hart_id_i ( hart_id_i ),\n\n .valid_i ( rvfi_valid ),\n .pc_i ( rvfi_pc_rdata ),\n .instr_i ( rvfi_insn ),\n .rs1_value_i ( rvfi_rs1_rdata ),\n .rs2_value_i ( rvfi_rs2_rdata ),\n .ex_reg_addr_i ( rvfi_rd_addr ),\n .ex_reg_wdata_i ( rvfi_rd_wdata ),\n .ex_data_addr_i ( rvfi_mem_addr ),\n .ex_data_wdata_i ( rvfi_mem_wdata ),\n .ex_data_rdata_i ( rvfi_mem_rdata )\n );\n`else\n // ibex_tracer uses language constructs which Verilator doesn't understand.\n`endif\n\nendmodule\n", "selected_doc_paths": ["doc/rvfi.rst", "doc/tracer.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 54, "lang": "sv", "rtl_files": ["rtl/ibex_compressed_decoder.sv"], "spec": "# Design Specification: Compressed Instruction Decoder (ibex_compressed_decoder)\n\n## Overview\n\nThis module decodes RISC-V compressed (16‑bit) instructions from the “C” extension into their equivalent 32‑bit RV32 instructions. It operates as a pure combinational block and produces three outputs:\n\n- A 32‑bit decompressed or pass‑through instruction.\n- A flag indicating whether the input instruction was a compressed instruction.\n- A flag indicating whether the compressed instruction encoding is illegal (reserved, undefined, or invalid).\n\nThe decoder does **not** validate the correctness of 32‑bit instructions; it only checks compressed encodings for compliance with the RISC‑V specification.\n\n## Behavior\n\n### 1. Instruction Identification\n\nThe decoder considers the two least significant bits of the 16‑bit half‑word (or the bottom two bits of the full 32‑bit input) to determine the instruction type:\n\n- **Uncompressed (32‑bit) instructions**: When the two least significant bits equal `11`, the input is treated as a standard 32‑bit instruction. The module passes the input directly to the instruction output, sets the compressed flag to false, and does not assert the illegal instruction flag (regardless of the instruction’s validity).\n\n- **Compressed (16‑bit) instructions**: When the two least significant bits are **not** `11` (i.e., `00`, `01`, or `10`), the module interprets the lower 16 bits as a RISC‑V compressed instruction. The compressed flag is asserted. The output instruction is the corresponding 32‑bit equivalent as defined below.\n\n### 2. Decoding Rules for Compressed Instructions\n\nThe compressed instruction set is divided into three major quadrants (C0, C1, C2) based on the bottom two bits. Within each quadrant, the three bits `[15:13]` and additional sub‑fields further select the operation.\n\n#### 2.1 Quadrant C0 (bits[1:0] = `00`)\n\n- **c.addi4spn** (opcode `000`) \n Decodes to an `ADDI` instruction that adds a zero‑extended, scaled immediate to register `x2` (stack pointer). If the immediate field is all zeros, the encoding is illegal and the illegal flag shall be asserted.\n\n- **c.lw** (opcode `010`) \n Decodes to a `LW` (load word) instruction that loads a word from memory at a base address given by a register in the `x8–x15` range (compressed register specifier `rd'`). The immediate is formed from the compressed encoding.\n\n- **c.sw** (opcode `110`) \n Decodes to a `SW` (store word) instruction that stores a word to memory, using the same base register range and immediate formation.\n\n- All other opcodes in C0 (e.g., `001`, `011`, `100`, `101`, `111`) are reserved and shall set the illegal instruction flag.\n\n#### 2.2 Quadrant C1 (bits[1:0] = `01`)\n\n- **c.addi / c.nop** (opcode `000`) \n Decodes to an `ADDI` instruction with the same destination and source register. When the destination register is `x0`, the instruction behaves as `c.nop` (the decompressed instruction is still `ADDI x0, x0, 0`).\n\n- **c.jal** (opcode `001`) and **c.j** (opcode `101`) \n Decode to the `JAL` instruction. `c.jal` uses `x1` as the link register; `c.j` uses `x0` (no link). The immediate is sign‑extended from the compressed encoding.\n\n- **c.li** (opcode `010`) \n Decodes to `ADDI rd, x0, imm` (load immediate). If the destination register is `x0` (a hint), the decoder still produces a valid `ADDI` instruction; no illegal flag is asserted.\n\n- **c.lui** (opcode `011`) \n Normally decodes to `LUI rd, imm`. If the destination register is `x2`, the instruction is reinterpreted as **c.addi16sp** and decodes to `ADDI x2, x2, nzimm`. \n If the immediate field (bits `[12]` and `[6:2]`) is all zeros, the encoding is illegal.\n\n- **c.srli** (opcode `100`, sub‑op `00`) and **c.srai** (opcode `100`, sub‑op `01`) \n Decode to `SRLI` or `SRAI` respectively on registers from the `x8–x15` range. If bit `[12]` is set (reserved for custom‑1 extensions), the instruction is illegal.\n\n- **c.andi** (opcode `100`, sub‑op `10`) \n Decodes to `ANDI rd', rd', imm` on the same register range.\n\n- **c.sub**, **c.xor**, **c.or**, **c.and** (opcode `100`, sub‑op `11`, further selected by bits `[12]` and `[6:5]`) \n Decode to the corresponding `SUB`, `XOR`, `OR`, or `AND` register‑register operations, using the compressed register specifiers for `rd'` and `rs2'`. \n The sub‑fields `100`, `101`, `110`, `111` in this group (the RV64 `c.subw`, `c.addw` variants) are illegal for RV32 and shall assert the illegal flag.\n\n- **c.beqz** (opcode `110`) and **c.bnez** (opcode `111`) \n Decode to `BEQ rs1', x0, imm` and `BNE rs1', x0, imm` respectively. The immediate is formed from the compressed encoding and sign‑extended.\n\n- Any other opcode or sub‑opcode combination not listed above shall cause the illegal instruction flag to be asserted.\n\n#### 2.3 Quadrant C2 (bits[1:0] = `10`)\n\n- **c.slli** (opcode `000`) \n Decodes to `SLLI rd, rd, shamt`. If bit `[12]` is set, the encoding is reserved for custom‑1 and is illegal.\n\n- **c.lwsp** (opcode `010`) \n Decodes to `LW rd, imm(x2)` (load word from stack pointer). If the destination register is `x0`, the encoding is illegal.\n\n- **c.mv** / **c.jr** (opcode `100`, bit `[12]` = 0) \n - If the source field `rs2` (bits `[6:2]`) is non‑zero, the instruction is **c.mv** and decodes to `ADD rd, x0, rs2`. \n - If the source field is zero, the instruction is **c.jr** and decodes to `JALR x0, rs1, 0`. A jump to register `x0` (i.e., `rs1 = x0`) is illegal.\n\n- **c.add** / **c.jalr** / **c.ebreak** (opcode `100`, bit `[12]` = 1) \n - If the source field `rs2` is non‑zero, the instruction is **c.add** and decodes to `ADD rd, rd, rs2`. \n - If the source field is zero: \n - If the destination register `rd` (bits `[11:7]`) is also zero, the instruction is **c.ebreak** and decodes to the `EBREAK` instruction (`0x00100073`). \n - Otherwise, the instruction is **c.jalr** and decodes to `JALR x1, rs1, 0`.\n\n- **c.swsp** (opcode `110`) \n Decodes to `SW rs2, imm(x2)` (store word through stack pointer).\n\n- Opcodes `001`, `011`, `101`, and `111` in this quadrant are reserved and shall set the illegal instruction flag.\n\n- Any undefined combination within the C2 quadrant shall cause the illegal instruction flag to be asserted.\n\n### 3. Illegal Instruction Flag\n\nThe illegal instruction flag (`illegal_instr_o`) is asserted under the following conditions:\n\n- A compressed instruction pattern that does not correspond to any defined RISC‑V compressed instruction in the specification (including reserved encodings and those marked as illegal in the paragraphs above).\n- A compressed instruction that, by definition, requires a non‑zero immediate or register field but that field is zero (e.g., `c.addi4spn` with zero immediate, `c.lwsp` with `rd=x0`, `c.jr` with `rs1=x0`, etc.).\n- Any opcode in a quadrant that is explicitly reserved or unused.\n\nThe flag is **not** asserted for valid compressed instructions, including hints (where the destination register is `x0` but the encoding is still defined; these produce legal 32‑bit instructions).\n\n### 4. Pass‑Through for 32‑bit Instructions\n\nWhen the input is identified as a 32‑bit instruction (bottom two bits = `11`), the module outputs the input unchanged as the decompressed instruction. No legality check is performed on the 32‑bit encoding; the illegal flag remains low.\n\n## Interface Summary\n\n| Port | Direction | Width | Description |\n|---------------|-----------|-------|-------------|\n| instruction input | input | 32 | The full instruction word (either 16‑bit compressed or 32‑bit uncompressed). |\n| instruction output | output| 32 | The decoded 32‑bit instruction (pass‑through for 32‑bit inputs). |\n| is compressed | output | 1 | Asserted when the two least significant bits of the input are not `11`. |\n| illegal instruction | output | 1 | Asserted when the compressed instruction encoding is not a valid RISC‑V compressed instruction. |\n\n## Constraints\n\n- All decoding is purely combinational. There are no clock, reset, or sequential elements.\n- The output instruction must be a valid 32‑bit RISC‑V instruction encoding (opcode, funct3, funct7, immediate fields, register addresses) for all defined compressed inputs.\n- The decoder does **not** implement register renaming or instruction execution; it only transforms the instruction encoding.\n- Immediate values for branch and jump instructions are sign‑extended according to the RISC‑V specification.\n- The compressed register specifiers (`rd'`, `rs1'`, `rs2'`) refer to registers `x8` (1000) to `x15` (1111) as per the RISC‑V compressed encoding standard.\n\n## Dependencies\n\nThe module imports constants from the `ibex_defines` package (not shown here) which contain the opcode constants (`OPCODE_OPIMM`, `OPCODE_LOAD`, `OPCODE_STORE`, `OPCODE_BRANCH`, `OPCODE_JAL`, `OPCODE_JALR`, `OPCODE_OP`, `OPCODE_LUI`). These are used to construct the output instruction’s opcode field and are assumed to be correct for the RV32 base instruction set.", "commit_id": "cd15ce88beba8ed8496f414af361f664764f47e2", "timestamp": "2019-05-31T16:26:20+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "5319734180ac4844e43d31ad19dc108aac503037", "pr_title": "Fix decoding of C.LI, C.LUI, C.SRLI, C.SRAI, C.SSLI", "pr_body": "Hints encoded in these compressed instructions must decode into hints\r\nin the corresponding base instructions. This resolves #51.", "issue_title": "HINT instruction decoding issue - 0x7065", "issue_body": "Based on the spec, it should be decoded as HINT instruction (C.LUI, rd == 0), but it's decoded as illegal instruction by design incorrectly.\r\nhttps://github.com/lowRISC/ibex/blob/master/rtl/ibex_compressed_decoder.sv#L105\r\n\r\n```\r\n 3'b011: begin\r\n // c.lui -> lui rd, imm\r\n instr_o = {{15 {instr_i[12]}}, instr_i[6:2], instr_i[11:7], {OPCODE_LUI}};\r\n\r\n if (instr_i[11:7] == 5'h02) begin\r\n // c.addi16sp -> addi x2, x2, nzimm\r\n instr_o = {{3 {instr_i[12]}}, instr_i[4:3], instr_i[5], instr_i[2],\r\n instr_i[6], 4'b0, 5'h02, 3'b000, 5'h02, {OPCODE_OPIMM}};\r\n end else if (instr_i[11:7] == 5'b0) begin // this is INCORRECT\r\n illegal_instr_o = 1'b1;\r\n end\r\n\r\n if ({instr_i[12], instr_i[6:2]} == 6'b0) illegal_instr_o = 1'b1;\r\n end\r\n```\r\n", "commit_message": "Fix decoding of C.LI, C.LUI, C.SRLI, C.SRAI, C.SSLI\n\nHints encoded in these compressed instructions must decode into hints\nin the corresponding base instructions. This resolves #51.", "fix_patch": "diff --git a/rtl/ibex_compressed_decoder.sv b/rtl/ibex_compressed_decoder.sv\nindex d0b31dd7a0..536d384398 100644\n--- a/rtl/ibex_compressed_decoder.sv\n+++ b/rtl/ibex_compressed_decoder.sv\n@@ -88,21 +88,20 @@ module ibex_compressed_decoder (\n \n 3'b010: begin\n // c.li -> addi rd, x0, nzimm\n+ // (c.li hints are translated into an addi hint)\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2], 5'b0,\n 3'b0, instr_i[11:7], {OPCODE_OPIMM}};\n- if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n end\n \n 3'b011: begin\n // c.lui -> lui rd, imm\n+ // (c.lui hints are translated into a lui hint)\n instr_o = {{15 {instr_i[12]}}, instr_i[6:2], instr_i[11:7], {OPCODE_LUI}};\n \n if (instr_i[11:7] == 5'h02) begin\n // c.addi16sp -> addi x2, x2, nzimm\n instr_o = {{3 {instr_i[12]}}, instr_i[4:3], instr_i[5], instr_i[2],\n instr_i[6], 4'b0, 5'h02, 3'b000, 5'h02, {OPCODE_OPIMM}};\n- end else if (instr_i[11:7] == 5'b0) begin\n- illegal_instr_o = 1'b1;\n end\n \n if ({instr_i[12], instr_i[6:2]} == 6'b0) illegal_instr_o = 1'b1;\n@@ -114,10 +113,10 @@ module ibex_compressed_decoder (\n 2'b01: begin\n // 00: c.srli -> srli rd, rd, shamt\n // 01: c.srai -> srai rd, rd, shamt\n+ // (c.srli/c.srai hints are translated into a srli/srai hint)\n instr_o = {1'b0, instr_i[10], 5'b0, instr_i[6:2], 2'b01, instr_i[9:7],\n 3'b101, 2'b01, instr_i[9:7], {OPCODE_OPIMM}};\n if (instr_i[12] == 1'b1) illegal_instr_o = 1'b1;\n- if (instr_i[6:2] == 5'b0) illegal_instr_o = 1'b1;\n end\n \n 2'b10: begin\n@@ -192,9 +191,9 @@ module ibex_compressed_decoder (\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.slli -> slli rd, rd, shamt\n+ // (c.ssli hints are translated into a slli hint)\n instr_o = {7'b0, instr_i[6:2], instr_i[11:7], 3'b001, instr_i[11:7], {OPCODE_OPIMM}};\n- if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n- if (instr_i[12] == 1'b1 || instr_i[6:2] == 5'b0) illegal_instr_o = 1'b1;\n+ if (instr_i[12] == 1'b1) illegal_instr_o = 1'b1; // reserved for custom extensions\n end\n \n 3'b010: begin\n", "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// //\n// Engineer: Sven Stucki - svstucki@student.ethz.ch //\n// //\n// Design Name: Compressed instruction decoder //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Decodes RISC-V compressed instructions into their RV32 //\n// equivalent. This module is fully combinatorial. //\n// //\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Compressed instruction decoder\n *\n * Decodes RISC-V compressed instructions into their RV32 equivalent.\n * This module is fully combinatorial.\n */\nmodule ibex_compressed_decoder (\n input logic [31:0] instr_i,\n output logic [31:0] instr_o,\n output logic is_compressed_o,\n output logic illegal_instr_o\n);\n import ibex_defines::*;\n\n ////////////////////////\n // Compressed decoder //\n ////////////////////////\n\n always_comb begin\n illegal_instr_o = 1'b0;\n instr_o = 'X;\n\n unique case (instr_i[1:0])\n // C0\n 2'b00: begin\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.addi4spn -> addi rd', x2, imm\n instr_o = {2'b0, instr_i[10:7], instr_i[12:11], instr_i[5],\n instr_i[6], 2'b00, 5'h02, 3'b000, 2'b01, instr_i[4:2], {OPCODE_OPIMM}};\n if (instr_i[12:5] == 8'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b010: begin\n // c.lw -> lw rd', imm(rs1')\n instr_o = {5'b0, instr_i[5], instr_i[12:10], instr_i[6],\n 2'b00, 2'b01, instr_i[9:7], 3'b010, 2'b01, instr_i[4:2], {OPCODE_LOAD}};\n end\n\n 3'b110: begin\n // c.sw -> sw rs2', imm(rs1')\n instr_o = {5'b0, instr_i[5], instr_i[12], 2'b01, instr_i[4:2],\n 2'b01, instr_i[9:7], 3'b010, instr_i[11:10], instr_i[6],\n 2'b00, {OPCODE_STORE}};\n end\n\n default: begin\n illegal_instr_o = 1'b1;\n end\n endcase\n end\n\n // C1\n 2'b01: begin\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.addi -> addi rd, rd, nzimm\n // c.nop\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2],\n instr_i[11:7], 3'b0, instr_i[11:7], {OPCODE_OPIMM}};\n end\n\n 3'b001, 3'b101: begin\n // 001: c.jal -> jal x1, imm\n // 101: c.j -> jal x0, imm\n instr_o = {instr_i[12], instr_i[8], instr_i[10:9], instr_i[6],\n instr_i[7], instr_i[2], instr_i[11], instr_i[5:3],\n {9 {instr_i[12]}}, 4'b0, ~instr_i[15], {OPCODE_JAL}};\n end\n\n 3'b010: begin\n // c.li -> addi rd, x0, nzimm\n // (c.li hints are translated into an addi hint)\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2], 5'b0,\n 3'b0, instr_i[11:7], {OPCODE_OPIMM}};\n end\n\n 3'b011: begin\n // c.lui -> lui rd, imm\n // (c.lui hints are translated into a lui hint)\n instr_o = {{15 {instr_i[12]}}, instr_i[6:2], instr_i[11:7], {OPCODE_LUI}};\n\n if (instr_i[11:7] == 5'h02) begin\n // c.addi16sp -> addi x2, x2, nzimm\n instr_o = {{3 {instr_i[12]}}, instr_i[4:3], instr_i[5], instr_i[2],\n instr_i[6], 4'b0, 5'h02, 3'b000, 5'h02, {OPCODE_OPIMM}};\n end\n\n if ({instr_i[12], instr_i[6:2]} == 6'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b100: begin\n unique case (instr_i[11:10])\n 2'b00,\n 2'b01: begin\n // 00: c.srli -> srli rd, rd, shamt\n // 01: c.srai -> srai rd, rd, shamt\n // (c.srli/c.srai hints are translated into a srli/srai hint)\n instr_o = {1'b0, instr_i[10], 5'b0, instr_i[6:2], 2'b01, instr_i[9:7],\n 3'b101, 2'b01, instr_i[9:7], {OPCODE_OPIMM}};\n if (instr_i[12] == 1'b1) illegal_instr_o = 1'b1;\n end\n\n 2'b10: begin\n // c.andi -> andi rd, rd, imm\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2], 2'b01, instr_i[9:7],\n 3'b111, 2'b01, instr_i[9:7], {OPCODE_OPIMM}};\n end\n\n 2'b11: begin\n unique case ({instr_i[12], instr_i[6:5]})\n 3'b000: begin\n // c.sub -> sub rd', rd', rs2'\n instr_o = {2'b01, 5'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7],\n 3'b000, 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b001: begin\n // c.xor -> xor rd', rd', rs2'\n instr_o = {7'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7], 3'b100,\n 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b010: begin\n // c.or -> or rd', rd', rs2'\n instr_o = {7'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7], 3'b110,\n 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b011: begin\n // c.and -> and rd', rd', rs2'\n instr_o = {7'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7], 3'b111,\n 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b100,\n 3'b101,\n 3'b110,\n 3'b111: begin\n // 100: c.subw\n // 101: c.addw\n illegal_instr_o = 1'b1;\n end\n\n default: begin\n illegal_instr_o = 1'bX;\n end\n endcase\n end\n\n default: begin\n illegal_instr_o = 1'bX;\n end\n endcase\n end\n\n 3'b110, 3'b111: begin\n // 0: c.beqz -> beq rs1', x0, imm\n // 1: c.bnez -> bne rs1', x0, imm\n instr_o = {{4 {instr_i[12]}}, instr_i[6:5], instr_i[2], 5'b0, 2'b01,\n instr_i[9:7], 2'b00, instr_i[13], instr_i[11:10], instr_i[4:3],\n instr_i[12], {OPCODE_BRANCH}};\n end\n\n default: begin\n illegal_instr_o = 1'bX;\n end\n endcase\n end\n\n // C2\n 2'b10: begin\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.slli -> slli rd, rd, shamt\n // (c.ssli hints are translated into a slli hint)\n instr_o = {7'b0, instr_i[6:2], instr_i[11:7], 3'b001, instr_i[11:7], {OPCODE_OPIMM}};\n if (instr_i[12] == 1'b1) illegal_instr_o = 1'b1; // reserved for custom extensions\n end\n\n 3'b010: begin\n // c.lwsp -> lw rd, imm(x2)\n instr_o = {4'b0, instr_i[3:2], instr_i[12], instr_i[6:4], 2'b00, 5'h02,\n 3'b010, instr_i[11:7], OPCODE_LOAD};\n if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b100: begin\n if (instr_i[12] == 1'b0) begin\n if (instr_i[6:2] != 5'b0) begin\n // c.mv -> add rd/rs1, x0, rs2\n // (c.mv hints are translated into an add hint)\n instr_o = {7'b0, instr_i[6:2], 5'b0, 3'b0, instr_i[11:7], {OPCODE_OP}};\n end else begin\n // c.jr -> jalr x0, rd/rs1, 0\n instr_o = {12'b0, instr_i[11:7], 3'b0, 5'b0, {OPCODE_JALR}};\n if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n end\n end else begin\n if (instr_i[6:2] != 5'b0) begin\n // c.add -> add rd, rd, rs2\n // (c.add hints are translated into an add hint)\n instr_o = {7'b0, instr_i[6:2], instr_i[11:7], 3'b0, instr_i[11:7], {OPCODE_OP}};\n end else begin\n if (instr_i[11:7] == 5'b0) begin\n // c.ebreak -> ebreak\n instr_o = {32'h00_10_00_73};\n end else begin\n // c.jalr -> jalr x1, rs1, 0\n instr_o = {12'b0, instr_i[11:7], 3'b000, 5'b00001, {OPCODE_JALR}};\n end\n end\n end\n end\n\n 3'b110: begin\n // c.swsp -> sw rs2, imm(x2)\n instr_o = {4'b0, instr_i[8:7], instr_i[12], instr_i[6:2], 5'h02, 3'b010,\n instr_i[11:9], 2'b00, {OPCODE_STORE}};\n end\n\n 3'b001,\n 3'b011,\n 3'b101,\n 3'b111: begin\n illegal_instr_o = 1'b1;\n end\n\n default: begin\n illegal_instr_o = 1'bX;\n end\n endcase\n end\n\n default: begin\n // 32 bit (or more) instruction\n instr_o = instr_i;\n end\n endcase\n end\n\n assign is_compressed_o = (instr_i[1:0] != 2'b11);\n\nendmodule\n", "selected_doc_paths": []}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 167, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# Behavioral Design Specification: Ibex Main Controller\n\n## Overview\n\nThe main controller is the central finite state machine (FSM) that orchestrates the execution pipeline of the Ibex processor core. It determines the core’s operational state, controls instruction fetch and decode stages, handles exceptions, interrupts, debug requests, and power‑saving modes. The controller interfaces with the decoder, prefetcher, load‑store unit (LSU), interrupt controller, debug module, and CSR logic.\n\n## Core Behavioral Requirements\n\n### Reset and Initialization\n- Upon reset, the controller shall enter a `RESET` state. In this state, the core does not fetch or decode any instructions.\n- The controller shall remain in `RESET` until a global fetch enable signal is asserted.\n- Once fetch enable is asserted, the controller shall assert the program counter (PC) set signal and select the boot address as the next PC. The boot address is taken from a fixed source (e.g., CSR `mtvec`).\n- Immediately after boot address selection, the controller shall transition to a `FIRST_FETCH` state.\n\n### Instruction Fetch and Decode\n- In the `FIRST_FETCH` state, the controller enables instruction fetch from the prefetcher. It stays in this state until the decode stage is ready to accept an instruction.\n- When the decode stage signals readiness, the controller transitions to `DECODE`.\n- In `DECODE`, the core executes normally. The controller monitors the valid instruction signal from the IF‑ID pipeline register.\n - If a branch or jump instruction is decoded and taken, the controller shall update the PC to the target address (branch/jump) and set a performance counter flag for taken branches or jumps.\n - If a special instruction (MRET, DRET, WFI, CSR‑status instruction) or an exception (illegal instruction, ECALL, EBREAK, load/store fault) is detected, the controller shall transition to the `FLUSH` state.\n - If a debug request is pending and no higher‑priority condition (e.g., ongoing multi‑cycle instruction stall) prevents it, the controller shall transition to `DBG_TAKEN_IF`.\n - If an interrupt is pending and enabled (global interrupt enable is set), and no debug request is pending, the controller shall transition to `IRQ_TAKEN`.\n\n### Pipeline Flush and Special Instructions\n- In the `FLUSH` state, the pipeline shall be halted (no new instructions fetched or decoded).\n- The controller shall take the following actions based on the cause:\n - **Exception (including LSU faults):** Save the exception PC (address of the instruction) and exception cause to the appropriate CSRs (`mepc`, `mcause`, `mtval`). Set the PC to the exception handler address (from `mtvec`). For illegal instruction exceptions, the faulting instruction (or its compressed form) shall be stored in `mtval`. For load/store faults, the address of the offending access shall be stored in `mtval`.\n - **EBREAK handling:**\n - If the core is already in debug mode, re‑enter the `DBG_TAKEN_ID` state without updating debug CSRs.\n - If not in debug mode and the `ebreakm` CSR bit is set, transition to `DBG_TAKEN_ID` without updating exception CSRs.\n - Otherwise, handle as a breakpoint exception (save PC, cause, jump to exception handler).\n - **MRET instruction:** Restore the PC from `mepc` and restore `mstatus.MIE` from `mstatus.MPIE`. Write `csr_restore_mret` signal.\n - **DRET instruction:** Restore the PC from `dpc`, clear debug mode, write `csr_restore_dret` signal.\n - **WFI instruction:** Transition to the `WAIT_SLEEP` state.\n- If single‑step debug is active (and the core is not already in debug mode), the controller shall suppress the PC update and go to `DBG_TAKEN_IF` after taking exception/special instruction actions.\n\n### Interrupt Handling\n- Interrupts are taken only when the core is in `DECODE` state, the global interrupt enable (`mstatus.MIE`) is set, and the core is not in debug mode.\n- Upon transitioning to `IRQ_TAKEN`:\n - The PC shall be set to the interrupt vector address: base of `mtvec` plus four times the interrupt ID.\n - The current PC (address of the interrupted instruction) shall be saved to `mepc`.\n - The cause register (`mcause`) shall be set with the interrupt bit (bit 31) high and the interrupt ID as exception code.\n - An interrupt acknowledge shall be asserted for one cycle, carrying the ID of the interrupt being taken.\n - After one cycle, the controller returns to `DECODE`.\n\n### Debug Entry\n- Debug requests (from `debug_req_i`) are honored only when the core is not already in debug mode.\n- In `DECODE`, a debug request takes priority over interrupts but yields to ongoing multi‑cycle instructions and exceptions.\n- Two debug entry states exist:\n - **`DBG_TAKEN_IF`:** Used for debug requests (halt request) and single‑step triggers. The controller shall:\n - Save the PC from the IF stage to `dpc`.\n - Save the debug cause to `dcsr` (halt request or single step).\n - Jump to the debug exception handler address (given by `DmHaltAddr` parameter).\n - Set the core into debug mode.\n - **`DBG_TAKEN_ID`:** Used when an EBREAK instruction is executed while in debug mode, or when EBREAK is taken from M‑mode with `ebreakm` set. The controller shall:\n - Save the PC from the ID stage (address of the EBREAK instruction) to `dpc`.\n - Save the debug cause (EBREAK) to `dcsr`.\n - Jump to the debug exception handler.\n - Only update `dpc` and `dcsr` if the core is not already in debug mode (for EBREAK re‑entry, no CSR update).\n\n### Sleep Mode (WFI)\n- In `WAIT_SLEEP`, the core indicates it is not busy, stops fetching, and suppresses all pipeline activity.\n- The controller shall remain in `WAIT_SLEEP` for exactly one cycle, then transition to `SLEEP`.\n- In `SLEEP`:\n - The core remains idle (no fetch, halt decode).\n - The core shall wake up and transition to `FIRST_FETCH` when any of the following occur:\n - An external interrupt pin (`irq_i`) is asserted.\n - A debug request is received.\n - The core is already in debug mode or single‑step mode (WFI is treated as a NOP in those cases).\n\n### Stall Control\n- The controller shall determine whether the current instruction finishes in the current cycle.\n- A stall condition (from LSU, multiplier/divider, jump, or branch) shall prevent new instructions from entering the decode stage.\n- During a stall, debug and interrupt requests are deferred but not lost; they are noted and handled once the stall clears.\n- While stalled, the controller shall keep the pipeline halted (inhibit IF‑ID register updates and instruction valid flags).\n\n### Pipeline Halting and Clearing\n- The controller shall provide two independent halt signals:\n - **Halt IF:** Prevents the instruction fetch stage from sending a new instruction to ID.\n - **Halt ID:** Inhibits the ID stage from advancing (e.g., when a multi‑cycle instruction causes an exception).\n- The controller shall also clear the instruction valid flag in the IF‑ID register under specific conditions (e.g., when a stall resolves, or when an exception occurs during a multi‑cycle instruction).\n\n### Performance Monitoring Outputs\n- The controller shall assert a performance counter flag for one cycle when a taken branch is executed.\n- The controller shall assert another flag when a jump instruction (any jump, including JAL, JALR) is executed.\n\n## Summary of State Transitions\n\n| Current State | Trigger / Condition | Next State |\n|---------------|---------------------|------------|\n| RESET | Fetch enable asserted | BOOT_SET |\n| BOOT_SET | Always (1 cycle) | FIRST_FETCH |\n| FIRST_FETCH | ID stage ready, no pending interrupt/debug | DECODE |\n| FIRST_FETCH | Interrupt pending | IRQ_TAKEN |\n| FIRST_FETCH | Debug request pending | DBG_TAKEN_IF |\n| DECODE | Special instruction or exception | FLUSH |\n| DECODE | Branch/jump taken (no other condition) | DECODE |\n| DECODE | Debug request, no stall, no special | DBG_TAKEN_IF |\n| DECODE | Interrupt, no debug, no stall, no special | IRQ_TAKEN |\n| FLUSH | After processing (exception, etc.) | DECODE |\n| FLUSH | WFI instruction | WAIT_SLEEP |\n| WAIT_SLEEP | Always (1 cycle) | SLEEP |\n| SLEEP | Wake condition (irq, debug, etc.) | FIRST_FETCH |\n| IRQ_TAKEN | After one cycle | DECODE |\n| DBG_TAKEN_IF | After one cycle | DECODE |\n| DBG_TAKEN_ID | After one cycle | DECODE |\n\n## Interface Dependencies (Conceptual)\n\nThe controller must receive:\n- Fetch enable\n- Decoded instruction type and validity\n- Branch/jump taken signals\n- Load/store error signals\n- Interrupt request and ID\n- Debug request and single‑step flag\n- Stall signals from execution units\n\nThe controller must output:\n- Fetch request and PC set/mux selection\n- Exception acknowledge, cause, and optional trap value\n- Interrupt acknowledge and ID\n- Debug CSR save, cause, and mode bit\n- Pipeline halt and clear signals\n- Performance counter flags", "commit_id": "59254498489d441f64c24e6b344fce73d0d8bbce", "timestamp": "2019-07-17T10:17:38+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "010985a39555bbbee969296e1da4f3bd0b502e63", "pr_title": "Controller: save next PC to dpc CSR upon a halt request", "pr_body": "This commit changes the controller to save the PC of the next\r\ninstruction to the dpc CSR when entering debug mode upon a halt\r\nrequest instead of the PC of the current instruction (only valid\r\nfor EBREAK instructions).\r\n\r\nThis bug was reported by @taoliug. This resolves #164.", "issue_title": "Debug request causes the same instruction to be executed twice", "issue_body": "In this test, debug_req is asserted while the core is executing instruction at PC 0x8000056a. dpc is saved to the current PC value rather than the next instruction. As a result, the instruction at 0x8000056a is executed again after exiting from debug mode(dret). \r\n\r\nibex log\r\n```\r\n 8487000 4145 8000056a 00cf9f93 slli x31, x31, 0xc x31=0x55508000 x31:0x9d655508\r\n 8595000 4199 80000040 3780e06f jal x0, 58232 \r\n 8639000 4221 8000e3b8 7b200073 dret \r\n 8683000 4243 8000056a 00cf9f93 slli x31, x31, 0xc x31=0x08000000 x31:0x55508000\r\n```\r\n![ebreak_issue](https://user-images.githubusercontent.com/34581368/61328147-46d5db00-a7cf-11e9-936b-24b943170987.png)\r\n", "commit_message": "Controller: save next PC to dpc CSR upon a halt request\n\nThis commit changes the controller to save the PC of the next\ninstruction to the dpc CSR when entering debug mode upon a halt\nrequest instead of the PC of the current instruction (only valid\nfor EBREAK instructions).\n\nThis bug was reported by @taoliug. This resolves #164.", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex d182155e2e..091a7f3c5e 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -323,7 +323,7 @@ module ibex_controller (\n if (!stall && !special_req) begin\n if (enter_debug_mode) begin\n // enter debug mode\n- ctrl_fsm_ns = DBG_TAKEN_ID;\n+ ctrl_fsm_ns = DBG_TAKEN_IF;\n halt_if = 1'b1;\n halt_id = 1'b1;\n \n@@ -382,19 +382,17 @@ module ibex_controller (\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- // 3. halt request during decode\n // regular ebreak's go through FLUSH.\n //\n- // for 1. do not update dcsr and dpc, for 2. and 3. do so [Debug Spec v0.13.2, p.39]\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 || debug_req_i) begin\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 ((ebrk_insn_i && debug_ebreakm_i && !debug_mode_q) || // ebreak with forced entry\n- (enter_debug_mode)) begin // halt request\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@@ -402,11 +400,7 @@ module ibex_controller (\n \n // dcsr\n debug_csr_save_o = 1'b1;\n- if (debug_req_i) begin\n- debug_cause_o = DBG_CAUSE_HALTREQ;\n- end else begin\n- debug_cause_o = DBG_CAUSE_EBREAK;\n- end\n+ debug_cause_o = DBG_CAUSE_EBREAK;\n end\n \n // enter debug mode\n", "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// Davide Schiavone - pschiavo@iis.ee.ethz.ch //\n// //\n// Design Name: Main controller //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Main controller of the processor //\n// //\n////////////////////////////////////////////////////////////////////////////////\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_status_i, // decoder has CSR status instr\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\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_defines::pc_sel_e pc_mux_o, // IF stage fetch address selector\n // (boot, normal, exception...)\n output ibex_defines::exc_pc_sel_e exc_pc_mux_o, // IF stage selector for exception PC\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 // External Interrupt Req Signals, used to wake up from wfi even if the interrupt is not taken\n input logic irq_i,\n // Interrupt Controller Signals\n input logic irq_req_ctrl_i,\n input logic [4:0] irq_id_ctrl_i,\n input logic m_IE_i, // interrupt enable bit from CSR\n // (M mode)\n\n output logic irq_ack_o,\n output logic [4:0] irq_id_o,\n\n output ibex_defines::exc_cause_e exc_cause_o,\n output logic exc_ack_o,\n output logic exc_kill_o,\n\n // debug signals\n input logic debug_req_i,\n output ibex_defines::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_restore_dret_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_defines::*;\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 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 exc_req;\n logic exc_req_lsu;\n logic special_req;\n logic enter_debug_mode;\n logic handle_irq;\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_i) 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 // exception requests\n assign exc_req = ecall_insn_i | ebrk_insn_i | illegal_insn_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_status_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 = irq_req_ctrl_i & m_IE_i & ~debug_mode_q;\n assign exc_kill_o = 1'b0;\n\n /////////////////////\n // Core controller //\n /////////////////////\n\n always_comb begin\n // Default values\n instr_req_o = 1'b1;\n\n exc_ack_o = 1'b0;\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_restore_dret_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 irq_ack_o = 1'b0;\n irq_id_o = irq_id_ctrl_i;\n\n debug_csr_save_o = 1'b0;\n debug_cause_o = DBG_CAUSE_EBREAK;\n debug_mode_d = debug_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 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_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 pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n\n exc_pc_mux_o = EXC_PC_IRQ;\n exc_cause_o = exc_cause_e'({1'b1, irq_id_ctrl_i});\n\n csr_save_cause_o = 1'b1;\n csr_save_if_o = 1'b1;\n\n irq_ack_o = 1'b1;\n exc_ack_o = 1'b1;\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 (illegal_insn_i) 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\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 end else if (dret_insn_i) begin\n pc_mux_o = PC_DRET;\n pc_set_o = 1'b1;\n csr_restore_dret_id_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\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 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 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", "selected_doc_paths": ["doc/exception_interrupts.rst", "doc/interrupts.rst", "doc/debug.rst", "doc/instruction_fetch.rst", "doc/cs_registers.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 294, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# Behavioral Design Specification: Ibex Controller\n\n## 1. Overview\n\nThe controller is the central state machine of the Ibex processor. It orchestrates the instruction fetch and decode stages, manages the pipeline flush, and coordinates the response to exceptions, interrupts, debug requests, and sleep instructions. It accepts stall signals from other execution units and controls the flow of instructions through the pipeline. The controller’s outputs determine the program counter (PC) next value, instruction fetch enable, and various control signals for the CSR unit and the debug subsystem.\n\n## 2. Reset and Boot Sequence\n\n- After reset is released, the controller must remain idle, not issuing any instruction fetch requests, until the external `fetch_enable` signal is asserted.\n- Once `fetch_enable` is asserted, the controller shall set the program counter to the boot address (provided externally) plus the reset offset (0x80) and immediately issue a fetch request.\n- After the first fetch is complete, the controller enters normal operation (fetch/decode).\n\n## 3. Normal Instruction Execution\n\n- In normal operation, the controller keeps the instruction fetch active and delivers fetched instructions to the decode stage.\n- The controller shall stall the pipeline when any of the following conditions is true:\n - A load-store unit (LSU) operation is in progress.\n - A multiply/divide operation is in progress.\n - A jump instruction (JAL, JALR) is being executed (one‑cycle stall).\n - A taken branch instruction is being executed (one‑cycle stall).\n- While stalled, the controller must not advance the decode stage and may prevent the IF stage from fetching new instructions.\n- The controller shall indicate when a jump or a taken branch instruction is executed (for performance monitoring purposes).\n\n## 4. Exceptions\n\nThe controller handles the following exception types, in order of priority as listed in the RISC‑V Privileged Specification (v1.11, Table 3.7):\n\n1. Instruction access fault (from fetch error)\n2. Illegal instruction (including DRET executed outside debug mode)\n3. Breakpoint (EBREAK instruction)\n4. Load access fault\n5. Store access fault\n6. Environment call from M‑mode (ECALL)\n\n### 4.1 Exception Handling Flow\n\n- When an exception is detected during decode, the controller shall:\n - Clear the instruction in the IF‑ID pipeline stage.\n - Save the current program counter (PC) to the `mepc` CSR.\n - Set the exception cause in the `mcause` CSR.\n - Set the `mtval` CSR with the faulting instruction (for illegal instruction/breakpoint) or with the faulting address (for load/store access faults), otherwise zero.\n - Update `mstatus` by copying the MIE bit to MPIE and clearing MIE.\n - Jump to the trap handler by setting the PC to the value in `mtvec` (for machine‑mode exceptions) or to the debug exception address (if in debug mode).\n- For instruction access faults, the faulting PC is stored in `mtval`.\n- For illegal instructions, the instruction encoding (compressed or uncompressed) is stored in `mtval`.\n- For load/store access faults, the address of the transaction causing the error is stored in `mtval`.\n\n### 4.2 Exceptions in Debug Mode\n\n- If an exception occurs while the core is already in debug mode, the controller shall jump to the dedicated debug exception handler address (`DmExceptionAddr`) instead of the normal trap handler.\n- Debug CSRs (`dpdc`, `dcsr`) are not modified by exceptions in debug mode (except for EBREAK, see Section 7).\n\n## 5. Interrupts\n\nThe controller supports the following interrupt sources, listed from highest to lowest priority:\n\n- Non‑maskable interrupt (NMI) – ID 31\n- Fast interrupts (15 signals) – IDs 30 to 16\n- External interrupt – ID 11\n- Timer interrupt – ID 7\n- Software interrupt – ID 3\n\n### 5.1 Interrupt Enable Conditions\n\n- NMI is always enabled (non‑maskable) and takes precedence over all other interrupts.\n- All maskable interrupts (fast, external, timer, software) are only taken when:\n - The core is not in debug mode.\n - The global interrupt enable (MIE) bit in `mstatus` is set.\n - The corresponding individual enable bit in the `mie` CSR is set.\n- Interrupts are ignored when the core is in debug mode, regardless of `mstatus.MIE` and `mie`.\n\n### 5.2 Interrupt Handling Flow\n\n- When a pending interrupt becomes eligible to take, the controller shall:\n - Halt the pipeline and clear any partially decoded instruction in the IF‑ID stage.\n - Save the PC of the next instruction to `mepc`.\n - Set the interrupt cause in `mcause` (with bit 31 = 1 to indicate an interrupt).\n - Save the current `mstatus.MIE` to `mstatus.MPIE` and clear MIE.\n - Jump to the vector table entry: `mtvec` base address plus 4 × interrupt ID.\n- For NMI, the controller shall also set a non‑maskable interrupt mode flag to prevent nested NMIs until an MRET is executed.\n\n### 5.3 Fast Interrupt Priority\n\n- Among the 15 fast interrupt lines, the one with the highest numerical identifier has the highest priority and is serviced first.\n\n### 5.4 Interrupts After Pipeline Flush\n\n- When a CSR write causes a pipeline flush (`csr_pipe_flush`), and an interrupt is pending and enabled, the controller shall take the interrupt immediately after the flush.\n\n## 6. WFI (Wait for Interrupt) Sleep\n\n- Upon execution of a WFI instruction, the controller shall:\n - Halt instruction fetch and decode.\n - Indicate that the core is sleeping (no outstanding bus transactions).\n - Remain in the sleep state until an interrupt (maskable or NMI) or a debug request is asserted.\n - If the core is already in debug mode or single‑stepping, WFI is treated as a NOP (the core does not sleep).\n- When woken by an interrupt, the controller shall resume fetching and decode from the current PC (the instruction following WFI).\n\n## 7. Debug Support\n\nThe controller supports debug according to the RISC‑V Debug Specification v0.13.\n\n### 7.1 Entering Debug Mode\n\nThe controller shall enter debug mode when any of the following conditions occur:\n\n1. **Halt request**: External `debug_req_i` is asserted.\n2. **Single‑step**: `debug_single_step` is set and the core is not already in debug mode (entered after the current instruction completes).\n3. **EBREAK with forced entry**: An EBREAK instruction executes in M‑mode and the `dcsr.ebreakm` bit is set (the core enters debug mode directly).\n4. **EBREAK in debug mode**: An EBREAK instruction executes while already in debug mode (the core returns to debug mode without updating debug CSRs).\n\nWhen entering debug mode, the controller shall:\n- Save the PC of the instruction that caused entry to `dpc`.\n- Set the cause in `dcsr` (halt request, single‑step, or EBREAK).\n- Jump to the debug halt address (`DmHaltAddr`).\n- Set the debug mode flag, which remains active until a DRET instruction is executed.\n\n### 7.2 Behavior in Debug Mode\n\n- While in debug mode, all interrupts (including NMI) are ignored.\n- Exceptions that occur in debug mode cause a jump to the debug exception handler address (`DmExceptionAddr`).\n- If an EBREAK is executed in debug mode, the controller shall re‑enter debug mode without modifying `dpc` or `dcsr` (i.e., it halts again at the same PC).\n\n### 7.3 Single‑Stepping\n\n- When single‑stepping is enabled, the controller shall execute exactly one instruction and then automatically enter debug mode.\n- If the executed instruction causes an exception, the controller shall still enter debug mode after saving the exception state but *without* jumping to the exception handler (the PC is not changed to the trap vector). The exception registers (mepc, mcause) are updated as usual.\n\n## 8. Pipeline Flush and Special Instructions\n\n### 8.1 MRET (Machine Return)\n\n- When an MRET instruction is decoded, the controller shall:\n - Flush the pipeline.\n - Restore the PC from `mepc`.\n - Copy `mstatus.MPIE` back to `mstatus.MIE`.\n - Clear the NMI mode flag if it was set.\n\n### 8.2 DRET (Debug Return)\n\n- When a DRET instruction is decoded (only valid in debug mode), the controller shall:\n - Flush the pipeline.\n - Set the PC to the address in `dpc`.\n - Exit debug mode (clear the debug mode flag).\n\n### 8.3 CSR Pipeline Flush\n\n- Some CSR write operations require a pipeline flush. The controller shall flush the pipeline upon assertion of the `csr_pipe_flush` signal. This flush may also enable a pending interrupt to be taken immediately.\n\n### 8.4 WFI (Wait for Interrupt)\n\n- Handled as described in Section 6. The pipeline is flushed before entering sleep.\n\n## 9. Stall and Pipeline Control\n\n- The controller receives stall signals from the load‑store unit, the multiplier/divider, and from the branch/jump stages.\n- It shall output a signal to the IF‑ID pipeline register to clear the instruction valid flag when the pipeline must be flushed (e.g., after a branch, interrupt, exception, or flush).\n- The controller shall indicate to the IF stage when the ID stage is ready to accept a new instruction (not stalled and not halted).\n- During stalls, the controller shall prevent further instruction fetch and decode as necessary.\n\n## 10. CSR Save/Restore Signals\n\nThe controller generates control signals to the CSR unit:\n\n- **Save IF stage PC**: When taking a trap (interrupt or exception) that requires saving the PC of the instruction being fetched (e.g., for debug entry or NMI).\n- **Save ID stage PC**: When taking a trap that requires saving the PC of the instruction in decode (e.g., for exceptions).\n- **Save cause**: When writing `mcause` or debug cause.\n- **Restore MPIE on MRET**: When executing an MRET.\n- **Debug CSR save**: When entering debug mode (to update `dpdc` and `dcsr`).\n\n## 11. Performance Monitoring\n\nThe controller shall output two performance monitoring signals:\n\n- **Jump executed**: Asserted for one cycle when a jump instruction (JAL, JALR) is executed.\n- **Taken branch executed**: Asserted for one cycle when a taken branch (BEQ, BNE, etc.) is executed.\n\n## 12. Busy and First Fetch Indication\n\n- The controller shall output a busy signal that indicates the core is actively processing instructions (i.e., not in reset or sleep). This signal is de‑asserted only during the sleep state.\n- A `first_fetch` signal shall be asserted during the very first instruction fetch after reset or after wake from sleep.\n\n## 13. Conformance and Assumptions\n\n- This specification assumes the core implements the RISC‑V Machine‑level ISA (RV32I base, optional M and C extensions) as defined in the RISC‑V Privileged Specification v1.11.\n- Debug behavior follows the RISC‑V Debug Specification v0.13.\n- All interrupt lines are level‑sensitive; the external agent must de‑assert the line after the handler acknowledges the interrupt.\n- The controller does not support user‑mode or supervisor‑mode traps; only M‑mode trapping is implemented.", "commit_id": "b87ed7c82e0d4875ecc8bade1330a88e67f48090", "timestamp": "2019-09-09T12:05:49+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "8d3d87ae53254f7716852e944caffa788b473253", "pr_title": "Controller: Fix exception cause ID of fast interrupts", "pr_body": "This commit fixes the generation of the exception cause ID of fast interrupt. Without this commit, the core tries to handle fast interrupts using the handlers of other interrupts like external, software, and timer interrupts.\r\n\r\nThis commit resolves lowRISC/ibex#290 reported by @udinator.", "issue_title": "Incorrect irq_fast ID assignment", "issue_body": "According to the documentation, Ibex should assign all of the fast interrupts `irq_fast_i[14:0]` an ID from 16 to 30, so that `irq_fast_i[0]` has an ID of 16, `irq_fast_i[1]` has an ID of 17, and so on. In the [Ibex CSR register file](https://github.com/lowRISC/ibex/blob/master/rtl/ibex_cs_registers.sv#L572), the entire 15 bit array is output to the [Ibex controller module](https://github.com/lowRISC/ibex/blob/master/rtl/ibex_controller.sv#L165), where `mfip_id` is assigned based on on the value of `irq_fast_i[14:0]`. However these assigned IDs are between 0 and 14. Later on in the controller, `exc_cause_o` is [assigned](https://github.com/lowRISC/ibex/blob/master/rtl/ibex_controller.sv#L363) by appending 1'b1 to `mfip_id`. This is sent to the [Ibex IF stage](https://github.com/lowRISC/ibex/blob/master/rtl/ibex_if_stage.sv#L109), where the 5 bit `irq_id`, which in this case is the ID assigned earlier in the controller, is multiplied by `0x4` and added to the address held in `mtvec` to get the trap address. However, the ID's of all fast interrupts are still from 0 to 14, which seems incorrect according to the RISC-V Privileged Spec Ch. 3.1.16. This means that there are now conflicts with all other interrupts that have ID's between 0 and 14, so Ibex will now jump to the wrong vectored address for all fast interrupts that are sent to the core. I think the `irq_fast` ID assignments in the CSR file should be from between 16 to 30 to fix this issue and comply with the spec.", "commit_message": "Controller: Fix exception cause ID of fast interrupts\n\nThis commit fixes the generation of the exception cause ID for fast\ninterrupts. Without this commit, the core tries to handle fast\ninterrupts using the handlers of other interrupts like external,\nsoftware, and timer interrupts.\n\nThis commit resolves lowRISC/ibex#290 reported by @udinator.", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex d61c3fddab..1ef0fac7f6 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -113,7 +113,7 @@ module ibex_controller (\n logic enter_debug_mode;\n logic handle_irq;\n \n- logic [4:0] mfip_id;\n+ logic [3:0] mfip_id;\n logic unused_csr_mtip;\n \n `ifndef SYNTHESIS\n@@ -164,22 +164,22 @@ module ibex_controller (\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+ 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@@ -360,7 +360,11 @@ module ibex_controller (\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+ // 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", "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\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 [3: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 (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 // \"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 = 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 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 // 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 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 // 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 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", "selected_doc_paths": ["doc/exception_interrupts.rst", "doc/debug.rst", "doc/cs_registers.rst", "doc/instruction_fetch.rst", "doc/integration.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 373, "lang": "sv", "rtl_files": ["rtl/ibex_tracer.sv"], "spec": "# Behavioral Design Specification: ibex_tracer\n\n## 1. Overview\n\nThe `ibex_tracer` is a simulation-only module that records each instruction executed by the Ibex core into a human-readable log file. It consumes execution information provided through the RISC‑V Formal Interface (RVFI) and produces a tab‑separated text trace that includes simulation time, cycle count, program counter (PC), the raw instruction, a disassembly similar to what `objdump` would produce, and the values of accessed registers and memory locations.\n\nThe tracer is **not synthesizable** and is intended solely for debugging and verification in simulation environments. It relies on SystemVerilog system functions (e.g., `$fopen`, `$fwrite`, `$time`, `$fclose`, `$value$plusargs`) that are available in standard simulators.\n\n---\n\n## 2. Input Interface\n\nThe module receives the following information for each retired instruction via the RVFI:\n\n- **Valid indication** – A single bit that signals when a new instruction has been executed and the remaining RVFI signals are stable.\n- **Instruction word** – The 32‑bit encoding of the executed instruction (or the lower 16 bits for a compressed instruction).\n- **Program counter** (PC) – The address of the instruction being executed (`pc_rdata`) and the next PC (`pc_wdata`).\n- **Register addresses and data** – The addresses and values of up to two source registers (`rs1`, `rs2`) and one destination register (`rd`), plus the write‑back value to `rd`.\n- **Memory access information** – For load and store instructions: the accessed memory address, byte‑level read/write masks, the data read from memory, and the data written to memory.\n- **Additional RVFI fields** – The module accepts `order`, `trap`, `halt`, `intr`, and `mode` signals but does not use them; they are present for future extensibility.\n\nAll input signals are synchronous to the rising edge of the provided clock. An asynchronous active‑low reset initializes the internal cycle counter and prepares the module for a new simulation run.\n\n---\n\n## 3. Output\n\nThe module produces a single output file per instantiation. The file contains a header line followed by one line per retired instruction (whenever `rvfi_valid` is asserted). The file is written during simulation and closed at the end of the simulation (`$finish` / `final` block).\n\n### 3.1 File Naming\n\nThe log file is named according to the following rule:\n\n```\n_.log\n```\n\n- `` defaults to `\"trace_core\"`.\n- The base name may be overridden by the simulation plusarg `+ibex_tracer_file_base=`.\n- `` is the 8‑digit hexadecimal representation of the `hart_id_i` input (the core’s Hart ID).\n\nIf the tracing facility is enabled in the core (e.g., via `ibex_core_tracing`), an implicit `ibex_tracer` instance is created. The file is opened on the first valid instruction and stays open until the simulation ends.\n\n### 3.2 Trace Line Format\n\nEach trace line consists of six tab‑separated fields:\n\n| Field | Description |\n|-------|-------------|\n| **Simulation time** | The current simulation time (from `$time`). |\n| **Cycle count** | The number of clock cycles elapsed since the last reset (or since simulation start if no reset is applied). |\n| **Program counter** (PC) | The address of the executed instruction (`pc_rdata`), displayed in hexadecimal. |\n| **Instruction** | The raw instruction word in hexadecimal. Compressed instructions (16‑bit) are shown as 4 hex digits; uncompressed (32‑bit) are shown as 8 hex digits. |\n| **Decoded instruction** | A human‑readable disassembly in a format similar to `objdump -Mnumeric -Mno-aliases -D`. See Section 3.3 for details. |\n| **Register and memory contents** | Values of accessed registers and memory locations. See Section 3.4. |\n\n### 3.3 Decoded Instruction Format\n\nThe tracer decodes every supported RISC‑V instruction (RV32I, RV32M, Zicsr, and the “C” compressed extension) and produces a string that mirrors the output of `objdump` with the options `-Mnumeric -Mno-aliases`. Key formatting rules:\n\n- Register names are numeric (e.g., `x1`, `x10`, `x31`). No ABI names are used.\n- Immediate values that are signed are shown as decimal numbers (e.g., `-3`). Unsigned values are shown in hexadecimal prefixed with `0x` (e.g., `0x100`).\n- Shift amounts are shown in hexadecimal.\n- CSR registers are shown with their standard symbolic names (e.g., `mstatus`, `mie`). If the CSR address is not recognized, it is shown as `0x
`.\n- Jump and branch instructions display the **absolute target address** (PC + immediate), unless the indirect jump (JALR) instruction is used, in which case the target is shown as an offset from a base register.\n- For fence instructions, the predecessor and successor sets are described using the letters `i`, `o`, `r`, `w`.\n\nIf the instruction does not decode to a recognized opcode, the decoded instruction field is set to `\"INVALID\"`.\n\nSpecial cases:\n- The `nop` instruction (ADDI with rd=x0, rs1=x0, immediate=0) is currently decoded as `addi x0,x0,0` (not as nop), to remain consistent with `objdump`.\n- The `ebreak` compressed instruction (`c.ebreak`) is recognized when the encoding matches `0x9002`.\n\n### 3.4 Register and Memory Contents Field\n\nThis field lists all registers and memory locations that are accessed by the instruction. Each item is separated by a space. The format distinguishes between reads and writes:\n\n- **Register read**: ` :0x` (e.g., ` x8:0x00008000`). \n The colon separates the register name from the value.\n- **Register write**: ` =0x` (e.g., ` x8=0x00007fff`). \n The equals sign indicates the value after the instruction is written.\n- **Memory access**: The address is shown as ` PA:0x
`. \n If a store was performed (`wmask != 0`), ` store:0x` is appended. \n If a load was performed (`rmask != 0`), ` load:0x` is appended.\n\nThe set of registers reported depends on the instruction type:\n\n- R‑type (register‑register): `rs1`, `rs2`, `rd` are shown.\n- I‑type (immediate): `rs1` and `rd` are shown.\n- U‑type (upper immediate): only `rd` is shown.\n- J‑type (jump): only `rd` is shown.\n- B‑type (branch): `rs1` and `rs2` are shown.\n- Load: `rs1`, `rd`, and memory access are shown.\n- Store: `rs1`, `rs2`, and memory access are shown.\n- CSR instructions: `rd` is shown; if the immediate form is used, `rs1` is included.\n- Compressed instructions follow analogous rules based on their operand usage.\n\n---\n\n## 4. Behavioral Requirements\n\n### 4.1 Triggering\n\nThe tracer must generate exactly one output line for every clock cycle in which `rvfi_valid` is asserted at the rising clock edge. No lines shall be written for cycles where `rvfi_valid` is de‑asserted.\n\n### 4.2 Timing of Values\n\nAll RVFI signals (`insn`, `pc_rdata`, `pc_wdata`, register data, memory data, etc.) are captured in the same cycle that `rvfi_valid` is high. The trace line reflects the state of those signals at that moment.\n\n### 4.3 Cycle Counter\n\nAn internal cycle counter increments on every rising clock edge after the reset is released. The counter is reset to zero when the asynchronous reset is active (low). The cycle count is reported in every trace line, starting from 0 after reset.\n\n### 4.4 Simulation Time\n\nThe current simulation time is obtained from the simulator’s `$time` system function and is reported in every trace line. The time unit is the simulator’s default time precision.\n\n### 4.5 File Management\n\n- The trace file shall be opened on the **first** `rvfi_valid` assertion after reset (or after simulation start if no explicit reset occurs).\n- The file shall be opened in write mode (`\"w\"`), which overwrites any previous file with the same name.\n- A header line shall be written immediately after opening the file:\n ```\n Time\tCycle\tPC\tInsn\tDecoded instruction\tRegister and memory contents\n ```\n- The file shall be closed during the simulation finalization phase (e.g., in a `final` block), ensuring all buffered data is flushed.\n- If the file cannot be opened (e.g., no file handle returned), an error message may be displayed but the tracer shall continue simulation without writing.\n\n### 4.6 Plusarg Support\n\nThe tracer must read the plusarg `+ibex_tracer_file_base=` at the time the first instruction is traced. If the plusarg is not provided, the default base name `\"trace_core\"` shall be used. The plusarg is read once; subsequent modifications during simulation have no effect.\n\n### 4.7 Reset Behavior\n\nWhen the asynchronous reset is active (low):\n\n- The cycle counter shall be reset to 0.\n- The tracer shall remain idle; no output is generated.\n- No file operations are performed.\n\nAfter reset de‑assertion, the tracer resumes normal operation on the next `rvfi_valid` assertion. The cycle counter starts counting from 0 again.\n\n### 4.8 No Side Effects on Core State\n\nThe tracer must not modify any core or system state. It is a passive observer. All output is written to external files.\n\n### 4.9 Unused RVFI Signals\n\nCertain RVFI signals (`order`, `trap`, `halt`, `intr`, `mode`) are accepted but shall be ignored by the tracer. Their values must not affect the trace output. These signals are present solely to maintain compatibility with the RVFI specification for future enhancements.\n\n---\n\n## 5. Supported Instruction Set Extensions\n\nThe tracer decodes the following RISC‑V instruction subsets:\n\n- **RV32I** base integer instructions (including `lui`, `auipc`, `jal`, `jalr`, branches, loads, stores, and ALU immediate/register operations).\n- **RV32M** standard multiplication and division extension (`mul`, `mulh`, `mulhsu`, `mulhu`, `div`, `divu`, `rem`, `remu`).\n- **Zicsr** CSR instructions (`csrrw`, `csrrs`, `csrrc`, `csrrwi`, `csrrsi`, `csrrci`).\n- **Zifencei** (`fence.i`).\n- **\"C\"** compressed instruction extension (16‑bit instructions, e.g., `c.addi`, `c.lw`, `c.sw`, `c.j`, `c.beqz`, etc.).\n- **System instructions** (`ecall`, `ebreak`, `mret`, `dret`, `wfi`).\n\nAny other opcode or illegal encoding results in the decoded instruction being `\"INVALID\"`. The tracer does **not** perform any functional simulation – it merely disassembles the raw instruction word. Consequently, it does not detect or report illegal instructions beyond marking them as `INVALID` in the trace output.\n\n---\n\n## 6. Limitations\n\n- The tracer is intended for **simulation only** and cannot be synthesized.\n- It relies on simulator‑specific system functions (`$fopen`, `$fwrite`, `$time`, `$value$plusargs`, `$fclose`). Portability across simulators is not guaranteed if a simulator lacks these functions.\n- The disassembly format aims to match `objdump` but may not be identical for every corner case (e.g., the `nop` instruction is decoded as `addi x0,x0,0` rather than as `nop`).\n- No support for RV64 or vector extensions.\n- The tracer does **not** filter out speculative instructions; it traces every instruction that the core reports as valid via `rvfi_valid`.", "commit_id": "2acb497d22a5da877a9c4350ef5693d0c767cc61", "timestamp": "2019-10-05T17:22:15+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "d8e4852f769c197330199a7356694baaef1b1a82", "pr_title": "Include rs1 and rd in trace of c.addi16sp", "pr_body": "New output looks like this:\n\n118 55 00000154 6121 c.addi16sp x2,64 x2:0x00000030 x2=0x00000070\n\nFixes #322", "issue_title": "Compressed tracer load/store issue", "issue_body": "Hi @raulbehl,\r\nI'm seeing some weird behavior with the tracer (from #262) involving long runs of compressed `lw` or `sw` instructions, below is the disassembled instruction sequence that is getting executed:\r\n![Screenshot from 2019-09-16 13-19-46](https://user-images.githubusercontent.com/16736281/64990442-afe7d680-d884-11e9-96a3-1c03d15861ca.png)\r\nAnd, below is what Ibex tracer is printing out for the exact same sequence:\r\n![Screenshot from 2019-09-16 13-20-56](https://user-images.githubusercontent.com/16736281/64990526-d3128600-d884-11e9-985a-0fb5a02ec7be.png)\r\n", "commit_message": "Include rs1 and rd in trace of c.addi16sp\n\nNew output looks like this:\n\n118 55 00000154 6121 c.addi16sp x2,64 x2:0x00000030 x2=0x00000070\n\nFixes #322", "fix_patch": "diff --git a/rtl/ibex_tracer.sv b/rtl/ibex_tracer.sv\nindex 370c66dee2..5d42905607 100644\n--- a/rtl/ibex_tracer.sv\n+++ b/rtl/ibex_tracer.sv\n@@ -488,6 +488,7 @@ module ibex_tracer (\n function void decode_ci_caddi16sp_insn(input string mnemonic);\n logic [9:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[4:3], rvfi_insn[5], rvfi_insn[2], rvfi_insn[6], 4'b0};\n+ data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n \n", "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 * Trace executed instructions in simulation\n *\n * This tracer takes execution information from the RISC-V Verification Interface (RVFI) and\n * produces a text file with a human-readable trace.\n *\n * All traced instructions are written to a log file. By default, the log file is named\n * trace_core_.log, with being the 8 digit hart ID of the core being traced.\n *\n * The file name base, defaulting to \"trace_core\" can be set using the \"ibex_tracer_file_base\"\n * plusarg passed to the simulation, e.g. \"+ibex_tracer_file_base=ibex_my_trace\". The exact syntax\n * of passing plusargs to a simulation depends on the simulator.\n *\n * The trace contains six columns, separated by tabs:\n * - The simulation time\n * - The clock cycle count since reset\n * - The program counter (PC)\n * - The instruction\n * - The decoded instruction in the same format as objdump, together with the accessed registers and\n * read/written memory values. Jumps and branches show the target address.\n * This column may be omitted if the instruction does not decode into a long form.\n * - Accessed registers and memory locations.\n *\n * Significant effort is spent to make the decoding produced by this tracer as similar as possible\n * to the one produced by objdump. This simplifies the correlation between the static program\n * information from the objdump-generated disassembly, and the runtime information from this tracer.\n */\nmodule ibex_tracer (\n input logic clk_i,\n input logic rst_ni,\n\n input logic [31:0] hart_id_i,\n\n // RVFI as described at https://github.com/SymbioticEDA/riscv-formal/blob/master/docs/rvfi.md\n // The standard interface does not have _i/_o suffixes. For consistency with the standard the\n // signals in this module don't have the suffixes either.\n input logic rvfi_valid,\n input logic [63:0] rvfi_order,\n input logic [31:0] rvfi_insn,\n input logic rvfi_trap,\n input logic rvfi_halt,\n input logic rvfi_intr,\n input logic [ 1:0] rvfi_mode,\n input logic [ 4:0] rvfi_rs1_addr,\n input logic [ 4:0] rvfi_rs2_addr,\n input logic [31:0] rvfi_rs1_rdata,\n input logic [31:0] rvfi_rs2_rdata,\n input logic [ 4:0] rvfi_rd_addr,\n input logic [31:0] rvfi_rd_wdata,\n input logic [31:0] rvfi_pc_rdata,\n input logic [31:0] rvfi_pc_wdata,\n input logic [31:0] rvfi_mem_addr,\n input logic [ 3:0] rvfi_mem_rmask,\n input logic [ 3:0] rvfi_mem_wmask,\n input logic [31:0] rvfi_mem_rdata,\n input logic [31:0] rvfi_mem_wdata\n);\n\n // These signals are part of RVFI, but not used in this module currently.\n // Keep them as part of the interface to change the tracer more easily in the future. Assigning\n // these signals to unused_* signals marks them explicitly as unused, an annotation picked up by\n // linters, including Verilator lint.\n logic [63:0] unused_rvfi_order = rvfi_order;\n logic unused_rvfi_trap = rvfi_trap;\n logic unused_rvfi_halt = rvfi_halt;\n logic unused_rvfi_intr = rvfi_intr;\n logic [ 1:0] unused_rvfi_mode = rvfi_mode;\n\n import ibex_pkg::*;\n import ibex_tracer_pkg::*;\n\n int file_handle;\n string file_name;\n\n int unsigned cycle;\n string decoded_str;\n logic insn_is_compressed;\n\n // Data items accessed during this instruction\n localparam RS1 = (1 << 0);\n localparam RS2 = (1 << 1);\n localparam RD = (1 << 2);\n localparam MEM = (1 << 3);\n logic [3:0] data_accessed;\n\n function void printbuffer_dumpline();\n string rvfi_insn_str;\n\n if (file_handle == 32'h0) begin\n string file_name_base = \"trace_core\";\n $value$plusargs(\"ibex_tracer_file_base=%s\", file_name_base);\n $sformat(file_name, \"%s_%h.log\", file_name_base, hart_id_i);\n\n $display(\"%m: Writing execution trace to %s\", file_name);\n file_handle = $fopen(file_name, \"w\");\n $fwrite(file_handle, \"Time\\tCycle\\tPC\\tInsn\\tDecoded instruction\\tRegister and memory contents\\n\");\n end\n\n // Write compressed instructions as four hex digits (16 bit word), and\n // uncompressed ones as 8 hex digits (32 bit words).\n if (insn_is_compressed) begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn[15:0]);\n end else begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn);\n end\n\n $fwrite(file_handle, \"%15t\\t%d\\t%h\\t%s\\t%s\\t\", $time, cycle, rvfi_pc_rdata, rvfi_insn_str, decoded_str);\n\n if ((data_accessed & RS1) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs1_addr), rvfi_rs1_rdata);\n end\n if ((data_accessed & RS2) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs2_addr), rvfi_rs2_rdata);\n end\n if ((data_accessed & RD) != 0) begin\n $fwrite(file_handle, \" %s=0x%08x\", reg_addr_to_str(rvfi_rd_addr), rvfi_rd_wdata);\n end\n if ((data_accessed & MEM) != 0) begin\n $fwrite(file_handle, \" PA:0x%08x\", rvfi_mem_addr);\n\n if (rvfi_mem_rmask != 4'b000) begin\n $fwrite(file_handle, \" store:0x%08x\", rvfi_mem_wdata);\n end\n if (rvfi_mem_wmask != 4'b000) begin\n $fwrite(file_handle, \" load:0x%08x\", rvfi_mem_rdata);\n end\n end\n\n $fwrite(file_handle, \"\\n\");\n endfunction\n\n\n // Format register address with \"x\" prefix, left-aligned to a fixed width of 3 characters.\n function string reg_addr_to_str(input logic [4:0] addr);\n if (addr < 10) begin\n return $sformatf(\" x%0d\", addr);\n end else begin\n return $sformatf(\"x%0d\", addr);\n end\n endfunction\n\n // Get a CSR name for a CSR address.\n function string get_csr_name(input logic [11:0] csr_addr);\n unique case (csr_addr)\n 12'd0: return \"ustatus\";\n 12'd4: return \"uie\";\n 12'd5: return \"utvec\";\n 12'd64: return \"uscratch\";\n 12'd65: return \"uepc\";\n 12'd66: return \"ucause\";\n 12'd67: return \"utval\";\n 12'd68: return \"uip\";\n 12'd1: return \"fflags\";\n 12'd2: return \"frm\";\n 12'd3: return \"fcsr\";\n 12'd3072: return \"cycle\";\n 12'd3073: return \"time\";\n 12'd3074: return \"instret\";\n 12'd3075: return \"hpmcounter3\";\n 12'd3076: return \"hpmcounter4\";\n 12'd3077: return \"hpmcounter5\";\n 12'd3078: return \"hpmcounter6\";\n 12'd3079: return \"hpmcounter7\";\n 12'd3080: return \"hpmcounter8\";\n 12'd3081: return \"hpmcounter9\";\n 12'd3082: return \"hpmcounter10\";\n 12'd3083: return \"hpmcounter11\";\n 12'd3084: return \"hpmcounter12\";\n 12'd3085: return \"hpmcounter13\";\n 12'd3086: return \"hpmcounter14\";\n 12'd3087: return \"hpmcounter15\";\n 12'd3088: return \"hpmcounter16\";\n 12'd3089: return \"hpmcounter17\";\n 12'd3090: return \"hpmcounter18\";\n 12'd3091: return \"hpmcounter19\";\n 12'd3092: return \"hpmcounter20\";\n 12'd3093: return \"hpmcounter21\";\n 12'd3094: return \"hpmcounter22\";\n 12'd3095: return \"hpmcounter23\";\n 12'd3096: return \"hpmcounter24\";\n 12'd3097: return \"hpmcounter25\";\n 12'd3098: return \"hpmcounter26\";\n 12'd3099: return \"hpmcounter27\";\n 12'd3100: return \"hpmcounter28\";\n 12'd3101: return \"hpmcounter29\";\n 12'd3102: return \"hpmcounter30\";\n 12'd3103: return \"hpmcounter31\";\n 12'd3200: return \"cycleh\";\n 12'd3201: return \"timeh\";\n 12'd3202: return \"instreth\";\n 12'd3203: return \"hpmcounter3h\";\n 12'd3204: return \"hpmcounter4h\";\n 12'd3205: return \"hpmcounter5h\";\n 12'd3206: return \"hpmcounter6h\";\n 12'd3207: return \"hpmcounter7h\";\n 12'd3208: return \"hpmcounter8h\";\n 12'd3209: return \"hpmcounter9h\";\n 12'd3210: return \"hpmcounter10h\";\n 12'd3211: return \"hpmcounter11h\";\n 12'd3212: return \"hpmcounter12h\";\n 12'd3213: return \"hpmcounter13h\";\n 12'd3214: return \"hpmcounter14h\";\n 12'd3215: return \"hpmcounter15h\";\n 12'd3216: return \"hpmcounter16h\";\n 12'd3217: return \"hpmcounter17h\";\n 12'd3218: return \"hpmcounter18h\";\n 12'd3219: return \"hpmcounter19h\";\n 12'd3220: return \"hpmcounter20h\";\n 12'd3221: return \"hpmcounter21h\";\n 12'd3222: return \"hpmcounter22h\";\n 12'd3223: return \"hpmcounter23h\";\n 12'd3224: return \"hpmcounter24h\";\n 12'd3225: return \"hpmcounter25h\";\n 12'd3226: return \"hpmcounter26h\";\n 12'd3227: return \"hpmcounter27h\";\n 12'd3228: return \"hpmcounter28h\";\n 12'd3229: return \"hpmcounter29h\";\n 12'd3230: return \"hpmcounter30h\";\n 12'd3231: return \"hpmcounter31h\";\n 12'd256: return \"sstatus\";\n 12'd258: return \"sedeleg\";\n 12'd259: return \"sideleg\";\n 12'd260: return \"sie\";\n 12'd261: return \"stvec\";\n 12'd262: return \"scounteren\";\n 12'd320: return \"sscratch\";\n 12'd321: return \"sepc\";\n 12'd322: return \"scause\";\n 12'd323: return \"stval\";\n 12'd324: return \"sip\";\n 12'd384: return \"satp\";\n 12'd3857: return \"mvendorid\";\n 12'd3858: return \"marchid\";\n 12'd3859: return \"mimpid\";\n 12'd3860: return \"mhartid\";\n 12'd768: return \"mstatus\";\n 12'd769: return \"misa\";\n 12'd770: return \"medeleg\";\n 12'd771: return \"mideleg\";\n 12'd772: return \"mie\";\n 12'd773: return \"mtvec\";\n 12'd774: return \"mcounteren\";\n 12'd832: return \"mscratch\";\n 12'd833: return \"mepc\";\n 12'd834: return \"mcause\";\n 12'd835: return \"mtval\";\n 12'd836: return \"mip\";\n 12'd928: return \"pmpcfg0\";\n 12'd929: return \"pmpcfg1\";\n 12'd930: return \"pmpcfg2\";\n 12'd931: return \"pmpcfg3\";\n 12'd944: return \"pmpaddr0\";\n 12'd945: return \"pmpaddr1\";\n 12'd946: return \"pmpaddr2\";\n 12'd947: return \"pmpaddr3\";\n 12'd948: return \"pmpaddr4\";\n 12'd949: return \"pmpaddr5\";\n 12'd950: return \"pmpaddr6\";\n 12'd951: return \"pmpaddr7\";\n 12'd952: return \"pmpaddr8\";\n 12'd953: return \"pmpaddr9\";\n 12'd954: return \"pmpaddr10\";\n 12'd955: return \"pmpaddr11\";\n 12'd956: return \"pmpaddr12\";\n 12'd957: return \"pmpaddr13\";\n 12'd958: return \"pmpaddr14\";\n 12'd959: return \"pmpaddr15\";\n 12'd2816: return \"mcycle\";\n 12'd2818: return \"minstret\";\n 12'd2819: return \"mhpmcounter3\";\n 12'd2820: return \"mhpmcounter4\";\n 12'd2821: return \"mhpmcounter5\";\n 12'd2822: return \"mhpmcounter6\";\n 12'd2823: return \"mhpmcounter7\";\n 12'd2824: return \"mhpmcounter8\";\n 12'd2825: return \"mhpmcounter9\";\n 12'd2826: return \"mhpmcounter10\";\n 12'd2827: return \"mhpmcounter11\";\n 12'd2828: return \"mhpmcounter12\";\n 12'd2829: return \"mhpmcounter13\";\n 12'd2830: return \"mhpmcounter14\";\n 12'd2831: return \"mhpmcounter15\";\n 12'd2832: return \"mhpmcounter16\";\n 12'd2833: return \"mhpmcounter17\";\n 12'd2834: return \"mhpmcounter18\";\n 12'd2835: return \"mhpmcounter19\";\n 12'd2836: return \"mhpmcounter20\";\n 12'd2837: return \"mhpmcounter21\";\n 12'd2838: return \"mhpmcounter22\";\n 12'd2839: return \"mhpmcounter23\";\n 12'd2840: return \"mhpmcounter24\";\n 12'd2841: return \"mhpmcounter25\";\n 12'd2842: return \"mhpmcounter26\";\n 12'd2843: return \"mhpmcounter27\";\n 12'd2844: return \"mhpmcounter28\";\n 12'd2845: return \"mhpmcounter29\";\n 12'd2846: return \"mhpmcounter30\";\n 12'd2847: return \"mhpmcounter31\";\n 12'd2944: return \"mcycleh\";\n 12'd2946: return \"minstreth\";\n 12'd2947: return \"mhpmcounter3h\";\n 12'd2948: return \"mhpmcounter4h\";\n 12'd2949: return \"mhpmcounter5h\";\n 12'd2950: return \"mhpmcounter6h\";\n 12'd2951: return \"mhpmcounter7h\";\n 12'd2952: return \"mhpmcounter8h\";\n 12'd2953: return \"mhpmcounter9h\";\n 12'd2954: return \"mhpmcounter10h\";\n 12'd2955: return \"mhpmcounter11h\";\n 12'd2956: return \"mhpmcounter12h\";\n 12'd2957: return \"mhpmcounter13h\";\n 12'd2958: return \"mhpmcounter14h\";\n 12'd2959: return \"mhpmcounter15h\";\n 12'd2960: return \"mhpmcounter16h\";\n 12'd2961: return \"mhpmcounter17h\";\n 12'd2962: return \"mhpmcounter18h\";\n 12'd2963: return \"mhpmcounter19h\";\n 12'd2964: return \"mhpmcounter20h\";\n 12'd2965: return \"mhpmcounter21h\";\n 12'd2966: return \"mhpmcounter22h\";\n 12'd2967: return \"mhpmcounter23h\";\n 12'd2968: return \"mhpmcounter24h\";\n 12'd2969: return \"mhpmcounter25h\";\n 12'd2970: return \"mhpmcounter26h\";\n 12'd2971: return \"mhpmcounter27h\";\n 12'd2972: return \"mhpmcounter28h\";\n 12'd2973: return \"mhpmcounter29h\";\n 12'd2974: return \"mhpmcounter30h\";\n 12'd2975: return \"mhpmcounter31h\";\n 12'd803: return \"mhpmevent3\";\n 12'd804: return \"mhpmevent4\";\n 12'd805: return \"mhpmevent5\";\n 12'd806: return \"mhpmevent6\";\n 12'd807: return \"mhpmevent7\";\n 12'd808: return \"mhpmevent8\";\n 12'd809: return \"mhpmevent9\";\n 12'd810: return \"mhpmevent10\";\n 12'd811: return \"mhpmevent11\";\n 12'd812: return \"mhpmevent12\";\n 12'd813: return \"mhpmevent13\";\n 12'd814: return \"mhpmevent14\";\n 12'd815: return \"mhpmevent15\";\n 12'd816: return \"mhpmevent16\";\n 12'd817: return \"mhpmevent17\";\n 12'd818: return \"mhpmevent18\";\n 12'd819: return \"mhpmevent19\";\n 12'd820: return \"mhpmevent20\";\n 12'd821: return \"mhpmevent21\";\n 12'd822: return \"mhpmevent22\";\n 12'd823: return \"mhpmevent23\";\n 12'd824: return \"mhpmevent24\";\n 12'd825: return \"mhpmevent25\";\n 12'd826: return \"mhpmevent26\";\n 12'd827: return \"mhpmevent27\";\n 12'd828: return \"mhpmevent28\";\n 12'd829: return \"mhpmevent29\";\n 12'd830: return \"mhpmevent30\";\n 12'd831: return \"mhpmevent31\";\n 12'd1952: return \"tselect\";\n 12'd1953: return \"tdata1\";\n 12'd1954: return \"tdata2\";\n 12'd1955: return \"tdata3\";\n 12'd1968: return \"dcsr\";\n 12'd1969: return \"dpc\";\n 12'd1970: return \"dscratch\";\n 12'd512: return \"hstatus\";\n 12'd514: return \"hedeleg\";\n 12'd515: return \"hideleg\";\n 12'd516: return \"hie\";\n 12'd517: return \"htvec\";\n 12'd576: return \"hscratch\";\n 12'd577: return \"hepc\";\n 12'd578: return \"hcause\";\n 12'd579: return \"hbadaddr\";\n 12'd580: return \"hip\";\n 12'd896: return \"mbase\";\n 12'd897: return \"mbound\";\n 12'd898: return \"mibase\";\n 12'd899: return \"mibound\";\n 12'd900: return \"mdbase\";\n 12'd901: return \"mdbound\";\n 12'd800: return \"mucounteren\";\n 12'd801: return \"mscounteren\";\n 12'd802: return \"mhcounteren\";\n default: return $sformatf(\"0x%x\", csr_addr);\n endcase\n endfunction\n\n function void decode_mnemonic(input string mnemonic);\n decoded_str = mnemonic;\n endfunction\n\n function void decode_r_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr, rvfi_rs2_addr);\n endfunction\n\n function void decode_i_insn(input string mnemonic);\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}));\n endfunction\n\n function void decode_i_shift_insn(input string mnemonic);\n // SLLI, SRLI, SRAI\n logic [4:0] shamt;\n shamt = {rvfi_insn[24:20]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,0x%0x\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr, shamt);\n endfunction\n\n function void decode_i_jalr_insn(input string mnemonic);\n // JALR\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function void decode_u_insn(input string mnemonic);\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, {rvfi_insn[31:12]});\n endfunction\n\n function void decode_j_insn(input string mnemonic);\n // JAL\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rd_addr, rvfi_pc_wdata);\n endfunction\n\n function void decode_b_insn(input string mnemonic);\n logic [31:0] branch_target;\n logic [31:0] imm;\n\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = $signed({ {19 {rvfi_insn[31]}}, rvfi_insn[31], rvfi_insn[7],\n rvfi_insn[30:25], rvfi_insn[11:8], 1'b0 });\n branch_target = rvfi_pc_rdata + imm;\n\n data_accessed = RS1 | RS2 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0x\", mnemonic, rvfi_rs1_addr, rvfi_rs2_addr, branch_target);\n endfunction\n\n function void decode_csr_insn(input string mnemonic);\n logic [11:0] csr;\n string csr_name;\n csr = rvfi_insn[31:20];\n csr_name = get_csr_name(csr);\n\n data_accessed = RD;\n\n if (!rvfi_insn[14]) begin\n data_accessed |= RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%s,x%0d\", mnemonic, rvfi_rd_addr, csr_name, rvfi_rs1_addr);\n end else begin\n decoded_str = $sformatf(\"%s\\tx%0d,%s,%0d\", mnemonic, rvfi_rd_addr, csr_name, { 27'b0, rvfi_insn[19:15]});\n end\n endfunction\n\n function void decode_cr_insn(input string mnemonic);\n if (rvfi_rs2_addr == 5'b0) begin\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d\", mnemonic, rvfi_rs1_addr);\n end else begin\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n end\n endfunction\n\n function void decode_ci_cli_insn(input string mnemonic);\n logic [5:0] imm;\n imm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n endfunction\n\n function void decode_ci_caddi_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function void decode_ci_caddi16sp_insn(input string mnemonic);\n logic [9:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[4:3], rvfi_insn[5], rvfi_insn[2], rvfi_insn[6], 4'b0};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function void decode_ci_clui_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, 20'($signed(nzimm)));\n endfunction\n\n function void decode_ci_cslli_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, shamt);\n endfunction\n\n function void decode_ciw_insn(input string mnemonic);\n // C.ADDI4SPN\n logic [9:0] nzuimm;\n nzuimm = {rvfi_insn[10:7], rvfi_insn[12:11], rvfi_insn[5], rvfi_insn[6], 2'b00};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x2,%0d\", mnemonic, rvfi_rd_addr, nzuimm);\n endfunction\n\n function void decode_cb_sr_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, shamt);\n endfunction\n\n function void decode_cb_insn(input string mnemonic);\n logic [7:0] imm;\n logic [31:0] jump_target;\n if (rvfi_insn[15:13] == 3'b110 || rvfi_insn[15:13] == 3'b111) begin\n // C.BNEZ and C.BEQZ\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = {rvfi_insn[12], rvfi_insn[6:5], rvfi_insn[2], rvfi_insn[11:10], rvfi_insn[4:3]};\n jump_target = rvfi_pc_rdata + 32'($signed({imm, 1'b0}));\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rs1_addr, jump_target);\n end else if (rvfi_insn[15:13] == 3'b100) begin\n // C.ANDI\n imm = {{2{rvfi_insn[12]}}, rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n end else begin\n imm = {rvfi_insn[12], rvfi_insn[6:2], 2'b00};\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, imm);\n end\n endfunction\n\n function void decode_cs_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n endfunction\n\n function void decode_cj_insn(input string mnemonic);\n decoded_str = $sformatf(\"%s\\t%0x\", mnemonic, rvfi_pc_wdata);\n endfunction\n\n function void decode_compressed_load_insn(input string mnemonic);\n logic [7:0] imm;\n\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.LW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.LWSP\n imm = {rvfi_insn[3:2], rvfi_insn[12], rvfi_insn[6:4], 2'b00};\n end\n data_accessed = RS1 | RD | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function void decode_compressed_store_insn(input string mnemonic);\n logic [7:0] imm;\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.SW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.SWSP\n imm = {rvfi_insn[8:7], rvfi_insn[12:9], 2'b00};\n end\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rs2_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function void decode_load_insn();\n string mnemonic;\n\n /*\n TODO: Gives wrong results in Verilator for unknown reasons. Debug what's going on.\n unique case (rvfi_insn[14:12])\n 3'b000: mnemonic = \"lb\";\n 3'b001: mnemonic = \"lh\";\n 3'b010: mnemonic = \"lw\";\n 3'b100: mnemonic = \"lbu\";\n 3'b101: mnemonic = \"lhu\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n */\n logic [2:0] size;\n size = rvfi_insn[14:12];\n if (size == 3'b000) begin\n mnemonic = \"lb\";\n end else if (size == 3'b001) begin\n mnemonic = \"lh\";\n end else if (size == 3'b010) begin\n mnemonic = \"lw\";\n end else if (size == 3'b100) begin\n mnemonic = \"lbu\";\n end else if (size == 3'b101) begin\n mnemonic = \"lhu\";\n end else begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n\n\n data_accessed = RD | RS1 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function void decode_store_insn();\n string mnemonic;\n\n unique case (rvfi_insn[13:12])\n 2'b00: mnemonic = \"sb\";\n 2'b01: mnemonic = \"sh\";\n 2'b10: mnemonic = \"sw\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n\n if (!rvfi_insn[14]) begin\n // regular store\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rs2_addr,\n $signed({ {20 {rvfi_insn[31]}}, rvfi_insn[31:25], rvfi_insn[11:7] }), rvfi_rs1_addr);\n end else begin\n decode_mnemonic(\"INVALID\");\n end\n endfunction\n\n function string get_fence_description(logic [3:0] bits);\n string desc = \"\";\n if (bits[3]) begin\n desc = {desc, \"i\"};\n end\n if (bits[2]) begin\n desc = {desc, \"o\"};\n end\n if (bits[1]) begin\n desc = {desc, \"r\"};\n end\n if (bits[0]) begin\n desc = {desc, \"w\"};\n end\n return desc;\n endfunction\n\n function void decode_fence();\n string predecessor;\n string successor;\n predecessor = get_fence_description(rvfi_insn[27:24]);\n successor = get_fence_description(rvfi_insn[23:20]);\n decoded_str = $sformatf(\"fence\\t%s,%s\", predecessor, successor);\n endfunction\n\n // cycle counter\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n cycle <= 0;\n end else begin\n cycle <= cycle + 1;\n end\n end\n\n // close output file for writing\n final begin\n if (file_handle != 32'h0) begin\n $fclose(file_handle);\n end\n end\n\n // log execution\n always_ff @(posedge clk_i) begin\n if (rvfi_valid) begin\n printbuffer_dumpline();\n end\n end\n\n always_comb begin\n decoded_str = \"\";\n data_accessed = 4'h0;\n insn_is_compressed = 0;\n\n // Check for compressed instructions\n if (rvfi_insn[1:0] != 2'b11) begin\n insn_is_compressed = 1;\n // Separate case to avoid overlapping decoding\n if (rvfi_insn[15:13] == 3'b100 && rvfi_insn[1:0] == 2'b10) begin\n if (rvfi_insn[12]) begin\n if (rvfi_insn[11:2] == 10'h0) begin\n decode_mnemonic(\"c.ebreak\");\n end else if (rvfi_insn[6:2] == 5'b0) begin\n decode_cr_insn(\"c.jalr\");\n end else begin\n decode_cr_insn(\"c.add\");\n end\n end else begin\n if (rvfi_insn[6:2] == 5'h0) begin\n decode_cr_insn(\"c.jr\");\n end else begin\n decode_cr_insn(\"c.mv\");\n end\n end\n end else begin\n unique casez (rvfi_insn[15:0])\n // C0 Opcodes\n INSN_CADDI4SPN: decode_ciw_insn(\"c.addi4spn\");\n INSN_CLW: decode_compressed_load_insn(\"c.lw\");\n INSN_CSW: decode_compressed_store_insn(\"c.sw\");\n // C1 Opcodes\n INSN_CADDI: decode_ci_caddi_insn(\"c.addi\");\n INSN_CJAL: decode_cj_insn(\"c.jal\");\n INSN_CJ: decode_cj_insn(\"c.j\");\n INSN_CLI: decode_ci_cli_insn(\"c.li\");\n INSN_CLUI: begin\n // These two instructions share opcode\n if (rvfi_insn[11:7] == 5'd2) begin\n decode_ci_caddi16sp_insn(\"c.addi16sp\");\n end else begin\n decode_ci_clui_insn(\"c.lui\");\n end\n end\n INSN_CSRLI: decode_cb_sr_insn(\"c.srli\");\n INSN_CSRAI: decode_cb_sr_insn(\"c.srai\");\n INSN_CANDI: decode_cb_insn(\"c.andi\");\n INSN_CSUB: decode_cs_insn(\"c.sub\");\n INSN_CXOR: decode_cs_insn(\"c.xor\");\n INSN_COR: decode_cs_insn(\"c.or\");\n INSN_CAND: decode_cs_insn(\"c.and\");\n INSN_CBEQZ: decode_cb_insn(\"c.beqz\");\n INSN_CBNEZ: decode_cb_insn(\"c.bnez\");\n // C2 Opcodes\n INSN_CSLLI: decode_ci_cslli_insn(\"c.slli\");\n INSN_CLWSP: decode_compressed_load_insn(\"c.lwsp\");\n INSN_SWSP: decode_compressed_store_insn(\"c.swsp\");\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end else begin\n unique casez (rvfi_insn)\n // Regular opcodes\n INSN_LUI: decode_u_insn(\"lui\");\n INSN_AUIPC: decode_u_insn(\"auipc\");\n INSN_JAL: decode_j_insn(\"jal\");\n INSN_JALR: decode_i_jalr_insn(\"jalr\");\n // BRANCH\n INSN_BEQ: decode_b_insn(\"beq\");\n INSN_BNE: decode_b_insn(\"bne\");\n INSN_BLT: decode_b_insn(\"blt\");\n INSN_BGE: decode_b_insn(\"bge\");\n INSN_BLTU: decode_b_insn(\"bltu\");\n INSN_BGEU: decode_b_insn(\"bgeu\");\n // OPIMM\n INSN_ADDI: begin\n if (rvfi_insn == 32'h00_00_00_13) begin\n // TODO: objdump doesn't decode this as nop currently, even though it would be helpful\n // Decide what to do here: diverge from objdump, or make the trace less readable to\n // users.\n //decode_mnemonic(\"nop\");\n decode_i_insn(\"addi\");\n end else begin\n decode_i_insn(\"addi\");\n end\n end\n INSN_SLTI: decode_i_insn(\"slti\");\n INSN_SLTIU: decode_i_insn(\"sltiu\");\n INSN_XORI: decode_i_insn(\"xori\");\n INSN_ORI: decode_i_insn(\"ori\");\n INSN_ANDI: decode_i_insn(\"andi\");\n INSN_SLLI: decode_i_shift_insn(\"slli\");\n INSN_SRLI: decode_i_shift_insn(\"srli\");\n INSN_SRAI: decode_i_shift_insn(\"srai\");\n // OP\n INSN_ADD: decode_r_insn(\"add\");\n INSN_SUB: decode_r_insn(\"sub\");\n INSN_SLL: decode_r_insn(\"sll\");\n INSN_SLT: decode_r_insn(\"slt\");\n INSN_SLTU: decode_r_insn(\"sltu\");\n INSN_XOR: decode_r_insn(\"xor\");\n INSN_SRL: decode_r_insn(\"srl\");\n INSN_SRA: decode_r_insn(\"sra\");\n INSN_OR: decode_r_insn(\"or\");\n INSN_AND: decode_r_insn(\"and\");\n // SYSTEM (CSR manipulation)\n INSN_CSRRW: decode_csr_insn(\"csrrw\");\n INSN_CSRRS: decode_csr_insn(\"csrrs\");\n INSN_CSRRC: decode_csr_insn(\"csrrc\");\n INSN_CSRRWI: decode_csr_insn(\"csrrwi\");\n INSN_CSRRSI: decode_csr_insn(\"csrrsi\");\n INSN_CSRRCI: decode_csr_insn(\"csrrci\");\n // SYSTEM (others)\n INSN_ECALL: decode_mnemonic(\"ecall\");\n INSN_EBREAK: decode_mnemonic(\"ebreak\");\n INSN_MRET: decode_mnemonic(\"mret\");\n INSN_DRET: decode_mnemonic(\"dret\");\n INSN_WFI: decode_mnemonic(\"wfi\");\n // RV32M\n INSN_PMUL: decode_r_insn(\"mul\");\n INSN_PMUH: decode_r_insn(\"mulh\");\n INSN_PMULHSU: decode_r_insn(\"mulhsu\");\n INSN_PMULHU: decode_r_insn(\"mulhu\");\n INSN_DIV: decode_r_insn(\"div\");\n INSN_DIVU: decode_r_insn(\"divu\");\n INSN_REM: decode_r_insn(\"rem\");\n INSN_REMU: decode_r_insn(\"remu\");\n // LOAD & STORE\n INSN_LOAD: decode_load_insn();\n INSN_STORE: decode_store_insn();\n // MISC-MEM\n INSN_FENCE: decode_fence();\n INSN_FENCEI: decode_mnemonic(\"fence.i\");\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end\n\nendmodule\n", "selected_doc_paths": ["doc/tracer.rst", "doc/rvfi.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 416, "lang": "sv", "rtl_files": ["rtl/ibex_tracer.sv"], "spec": "# Behavioral Design Specification: `ibex_tracer` Module\n\n## 1. Overview\n\nThe `ibex_tracer` module provides a simulation-only trace of instructions executed by a RISC‑V core. It observes execution information through a standard RISC‑V Formal Interface (RVFI) and writes a human‑readable log file containing detailed information about each instruction.\n\nThe purpose of this module is to assist in debugging, performance analysis, and verification by producing output that closely resembles the disassembly produced by standard tools (e.g., `objdump`), enriched with dynamic register and memory access data.\n\n## 2. Interface\n\nThe module operates in a simulation environment and receives the following information from the core under trace:\n\n- A **clock** and an **asynchronous active‑low reset**.\n- A **hart identifier** (a 32‑bit value) used to distinguish traces from multiple cores.\n- The **RVFI signals** as defined by the RISC‑V Formal Interface (RVFI), including:\n - Indication that a new instruction is being committed (`valid`).\n - The instruction word itself (`insn`).\n - The program counter values before and after execution (`pc_rdata`, `pc_wdata`).\n - Addresses and data of accessed registers (`rs1_addr`, `rs2_addr`, `rd_addr`; `rs1_rdata`, `rs2_rdata`, `rd_wdata`).\n - Memory access information (`mem_addr`, `mem_rmask`, `mem_wmask`, `mem_rdata`, `mem_wdata`).\n\nOther RVFI signals (order, trap, halt, interrupt, mode) are part of the interface but are not used for tracing in this module.\n\n## 3. Reset and Clocking\n\n- On **reset** the module shall reset an internal cycle counter to zero. No other persistent state exists in the tracer.\n- The module is clocked by the same clock used by the core. The internal cycle counter increments on every positive clock edge, regardless of whether an instruction is traced. This cycle count reflects the number of clock cycles elapsed since the last reset.\n- The module shall produce output only on the positive edge of the clock.\n\n## 4. Output File\n\n### 4.1 Default File Name\n\nThe module shall write all traced instructions to a plain‑text file. The default file name is:\n\n```\ntrace_core_.log\n```\n\nwhere `` is an 8‑digit zero‑padded hexadecimal representation of the 32‑bit hart identifier given at reset. \n*Example:* If `hart_id_i` is 32’h00000008, the file name is `trace_core_00000008.log`.\n\n### 4.2 Custom File Name via Plusarg\n\nThe module shall support a simulation plusarg `ibex_tracer_file_base`. If this plusarg is present, its value shall replace the base name `trace_core`. \n*Example:* Simulation is invoked with `+ibex_tracer_file_base=ibex_my_trace` → file becomes `ibex_my_trace_.log`.\n\nThe file shall be opened on the first instruction trace (when the first valid assertion occurs). If the file cannot be opened or the plusarg is set to an invalid value, the behavior is undefined; the simulation may abort or produce no output.\n\n### 4.3 File Header\n\nOn creation of the log file, the module shall write a single header line containing tab‑separated column titles:\n\n```\nTime\tCycle\tPC\tInsn\tDecoded instruction\tRegister and memory contents\n```\n\nAll subsequent lines follow this schema (see Section 7).\n\n### 4.4 File Closure\n\nWhen the simulation ends (i.e., when the simulation `final` block executes), the module shall close the log file, flushing any buffered data.\n\n## 5. Logging Conditions\n\nThe module shall write one trace line for every clock cycle in which the RVFI `valid` signal is asserted (high). No output shall be produced when `valid` is de‑asserted. The trace line reflects the information present at that same clock edge.\n\n## 6. Cycle Counter\n\nAn internal counter shall track the number of clock cycles since the last de‑assertion of reset. The counter:\n- Resets to 0 when reset is asserted.\n- Increments by 1 on every rising clock edge.\n\nThis counter shall be included in the trace output (column 2, “Cycle”).\n\n## 7. Trace Output Format\n\nEach trace line is a single line of text containing six tab‑separated fields. No additional whitespace or formatting is added between columns beyond tabs.\n\n| Column | Contents |\n|----------|------------------------------------------------------------------------------------------------|\n| **Time** | The current simulation time, printed as a decimal integer with a leading tab (width 15). |\n| **Cycle**| The cycle counter value (decimal integer). |\n| **PC** | The program counter before execution (`pc_rdata`), printed as hexadecimal without leading zeros. |\n| **Insn** | The instruction word, printed as hexadecimal. For compressed instructions (16‑bit) only the lower 16 bits are printed (4 hex digits); for uncompressed (32‑bit) the full word (8 hex digits) is printed. |\n| **Decoded instruction** | A disassembled description of the instruction (see Section 8). |\n| **Register and memory contents** | Dynamic information about register reads/writes and memory accesses (see Section 9). |\n\n## 8. Decoded Instruction\n\nThe module shall produce a human‑readable mnemonic and operand representation that closely matches the output of `objdump -Mnumeric -Mno-aliases -D`. The following rules apply:\n\n- **Register names** are printed in numeric form: `x0`, `x1`, …, `x31`.\n- **CSR names** are printed using the symbolic names defined by the RISC‑V privilege specification (e.g., `mstatus`, `mtvec`, `cycle`, etc.). If a CSR address is not recognized, the module shall print the raw hexadecimal address (formatted as `0x`).\n- **Immediate values** that are signed are printed as decimal integers. Unsigned immediates (e.g., shift amounts, upper immediates for `lui`/`auipc`) are printed in hexadecimal with the prefix `0x`.\n- **Jump and branch targets**: The module shall compute the absolute target address (PC + immediate) and print it as hexadecimal with the prefix `0x`. This target is not the value of `pc_wdata` for conditional branches; it is derived from the immediate field and the original PC.\n- **Memory instructions** (`lb`, `lh`, `lw`, `lbu`, `lhu`, `sb`, `sh`, `sw`) are printed with the destination (for loads) or source register, the immediate offset, and the base register, e.g., `lw x5,8(x10)`.\n- **Special instructions**:\n - `ecall`, `ebreak`, `mret`, `dret`, `wfi`, `fence.i` are printed with their mnemonic only.\n - `fence` is printed as `fence\t,` where predecessor and successor are strings composed of the letters `i`, `o`, `r`, `w` according to the bits in the instruction.\n- **Compressed instructions** (16‑bit, detected when the two least significant bits of the instruction are not `2'b11`) are decoded into their 32‑bit equivalent mnemonics pre‑fixed with `c.` (e.g., `c.addi`, `c.lw`, `c.swsp`). The operand format matches the compressed instruction encoding.\n- **Invalid instructions**: If the instruction word does not match any known opcode (including reserved encodings), the module shall print the literal `INVALID` as the decoded instruction and no register/memory access information.\n\n## 9. Register and Memory Access Tracking\n\nFor each traced instruction, the module shall annotate which registers were read, which register was written, and whether memory was accessed. This information is printed in the sixth column, separated by spaces, in the following order:\n\n- **Read registers** (any of `rs1` or `rs2` that are actually accessed by the instruction): format `:0x` where `` is the numeric register name (e.g., `x5:0x00000001`). The register name is left‑aligned to a fixed width of 3 characters (including the leading `x` and a space if the number is a single digit, e.g., ` x5`).\n- **Written register** (if the destination register is `x0`, it is still listed if the instruction logically writes it, though the value is zero): format `=0x`.\n- **Memory access**: The module shall print the physical address `PA:0x`, followed by any store data (`store:0x`) if the write enable mask is non‑zero, and any load data (`load:0x`) if the read enable mask is non‑zero. Both store and load may be present on the same instruction (e.g., for atomic operations, though Ibex does not implement them; in future extensions both may appear).\n\nThe module shall decide which registers are accessed based on the instruction type and its operands, not solely on the presence of non‑zero register addresses. For example:\n- For `add x1,x2,x3`, all three registers are accessed: `x2` and `x3` are read, `x1` is written.\n- For `li x5,0` (pseudo‑op, but decoded as `c.li` or `addi`), only the destination `x5` is written (no register read).\n- For `jal x1,label`, only `x1` is written (the PC is not considered a register access).\n- For `beqz x1,label` (compressed `c.beqz`), only `x1` is read.\n- For memory operations (`lw`, `sw`), the base register (`rs1`) is always read, and `rs2` is read for stores.\n\n## 10. Decoding of CSR Instructions\n\nFor `CSRRW`, `CSRRS`, `CSRRC` and their immediate variants (`CSRRWI`, `CSRRSI`, `CSRRCI`), the CSR address field is decoded to a symbolic name as described in Section 8. The module shall use the standard CSR names from the RISC‑V privileged specification (version 1.11) for all implemented CSRs. Unrecognized addresses shall be printed as `0x`.\n\n## 11. Simulation End\n\nUpon simulation termination (e.g., `$finish`), the module shall close the log file. If no instruction was ever traced (file never opened), no file shall be created and no error shall occur.\n\n## 12. Conditions Not Covered\n\n- The module is purely a simulation aid; it has no functional role in the core’s operation and shall not affect the core’s behavior.\n- The module does not support tracing of exceptions, interrupts, or trap handling (RVFI trap and halt signals are present but ignored).\n- The module does not enforce any ordering of instructions; it simply logs them as they appear on the RVFI interface.\n- The module assumes that the `valid` signal is asserted for exactly one clock cycle per committed instruction.\n- The module does not verify the integrity of the RVFI data; it assumes the core provides consistent information.\n\n## 13. File Format Summary\n\nA complete trace line for a store instruction (e.g., `sw x2,12(x1)`) might look like:\n\n```\nTime: 200 Cycle: 25 PC: 0000015c Insn: c622 Decoded: c.swsp x8,12(x2) Reg/Mem: x2:0x00002000 x8:0x00000000 PA:0x0000200c store:0x00000000 load:0xffffffff\n```\n\n(Line breaks added for readability; actual output is a single line with tabs.)", "commit_id": "8e40f65582e7925d2cd50021256005391ad07460", "timestamp": "2019-10-23T17:30:12+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "023b7b6856269296a481c0f8e7c21575878b4fe1", "pr_title": "[RTL/Tracer] Fix compressed jump RD write", "pr_body": "Fixes #414.", "issue_title": "[tracer] C.JALR does not display write to x1", "issue_body": "Hi all,\r\n![Screenshot from 2019-10-21 11-27-57](https://user-images.githubusercontent.com/16736281/67232342-056c5180-f3f6-11e9-8789-9d6f85472320.png)\r\nAs shown from this trace, even though `c.jalr` instruction will write `PC+2` to `x1`, this write is not reflected in the tracer log.\r\nBest,\r\nUdi", "commit_message": "[RTL/Tracer] Fix compressed jump RD write", "fix_patch": "diff --git a/rtl/ibex_tracer.sv b/rtl/ibex_tracer.sv\nindex deba8e549f..40eaa1e037 100644\n--- a/rtl/ibex_tracer.sv\n+++ b/rtl/ibex_tracer.sv\n@@ -463,7 +463,13 @@ module ibex_tracer (\n \n function void decode_cr_insn(input string mnemonic);\n if (rvfi_rs2_addr == 5'b0) begin\n- data_accessed = RS1;\n+ if (rvfi_insn[12] == 1'b1) begin\n+ // C.JALR\n+ data_accessed = RS1 | RD;\n+ end else begin\n+ // C.JR\n+ data_accessed = RS1;\n+ end\n decoded_str = $sformatf(\"%s\\tx%0d\", mnemonic, rvfi_rs1_addr);\n end else begin\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n@@ -549,6 +555,10 @@ module ibex_tracer (\n endfunction\n \n function void decode_cj_insn(input string mnemonic);\n+ if (rvfi_insn[15:13] == 3'b001) begin\n+ // C.JAL\n+ data_accessed = RD;\n+ end\n decoded_str = $sformatf(\"%s\\t%0x\", mnemonic, rvfi_pc_wdata);\n endfunction\n \n", "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 * Trace executed instructions in simulation\n *\n * This tracer takes execution information from the RISC-V Verification Interface (RVFI) and\n * produces a text file with a human-readable trace.\n *\n * All traced instructions are written to a log file. By default, the log file is named\n * trace_core_.log, with being the 8 digit hart ID of the core being traced.\n *\n * The file name base, defaulting to \"trace_core\" can be set using the \"ibex_tracer_file_base\"\n * plusarg passed to the simulation, e.g. \"+ibex_tracer_file_base=ibex_my_trace\". The exact syntax\n * of passing plusargs to a simulation depends on the simulator.\n *\n * The trace contains six columns, separated by tabs:\n * - The simulation time\n * - The clock cycle count since reset\n * - The program counter (PC)\n * - The instruction\n * - The decoded instruction in the same format as objdump, together with the accessed registers and\n * read/written memory values. Jumps and branches show the target address.\n * This column may be omitted if the instruction does not decode into a long form.\n * - Accessed registers and memory locations.\n *\n * Significant effort is spent to make the decoding produced by this tracer as similar as possible\n * to the one produced by objdump. This simplifies the correlation between the static program\n * information from the objdump-generated disassembly, and the runtime information from this tracer.\n */\nmodule ibex_tracer (\n input logic clk_i,\n input logic rst_ni,\n\n input logic [31:0] hart_id_i,\n\n // RVFI as described at https://github.com/SymbioticEDA/riscv-formal/blob/master/docs/rvfi.md\n // The standard interface does not have _i/_o suffixes. For consistency with the standard the\n // signals in this module don't have the suffixes either.\n input logic rvfi_valid,\n input logic [63:0] rvfi_order,\n input logic [31:0] rvfi_insn,\n input logic rvfi_trap,\n input logic rvfi_halt,\n input logic rvfi_intr,\n input logic [ 1:0] rvfi_mode,\n input logic [ 4:0] rvfi_rs1_addr,\n input logic [ 4:0] rvfi_rs2_addr,\n input logic [31:0] rvfi_rs1_rdata,\n input logic [31:0] rvfi_rs2_rdata,\n input logic [ 4:0] rvfi_rd_addr,\n input logic [31:0] rvfi_rd_wdata,\n input logic [31:0] rvfi_pc_rdata,\n input logic [31:0] rvfi_pc_wdata,\n input logic [31:0] rvfi_mem_addr,\n input logic [ 3:0] rvfi_mem_rmask,\n input logic [ 3:0] rvfi_mem_wmask,\n input logic [31:0] rvfi_mem_rdata,\n input logic [31:0] rvfi_mem_wdata\n);\n\n // These signals are part of RVFI, but not used in this module currently.\n // Keep them as part of the interface to change the tracer more easily in the future. Assigning\n // these signals to unused_* signals marks them explicitly as unused, an annotation picked up by\n // linters, including Verilator lint.\n logic [63:0] unused_rvfi_order = rvfi_order;\n logic unused_rvfi_trap = rvfi_trap;\n logic unused_rvfi_halt = rvfi_halt;\n logic unused_rvfi_intr = rvfi_intr;\n logic [ 1:0] unused_rvfi_mode = rvfi_mode;\n\n import ibex_pkg::*;\n import ibex_tracer_pkg::*;\n\n int file_handle;\n string file_name;\n\n int unsigned cycle;\n string decoded_str;\n logic insn_is_compressed;\n\n // Data items accessed during this instruction\n localparam RS1 = (1 << 0);\n localparam RS2 = (1 << 1);\n localparam RD = (1 << 2);\n localparam MEM = (1 << 3);\n logic [3:0] data_accessed;\n\n function void printbuffer_dumpline();\n string rvfi_insn_str;\n\n if (file_handle == 32'h0) begin\n string file_name_base = \"trace_core\";\n $value$plusargs(\"ibex_tracer_file_base=%s\", file_name_base);\n $sformat(file_name, \"%s_%h.log\", file_name_base, hart_id_i);\n\n $display(\"%m: Writing execution trace to %s\", file_name);\n file_handle = $fopen(file_name, \"w\");\n $fwrite(file_handle, \"Time\\tCycle\\tPC\\tInsn\\tDecoded instruction\\tRegister and memory contents\\n\");\n end\n\n // Write compressed instructions as four hex digits (16 bit word), and\n // uncompressed ones as 8 hex digits (32 bit words).\n if (insn_is_compressed) begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn[15:0]);\n end else begin\n rvfi_insn_str = $sformatf(\"%h\", rvfi_insn);\n end\n\n $fwrite(file_handle, \"%15t\\t%d\\t%h\\t%s\\t%s\\t\", $time, cycle, rvfi_pc_rdata, rvfi_insn_str, decoded_str);\n\n if ((data_accessed & RS1) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs1_addr), rvfi_rs1_rdata);\n end\n if ((data_accessed & RS2) != 0) begin\n $fwrite(file_handle, \" %s:0x%08x\", reg_addr_to_str(rvfi_rs2_addr), rvfi_rs2_rdata);\n end\n if ((data_accessed & RD) != 0) begin\n $fwrite(file_handle, \" %s=0x%08x\", reg_addr_to_str(rvfi_rd_addr), rvfi_rd_wdata);\n end\n if ((data_accessed & MEM) != 0) begin\n $fwrite(file_handle, \" PA:0x%08x\", rvfi_mem_addr);\n\n if (rvfi_mem_rmask != 4'b000) begin\n $fwrite(file_handle, \" store:0x%08x\", rvfi_mem_wdata);\n end\n if (rvfi_mem_wmask != 4'b000) begin\n $fwrite(file_handle, \" load:0x%08x\", rvfi_mem_rdata);\n end\n end\n\n $fwrite(file_handle, \"\\n\");\n endfunction\n\n\n // Format register address with \"x\" prefix, left-aligned to a fixed width of 3 characters.\n function string reg_addr_to_str(input logic [4:0] addr);\n if (addr < 10) begin\n return $sformatf(\" x%0d\", addr);\n end else begin\n return $sformatf(\"x%0d\", addr);\n end\n endfunction\n\n // Get a CSR name for a CSR address.\n function string get_csr_name(input logic [11:0] csr_addr);\n unique case (csr_addr)\n 12'd0: return \"ustatus\";\n 12'd4: return \"uie\";\n 12'd5: return \"utvec\";\n 12'd64: return \"uscratch\";\n 12'd65: return \"uepc\";\n 12'd66: return \"ucause\";\n 12'd67: return \"utval\";\n 12'd68: return \"uip\";\n 12'd1: return \"fflags\";\n 12'd2: return \"frm\";\n 12'd3: return \"fcsr\";\n 12'd3072: return \"cycle\";\n 12'd3073: return \"time\";\n 12'd3074: return \"instret\";\n 12'd3075: return \"hpmcounter3\";\n 12'd3076: return \"hpmcounter4\";\n 12'd3077: return \"hpmcounter5\";\n 12'd3078: return \"hpmcounter6\";\n 12'd3079: return \"hpmcounter7\";\n 12'd3080: return \"hpmcounter8\";\n 12'd3081: return \"hpmcounter9\";\n 12'd3082: return \"hpmcounter10\";\n 12'd3083: return \"hpmcounter11\";\n 12'd3084: return \"hpmcounter12\";\n 12'd3085: return \"hpmcounter13\";\n 12'd3086: return \"hpmcounter14\";\n 12'd3087: return \"hpmcounter15\";\n 12'd3088: return \"hpmcounter16\";\n 12'd3089: return \"hpmcounter17\";\n 12'd3090: return \"hpmcounter18\";\n 12'd3091: return \"hpmcounter19\";\n 12'd3092: return \"hpmcounter20\";\n 12'd3093: return \"hpmcounter21\";\n 12'd3094: return \"hpmcounter22\";\n 12'd3095: return \"hpmcounter23\";\n 12'd3096: return \"hpmcounter24\";\n 12'd3097: return \"hpmcounter25\";\n 12'd3098: return \"hpmcounter26\";\n 12'd3099: return \"hpmcounter27\";\n 12'd3100: return \"hpmcounter28\";\n 12'd3101: return \"hpmcounter29\";\n 12'd3102: return \"hpmcounter30\";\n 12'd3103: return \"hpmcounter31\";\n 12'd3200: return \"cycleh\";\n 12'd3201: return \"timeh\";\n 12'd3202: return \"instreth\";\n 12'd3203: return \"hpmcounter3h\";\n 12'd3204: return \"hpmcounter4h\";\n 12'd3205: return \"hpmcounter5h\";\n 12'd3206: return \"hpmcounter6h\";\n 12'd3207: return \"hpmcounter7h\";\n 12'd3208: return \"hpmcounter8h\";\n 12'd3209: return \"hpmcounter9h\";\n 12'd3210: return \"hpmcounter10h\";\n 12'd3211: return \"hpmcounter11h\";\n 12'd3212: return \"hpmcounter12h\";\n 12'd3213: return \"hpmcounter13h\";\n 12'd3214: return \"hpmcounter14h\";\n 12'd3215: return \"hpmcounter15h\";\n 12'd3216: return \"hpmcounter16h\";\n 12'd3217: return \"hpmcounter17h\";\n 12'd3218: return \"hpmcounter18h\";\n 12'd3219: return \"hpmcounter19h\";\n 12'd3220: return \"hpmcounter20h\";\n 12'd3221: return \"hpmcounter21h\";\n 12'd3222: return \"hpmcounter22h\";\n 12'd3223: return \"hpmcounter23h\";\n 12'd3224: return \"hpmcounter24h\";\n 12'd3225: return \"hpmcounter25h\";\n 12'd3226: return \"hpmcounter26h\";\n 12'd3227: return \"hpmcounter27h\";\n 12'd3228: return \"hpmcounter28h\";\n 12'd3229: return \"hpmcounter29h\";\n 12'd3230: return \"hpmcounter30h\";\n 12'd3231: return \"hpmcounter31h\";\n 12'd256: return \"sstatus\";\n 12'd258: return \"sedeleg\";\n 12'd259: return \"sideleg\";\n 12'd260: return \"sie\";\n 12'd261: return \"stvec\";\n 12'd262: return \"scounteren\";\n 12'd320: return \"sscratch\";\n 12'd321: return \"sepc\";\n 12'd322: return \"scause\";\n 12'd323: return \"stval\";\n 12'd324: return \"sip\";\n 12'd384: return \"satp\";\n 12'd3857: return \"mvendorid\";\n 12'd3858: return \"marchid\";\n 12'd3859: return \"mimpid\";\n 12'd3860: return \"mhartid\";\n 12'd768: return \"mstatus\";\n 12'd769: return \"misa\";\n 12'd770: return \"medeleg\";\n 12'd771: return \"mideleg\";\n 12'd772: return \"mie\";\n 12'd773: return \"mtvec\";\n 12'd774: return \"mcounteren\";\n 12'd832: return \"mscratch\";\n 12'd833: return \"mepc\";\n 12'd834: return \"mcause\";\n 12'd835: return \"mtval\";\n 12'd836: return \"mip\";\n 12'd928: return \"pmpcfg0\";\n 12'd929: return \"pmpcfg1\";\n 12'd930: return \"pmpcfg2\";\n 12'd931: return \"pmpcfg3\";\n 12'd944: return \"pmpaddr0\";\n 12'd945: return \"pmpaddr1\";\n 12'd946: return \"pmpaddr2\";\n 12'd947: return \"pmpaddr3\";\n 12'd948: return \"pmpaddr4\";\n 12'd949: return \"pmpaddr5\";\n 12'd950: return \"pmpaddr6\";\n 12'd951: return \"pmpaddr7\";\n 12'd952: return \"pmpaddr8\";\n 12'd953: return \"pmpaddr9\";\n 12'd954: return \"pmpaddr10\";\n 12'd955: return \"pmpaddr11\";\n 12'd956: return \"pmpaddr12\";\n 12'd957: return \"pmpaddr13\";\n 12'd958: return \"pmpaddr14\";\n 12'd959: return \"pmpaddr15\";\n 12'd2816: return \"mcycle\";\n 12'd2818: return \"minstret\";\n 12'd2819: return \"mhpmcounter3\";\n 12'd2820: return \"mhpmcounter4\";\n 12'd2821: return \"mhpmcounter5\";\n 12'd2822: return \"mhpmcounter6\";\n 12'd2823: return \"mhpmcounter7\";\n 12'd2824: return \"mhpmcounter8\";\n 12'd2825: return \"mhpmcounter9\";\n 12'd2826: return \"mhpmcounter10\";\n 12'd2827: return \"mhpmcounter11\";\n 12'd2828: return \"mhpmcounter12\";\n 12'd2829: return \"mhpmcounter13\";\n 12'd2830: return \"mhpmcounter14\";\n 12'd2831: return \"mhpmcounter15\";\n 12'd2832: return \"mhpmcounter16\";\n 12'd2833: return \"mhpmcounter17\";\n 12'd2834: return \"mhpmcounter18\";\n 12'd2835: return \"mhpmcounter19\";\n 12'd2836: return \"mhpmcounter20\";\n 12'd2837: return \"mhpmcounter21\";\n 12'd2838: return \"mhpmcounter22\";\n 12'd2839: return \"mhpmcounter23\";\n 12'd2840: return \"mhpmcounter24\";\n 12'd2841: return \"mhpmcounter25\";\n 12'd2842: return \"mhpmcounter26\";\n 12'd2843: return \"mhpmcounter27\";\n 12'd2844: return \"mhpmcounter28\";\n 12'd2845: return \"mhpmcounter29\";\n 12'd2846: return \"mhpmcounter30\";\n 12'd2847: return \"mhpmcounter31\";\n 12'd2944: return \"mcycleh\";\n 12'd2946: return \"minstreth\";\n 12'd2947: return \"mhpmcounter3h\";\n 12'd2948: return \"mhpmcounter4h\";\n 12'd2949: return \"mhpmcounter5h\";\n 12'd2950: return \"mhpmcounter6h\";\n 12'd2951: return \"mhpmcounter7h\";\n 12'd2952: return \"mhpmcounter8h\";\n 12'd2953: return \"mhpmcounter9h\";\n 12'd2954: return \"mhpmcounter10h\";\n 12'd2955: return \"mhpmcounter11h\";\n 12'd2956: return \"mhpmcounter12h\";\n 12'd2957: return \"mhpmcounter13h\";\n 12'd2958: return \"mhpmcounter14h\";\n 12'd2959: return \"mhpmcounter15h\";\n 12'd2960: return \"mhpmcounter16h\";\n 12'd2961: return \"mhpmcounter17h\";\n 12'd2962: return \"mhpmcounter18h\";\n 12'd2963: return \"mhpmcounter19h\";\n 12'd2964: return \"mhpmcounter20h\";\n 12'd2965: return \"mhpmcounter21h\";\n 12'd2966: return \"mhpmcounter22h\";\n 12'd2967: return \"mhpmcounter23h\";\n 12'd2968: return \"mhpmcounter24h\";\n 12'd2969: return \"mhpmcounter25h\";\n 12'd2970: return \"mhpmcounter26h\";\n 12'd2971: return \"mhpmcounter27h\";\n 12'd2972: return \"mhpmcounter28h\";\n 12'd2973: return \"mhpmcounter29h\";\n 12'd2974: return \"mhpmcounter30h\";\n 12'd2975: return \"mhpmcounter31h\";\n 12'd803: return \"mhpmevent3\";\n 12'd804: return \"mhpmevent4\";\n 12'd805: return \"mhpmevent5\";\n 12'd806: return \"mhpmevent6\";\n 12'd807: return \"mhpmevent7\";\n 12'd808: return \"mhpmevent8\";\n 12'd809: return \"mhpmevent9\";\n 12'd810: return \"mhpmevent10\";\n 12'd811: return \"mhpmevent11\";\n 12'd812: return \"mhpmevent12\";\n 12'd813: return \"mhpmevent13\";\n 12'd814: return \"mhpmevent14\";\n 12'd815: return \"mhpmevent15\";\n 12'd816: return \"mhpmevent16\";\n 12'd817: return \"mhpmevent17\";\n 12'd818: return \"mhpmevent18\";\n 12'd819: return \"mhpmevent19\";\n 12'd820: return \"mhpmevent20\";\n 12'd821: return \"mhpmevent21\";\n 12'd822: return \"mhpmevent22\";\n 12'd823: return \"mhpmevent23\";\n 12'd824: return \"mhpmevent24\";\n 12'd825: return \"mhpmevent25\";\n 12'd826: return \"mhpmevent26\";\n 12'd827: return \"mhpmevent27\";\n 12'd828: return \"mhpmevent28\";\n 12'd829: return \"mhpmevent29\";\n 12'd830: return \"mhpmevent30\";\n 12'd831: return \"mhpmevent31\";\n 12'd1952: return \"tselect\";\n 12'd1953: return \"tdata1\";\n 12'd1954: return \"tdata2\";\n 12'd1955: return \"tdata3\";\n 12'd1968: return \"dcsr\";\n 12'd1969: return \"dpc\";\n 12'd1970: return \"dscratch\";\n 12'd512: return \"hstatus\";\n 12'd514: return \"hedeleg\";\n 12'd515: return \"hideleg\";\n 12'd516: return \"hie\";\n 12'd517: return \"htvec\";\n 12'd576: return \"hscratch\";\n 12'd577: return \"hepc\";\n 12'd578: return \"hcause\";\n 12'd579: return \"hbadaddr\";\n 12'd580: return \"hip\";\n 12'd896: return \"mbase\";\n 12'd897: return \"mbound\";\n 12'd898: return \"mibase\";\n 12'd899: return \"mibound\";\n 12'd900: return \"mdbase\";\n 12'd901: return \"mdbound\";\n 12'd800: return \"mucounteren\";\n 12'd801: return \"mscounteren\";\n 12'd802: return \"mhcounteren\";\n default: return $sformatf(\"0x%x\", csr_addr);\n endcase\n endfunction\n\n function void decode_mnemonic(input string mnemonic);\n decoded_str = mnemonic;\n endfunction\n\n function void decode_r_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr, rvfi_rs2_addr);\n endfunction\n\n function void decode_i_insn(input string mnemonic);\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0d\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}));\n endfunction\n\n function void decode_i_shift_insn(input string mnemonic);\n // SLLI, SRLI, SRAI\n logic [4:0] shamt;\n shamt = {rvfi_insn[24:20]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,0x%0x\", mnemonic, rvfi_rd_addr, rvfi_rs1_addr, shamt);\n endfunction\n\n function void decode_i_jalr_insn(input string mnemonic);\n // JALR\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function void decode_u_insn(input string mnemonic);\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, {rvfi_insn[31:12]});\n endfunction\n\n function void decode_j_insn(input string mnemonic);\n // JAL\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rd_addr, rvfi_pc_wdata);\n endfunction\n\n function void decode_b_insn(input string mnemonic);\n logic [31:0] branch_target;\n logic [31:0] imm;\n\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = $signed({ {19 {rvfi_insn[31]}}, rvfi_insn[31], rvfi_insn[7],\n rvfi_insn[30:25], rvfi_insn[11:8], 1'b0 });\n branch_target = rvfi_pc_rdata + imm;\n\n data_accessed = RS1 | RS2 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d,%0x\", mnemonic, rvfi_rs1_addr, rvfi_rs2_addr, branch_target);\n endfunction\n\n function void decode_csr_insn(input string mnemonic);\n logic [11:0] csr;\n string csr_name;\n csr = rvfi_insn[31:20];\n csr_name = get_csr_name(csr);\n\n data_accessed = RD;\n\n if (!rvfi_insn[14]) begin\n data_accessed |= RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%s,x%0d\", mnemonic, rvfi_rd_addr, csr_name, rvfi_rs1_addr);\n end else begin\n decoded_str = $sformatf(\"%s\\tx%0d,%s,%0d\", mnemonic, rvfi_rd_addr, csr_name, { 27'b0, rvfi_insn[19:15]});\n end\n endfunction\n\n function void decode_cr_insn(input string mnemonic);\n if (rvfi_rs2_addr == 5'b0) begin\n if (rvfi_insn[12] == 1'b1) begin\n // C.JALR\n data_accessed = RS1 | RD;\n end else begin\n // C.JR\n data_accessed = RS1;\n end\n decoded_str = $sformatf(\"%s\\tx%0d\", mnemonic, rvfi_rs1_addr);\n end else begin\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n end\n endfunction\n\n function void decode_ci_cli_insn(input string mnemonic);\n logic [5:0] imm;\n imm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n endfunction\n\n function void decode_ci_caddi_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function void decode_ci_caddi16sp_insn(input string mnemonic);\n logic [9:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[4:3], rvfi_insn[5], rvfi_insn[2], rvfi_insn[6], 4'b0};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(nzimm));\n endfunction\n\n function void decode_ci_clui_insn(input string mnemonic);\n logic [5:0] nzimm;\n nzimm = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, 20'($signed(nzimm)));\n endfunction\n\n function void decode_ci_cslli_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rd_addr, shamt);\n endfunction\n\n function void decode_ciw_insn(input string mnemonic);\n // C.ADDI4SPN\n logic [9:0] nzuimm;\n nzuimm = {rvfi_insn[10:7], rvfi_insn[12:11], rvfi_insn[5], rvfi_insn[6], 2'b00};\n data_accessed = RD;\n decoded_str = $sformatf(\"%s\\tx%0d,x2,%0d\", mnemonic, rvfi_rd_addr, nzuimm);\n endfunction\n\n function void decode_cb_sr_insn(input string mnemonic);\n logic [5:0] shamt;\n shamt = {rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, shamt);\n endfunction\n\n function void decode_cb_insn(input string mnemonic);\n logic [7:0] imm;\n logic [31:0] jump_target;\n if (rvfi_insn[15:13] == 3'b110 || rvfi_insn[15:13] == 3'b111) begin\n // C.BNEZ and C.BEQZ\n // We cannot use rvfi_pc_wdata for conditional jumps.\n imm = {rvfi_insn[12], rvfi_insn[6:5], rvfi_insn[2], rvfi_insn[11:10], rvfi_insn[4:3]};\n jump_target = rvfi_pc_rdata + 32'($signed({imm, 1'b0}));\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,%0x\", mnemonic, rvfi_rs1_addr, jump_target);\n end else if (rvfi_insn[15:13] == 3'b100) begin\n // C.ANDI\n imm = {{2{rvfi_insn[12]}}, rvfi_insn[12], rvfi_insn[6:2]};\n data_accessed = RS1 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,%0d\", mnemonic, rvfi_rd_addr, $signed(imm));\n end else begin\n imm = {rvfi_insn[12], rvfi_insn[6:2], 2'b00};\n data_accessed = RS1;\n decoded_str = $sformatf(\"%s\\tx%0d,0x%0x\", mnemonic, rvfi_rs1_addr, imm);\n end\n endfunction\n\n function void decode_cs_insn(input string mnemonic);\n data_accessed = RS1 | RS2 | RD; // RS1 == RD\n decoded_str = $sformatf(\"%s\\tx%0d,x%0d\", mnemonic, rvfi_rd_addr, rvfi_rs2_addr);\n endfunction\n\n function void decode_cj_insn(input string mnemonic);\n if (rvfi_insn[15:13] == 3'b001) begin\n // C.JAL\n data_accessed = RD;\n end\n decoded_str = $sformatf(\"%s\\t%0x\", mnemonic, rvfi_pc_wdata);\n endfunction\n\n function void decode_compressed_load_insn(input string mnemonic);\n logic [7:0] imm;\n\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.LW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.LWSP\n imm = {rvfi_insn[3:2], rvfi_insn[12], rvfi_insn[6:4], 2'b00};\n end\n data_accessed = RS1 | RD | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function void decode_compressed_store_insn(input string mnemonic);\n logic [7:0] imm;\n if (rvfi_insn[1:0] == OPCODE_C0) begin\n // C.SW\n imm = {1'b0, rvfi_insn[5], rvfi_insn[12:10], rvfi_insn[6], 2'b00};\n end else begin\n // C.SWSP\n imm = {rvfi_insn[8:7], rvfi_insn[12:9], 2'b00};\n end\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rs2_addr, imm, rvfi_rs1_addr);\n endfunction\n\n function void decode_load_insn();\n string mnemonic;\n\n /*\n Gives wrong results in Verilator < 4.020.\n See https://github.com/lowRISC/ibex/issues/372 and\n https://www.veripool.org/issues/1536-Verilator-Misoptimization-in-if-and-case-with-default-statement-inside-a-function\n\n unique case (rvfi_insn[14:12])\n 3'b000: mnemonic = \"lb\";\n 3'b001: mnemonic = \"lh\";\n 3'b010: mnemonic = \"lw\";\n 3'b100: mnemonic = \"lbu\";\n 3'b101: mnemonic = \"lhu\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n */\n logic [2:0] size;\n size = rvfi_insn[14:12];\n if (size == 3'b000) begin\n mnemonic = \"lb\";\n end else if (size == 3'b001) begin\n mnemonic = \"lh\";\n end else if (size == 3'b010) begin\n mnemonic = \"lw\";\n end else if (size == 3'b100) begin\n mnemonic = \"lbu\";\n end else if (size == 3'b101) begin\n mnemonic = \"lhu\";\n end else begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n\n\n data_accessed = RD | RS1 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rd_addr,\n $signed({{20 {rvfi_insn[31]}}, rvfi_insn[31:20]}), rvfi_rs1_addr);\n endfunction\n\n function void decode_store_insn();\n string mnemonic;\n\n unique case (rvfi_insn[13:12])\n 2'b00: mnemonic = \"sb\";\n 2'b01: mnemonic = \"sh\";\n 2'b10: mnemonic = \"sw\";\n default: begin\n decode_mnemonic(\"INVALID\");\n return;\n end\n endcase\n\n if (!rvfi_insn[14]) begin\n // regular store\n data_accessed = RS1 | RS2 | MEM;\n decoded_str = $sformatf(\"%s\\tx%0d,%0d(x%0d)\", mnemonic, rvfi_rs2_addr,\n $signed({ {20 {rvfi_insn[31]}}, rvfi_insn[31:25], rvfi_insn[11:7] }), rvfi_rs1_addr);\n end else begin\n decode_mnemonic(\"INVALID\");\n end\n endfunction\n\n function string get_fence_description(logic [3:0] bits);\n string desc = \"\";\n if (bits[3]) begin\n desc = {desc, \"i\"};\n end\n if (bits[2]) begin\n desc = {desc, \"o\"};\n end\n if (bits[1]) begin\n desc = {desc, \"r\"};\n end\n if (bits[0]) begin\n desc = {desc, \"w\"};\n end\n return desc;\n endfunction\n\n function void decode_fence();\n string predecessor;\n string successor;\n predecessor = get_fence_description(rvfi_insn[27:24]);\n successor = get_fence_description(rvfi_insn[23:20]);\n decoded_str = $sformatf(\"fence\\t%s,%s\", predecessor, successor);\n endfunction\n\n // cycle counter\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n cycle <= 0;\n end else begin\n cycle <= cycle + 1;\n end\n end\n\n // close output file for writing\n final begin\n if (file_handle != 32'h0) begin\n $fclose(file_handle);\n end\n end\n\n // log execution\n always_ff @(posedge clk_i) begin\n if (rvfi_valid) begin\n printbuffer_dumpline();\n end\n end\n\n always_comb begin\n decoded_str = \"\";\n data_accessed = 4'h0;\n insn_is_compressed = 0;\n\n // Check for compressed instructions\n if (rvfi_insn[1:0] != 2'b11) begin\n insn_is_compressed = 1;\n // Separate case to avoid overlapping decoding\n if (rvfi_insn[15:13] == 3'b100 && rvfi_insn[1:0] == 2'b10) begin\n if (rvfi_insn[12]) begin\n if (rvfi_insn[11:2] == 10'h0) begin\n decode_mnemonic(\"c.ebreak\");\n end else if (rvfi_insn[6:2] == 5'b0) begin\n decode_cr_insn(\"c.jalr\");\n end else begin\n decode_cr_insn(\"c.add\");\n end\n end else begin\n if (rvfi_insn[6:2] == 5'h0) begin\n decode_cr_insn(\"c.jr\");\n end else begin\n decode_cr_insn(\"c.mv\");\n end\n end\n end else begin\n unique casez (rvfi_insn[15:0])\n // C0 Opcodes\n INSN_CADDI4SPN: begin\n if (rvfi_insn[12:2] == 11'h0) begin\n // Align with pseudo-mnemonic used by GNU binutils and LLVM's MC layer\n decode_mnemonic(\"c.unimp\");\n end else begin\n decode_ciw_insn(\"c.addi4spn\");\n end\n end\n INSN_CLW: decode_compressed_load_insn(\"c.lw\");\n INSN_CSW: decode_compressed_store_insn(\"c.sw\");\n // C1 Opcodes\n INSN_CADDI: decode_ci_caddi_insn(\"c.addi\");\n INSN_CJAL: decode_cj_insn(\"c.jal\");\n INSN_CJ: decode_cj_insn(\"c.j\");\n INSN_CLI: decode_ci_cli_insn(\"c.li\");\n INSN_CLUI: begin\n // These two instructions share opcode\n if (rvfi_insn[11:7] == 5'd2) begin\n decode_ci_caddi16sp_insn(\"c.addi16sp\");\n end else begin\n decode_ci_clui_insn(\"c.lui\");\n end\n end\n INSN_CSRLI: decode_cb_sr_insn(\"c.srli\");\n INSN_CSRAI: decode_cb_sr_insn(\"c.srai\");\n INSN_CANDI: decode_cb_insn(\"c.andi\");\n INSN_CSUB: decode_cs_insn(\"c.sub\");\n INSN_CXOR: decode_cs_insn(\"c.xor\");\n INSN_COR: decode_cs_insn(\"c.or\");\n INSN_CAND: decode_cs_insn(\"c.and\");\n INSN_CBEQZ: decode_cb_insn(\"c.beqz\");\n INSN_CBNEZ: decode_cb_insn(\"c.bnez\");\n // C2 Opcodes\n INSN_CSLLI: decode_ci_cslli_insn(\"c.slli\");\n INSN_CLWSP: decode_compressed_load_insn(\"c.lwsp\");\n INSN_SWSP: decode_compressed_store_insn(\"c.swsp\");\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end else begin\n unique casez (rvfi_insn)\n // Regular opcodes\n INSN_LUI: decode_u_insn(\"lui\");\n INSN_AUIPC: decode_u_insn(\"auipc\");\n INSN_JAL: decode_j_insn(\"jal\");\n INSN_JALR: decode_i_jalr_insn(\"jalr\");\n // BRANCH\n INSN_BEQ: decode_b_insn(\"beq\");\n INSN_BNE: decode_b_insn(\"bne\");\n INSN_BLT: decode_b_insn(\"blt\");\n INSN_BGE: decode_b_insn(\"bge\");\n INSN_BLTU: decode_b_insn(\"bltu\");\n INSN_BGEU: decode_b_insn(\"bgeu\");\n // OPIMM\n INSN_ADDI: begin\n if (rvfi_insn == 32'h00_00_00_13) begin\n // TODO: objdump doesn't decode this as nop currently, even though it would be helpful\n // Decide what to do here: diverge from objdump, or make the trace less readable to\n // users.\n //decode_mnemonic(\"nop\");\n decode_i_insn(\"addi\");\n end else begin\n decode_i_insn(\"addi\");\n end\n end\n INSN_SLTI: decode_i_insn(\"slti\");\n INSN_SLTIU: decode_i_insn(\"sltiu\");\n INSN_XORI: decode_i_insn(\"xori\");\n INSN_ORI: decode_i_insn(\"ori\");\n INSN_ANDI: decode_i_insn(\"andi\");\n INSN_SLLI: decode_i_shift_insn(\"slli\");\n INSN_SRLI: decode_i_shift_insn(\"srli\");\n INSN_SRAI: decode_i_shift_insn(\"srai\");\n // OP\n INSN_ADD: decode_r_insn(\"add\");\n INSN_SUB: decode_r_insn(\"sub\");\n INSN_SLL: decode_r_insn(\"sll\");\n INSN_SLT: decode_r_insn(\"slt\");\n INSN_SLTU: decode_r_insn(\"sltu\");\n INSN_XOR: decode_r_insn(\"xor\");\n INSN_SRL: decode_r_insn(\"srl\");\n INSN_SRA: decode_r_insn(\"sra\");\n INSN_OR: decode_r_insn(\"or\");\n INSN_AND: decode_r_insn(\"and\");\n // SYSTEM (CSR manipulation)\n INSN_CSRRW: decode_csr_insn(\"csrrw\");\n INSN_CSRRS: decode_csr_insn(\"csrrs\");\n INSN_CSRRC: decode_csr_insn(\"csrrc\");\n INSN_CSRRWI: decode_csr_insn(\"csrrwi\");\n INSN_CSRRSI: decode_csr_insn(\"csrrsi\");\n INSN_CSRRCI: decode_csr_insn(\"csrrci\");\n // SYSTEM (others)\n INSN_ECALL: decode_mnemonic(\"ecall\");\n INSN_EBREAK: decode_mnemonic(\"ebreak\");\n INSN_MRET: decode_mnemonic(\"mret\");\n INSN_DRET: decode_mnemonic(\"dret\");\n INSN_WFI: decode_mnemonic(\"wfi\");\n // RV32M\n INSN_PMUL: decode_r_insn(\"mul\");\n INSN_PMUH: decode_r_insn(\"mulh\");\n INSN_PMULHSU: decode_r_insn(\"mulhsu\");\n INSN_PMULHU: decode_r_insn(\"mulhu\");\n INSN_DIV: decode_r_insn(\"div\");\n INSN_DIVU: decode_r_insn(\"divu\");\n INSN_REM: decode_r_insn(\"rem\");\n INSN_REMU: decode_r_insn(\"remu\");\n // LOAD & STORE\n INSN_LOAD: decode_load_insn();\n INSN_STORE: decode_store_insn();\n // MISC-MEM\n INSN_FENCE: decode_fence();\n INSN_FENCEI: decode_mnemonic(\"fence.i\");\n default: decode_mnemonic(\"INVALID\");\n endcase\n end\n end\n\nendmodule\n", "selected_doc_paths": ["doc/tracer.rst", "doc/rvfi.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 302, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# Design Specification: Ibex Controller Module\n\n## Overview\n\nThe controller is the central state machine of the Ibex processor core. It manages the instruction pipeline flow, coordinates instruction fetch and decode, handles all exception and interrupt events, and controls debug mode entry and exit. It governs when the processor is busy, when it is ready to fetch new instructions, and when it must flush or redirect the pipeline due to control flow changes (branches, jumps, exceptions, interrupts, debug requests).\n\nThe controller operates in a sequence of major phases:\n\n- **Reset and boot initialisation** – waits for an external enable signal, then sets the program counter to the boot address.\n- **Normal instruction execution** – fetches instructions, decodes them, and handles jumps, branches, stalls, and special instructions.\n- **Exception handling** – responds to illegal instructions, environment calls (ECALL), breakpoints (EBREAK), instruction fetch errors, and load/store access faults.\n- **Interrupt handling** – responds to non‑maskable interrupts (NMI), fast local interrupts, external interrupts, timer interrupts, and software interrupts, subject to global and per‑interrupt enable bits.\n- **Debug support** – responds to a debug request, implements single‑stepping, and handles EBREAK instructions according to the RISC‑V Debug Specification v0.13.13.\n- **Pipeline control** – signals the fetch and decode stages to stall, flush, or clear valid bits as needed.\n\nThe controller also provides performance monitor signals indicating when a taken branch or a jump instruction is executed.\n\n---\n\n## Functional Behaviour\n\n### 1. Reset and Boot Initialisation\n\nUpon reset, the controller:\n\n- **waits** for an external fetch‑enable signal to become active.\n- Once fetch‑enable is asserted, **sets the program counter (PC)** to the configured boot address and **starts fetching** instructions from that address.\n- The first instruction fetch is indicated by an output signal that remains active until the first valid instruction enters the decode stage.\n\nWhile waiting for fetch‑enable, the processor is not busy and does not request any instruction fetches.\n\n### 2. Normal Operation (DECODE State)\n\nWhen the processor is not servicing an exception, interrupt, or debug event, the controller:\n\n- **Requests instruction fetches** continuously from the prefetcher.\n- **Accepts valid instructions** from the instruction‑fetch / decode (ID) pipeline register when no stall is active.\n- **Handles control flow changes**:\n - **Branches** – When a branch is taken (e.g., conditional branch), the controller sets the PC to the branch target and signals the prefetcher to redirect fetch.\n - **Jumps** – For unconditional jump instructions (JAL, JALR), the controller sets the PC to the jump target and signals the prefetcher. Both jumps and taken branches are counted as performance events.\n- **Responds to special instructions, pipeline flushes, exceptions, and interrupts** as described in the following sections.\n- **Stalls** the fetch stage when the current instruction requires multiple cycles (e.g., load/store, multiply/divide, jump/branch penalty). The decode stage is stalled only when the current multi‑cycle instruction is not yet complete.\n\nWhen a valid instruction is being decoded and the pipeline is not stalled, the controller checks for:\n\n- **Debug requests** (higher priority than interrupts)\n- **Interrupt requests** (if not in debug mode)\n\nThese are serviced only after the current multi‑cycle instruction finishes (i.e., when the stall signal deasserts), unless a special instruction or exception forces a pipeline flush earlier.\n\n### 3. Exception Handling\n\nThe controller recognises the following exception causes (ordered by precedence when multiple occur simultaneously):\n\n| Priority | Exception Cause | Trigger |\n|----------|--------------------------|-----------------------------------------------------------|\n| 1 | Instruction access fault | Fetch error on the instruction currently in decode |\n| 2 | Illegal instruction | Decoder reports illegal instruction or DRET executed outside debug mode |\n| 3 | Breakpoint | EBREAK instruction (when not entering debug mode) |\n| 4 | Environment call M-mode | ECALL instruction |\n| 5 | Store access fault | Store error from LSU (may be delayed by one cycle) |\n| 6 | Load access fault | Load error from LSU (may be delayed by one cycle) |\n\nWhen an exception occurs:\n\n- The controller **flushes the pipeline**: the fetch and decode stages are halted, and the instruction in the ID stage is killed.\n- The **PC is set to the exception vector address**:\n - If the core is in debug mode, the exception vector is the debug exception address.\n - Otherwise, the normal exception vector (from `mtvec`) is used.\n- The **exception PC** (address of the offending instruction) is saved to `mepc` (or the debug equivalent `dpc` when appropriate).\n- The **exception cause** is saved to `mcause` (or `dcsr`).\n- **`mtval`** is set to additional information:\n - For instruction access fault: the faulting instruction address.\n - For illegal instruction: the raw instruction word (uncompressed or compressed zero‑extended to 32 bits).\n - For load/store faults: the address that caused the fault.\n\nAfter the pipeline flush and register updates, the controller returns to normal fetch at the exception handler address.\n\n**EBREAK special cases:**\n\n- **EBREAK in debug mode** – Instead of taking a breakpoint exception, the controller re‑enters debug mode **without updating `dpc` or `dcsr`** and jumps to the debug exception handler. This is the only way to re‑enter debug mode while already in debug mode.\n- **EBREAK when `debug_ebreakm` is set** – The controller enters debug mode, saves the PC and cause, and jumps to the debug exception handler.\n- **All other EBREAK** – Treated as a breakpoint exception (cause 3) and handled like any other exception.\n\n**DRET outside debug mode** is decoded as an illegal instruction, causing an illegal instruction exception.\n\n### 4. Interrupt Handling\n\nInterrupts are taken only when the core is **not in debug mode** and the **global interrupt enable (MIE)** bit is set. The NMI (non‑maskable interrupt) is also disabled in debug mode but is taken irrespective of MIE.\n\nInterrupt priorities (high to low):\n\n1. **Non‑maskable interrupt (NMI)** – ID 31\n2. **Fast interrupts** – ID 30 down to 16 (15 sources, highest ID has highest priority)\n3. **External interrupt** – ID 11\n4. **Timer interrupt** – ID 7\n5. **Software interrupt** – ID 3\n\nThe controller samples interrupt requests continuously. It takes an interrupt **only when**:\n\n- The request is active (level‑sensitive), and\n- The corresponding bit in `mie` is set (except NMI), and\n- The global MIE is set (except NMI), and\n- The core is not already handling an interrupt (unless nested interrupts are explicitly enabled by the handler software).\n\n**NMI handling:**\n\n- NMI is taken as soon as it is asserted, even if a previous NMI is being handled. The controller enters a special **NMI mode** to allow recovery of the backed‑up CSRs (non‑standard support).\n- Upon taking NMI, the exception cause is set to the NMI interrupt code (31) and the core jumps to the vector base + 0x7C.\n\n**Vectored interrupts:**\n\n- For all other interrupts, the controller uses vectored mode: the PC is set to `mtvec` base + 4 × interrupt ID.\n- The interrupt cause is encoded in `mcause` with the high bit set (interrupt flag) and the remainder equal to the interrupt ID.\n\nWhen an interrupt is taken:\n\n- The pipeline is flushed (fetch and decode halted).\n- The current PC is saved to `mepc`.\n- The `mstatus` MIE bit is copied to MPIE, and MIE is cleared (disabling further interrupts).\n- The appropriate exception cause is saved to `mcause`.\n- The PC is set to the interrupt vector address, and normal fetch resumes from there.\n\n**Interrupt handling is deferred** while there is a pending multi‑cycle instruction (stall active) or while a special instruction (MRET, DRET, WFI, CSR pipeline flush) or exception is being processed. Once the stall condition ends or the special instruction is handled, the interrupt is taken in the next cycle.\n\n### 5. Debug Support\n\nThe controller supports execution‑based debug as defined in the RISC‑V Debug Specification v0.13.13.\n\n**Entering debug mode:**\n\nThe controller enters debug mode under the following conditions:\n\n1. **Debug request (`debug_req`)** – Asserted by an external debug module. The controller saves the current PC to `dpc`, updates `dcsr` with cause “halt request”, and jumps to the debug entry address (`DmHaltAddr`).\n2. **Single‑step** – When single‑step is enabled and an instruction has completed without an exception, the controller enters debug mode after that instruction. The PC of the completed instruction is saved to `dpc`, cause is “single step”.\n3. **EBREAK with forced entry** – If `debug_ebreakm` is set and an EBREAK is executed from M‑mode, the controller enters debug mode, saves PC and cause (“EBREAK”).\n4. **EBREAK in debug mode** – Re‑enters debug mode without updating `dpc` or `dcsr` (as above).\n\n**Behaviour in debug mode:**\n\n- In debug mode, the core ignores all interrupts (including NMI) and debug requests.\n- Exceptions that occur in debug mode are handled using the **debug exception address** (`DmExceptionAddr`) instead of the normal exception vector.\n- The `debug_mode` output is asserted while the core is in debug mode.\n\n**Leaving debug mode:**\n\n- The `dret` instruction causes the controller to exit debug mode: it sets the PC to the value in `dpc`, clears the debug mode flag, and resumes normal fetch.\n- The `dret` instruction is illegal when not in debug mode (causes an illegal instruction exception).\n\n**Single‑stepping:**\n\n- When single‑step is enabled, the controller executes exactly one instruction, then enters debug mode (unless that instruction itself causes an exception or triggers a higher‑priority event).\n- Exception handling under single‑step: The exception registers are set as usual, but the controller then takes the debug trap (enters debug mode) instead of jumping to the exception handler. The PC is **not** redirected to the exception vector.\n\n### 6. Pipeline Control\n\nThe controller drives signals that control the fetch and decode stages:\n\n- **Fetch request** – Active by default; de‑asserted during reset, boot setup, and sleep.\n- **Fetch stall** – Asserted to prevent the fetch stage from providing a new instruction to the decode stage. Occurs during:\n - Pipeline flushes (exceptions, interrupts, debug entry)\n - Single‑step (to pause after one instruction)\n - Wait for a multi‑cycle instruction to complete while a debug/interrupt request is pending\n - Sleep state\n- **Decode stall** – Asserted to prevent the decode stage from processing a new instruction. Decode is stalled during pipeline flushes, sleep, and when the pipeline is being redirected.\n- **Instruction valid clear** – Kills the instruction currently in the ID register. Asserted when the pipeline is being flushed (exception, interrupt, debug, special instruction) or when a multi‑cycle instruction causes a late exception.\n- **Decode ready** – Indicates the decode stage is ready to accept a new instruction from the fetch stage. Active only when no stall is asserted and the fetch stage is not halted.\n\n**Stall sources:**\n\n- Load/store unit (LSU) – multi‑cycle memory access.\n- Multiplier/divider – multi‑cycle arithmetic.\n- Jump/branch – pipeline bubble while redirecting fetch.\n\n**Sleep mode:**\n\n- When a `wfi` (wait for interrupt) instruction is executed, the controller transitions to a sleep state.\n- In sleep, the core is **not busy**, fetch and decode are halted, and no instruction fetches are requested.\n- The controller leaves sleep when any wake‑up event occurs: interrupt request, debug request, or if the core is already in debug mode / single‑step mode (in which case `wfi` is treated as a NOP).\n\n### 7. Performance Counters\n\nThe controller provides two output signals for performance monitoring:\n\n- **Taken branch** – asserted for one cycle when a conditional branch is taken.\n- **Jump** – asserted for one cycle when a jump instruction (JAL, JALR) is executed.\n\nThese signals are only generated for instructions that are successfully decoded and executed (not flushed).\n\n### 8. Output Summary\n\nThe controller drives the following key outputs (conceptual behaviour):\n\n- **Core busy** – indicates the core is actively executing instructions or handling exceptions/interrupts. De‑asserted during sleep and reset‑wait.\n- **First fetch** – asserted from the beginning of boot until the first instruction enters decode.\n- **PC set** – requests the prefetcher to redirect to a new address (boot, jump, branch, exception, return, etc.).\n- **PC selector** – selects the source of the new PC: boot address, jump/branch target, exception vector, return address (MRET, DRET), or debug entry.\n- **Exception cause** – provides the cause code to be written into `mcause` (or `dcsr` for debug).\n- **Exception PC selector** – selects between normal exception vector and debug exception vector.\n- **CSR save/restore signals** – control when to save or restore CSRs (PC, cause, `mstatus`) during exception, interrupt, debug, or return‑from‑trap.\n- **`mtval`** – exception‑specific information (instruction word, faulting address).\n- **Debug mode** – indicates whether the core is currently in debug mode.\n- **Debug CSR save** – triggers saving to `dcsr` and `dpc` on debug entry.\n- **Debug cause** – indicates the reason for entering debug mode (halt request, single step, EBREAK).\n\n---\n\n## Dependencies and Constraints\n\n- The controller assumes a stable clock and reset.\n- All interrupt and debug request inputs are level‑sensitive; the controller samples them every cycle.\n- The controller expects the decoder to provide decoded instruction attributes (illegal, ECALL, MRET, etc.) one cycle after the instruction is valid in the ID stage.\n- LSU error signals (`load_err`, `store_err`) are captured and used in the next cycle to allow the current instruction to finish.\n- The prefetcher is responsible for respecting the PC set and PC mux commands to fetch from the correct address.\n- The controller is designed for a single‑issue, in‑order pipeline with no speculation beyond branches.", "commit_id": "ac22439374a0bafd6fc2f9d38aefc02e44fa2abb", "timestamp": "2019-09-11T09:45:27+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "85ae06d054b6d886276d2e5d3e2021df4c237049", "pr_title": "Controller: fix `nmi_mode` default assignment", "pr_body": "Without this commit, the `nmi_mode` register is continuously cleared and set again, and the core can never handle the NMI.\r\n\r\nThis resolves lowRISC/ibex#300 reported by @udinator.", "issue_title": "Non-maskable interrupt handling", "issue_body": "Hi all,\r\nIn testing Ibex's interrupt interface, I ran into the following situation:\r\n![Screenshot from 2019-09-10 14-39-58](https://user-images.githubusercontent.com/16736281/64652505-e3d08100-d3d8-11e9-8886-8a355f31a7f7.png)\r\nI drive `irq_nm_i`, signaling a non-maskable interrupt to Ibex. Since Ibex treats interrupts as level sensitive, and relies on handler routines to deassert the interrupt lines, I treat non-maskable interrupts the same way, and leave it driven to `1'b1` until the handler code is completed. However, Ibex, after jumping into the `DECODE` state from `IRQ_TAKEN` upon detection of the `irq_nm`, seems to keep detecting that `irq_nm` is high, and then infinitely loops between the `DECODE` and `IRQ_TAKEN` states, causing the simulation to time out. Since according to #199 as well as the docs this seems to be incorrect behavior for `irq_nm`, would it be possible to clarify what expected behavior for non-maskable interrupt should be? ", "commit_message": "Controller: fix `nmi_mode` default assignment\n\nWithout this commit, the `nmi_mode` register is continuously cleared and\nset again, and the core can never handle the NMI.\n\nThis resolves lowRISC/ibex#300 reported by @udinator.", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex 1ef0fac7f6..5a8fc54a8e 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -215,7 +215,7 @@ module ibex_controller (\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+ nmi_mode_d = nmi_mode_q;\n \n perf_tbranch_o = 1'b0;\n perf_jump_o = 1'b0;\n", "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\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 [3: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 (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 // \"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 = 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 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 = 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 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 // 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 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 // 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 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", "selected_doc_paths": ["doc/exception_interrupts.rst", "doc/debug.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 196, "lang": "sv", "rtl_files": ["rtl/ibex_pkg.sv"], "spec": "# Behavioral Design Specification for the Ibex RISC‑V Core\n\n## 1. Overview\n\nThe Ibex core is a 32‑bit RISC‑V processor that implements the RV32IMC instruction set (base integer, multiplication/division, and compressed instructions) as defined in the RISC‑V Instruction Set Manual, version 2.1. It operates in Machine mode (M‑mode) only, with support for the standard M‑mode control and status registers (CSRs), vectored interrupts, execution‑based debug, and performance counters. The core is designed for embedded systems and is fully compliant with the RISC‑V Privileged Specification, version 1.11, and the RISC‑V Debug Specification, version 0.13.\n\nThis specification defines the required external behavior of the core. The core shall be synthesizable and operate correctly under all conditions described herein.\n\n---\n\n## 2. Instruction Execution\n\n### 2.1 Supported Instructions\n\nThe core shall execute all instructions of the RV32I base ISA (excluding fence.i, which is optional) and the M extension (multiply/divide). The compressed instruction set (C extension) shall be fully supported. Instruction opcodes are defined according to the standard RISC‑V encoding.\n\n### 2.2 Arithmetic and Logic Unit (ALU)\n\nThe ALU shall support the following operations:\n\n- Addition and subtraction (including comparison for set‑less‑than).\n- Bitwise XOR, OR, AND.\n- Logic shifts (left, right, arithmetic right).\n- Integer comparisons: equality, not‑equal, less‑than (signed and unsigned), greater‑than, less‑than‑or‑equal, greater‑than‑or‑equal. \n- Set‑less‑than instructions (SLT, SLTU, SLET, SLETU).\n\nAll ALU operations shall complete in a single cycle (except for multiplication and division, which take multiple cycles).\n\n### 2.3 Multiply/Divide Unit\n\nThe core shall provide hardware multiply and divide operations:\n\n- **Multiplication**: `MUL`, `MULH`, `MULHSU`, `MULHU`. The multiply result is available after a fixed latency (e.g., 3 cycles). \n- **Division**: `DIV`, `DIVU`, `REM`, `REMU`. The divide/remainder result is available after a fixed latency (e.g., 35 cycles). Division by zero shall produce the standard RISC‑V results: the quotient is all‑1s and the remainder equals the dividend.\n\n### 2.4 Load/Store Unit (LSU)\n\nThe core shall perform byte, half‑word, and word loads and stores to the data memory interface. Misaligned accesses are supported by decomposing them into two aligned accesses; each misaligned access counts as two separate memory transactions. The LSU shall handle load‑access faults and store‑access faults by raising the corresponding exceptions.\n\n---\n\n## 3. Fetch and Pipeline\n\n### 3.1 Instruction Fetch\n\nThe core shall fetch instructions from the instruction memory interface starting at the reset address. The reset address is formed by concatenating the three most significant bytes of the boot address with the reset offset `0x80`. The boot address is supplied as an input and must be 256‑byte aligned. After the first fetch the boot address can be changed (e.g., to update the interrupt vector table base).\n\n### 3.2 Pipeline Structure\n\nThe core implements a multi‑stage pipeline (typical stages: fetch, decode, execute, memory, writeback). The pipeline shall:\n\n- Correctly resolve data hazards through forwarding (operand bypass) and, where necessary, stalling.\n- Handle control hazards (branches, jumps) with a predictable branch‑target buffer and a minimal branch penalty.\n- Support compressed instructions by expanding them to 32‑bit equivalents in the decode stage.\n- Stall the pipeline when the instruction or data memory interface is not ready.\n\n---\n\n## 4. Control and Status Registers (CSRs)\n\n### 4.1 CSR Address Space\n\nThe core implements all mandatory M‑mode CSRs and a set of optional performance‑monitoring CSRs, as listed in the RISC‑V Privileged Specification. The following registers shall be accessible via the `CSRRW`, `CSRRS`, `CSRRC` instructions (and their immediate variants):\n\n| Address | Name | Access | Description |\n|---------|-----------------|---------|-------------------------------------|\n| 0x300 | `mstatus` | WARL | Machine status |\n| 0x301 | `misa` | WARL | Machine ISA (hardwired, read‑only) |\n| 0x304 | `mie` | WARL | Machine interrupt enable |\n| 0x305 | `mtvec` | WARL | Trap vector base address |\n| 0x320 | `mcountinhibit` | RW | Counter inhibit |\n| 0x323–0x33F | `mhpmevent3..31` | WARL | Event selectors for performance counters |\n| 0x340 | `mscratch` | RW | Machine scratch register |\n| 0x341 | `mepc` | WARL | Exception program counter |\n| 0x342 | `mcause` | WLRL | Exception cause |\n| 0x343 | `mtval` | WARL | Trap value |\n| 0x344 | `mip` | R | Interrupt pending (read‑only) |\n| 0x7B0 | `dcsr` | RW | Debug control and status |\n| 0x7B1 | `dpc` | RW | Debug program counter |\n| 0x7B2 | `dscratch0` | RW | Debug scratch register 0 |\n| 0x7B3 | `dscratch1` | RW | Debug scratch register 1 |\n| 0xB00 | `mcycle` | RW | Cycle counter (low 32 bits) |\n| 0xB80 | `mcycleh` | RW | Cycle counter (high 32 bits) |\n| 0xB02 | `minstret` | RW | Instruction retired counter (low) |\n| 0xB82 | `minstreth` | RW | Instruction retired counter (high) |\n| 0xB03–0xB1F | `mhpmcounter3..31` | WARL | Performance counters (low) |\n| 0xB83–0xB9F | `mhpmcounter3h..31h` | WARL | Performance counters (high) |\n| 0xF14 | `mhartid` | R | Hardware thread ID (read‑only) |\n\n### 4.2 CSR Behavior\n\n- All WARL registers shall tolerate any write value and return an implementation‑dependent legal value on read. Specifically:\n - `misa` is hardwired and shall reflect only the supported extensions (I, M, C). Writes are ignored.\n - `mtvec` is hardwired to the boot address and cannot be changed.\n - `mstatus` shall have bits 12:11 (MPP) read as 2'b11 (Machine mode) and ignore writes to those bits. Bits 7 (MPIE) and 3 (MIE) are RW.\n - `mepc`, `mcause`, `mtval`, and `mcountinhibit` are fully writable.\n- `mip` shall reflect the current interrupt pending status, computed as the logical AND of the interrupt inputs with the corresponding bits in `mie`. Bits 30:16 correspond to fast interrupts, bit 11 to external, bit 7 to timer, bit 3 to software. Bit 31 (NMI) is not visible.\n- `dcsr` shall implement fields required by the debug specification, including `xdebugver` (value 4 indicating standard RISC‑V debug), halt/step control, and privilege mode.\n- `mhartid` shall be constructed from an input cluster ID (bits 10:5) and core ID (bits 3:0). The reset value is determined by these inputs.\n\n---\n\n## 5. Exception and Interrupt Handling\n\n### 5.1 Exception Types\n\nThe core shall generate exceptions for the following causes (exception code in parentheses):\n\n- Illegal instruction (2)\n- Breakpoint (3)\n- Load access fault (5)\n- Store access fault (7)\n- Environment call from M‑mode (ECALL, 11)\n\nAll exceptions are taken immediately when detected. The illegal instruction, LSU errors, and ECALL exceptions are always enabled and cannot be masked.\n\n### 5.2 Interrupt Types\n\nThe core shall accept the following interrupt sources, each with a fixed interrupt ID:\n\n| Interrupt ID | Description |\n|--------------|---------------------------------------|\n| 31 | Non‑maskable interrupt (NMI) |\n| 30..16 | Fast interrupts (15 local lines) |\n| 11 | External interrupt (platform‑level) |\n| 7 | Timer interrupt |\n| 3 | Software interrupt (inter‑processor) |\n\nAll interrupts except NMI are level‑sensitive and qualified by the global interrupt enable (`mstatus.MIE`) and the corresponding enable bit in `mie`. The NMI is always enabled (not affected by `mstatus.MIE` or `mie`) and is not visible in `mip`.\n\nInterrupt priority is determined by the interrupt ID: higher ID has higher priority. The NMI (ID 31) has the highest priority.\n\n### 5.3 Trap Entry\n\nWhen an exception or interrupt is taken, the core shall:\n\n1. Save the current PC into `mepc`.\n2. Save the current `mstatus.MIE` into `mstatus.MPIE`, then clear `mstatus.MIE`.\n3. Set `mcause` to the appropriate cause value (interrupt bit = 1 for interrupts, 0 for exceptions; exception code as above).\n4. Set `mtval` to the trap‑specific information:\n - For load/store faults: the faulting address (or misaligned address if applicable).\n - For illegal instruction: the faulting instruction word.\n - For all other exceptions: zero.\n5. Jump to the trap handler address determined by `mtvec`:\n - For exceptions: base address of `mtvec`.\n - For interrupts: `mtvec` base + 4 × interrupt ID (vectored mode). The NMI uses offset 0x7C (ID 31).\n\n### 5.4 Trap Return\n\nThe MRET instruction shall restore the PC from `mepc` and restore `mstatus.MIE` from `mstatus.MPIE`. The DRET instruction (debug return) shall behave according to the debug specification.\n\n### 5.5 Nested Trap Support\n\nThe core supports nested exceptions and interrupts. When an exception occurs inside a trap handler, it will cause another trap, overwriting `mepc` and `mstatus`. Software must save these registers early in the handler if nested handling is desired. Interrupts are automatically disabled after entry (MIE cleared). Software may enable them again explicitly.\n\nWhen an NMI occurs during a trap handler, the core shall back up `mstatus.MPP`, `mstatus.MPIE`, `mepc`, and `mcause` into dedicated non‑accessible registers, enabling recovery after the NMI is handled.\n\n### 5.6 Debug Mode Interactions\n\nWhen the core is in debug mode, all interrupts (including the NMI) are ignored, regardless of `mstatus.MIE` or `mie`. Exceptions that occur in debug mode cause a debug exception, which is handled using `DmExceptionAddr` as the handler address.\n\n---\n\n## 6. Debug Support\n\n### 6.1 Entering Debug Mode\n\nThe core shall enter debug mode when a debug request is asserted (`debug_req`). Entry is taken at an instruction boundary. The core shall:\n\n- Save the current PC into `dpc`.\n- Update `dcsr` to reflect the cause of entry (e.g., halt request) and the current privilege mode.\n- Jump to the debug handler address given by the `DmHaltAddr` parameter.\n\n### 6.2 Debug Mode Actions\n\nWhile in debug mode, the core shall execute instructions as normal but ignore all interrupts. It shall permit single‑stepping as controlled by `dcsr.step`. The core shall support the following debug causes (recorded in `dcsr.cause`):\n\n- `none` (0) – no debug entry.\n- `ebreak` (1) – triggered by an `ebreak` instruction.\n- `trigger` (2) – triggered by a hardware trigger.\n- `haltreq` (3) – triggered by the external debug request.\n- `step` (4) – triggered by single‑step completion.\n\n### 6.3 Exceptions in Debug Mode\n\nIf an exception occurs while the core is in debug mode, it shall cause a debug exception: the core jumps to the `DmExceptionAddr` and updates `dcsr` accordingly (cause set to the exception type). This allows the debugger to handle the exception.\n\n### 6.4 Leaving Debug Mode\n\nThe DRET instruction shall return from debug mode: the PC is restored from `dpc`, and the core resumes normal execution. Interrupts become active again.\n\n---\n\n## 7. Performance Counters\n\n### 7.1 Available Counters\n\nThe core shall implement the following fixed counters:\n\n- `mcycle`/`mcycleh`: 64‑bit cycle counter, incrementing once per clock cycle.\n- `minstret`/`minstreth`: 64‑bit instruction retired counter, incrementing for each instruction that completes (including compressed instructions). \n\nOptional performance counters (`mhpmcounter3..31` and their high halves) may be instantiated via the `NumMHPMCounters` parameter (0 to 8). The width of these counters is controlled by the `WidthMHPMCounters` parameter (1–64 bits, default 40). Unavailable counters shall read zero on any access.\n\n### 7.2 Event Selection\n\nEach `mhpmeventX` CSR (X = 3..31) selects which hardware events are counted by the corresponding `mhpmcounterX`. The event selectors are **hardwired** to specific events in Ibex; writing to them has no effect.\n\n| Counter | Fixed Event ID | Event Name |\n|---------|----------------|------------------|\n| 3 | 3 | Cycles waiting for data memory |\n| 4 | 4 | Cycles waiting for instruction fetch |\n| 5 | 5 | Load accesses (misaligned counted as two) |\n| 6 | 6 | Store accesses (misaligned counted as two) |\n| 7 | 7 | Unconditional jumps (JAL, JALR) |\n| 8 | 8 | Branches (conditional) |\n| 9 | 9 | Taken branches (conditional) |\n| 10 | 10 | Compressed instructions retired |\n\nThe event ID corresponds to the bit position in the event selector register. For example, `mhpmevent3` resets to `0x0000_0008` (bit 3 set), so it counts event 3. All other `mhpmevent` registers not listed shall be tied to zero, causing the corresponding counters to never increment.\n\n### 7.3 Counter Control\n\nThe `mcountinhibit` CSR (address 0x320) allows software to stop individual counters. Bit 0 inhibits `mcycle`, bit 2 inhibits `minstret`, and bit X inhibits `mhpmcounterX`. After reset, all counters are enabled. Counter values can be read or written via the corresponding CSR addresses; writes are non‑destructive to the counting logic (i.e., software may set the counter to any value).\n\n---\n\n## 8. Reset and Initialization\n\n### 8.1 Reset Behavior\n\nUpon assertion of the reset signal, the core shall:\n\n- Load the reset PC as described in Section 3.1.\n- Initialize all CSRs to their reset values (see Section 4 and the Privileged Specification). Notable exceptions:\n - `mstatus` resets to `0x0000_1800` (MIE=0, MPIE=0, MPP=11).\n - `mcountinhibit` resets to `0x0000_0000` (all counters enabled).\n - Debug CSRs (dcsr, dpc, dscratch0/1) reset to 0.\n- Enter Machine mode, with interrupts disabled.\n- Begin fetching instructions from the reset address.\n\n### 8.2 Power‑up Stability\n\nAll state elements shall be initialized to a known value after reset. The core shall not rely on any implicit initial state.\n\n---\n\n## 9. Interface Requirements (Behavioral)\n\nThe core shall communicate with the system through the following abstract interfaces:\n\n- **Instruction memory interface**: Used to fetch instructions. The core must handle wait states and stalls when the memory is not ready.\n- **Data memory interface**: Used for load and store operations. The core must support byte, half‑word, and word transactions. It must generate aligned accesses for misaligned requests (two transactions).\n- **Interrupt inputs**: The core shall sample the interrupt lines every cycle. All lines are level‑sensitive.\n- **Debug request**: A single input that triggers debug mode entry.\n- **Boot address**: A multi‑bit input that defines the reset PC and the interrupt vector base.\n- **Hart ID**: Inputs for cluster ID and core ID that form `mhartid`.\n\nThe core must not rely on external arbitration or handshake protocols beyond standard ready/valid signals.\n\n---\n\n## 10. Compliance and Assumptions\n\n- The core assumes that the external memory system returns valid data within a bounded time.\n- The interrupt lines must be held asserted until the corresponding handler clears the source.\n- The debug module is responsible for controlling the debug request signal and for providing the `DmHaltAddr` and `DmExceptionAddr` parameters.\n- The core is intended for use in a single‑hart system; it does not implement any cache coherency or multi‑core synchronization.\n\nEnd of Specification.", "commit_id": "1aa276dbc07edd925d265c9ae9c823d3833a37c1", "timestamp": "2019-07-26T10:38:10+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "6d72aebc1621139a05f333ab7eb284e8cc68b660", "pr_title": "Correct cause number for illegal instruction exception", "pr_body": "This bug has beed reported by @taoliug. This resolves #195.", "issue_title": "Wrong encoding of EXC_CAUSE_ILLEGAL_INSN", "issue_body": "This issue seems to be introduced in this commit\r\nhttps://github.com/lowRISC/ibex/commit/c2fffe04406287bc7e1be3962999f0f6b44ebe87#diff-ef03dc5b772f9745e0a161472ea79c60R190\r\n\r\nEXC_CAUSE_ILLEGAL_INSN should be 2 according to RISC-V privileged mode spec", "commit_message": "Correct cause number for illegal instruction exception\n\nThis bug has beed reported by @taoliug. This resolves #195.", "fix_patch": "diff --git a/rtl/ibex_pkg.sv b/rtl/ibex_pkg.sv\nindex 819ab200b8..d65b9bedbc 100644\n--- a/rtl/ibex_pkg.sv\n+++ b/rtl/ibex_pkg.sv\n@@ -190,7 +190,7 @@ typedef enum logic [5:0] {\n // EXC_CAUSE_IRQ_FAST_14 = {1'b1, 5'd30},\n EXC_CAUSE_IRQ_NM = {1'b1, 5'd31}, // == EXC_CAUSE_IRQ_FAST_15\n EXC_CAUSE_INSN_ADDR_MISA = {1'b0, 5'd00},\n- EXC_CAUSE_ILLEGAL_INSN = {1'b0, 5'd01},\n+ EXC_CAUSE_ILLEGAL_INSN = {1'b0, 5'd02},\n EXC_CAUSE_BREAKPOINT = {1'b0, 5'd03},\n EXC_CAUSE_LOAD_ACCESS_FAULT = {1'b0, 5'd05},\n EXC_CAUSE_STORE_ACCESS_FAULT = {1'b0, 5'd07},\n", "fixed_rtl_code": "// Copyright lowRISC contributors.\n// Copyright 2017 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// Sven Stucki - svstucki@student.ethz.ch //\n// //\n// //\n// Design Name: RISC-V processor core //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Defines for various constants used by the processor core. //\n// //\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Package with constants used by Ibex\n */\npackage ibex_pkg;\n\n\n/////////////\n// Opcodes //\n/////////////\n\ntypedef enum logic [6:0] {\n OPCODE_LOAD = 7'h03,\n OPCODE_MISC_MEM = 7'h0f,\n OPCODE_OP_IMM = 7'h13,\n OPCODE_AUIPC = 7'h17,\n OPCODE_STORE = 7'h23,\n OPCODE_OP = 7'h33,\n OPCODE_LUI = 7'h37,\n OPCODE_BRANCH = 7'h63,\n OPCODE_JALR = 7'h67,\n OPCODE_JAL = 7'h6f,\n OPCODE_SYSTEM = 7'h73\n} opcode_e;\n\n\n////////////////////\n// ALU operations //\n////////////////////\n\ntypedef enum logic [4:0] {\n // Arithmetics\n ALU_ADD,\n ALU_SUB,\n\n // Logics\n ALU_XOR,\n ALU_OR,\n ALU_AND,\n\n // Shifts\n ALU_SRA,\n ALU_SRL,\n ALU_SLL,\n\n // Comparisons\n ALU_LT,\n ALU_LTU,\n ALU_LE,\n ALU_LEU,\n ALU_GT,\n ALU_GTU,\n ALU_GE,\n ALU_GEU,\n ALU_EQ,\n ALU_NE,\n\n // Set lower than\n ALU_SLT,\n ALU_SLTU,\n ALU_SLET,\n ALU_SLETU\n} alu_op_e;\n\ntypedef enum logic [1:0] {\n // Multiplier/divider\n MD_OP_MULL,\n MD_OP_MULH,\n MD_OP_DIV,\n MD_OP_REM\n} md_op_e;\n\n\n//////////////////////////////////\n// Control and status registers //\n//////////////////////////////////\n\n// CSR operations\ntypedef enum logic [1:0] {\n CSR_OP_READ,\n CSR_OP_WRITE,\n CSR_OP_SET,\n CSR_OP_CLEAR\n} csr_op_e;\n\n// Privileged mode\ntypedef enum logic[1:0] {\n PRIV_LVL_M = 2'b11,\n PRIV_LVL_H = 2'b10,\n PRIV_LVL_S = 2'b01,\n PRIV_LVL_U = 2'b00\n} priv_lvl_e;\n\n// Constants for the dcsr.xdebugver fields\ntypedef enum logic[3:0] {\n XDEBUGVER_NO = 4'd0, // no external debug support\n XDEBUGVER_STD = 4'd4, // external debug according to RISC-V debug spec\n XDEBUGVER_NONSTD = 4'd15 // debug not conforming to RISC-V debug spec\n} x_debug_ver_e;\n\n\n//////////////\n// ID stage //\n//////////////\n\n// Operand a selection\ntypedef enum logic[1:0] {\n OP_A_REG_A,\n OP_A_FWD,\n OP_A_CURRPC,\n OP_A_IMM\n} op_a_sel_e;\n\n// Immediate a selection\ntypedef enum logic {\n IMM_A_Z,\n IMM_A_ZERO\n} imm_a_sel_e;\n\n// Operand b selection\ntypedef enum logic {\n OP_B_REG_B,\n OP_B_IMM\n} op_b_sel_e;\n\n// Immediate b selection\ntypedef enum logic [2:0] {\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} imm_b_sel_e;\n\n// Regfile write data selection\ntypedef enum logic [1:0] {\n RF_WD_LSU,\n RF_WD_EX,\n RF_WD_CSR\n} rf_wd_sel_e;\n\n//////////////\n// IF stage //\n//////////////\n\n// PC mux selection\ntypedef enum logic [2:0] {\n PC_BOOT,\n PC_JUMP,\n PC_EXC,\n PC_ERET,\n PC_DRET\n} pc_sel_e;\n\n// Exception PC mux selection\ntypedef enum logic [1:0] {\n EXC_PC_EXC,\n EXC_PC_IRQ,\n EXC_PC_DBD,\n EXC_PC_DBG_EXC // Exception while in debug mode\n} exc_pc_sel_e;\n\n// Exception cause\ntypedef enum logic [5:0] {\n EXC_CAUSE_IRQ_SOFTWARE_M = {1'b1, 5'd03},\n EXC_CAUSE_IRQ_TIMER_M = {1'b1, 5'd07},\n EXC_CAUSE_IRQ_EXTERNAL_M = {1'b1, 5'd11},\n // EXC_CAUSE_IRQ_FAST_0 = {1'b1, 5'd16},\n // EXC_CAUSE_IRQ_FAST_14 = {1'b1, 5'd30},\n EXC_CAUSE_IRQ_NM = {1'b1, 5'd31}, // == EXC_CAUSE_IRQ_FAST_15\n EXC_CAUSE_INSN_ADDR_MISA = {1'b0, 5'd00},\n EXC_CAUSE_ILLEGAL_INSN = {1'b0, 5'd02},\n EXC_CAUSE_BREAKPOINT = {1'b0, 5'd03},\n EXC_CAUSE_LOAD_ACCESS_FAULT = {1'b0, 5'd05},\n EXC_CAUSE_STORE_ACCESS_FAULT = {1'b0, 5'd07},\n EXC_CAUSE_ECALL_MMODE = {1'b0, 5'd11}\n} exc_cause_e;\n\n// Debug cause\ntypedef enum logic [2:0] {\n DBG_CAUSE_NONE = 3'h0,\n DBG_CAUSE_EBREAK = 3'h1,\n DBG_CAUSE_TRIGGER = 3'h2,\n DBG_CAUSE_HALTREQ = 3'h3,\n DBG_CAUSE_STEP = 3'h4\n} dbg_cause_e;\n\n// CSRs\ntypedef enum logic[11:0] {\n // Machine information\n CSR_MHARTID = 12'hF14,\n\n // Machine trap setup\n CSR_MSTATUS = 12'h300,\n CSR_MISA = 12'h301,\n CSR_MIE = 12'h304,\n CSR_MTVEC = 12'h305,\n\n // Machine trap handling\n CSR_MSCRATCH = 12'h340,\n CSR_MEPC = 12'h341,\n CSR_MCAUSE = 12'h342,\n CSR_MTVAL = 12'h343,\n CSR_MIP = 12'h344,\n\n // Debug/trace\n CSR_DCSR = 12'h7b0,\n CSR_DPC = 12'h7b1,\n\n // Debug\n CSR_DSCRATCH0 = 12'h7b2, // optional\n CSR_DSCRATCH1 = 12'h7b3, // optional\n\n // Machine Counter/Timers\n CSR_MCOUNTINHIBIT = 12'h320,\n CSR_MCYCLE = 12'hB00,\n CSR_MCYCLEH = 12'hB80,\n CSR_MINSTRET = 12'hB02,\n CSR_MINSTRETH = 12'hB82\n} csr_num_e;\n\n// CSR mhpmcounter-related offsets and mask\nparameter logic [11:0] CSR_OFF_MCOUNTER_SETUP = 12'h320; // mcounter_setup @ 12'h323 - 12'h33F\nparameter logic [11:0] CSR_OFF_MCOUNTER = 12'hB00; // mcounter @ 12'hB03 - 12'hB1F\nparameter logic [11:0] CSR_OFF_MCOUNTERH = 12'hB80; // mcounterh @ 12'hB83 - 12'hB9F\nparameter logic [11:0] CSR_MASK_MCOUNTER = 12'hFE0;\n\n// CSR interrupt pending/enable bits\nparameter int unsigned CSR_MSIX_BIT = 3;\nparameter int unsigned CSR_MTIX_BIT = 7;\nparameter int unsigned CSR_MEIX_BIT = 11;\nparameter int unsigned CSR_MFIX_BIT_LOW = 16;\nparameter int unsigned CSR_MFIX_BIT_HIGH = 30;\n\nendpackage\n", "selected_doc_paths": ["doc/cs_registers.rst", "doc/debug.rst", "doc/exception_interrupts.rst", "doc/performance_counters.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 286, "lang": "sv", "rtl_files": ["rtl/ibex_cs_registers.sv"], "spec": "# Behavioral Design Specification for `ibex_cs_registers`\n\n## 1. Overview\n\nThe `ibex_cs_registers` module implements the machine‑level Control and Status Registers (CSRs) required by the RISC‑V Privileged Specification, version 1.11. It manages all trap‑related state (interrupts, exceptions, debug), provides the Physical Memory Protection (PMP) register file, and implements the performance counter infrastructure.\n\nThe module acts as the main CSR storage for a single RISC‑V hart. All CSR accesses from the pipeline are handled here. The module also generates interrupt pending signals and exposes critical CSR fields to the rest of the core (e.g., `mtvec`, `mepc`, `mstatus`).\n\n---\n\n## 2. Interface\n\n### Clock and Reset\n- The module operates on a single positive‑edge clock.\n- An asynchronous active‑low reset initialises all state to known values.\n\n### Hart and Privilege\n- A 32‑bit hart ID input is provided for the `mhartid` CSR.\n- The current privilege level is output. The module only ever reports M‑mode (machine mode).\n\n### CSR Access\n- The pipeline requests CSR reads or writes using:\n - An address (12‑bit).\n - Write data (32‑bit).\n - An operation type: read, write, set, or clear.\n- The module supplies read data and a signal indicating an illegal CSR instruction (access to a non‑existing CSR, write to a read‑only CSR, or insufficient privilege).\n\n### Interrupts\n- Five interrupt sources are provided:\n - Software interrupt, timer interrupt, external interrupt, and 15 fast interrupts.\n- The module outputs pending bits for each interrupt type (gated with the respective `mie` enable).\n- A global interrupt pending signal (`irq_pending_o`) is asserted if any unmasked interrupt is high.\n- The `mstatus.MIE` field is output for use by the interrupt controller.\n- The mip CSR is a pure combinational function of the interrupt inputs and the `mie` register.\n\n### Exception and Trap Handling\n- The pipeline signals when a trap (exception or interrupt) must be taken (`csr_save_cause_i`), supplying the exception cause, trap value (`mtval`), and the program counters from IF and ID stages.\n- A separate signal controls whether the trap is a debug event (`debug_csr_save_i`).\n- When a MRET instruction is executed (`csr_restore_mret_i`), the module restores the previous trap state.\n\n### Debug\n- The module is aware of debug mode via an input (`debug_mode_i`). In debug mode, certain CSRs become accessible (dcsr, dpc, dscratch0, dscratch1).\n- A debug cause input is provided when saving debug trap state.\n- Outputs include the debug PC (`depc`), single‑step enable, and `ebreakm` behaviour.\n\n### PMP\n- Physical Memory Protection configuration registers are implemented with configurable number of regions, granularity, and enable flag.\n- The module outputs the PMP configuration and address values (expanded to 34‑bit physical addresses) for use by the PMP checker.\n\n### Performance Counters\n- Several hardware performance monitoring counters are implemented:\n - `mcycle(h)`: cycle counter (always present, 64‑bit).\n - `minstret(h)`: retired instruction counter (always present, 64‑bit).\n - `mhpmcounter3(h)` through `mhpmcounter31(h)`: programmable events counters (optional, configurable number and width).\n- The module receives event signals (e.g., instruction retired, load, store, branch taken) and increments the appropriate counters.\n- An `mcountinhibit` CSR allows software to stop individual counters.\n\n---\n\n## 3. CSR List and Behavioral Description\n\nThe module implements the standard RISC‑V machine‑level CSRs listed below. Unless otherwise noted, all CSRs are only accessible in M‑mode.\n\n| Address | Name | Access | Description |\n|---------|-----------------|---------|-------------|\n| 0x300 | mstatus | WARL | Machine status register |\n| 0x301 | misa | WARL | ISA and extensions (hard‑wired) |\n| 0x304 | mie | WARL | Interrupt enable register |\n| 0x305 | mtvec | WARL | Trap‑vector base address (vectored mode) |\n| 0x320 | mcountinhibit | RW | Counter inhibit register |\n| 0x323..0x33F | mhpmevent3..31 | WARL | Event selectors (hard‑wired read‑only) |\n| 0x340 | mscratch | RW | Scratch register |\n| 0x341 | mepc | WARL | Exception program counter |\n| 0x342 | mcause | WLRL | Exception cause |\n| 0x343 | mtval | WARL | Trap value |\n| 0x344 | mip | R | Interrupt pending (read‑only) |\n| 0x3A0..0x3A3 | pmpcfg0..3 | WARL | PMP configuration (4 regions per CSR) |\n| 0x3B0..0x3BF | pmpaddr0..15 | WARL | PMP address registers |\n| 0x7B0 | dcsr | RW | Debug control and status |\n| 0x7B1 | dpc | RW | Debug PC |\n| 0x7B2 | dscratch0 | RW | Debug scratch 0 |\n| 0x7B3 | dscratch1 | RW | Debug scratch 1 |\n| 0xB00 | mcycle | RW | Lower 32 bits of cycle counter |\n| 0xB02 | minstret | RW | Lower 32 bits of retired instruction counter |\n| 0xB03..0xB1F | mhpmcounter3..31 | WARL | Lower 32 bits of event counters |\n| 0xB80 | mcycleh | RW | Upper 32 bits of cycle counter |\n| 0xB82 | minstreth | RW | Upper 32 bits of retired instruction counter |\n| 0xB83..0xB9F | mhpmcounter3h..31h | WARL | Upper 32 bits of event counters |\n| 0xF14 | mhartid | R | Hardware thread ID (read‑only) |\n\n### 3.1 `mstatus` (Machine Status – 0x300)\n\n- **Fields:**\n - **MIE** (bit 3): Global interrupt enable. When cleared, all interrupts (except NMI) are masked.\n - **MPIE** (bit 7): Previous interrupt enable. Copied from MIE when a trap is taken.\n - **MPP** (bits 12:11): Machine previous privilege. Always reads 2’b11 (M‑mode) and is not modifiable by software.\n- **Behaviour:**\n - On trap entry: MIE is cleared, MPIE ← old MIE, MPP set to M‑mode.\n - On MRET: MIE ← MPIE, MPP and MPIE are restored from internal backup (see §5).\n - Software writes to MIE and MPIE are allowed; MPP writes are ignored.\n\n### 3.2 `misa` (Machine ISA – 0x301)\n\n- **Read‑only, hard‑wired.**\n- Reflects the supported extensions: I (base integer), C (compressed), M (multiply/divide, if `RV32M=1`), and E (embedded, if `RV32E=1`). No other extensions are indicated.\n- The MXL field (bits 31:30) reads 2’b01 (RV32).\n\n### 3.3 `mie` (Machine Interrupt Enable – 0x304)\n\n- **Fields:**\n - MSIE (bit 3): Enable software interrupt.\n - MTIE (bit 7): Enable timer interrupt.\n - MEIE (bit 11): Enable external interrupt.\n - MFIE (bits 30:16): Enable each of the 15 fast interrupts.\n- All bits are WARL and reset to 0.\n\n### 3.4 `mtvec` (Machine Trap‑Vector Base – 0x305)\n\n- **Fields:**\n - **BASE** (bits 31:8): Vector base address. Must be 256‑byte aligned (bits 7:2 forced to zero). Writes to those bits are ignored.\n - **MODE** (bits 1:0): Always reads 2’b01 (vectored mode). Writes to MODE are ignored.\n- The reset value is `0x0000_0001` (BASE=0, MODE=01). On reset, the module may load BASE from an external boot address input.\n\n### 3.5 `mepc` (Machine Exception PC – 0x341)\n\n- On trap save: the current program counter (from either IF or ID stage, selected by pipeline) is written. The least significant bit is forced to 0 (half‑word alignment for the C extension) – writing bit 0 has no effect.\n- On MRET: the restored `mepc` is the one that was saved (no alignment change).\n\n### 3.6 `mcause` (Machine Cause – 0x342)\n\n- **Fields:**\n - **Interrupt** (bit 31): 1 if the trap was caused by an interrupt.\n - **Exception Code** (bits 4:0): The cause code (e.g., 3 for breakpoint, 11 for ECALL).\n- The register is set automatically on trap entry and can be explicitly written.\n\n### 3.7 `mtval` (Machine Trap Value – 0x343)\n\n- **Behaviour:**\n - For instruction access faults: holds the faulting address.\n - For load/store access faults: holds the bad virtual address (with misaligned address if applicable).\n - For illegal instructions: holds the instruction word.\n - For other exceptions: zero.\n- The value is supplied externally via `csr_mtval_i` at trap time.\n\n### 3.8 `mip` (Machine Interrupt Pending – 0x344)\n\n- **Read‑only, combinational.**\n- Each pending bit is the logical AND of the corresponding interrupt input and its enable bit in `mie`.\n- The module outputs separate pending signals (`csr_msip_o`, `csr_mtip_o`, `csr_meip_o`, `csr_mfip_o`) for the pipeline.\n\n### 3.9 `mscratch` (0x340)\n\n- General‑purpose scratch register. Full read/write.\n\n### 3.10 PMP Registers (`pmpcfg0..3`, `pmpaddr0..15`)\n\n- See §7.\n\n### 3.11 Debug Registers (`dcsr`, `dpc`, `dscratch0/1`)\n\n- Accessible only when the core is in debug mode (`debug_mode_i` asserted). Otherwise, accessing them causes an illegal instruction exception.\n- **`dcsr`** (0x7B0):\n - WARL. On write, `xdebugver` is forced to the standard version, `prv` is forced to M‑mode, and certain reserved bits (nmip, mprven, stopcount, stoptime) are forced to zero.\n - Bits `step` and `ebreakm` are used to control single‑stepping and breakpoint behaviour.\n- **`dpc`** (0x7B1):\n - Holds the debug exception PC. On write, if the least significant bit is 0, the value is stored; otherwise the write is ignored (ensuring half‑word alignment).\n- **`dscratch0`** and **`dscratch1`** (0x7B2/3): General‑purpose debug scratch registers.\n\n### 3.12 Performance Counter CSRs (`mcountinhibit`, `mcycle(h)`, `minstret(h)`, `mhpmcounter*`, `mhpmevent*`)\n\n- See §8.\n\n### 3.13 `mhartid` (0xF14)\n\n- **Read‑only.**\n- Returns the external `hart_id_i` input (32‑bit).\n\n---\n\n## 4. CSR Access Protocol\n\nWhen the pipeline requests a CSR operation, the module:\n\n1. Decodes the CSR address to select the target register.\n2. Reads the current value into `csr_rdata_int`.\n3. Determines if the access is legal:\n - No illegal address decoding error.\n - No write attempt to a read‑only CSR (address bits 11:10 = 2’b11).\n - Sufficient privilege (only M‑mode is supported, so always legal).\n4. Based on the operation type:\n - **Read**: return the read value; no modification.\n - **Write**: apply the supplied write data directly.\n - **Set**: bitwise OR the read value with write data.\n - **Clear**: bitwise AND the read value with the complement of write data.\n5. The effective write is only performed when:\n - The operation is not a read.\n - The access is legal.\n - A new instruction is present in the ID stage (`instr_new_id_i` asserted for one cycle). This ensures each CSR write is executed exactly once per instruction.\n6. The read data is provided on the same cycle as `csr_access_i`; the write update takes effect on the next clock edge.\n\n---\n\n## 5. Trap Handling (Exceptions and Interrupts)\n\n### 5.1 Trap Entry\n\nWhen the pipeline asserts `csr_save_cause_i`:\n\n1. The trap program counter is selected from either the IF or ID stage PC (as indicated by `csr_save_if_i` / `csr_save_id_i`).\n2. If the trap is **not** a debug event (`debug_csr_save_i = 0`):\n - `mepc` ← trap PC.\n - `mcause` ← exception cause (from `csr_mcause_i`). The interrupt bit is set if the cause corresponds to an interrupt.\n - `mtval` ← supplied trap value.\n - `mstatus.MIE` ← 0 (disable interrupts).\n - `mstatus.MPIE` ← old `mstatus.MIE` (save previous enable).\n - `mstatus.MPP` ← M‑mode.\n - Internal backup registers (`mstack`) are updated: `mstack.MPIE` ← `mstatus.MPIE`, `mstack.MPP` ← `mstatus.MPP`, `mstack_epc` ← old `mepc`, `mstack_cause` ← old `mcause`. This allows recovery from a non‑maskable interrupt (NMI) occurring inside a trap handler.\n3. If the trap is a **debug event** (`debug_csr_save_i = 1`):\n - Only the debug CSRs are updated:\n - `dcsr.cause` ← debug cause input.\n - `dcsr.prv` ← M‑mode.\n - `dpc` ← trap PC.\n - The standard machine CSRs (`mepc`, `mcause`, `mtval`, `mstatus`) are **not** modified.\n\n### 5.2 Trap Return (MRET)\n\nWhen the pipeline asserts `csr_restore_mret_i`:\n\n1. `mstatus.MIE` ← `mstatus.MPIE` (restore the previous interrupt enable).\n2. `mstatus.MPIE` ← `mstack.MPIE` (restore the backup MPIE).\n3. `mstatus.MPP` ← `mstack.MPP` (restore the backup MPP).\n4. `mepc` ← `mstack_epc`.\n5. `mcause` ← `mstack_cause`.\n\nThis design ensures that a nested trap (e.g., NMI during an exception handler) does not lose the original context.\n\n---\n\n## 6. Debug Mode Behaviour\n\n- When `debug_mode_i` is high, the module suppresses all interrupt arbitration: no interrupts are taken (including NMI). The `mip` pending outputs may still be asserted, but the core will not take them.\n- The debug CSRs (`dcsr`, `dpc`, `dscratch0/1`) are only visible and writable in debug mode. If accessed outside debug mode, an illegal instruction exception is signalled.\n- The `debug_single_step_o` output reflects `dcsr.step`.\n- The `debug_ebreakm_o` output reflects `dcsr.ebreakm`.\n\n---\n\n## 7. Physical Memory Protection (PMP)\n\n### 7.1 Configuration Parameters\n\n- **PMPEnable**: When 0, all PMP registers read as zero and the outputs are tied to zero. No PMP logic is instantiated.\n- **PMPNumRegions**: Number of regions (1..16). Each region has a cfg and an addr register.\n- **PMPGranularity**: Minimum region size = 2^(G+2) bytes. When G > 0, NA4 mode (previously used for 4‑byte regions) is treated as OFF; bits [G-1:0] of address registers are masked appropriately in read data.\n\n### 7.2 PMP Configuration Registers (`pmpcfg0..3`)\n\n- Each 32‑bit register holds 4 configuration bytes (one per region).\n- Each byte contains:\n - Bit 7: Lock (L). When set, the configuration and address of that region are locked (no further writes allowed).\n - Bits 6‑5: Reserved (read as zero).\n - Bits 4‑3: Mode (OFF, TOR, NA4/NAPOT).\n - Bit 2: Execute permission (X).\n - Bit 1: Write permission (W). The combination W=1, R=0 is illegal and forces W=0.\n - Bit 0: Read permission (R).\n- Mode encoding: 00=OFF, 01=TOR, 10=NA4 (or OFF if G>0), 11=NAPOT.\n\n### 7.3 PMP Address Registers (`pmpaddr0..15`)\n\n- Holds bits [33:2] of the physical address (for RV32, the full address). On reads, some low bits may be forced to 0 or 1 depending on granularity and mode.\n- The address register is writable only if the lock bit of the corresponding cfg is not set. For region i, the write is also inhibited if region i+1 is in TOR mode (address sharing).\n\n### 7.4 Outputs\n\n- The module outputs the PMP configuration (lock, mode, X, W, R) and the 34‑bit address (with two trailing zeros) for each implemented region. These are used by the PMP checker in the instruction fetch and load‑store units.\n\n---\n\n## 8. Performance Counters\n\n### 8.1 Counter Architecture\n\n- **Fixed counters** (always present, 64‑bit):\n - `mcycle(h)`: Increments every cycle.\n - `minstret(h)`: Increments on each instruction retirement (`instr_ret_i`).\n- **Event counters** (optional, configurable number `MHPMCounterNum`, width `MHPMCounterWidth`):\n - `mhpmcounter3`..`mhpmcounter(2+MHPMCounterNum)`.\n - Each event counter is associated with a hard‑wired event via the corresponding `mhpmevent` register (read‑only). The event selectors are tied to a single bit (the bit index equal to the event ID). For example, `mhpmcounter3` counts cycles where the LSU is busy, `mhpmcounter4` counts cycles waiting for instruction fetches, etc.\n - Unused counters (beyond `2+MHPMCounterNum`) read as zero and are not incremented.\n\n### 8.2 Counter Control\n\n- `mcountinhibit` CSR (0x320):\n - Bit 0: inhibit `mcycle`.\n - Bit 1: always 0 (reserved).\n - Bit 2: inhibit `minstret`.\n - Bits 3..31: inhibit respective event counters.\n- Bits above the number of implemented counters are force‑tied to 1 (i.e., those counters are always inhibited).\n- When a counter is inhibited, it does not increment but can still be written by software.\n\n### 8.3 Counter Reads and Writes\n\n- The lower 32 bits are read from the base address (e.g., `mcycle`), the upper 32 bits from the `h` address (e.g., `mcycleh`).\n- Writes to the lower half affect only the lower 32 bits; writes to the upper half affect only the upper 32 bits.\n- All counter bits that are beyond the configured width are masked to zero when written and when read.\n\n### 8.4 Events\n\nThe module receives external event signals (e.g., instruction retired, load, store, branch, jump) and uses them to increment the appropriate counters. A detailed mapping of events to counter indices is given in the performance counters documentation.\n\n---\n\n## 9. Reset Behaviour\n\nUpon reset (`rst_ni` deasserted):\n\n- `mstatus`: MIE=0, MPIE=0, MPP=M.\n- `mie`, `mscratch`, `mepc`, `mcause`, `mtval`, `mcountinhibit`, all counter registers: zero.\n- `mtvec`: 32’h0000_0001 (BASE=0, MODE=01). If `csr_mtvec_init_i` is asserted during reset, BASE is loaded from `boot_addr_i[31:8]` with bits [7:2] forced to zero.\n- `dcsr`: xdebugver=STD, cause=none, prv=M, all other bits zero.\n- `dpc`, `dscratch0/1`, `mstack` registers: zero.\n- All PMP registers: zero.\n- Counter and event selector hardware state: zero.\n\n---\n\n## 10. Illegal Instruction Detection\n\nThe module asserts `illegal_csr_insn_o` if any of the following conditions hold:\n\n- The CSR address does not correspond to a known CSR.\n- The operation is a write to a read‑only CSR (address bits 11:10 = 2’b11).\n- The CSR is a debug CSR and the core is not in debug mode.\n- The CSR is a performance counter/reserved address that does not exist (e.g., accessing a counter number above the implemented number, or accessing `mhpmcounter1`).\n\nThe pipeline uses this signal to raise an illegal instruction exception.\n\n---\n\n## 11. Additional Outputs\n\n- `csr_mtvec_o`: Current value of `mtvec` (used for trap vector address calculation).\n- `csr_mepc_o`: Current value of `mepc` (used for MRET).\n- `csr_depc_o`: Current value of `dpc` (used for debug exit).\n- `csr_mstatus_mie_o`: Value of MIE bit (used for interrupt arbitration).\n- `irq_pending_o`: OR of all unmasked interrupt pending bits.\n\n---\n\n*This specification describes the required external behaviour of the `ibex_cs_registers` module. All internal implementation details are deliberately omitted.*", "commit_id": "16177fe8db9012197c150d7487428437e020eaa6", "timestamp": "2019-09-06T14:32:16+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "1162b995fa5c75c222a0aa6a48fa746e6ceb0249", "pr_title": "CSRs: reset `dcsr.XDEBUGVER` to `XDEBUGVER_STD` instead of 0", "pr_body": "This field is read only and should be set to the right value straight away.\r\n\r\nThis fixes lowRISC/ibex#285.", "issue_title": "Dcsr.xdebugver reset value", "issue_body": "Hi all,\r\nI noticed that in the CSR register module, `dcsr.xdebugver` is set to `XDEBUGVER_NO` upon reset, but after reset is over and an explicit write to `dcsr` occurs, the `xdebugver` field will then be permanently set to the value of `XDEBUGVER_STD` for the duration of the simulation. This seems to contradict with the behavior of the `dcsr.prv` field, which is set to `PRV_LVL_M` at reset, as well as whenever a write occurs outside of reset. Why does this separate reset behavior for `xdebugver` occur, instead of setting it to `XDEBUGVER_STD` from reset onwards especially since this field is read-only and stays as a constant?\r\nThank you!\r\nUdi", "commit_message": "CSRs: reset `dcsr.XDEBUGVER` to `XDEBUGVER_STD` instead of 0\n\nThis field is read only and should be set to the right value straight\naway.\n\nThis fixes lowRISC/ibex#285.", "fix_patch": "diff --git a/rtl/ibex_cs_registers.sv b/rtl/ibex_cs_registers.sv\nindex f65ab51c9a..d7763df226 100644\n--- a/rtl/ibex_cs_registers.sv\n+++ b/rtl/ibex_cs_registers.sv\n@@ -596,7 +596,7 @@ module ibex_cs_registers #(\n mtval_q <= '0;\n mtvec_q <= 32'b01;\n dcsr_q <= '{\n- xdebugver: XDEBUGVER_NO, // 4'h0\n+ xdebugver: XDEBUGVER_STD,\n cause: DBG_CAUSE_NONE, // 3'h0\n prv: PRIV_LVL_M,\n default: '0\n", "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 * Control and Status Registers\n *\n * Control and Status Registers (CSRs) following the RISC-V Privileged\n * Specification, draft version 1.11\n */\nmodule ibex_cs_registers #(\n parameter int unsigned MHPMCounterNum = 8,\n parameter int unsigned MHPMCounterWidth = 40,\n parameter bit PMPEnable = 0,\n parameter int unsigned PMPGranularity = 0,\n parameter int unsigned PMPNumRegions = 4,\n parameter bit RV32E = 0,\n parameter bit RV32M = 0\n) (\n // Clock and Reset\n input logic clk_i,\n input logic rst_ni,\n\n // Hart ID\n input logic [31:0] hart_id_i,\n output ibex_pkg::priv_lvl_e priv_mode_o,\n\n // mtvec\n output logic [31:0] csr_mtvec_o,\n input logic csr_mtvec_init_i,\n input logic [31:0] boot_addr_i,\n\n // Interface to registers (SRAM like)\n input logic csr_access_i,\n input ibex_pkg::csr_num_e csr_addr_i,\n input logic [31:0] csr_wdata_i,\n input ibex_pkg::csr_op_e csr_op_i,\n output logic [31:0] csr_rdata_o,\n\n // interrupts\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 output logic irq_pending_o, // interupt request pending\n output logic csr_msip_o, // software interrupt pending\n output logic csr_mtip_o, // timer interrupt pending\n output logic csr_meip_o, // external interrupt pending\n output logic [14:0] csr_mfip_o, // fast interrupt pending\n output logic csr_mstatus_mie_o,\n output logic [31:0] csr_mepc_o,\n\n // PMP\n output ibex_pkg::pmp_cfg_t csr_pmp_cfg_o [PMPNumRegions],\n output logic [33:0] csr_pmp_addr_o [PMPNumRegions],\n\n // debug\n input logic debug_mode_i,\n input ibex_pkg::dbg_cause_e debug_cause_i,\n input logic debug_csr_save_i,\n output logic [31:0] csr_depc_o,\n output logic debug_single_step_o,\n output logic debug_ebreakm_o,\n\n input logic [31:0] pc_if_i,\n input logic [31:0] pc_id_i,\n\n input logic csr_save_if_i,\n input logic csr_save_id_i,\n input logic csr_restore_mret_i,\n input logic csr_save_cause_i,\n input ibex_pkg::exc_cause_e csr_mcause_i,\n input logic [31:0] csr_mtval_i,\n output logic illegal_csr_insn_o, // access to non-existent CSR,\n // with wrong priviledge level, or\n // missing write permissions\n input logic instr_new_id_i, // ID stage sees a new instr\n\n // Performance Counters\n input logic instr_ret_i, // instr retired in ID/EX stage\n input logic instr_ret_compressed_i, // compressed instr retired\n input logic imiss_i, // instr fetch\n input logic pc_set_i, // PC was set to a new value\n input logic jump_i, // jump instr seen (j, jr, jal, jalr)\n input logic branch_i, // branch instr seen (bf, bnf)\n input logic branch_taken_i, // branch was taken\n input logic mem_load_i, // load from memory in this cycle\n input logic mem_store_i, // store to memory in this cycle\n input logic lsu_busy_i\n);\n\n import ibex_pkg::*;\n\n // misa\n localparam logic [1:0] MXL = 2'd1; // M-XLEN: XLEN in M-Mode for RV32\n localparam logic [31:0] MISA_VALUE =\n (0 << 0) // A - Atomic Instructions extension\n | (1 << 2) // C - Compressed extension\n | (0 << 3) // D - Double precision floating-point extension\n | (32'(RV32E) << 4) // E - RV32E base ISA\n | (0 << 5) // F - Single precision floating-point extension\n | (1 << 8) // I - RV32I/64I/128I base ISA\n | (32'(RV32M) << 12) // M - Integer Multiply/Divide extension\n | (0 << 13) // N - User level interrupts supported\n | (0 << 18) // S - Supervisor mode implemented\n | (0 << 20) // U - User mode implemented\n | (0 << 23) // X - Non-standard extensions present\n | (32'(MXL) << 30); // M-XLEN\n\n typedef struct packed {\n logic mie;\n logic mpie;\n priv_lvl_e mpp;\n } Status_t;\n\n // struct for mip/mie CSRs\n typedef struct packed {\n logic irq_software;\n logic irq_timer;\n logic irq_external;\n logic [14:0] irq_fast; // 15 fast interrupts,\n // one interrupt is reserved for NMI (not visible through mip/mie)\n } Interrupts_t;\n\n typedef struct packed {\n x_debug_ver_e xdebugver;\n logic [11:0] zero2;\n logic ebreakm;\n logic zero1;\n logic ebreaks;\n logic ebreaku;\n logic stepie;\n logic stopcount;\n logic stoptime;\n dbg_cause_e cause;\n logic zero0;\n logic mprven;\n logic nmip;\n logic step;\n priv_lvl_e prv;\n } Dcsr_t;\n\n // Interrupt and exception control signals\n logic [31:0] exception_pc;\n\n // CSRs\n Status_t mstatus_q, mstatus_d;\n Interrupts_t mie_q, mie_d;\n logic [31:0] mscratch_q, mscratch_d;\n logic [31:0] mepc_q, mepc_d;\n logic [5:0] mcause_q, mcause_d;\n logic [31:0] mtval_q, mtval_d;\n logic [31:0] mtvec_q, mtvec_d;\n Interrupts_t mip;\n Dcsr_t dcsr_q, dcsr_d;\n logic [31:0] depc_q, depc_d;\n logic [31:0] dscratch0_q, dscratch0_d;\n logic [31:0] dscratch1_q, dscratch1_d;\n\n // CSRs for recoverable NMIs\n // NOTE: these CSRS are nonstandard, see https://github.com/riscv/riscv-isa-manual/issues/261\n Status_t mstack_q, mstack_d;\n logic [31:0] mstack_epc_q, mstack_epc_d;\n logic [5:0] mstack_cause_q, mstack_cause_d;\n\n // PMP Signals\n logic [31:0] pmp_addr_rdata [PMP_MAX_REGIONS];\n logic [PMP_CFG_W-1:0] pmp_cfg_rdata [PMP_MAX_REGIONS];\n\n // Hardware performance monitor signals\n logic [31:0] mcountinhibit_d, mcountinhibit_q, mcountinhibit;\n logic [31:0] mcountinhibit_force;\n logic mcountinhibit_we;\n logic [63:0] mhpmcounter_mask [32];\n logic [63:0] mhpmcounter_d [32];\n logic [63:0] mhpmcounter_q [32];\n logic [31:0] mhpmcounter_we;\n logic [31:0] mhpmcounterh_we;\n logic [31:0] mhpmcounter_incr;\n logic [31:0] mhpmevent [32];\n logic [4:0] mhpmcounter_idx;\n\n // CSR update logic\n logic [31:0] csr_wdata_int;\n logic [31:0] csr_rdata_int;\n logic csr_we_int;\n logic csr_wreq;\n\n // Access violation signals\n logic illegal_csr;\n logic illegal_csr_priv;\n logic illegal_csr_write;\n\n logic [7:0] unused_boot_addr;\n\n assign unused_boot_addr = boot_addr_i[7:0];\n\n /////////////\n // CSR reg //\n /////////////\n\n logic [$bits(csr_num_e)-1:0] csr_addr;\n assign csr_addr = {csr_addr_i};\n assign mhpmcounter_idx = csr_addr[4:0];\n\n assign illegal_csr_priv = 1'b0; // we only support M-mode\n assign illegal_csr_write = (csr_addr[11:10] == 2'b11) && csr_wreq;\n assign illegal_csr_insn_o = illegal_csr | illegal_csr_write | illegal_csr_priv;\n\n // mip CSR is purely combintational - must be able to re-enable the clock upon WFI\n assign mip.irq_software = irq_software_i & mie_q.irq_software;\n assign mip.irq_timer = irq_timer_i & mie_q.irq_timer;\n assign mip.irq_external = irq_external_i & mie_q.irq_external;\n assign mip.irq_fast = irq_fast_i & mie_q.irq_fast;\n\n // read logic\n always_comb begin\n csr_rdata_int = '0;\n illegal_csr = 1'b0;\n\n unique case (csr_addr_i)\n // mhartid: unique hardware thread id\n CSR_MHARTID: csr_rdata_int = hart_id_i;\n\n // mstatus: always M-mode, contains IE bit\n CSR_MSTATUS: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSTATUS_MIE_BIT] = mstatus_q.mie;\n csr_rdata_int[CSR_MSTATUS_MPIE_BIT] = mstatus_q.mpie;\n csr_rdata_int[CSR_MSTATUS_MPP_BIT_HIGH:CSR_MSTATUS_MPP_BIT_LOW] = mstatus_q.mpp;\n end\n\n // misa\n CSR_MISA: csr_rdata_int = MISA_VALUE;\n\n // interrupt enable\n CSR_MIE: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mie_q.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mie_q.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mie_q.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mie_q.irq_fast;\n end\n\n CSR_MSCRATCH: csr_rdata_int = mscratch_q;\n\n // mtvec: trap-vector base address\n CSR_MTVEC: csr_rdata_int = mtvec_q;\n\n // mepc: exception program counter\n CSR_MEPC: csr_rdata_int = mepc_q;\n\n // mcause: exception cause\n CSR_MCAUSE: csr_rdata_int = {mcause_q[5], 26'b0, mcause_q[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: csr_rdata_int = mtval_q;\n\n // mip: interrupt pending\n CSR_MIP: begin\n csr_rdata_int = '0;\n csr_rdata_int[CSR_MSIX_BIT] = mip.irq_software;\n csr_rdata_int[CSR_MTIX_BIT] = mip.irq_timer;\n csr_rdata_int[CSR_MEIX_BIT] = mip.irq_external;\n csr_rdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW] = mip.irq_fast;\n end\n\n // PMP registers\n CSR_PMPCFG0: csr_rdata_int = {pmp_cfg_rdata[3], pmp_cfg_rdata[2],\n pmp_cfg_rdata[1], pmp_cfg_rdata[0]};\n CSR_PMPCFG1: csr_rdata_int = {pmp_cfg_rdata[7], pmp_cfg_rdata[6],\n pmp_cfg_rdata[5], pmp_cfg_rdata[4]};\n CSR_PMPCFG2: csr_rdata_int = {pmp_cfg_rdata[11], pmp_cfg_rdata[10],\n pmp_cfg_rdata[9], pmp_cfg_rdata[8]};\n CSR_PMPCFG3: csr_rdata_int = {pmp_cfg_rdata[15], pmp_cfg_rdata[14],\n pmp_cfg_rdata[13], pmp_cfg_rdata[12]};\n CSR_PMPADDR0: csr_rdata_int = pmp_addr_rdata[0];\n CSR_PMPADDR1: csr_rdata_int = pmp_addr_rdata[1];\n CSR_PMPADDR2: csr_rdata_int = pmp_addr_rdata[2];\n CSR_PMPADDR3: csr_rdata_int = pmp_addr_rdata[3];\n CSR_PMPADDR4: csr_rdata_int = pmp_addr_rdata[4];\n CSR_PMPADDR5: csr_rdata_int = pmp_addr_rdata[5];\n CSR_PMPADDR6: csr_rdata_int = pmp_addr_rdata[6];\n CSR_PMPADDR7: csr_rdata_int = pmp_addr_rdata[7];\n CSR_PMPADDR8: csr_rdata_int = pmp_addr_rdata[8];\n CSR_PMPADDR9: csr_rdata_int = pmp_addr_rdata[9];\n CSR_PMPADDR10: csr_rdata_int = pmp_addr_rdata[10];\n CSR_PMPADDR11: csr_rdata_int = pmp_addr_rdata[11];\n CSR_PMPADDR12: csr_rdata_int = pmp_addr_rdata[12];\n CSR_PMPADDR13: csr_rdata_int = pmp_addr_rdata[13];\n CSR_PMPADDR14: csr_rdata_int = pmp_addr_rdata[14];\n CSR_PMPADDR15: csr_rdata_int = pmp_addr_rdata[15];\n\n CSR_DCSR: begin\n csr_rdata_int = dcsr_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DPC: begin\n csr_rdata_int = depc_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH0: begin\n csr_rdata_int = dscratch0_q;\n illegal_csr = ~debug_mode_i;\n end\n CSR_DSCRATCH1: begin\n csr_rdata_int = dscratch1_q;\n illegal_csr = ~debug_mode_i;\n end\n\n // machine counter/timers\n CSR_MCOUNTINHIBIT: csr_rdata_int = mcountinhibit;\n CSR_MCYCLE: csr_rdata_int = mhpmcounter_q[0][31: 0];\n CSR_MCYCLEH: csr_rdata_int = mhpmcounter_q[0][63:32];\n CSR_MINSTRET: csr_rdata_int = mhpmcounter_q[2][31: 0];\n CSR_MINSTRETH: csr_rdata_int = mhpmcounter_q[2][63:32];\n\n default: begin\n if ((csr_addr & CSR_MASK_MCOUNTER) == CSR_OFF_MCOUNTER_SETUP) begin\n csr_rdata_int = mhpmevent[mhpmcounter_idx];\n // check access to non-existent or already covered CSRs\n if ((csr_addr[4:0] == 5'b00000) || // CSR_MCOUNTINHIBIT\n (csr_addr[4:0] == 5'b00001) ||\n (csr_addr[4:0] == 5'b00010)) begin\n illegal_csr = csr_access_i;\n end\n\n end else if ((csr_addr & CSR_MASK_MCOUNTER) == CSR_OFF_MCOUNTER) begin\n csr_rdata_int = mhpmcounter_q[mhpmcounter_idx][31: 0];\n // check access to non-existent or already covered CSRs\n if ((csr_addr[4:0] == 5'b00000) || // CSR_MCYCLE\n (csr_addr[4:0] == 5'b00001) ||\n (csr_addr[4:0] == 5'b00010)) begin // CSR_MINSTRET\n illegal_csr = csr_access_i;\n end\n\n end else if ((csr_addr & CSR_MASK_MCOUNTER) == CSR_OFF_MCOUNTERH) begin\n csr_rdata_int = mhpmcounter_q[mhpmcounter_idx][63:32];\n // check access to non-existent or already covered CSRs\n if ((csr_addr[4:0] == 5'b00000) || // CSR_MCYCLEH\n (csr_addr[4:0] == 5'b00001) ||\n (csr_addr[4:0] == 5'b00010)) begin // CSR_MINSTRETH\n illegal_csr = csr_access_i;\n end\n end else begin\n illegal_csr = csr_access_i;\n end\n end\n endcase\n end\n\n // write logic\n always_comb begin\n exception_pc = pc_id_i;\n\n mstatus_d = mstatus_q;\n mie_d = mie_q;\n mscratch_d = mscratch_q;\n mepc_d = mepc_q;\n mcause_d = mcause_q;\n mtval_d = mtval_q;\n mtvec_d = csr_mtvec_init_i ? {boot_addr_i[31:8], 6'b0, 2'b01} : mtvec_q;\n dcsr_d = dcsr_q;\n depc_d = depc_q;\n dscratch0_d = dscratch0_q;\n dscratch1_d = dscratch1_q;\n\n mstack_d = mstack_q;\n mstack_epc_d = mstack_epc_q;\n mstack_cause_d = mstack_cause_q;\n\n mcountinhibit_we = 1'b0;\n mhpmcounter_we = '0;\n mhpmcounterh_we = '0;\n\n unique case (csr_addr_i)\n // mstatus: IE bit\n CSR_MSTATUS: begin\n if (csr_we_int) begin\n mstatus_d = '{\n mie: csr_wdata_int[CSR_MSTATUS_MIE_BIT],\n mpie: csr_wdata_int[CSR_MSTATUS_MPIE_BIT],\n mpp: PRIV_LVL_M\n };\n end\n end\n\n // interrupt enable\n CSR_MIE: begin\n if (csr_we_int) begin\n mie_d.irq_software = csr_wdata_int[CSR_MSIX_BIT];\n mie_d.irq_timer = csr_wdata_int[CSR_MTIX_BIT];\n mie_d.irq_external = csr_wdata_int[CSR_MEIX_BIT];\n mie_d.irq_fast = csr_wdata_int[CSR_MFIX_BIT_HIGH:CSR_MFIX_BIT_LOW];\n end\n end\n\n CSR_MSCRATCH: if (csr_we_int) mscratch_d = csr_wdata_int;\n\n // mepc: exception program counter\n CSR_MEPC: if (csr_we_int) mepc_d = {csr_wdata_int[31:1], 1'b0};\n\n // mcause\n CSR_MCAUSE: if (csr_we_int) mcause_d = {csr_wdata_int[31], csr_wdata_int[4:0]};\n\n // mtval: trap value\n CSR_MTVAL: if (csr_we_int) mtval_d = csr_wdata_int;\n\n // mtvec\n // mtvec.MODE set to vectored\n // mtvec.BASE must be 256-byte aligned\n CSR_MTVEC: if (csr_we_int) mtvec_d = {csr_wdata_int[31:8], 6'b0, 2'b01};\n\n CSR_DCSR: begin\n if (csr_we_int) begin\n dcsr_d = csr_wdata_int;\n dcsr_d.xdebugver = XDEBUGVER_STD;\n dcsr_d.prv = PRIV_LVL_M; // only M-mode is supported\n\n // currently not supported:\n dcsr_d.nmip = 1'b0;\n dcsr_d.mprven = 1'b0;\n dcsr_d.stopcount = 1'b0;\n dcsr_d.stoptime = 1'b0;\n\n // forced to be zero\n dcsr_d.zero0 = 1'b0;\n dcsr_d.zero1 = 1'b0;\n dcsr_d.zero2 = 12'h0;\n end\n end\n\n CSR_DPC: begin\n // Only valid PC addresses are allowed (half-word aligned with C ext.)\n if (csr_we_int && csr_wdata_int[0] == 1'b0) begin\n depc_d = csr_wdata_int;\n end\n end\n\n CSR_DSCRATCH0: begin\n if (csr_we_int) begin\n dscratch0_d = csr_wdata_int;\n end\n end\n\n CSR_DSCRATCH1: begin\n if (csr_we_int) begin\n dscratch1_d = csr_wdata_int;\n end\n end\n\n CSR_MCOUNTINHIBIT: begin\n if (csr_we_int) begin\n mcountinhibit_we = 1'b1;\n end\n end\n\n CSR_MCYCLE: begin\n if (csr_we_int) begin\n mhpmcounter_we[0] = 1'b1;\n end\n end\n\n CSR_MCYCLEH: begin\n if (csr_we_int) begin\n mhpmcounterh_we[0] = 1'b1;\n end\n end\n\n CSR_MINSTRET: begin\n if (csr_we_int) begin\n mhpmcounter_we[2] = 1'b1;\n end\n end\n\n CSR_MINSTRETH: begin\n if (csr_we_int) begin\n mhpmcounterh_we[2] = 1'b1;\n end\n end\n\n default: begin\n if (csr_we_int == 1'b1) begin\n // performance counters and event selector\n if ((csr_addr & CSR_MASK_MCOUNTER) == CSR_OFF_MCOUNTER) begin\n mhpmcounter_we[mhpmcounter_idx] = 1'b1;\n end else if ((csr_addr & CSR_MASK_MCOUNTER) == CSR_OFF_MCOUNTERH) begin\n mhpmcounterh_we[mhpmcounter_idx] = 1'b1;\n end\n end\n end\n endcase\n\n // exception controller gets priority over other writes\n unique case (1'b1)\n\n csr_save_cause_i: begin\n unique case (1'b1)\n csr_save_if_i: begin\n exception_pc = pc_if_i;\n end\n csr_save_id_i: begin\n exception_pc = pc_id_i;\n end\n default:;\n endcase\n\n if (debug_csr_save_i) begin\n // all interrupts are masked\n // do not update cause, epc, tval, epc and status\n dcsr_d.prv = PRIV_LVL_M;\n dcsr_d.cause = debug_cause_i;\n depc_d = exception_pc;\n end else begin\n mtval_d = csr_mtval_i;\n mstatus_d.mie = 1'b0; // disable interrupts\n // save current status\n mstatus_d.mpie = mstatus_q.mie;\n mstatus_d.mpp = PRIV_LVL_M;\n mepc_d = exception_pc;\n mcause_d = {csr_mcause_i};\n // save previous status for recoverable NMI\n mstack_d.mpie = mstatus_q.mpie;\n mstack_d.mpp = mstatus_q.mpp;\n mstack_epc_d = mepc_q;\n mstack_cause_d = mcause_q;\n end\n end // csr_save_cause_i\n\n csr_restore_mret_i: begin // MRET\n mstatus_d.mie = mstatus_q.mpie; // re-enable interrupts\n // restore previous status for recoverable NMI\n mstatus_d.mpie = mstack_q.mpie;\n mstatus_d.mpp = mstack_q.mpp;\n mepc_d = mstack_epc_q;\n mcause_d = mstack_cause_q;\n end // csr_restore_mret_i\n\n default:;\n endcase\n end\n\n // CSR operation logic\n always_comb begin\n csr_wreq = 1'b1;\n\n unique case (csr_op_i)\n CSR_OP_WRITE: csr_wdata_int = csr_wdata_i;\n CSR_OP_SET: csr_wdata_int = csr_wdata_i | csr_rdata_o;\n CSR_OP_CLEAR: csr_wdata_int = ~csr_wdata_i & csr_rdata_o;\n CSR_OP_READ: begin\n csr_wdata_int = csr_wdata_i;\n csr_wreq = 1'b0;\n end\n default: begin\n csr_wdata_int = 'X;\n csr_wreq = 1'bX;\n end\n endcase\n end\n\n // only write CSRs during one clock cycle\n assign csr_we_int = csr_wreq & ~illegal_csr_priv & instr_new_id_i;\n\n assign csr_rdata_o = csr_rdata_int;\n\n // directly output some registers\n assign csr_msip_o = mip.irq_software;\n assign csr_mtip_o = mip.irq_timer;\n assign csr_meip_o = mip.irq_external;\n assign csr_mfip_o = mip.irq_fast;\n\n assign csr_mepc_o = mepc_q;\n assign csr_depc_o = depc_q;\n assign csr_mtvec_o = mtvec_q;\n\n assign csr_mstatus_mie_o = mstatus_q.mie;\n assign debug_single_step_o = dcsr_q.step;\n assign debug_ebreakm_o = dcsr_q.ebreakm;\n\n assign irq_pending_o = csr_msip_o | csr_mtip_o | csr_meip_o | (|csr_mfip_o);\n\n // actual registers\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n mstatus_q <= '{\n mie: 1'b0,\n mpie: 1'b0,\n mpp: PRIV_LVL_M\n };\n mie_q <= '0;\n mscratch_q <= '0;\n mepc_q <= '0;\n mcause_q <= '0;\n mtval_q <= '0;\n mtvec_q <= 32'b01;\n dcsr_q <= '{\n xdebugver: XDEBUGVER_STD,\n cause: DBG_CAUSE_NONE, // 3'h0\n prv: PRIV_LVL_M,\n default: '0\n };\n depc_q <= '0;\n dscratch0_q <= '0;\n dscratch1_q <= '0;\n\n mstack_q <= '{\n mie: 1'b0,\n mpie: 1'b0,\n mpp: PRIV_LVL_M\n };\n mstack_epc_q <= '0;\n mstack_cause_q <= '0;\n\n end else begin\n // update CSRs\n mstatus_q <= mstatus_d;\n mie_q <= mie_d;\n mscratch_q <= mscratch_d;\n mepc_q <= mepc_d;\n mcause_q <= mcause_d;\n mtval_q <= mtval_d;\n mtvec_q <= mtvec_d;\n dcsr_q <= dcsr_d;\n depc_q <= depc_d;\n dscratch0_q <= dscratch0_d;\n dscratch1_q <= dscratch1_d;\n\n mstack_q <= mstack_d;\n mstack_epc_q <= mstack_epc_d;\n mstack_cause_q <= mstack_cause_d;\n\n end\n end\n\n assign priv_mode_o = mstatus_q.mpp;\n\n // -----------------\n // PMP registers\n // -----------------\n\n if (PMPEnable) begin : g_pmp_registers\n pmp_cfg_t pmp_cfg [PMPNumRegions];\n pmp_cfg_t pmp_cfg_wdata [PMPNumRegions];\n logic [31:0] pmp_addr [PMPNumRegions];\n logic [PMPNumRegions-1:0] pmp_cfg_we;\n logic [PMPNumRegions-1:0] pmp_addr_we;\n\n // Expanded / qualified register read data\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_exp_rd_data\n if (i < PMPNumRegions) begin : g_implemented_regions\n // Add in zero padding for reserved fields\n assign pmp_cfg_rdata[i] = {pmp_cfg[i].lock, 2'b00, pmp_cfg[i].mode,\n pmp_cfg[i].exec, pmp_cfg[i].write, pmp_cfg[i].read};\n\n // Address field read data depends on the current programmed mode and the granularity\n // See RISC-V Privileged Specification, version 1.11, Section 3.6.1\n if (PMPGranularity == 0) begin : g_pmp_g0\n // If G == 0, read data is unmodified\n assign pmp_addr_rdata[i] = pmp_addr[i];\n\n end else if (PMPGranularity == 1) begin : g_pmp_g1\n // If G == 1, bit [G-1] reads as zero in TOR or OFF mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end\n end\n\n end else begin\n // For G >= 2, bits are masked to one or zero depending on the mode\n always_comb begin\n pmp_addr_rdata[i] = pmp_addr[i];\n if ((pmp_cfg[i].mode == PMP_MODE_OFF) || (pmp_cfg[i].mode == PMP_MODE_TOR)) begin\n // In TOR or OFF mode, bits [G-1:0] must read as zero\n pmp_addr_rdata[i][PMPGranularity-1:0] = '0;\n end else if (pmp_cfg[i].mode == PMP_MODE_NAPOT) begin\n // In NAPOT mode, bits [G-2:0] must read as one\n pmp_addr_rdata[i][PMPGranularity-2:0] = '1;\n end\n end\n end\n\n end else begin : g_other_regions\n // Non-implemented regions read as zero\n assign pmp_cfg_rdata[i] = '0;\n assign pmp_addr_rdata[i] = '0;\n end\n end\n\n // Write data calculation\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_pmp_csrs\n // -------------------------\n // Instantiate cfg registers\n // -------------------------\n assign pmp_cfg_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_CFG + (i[11:0] >> 2)));\n\n // Select the correct WDATA (each CSR contains 4 CFG fields, each with 2 RES bits)\n assign pmp_cfg_wdata[i].lock = csr_wdata_int[(i%4)*PMP_CFG_W+7];\n // NA4 mode is not selectable when G > 0, mode is treated as OFF\n always_comb begin\n unique case (csr_wdata_int[(i%4)*PMP_CFG_W+3+:2])\n 2'b00 : pmp_cfg_wdata[i].mode = PMP_MODE_OFF;\n 2'b01 : pmp_cfg_wdata[i].mode = PMP_MODE_TOR;\n 2'b10 : pmp_cfg_wdata[i].mode = (PMPGranularity == 0) ? PMP_MODE_NA4:\n PMP_MODE_OFF;\n 2'b11 : pmp_cfg_wdata[i].mode = PMP_MODE_NAPOT;\n default : pmp_cfg_wdata[i].mode = pmp_cfg_mode_e'('X);\n endcase\n end\n assign pmp_cfg_wdata[i].exec = csr_wdata_int[(i%4)*PMP_CFG_W+2];\n // W = 1, R = 0 is a reserved combination. For now, we force W to 0 if R == 0\n assign pmp_cfg_wdata[i].write = &csr_wdata_int[(i%4)*PMP_CFG_W+:2];\n assign pmp_cfg_wdata[i].read = csr_wdata_int[(i%4)*PMP_CFG_W];\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pmp_cfg[i] <= pmp_cfg_t'('b0);\n end else if (pmp_cfg_we[i]) begin\n pmp_cfg[i] <= pmp_cfg_wdata[i];\n end\n end\n\n // --------------------------\n // Instantiate addr registers\n // --------------------------\n if (i < PMPNumRegions - 1) begin : g_lower\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (pmp_cfg[i+1].mode != PMP_MODE_TOR) &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end else begin : g_upper\n assign pmp_addr_we[i] = csr_we_int & ~pmp_cfg[i].lock &\n (csr_addr == (CSR_OFF_PMP_ADDR + i[11:0]));\n end\n\n always_ff @(posedge clk_i or negedge rst_ni) begin\n if (!rst_ni) begin\n pmp_addr[i] <= 'b0;\n end else if (pmp_addr_we[i]) begin\n pmp_addr[i] <= csr_wdata_int;\n end\n end\n assign csr_pmp_cfg_o[i] = pmp_cfg[i];\n assign csr_pmp_addr_o[i] = {pmp_addr[i],2'b00};\n end\n\n end else begin : g_no_pmp_tieoffs\n // Generate tieoffs when PMP is not configured\n for (genvar i = 0; i < PMP_MAX_REGIONS; i++) begin : g_rdata\n assign pmp_addr_rdata[i] = '0;\n assign pmp_cfg_rdata[i] = '0;\n end\n for (genvar i = 0; i < PMPNumRegions; i++) begin : g_outputs\n assign csr_pmp_cfg_o[i] = pmp_cfg_t'('0);\n assign csr_pmp_addr_o[i] = '0;\n end\n end\n\n //////////////////////////\n // Performance monitor //\n //////////////////////////\n\n // update enable signals\n always_comb begin : mcountinhibit_update\n if (mcountinhibit_we == 1'b1) begin\n mcountinhibit_d = {csr_wdata_int[31:2], 1'b0, csr_wdata_int[0]}; // bit 1 must always be 0\n end else begin\n mcountinhibit_d = mcountinhibit_q;\n end\n end\n\n assign mcountinhibit_force = {{29-MHPMCounterNum{1'b1}}, {MHPMCounterNum{1'b0}}, 3'b000};\n assign mcountinhibit = mcountinhibit_q | mcountinhibit_force;\n\n // event selection (hardwired) & control\n always_comb begin : gen_mhpmcounter_incr\n\n // active counters\n mhpmcounter_incr[0] = 1'b1; // mcycle\n mhpmcounter_incr[1] = 1'b0; // reserved\n mhpmcounter_incr[2] = instr_ret_i; // minstret\n mhpmcounter_incr[3] = lsu_busy_i; // cycles waiting for data memory\n mhpmcounter_incr[4] = imiss_i & ~pc_set_i; // cycles waiting for instr fetches\n // excl. jump and branch set cycles\n mhpmcounter_incr[5] = mem_load_i; // num of loads\n mhpmcounter_incr[6] = mem_store_i; // num of stores\n mhpmcounter_incr[7] = jump_i; // num of jumps (unconditional)\n mhpmcounter_incr[8] = branch_i; // num of branches (conditional)\n mhpmcounter_incr[9] = branch_taken_i; // num of taken branches (conditional)\n mhpmcounter_incr[10] = instr_ret_compressed_i; // num of compressed instr\n\n // inactive counters\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmcounter_incr_inactive\n mhpmcounter_incr[i] = 1'b0;\n end\n end\n\n // event selector (hardwired, 0 means no event)\n always_comb begin : gen_mhpmevent\n\n // activate all\n for (int i=0; i<32; i++) begin : gen_mhpmevent_active\n mhpmevent[i] = '0;\n mhpmevent[i][i] = 1'b1;\n end\n\n // deactivate\n mhpmevent[1] = '0; // not existing, reserved\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mhpmevent_inactive\n mhpmevent[i] = '0;\n end\n end\n\n // mask, controls effective counter width\n always_comb begin : gen_mask\n\n for (int i=0; i<3; i++) begin : gen_mask_fixed\n // mcycle, mtime, minstret are always 64 bit wide\n mhpmcounter_mask[i] = {64{1'b1}};\n end\n\n for (int unsigned i=3; i<3+MHPMCounterNum; i++) begin : gen_mask_configurable\n // mhpmcounters have a configurable width\n mhpmcounter_mask[i] = {{64-MHPMCounterWidth{1'b0}}, {MHPMCounterWidth{1'b1}}};\n end\n\n for (int unsigned i=3+MHPMCounterNum; i<32; i++) begin : gen_mask_inactive\n // mask inactive mhpmcounters\n mhpmcounter_mask[i] = '0;\n end\n end\n\n // update\n always_comb begin : mhpmcounter_update\n mhpmcounter_d = mhpmcounter_q;\n\n for (int i=0; i<32; i++) begin : gen_mhpmcounter_update\n\n // increment\n if (mhpmcounter_incr[i] & ~mcountinhibit[i]) begin\n mhpmcounter_d[i] = mhpmcounter_mask[i] & (mhpmcounter_q[i] + 64'h1);\n end\n\n // write\n if (mhpmcounter_we[i]) begin\n mhpmcounter_d[i][31: 0] = mhpmcounter_mask[i][31: 0] & csr_wdata_int;\n end else if (mhpmcounterh_we[i]) begin\n mhpmcounter_d[i][63:32] = mhpmcounter_mask[i][63:32] & csr_wdata_int;\n end\n end\n end\n\n // performance monitor registers\n always_ff @(posedge clk_i or negedge rst_ni) begin : perf_counter_registers\n if (!rst_ni) begin\n mcountinhibit_q <= '0;\n for (int i=0; i<32; i++) begin\n mhpmcounter_q[i] <= '0;\n end\n end else begin\n mhpmcounter_q <= mhpmcounter_d;\n mcountinhibit_q <= mcountinhibit_d;\n end\n end\n\nendmodule\n", "selected_doc_paths": ["doc/cs_registers.rst", "doc/exception_interrupts.rst", "doc/debug.rst", "doc/pmp.rst", "doc/performance_counters.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 222, "lang": "sv", "rtl_files": ["rtl/ibex_id_stage.sv"], "spec": "# Design Specification: Instruction Decode Stage (ibex_id_stage)\n\n## Overview\n\nThe Instruction Decode (ID) stage is the second stage of the Ibex processor pipeline. It receives an instruction from the Instruction Fetch (IF) stage, decodes it, reads the register file, computes immediates, prepares operands for the execution units, and controls the flow of multi-cycle instructions (load/store, multiply/divide, branches, jumps). The ID stage also interfaces with the control logic for exceptions, interrupts, debug, and CSR operations.\n\nThe stage is parameterizable to support:\n- **RV32E**: reduces the register file to 16 registers (x0–x15) instead of 32.\n- **RV32M**: enables the multiply/divide extension.\n\n## Interfaces and Behavior\n\n### Inputs from the Fetch Stage\n- A valid instruction (31:0) and an indication whether the instruction is compressed (16-bit) are provided along with a validity flag (`instr_valid_i`).\n- A signal (`instr_new_i`) indicates that a new instruction has entered the IF-ID pipeline register and should be decoded.\n- The current program counter (PC) of the instruction is supplied.\n\nThe ID stage outputs:\n- `instr_req_o`: request to the prefetcher for the next instruction.\n- `id_in_ready_o`: signals that the ID stage is ready to accept a new instruction (pipeline handshake).\n- `instr_valid_clear_o`: kills the instruction in the IF-ID pipeline register (e.g., on exceptions, branch mispredictions).\n\n### Decoder and Controller\n\nThe ID stage contains a decoder that identifies the instruction type, its operands, and the required operation. The decoder classifies the instruction and produces control signals for:\n- ALU operation\n- Multiply/divide operation\n- Memory access (load/store)\n- CSR access\n- Branch/jump type\n- Immediate selection and sign-extension\n- Register file read/write addresses and write data source\n\nAll decode outputs are qualified by the validity of the instruction and by the current execution state. An illegal instruction is flagged when the decoder cannot recognize the opcode/funct3/funct7 combination or when the instruction is a compressed illegal instruction (`illegal_c_insn_i`). Additionally, an illegal CSR instruction signal from the CSR unit may further invalidate the instruction.\n\nThe controller (`ibex_controller`) manages the overall pipeline flow, exception handling, interrupt handling, debug mode, and PC update decisions. It receives signals from the decoder (illegal, ecall, mret, dret, wfi, ebreak, CSR status) and from the execution stage (branch decision, LSU errors), and controls the fetch stage via PC set signals and cause/exception PC mux selections.\n\n### Register File Access\n\nThe ID stage accesses the register file through two read ports (source registers `rs1` and `rs2`) and one write port. The write port is used for results from the ALU, LSU, or CSR reads. Write enable is gated by:\n- Whether the instruction is executing (not stalled or killed).\n- Whether the instruction is a multi-cycle operation (load/store, multiply/divide) – for these, the write enable is asserted only when the result is ready (via the write‑back FSM).\n- A flag indicating an illegal CSR instruction – write is suppressed to prevent corrupting the register file.\n\nThe register file may be flip‑flop based (for FPGA/Verilator) or latch‑based (for ASICs). In both cases, a write to register `x0` is ignored (it is statically zero).\n\n### Immediate Generation\n\nSix types of immediates are generated from the instruction bits according to the RISC‑V specification:\n- I‑type (12‑bit signed immediate)\n- S‑type (12‑bit signed immediate, split across two fields)\n- B‑type (13‑bit signed immediate, branch offset)\n- U‑type (20‑bit upper immediate)\n- J‑type (21‑bit signed immediate, jump offset)\n- Z immediate (for CSR instructions, the `rs1` field interpreted as an unsigned immediate)\n\nThe correct immediate is selected based on the instruction type and is driven to the ALU as operand B (or, for certain ALU operations, operand A uses Z immediate from CSR source register).\n\n### Operand Preparation for the ALU\n\nThe ALU has two operands:\n- **Operand A** can be selected from:\n - Register `rs1` data\n - The last address used by the load‑store unit (needed for misaligned address increments)\n - The current PC (for PC‑relative addresses)\n - The Z immediate (for CSR immediate operations)\n- **Operand B** can be selected from:\n - Register `rs2` data\n - One of the immediate values (I, S, B, U, J, or an increment value for PC+4/PC+2)\n\nThe selection is controlled by the decoder, but can be overridden during misaligned memory accesses (when the LSU requests an address increment). During such cases, operand A is forced to the last address, operand B is forced to the immediate that increments the address by 4, and the ALU performs an addition.\n\nThe prepared operands are sent to the EX stage together with the ALU operation code.\n\n### Multi‑Cycle Instruction Handling\n\nThe ID stage distinguishes between single‑cycle (ALU, CSR, branches not taken, jumps) and multi‑cycle operations. Multi‑cycle operations are:\n- **Load/store** (data memory access) – requires one or more cycles depending on alignment.\n- **Multiply/divide** – requires several cycles.\n- **Branches** (taken) – requires a target address calculation and PC update.\n- **Jumps** – requires a target address calculation and PC update.\n\nFor multi‑cycle instructions, the ID stage enters a **wait state** (WAIT_MULTICYCLE) and stalls the pipeline until the execution stage (or LSU) signals completion (`ex_valid_i` or `lsu_valid_i`). During this wait, the ID stage keeps the decoder outputs constant and asserts appropriate stall signals to the controller and fetch stage, preventing new instructions from entering.\n\n- For **load/store** and **multiply/divide**: the stage stalls until the corresponding unit indicates the result is available.\n- For **taken branches**: the stage stalls while the branch target is computed and the PC is updated; a new instruction is fetched from the target.\n- For **not‑taken branches** and **jumps**: the instruction completes in one cycle (jump target is computed in the EX stage, but the ID stage does not stall for jumps – the PC update is handled by the controller based on the jump set signal from the decoder).\n\n### Branch and Jump Control\n\nThe decoder identifies branch and jump instructions. For conditional branches, the branch decision is provided from the EX stage (`branch_decision_i`). The ID stage:\n- If the branch is taken, sets a flag (`branch_set`) that tells the controller to redirect the PC to the branch target.\n- If the branch is not taken, the instruction retires immediately.\n- For unconditional jumps, a `jump_set` signal is sent to the controller for PC redirection.\n\nThe ID stage also outputs performance counters for jumps, branches, and taken branches.\n\n### CSR Operations\n\nCSR instructions are decoded and their access type (read, write, set, clear) is forwarded to the CSR unit. The ID stage also supplies the CSR address and the write data (from register `rs1` or a Z immediate). The CSR unit returns read data, which is selected as the register file write data when the instruction completes.\n\nThe ID stage supports special CSR operations for handling exceptions and interrupts:\n- `csr_save_if_o` and `csr_save_id_o`: trigger saving of exception context (PC, status) during IF and ID stages respectively.\n- `csr_restore_mret_id_o`: invoked by the `mret` instruction to restore machine status.\n- `csr_save_cause_o`: stores the exception cause and trap value.\n\nIllegal CSR accesses (detected by the CSR unit) cause the instruction to be treated as illegal and no register file write occurs.\n\n### Exceptions and Interrupts\n\nWhile in the ID stage, certain exceptions can be raised:\n- **Illegal instruction**: when the decoder cannot decode the opcode or when a compressed illegal instruction is detected.\n- **Environment call (ECALL)**: executed in the controller.\n- **Breakpoint (EBREAK)**: handled by the controller.\n- **MRET/DRET/WFI**: handled by the controller.\n\nThe controller also manages **interrupts** (including non‑maskable interrupt) and **debug requests**. When an interrupt is taken, the controller generates the necessary CSR save and PC update signals. The ID stage provides the current PC and trap value to the CSR logic.\n\n### Debug Support\n\nDebug signals (request, single‑step, ebreak in M‑mode) are monitored and the controller generates appropriate debug causes and saves debug context when entering debug mode.\n\n### Performance Counters\n\nThe ID stage outputs:\n- `perf_jump_o`: pulsed when a jump instruction is executed.\n- `perf_branch_o`: pulsed when a conditional branch instruction is executed (both taken and not taken).\n- `perf_tbranch_o`: pulsed only for taken branches.\n- `instr_ret_o`: pulsed when an instruction retires (completes execution in the ID stage or after multi‑cycle completion).\n- `instr_ret_compressed_o`: pulsed when a retired instruction was compressed.\n\nThese signals are used by the performance counter logic.\n\n### Error Handling\n\nMemory access errors from the LSU (`lsu_load_err_i`, `lsu_store_err_i`) are passed to the controller to generate an exception. When an error occurs during a load/store, the register file write for that instruction is suppressed.\n\n### Pipeline Stall Sources\n\nThe ID stage can stall the pipeline for several reasons:\n- **Load/store** and **multiply/divide** operations while waiting for completion.\n- **Taken branches** (pipeline flush and redirection).\n- **Jumps** (single‑cycle, but redirect causes a flush – the stall signal prevents the next instruction from entering ID prematurely).\n- **External stall** from the controller (e.g., during interrupts, debug, or when the IF stage cannot deliver a new instruction).\n\n### Interaction with the IF Stage\n\nThe ID stage requests new instructions by asserting `instr_req_o` (to the prefetcher). It also signals readiness via `id_in_ready_o`. When a branch or jump occurs, or when an exception/interrupt is taken, the controller asserts `pc_set_o` with an appropriate PC mux select, and `instr_valid_clear_o` invalidates the instruction currently in the IF‑ID pipeline register.\n\n### Misaligned Memory Accesses\n\nThe ID stage supports misaligned load/store by providing an additional address increment to the ALU. When the LSU asserts `lsu_addr_incr_req_i`, the ALU operand muxes are overridden: operand A becomes the last address, operand B becomes `+4`, and the ALU produces the second aligned address. This mechanism is transparent to the decoder and does not require changes to the instruction decoding.\n\n## Summary of Behavioral Requirements\n\n- The ID stage must decode any valid instruction and produce the correct control signals for the execution units.\n- It must correctly handle single‑cycle and multi‑cycle instructions, stalling the pipeline as needed.\n- It must read the register file and compute immediates according to the RISC‑V specification.\n- It must support misaligned memory accesses by coordinating with the LSU and ALU.\n- It must detect illegal instructions and cooperate with the controller to raise exceptions.\n- It must interface with the CSR unit for CSR read/write operations and for saving/restoring trap context.\n- It must propagate interrupt and debug requests to the controller.\n- It must supply performance counter signals for retired instructions, branches, and jumps.\n- It must ensure that writes to register `x0` are ignored and that write enables are properly gated during stalls, errors, and illegal accesses.\n- It must be parameterizable for RV32E and RV32M.", "commit_id": "e5bdf1ea9fd522bb345db6f7310b2c0f9253c706", "timestamp": "2019-08-06T16:04:58+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "ea0296d74aa216397915069e4b10d418df1cd205", "pr_title": "Fix IF stalls preventing deassertion of regfile write enable", "pr_body": "This PR makes sure the signal `instr_multicycle_done_q` is only evaluated when the decoder currently has a multicycle instruction (load/store, mult/div, branch, jump). If this signal is evaluated\r\nfor single-cycle instructions, it can prevent the reg file write enable from being de-asserted in the case of stalls due to the IF stage.\r\n\r\n@udinator: Could you please verify that this actually fixes the bug you reported in #216 before we merge it?", "issue_title": "instr_multicycle_done is not asserted, continuous register writes", "issue_body": "While executing the code shown below:\r\n![Screenshot from 2019-08-05 18-14-11](https://user-images.githubusercontent.com/16736281/62504340-e2de7b00-b7ac-11e9-8b26-0cc4090ccec3.png)\r\nWe see this incorrect behavior in the core:\r\n![Screenshot from 2019-08-05 18-13-52](https://user-images.githubusercontent.com/16736281/62504356-ee31a680-b7ac-11e9-8d28-748683269f7e.png)\r\n\r\nAs shown, the `addi` instruction at PC `0x80000088` appears to correctly load register `x13` with the value `0xa5a5a5a5`, but at the very next instruction (PC: `0x8000008c`), we can see from the trace log that `x13` now has the value `0xa5a5de17`. \r\n![Screenshot from 2019-08-05 18-12-33](https://user-images.githubusercontent.com/16736281/62504456-76b04700-b7ad-11e9-94ab-524900644a48.png)\r\n\r\nFrom the waveform, `rf_reg[13]` is written correctly by the `addi` after adding the immediate value `0x5a5` (`alu_operand_b_i`), and becomes `0xa5a5a5a5`. After this, the testbench does not assert the `instr_gnt_i` for a number of cycles, leading the core to stay in the DECODE phase while waiting for the next instruction fetch. However, we see that `rf_reg[13]` keeps getting written with the incremented values of `alu_result` in every consecutive cycle that the core waits, as `instr_multicycle_done_q` in the ID stage does not go high after the `addi` finishes. This keeps `regfile_we` at 1, causing the continuous writes.", "commit_message": "ID stage: only eval `instr_multicycle_done_q` for multi-cycle instr\n\nThis signal should only be evaluated if the ID/EX stage currently\nexecutes a multi-cycle instruction. Without this commit, the signal\nis also evaluated for single-cycle instructions and can for example\ncause the register file write enable to not be de-asserted in case of\nstalls in the IF stage.\n\nThis bug was repored by @udinator. This resolves lowrisc/ibex#216.", "fix_patch": "diff --git a/rtl/ibex_id_stage.sv b/rtl/ibex_id_stage.sv\nindex 1f8a35bb09..e6e36c487c 100644\n--- a/rtl/ibex_id_stage.sv\n+++ b/rtl/ibex_id_stage.sv\n@@ -163,6 +163,7 @@ module ibex_id_stage #(\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@@ -477,11 +478,14 @@ module ibex_id_stage #(\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- assign instr_executing = (instr_new_i | ~instr_multicycle_done_q);\n+ assign instr_executing = instr_new_i | (instr_multicycle & ~instr_multicycle_done_q);\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@@ -489,6 +493,7 @@ module ibex_id_stage #(\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@@ -531,8 +536,6 @@ module ibex_id_stage #(\n // ID-EX/WB FSM //\n //////////////////\n \n- assign multdiv_en_dec = mult_en_dec | div_en_dec;\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@@ -580,6 +583,7 @@ module ibex_id_stage #(\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", "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: Renzo Andri - andrire@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// Davide Schiavone - pschiavo@iis.ee.ethz.ch //\n// //\n// Design Name: Instruction Decode Stage //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Decode stage of the core. It decodes the instructions //\n// and hosts the register file. //\n// //\n////////////////////////////////////////////////////////////////////////////////\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 */\nmodule ibex_id_stage #(\n parameter bit RV32E = 0,\n parameter bit RV32M = 1\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 core_ctrl_firstfetch_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 [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\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 // MUL, DIV\n output logic mult_en_ex_o,\n output logic div_en_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_save_cause_o,\n output logic [31:0] csr_mtval_o,\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 [1:0] data_reg_offset_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 csr_msip_i,\n input logic csr_mtip_i,\n input logic csr_meip_i,\n input logic [14:0] csr_mfip_i,\n input logic irq_pending_i,\n input logic irq_nm_i,\n\n input logic lsu_load_err_i,\n input logic lsu_store_err_i,\n\n // Debug Signal\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\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_n, branch_set_q;\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_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 [1:0] data_reg_offset_id;\n logic data_req_id, data_req_dec;\n\n // CSR control\n logic csr_status;\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 = 'X;\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 = 'X;\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 = 'X;\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 ) decoder_i (\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 .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\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_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_status_o ( csr_status ),\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 .data_reg_offset_o ( data_reg_offset_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 = 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 .first_fetch_o ( core_ctrl_firstfetch_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_status_i ( csr_status ),\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\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_q ),\n .jump_set_i ( jump_set ),\n\n // interrupt signals\n .csr_mstatus_mie_i ( csr_mstatus_mie_i ),\n .csr_msip_i ( csr_msip_i ),\n .csr_mtip_i ( csr_mtip_i ),\n .csr_meip_i ( csr_meip_i ),\n .csr_mfip_i ( csr_mfip_i ),\n .irq_pending_i ( irq_pending_i ),\n .irq_nm_i ( irq_nm_i ),\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_save_cause_o ( csr_save_cause_o ),\n .csr_mtval_o ( csr_mtval_o ),\n\n // Debug Signal\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\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 assign instr_executing = instr_new_i | (instr_multicycle & ~instr_multicycle_done_q);\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 assign data_reg_offset_ex_o = data_reg_offset_id;\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 assign mult_en_ex_o = mult_en_id;\n assign div_en_ex_o = div_en_id;\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 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 branch_set_q <= 1'b0;\n instr_multicycle_done_q <= 1'b0;\n end else begin\n id_wb_fsm_cs <= id_wb_fsm_ns;\n branch_set_q <= branch_set_n;\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_n = 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) 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_n = 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 = id_fsm_e'(1'bX);\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`ifndef VERILATOR\n // make sure that branch decision is valid when jumping\n assert property (\n @(posedge clk_i) (branch_decision_i !== 1'bx || branch_in_dec == 1'b0) ) else\n $display(\"Branch decision is X\");\n\n`ifdef CHECK_MISALIGNED\n assert property (\n @(posedge clk_i) (~lsu_addr_incr_req_i) ) else\n $display(\"Misaligned memory access at %x\",pc_id_i);\n`endif\n\n // the instruction delivered to the ID stage should always be valid\n assert property (\n @(posedge clk_i) (instr_valid_i & (~illegal_c_insn_i)) |-> (!$isunknown(instr_rdata_i)) ) else\n $display(\"Instruction is valid, but has at least one X\");\n\n // make sure multicycles enable signals are unique\n assert property (\n @(posedge clk_i) ~(data_req_dec & multdiv_en_dec)) else\n $display(\"Multicycles enable signals are not unique\");\n\n`endif\n\nendmodule\n", "selected_doc_paths": ["doc/register_file.rst", "doc/instruction_fetch.rst", "doc/exception_interrupts.rst", "doc/load_store_unit.rst", "doc/cs_registers.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 176, "lang": "sv", "rtl_files": ["rtl/ibex_decoder.sv"], "spec": "# Behavioral Design Specification: Ibex Instruction Decoder\n\n## 1. Overview\n\nThe instruction decoder is the central combinational logic block that interprets a 32-bit RISC‑V instruction and generates all control signals required by the subsequent pipeline stages (register file, ALU, load‑store unit, CSR unit, and program counter update logic). It is part of the Ibex core, a small 32‑bit RISC‑V processor.\n\nThe decoder must:\n\n- Extract and sign‑extend immediates of the I, S, B, U, J, and Z formats.\n- Identify the register source addresses (rs1, rs2) and destination address (rd) from the instruction.\n- Determine the operation to be performed by the ALU (including shifts, comparisons, and addition) and the selection of its two operands (register file values, program counter, immediates, or zero).\n- Control the load‑store unit (LSU) for loads and stores, specifying byte/halfword/word size, signedness, and write enable.\n- Control the multiplier/divider unit when the M extension is enabled.\n- Control CSR read/write/set/clear operations.\n- Identify special instructions (ecall, ebreak, mret, dret, wfi) and indicate them to the controller.\n- Detect illegal instructions and suppress all data‑modifying actions when an illegal instruction is encountered.\n\nThe decoder operates purely combinationally; it does not contain any state elements. It is parameterized by two build‑time options: **RV32E** (reduced register file with 16 registers) and **RV32M** (enable multiply/divide extension).\n\n## 2. Supported Instruction Sets\n\n- **RV32I** – Base integer instruction set (mandatory).\n- **RV32M** – Integer multiplication and division extension (optional, controlled by parameter `RV32M`).\n- **RV32E** – Embedded variant with 16 registers instead of 32 (optional, controlled by parameter `RV32E`).\n\nThe decoder does not handle compressed (16‑bit) instructions directly; it receives a single compressed‑instruction‑failure signal (`illegal_c_insn_i`) from a separate compressed instruction decoder. When this signal is asserted, the current instruction shall be treated as illegal regardless of its decoded opcode.\n\n## 3. Instruction Decoding Flow\n\nThe decoder receives the 32‑bit instruction word and a signal indicating whether the instruction is new (first cycle of a multi‑cycle operation) or is the second cycle of a jump/branch sequence. It produces the following categories of outputs:\n\n### 3.1 Immediate Generation\n\nSix types of immediates must be produced, all 32 bits wide:\n\n- **I‑type**: Sign‑extended 12‑bit immediate, formed from bits [31:20] of the instruction.\n- **S‑type**: Sign‑extended 12‑bit immediate, formed by concatenating bits [31:25] and [11:7].\n- **B‑type**: Sign‑extended 13‑bit immediate (shifted left by 1), formed from bits [31], [7], [30:25], and [11:8].\n- **U‑type**: 20‑bit upper immediate (zero‑extended lower 12 bits), formed from bits [31:12] shifted left by 12.\n- **J‑type**: Sign‑extended 21‑bit immediate (shifted left by 1), formed from bits [19:12], [20], [30:21], and the sign bit.\n- **Z‑type**: Zero‑extended 5‑bit immediate, formed from bits [19:15] (rs1 field) – used for CSR instructions.\n\n### 3.2 Register File Addressing\n\n- **Read address A** (rs1) – always taken from instruction bits [19:15].\n- **Read address B** (rs2) – always taken from instruction bits [24:20].\n- **Write address** (rd) – always taken from instruction bits [11:7].\n\n### 3.3 RV32E Register Check\n\nWhen the RV32E parameter is set, register addresses must be checked for illegal high‑order bit (bit 4) usage. If any of the following conditions are true, the instruction is illegal (and write enable is suppressed):\n\n- Register rs1 is used as an ALU operand (when the ALU would actually read it) and rs1[4] = 1.\n- Register rs2 is used as an ALU operand (when the ALU would actually read it) and rs2[4] = 1.\n- The destination register rd is written (regfile write enable active) and rd[4] = 1.\n\nFor the non‑RV32E case, this check is always satisfied (no illegal condition).\n\n### 3.4 CSR Operand Check\n\nFor CSR instructions that are of type SET or CLEAR (CSRRSI, CSRRCI, CSRRS, CSRRC) and where the rs1 field (either immediate or register index) is all‑zero, the operation must be downgraded to a read-only CSR access (CSR_OP_READ). This prevents unintentional writes to CSRs when the immediate or register x0 is used.\n\n### 3.5 Instruction Classification by Opcode\n\nThe decoder uses the 7‑bit opcode field (bits [6:0]) to select one of the following instruction groups. Within each group, the funct3 (bits [14:12]) and funct7 (bits [31:25]) fields further refine the operation.\n\n#### 3.5.1 Jumps and Branches\n\n**JAL (Jump and Link)**\n- **First cycle** (instr_new_i active): Compute the jump target by adding the current program counter (PC) to the J‑type immediate. The ALU output will be the target PC. No register write occurs in this cycle. The `jump_set` signal is asserted to update the PC in the same cycle. The decoder also indicates that a jump is being calculated.\n- **Second cycle** (instr_new_i inactive): Compute PC+4 (by adding the PC to the constant +4) and write that value to the destination register (rd). No jump_set is asserted.\n\n**JALR (Jump and Link Register)**\n- **First cycle**: Compute the jump target by adding register rs1 to the I‑type immediate. The result must have its least significant bit forced to zero (as per RISC‑V spec); this is performed outside the decoder. No register write. `jump_set` is asserted.\n- **Second cycle**: Same as JAL second cycle (write PC+4 to rd).\n- **Illegal condition**: If the funct3 field is not 000, the instruction is illegal.\n\n**Branches (BRANCH opcode)**\n- **First cycle**: Evaluate the branch condition using the two register operands (rs1, rs2). The ALU comparator is selected according to funct3:\n - 000: equal\n - 001: not equal\n - 100: less than (signed)\n - 101: greater or equal (signed)\n - 110: less than (unsigned)\n - 111: greater or equal (unsigned)\n - Any other value: illegal instruction.\n- **Second cycle**: Compute the branch target address (PC + B‑immediate) using the ALU. No register write. No condition evaluation.\n- The decoder asserts a `branch_in_dec` signal to indicate that a branch is being processed.\n\n#### 3.5.2 Loads and Stores\n\n**Store (STORE opcode)**\n- Address computation: add register rs1 to either an S‑type immediate (if bit [14] = 0) or, if bit [14] = 1, the instruction is illegal (no register offset available).\n- Load‑store unit request is made with write enable active.\n- Byte size is determined by bits [13:12]:\n - 00: store byte (SB)\n - 01: store halfword (SH)\n - 10: store word (SW)\n - 11: illegal.\n- The data to be stored is taken from register rs2. The decoder also outputs a byte offset indicator to the LSU for sub‑word stores.\n\n**Load (LOAD opcode)**\n- Address computation: add rs1 to I‑type immediate.\n- Load‑store unit request is made with write enable inactive.\n- Data read from memory is written to the register file (rd) via the LSU write‑back path.\n- Size and signedness:\n - If bit [14] = 1, the load is unsigned (zero‑extended); if bit [14] = 0, signed (sign‑extended).\n - Bits [13:12] select the size:\n - 00: load byte (LB / LBU)\n - 01: load halfword (LH / LHU)\n - 10: load word (LW). If bit [14] = 1 (LWU), the instruction is illegal because LWU does not exist in RV32I.\n - 11: illegal.\n\n#### 3.5.3 ALU Immediate and Register Operations\n\n**LUI (Load Upper Immediate)**\n- ALU takes zero as operand A and the U‑type immediate as operand B; adder produces the immediate itself.\n- Result written to rd.\n\n**AUIPC (Add Upper Immediate to PC)**\n- ALU takes the PC as operand A and the U‑type immediate as operand B; adder produces PC + immediate.\n- Result written to rd.\n\n**OP‑IMM (Register‑Immediate ALU Operations)**\n- ALU takes rs1 as operand A and I‑type immediate as operand B.\n- ALU operation selected by funct3:\n - 000: add (ADDI)\n - 010: set if less than signed (SLTI)\n - 011: set if less than unsigned (SLTIU)\n - 100: XOR (XORI)\n - 110: OR (ORI)\n - 111: AND (ANDI)\n - 001: shift left logical (SLLI) – requires bits [31:25] to be all zero; otherwise illegal.\n - 101: shift right logical (SRLI) if bits [31:25] = 0; shift right arithmetic (SRAI) if bits [31:25] = 0b0100000; otherwise illegal.\n- Result written to rd.\n\n**OP (Register‑Register ALU Operations)**\n- ALU takes rs1 and rs2 as operands.\n- If bit[31] = 1, the instruction is illegal (reserved for future standard extensions or custom).\n- Otherwise, the operation is selected by the concatenation of funct7[6:0] and funct3:\n - **RV32I operations (always legal):**\n - 0b0000000_000: ADD\n - 0b0100000_000: SUB\n - 0b0000000_010: SLT\n - 0b0000000_011: SLTU\n - 0b0000000_100: XOR\n - 0b0000000_110: OR\n - 0b0000000_111: AND\n - 0b0000000_001: SLL\n - 0b0000000_101: SRL\n - 0b0100000_101: SRA\n - **RV32M operations (legal only when `RV32M` = 1):**\n - MUL (0b0000001_000): multiplication, lower 32 bits\n - MULH (0b0000001_001): multiplication, upper 32 bits, both operands signed\n - MULHSU (0b0000001_010): multiplication, upper 32 bits, signed × unsigned\n - MULHU (0b0000001_011): multiplication, upper 32 bits, both unsigned\n - DIV (0b0000001_100): signed division\n - DIVU (0b0000001_101): unsigned division\n - REM (0b0000001_110): signed remainder\n - REMU (0b0000001_111): unsigned remainder\n When RV32M is disabled, these encoding combinations are illegal.\n - Any other encoding (including those with funct7 bits not matching the above) is illegal.\n\nFor multiply/divide instructions, the decoder enables either the multiplier or divider unit, selects the appropriate MD_OP and signed‑mode signals, and drives the ALU to produce an ADD of zero (the multiplier/divider result bypasses the ALU; the ALU output is not used).\n\n#### 3.5.4 Memory Fence and System Instructions\n\n**MISC‑MEM (FENCE)**\n- Only funct3 = 000 is supported; it is treated as a NOP (no register write, default ALU operation).\n- Any other funct3 value (e.g., FENCE.I) is illegal.\n\n**SYSTEM**\n- **Non‑CSR instructions** (funct3 = 000):\n - The decoder asserts one of the following signals according to the immediate bits [31:20]:\n - 0x000: ecall\n - 0x001: ebreak\n - 0x302: mret\n - 0x7B2: dret\n - 0x105: wfi\n - Any other value: illegal.\n - For any of these, both the rs1 and rd fields must be zero; otherwise the instruction is illegal.\n- **CSR instructions** (funct3 = 001, 010, 011, 101, 110, 111):\n - CSR access is enabled.\n - The write‑back path is set to the CSR result.\n - Operand A selection:\n - If bit [14] = 1, operand A comes from the Z‑type immediate (rs1 field zero‑extended).\n - If bit [14] = 0, operand A comes from register rs1.\n - Operand B selection is always the I‑type immediate (which holds the CSR address).\n - The CSR operation (read, write, set, clear) is determined by bits [13:12]:\n - 01: write (CSRRW)\n - 10: set (CSRRS)\n - 11: clear (CSRRC)\n - 00: illegal.\n - If the CSR address corresponds to `mstatus`, `dcsr`, `dpc`, `dscratch0`, or `dscratch1`, a status signal is asserted to trigger a pipeline flush.\n- The decoder also performs the zero‑rs1 check described in §3.4.\n\n### 3.6 Illegal Instruction Detection\n\nThe instruction is considered illegal (and the `illegal_insn_o` output asserted) if any of the following conditions occur:\n\n1. The opcode does not match any of the recognized opcode groups.\n2. The compressed instruction failure input (`illegal_c_insn_i`) is asserted.\n3. An unsupported or reserved encoding combination is used within a recognized group (e.g., invalid funct3 for branches, invalid funct7 for OP‑IMM shifts, unknown SYSTEM immediate, etc.).\n4. The RV32E register check fails (see §3.3).\n5. A CSR instruction uses an illegal funct3 (00) for the operation field.\n6. Within the OP‑IMM group, the shift immediate fields are not all zero for SLLI or not one of the two valid patterns for SRL/SRA.\n\nWhen an illegal instruction is detected:\n\n- All write enables (register file write, data memory write request, multiplier/divider enable, CSR access) are forced to zero.\n- The jump_set and branch_in_dec signals are de‑asserted.\n- The data memory request (`data_req`) is cleared.\n- The jump_in_dec signal is cleared.\n\nThe combined `illegal_insn_o` output is the logical OR of the decoder’s own `illegal_insn` signal and the RV32E register violation flag. Similarly, the final register file write enable (`regfile_we_o`) is the AND of the decoder’s internal `regfile_we` and the negated RV32E violation flag.\n\nNote: Some illegal conditions (e.g., privilege violations on CSR access) are detected inside the CSR unit, not in the decoder. The decoder only checks encoding legality.\n\n## 4. Immediate Multiplexer Selection\n\nThe decoder outputs two select signals for the two immediate multiplexers (imm_a_mux_sel and imm_b_mux_sel) that feed into the ALU operand MUXes. These selects determine which immediate format is used:\n\n- If the imm_a multiplexer selects zero (e.g., for LUI), the operand A is forced to zero.\n- If the imm_b multiplexer selects one of the immediate types (I, S, B, U, J, or the fixed +4 increment), the corresponding immediate is used.\n\nThe decoder also directly outputs the six immediate values (I, S, B, U, J, Z) as 32‑bit signals.\n\n## 5. Interaction with the Controller (Pipeline Stages)\n\nThe decoder receives a signal `instr_new_i` from the IF‑ID pipe register. This signal is high when the instruction has just been fetched (first cycle in the decode stage). For instructions that require two cycles to compute both a result and a return address (JAL, JALR) or to evaluate the condition and compute the target (branches), the decoder must provide different control signals in each cycle:\n\n- **JAL / JALR**: In the first cycle (new instruction), the decoder generates the jump target and asserts `jump_set`. In the second cycle (old instruction), it generates PC+4 and writes it to rd.\n- **Branches**: In the first cycle, the ALU compares the two register operands. In the second cycle, the ALU computes the branch target. The `branch_in_dec` signal is high during both cycles.\n\nThe decoder’s `jump_in_dec_o` output is asserted during both cycles of JAL/JALR to indicate that a jump is being processed.\n\n## 6. Output Summary\n\nThe decoder produces the following categories of outputs (described behaviorally, without signal names):\n\n- **Immediate values**: Six 32‑bit values (I, S, B, U, J, Z).\n- **Register file addresses**: Three 5‑bit addresses (rs1, rs2, rd).\n- **Register file write enable**: Active only when the instruction writes to a register and the instruction is not illegal; also suppressed for illegal RV32E register accesses.\n- **Register file write data source selection**: Either the ALU result, the LSU read data, or the CSR read data.\n- **ALU control**: Operation code, operand A selection (rs1, PC, immediate, zero), operand B selection (rs2 or immediate). Also immediate MUX selects for choosing among immediate types.\n- **Load‑store unit control**: Request, write enable, data size, sign extension, byte offset for stores.\n- **Multiplier/divider control**: Enable, operation type, signed mode.\n- **CSR control**: Access enable, operation type, status signal for specific CSR addresses.\n- **Branch/jump control**: Jump‑in‑decode, jump‑set, branch‑in‑decode signals.\n- **Special instruction flags**: ecall, ebreak, mret, dret, wfi.\n- **Illegal instruction indicator**: Combined with RV32E register violation.\n\nAll outputs are combinational functions of the instruction word and the `instr_new_i` and `illegal_c_insn_i` inputs.\n\n## 7. Parameter Dependencies\n\n- **RV32E = 0**: Standard 32‑register file; no register address checks.\n- **RV32E = 1**: Only 16 registers (addresses 0..15) are available; instructions using register addresses with bit 4 = 1 cause an illegal instruction exception.\n- **RV32M = 0**: Multiply/divide instructions (M‑extension) are not supported and decode as illegal.\n- **RV32M = 1**: Multiply/divide instructions decode normally and enable the multiplier/divider unit.", "commit_id": "04f4cd44f6b62a48af65f11143278be00d54132b", "timestamp": "2019-07-19T10:29:34+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "e4383589eb7614f595504fedd3eb2caaad3a74ab", "pr_title": "Decoder: remove reg-reg load, make LWU illegal", "pr_body": "The custom reg-reg instruction was added in the original design but is\r\nno longer needed. This commit removes it. Also, load instructions with\r\n`instr[14:12] == 3'b110` are now decoded as illegal.\r\n\r\nThis resolves #25.", "issue_title": "Remove reg-reg loads", "issue_body": "reg-reg load (i.e., offset taken from a register and not from an immediate) should not be part of the Ibex ISA.\r\n\r\nThe code at line 261 here:\r\nhttps://github.com/lowRISC/ibex/blob/master/rtl/ibex_decoder.sv\r\n\r\nis a piece of code coming from RISCY and it should be removed.", "commit_message": "Decoder: remove reg-reg load, make LWU illegal\n\nThe custom reg-reg load instruction was added in the original design but\nis no longer needed. This commit removes it. Also, load instructions\nwith `instr[14:12] == 3'b110` are now decoded as illegal.\n\nThis resolves #25.", "fix_patch": "diff --git a/rtl/ibex_decoder.sv b/rtl/ibex_decoder.sv\nindex 7326bf0fec..7088d94eab 100644\n--- a/rtl/ibex_decoder.sv\n+++ b/rtl/ibex_decoder.sv\n@@ -299,12 +299,10 @@ module ibex_decoder #(\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+ 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: illegal_insn = 1'b1;\n endcase\n end\n \n@@ -325,37 +323,18 @@ module ibex_decoder #(\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+ 2'b00: data_type_o = 2'b10; // LB(U)\n+ 2'b01: data_type_o = 2'b01; // LH(U)\n+ 2'b10: begin\n+ data_type_o = 2'b00; // LW\n+ if (instr[14]) begin\n+ illegal_insn = 1'b1; // LWU does not exist\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+ default: begin\n+ illegal_insn = 1'b1;\n+ end\n+ endcase\n end\n \n /////////\n", "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: illegal_insn = 1'b1;\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(U)\n 2'b01: data_type_o = 2'b01; // LH(U)\n 2'b10: begin\n data_type_o = 2'b00; // LW\n if (instr[14]) begin\n illegal_insn = 1'b1; // LWU does not exist\n end\n end\n default: begin\n illegal_insn = 1'b1;\n end\n endcase\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, PC\n // NOTE: instructions can also be detected to be illegal inside the CSRs (upon accesses with\n // insufficient privileges), or when accessing non-available registers in RV32E,\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 jump_set_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", "selected_doc_paths": ["doc/cs_registers.rst", "doc/debug.rst", "doc/exception_interrupts.rst", "doc/load_store_unit.rst", "doc/register_file.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 169, "lang": "sv", "rtl_files": ["rtl/ibex_id_stage.sv"], "spec": "# Behavioral Specification: Instruction Decode Stage (ID Stage) of Ibex Core\n\n## 1. Overview\n\nThe Instruction Decode (ID) stage is responsible for:\n\n- Receiving fetched instructions from the Instruction Fetch (IF) stage.\n- Decoding the instruction to determine the operation and required resources.\n- Providing the operand values for the Execution (EX) stage, including register file reads and immediate generation.\n- Hosting the register file and managing register reads and writes.\n- Controlling the flow of multicycle instructions (load/store, multiply/divide) through the pipeline.\n- Detecting and signalling control flow changes (branches, jumps, returns).\n- Generating stall signals for the pipeline when multicycle operations are in progress.\n- Detecting illegal instructions and forwarding them to the exception handler.\n- Supporting CSR access, interrupts, and debug mode interactions.\n\nThe ID stage works in conjunction with the controller, decoder, and interrupt controller sub‑blocks.\n\n## 2. Operation\n\n### 2.1 Instruction Acceptance\n\nThe ID stage accepts a new instruction when the IF stage provides a valid instruction together with a *new instruction* indicator. \nThe instruction may be a normal 32‑bit instruction or a compressed 16‑bit instruction (RVC). \nWhen a compressed instruction is indicated, the ID stage uses the lower 16 bits of the instruction data and expects the higher 16 bits to be unpredictable.\n\nIf the instruction is a multicycle operation (load, store, multiply, divide, branch, jump), the ID stage transitions into a waiting state and stalls the pipeline until the operation completes. \nSingle‑cycle instructions (arithmetic, logical, shifts, etc.) are processed immediately and the ID stage remains ready for the next instruction.\n\n### 2.2 Pipeline Ready and Stalls\n\n- The ID stage asserts a **ready signal** to the IF stage when it is able to accept a new instruction in the next cycle.\n- When the ID stage is waiting for a multicycle operation to complete, it asserts appropriate **stall signals** to freeze the IF and ID pipeline registers.\n- The stall signals are separate for:\n - Load/Store Unit (LSU) operations\n - Multiplier/Divider (MULDIV) operations\n - Branches (conditional)\n - Jumps (unconditional)\n\nThe stall remains active until the respective execution unit (EX or LSU) indicates that the result is valid.\n\n### 2.3 Multicycle Operation State Machine\n\nThe ID stage contains a two‑state finite state machine:\n\n- **IDLE**: Normal operation. When a new instruction arrives, the ID stage examines its type.\n - If it is a load/store or multiply/divide instruction, the ID stage moves to **WAIT_MULTICYCLE** and stalls the pipeline.\n - If it is a conditional branch, the ID stage evaluates the branch decision (provided by the EX stage). If the branch is taken, it stalls and sets a branch‑taken signal; otherwise it remains in IDLE.\n - If it is an unconditional jump, the ID stage stalls and moves to WAIT_MULTICYCLE.\n - For all other instructions (single‑cycle), the ID stage remains in IDLE and the instruction is considered completed immediately.\n\n- **WAIT_MULTICYCLE**: The ID stage waits for the completion signal from the appropriate execution unit.\n - For load/store: it waits for the LSU to signal that the access is valid.\n - For multiply/divide: it waits for the EX stage to signal that the result is valid (the multiplier/divider is considered part of the EX stage).\n - For branches/jumps: The wait is normally one cycle (when taken); the completion signal comes from the EX stage.\n - When the completion signal is received, the ID stage transitions back to IDLE, deasserts the stall, and allows the pipeline to advance.\n - The register file write enable for multicycle instructions is gated by the absence of an error (load access fault or store access fault).\n\n## 3. Interfaces\n\n### 3.1 Instruction Fetch Interface\n\nThe ID stage receives:\n\n- **Instruction valid** and **new instruction** indicators.\n- **Instruction data** (32‑bit) and a separate **compressed instruction data** (16‑bit).\n- **Compressed instruction indicator** to select between the 32‑bit and 16‑bit instruction word.\n\nThe ID stage drives:\n\n- **Instruction request** to the IF stage (used for controlling the prefetcher).\n- **Instruction valid clear** to kill the instruction in the IF/ID pipeline register.\n- **Instruction ready** to indicate that the ID stage can accept a new instruction.\n\n### 3.2 Operand Generation and Execution Interface\n\nThe ID stage provides the EX stage with:\n\n- ALU operation type and two operands (A and B).\n- Multiplier/divider operation type, signed mode, and two operands.\n- Control signals for the load/store unit (request, write enable, data type, sign extension, data to write, register offset).\n- Control signals for CSR accesses (request, operation type).\n\nThe ID stage also receives:\n\n- **Branch decision** from the EX stage to determine whether a conditional branch is taken.\n- **EX stage valid** and **LSU valid** signals to know when multicycle operations have completed.\n- **LSU first address** and **increment request** for misaligned memory accesses (the ID stage adjusts the ALU operands accordingly to compute the second address).\n\n### 3.3 Register File Interface\n\nThe ID stage reads two registers (source operands) and writes one register (destination). \nThe register file is implemented either as flip‑flop‑based (for FPGA) or latch‑based (for ASIC). \nRegister address 0 is hardwired to 0 and cannot be written.\n\nThe ID stage selects the write‑back data source:\n\n- From the EX stage (ALU or multiplier/divider result)\n- From the LSU (data loaded from memory)\n- From the CSR read data\n\n### 3.4 Exception and Interrupt Interface\n\nThe ID stage forwards decoded exception‑causing instructions (illegal instruction, ECALL, EBREAK, MRET, DRET, WFI) and CSR status to the controller. \nIt also passes information about load/store errors from the LSU to the controller.\n\nThe ID stage participates in interrupt handling:\n\n- It includes an interrupt controller that qualifies interrupts with the global interrupt enable (M‑mode).\n- It acknowledges the interrupt and provides the interrupt ID to the external interrupt controller.\n\n### 3.5 Debug Interface\n\nThe ID stage handles debug requests, single‑step, and debug breakpoints by interacting with the controller. \nIt provides the debug cause and a CSR save signal for debug mode.\n\n### 3.6 Performance Counters\n\nThe ID stage generates the following performance monitoring signals:\n\n- **Jump instruction executed**: set when an unconditional jump is retired.\n- **Branch instruction executed**: set for every conditional branch instruction.\n- **Taken branch executed**: set when a conditional branch is taken.\n- **Instruction retired**: set when any instruction completes execution (single‑cycle or multicycle).\n- **Compressed instruction retired**: set when the retired instruction was compressed.\n\n## 4. Instruction Decoding\n\nThe ID stage decodes the incoming instruction using a dedicated decoder. \nThe decoder determines:\n\n- Whether the instruction is legal; if illegal, an illegal instruction exception is signalled.\n- The instruction category (ALU, load, store, branch, jump, CSR, multiply, divide, etc.).\n- The immediate values (I‑type, S‑type, B‑type, U‑type, J‑type, Z‑type for CSR).\n- The register file read addresses and write address.\n- The ALU operation and operand selection modes.\n- The multiplier/divider enable and operation.\n- The load/store unit control fields.\n- The CSR access and operation.\n- The branch / jump indicators.\n\nThe decoder also handles compressed instructions and expands them into their equivalent 32‑bit representation for the purposes of immediate generation and control.\n\n## 5. Register File\n\n### 5.1 Capacity\n\nThe register file contains either 31 or 15 architecturally visible registers, depending on whether the RV32E extension is enabled. \nRegister `x0` is always read as 0; writes to `x0` are ignored.\n\n### 5.2 Read Ports\n\nTwo read ports are available, allowing both source operands to be read in the same cycle.\n\n### 5.3 Write Port\n\nA single write port is used. \nThe write data can come from the ALU/MUL/DIV result, the LSU data, or the CSR read data.\n\nWrite enables are gated:\n\n- Writes are suppressed when the instruction is not executing (e.g., after a pipeline flush).\n- For multicycle instructions, the write enable is asserted only when the execution unit signals completion without error. Load/store errors prevent the write.\n- Illegal CSR accesses also prevent the register file write.\n\n### 5.4 Implementation Options\n\nTwo physical implementations exist: flip‑flop‑based (default for FPGA and Verilator simulation) and latch‑based (for ASIC). \nBoth implementations provide the same functional behavior as seen by the ID stage. \nThe latch‑based version requires a specific clock gating scheme to ensure correct write timing.\n\n## 6. Operand Generation\n\n### 6.1 ALU Operands\n\n- **Operand A** can be:\n - Register value from port A\n - The current PC (for PC‑relative addressing)\n - The previous load/store address (for misaligned LSU second access)\n - A zero immediate (used for CSR Z‑type)\n- **Operand B** can be:\n - Register value from port B\n - One of several immediate types, selected based on the decoded instruction\n\nFor misaligned load/store operations, the LSU requests a second access and provides the first address. The ID stage then forces Operand A to that first address and Operand B to a constant +4 increment, thus computing the second aligned address.\n\n### 6.2 Multiplier/Divider Operands\n\nThe two source register values are forwarded directly to the multiplier/divider.\n\n### 6.3 Load/Store Data\n\nThe store data is the value read from register port B. \nThe data type (byte, halfword, word) and sign‑extension control are provided to the LSU.\n\n## 7. Control Flow\n\n### 7.1 Branches\n\nWhen a conditional branch instruction is decoded, the ID stage sends the branch decision to the controller. \nIf the branch is **taken**, the ID stage stalls the pipeline for one cycle and signals the controller to set the PC to the branch target. \nIf the branch is **not taken**, the instruction completes immediately without stalling.\n\n### 7.2 Jumps (JAL, JALR)\n\nUnconditional jumps cause the ID stage to stall the pipeline for one cycle while the controller updates the PC. \nThe jump target address is computed in the EX stage; the ID stage merely signals the jump and provides the relevant immediate or register value.\n\n### 7.3 PC Update\n\nThe ID stage (through the controller) drives the PC selection mux for:\n\n- Normal sequential fetch\n- Branch / jump targets\n- Exception vector base\n- Interrupt vector base (vectored mode)\n- MRET and DRET return addresses\n\n## 8. Exception / Interrupt Handling\n\n### 8.1 Exception Sources\n\nThe ID stage detects the following exception causes through the decoder and external signals:\n\n- **Illegal instruction**: decoder signals illegal instruction or CSR access is illegal.\n- **Breakpoint**: EBREAK instruction.\n- **Environment call**: ECALL instruction.\n- **Load access fault**: error reported by the LSU during a load.\n- **Store access fault**: error reported by the LSU during a store.\n\nAll exceptions cause the core to jump to the address in the `mtvec` CSR (with the exception code determining the vector offset for interrupts).\n\n### 8.2 Interrupts\n\nThe interrupt controller within the ID stage qualifies incoming interrupt requests with the global interrupt enable bit (`MSTATUS.MIE`). \nIt provides the interrupt ID and a request to the main controller. \nThe controller acknowledges the interrupt, causing the core to jump to the appropriate vector address.\n\n### 8.3 Trap Handling\n\nWhen an exception or interrupt is taken, the ID stage (through the controller) saves the current PC and status to the `mepc` and `mstatus` CSRs. \nExecution of the `mret` instruction restores those CSRs and returns to the saved PC.\n\n## 9. Performance Counters\n\nThe ID stage provides the following event counts to the performance monitoring infrastructure:\n\n- **Jump**: incremented for every executed unconditional jump instruction.\n- **Branch**: incremented for every executed conditional branch instruction.\n- **Taken branch**: incremented only when the branch is actually taken.\n- **Instruction retired**: incremented for every instruction that completes (either single‑cycle or at the end of a multicycle operation).\n- **Compressed instruction retired**: incremented for every retired instruction that was originally compressed.\n\n---\n\n*This specification describes the required behavior of the Ibex Instruction Decode stage. It focuses on what the module must do under different conditions, without reference to internal implementation details.*", "commit_id": "f12b94c2a21dfb4779be5c4b9c460eb3f3c48323", "timestamp": "2019-07-18T10:28:14+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "63702b3e758abf35bcbe01c7aa15bd480d8f66be", "pr_title": "ID/EX stage: do not write to register file upon load errors", "pr_body": "This commit fixes the write back FSM to not store values returned from\r\nmemory to the register file when the LSU is reporting a load error.\r\n\r\nThis bug was reported by @ivanmgribeiro. This commit resolves #162.", "issue_title": "Load instructions that cause an error still write to registers", "issue_body": "Hi,\r\nThere seems to be a bug in Ibex when performing a read from memory which returns an error.\r\n\r\nI would expect that when the memory slave sets data_err high, the core would not write the data that was read in into a register, but it appears to still be written to the register regardless.\r\n\r\nWhat i observe is that the data is still written into the register.\r\n\r\nI'm using the following instructions:\r\n```\r\naddi r2, r0, 1\r\nlw r2, r2[2]\r\naddi r3, r2, 1\r\n```\r\nWhen using the load word instruction, the register is overwritten with 0x0, but when using load halfword or load byte, it seems to actually read what is returned by memory and store it in the register.\r\n\r\nMy memory slave is configured such that accesses outside of the range 0x80000000 - 0x80007fff will set data_err high.\r\n\r\nI've performed a fix that seemed to work locally by changing the line\r\nhttps://github.com/lowRISC/ibex/blob/b7ef64b62da74afe52bb40165e17a7e87539d47a/rtl/ibex_id_stage.sv#L283\r\nto\r\n```\r\nassign regfile_we = (illegal_csr_insn_i || !instr_executing || lsu_load_err_i) ? 1'b0 :\r\n```\r\n\r\nThis fix seems to work with other failing loads as well, but I'm not sure that it conforms to your style guide or whether it should be done here or at some other point in the code.", "commit_message": "ID/EX stage: do not write to register file upon load errors\n\nThis commit fixes the write back FSM to not store values returned from\nmemory to the register file when the LSU is reporting a load error.\n\nThis bug was reported by @ivanmgribeiro. This commit resolves #162.", "fix_patch": "diff --git a/rtl/ibex_id_stage.sv b/rtl/ibex_id_stage.sv\nindex 668a56a4d6..812282e42e 100644\n--- a/rtl/ibex_id_stage.sv\n+++ b/rtl/ibex_id_stage.sv\n@@ -622,7 +622,7 @@ module ibex_id_stage #(\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;\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", "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: Renzo Andri - andrire@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// Davide Schiavone - pschiavo@iis.ee.ethz.ch //\n// //\n// Design Name: Instruction Decode Stage //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Decode stage of the core. It decodes the instructions //\n// and hosts the register file. //\n// //\n////////////////////////////////////////////////////////////////////////////////\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 */\nmodule ibex_id_stage #(\n parameter bit RV32E = 0,\n parameter bit RV32M = 1\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 core_ctrl_firstfetch_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 [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_defines::pc_sel_e pc_mux_o,\n output ibex_defines::exc_pc_sel_e exc_pc_mux_o,\n\n input logic illegal_c_insn_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_defines::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 // MUL, DIV\n output logic mult_en_ex_o,\n output logic div_en_ex_o,\n output ibex_defines::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_defines::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 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 [1:0] data_reg_offset_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 irq_i,\n input logic [4:0] irq_id_i,\n input logic m_irq_enable_i,\n output logic irq_ack_o,\n output logic [4:0] irq_id_o,\n output ibex_defines::exc_cause_e exc_cause_o,\n\n input logic lsu_load_err_i,\n input logic lsu_store_err_i,\n\n // Debug Signal\n output ibex_defines::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\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_defines::*;\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_n, branch_set_q;\n logic jump_in_dec;\n logic jump_set;\n\n logic instr_executing;\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 // Signals running between controller and exception controller\n logic irq_req_ctrl;\n logic [4:0] irq_id_ctrl;\n logic exc_ack, exc_kill;// handshake\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_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 [1:0] data_reg_offset_id;\n logic data_req_id, data_req_dec;\n\n // CSR control\n logic csr_status;\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 = 'X;\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 = 'X;\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 = 'X;\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 ) decoder_i (\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 .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\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_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_status_o ( csr_status ),\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 .data_reg_offset_o ( data_reg_offset_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 = 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 .first_fetch_o ( core_ctrl_firstfetch_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_status_i ( csr_status ),\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\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 // from prefetcher\n .instr_req_o ( instr_req_o ),\n\n // to prefetcher\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_q ),\n .jump_set_i ( jump_set ),\n\n .irq_i ( irq_i ),\n // Interrupt Controller Signals\n .irq_req_ctrl_i ( irq_req_ctrl ),\n .irq_id_ctrl_i ( irq_id_ctrl ),\n .m_IE_i ( m_irq_enable_i ),\n\n .irq_ack_o ( irq_ack_o ),\n .irq_id_o ( irq_id_o ),\n\n .exc_ack_o ( exc_ack ),\n .exc_kill_o ( exc_kill ),\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\n // Debug Signal\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\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 // Interrupt controller //\n //////////////////////////\n\n ibex_int_controller int_controller_i (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n // to controller\n .irq_req_ctrl_o ( irq_req_ctrl ),\n .irq_id_ctrl_o ( irq_id_ctrl ),\n\n .ctrl_ack_i ( exc_ack ),\n .ctrl_kill_i ( exc_kill ),\n\n // Interrupt signals\n .irq_i ( irq_i ),\n .irq_id_i ( irq_id_i ),\n\n .m_IE_i ( m_irq_enable_i )\n );\n\n //////////////\n // ID-EX/WB //\n //////////////\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 assign instr_executing = (instr_new_i | ~instr_multicycle_done_q);\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 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 assign data_reg_offset_ex_o = data_reg_offset_id;\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 assign mult_en_ex_o = mult_en_id;\n assign div_en_ex_o = div_en_id;\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 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 branch_set_q <= 1'b0;\n instr_multicycle_done_q <= 1'b0;\n end else begin\n id_wb_fsm_cs <= id_wb_fsm_ns;\n branch_set_q <= branch_set_n;\n instr_multicycle_done_q <= instr_multicycle_done_n;\n end\n end\n\n //////////////////\n // ID-EX/WB FSM //\n //////////////////\n\n assign multdiv_en_dec = mult_en_dec | div_en_dec;\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_n = 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) 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_n = 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_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 = id_fsm_e'(1'bX);\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`ifndef VERILATOR\n // make sure that branch decision is valid when jumping\n assert property (\n @(posedge clk_i) (branch_decision_i !== 1'bx || branch_in_dec == 1'b0) ) else\n $display(\"Branch decision is X\");\n\n`ifdef CHECK_MISALIGNED\n assert property (\n @(posedge clk_i) (~lsu_addr_incr_req_i) ) else\n $display(\"Misaligned memory access at %x\",pc_id_i);\n`endif\n\n // the instruction delivered to the ID stage should always be valid\n assert property (\n @(posedge clk_i) (instr_valid_i & (~illegal_c_insn_i)) |-> (!$isunknown(instr_rdata_i)) ) else\n $display(\"Instruction is valid, but has at least one X\");\n\n // make sure multicycles enable signals are unique\n assert property (\n @(posedge clk_i) ~(data_req_dec & multdiv_en_dec)) else\n $display(\"Multicycles enable signals are not unique\");\n\n`endif\n\nendmodule\n", "selected_doc_paths": ["doc/register_file.rst", "doc/instruction_fetch.rst", "doc/load_store_unit.rst", "doc/exception_interrupts.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 48, "lang": "sv", "rtl_files": ["rtl/ibex_compressed_decoder.sv"], "spec": "# Compressed Instruction Decoder (ibex) – Behavioral Specification\n\n## 1. Overview\n\nThe compressed instruction decoder translates 16‑bit RISC‑V compressed (C‑extension) instructions into their equivalent 32‑bit RV32 instructions. It operates as a fully combinatorial block; the output is available in the same clock cycle as the input. The module also indicates whether the input instruction is a compressed instruction and whether it is illegal.\n\n## 2. Interface and Behavior\n\nThe module accepts a 32‑bit instruction word and produces:\n\n- A 32‑bit decoded instruction (the equivalent RV32 instruction).\n- A flag indicating that the input instruction is a compressed instruction (i.e., its lowest two bits are not `11`).\n- A flag indicating that the input instruction is illegal (either an undefined compressed encoding or a valid encoding that the RISC‑V specification defines as illegal).\n\n**Instruction length determination** \nIf the two least significant bits of the input instruction are `11`, the input is an uncompressed 32‑bit instruction. In this case the decoder passes the input instruction through unchanged and does not assert the compressed flag. All other bit‑pairs (`00`, `01`, `10`) indicate a 16‑bit compressed instruction; the compressed flag is asserted and the decoder attempts to map it to a corresponding 32‑bit instruction.\n\n**Illegal instruction detection** \nThe module asserts the illegal instruction flag for any compressed encoding that:\n\n- Is reserved or undefined in the RISC‑V C‑extension specification.\n- Uses a register operand that is illegal for that instruction (e.g., `x0` when the encoding explicitly disallows it, or a zero immediate for `c.addi4spn`, `c.addi16sp`, or shift‑immediate operations).\n- Falls into a reserved encoding space (e.g., quadrant `C1` with `funct3=100` and `funct2=11`, sub‑fields that decode to `c.subw`/`c.addw` in RV32).\n\nWhen the illegal instruction flag is asserted, the output instruction is undefined.\n\n---\n\n## 3. Decoding Rules by Quadrant\n\nThe compressed instructions are grouped by the two least‑significant bits. The third‑most significant bits (`bits 15:13`) further select the operation within each quadrant.\n\n### 3.1 Quadrant C0 (`bits[1:0] = 00`)\n\n| `bits[15:13]` | Decoded behavior |\n|---------------|------------------|\n| `000` | **c.addi4spn** – Decode to `ADDI rd', x2, nzuimm`. The immediate is formed from bits `[12:11]`, `[10:7]`, `[6]`, `[5]`. If the immediate field is all zero, the instruction is illegal. |\n| `010` | **c.lw** – Decode to `LW rd', offset(rs1')`. The offset is formed from bits `[12:10]`, `[6]`, `[5]`. |\n| `110` | **c.sw** – Decode to `SW rs2', offset(rs1')`. The offset is formed from bits `[12]`, `[11:10]`, `[6]`, `[5]`. |\n| others | Illegal. |\n\n*Note: `rd'` and `rs1'` refer to the compressed register encodings that map to RV32 registers `x8`…`x15`.*\n\n### 3.2 Quadrant C1 (`bits[1:0] = 01`)\n\n| `bits[15:13]` | Decoded behavior |\n|---------------|------------------|\n| `000` | **c.addi** (or **c.nop** when `rd = x0`). Decode to `ADDI rd, rd, nzimm`. The immediate is a 6‑bit sign‑extended value formed from `[12]`, `[6:2]`. |\n| `001` / `101` | **c.jal** (001) or **c.j** (101). Decode to `JAL x1, imm` or `JAL x0, imm` respectively. The immediate is a 12‑bit branch‑style offset constructed from instruction bits. |\n| `010` | **c.li** – Decode to `ADDI rd, x0, nzimm`. If `rd = x0` the instruction is illegal. |\n| `011` | **c.lui** – Decode to `LUI rd, imm`. If `rd = x0` the instruction is illegal. If `rd = x2` (sp), the encoding is reinterpreted as **c.addi16sp**: decode to `ADDI x2, x2, nzimm`. The immediate field must be non‑zero (otherwise illegal). |\n| `100` | Sub‑quadrant selected by `bits[11:10]`:
• `00` – **c.srli**: `SRLI rd', rd', shamt`. `shamt` must be non‑zero; `bit[12]` must be `0`.
• `01` – **c.srai**: `SRAI rd', rd', shamt`. Same constraints.
• `10` – **c.andi**: `ANDI rd', rd', imm`.
• `11` – Select by `bits[12]` and `bits[6:5]`:
 `000` – **c.sub**: `SUB rd', rd', rs2'`
 `001` – **c.xor**: `XOR rd', rd', rs2'`
 `010` – **c.or**: `OR rd', rd', rs2'`
 `011` – **c.and**: `AND rd', rd', rs2'`
 `100`–`111` – Illegal (reserved, correspond to RV64 c.subw/c.addw). |\n| `110` / `111` | **c.beqz** (110) or **c.bnez** (111). Decode to `BEQ rs1', x0, imm` or `BNE rs1', x0, imm`. The immediate is formed following the B‑type encoding. |\n| others | Illegal. |\n\n### 3.3 Quadrant C2 (`bits[1:0] = 10`)\n\n| `bits[15:13]` | Decoded behavior |\n|---------------|------------------|\n| `000` | **c.slli** – Decode to `SLLI rd, rd, shamt`. The register must not be `x0`; `shamt` must be non‑zero; `bit[12]` must be `0` (excluding the HINT space). Violation causes illegal. |\n| `010` | **c.lwsp** – Decode to `LW rd, offset(x2)`. Register `rd` must not be `x0`. |\n| `100` | Sub‑case selected by `bit[12]` and `bits[6:2]`:
• `bit[12]=0`:
 If `bits[6:2]` ≠ `0` – **c.mv**: `ADD rd/rs1, x0, rs2`.
 If `bits[6:2] == 0` – **c.jr**: `JALR x0, rs1, 0`. The register `rs1` (bits `[11:7]`) must not be `x0` (otherwise illegal).
• `bit[12]=1`:
 If `bits[6:2]` ≠ `0` – **c.add**: `ADD rd, rd, rs2`.
 If `bits[6:2] == 0`:
  If `bits[11:7] == 0` – **c.ebreak**: output is the 32‑bit `EBREAK` instruction (`0x00100073`).
  If `bits[11:7] != 0` – **c.jalr**: `JALR x1, rs1, 0`. |\n| `110` | **c.swsp** – Decode to `SW rs2, offset(x2)`. |\n| `001`, `011`, `101`, `111` | Illegal. |\n| others | Illegal. |\n\n---\n\n## 4. Special Conditions\n\n- **HINT instructions** – Some compressed encodings that are architecturally defined as HINTs (e.g., `c.nop`, certain shift‑immediates with zero shift amount) are treated as nops rather than illegal. The decoder follows the same decoding path (they become an `add` or `slli` with a zero immediate that the architectural HINT specification defines). The illegal flag is not asserted for those cases.\n- **Uncompressed instructions** – When `bits[1:0] == 11` the module outputs the input instruction unchanged and does not assert the compressed flag. No decoding is performed.\n- **Output width** – The decoded output is always 32 bits, even though the original compressed instruction is 16 bits.\n\n---\n\n## 5. Error Conditions\n\nThe illegal instruction flag shall be asserted (high) for any of the following:\n\n- Any compressed encoding with `bits[1:0]` not `11` that does not match a defined encoding in the tables above.\n- Specific encodings explicitly marked as illegal by the RISC‑V specification:\n - `c.addi4spn` with a zero immediate.\n - `c.li` with `rd = x0`.\n - `c.lui` with `rd = x0` (but `c.addi16sp` is allowed when `rd = x2`).\n - `c.lui` with a zero immediate (`bits[12]` and `bits[6:2]` all zero).\n - `c.addi16sp` with a zero immediate.\n - `c.slli` with `rd = x0`, or with a zero shift amount, or with `bit[12]=1`.\n - `c.srli`/`c.srai` with zero shift amount or `bit[12]=1`.\n - `c.lwsp` with `rd = x0`.\n - `c.jr` with `rs1 = x0`.\n - Reserved encodings in the `C1` quadrant (`funct3=100`, `funct2=11`, sub‑fields `100`–`111`).\n - All reserved encodings in quadrant `C2` (`funct3 = 001`, `011`, `101`, `111`).\n\nWhen the illegal flag is asserted, the content of the decoded instruction output is undefined.\n\n---\n\n## 6. Performance and Timing\n\nThe module is purely combinatorial; the outputs are valid immediately after the input stabilizes. There are no clocked registers, no pipelining, and no state dependencies. The propagation delay is determined solely by the logic depth of the decoder.\n\n---\n\n## 7. Area and Implementation Notes (informative)\n\nThe decoder uses only combinational logic and can be synthesized with minimal area. The design is intended for use in a RISC‑V processor pipeline stage where early decoding of compressed instructions is required.", "commit_id": "145269fdc88e1d545fca692fd3e3a43c99e1ac12", "timestamp": "2019-05-23T09:05:04+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "409892ec8c4bf47a03b3c2107b79e701b2628bb6", "pr_title": "Compressed hints", "pr_body": "Fix handling of HINTs in compressed instructions. \r\n\r\nFixes #46 (and a bit more)\r\n\r\n\r\n@taoliug can you re-test with these modifications?\r\n@asb does my reading of the spec sound about right?", "issue_title": "Evaluate the feasibility of parameterising ibex by XLEN", "issue_body": "It could be interesting to support RV64I as well as RV32I (imagine small helper cores, with access to the same address space as a larger 64-bit application cores). Before leaping into doing this, someone needs to do the ground work to see how disruptive it might be, so we can evaluate the potential maintenance / readability costs vs the benefits of supporting an RV64I configuration.", "commit_message": "Fix handling of C.MV and C.JR\n\n- Decoding must give precedence to rs2 (i.e. instr_i[6:2]) to\n switch between C.MV and C.JR.\n \"C.MV is only valid when rs2̸=x0; the code points with rs2=x0\n correspond to the C.JR instruction. The code points with rs2̸=x0\n and rd=x0 are HINTs.\"\n\n- C.JR is only valid with rs1==x0. Throw an illegal instruction\n exception if that's not the case.\n \"C.JR is only valid when rs1̸=x0; the code point with rs1=x0\n is reserved.\" RV32 Spec, p103\n\nAll spec references based on RISC-V Unprivileged ISA\nV20190305-Base-Ratification", "fix_patch": "diff --git a/rtl/ibex_compressed_decoder.sv b/rtl/ibex_compressed_decoder.sv\nindex 1fac9d559f..d0b31dd7a0 100644\n--- a/rtl/ibex_compressed_decoder.sv\n+++ b/rtl/ibex_compressed_decoder.sv\n@@ -206,24 +206,28 @@ module ibex_compressed_decoder (\n \n 3'b100: begin\n if (instr_i[12] == 1'b0) begin\n- // c.mv -> add rd/rs1, x0, rs2\n- instr_o = {7'b0, instr_i[6:2], 5'b0, 3'b0, instr_i[11:7], {OPCODE_OP}};\n-\n- if (instr_i[6:2] == 5'b0) begin\n+ if (instr_i[6:2] != 5'b0) begin\n+ // c.mv -> add rd/rs1, x0, rs2\n+ // (c.mv hints are translated into an add hint)\n+ instr_o = {7'b0, instr_i[6:2], 5'b0, 3'b0, instr_i[11:7], {OPCODE_OP}};\n+ end else begin\n // c.jr -> jalr x0, rd/rs1, 0\n instr_o = {12'b0, instr_i[11:7], 3'b0, 5'b0, {OPCODE_JALR}};\n+ if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n end\n end else begin\n- // c.add -> add rd, rd, rs2\n- instr_o = {7'b0, instr_i[6:2], instr_i[11:7], 3'b0, instr_i[11:7], {OPCODE_OP}};\n-\n- if (instr_i[11:7] == 5'b0) begin\n- // c.ebreak -> ebreak\n- instr_o = {32'h00_10_00_73};\n- if (instr_i[6:2] != 5'b0) illegal_instr_o = 1'b1;\n- end else if (instr_i[6:2] == 5'b0) begin\n- // c.jalr -> jalr x1, rs1, 0\n- instr_o = {12'b0, instr_i[11:7], 3'b000, 5'b00001, {OPCODE_JALR}};\n+ if (instr_i[6:2] != 5'b0) begin\n+ // c.add -> add rd, rd, rs2\n+ // (c.add hints are translated into an add hint)\n+ instr_o = {7'b0, instr_i[6:2], instr_i[11:7], 3'b0, instr_i[11:7], {OPCODE_OP}};\n+ end else begin\n+ if (instr_i[11:7] == 5'b0) begin\n+ // c.ebreak -> ebreak\n+ instr_o = {32'h00_10_00_73};\n+ end else begin\n+ // c.jalr -> jalr x1, rs1, 0\n+ instr_o = {12'b0, instr_i[11:7], 3'b000, 5'b00001, {OPCODE_JALR}};\n+ end\n end\n end\n end\n", "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// //\n// Engineer: Sven Stucki - svstucki@student.ethz.ch //\n// //\n// Design Name: Compressed instruction decoder //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Decodes RISC-V compressed instructions into their RV32 //\n// equivalent. This module is fully combinatorial. //\n// //\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Compressed instruction decoder\n *\n * Decodes RISC-V compressed instructions into their RV32 equivalent.\n * This module is fully combinatorial.\n */\nmodule ibex_compressed_decoder (\n input logic [31:0] instr_i,\n output logic [31:0] instr_o,\n output logic is_compressed_o,\n output logic illegal_instr_o\n);\n import ibex_defines::*;\n\n ////////////////////////\n // Compressed decoder //\n ////////////////////////\n\n always_comb begin\n illegal_instr_o = 1'b0;\n instr_o = 'X;\n\n unique case (instr_i[1:0])\n // C0\n 2'b00: begin\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.addi4spn -> addi rd', x2, imm\n instr_o = {2'b0, instr_i[10:7], instr_i[12:11], instr_i[5],\n instr_i[6], 2'b00, 5'h02, 3'b000, 2'b01, instr_i[4:2], {OPCODE_OPIMM}};\n if (instr_i[12:5] == 8'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b010: begin\n // c.lw -> lw rd', imm(rs1')\n instr_o = {5'b0, instr_i[5], instr_i[12:10], instr_i[6],\n 2'b00, 2'b01, instr_i[9:7], 3'b010, 2'b01, instr_i[4:2], {OPCODE_LOAD}};\n end\n\n 3'b110: begin\n // c.sw -> sw rs2', imm(rs1')\n instr_o = {5'b0, instr_i[5], instr_i[12], 2'b01, instr_i[4:2],\n 2'b01, instr_i[9:7], 3'b010, instr_i[11:10], instr_i[6],\n 2'b00, {OPCODE_STORE}};\n end\n\n default: begin\n illegal_instr_o = 1'b1;\n end\n endcase\n end\n\n // C1\n 2'b01: begin\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.addi -> addi rd, rd, nzimm\n // c.nop\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2],\n instr_i[11:7], 3'b0, instr_i[11:7], {OPCODE_OPIMM}};\n end\n\n 3'b001, 3'b101: begin\n // 001: c.jal -> jal x1, imm\n // 101: c.j -> jal x0, imm\n instr_o = {instr_i[12], instr_i[8], instr_i[10:9], instr_i[6],\n instr_i[7], instr_i[2], instr_i[11], instr_i[5:3],\n {9 {instr_i[12]}}, 4'b0, ~instr_i[15], {OPCODE_JAL}};\n end\n\n 3'b010: begin\n // c.li -> addi rd, x0, nzimm\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2], 5'b0,\n 3'b0, instr_i[11:7], {OPCODE_OPIMM}};\n if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b011: begin\n // c.lui -> lui rd, imm\n instr_o = {{15 {instr_i[12]}}, instr_i[6:2], instr_i[11:7], {OPCODE_LUI}};\n\n if (instr_i[11:7] == 5'h02) begin\n // c.addi16sp -> addi x2, x2, nzimm\n instr_o = {{3 {instr_i[12]}}, instr_i[4:3], instr_i[5], instr_i[2],\n instr_i[6], 4'b0, 5'h02, 3'b000, 5'h02, {OPCODE_OPIMM}};\n end else if (instr_i[11:7] == 5'b0) begin\n illegal_instr_o = 1'b1;\n end\n\n if ({instr_i[12], instr_i[6:2]} == 6'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b100: begin\n unique case (instr_i[11:10])\n 2'b00,\n 2'b01: begin\n // 00: c.srli -> srli rd, rd, shamt\n // 01: c.srai -> srai rd, rd, shamt\n instr_o = {1'b0, instr_i[10], 5'b0, instr_i[6:2], 2'b01, instr_i[9:7],\n 3'b101, 2'b01, instr_i[9:7], {OPCODE_OPIMM}};\n if (instr_i[12] == 1'b1) illegal_instr_o = 1'b1;\n if (instr_i[6:2] == 5'b0) illegal_instr_o = 1'b1;\n end\n\n 2'b10: begin\n // c.andi -> andi rd, rd, imm\n instr_o = {{6 {instr_i[12]}}, instr_i[12], instr_i[6:2], 2'b01, instr_i[9:7],\n 3'b111, 2'b01, instr_i[9:7], {OPCODE_OPIMM}};\n end\n\n 2'b11: begin\n unique case ({instr_i[12], instr_i[6:5]})\n 3'b000: begin\n // c.sub -> sub rd', rd', rs2'\n instr_o = {2'b01, 5'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7],\n 3'b000, 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b001: begin\n // c.xor -> xor rd', rd', rs2'\n instr_o = {7'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7], 3'b100,\n 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b010: begin\n // c.or -> or rd', rd', rs2'\n instr_o = {7'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7], 3'b110,\n 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b011: begin\n // c.and -> and rd', rd', rs2'\n instr_o = {7'b0, 2'b01, instr_i[4:2], 2'b01, instr_i[9:7], 3'b111,\n 2'b01, instr_i[9:7], {OPCODE_OP}};\n end\n\n 3'b100,\n 3'b101,\n 3'b110,\n 3'b111: begin\n // 100: c.subw\n // 101: c.addw\n illegal_instr_o = 1'b1;\n end\n\n default: begin\n illegal_instr_o = 1'bX;\n end\n endcase\n end\n\n default: begin\n illegal_instr_o = 1'bX;\n end\n endcase\n end\n\n 3'b110, 3'b111: begin\n // 0: c.beqz -> beq rs1', x0, imm\n // 1: c.bnez -> bne rs1', x0, imm\n instr_o = {{4 {instr_i[12]}}, instr_i[6:5], instr_i[2], 5'b0, 2'b01,\n instr_i[9:7], 2'b00, instr_i[13], instr_i[11:10], instr_i[4:3],\n instr_i[12], {OPCODE_BRANCH}};\n end\n\n default: begin\n illegal_instr_o = 1'bX;\n end\n endcase\n end\n\n // C2\n 2'b10: begin\n unique case (instr_i[15:13])\n 3'b000: begin\n // c.slli -> slli rd, rd, shamt\n instr_o = {7'b0, instr_i[6:2], instr_i[11:7], 3'b001, instr_i[11:7], {OPCODE_OPIMM}};\n if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n if (instr_i[12] == 1'b1 || instr_i[6:2] == 5'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b010: begin\n // c.lwsp -> lw rd, imm(x2)\n instr_o = {4'b0, instr_i[3:2], instr_i[12], instr_i[6:4], 2'b00, 5'h02,\n 3'b010, instr_i[11:7], OPCODE_LOAD};\n if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n end\n\n 3'b100: begin\n if (instr_i[12] == 1'b0) begin\n if (instr_i[6:2] != 5'b0) begin\n // c.mv -> add rd/rs1, x0, rs2\n // (c.mv hints are translated into an add hint)\n instr_o = {7'b0, instr_i[6:2], 5'b0, 3'b0, instr_i[11:7], {OPCODE_OP}};\n end else begin\n // c.jr -> jalr x0, rd/rs1, 0\n instr_o = {12'b0, instr_i[11:7], 3'b0, 5'b0, {OPCODE_JALR}};\n if (instr_i[11:7] == 5'b0) illegal_instr_o = 1'b1;\n end\n end else begin\n if (instr_i[6:2] != 5'b0) begin\n // c.add -> add rd, rd, rs2\n // (c.add hints are translated into an add hint)\n instr_o = {7'b0, instr_i[6:2], instr_i[11:7], 3'b0, instr_i[11:7], {OPCODE_OP}};\n end else begin\n if (instr_i[11:7] == 5'b0) begin\n // c.ebreak -> ebreak\n instr_o = {32'h00_10_00_73};\n end else begin\n // c.jalr -> jalr x1, rs1, 0\n instr_o = {12'b0, instr_i[11:7], 3'b000, 5'b00001, {OPCODE_JALR}};\n end\n end\n end\n end\n\n 3'b110: begin\n // c.swsp -> sw rs2, imm(x2)\n instr_o = {4'b0, instr_i[8:7], instr_i[12], instr_i[6:2], 5'h02, 3'b010,\n instr_i[11:9], 2'b00, {OPCODE_STORE}};\n end\n\n 3'b001,\n 3'b011,\n 3'b101,\n 3'b111: begin\n illegal_instr_o = 1'b1;\n end\n\n default: begin\n illegal_instr_o = 1'bX;\n end\n endcase\n end\n\n default: begin\n // 32 bit (or more) instruction\n instr_o = instr_i;\n end\n endcase\n end\n\n assign is_compressed_o = (instr_i[1:0] != 2'b11);\n\nendmodule\n", "selected_doc_paths": []}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 172, "lang": "sv", "rtl_files": ["rtl/ibex_decoder.sv"], "spec": "# Behavioral Design Specification: Ibex Decoder (`ibex_decoder`)\n\n## Overview\n\nThe decoder is the central instruction decode unit of the Ibex RISC-V core. \nIt receives a 32-bit instruction word from the IF-ID pipeline stage and produces all control signals required by subsequent pipeline stages (EX, MEM, WB), the register file, the load-store unit (LSU), the ALU, the multiply/divide unit, and the CSR logic.\n\nThe decoder must identify the instruction, extract immediate values and register addresses, select ALU operations, generate memory request signals, and detect illegal instructions. \nIt also implements the RV32E register‑file restriction (only registers x0–x15 are available) and conditionally enables the RV32M integer multiplication and division extension based on a parameter.\n\n## Interface (Observable Behavior)\n\nThe decoder communicates with:\n\n- **Controller**: flags for illegal instruction, trap instructions (EBREAK, ECALL, MRET, DRET, WFI), and jump‑taken signals.\n- **IF-ID pipeline register**: receives the instruction data and a “new instruction” indicator.\n- **Register file**: provides read addresses for two source registers and a write address for the destination register, plus a write enable.\n- **Immediate generation**: outputs five pre‑computed immediate values (I‑type, S‑type, B‑type, U‑type, J‑type) and a zero‑extended CSR immediate (zimm).\n- **ALU**: selects the operation, operand A source (register, PC, immediate, or zero), operand B source (register or immediate), and immediate‑select muxes.\n- **Multiply/Divide unit**: enables for multi-cycle multiplication or division, selects the operation (MUL, MULH, DIV, REM, etc.), and indicates signedness mode.\n- **CSR logic**: enables CSR access, selects the CSR operation (read, write, set, clear), and flags access to the `mstatus` or debug CSRs to trigger pipeline flushes.\n- **Load‑Store Unit**: generates request, write enable, data size (byte, halfword, word), sign extension control, and byte offset for stores.\n\n## Functional Behavior\n\n### 1. Instruction Decode Categories\n\nThe decoder distinguishes the following major opcode groups:\n\n#### Jumps (JAL, JALR)\n- **JAL (Jump and Link)**:\n - In the first cycle (`instr_new_i` asserted): compute the jump target by adding the current PC to a J‑type immediate; suppress register write.\n - In the second cycle: compute PC+4 and write it to the destination register; the jump is already taken.\n- **JALR (Jump and Link Register)**:\n - Similar two‑cycle protocol: first cycle computes target = register value + I‑type immediate; second cycle writes PC+4.\n - If the `funct3` field is not zero, the instruction is illegal.\n\n#### Branches (BEQ, BNE, BLT, BGE, BLTU, BGEU)\n- The condition is evaluated in the first cycle using the two source registers.\n- In the second cycle the branch target is computed by adding the current PC to a B‑type immediate.\n- The operation selected for condition evaluation must match the `funct3` encoding:\n - `000` → equal\n - `001` → not equal\n - `100` → less than (signed)\n - `101` → greater than or equal (signed)\n - `110` → less than (unsigned)\n - `111` → greater than or equal (unsigned)\n- Any other `funct3` value causes an illegal instruction.\n\n#### Loads (LB, LH, LW, LBU, LHU)\n- Compute the effective address by adding the base register (rs1) to an I‑type immediate (or to a register rs2 for the `funct3=111` variant – effectively a register‑register load encoding).\n- The effective address is output to the LSU along with the request signal.\n- Data size is determined by `funct3[1:0]`:\n - `00` → byte\n - `01` → halfword\n - `10` → word\n - `11` or `011` → illegal (LD is RV64 only; reg‑reg encoding `funct3=111` is handled separately).\n- Sign extension is controlled by `funct3[2]`: if clear, zero‑extend; if set (for unsigned loads), the result is zero‑extended.\n- The load result is written to the destination register (rd).\n\n#### Stores (SB, SH, SW)\n- Compute the effective address by adding the base register (rs1) to an S‑type immediate.\n- Data size is selected by `funct3[1:0]` (same encoding as loads).\n- Store data and byte enables are driven by the LSU.\n- If `funct3[2]` is set (indicating a register offset), the instruction is illegal (no register‑register store in RV32I).\n\n#### ALU Immediate Operations (ADDI, SLTI, SLTIU, XORI, ORI, ANDI, SLLI, SRLI, SRAI)\n- Source operand A is the register value (rs1); operand B is the I‑type immediate.\n- Operation is selected by `funct3`:\n - `000` → ADD\n - `010` → SLT (set less than, signed)\n - `011` → SLTU (unsigned)\n - `100` → XOR\n - `110` → OR\n - `111` → AND\n - `001` → SLL (shift left logical). The shift amount field (`imm[5:0]` plus `funct7`) must be all zeros; otherwise illegal.\n - `101` → SRL if `funct7` is zero; SRA if `funct7` is `010_0000`; otherwise illegal.\n- Result is written to the destination register (rd).\n\n#### ALU Register Operations (ADD, SUB, SLT, SLTU, XOR, OR, AND, SLL, SRL, SRA)\n- Both source operands come from registers (rs1, rs2).\n- The operation is determined by the combination of `funct7` and `funct3`:\n - Standard RV32I operations as listed above.\n- If `funct7` bit 5 (i.e., `instr[31]`) is set, the instruction is illegal (this bit is used for the RV32M extension – see below).\n\n#### Multiply/Divide (RV32M extension, conditional on parameter `RV32M = 1`)\n- When `funct7` is `b0000001` (the M‑extension prefix), the decoder enables multiplication or division based on `funct3`:\n - `000` → MUL (signed×signed, low 32 bits)\n - `001` → MULH (signed×signed, high 32 bits)\n - `010` → MULHSU (signed×unsigned, high)\n - `011` → MULHU (unsigned×unsigned, high)\n - `100` → DIV (signed division)\n - `101` → DIVU (unsigned division)\n - `110` → REM (signed remainder)\n - `111` → REMU (unsigned remainder)\n- The `mult_en_o` and `div_en_o` signals are asserted accordingly only when `RV32M` is true.\n- If `RV32M` is false, these instructions are illegal.\n- The operation output for the ALU is set to ADD (the actual multiplication/division will be handled by the dedicated unit; the ALU result is not used for these instructions in the same way).\n\n#### LUI and AUIPC\n- **LUI**: adds a U‑type immediate to zero → result written to rd.\n- **AUIPC**: adds a U‑type immediate to the current PC → result written to rd.\n\n#### Miscellaneous Memory (FENCE)\n- `funct3 = 000` is treated as a nop (no operation).\n- `funct3 = 001` (FENCE.I) is illegal (Zifencei extension not implemented).\n- All other `funct3` values are illegal.\n\n#### System Instructions\n- **Non‑CSR** (`funct3 = 000`): Identified by the 12‑bit opcode field (`instr[31:20]`):\n - `0x000` → ECALL (environment call)\n - `0x001` → EBREAK (breakpoint/debug trap)\n - `0x302` → MRET (return from machine mode exception)\n - `0x7B2` → DRET (return from debug mode)\n - `0x105` → WFI (wait for interrupt)\n - Any other value → illegal.\n - Additionally, if either rs1 or rd is non‑zero, the instruction is illegal.\n- **CSR operations** (`funct3 != 000`):\n - The decoder selects the CSR address from the I‑type immediate field.\n - The write data source is either a register value (when `funct3[2] = 0`) or a zero‑extended 5‑bit immediate from rs1 (when `funct3[2] = 1`).\n - The operation is determined by `funct3[1:0]`:\n - `01` → CSR write (full replacement)\n - `10` → CSR set (bitwise OR)\n - `11` → CSR clear (bitwise AND with inverted immediate)\n - `00` → illegal\n - If the specified CSR is `mstatus`, `dcsr`, `dpc`, `dscratch0`, or `dscratch1`, the decoder asserts a pipeline‑flush signal (`csr_status_o`).\n - The decoder also checks that CSRRSI/CSRRCI with zero immediate (`rs1 = 0`) and CSRRS/CSRRC with `rs1 = x0` are converted to a CSR read operation (no write).\n\n### 2. Immediate Generation\n\nThe decoder extracts and sign‑extends the following immediates from the instruction word, as required by the RISC‑V specification:\n\n- **I‑type**: 12‑bit signed immediate (bits [31:20]) – used for loads, ALU immediates, JALR, and CSR address.\n- **S‑type**: 12‑bit signed immediate formed from bits [31:25] and [11:7] – used for stores.\n- **B‑type**: 13‑bit signed immediate formed from bits [31, 7, 30:25, 11:8] – used for branches.\n- **U‑type**: 20‑bit upper immediate (bits [31:12]) – used for LUI and AUIPC.\n- **J‑type**: 21‑bit signed immediate formed from bits [31, 19:12, 20, 30:21] – used for JAL.\n- **zimm**: 5‑bit zero‑extended immediate from register rs1 field – used for CSR immediate‑type instructions.\n\n### 3. Register File Interaction\n\n- Read addresses are extracted directly from the instruction:\n - rs1 from bits [19:15]\n - rs2 from bits [24:20]\n- The write address (rd) is extracted from bits [11:7].\n- The register file write enable is asserted for instructions that produce a result: JAL (second cycle), JALR (second cycle), LUI, AUIPC, ALU operations (both immediate and register), loads, and CSR accesses.\n- Write enable is suppressed for illegal instructions or when an RV32E illegal register access is detected.\n\n### 4. Error Detection and Illegal Instruction Handling\n\nThe decoder must detect the following illegal instruction conditions:\n\n- **Illegal opcode** (any opcode not assigned in the case statement).\n- **Undefined funct3 or funct7** within a legal opcode (e.g., invalid branch condition, invalid shifter encoding, illegal load/store size, etc.).\n- **Funct3=000 with non‑zero rs1/rd** for system calls.\n- **Funct3=000 with unrecognized 12‑bit opcode** for system instructions.\n- **Funct3=011 for loads** (RV64-only LD).\n- **Funct3=100 for stores** (register‑offset store, which does not exist).\n- **Funct3=111 for loads with undefined funct7** (reg‑reg load variants not supported).\n- **Funct7 bit 5 set for ALU register operations** (that bit is reserved for M‑extension; if M‑extension is enabled, the M‑prefix `b0000001` is legal; any other `funct7` with bit 5 set is illegal).\n- **RV32M instructions when `RV32M=0`**.\n- **Compressed instruction decode failure** (input `illegal_c_insn_i`); this makes the instruction illegal regardless of other decode results.\n- **RV32E register violations**: on a core configured for RV32E, any access (read or write) to register x16–x31 through the corresponding address fields (msb of address is 1) in an instruction that would actually use that register (i.e., the register field is active) is illegal. The decoder checks:\n - rs1 with msb=1 when operand A is selected from register A.\n - rs2 with msb=1 when operand B is selected from register B.\n - rd with msb=1 when the write enable is asserted.\n - The illegal condition is ORed with the main `illegal_insn` signal.\n\nWhen an illegal instruction is detected (including RV32E violations), the decoder must:\n\n- Clear all strobe signals that could cause side effects: register file write enable, data request, data write enable, multiply/divide enables, jump/branch in‑decoder flags, CSR access.\n- Assert the `illegal_insn_o` output flag (which is the OR of `illegal_insn` and `illegal_reg_rv32e`).\n- The register file write enable output is gated with `~illegal_reg_rv32e` so that writes to forbidden registers are never propagated.\n\n### 5. Pipeline Control Signals\n\n- **Jump in decoder**: asserted for JAL and JALR during both cycles.\n- **Jump set**: asserted in the first cycle of JAL/JALR to indicate that the PC should be updated.\n- **Branch in decoder**: asserted for all branch instructions during both cycles.\n- The decoder also provides a `csr_status_o` flag that indicates an access to `mstatus` or debug CSRs; this flag is used by the controller to flush the pipeline.\n\n### 6. Configuration Parameters\n\n- **RV32E**: When set to 1, the decoder restricts register files to x0–x15 (5‑bit addresses with msb=0 are valid only for the specific operand selection cases).\n- **RV32M**: When set to 1, the decoder enables the M‑extension multiplication and division instructions; when set to 0, those instructions are flagged as illegal.\n\n## Timing and Sequential Behavior\n\nThe decoder is combinatorial logic with respect to its inputs and outputs. \nIt does not contain any state elements itself; however, the controller uses the `instr_new_i` signal to distinguish between two phases of execution for multi‑cycle instructions (JAL, JALR, branches). \n\n- When `instr_new_i` is high: the instruction is new, and the first cycle of decode applies (jump target calculation before register write for jumps, condition evaluation for branches).\n- When `instr_new_i` is low: the instruction has already been seen, and the decoder performs the second cycle (writing PC+4 for jumps, computing branch target for branches).\n\nAll other instructions are fully decoded in a single cycle and do not depend on `instr_new_i`.\n\n## Summary of Responsibilities\n\nThe decoder must:\n\n- Correctly decode all RV32I instructions.\n- Conditionally decode RV32M instructions based on the `RV32M` parameter.\n- Detect and report illegal instructions, including those arising from compressed‑instruction decode failures and RV32E register violations.\n- Provide correct immediate values for each instruction type.\n- Generate precise control signals for the register file, ALU, multiply/divide unit, LSU, and CSR logic.\n- Handle the two‑cycle protocol for jumps and branches.\n- Prevent side effects (register writes, memory requests, CSR modifications) for illegal instructions.\n- Observe the RV32E register restriction and suppress writes to the upper half of the register file when enabled.", "commit_id": "f12b94c2a21dfb4779be5c4b9c460eb3f3c48323", "timestamp": "2019-07-18T14:52:27+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "04f4cd44f6b62a48af65f11143278be00d54132b", "pr_title": "Decoder: avoid setting PC upon illegal JALR instructions", "pr_body": "Without this commit, the PC is still set to a possible wrong jump target on illegal JALR instructions ultimately causing the wrong PC being saved to `mepc` during the illegal instruction exception.\r\n\r\nThis bug has been reported by @taoliug. This commit resolves #170.", "issue_title": "MEPC is not updated with correct value for illegal JALR instruction", "issue_body": "spike log\r\n\r\n```\r\ncore 0: 0xffffffff8000f720 (0x65d42c67) unknown\r\ncore 0: exception trap_illegal_instruction, epc 0xffffffff8000f720\r\ncore 0: tval 0x0000000000000000\r\ncore 0: 0x000000008001d000 (0x00007119) addi sp, sp, -128\r\n\r\n```\r\n0x65d42c67 is detected as illegal instruction by ibex correctly. However, seems like the core still executed the JALR instruction which causes the PC changed to some unexpected value(0x65a) and get saved to MEPC eventually.\r\n\r\nibex log:\r\n```\r\n 34443000 17123 8000f720 65d42c67 INVALID \r\n 34465000 17134 0000065a xxxxxxxx lui xx, 0xxxxxx000 \r\n```\r\n![screencapture-remotedesktop-corp-google-access-session-6fd70a76-592d-4962-9324-fb0b435c9f3d-2019-07-17-21_31_58](https://user-images.githubusercontent.com/34581368/61429489-5d695880-a8db-11e9-8493-ca7f5e4068aa.png)\r\n\r\n\r\n\r\n", "commit_message": "Decoder: avoid setting PC upon illegal JALR instructions\n\nWithout this commit, the PC is still set to a possible wrong jump\ntarget on illegal JALR instructions ultimately causing the wrong PC\nbeing saved to `mepc` during the illegal instruction exception.\n\nThis bug has been reported by @taoliug. This commit resolves #170.", "fix_patch": "diff --git a/rtl/ibex_decoder.sv b/rtl/ibex_decoder.sv\nindex 03910af64c..7326bf0fec 100644\n--- a/rtl/ibex_decoder.sv\n+++ b/rtl/ibex_decoder.sv\n@@ -602,9 +602,9 @@ module ibex_decoder #(\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+ // into register file, LSU, EX, WB, CSRs, PC\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+ // insufficient privileges), or when accessing non-available registers in RV32E,\n // these cases are not handled here\n if (illegal_insn) begin\n regfile_we = 1'b0;\n@@ -613,6 +613,7 @@ module ibex_decoder #(\n mult_en_o = 1'b0;\n div_en_o = 1'b0;\n jump_in_dec_o = 1'b0;\n+ jump_set_o = 1'b0;\n branch_in_dec_o = 1'b0;\n csr_access_o = 1'b0;\n end\n", "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, PC\n // NOTE: instructions can also be detected to be illegal inside the CSRs (upon accesses with\n // insufficient privileges), or when accessing non-available registers in RV32E,\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 jump_set_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", "selected_doc_paths": ["doc/register_file.rst", "doc/load_store_unit.rst", "doc/cs_registers.rst", "doc/exception_interrupts.rst", "doc/debug.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 40, "lang": "sv", "rtl_files": ["rtl/ibex_id_stage.sv"], "spec": "# Instruction Decode Stage (ID) – Behavioral Specification\n\n## 1. Overview\n\nThe Instruction Decode (ID) stage is part of the core pipeline. It receives a fetched instruction from the Instruction Fetch (IF) stage, decodes it, reads the register file, prepares operand data for the Execute (EX) stage, and controls the flow of multi-cycle operations (loads, stores, multiplications, divisions, jumps, and branches).\n\nThe ID stage is responsible for:\n\n- Determining the type of instruction and its control signals.\n- Reading source registers and forwarding data when necessary.\n- Generating immediates according to the instruction format.\n- Detecting and signalling stalls due to data hazards, multi-cycle instructions, or pipeline control.\n- Managing the write-back of results to the register file (in collaboration with the EX stage and Load/Store Unit).\n\n## 2. Inputs and Outputs (Conceptual)\n\nThe ID stage communicates with:\n\n- **IF stage** – receives valid instruction data and the program counter.\n- **EX stage** – provides operands, ALU and multiplier/divider control signals, and data memory request signals.\n- **Load/Store Unit (LSU)** – receives memory access requests and supplies write-back data after load operations.\n- **Register file** – reads source operands and writes results.\n- **Controller** – receives decoding results and stall signals, provides pipeline control (flush, halt, PC update).\n- **Interrupt controller** – receives interrupt requests and acknowledges.\n- **CSR module** – receives CSR access signals and returns CSR read data.\n- **Performance counters** – provides event indicators for jumps, branches, and taken branches.\n\n## 3. Functional Requirements\n\n### 3.1 Instruction Decoding\n\nThe ID stage shall decode the 32‑bit instruction (or compressed instruction after expansion) to determine:\n\n- The operation to be performed (ALU operation, memory access, CSR access, multiplication/division).\n- The register source and destination addresses.\n- The immediate type (I‑type, S‑type, B‑type, U‑type, J‑type, zero‑extended CSR immediate).\n- Whether the instruction is a jump, branch, or other multi-cycle operation.\n- Whether the instruction is illegal, an `ebreak`, `ecall`, `mret`, or `dret`.\n\nIt shall assert an illegal instruction signal when the opcode or fields do not correspond to a valid RISC‑V instruction (including the case where the instruction is a valid compressed instruction whose expansion is illegal).\n\nWhen the `RV32E` parameter is set, the decoder shall also check that the accessed register addresses (source and destination) do not refer to registers x16–x31; a violation shall be treated as an illegal instruction.\n\n### 3.2 Register File Access\n\nThe ID stage hosts the register file with 31 or 15 32‑bit general‑purpose registers (depending on the `RV32E` parameter). Register `x0` is hard‑wired to zero.\n\nIt shall:\n\n- Read the two source registers (addresses encoded in the instruction) on every cycle.\n- Provide operand values to the next stage (after potential forwarding).\n- Write back results from the EX stage, LSU, or CSR read data during the write‑back phase.\n\nThe write‑back destination address and write enable are generated by the ID stage and gated appropriately during multi‑cycle operations.\n\n### 3.3 Operand Preparation\n\nThe ID stage constructs the two operands for the ALU (or for a multiplier/divider):\n\n- **Operand A** can be:\n - A forwarded or direct register value (with possible substitution for misaligned address).\n - The current program counter (`pc_id_i`).\n - An immediate value (zero‑extended CSR immediate `zimm`).\n- **Operand B** can be:\n - A direct register value (second source).\n - One of the five immediate types (I, S, B, U, J) or a PC increment value (2 or 4, depending on whether the instruction is compressed and on misaligned state).\n\nImmediates are sign‑extended or zero‑extended according to the RISC‑V specification.\n\n### 3.4 Forwarding\n\nThe ID stage shall handle the following forwarding cases:\n\n- When a load instruction is waiting for data (multi‑cycle), the operand A may be replaced by the misaligned address from the LSU (`misaligned_addr_i`) if the first part of a misaligned access has already been processed. This is controlled by the controller.\n- All other forwarding (e.g., from a previous ALU operation) is performed in the EX stage; the ID stage simply passes the register file’s output values (after any misaligned address substitution) to the EX stage.\n\n### 3.5 Multi‑Cycle Instruction Handling\n\nThe ID stage controls the progress of instructions that require more than one cycle:\n\n- **Loads and stores**: The request is sent to the LSU. The ID stage stalls until the EX stage signals readiness (`ex_ready_i`). During the wait, write‑back is disabled.\n- **Multiplications and divisions**: The multiplier/divider operation is started. The ID stage stalls until the EX stage signals completion.\n- **Conditional branches**: If the branch is taken (as determined by `branch_decision_i`), the ID stage stalls for one extra cycle while the controller updates the PC. If not taken, the instruction completes in a single cycle.\n- **Unconditional jumps**: The ID stage stalls for one cycle while the PC is set to the target address. Write‑back is held until the next cycle.\n\nThe ID stage shall output a signal indicating that a multi‑cycle instruction is in progress so that the controller can manage concurrent events (interrupts, exceptions).\n\n### 3.6 Stall and Pipeline Control\n\nThe ID stage generates stall/hold signals:\n\n- It shall halt the IF stage (`halt_if_o`) when the ID stage is not ready to accept a new instruction (e.g., during a multi‑cycle operation) or when a flush is required.\n- It shall indicate to the IF stage when it is ready for the next instruction (`id_ready_o`). This signal is the combination of no load stall, no branch stall, no jump stall, and no multiplier/divider stall.\n- It shall provide a valid signal (`id_valid_o`) that is true when the instruction is valid and the ID stage is not being halted.\n\nThe ID stage also outputs `clear_instr_valid_o` to invalidate the current instruction in the IF/ID pipeline register when the ID stage is ready or halted (to prevent re‑decoding).\n\n### 3.7 Branch and Jump Handling\n\nWhen a branch instruction is decoded:\n\n- The ID stage shall compute whether the branch is taken using the external `branch_decision_i` input.\n- If taken, it sets a branch flag (`branch_set`) that is registered and used by the controller to update the PC.\n- It also outputs a performance counter event (`perf_branch_o`) for each branch instruction, and `perf_tbranch_o` only for taken branches.\n\nWhen a jump instruction (JAL, JALR) is decoded:\n\n- The ID stage asserts a jump flag (`jump_set`) to the controller to set the new PC.\n- It outputs a performance counter event (`perf_jump_o`).\n\nAll jump/branch signalling is clocked and synchronized with the FSM that handles multi-cycle transitions.\n\n### 3.8 CSR Access\n\nThe ID stage decodes CSR instructions and passes the CSR operation type and access signal to the EX stage. CSR read data is returned to the ID stage from the CSR module and selected in the write‑back mux when a CSR instruction is executed.\n\n### 3.9 Exception and Interrupt Support\n\nThe ID stage interfaces with the controller and interrupt controller to:\n\n- Recognise exception‑causing instructions (illegal, `ecall`, `ebreak`, `mret`, `dret`).\n- Provide the exception cause to the controller.\n- Forward the interrupt request and ID from the interrupt controller to the controller.\n- Acknowledge interrupts and indicate which interrupt ID is taken.\n\nThe ID stage does not itself handle exception prioritisation or trap entry; it only decodes the instruction and forwards exception‑relevant information.\n\n### 3.10 Write‑Back Data Selection\n\nThe ID stage selects the data to be written back to the register file from three sources:\n\n- **EX stage result** (ALU, multiplier/divider, or branch target).\n- **LSU load data** (when the instruction is a load).\n- **CSR read data** (when the instruction is a CSR read).\n\nThe selection is made based on the type of instruction that is completing in the write‑back cycle.\n\nDuring multi‑cycle operations, write‑back is disabled until the instruction finishes.\n\n### 3.11 Performance Counters\n\nThe ID stage shall output the following event indicators:\n\n- `perf_jump_o`: asserted for one cycle when a jump instruction (JAL, JALR) is decoded and starts execution.\n- `perf_branch_o`: asserted for one cycle when a branch instruction is decoded (both taken and not taken).\n- `perf_tbranch_o`: asserted for one cycle when a branch instruction is decoded and the branch is taken.\n\nThese signals are used by the performance counter unit to increment counter registers.\n\n### 3.12 Assertions (Non‑Functional Verification Guidance)\n\nThe module contains embedded assertions for verification that shall not be synthesised but are present in simulation:\n\n- The `branch_decision_i` signal must be stable (not X) when a branch instruction is present.\n- Misaligned memory accesses (observed by the ID stage) must not happen (optional check).\n- A valid instruction of 32 bits must not contain X values.\n- Multi‑cycle enable signals for LSU and multiplier/divider shall not be active simultaneously.\n\n## 4. Behavior Under Reset\n\nUpon reset (`rst_ni` de‑asserted), the ID stage shall:\n\n- Clear all internal state (FSM, branch_set register).\n- Not request new instructions.\n- Hold all outputs in their reset state (typically zero).\n\n## 5. Configuration Parameters\n\n- **RV32E** (bit): When set, the register file contains 15 registers (x0–x14) instead of 31. The decoder shall treat any access to register addresses with bit 4 set as an illegal instruction.\n- **RV32M** (bit): When set, the multiplier/divider unit is present, and the decoder may issue multiplication and division instructions. When cleared, these instructions shall be treated as illegal instructions by the decoder.\n\n## 6. Summary of Key Behaviours\n\n- Decodes a 32‑bit instruction (or expanded compressed instruction) into control signals and immediates.\n- Reads the register file and forwards special values (misaligned address) when required.\n- Detects and handles multi‑cycle instructions by stalling the pipeline appropriately.\n- Generates stall signals for the IF stage and handshake signals for the EX stage.\n- Selects the write‑back data source after completion.\n- Recognises illegal instructions, exceptions, and debug triggers and passes them to the controller.\n- Provides performance counter events for jumps and branches.", "commit_id": "e87d0cc3e9225ed29cb6a89ccace2a5fe284a677", "timestamp": "2019-05-15T16:55:20+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "9836ef883d463c857f83410204e3b32e2d8233b0", "pr_title": "Fix synthesis ikarageo", "pr_body": "Replaces #38 as the other one seemed to be messed up by GitHub", "issue_title": "Fix unsynthesizable construct and missing signal for tracer", "issue_body": "- Synthesis tools throw warnings with system task $stop. \r\n- Functionality of tracer broke after commit 53f2fb935030eee131e4d927f6890295f86344ac", "commit_message": "Restore functionality of tracer\n\nTracer functionality is broken after transition to ibex. \"operand_b_fw_id\" is missing from instruction decoder.", "fix_patch": "diff --git a/rtl/ibex_id_stage.sv b/rtl/ibex_id_stage.sv\nindex 93c16c4054..4ba1f90e99 100644\n--- a/rtl/ibex_id_stage.sv\n+++ b/rtl/ibex_id_stage.sv\n@@ -227,6 +227,7 @@ module ibex_id_stage #(\n op_fw_sel_e operand_a_fw_mux_sel;\n \n logic [31:0] operand_a_fw_id;\n+ logic [31:0] operand_b_fw_id;\n \n logic [31:0] alu_operand_a;\n logic [31:0] alu_operand_b;\n@@ -304,6 +305,7 @@ module ibex_id_stage #(\n \n // ALU_Op_b Mux\n assign alu_operand_b = (alu_op_b_mux_sel == OP_B_IMM) ? imm_b : regfile_data_rb_id;\n+ assign operand_b_fw_id = regfile_data_rb_id;\n \n ///////////////\n // Registers //\n@@ -645,7 +647,7 @@ module ibex_id_stage #(\n // make sure that branch decision is valid when jumping\n assert property (\n @(posedge clk_i) (branch_decision_i !== 1'bx || branch_in_id == 1'b0) ) else begin\n- $display(\"Branch decision is X\"); $stop; end\n+ $display(\"Branch decision is X\"); end\n \n `ifdef CHECK_MISALIGNED\n assert property (\n", "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: Renzo Andri - andrire@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// Davide Schiavone - pschiavo@iis.ee.ethz.ch //\n// //\n// Design Name: Instruction Decode Stage //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Decode stage of the core. It decodes the instructions //\n// and hosts the register file. //\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 Decode Stage\n *\n * Decode stage of the core. It decodes the instructions and hosts the register\n * file.\n */\nmodule ibex_id_stage #(\n parameter bit RV32E = 0,\n parameter bit RV32M = 1\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 core_ctrl_firstfetch_o,\n output logic is_decoding_o,\n\n // Interface to IF stage\n input logic instr_valid_i,\n input logic [31:0] instr_rdata_i, // comes from pipeline of IF stage\n output logic instr_req_o,\n\n // Jumps and branches\n input logic branch_decision_i,\n\n // IF and ID stage signals\n output logic clear_instr_valid_o,\n output logic pc_set_o,\n output ibex_defines::pc_sel_e pc_mux_o,\n output ibex_defines::exc_pc_sel_e exc_pc_mux_o,\n\n input logic illegal_c_insn_i,\n input logic is_compressed_i,\n\n input logic [31:0] pc_id_i,\n\n // Stalls\n output logic halt_if_o, // controller requests a halt of the IF stage\n output logic id_ready_o, // ID stage is ready for the next instruction\n input logic ex_ready_i,\n output logic id_valid_o, // ID stage is done\n\n // ALU\n output ibex_defines::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 // MUL, DIV\n output logic mult_en_ex_o,\n output logic div_en_ex_o,\n output ibex_defines::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_ex_o,\n output ibex_defines::csr_op_e csr_op_ex_o,\n output ibex_defines::exc_cause_e csr_cause_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\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 [1:0] data_reg_offset_ex_o,\n output logic [31:0] data_wdata_ex_o,\n\n input logic data_misaligned_i,\n input logic [31:0] misaligned_addr_i,\n\n // Interrupt signals\n input logic irq_i,\n input logic [4:0] irq_id_i,\n input logic m_irq_enable_i,\n output logic irq_ack_o,\n output logic [4:0] irq_id_o,\n output ibex_defines::exc_cause_e exc_cause_o,\n\n input logic lsu_load_err_i,\n input logic lsu_store_err_i,\n\n // Debug Signal\n output ibex_defines::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\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 // Performance Counters\n output logic perf_jump_o, // we are executing a jump instruction\n output logic perf_branch_o, // we are executing a branch instruction\n output logic perf_tbranch_o // we are executing a taken branch instruction\n);\n\n import ibex_defines::*;\n\n logic [31:0] instr;\n\n // Decoder/Controller ID stage internal signals\n logic deassert_we;\n\n logic illegal_insn_dec;\n logic illegal_reg_rv32e;\n logic ebrk_insn;\n logic mret_insn_dec;\n logic dret_insn_dec;\n logic ecall_insn_dec;\n logic pipe_flush_dec;\n\n logic branch_in_id;\n logic branch_set_n;\n logic branch_set_q;\n logic branch_mux_dec;\n logic jump_set;\n logic jump_mux_dec;\n logic jump_in_id;\n\n logic instr_multicyle;\n logic load_stall;\n logic multdiv_stall;\n logic branch_stall;\n logic jump_stall;\n\n logic halt_id;\n //FSM signals to write back multi cycles instructions\n logic regfile_we;\n\n typedef enum logic {RF_LSU, RF_EX} select_e;\n select_e select_data_rf;\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 // Signals running between controller and exception controller\n logic irq_req_ctrl;\n logic [4:0] irq_id_ctrl;\n logic exc_ack, exc_kill;// handshake\n\n // Register file interface\n logic [4:0] regfile_addr_ra_id;\n logic [4:0] regfile_addr_rb_id;\n\n logic [4:0] regfile_alu_waddr_id;\n logic regfile_we_id;\n\n logic [31:0] regfile_data_ra_id;\n logic [31:0] regfile_data_rb_id;\n\n // ALU Control\n alu_op_e alu_operator;\n op_a_sel_e alu_op_a_mux_sel;\n op_b_sel_e alu_op_b_mux_sel;\n\n imm_a_sel_e imm_a_mux_sel;\n imm_b_sel_e imm_b_mux_sel;\n\n // Multiplier Control\n logic mult_int_en; // use integer multiplier\n logic div_int_en; // use integer division or reminder\n logic multdiv_int_en;\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 [1:0] data_reg_offset_id;\n logic data_req_id;\n\n // CSR control\n logic csr_access;\n csr_op_e csr_op;\n logic csr_status;\n\n // Forwarding\n op_fw_sel_e operand_a_fw_mux_sel;\n\n logic [31:0] operand_a_fw_id;\n logic [31:0] operand_b_fw_id;\n\n logic [31:0] alu_operand_a;\n logic [31:0] alu_operand_b;\n\n assign instr = instr_rdata_i;\n\n // immediate extraction and sign extension\n assign imm_i_type = { {20 {instr[31]}}, instr[31:20] };\n assign imm_s_type = { {20 {instr[31]}}, instr[31:25], instr[11:7] };\n assign imm_b_type = { {19 {instr[31]}}, instr[31], instr[7], instr[30:25], instr[11:8], 1'b0 };\n assign imm_u_type = { instr[31:12], 12'b0 };\n assign imm_j_type = { {12 {instr[31]}}, instr[19:12], instr[20], instr[30:21], 1'b0 };\n\n // immediate for CSR manipulatin (zero extended)\n assign zimm_rs1_type = { 27'b0, instr[`REG_S1] };\n\n ///////////////////////////////\n // Source register selection //\n ///////////////////////////////\n assign regfile_addr_ra_id = instr[`REG_S1];\n assign regfile_addr_rb_id = instr[`REG_S2];\n\n ///////////////////////////\n // Destination registers //\n ///////////////////////////\n assign regfile_alu_waddr_id = instr[`REG_D];\n\n //if (RV32E)\n // assign illegal_reg_rv32e = (regfile_addr_ra_id[4] |\n // regfile_addr_rb_id[4] |\n // regfile_alu_waddr_id[4]);\n //else\n assign illegal_reg_rv32e = 1'b0;\n\n // kill instruction in the IF/ID stage by setting the instr_valid_id control\n // signal to 0 for instructions that are done\n assign clear_instr_valid_o = id_ready_o | halt_id;\n\n ///////////////\n // Operand A //\n ///////////////\n\n // ALU_Op_a Mux\n always_comb begin : alu_operand_a_mux\n case (alu_op_a_mux_sel)\n OP_A_REGA_OR_FWD: alu_operand_a = operand_a_fw_id;\n OP_A_CURRPC: alu_operand_a = pc_id_i;\n OP_A_IMM: alu_operand_a = imm_a;\n default: alu_operand_a = operand_a_fw_id;\n endcase // case (alu_op_a_mux_sel)\n end\n\n assign imm_a = (imm_a_mux_sel == IMM_A_Z) ? zimm_rs1_type : '0;\n\n // Operand a forwarding mux used with LSU instructions\n assign operand_a_fw_id\n = (operand_a_fw_mux_sel == SEL_MISALIGNED) ? misaligned_addr_i : regfile_data_ra_id;\n\n ///////////////\n // Operand B //\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_PCINCR: imm_b = (is_compressed_i && !data_misaligned_i) ? 32'h2 : 32'h4;\n default: imm_b = imm_i_type;\n endcase\n end\n\n // ALU_Op_b Mux\n assign alu_operand_b = (alu_op_b_mux_sel == OP_B_IMM) ? imm_b : regfile_data_rb_id;\n assign operand_b_fw_id = regfile_data_rb_id;\n\n ///////////////\n // Registers //\n ///////////////\n\n logic [31:0] regfile_wdata_mux;\n logic regfile_we_mux;\n logic [4:0] regfile_waddr_mux;\n\n //TODO: add assertion\n // Register File mux\n always_comb begin\n regfile_we_mux = regfile_we;\n regfile_waddr_mux = regfile_alu_waddr_id;\n if (select_data_rf == RF_LSU) begin\n regfile_wdata_mux = regfile_wdata_lsu_i;\n end else if (csr_access) begin\n regfile_wdata_mux = csr_rdata_i;\n end else begin\n regfile_wdata_mux = regfile_wdata_ex_i;\n end\n end\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_addr_ra_id ),\n .rdata_a_o ( regfile_data_ra_id ),\n // Read port b\n .raddr_b_i ( regfile_addr_rb_id ),\n .rdata_b_o ( regfile_data_rb_id ),\n // write port\n .waddr_a_i ( regfile_waddr_mux ),\n .wdata_a_i ( regfile_wdata_mux ),\n .we_a_i ( regfile_we_mux )\n );\n\n assign multdiv_int_en = mult_int_en | div_int_en;\n\n /////////////\n // Decoder //\n /////////////\n\n ibex_decoder #( .RV32M ( RV32M ) ) decoder_i (\n // controller related signals\n .deassert_we_i ( deassert_we ),\n .data_misaligned_i ( data_misaligned_i ),\n .branch_mux_i ( branch_mux_dec ),\n .jump_mux_i ( jump_mux_dec ),\n\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 .pipe_flush_o ( pipe_flush_dec ),\n\n // from IF/ID pipeline\n .instr_rdata_i ( instr ),\n .illegal_c_insn_i ( illegal_c_insn_i ),\n\n // ALU signals\n .alu_operator_o ( alu_operator ),\n .alu_op_a_mux_sel_o ( alu_op_a_mux_sel ),\n .alu_op_b_mux_sel_o ( alu_op_b_mux_sel ),\n\n .imm_a_mux_sel_o ( imm_a_mux_sel ),\n .imm_b_mux_sel_o ( imm_b_mux_sel ),\n\n .mult_int_en_o ( mult_int_en ),\n .div_int_en_o ( div_int_en ),\n .multdiv_operator_o ( multdiv_operator ),\n .multdiv_signed_mode_o ( multdiv_signed_mode ),\n // Register file control signals\n .regfile_we_o ( regfile_we_id ),\n\n // CSR control signals\n .csr_access_o ( csr_access ),\n .csr_op_o ( csr_op ),\n .csr_status_o ( csr_status ),\n\n // Data bus interface\n .data_req_o ( data_req_id ),\n .data_we_o ( data_we_id ),\n .data_type_o ( data_type_id ),\n .data_sign_extension_o ( data_sign_ext_id ),\n .data_reg_offset_o ( data_reg_offset_id ),\n\n // jump/branches\n .jump_in_id_o ( jump_in_id ),\n .branch_in_id_o ( branch_in_id )\n );\n\n ////////////////\n // Controller //\n ////////////////\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 .first_fetch_o ( core_ctrl_firstfetch_o ),\n .is_decoding_o ( is_decoding_o ),\n\n // decoder related signals\n .deassert_we_o ( deassert_we ),\n .illegal_insn_i ( illegal_insn_dec | illegal_reg_rv32e ),\n .ecall_insn_i ( ecall_insn_dec ),\n .mret_insn_i ( mret_insn_dec ),\n .dret_insn_i ( dret_insn_dec ),\n .pipe_flush_i ( pipe_flush_dec ),\n .ebrk_insn_i ( ebrk_insn ),\n .csr_status_i ( csr_status ),\n\n // from IF/ID pipeline\n .instr_valid_i ( instr_valid_i ),\n\n // from prefetcher\n .instr_req_o ( instr_req_o ),\n\n // to prefetcher\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 .data_misaligned_i ( data_misaligned_i ),\n\n // jump/branch control\n .branch_in_id_i ( branch_in_id ),\n .branch_set_i ( branch_set_q ),\n .jump_set_i ( jump_set ),\n\n .instr_multicyle_i ( instr_multicyle ),\n\n .irq_i ( irq_i ),\n // Interrupt Controller Signals\n .irq_req_ctrl_i ( irq_req_ctrl ),\n .irq_id_ctrl_i ( irq_id_ctrl ),\n .m_IE_i ( m_irq_enable_i ),\n\n .irq_ack_o ( irq_ack_o ),\n .irq_id_o ( irq_id_o ),\n\n .exc_ack_o ( exc_ack ),\n .exc_kill_o ( exc_kill ),\n\n // CSR Controller Signals\n .csr_save_cause_o ( csr_save_cause_o ),\n .csr_cause_o ( csr_cause_o ),\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\n // Debug Signal\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\n // Forwarding signals\n .operand_a_fw_mux_sel_o ( operand_a_fw_mux_sel ),\n\n // Stall signals\n .halt_if_o ( halt_if_o ),\n .halt_id_o ( halt_id ),\n\n .id_ready_i ( id_ready_o ),\n\n // Performance Counters\n .perf_jump_o ( perf_jump_o ),\n .perf_tbranch_o ( perf_tbranch_o )\n );\n\n //////////////////////////\n // Interrupt controller //\n //////////////////////////\n\n ibex_int_controller int_controller_i (\n .clk_i ( clk_i ),\n .rst_ni ( rst_ni ),\n\n // to controller\n .irq_req_ctrl_o ( irq_req_ctrl ),\n .irq_id_ctrl_o ( irq_id_ctrl ),\n\n .ctrl_ack_i ( exc_ack ),\n .ctrl_kill_i ( exc_kill ),\n\n // Interrupt signals\n .irq_i ( irq_i ),\n .irq_id_i ( irq_id_i ),\n\n .m_IE_i ( m_irq_enable_i )\n );\n\n ///////////\n // ID-EX //\n ///////////\n\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_data_rb_id;\n assign data_req_ex_o = data_req_id;\n assign data_reg_offset_ex_o = data_reg_offset_id;\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 assign csr_access_ex_o = csr_access;\n assign csr_op_ex_o = csr_op;\n\n assign mult_en_ex_o = mult_int_en;\n assign div_en_ex_o = div_int_en;\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_data_ra_id;\n assign multdiv_operand_b_ex_o = regfile_data_rb_id;\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 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 branch_set_q <= 1'b0;\n end else begin\n id_wb_fsm_cs <= id_wb_fsm_ns;\n branch_set_q <= branch_set_n;\n end\n end\n\n //////////////////\n // ID-EX/WB FSM //\n //////////////////\n always_comb begin : id_wb_fsm\n id_wb_fsm_ns = id_wb_fsm_cs;\n regfile_we = regfile_we_id;\n load_stall = 1'b0;\n multdiv_stall = 1'b0;\n jump_stall = 1'b0;\n branch_stall = 1'b0;\n select_data_rf = RF_EX;\n instr_multicyle = 1'b0;\n branch_set_n = 1'b0;\n branch_mux_dec = 1'b0;\n jump_set = 1'b0;\n jump_mux_dec = 1'b0;\n perf_branch_o = 1'b0;\n\n unique case (id_wb_fsm_cs)\n\n IDLE: begin\n jump_mux_dec = 1'b1;\n branch_mux_dec = 1'b1;\n unique case (1'b1)\n data_req_id: begin\n //LSU operation\n regfile_we = 1'b0;\n id_wb_fsm_ns = WAIT_MULTICYCLE;\n load_stall = 1'b1;\n instr_multicyle = 1'b1;\n end\n branch_in_id: begin\n //Cond Branch operation\n id_wb_fsm_ns = branch_decision_i ? WAIT_MULTICYCLE : IDLE;\n branch_stall = branch_decision_i;\n instr_multicyle = branch_decision_i;\n branch_set_n = branch_decision_i;\n perf_branch_o = 1'b1;\n end\n multdiv_int_en: begin\n //MUL or DIV operation\n regfile_we = 1'b0;\n id_wb_fsm_ns = WAIT_MULTICYCLE;\n multdiv_stall = 1'b1;\n instr_multicyle = 1'b1;\n end\n jump_in_id: begin\n //UnCond Branch operation\n regfile_we = 1'b0;\n id_wb_fsm_ns = WAIT_MULTICYCLE;\n jump_stall = 1'b1;\n instr_multicyle = 1'b1;\n jump_set = 1'b1;\n end\n default:;\n endcase\n end\n\n WAIT_MULTICYCLE: begin\n if (ex_ready_i) begin\n regfile_we = regfile_we_id;\n id_wb_fsm_ns = IDLE;\n load_stall = 1'b0;\n multdiv_stall = 1'b0;\n select_data_rf = data_req_id ? RF_LSU : RF_EX;\n end else begin\n regfile_we = 1'b0;\n instr_multicyle = 1'b1;\n unique case (1'b1)\n data_req_id:\n load_stall = 1'b1;\n multdiv_int_en:\n multdiv_stall = 1'b1;\n default:;\n endcase\n end\n end\n\n default:;\n endcase\n end\n\n // stall control\n assign id_ready_o = ~load_stall & ~branch_stall & ~jump_stall & ~multdiv_stall;\n\n assign id_valid_o = ~halt_id & id_ready_o;\n\n ////////////////\n // Assertions //\n ////////////////\n`ifndef VERILATOR\n // make sure that branch decision is valid when jumping\n assert property (\n @(posedge clk_i) (branch_decision_i !== 1'bx || branch_in_id == 1'b0) ) else begin\n $display(\"Branch decision is X\"); end\n\n`ifdef CHECK_MISALIGNED\n assert property (\n @(posedge clk_i) (~data_misaligned_i) ) else $display(\"Misaligned memory access at %x\",pc_id_i);\n`endif\n\n // the instruction delivered to the ID stage should always be valid\n assert property (\n @(posedge clk_i) (instr_valid_i & (~illegal_c_insn_i)) |-> (!$isunknown(instr_rdata_i)) ) else\n $display(\"Instruction is valid, but has at least one X\");\n\n // make sure multicycles enable signals are unique\n assert property (\n @(posedge clk_i) ~(data_req_ex_o & multdiv_int_en )) else\n $display(\"Multicycles enable signals are not unique\");\n\n`endif\n\nendmodule\n", "selected_doc_paths": ["doc/register_file.rst", "doc/cs_registers.rst", "doc/load_store_unit.rst", "doc/exception_interrupts.rst", "doc/performance_counters.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 131, "lang": "sv", "rtl_files": ["rtl/ibex_decoder.sv"], "spec": "# Instruction Decoder (ibex_decoder) Behavioral Specification\n\n## Overview\n\nThe instruction decoder is a combinatorial block that interprets a 32-bit instruction word and generates all control signals required by the execution pipeline, register file, load-store unit, CSR interface, and ALU/multiplier/divider. It operates in the instruction decode stage of the Ibex core and determines the operation to be performed in subsequent pipeline stages.\n\n## Inputs and Parameters\n\n### Configuration Parameters\n\n- **RV32E**: When enabled, the core uses the RV32E base integer instruction set, which provides only 16 general-purpose registers (x0–x15). The decoder must treat any instruction that accesses a register with index ≥ 16 as illegal.\n- **RV32M**: When enabled, the core supports the M extension (integer multiplication and division). Instructions from the M extension shall be treated as illegal when this parameter is disabled.\n\n### Inputs\n\n- A valid 32-bit instruction word, received from the IF-ID pipeline register.\n- A signal indicating whether the instruction is a new instruction (i.e., valid for execution) or a second cycle of a multi-cycle operation (e.g., branch target calculation).\n- A flag indicating that a compressed instruction (16-bit) could not be decoded successfully. When this flag is active, the decoder shall treat the current instruction as illegal.\n\n## Behavioral Requirements\n\n### 1. Instruction Decoding\n\nThe decoder shall interpret the opcode (bits [6:0]) of the instruction and, for each opcode, examine the funct3 and funct7 fields as needed. It shall generate the following control signals:\n\n- **ALU operation**: The ALU shall be configured to perform addition, subtraction, bitwise logical operations, shifts, or comparison operations as required by the instruction.\n- **ALU operand sources**: The two ALU operands shall be selected from:\n - Register file read port A (rs1)\n - Register file read port B (rs2)\n - Current PC value (for jumps, branches, AUIPC)\n - Immediate values (I-type, S-type, B-type, U-type, J-type)\n - Zero constant (for LUI)\n - Zero-extended rs1 field (for CSR immediate operations)\n- **Immediate generation**: The decoder shall compute the correct immediate value for each instruction type according to the RISC-V specification. All immediates shall be properly sign-extended except for CSR-related immediates (zimm) which are zero-extended.\n- **Register file write enable**: The decoder shall indicate whether the instruction writes a result to the register file. It shall also select the write data source: ALU result, load-store unit result, or CSR read value.\n- **Register file address outputs**: The decoder shall forward the source register addresses (rs1, rs2) and destination register address (rd) directly from the instruction fields.\n\n### 2. Instruction Categories and Their Behavior\n\n#### 2.1 Jumps (JAL, JALR)\n\n- **JAL (Jump and Link)**: The decoder shall perform the jump target calculation (PC + J-immediate) in the execution stage. In the first cycle (new instruction), it shall set the ALU to add PC and the J-immediate, disable register write, and assert the jump set signal. In the second cycle, it shall calculate PC+4 and write that value to the destination register.\n- **JALR (Jump and Link Register)**: Similar to JAL, but the base address is taken from register rs1. The ALU shall add rs1 and the I-immediate. If funct3 is not zero, the instruction is illegal. In the second cycle, PC+4 is written to rd.\n- For both jump types, the decoder shall assert a signal indicating that a jump is being calculated (jump in decode).\n\n#### 2.2 Branches (BEQ, BNE, BLT, BGE, BLTU, BGEU)\n\n- In the first cycle (new instruction), the decoder shall configure the ALU to compare registers rs1 and rs2 using the appropriate comparison operation (EQ, NE, LT, GE, LTU, GEU) based on funct3. Unsupported funct3 values shall cause an illegal instruction.\n- In the second cycle, the decoder shall calculate the branch target (PC + B-immediate) by adding PC and the B-immediate. Register write remains disabled.\n- The decoder shall assert a branch-in-decode signal.\n\n#### 2.3 Load Instructions (LB, LH, LW, LBU, LHU, and register-indexed variants)\n\n- The decoder shall configure the ALU to add register rs1 and an I-immediate (or register rs2 for the register-indexed variants) to produce the load address.\n- It shall enable the data request to the load-store unit and select the load-store unit result as the register write data.\n- Data type (byte, halfword, word) and sign extension (signed/unsigned) shall be set according to funct3 (or funct7 for register-indexed variants).\n- For the LWU variant (funct3=3'b011), the instruction shall be treated as illegal because it is a 64-bit instruction (RV64 only).\n- Funct3=3'b111 indicates a register-indexed load; the decoder shall use funct7 to determine the size and sign extension.\n- If funct3 bit [2] is set and a register offset is used (funct3=3'b111), the decoder shall treat the instruction as illegal when the offset encoding is unsupported.\n\n#### 2.4 Store Instructions (SB, SH, SW)\n\n- The decoder shall enable a data request to the load-store unit with write enable set.\n- The ALU shall add register rs1 and an S-immediate to produce the store address.\n- If funct3 bit [2] is set, the instruction is illegal (no C extension support for stores).\n- Data type shall be set based on funct3 bits [1:0] (byte, halfword, word). Unsupported encodings are illegal.\n\n#### 2.5 ALU Immediate Instructions (ADDI, SLTI, SLTIU, XORI, ORI, ANDI, SLLI, SRLI, SRAI)\n\n- The decoder shall configure the ALU to operate on register rs1 and an I-immediate.\n- For shift operations (SLLI, SRLI, SRAI), the shift amount is the lower 5 bits of the immediate; the upper bits (funct7) must be zero (or 0x20 for SRAI). Non-zero funct7 shall cause an illegal instruction.\n- The destination register shall be written with the ALU result.\n\n#### 2.6 Register-Register ALU Instructions (ADD, SUB, SLT, SLTU, XOR, OR, AND, SLL, SRL, SRA)\n\n- The decoder shall configure the ALU to operate on registers rs1 and rs2.\n- Bit [31] of the instruction must be zero; otherwise the instruction is illegal.\n- The operation is determined by funct7 and funct3 as per the RISC-V specification.\n- If the RV32M extension is enabled, the M-extension instructions (MUL, MULH, MULHSU, MULHU, DIV, DIVU, REM, REMU) shall be decoded accordingly, enabling the multiplier/divider unit. If RV32M is disabled, these instructions shall be treated as illegal.\n- For multiply/divide instructions, the ALU operation shall be set to addition (nop) and the multiplier/divider shall be triggered with the appropriate operation and signed mode.\n\n#### 2.7 LUI and AUIPC\n\n- **LUI**: The ALU shall output the U-immediate shifted left by 12 bits (by selecting the immediate as operand A and zero as operand B, performing addition). The result shall be written to the destination register.\n- **AUIPC**: The ALU shall add the current PC to the U-immediate. The result shall be written to the destination register.\n\n#### 2.8 Fence Instructions\n\n- Fence (funct3=000) shall be treated as a NOP: no register write, no memory operation. The ALU shall be configured in a safe state.\n- Fence.i (funct3=001) shall be treated as an illegal instruction.\n\n#### 2.9 System Instructions (ECALL, EBREAK, MRET, DRET, WFI, and CSR Access)\n\n- When funct3 is 000, the decoder shall decode the funct12 field:\n - `0x000`: ECALL (environment call) – assert ecall signal.\n - `0x001`: EBREAK (breakpoint) – assert ebreak signal.\n - `0x302`: MRET (return from machine-mode exception) – assert mret signal.\n - `0x7B2`: DRET (return from debug) – assert dret signal.\n - `0x105`: WFI (wait for interrupt) – assert pipeline flush signal.\n - All other values shall be treated as illegal.\n - Additionally, rs1 and rd must both be zero; otherwise the instruction is illegal.\n- When funct3 is non-zero (001, 010, 011), the decoder shall treat the instruction as a CSR access:\n - Enable CSR access and select CSR write data as the register file write data.\n - The ALU operand A shall be the zero-extended rs1 field (for CSR immediate variants) or register rs1 (for register variants), determined by funct3 bit [2].\n - The CSR operation (WRITE, SET, CLEAR) is determined by funct3 bits [1:0]. Unsupported encodings shall be illegal.\n - If the operation is SET or CLEAR and the source (uimm or rs1) is zero, the operation shall be downgraded to a read-only access (CSR_OP_READ) to prevent unintentional CSR modification with x0.\n - If the CSR address targets `mstatus`, `dcsr`, `dpc`, `dscratch0`, or `dscratch1`, a CSR status signal shall be asserted to indicate that the CSR write requires a pipeline flush (status change).\n\n### 3. Illegal Instruction Detection\n\nThe decoder shall detect illegal instructions based on the following criteria:\n\n- Any opcode (bits [6:0]) not listed in the RISC-V base ISA, or not implemented in this decoder, shall cause the `illegal_insn` signal to be asserted.\n- Within each opcode, illegal encodings (unsupported funct3, funct7, or register fields) shall cause the illegal instruction signal.\n- If the compressed instruction decode failure flag is active, the decoded instruction shall be treated as illegal regardless of its content.\n- In RV32E mode, any instruction that reads or writes a register with index ≥ 16 (i.e., bit 4 of the register address is set) and actually uses that register (e.g., rs1 used as source, rs2 used as source, rd written) shall be illegal. The decoder shall generate an `illegal_reg_rv32e` flag that is combined with the main illegal instruction flag.\n- When an illegal instruction is detected, all write enables to the register file, load-store unit, multiplier/divider, and CSR interface shall be disabled. Jump and branch control signals shall be cleared.\n\n### 4. Multi-Cycle Handling (Branch/Jump Second Cycle)\n\nThe decoder receives an indication whether the instruction is a new instruction or a second-cycle operation. For jump and branch instructions:\n\n- In the first cycle (new instruction active), the decoder shall set up the ALU for the comparison or target addition as described above, and disable register file write. The jump-set signal shall be asserted for jumps.\n- In the second cycle (new instruction inactive), the decoder shall reconfigure the ALU to add PC to the appropriate immediate (INCR_PC for jumps to store PC+4, or B-immediate for branches to compute target). Register write may be enabled for jumps (to store link address) but disabled for branches.\n\n### 5. CSR Access Control\n\nWhen a CSR instruction is decoded:\n\n- The decoder shall enable the CSR interface and select the CSR result as the write-back data source.\n- The CSR address is encoded in the I-immediate field.\n- The operation (read, write, set, clear) shall be determined from funct3. As noted, if a write-type operation has a zero source operand, the operation shall be treated as a read-only access.\n- If the CSR address is one of the special status registers (mstatus, dcsr, dpc, dscratch0, dscratch1), a status-change indicator shall be asserted to allow the pipeline to flush and update the CSR state correctly.\n\n### 6. Load-Store Unit Control\n\n- For loads and stores, the decoder shall generate a data request signal, write enable (stores only), data type (byte/halfword/word), sign extension (for loads), and byte offset information.\n- The decoder shall also configure the ALU to compute the effective address (base register + offset).\n- The data request shall be held active until the LSU grants the request (handshake).\n\n### 7. Outputs to Execution Pipeline\n\nThe decoder shall provide:\n\n- ALU operator selection.\n- ALU operand A and B mux selects.\n- Immediate mux selects (for operand A and B).\n- Pre-computed immediate values for all types.\n- Register file read and write addresses.\n- Register file write data source select.\n- Multiplier/divider enable and operation selection (including signed mode).\n- Branch and jump in-decode flags.\n\n### 8. Interaction with Other Pipeline Stages\n\n- The decoder is purely combinational; its outputs are used by the execute, memory, and write-back stages.\n- The illegal instruction signal (combined with the RV32E register check) propagates to the controller to raise an illegal instruction exception (exception code 2).\n- The ecall, ebreak, mret, dret, and pipe_flush signals are passed to the controller for appropriate trap handling or pipeline control.\n\n## Summary of Normative Requirements\n\n- The decoder shall correctly decode all RV32I base instructions and, if configured, RV32M extension instructions.\n- The decoder shall treat unsupported opcodes or encodings as illegal.\n- The decoder shall respect the RV32E parameter by flagging instructions that access non-existent registers as illegal.\n- The decoder shall handle two-cycle jump and branch operations correctly by distinguishing between the new-instruction and second-cycle phases.\n- The decoder shall generate all immediate values as per the RISC-V specification.\n- The decoder shall disable all resource write controls when an illegal instruction is detected.\n- The decoder shall not introduce any sequential state; all outputs are strictly combinatorial.", "commit_id": "33b7904a124b39e78481eb3176c062e182bce5de", "timestamp": "2019-07-10T14:24:22+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "8b4e33711847e4ea88cd0f205b8f66f8e09f8bac", "pr_title": "Decoder: fix drive conflict, set `jump_set_o` for JALR", "pr_body": "This PR solves problems reported by @jeanlouismaquet in #130.", "issue_title": "Problem when the value of opcode FSM is OPCODE_JALR", "issue_body": "Hello,\r\n\r\nWith the new file ibex_decoder.sv (5093e0a), when the opcode FSM = OPCODE_JALR, the pc_mux_o FSM stays at PC_BOOT value. Normally, the pc_mux_o FSM must toogle to PC_JUMP value.\r\nI created a zip file containing:\r\n ibex_28may19.log : result from the ibex_tracer module. No problem \r\n ibex_last_version.log : result from the ibex_tracer module : problem line 43 (jalr)\r\n waves_AES_CBC_old.wlf : waveform (modelsim) : pc_mux_o signal : PC_JUMP -> PC_BOOT -> PC_JUMP -> PC_BOOT \r\n waves_AES_CBC_new.wlf : waveform (modelsim) : problem (pc_mux_o : PCPC_JUMP -> PC_BOOT) \r\n ibex_new_jalr.png printscreen of waveform (version with _**problem)**_\r\n ibex_old_jalr.png printscreen of waveform (correct version)\r\n\r\nSolution : In ibex_decoder.sv, after the line 239, add the following line:\r\n **_jump_set_o = 1'b1;_**\r\n\r\nRemark: During compilation of ibex_decoder.sv file with modelsim, I obtain the following error:\r\n **_Error (suppressible): (vlog-12003) /cad/projects/eSecure/jlm4/design/digital/modules/esecure_cpu/macro/IP_ibex/sources/hdl/ibex_decoder.sv(623): Variable 'illegal_insn_o' written by continuous and procedural assignments. See /cad/projects/eSecure/jlm4/design/digital/modules/esecure_cpu/macro/IP_ibex/sources/hdl/ibex_decoder.sv(554)._** \r\n\r\nSolution : At line 553 : change the **_illegal_insn_o_** signal by **_illegal_insn_**.\r\n\r\nDespite the addition of the line **_jump_set_o = 1'b1;_** , my simulation still has errors.\r\nI'm debugging this new problem.\r\n\r\nBest regards,\r\n\r\nJean-Louis\r\n[problem_ibex_jalr.zip](https://github.com/lowRISC/ibex/files/3377638/problem_ibex_jalr.zip)\r\n\r\n", "commit_message": "Decoder: fix drive conflict, set `jump_set_o` for JALR\n\nThis commit solves problems reported by @jeanlouismaquet in #130.", "fix_patch": "diff --git a/rtl/ibex_decoder.sv b/rtl/ibex_decoder.sv\nindex 6eee408791..30df485f99 100644\n--- a/rtl/ibex_decoder.sv\n+++ b/rtl/ibex_decoder.sv\n@@ -237,6 +237,7 @@ module ibex_decoder #(\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@@ -550,7 +551,7 @@ module ibex_decoder #(\n \n // rs1 and rd must be 0\n if (instr[`REG_S1] || instr[`REG_D]) begin\n- illegal_insn_o = 1'b1;\n+ illegal_insn = 1'b1;\n end\n end else begin\n // instruction to read/modify CSR\n", "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 pipe_flush_o, // pipeline flush is requested\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 pipe_flush_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 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 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_OPIMM: 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 if (!instr[28]) begin // non bit-manipulation instructions\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_FENCE: 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 // flush pipeline\n pipe_flush_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", "selected_doc_paths": ["doc/register_file.rst", "doc/load_store_unit.rst", "doc/cs_registers.rst", "doc/exception_interrupts.rst", "doc/debug.rst"]}} +{"input": {"repo": "lowRISC/ibex", "pr_id": 157, "lang": "sv", "rtl_files": ["rtl/ibex_controller.sv"], "spec": "# Ibex Controller Behavioral Specification\n\n## 1. Overview\n\nThe controller is the central finite-state machine that governs the instruction execution pipeline of the Ibex core. It manages all major state transitions, including:\n\n- Reset and boot sequence\n- Fetch-decode-execute flow\n- Exception and interrupt entry/exit\n- Debug mode entry and handling\n- Wait-for-interrupt (WFI) sleep and wakeup\n- Pipeline stall control\n- Instruction fetch requests\n\nAll changes to the processor’s execution mode, program counter (PC), and control/status registers (CSRs) related to traps and debug are initiated by the controller.\n\n## 2. Reset and Boot\n\n- Upon assertion of the reset signal, the controller shall enter a reset state. It shall not request any instruction fetches and shall hold the PC at the boot address.\n- While the reset signal is active, the controller shall ignore all other external requests (interrupts, debug requests).\n- After reset deassertion, the controller shall wait for the fetch enable signal to become active. Once active, the controller shall initiate the first instruction fetch from the boot address. The boot address is derived from the top 24 bits of the hardware-provided boot address, with the lower 8 bits set to `0x80` (reset vector).\n- During the boot sequence, the controller shall request one PC set to the boot address and then transition to a mode where it continuously requests new instructions.\n\n## 3. Normal Operation\n\n- After boot, the controller shall continuously drive the instruction fetch request signal high unless it explicitly halts fetching (e.g., during pipeline flushes or sleep).\n- The controller shall advance the pipeline by signaling when the instruction decode (ID) stage is ready for a new instruction. This readiness is determined by the absence of stalls and a halt condition from the controller.\n- While the pipeline is not stalled and no special conditions exist, the controller shall keep the ID stage output valid for execution.\n- The controller shall track whether the core is busy processing instructions; it shall assert a busy signal continuously except when explicitly in a sleep or wait-for-sleep state.\n\n## 4. Exception Handling\n\nThe controller shall handle the following exception types (listed in priority order within the respective state):\n\n- Illegal instruction\n- Breakpoint (EBREAK)\n- Load access fault\n- Store access fault\n- Environment call (ECALL) from M-mode\n\n**Exception Detection and Entry:**\n\n- When the decode stage identifies an illegal instruction, ECALL, or EBREAK in a valid instruction, the controller shall initiate exception entry.\n- Load and store errors may be reported by the load-store unit (LSU) one cycle after the instruction that caused them finishes. The controller shall register these errors and use them to trigger an exception entry on the next cycle after the instruction completes.\n- Upon exception entry, the controller shall:\n - Set the PC to the exception handler address (from `mtvec` CSR for regular exceptions, or from `dm_exception_addr` for exceptions occurring in debug mode).\n - Save the return PC (address of the offending instruction) into `mepc` (or `dpc` if in debug mode).\n - Save the exception cause code into `mcause` (or `dcause`).\n - Optionally save the faulting instruction or data address into `mtval` for certain exceptions.\n - Clear the current instruction in the ID stage.\n\n**Exception Priority within Decode:**\n\n- If multiple exceptional conditions occur simultaneously, the controller shall follow the RISC-V privileged specification priority order:\n 1. Load/store access fault\n 2. Illegal instruction\n 3. Breakpoint\n 4. ECALL\n\n**Post-Exception Flow:**\n\n- After entering the exception handler, the controller shall resume normal instruction fetch from the handler’s PC.\n\n## 5. Interrupt Handling\n\n- Interrupts are accepted only when the global interrupt enable bit (`mstatus.MIE`) is set and the core is not in debug mode.\n- The controller shall ignore interrupt requests if the current instruction is a multi-cycle instruction (LSU, multiply/divide) until that instruction completes.\n- When an interrupt is to be taken, the controller shall:\n - Convert the interrupt ID (provided by the interrupt controller) into an exception cause code with the interrupt flag set.\n - Set the PC to the vectored interrupt address: `mtvec` base address plus four times the interrupt cause number.\n - Save the return PC into `mepc`.\n - Save `mstatus.MIE` into `mstatus.MPIE` and disable interrupts (`MIE=0`).\n - Acknowledge the interrupt to the external interrupt controller.\n- Interrupts shall not be taken when the core is already in an exception or interrupt handler, unless software explicitly re-enables interrupts (the controller does not enforce nesting on its own; the CSR logic controls the enable bits).\n\n## 6. Debug Support\n\n- The controller supports debug mode as defined in the RISC-V Debug Specification v0.13.\n- A debug request (`debug_req`) can be asserted at any time. The controller shall recognize it only if the core is not already in debug mode.\n\n**Debug Entry Points and Prioritization:**\n\n1. **Single-step** – If single-step is enabled and the core is not in debug mode, after executing one instruction the controller shall enter debug mode and save the PC of the next instruction (or optionally the current instruction on a branch/trap).\n2. **Halt request** – When a debug request arrives and the core is not already in debug mode, the controller shall enter debug mode as soon as possible (after completing any multi-cycle instruction).\n3. **EBREAK in debug mode** – If an EBREAK instruction is executed while in debug mode, the controller shall halt again (re‑enter debug mode) without updating `dpc` or `dcsr`.\n4. **EBREAK with forced entry** – If the `debug_ebreakm` CSR bit is set and an EBREAK occurs in M‑mode, the controller shall enter debug mode regardless of the current debug mode (unless already in debug mode, in which case case 3 applies).\n5. **Debug mode exception** – If an exception occurs while in debug mode, the controller shall jump to the debug exception handler address (stored in the `dm_exception_addr` parameter) instead of the normal `mtvec`.\n\n**Debug Entry Actions:**\n\n- When entering debug mode (single-step, halt request, or forced EBREAK):\n - Set the PC to the debug halt address (`dm_halt_addr`).\n - Save the PC of the next instruction (or the EBREAK address) into `dpc`.\n - Save the debug cause (`DBG_CAUSE_HALTREQ`, `DBG_CAUSE_STEP`, or `DBG_CAUSE_EBREAK`) into `dcsr`.\n - Set the debug mode flip-flop.\n- When an exception occurs in debug mode (except EBREAK re‑entry):\n - Jump to the debug exception address, save the PC into `dpc`, save the cause into `dcsr`, and keep the debug mode active.\n\n**Debug Exit:**\n\n- The debug mode shall be exited upon executing a `dret` instruction, which restores the PC from `dpc` and clears the debug mode flip‑flop.\n\n## 7. Wait-for-Interrupt (WFI) and Sleep\n\n- When a `wfi` instruction is decoded and is not an illegal instruction, the controller shall transition to a “wait for sleep” state and then to a “sleep” state.\n- In the sleep state, the controller shall:\n - Stop requesting new instruction fetches.\n - Halt the IF and ID pipeline stages.\n - Deassert the core busy signal.\n- The controller shall leave the sleep state and resume normal fetch when any of the following occurs:\n - An interrupt request is asserted (even if not enabled – the external interrupt line is used as a wake‑up signal).\n - A debug request is asserted.\n - The core is in debug mode or single‑step mode (WFI is treated as a NOP).\n- After leaving sleep, the controller shall re‑enable instruction fetches and proceed to the first fetch state.\n\n## 8. Pipeline Flush and Special Instructions\n\n- The controller shall flush the pipeline when any of the following occurs:\n - An exception is taken (including from LSU errors).\n - An interrupt is taken.\n - A debug entry is taken.\n - A multi‑cycle instruction executes and has a side effect (e.g., CSR write) – handled by the stall mechanism.\n- During a flush, the controller shall:\n - Halt the IF and ID stages.\n - Discard the current instruction in the ID stage.\n- After the flush is complete, the controller shall resume normal operation from the appropriate target PC.\n\n**Special Instructions (MRET, DRET, WFI):**\n\n- **MRET:** The controller shall set the PC to the value in `mepc` and restore `mstatus.MIE` from `mstatus.MPIE`. It shall then resume fetch from that address.\n- **DRET:** The controller shall set the PC to the value in `dpc` and clear the debug mode flag. It shall then resume fetch.\n- **WFI:** See Section 7.\n\n## 9. Stall Control\n\n- The controller shall stall the ID stage when any external stall signal is asserted: load/store unit (LSU) access pending, multiply/divide operation in progress, branch/jump resolution pending.\n- While stalled, the controller shall:\n - Not accept new instructions into ID.\n - Keep the current instruction in ID valid (or wait for its completion).\n - Not advance to the next instruction.\n - Allow exception and debug/interrupt requests to be prepared but deferred until the stall is released.\n- The controller shall deassert the ID stage ready signal during stalls.\n\n## 10. Performance Monitoring\n\n- The controller shall provide two performance output signals:\n - **Jump taken** – asserted when a jump instruction (JAL, JALR) is executed and taken.\n - **Taken branch** – asserted when a branch instruction is taken (branch taken).\n- These signals shall be generated in the decode state when the respective condition is true and the instruction is valid.\n\n## 11. Interface and External Dependencies\n\nThe controller interfaces with:\n\n- **Instruction fetch unit** – requests instruction fetches, provides PC set and PC mux selection (normal, boot, exception, return, debug).\n- **Decode stage** – receives instruction type indicators (illegal, ecall, ebreak, etc.) and provides kill/ready signals.\n- **Load-store unit** – receives error signals for load/store access faults.\n- **Interrupt controller** – receives interrupt request and interrupt ID, outputs interrupt acknowledge and ID.\n- **Debug module** – receives debug request, debug single‑step, and ebreakm control; outputs debug cause and CSR save controls.\n- **CSR registers** – provides controls to save/restore PC and cause values.\n- **Stall logic** – receives stall requests from LSU, multiplier, and branch/jump units.\n\nAll interactions are synchronous to the core clock and use the same reset domain.\n\n## 12. Electrical and Timing Behavior\n\n- The controller shall be clocked by the main core clock (`clk`).\n- All state transitions shall occur on the rising edge of the clock.\n- Asynchronous reset (active low) shall initialize all state to the reset condition.\n- Output signals driven by the controller shall be combinational or registered as needed for timing closure; the specification does not mandate register stages, but the functional behavior described herein must be met on a cycle‑by‑cycle basis as seen by the rest of the core.\n\n*End of Specification*", "commit_id": "c4370083106042cc0398de615e69d661032c04ba", "timestamp": "2019-07-15T17:37:34+00:00"}, "bug_info": [], "aux": {"merge_commit_sha": "a775abd96768165c4637ea6bc3c5bf09a298007c", "pr_title": "Fix dpc CSR not updated", "pr_body": "This PR lets the core also check `debug_req_i` and `debug_single_step_i` while entering debug mode to avoid entering debug mode without setting up the debug CSRs properly (which anyway depend on these signals), if these signals go low during the procedure.\r\n\r\nThis resolves #153 .", "issue_title": "dpc is not updated properly if debug_req_i is a one cycle pulse", "issue_body": "As you can see from below waveform, debug_req_i is modeled as a pulse interrupt which is only asserted for one cycle. ibex can enter debug mode and start fetching instructions from DmHaltAddr. However, dpc is not updated properly (keep at default value 0). I cannot find in the RISC-V debug spec that whether the halt request should be a level or pulse signal, can you help to clarify? \r\n\r\n![screencapture-remotedesktop-corp-google-access-session-6fd70a76-592d-4962-9324-fb0b435c9f3d-2019-07-14-16_45_08](https://user-images.githubusercontent.com/34581368/61190801-d86e0d00-a656-11e9-98e2-4a928cc92108.png)\r\n", "commit_message": "Update ibex_controller.sv", "fix_patch": "diff --git a/rtl/ibex_controller.sv b/rtl/ibex_controller.sv\nindex 573189c2b0..a0c6c49600 100644\n--- a/rtl/ibex_controller.sv\n+++ b/rtl/ibex_controller.sv\n@@ -358,24 +358,24 @@ module ibex_controller (\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- pc_mux_o = PC_EXC;\n- pc_set_o = 1'b1;\n- exc_pc_mux_o = EXC_PC_DBD;\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+ 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 if (debug_req_i) begin\n- debug_cause_o = DBG_CAUSE_HALTREQ;\n- end else if (ebrk_insn_i) begin\n- debug_cause_o = DBG_CAUSE_EBREAK;\n- end\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+ // enter debug mode\n+ debug_mode_d = 1'b1;\n+ end\n \n ctrl_fsm_ns = DECODE;\n end\n@@ -389,29 +389,31 @@ module ibex_controller (\n //\n // for 1. do not update dcsr and dpc, for 2. and 3. do so [Debug Spec v0.13.2, p.39]\n // jump to debug exception handler in debug memory\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 ((ebrk_insn_i && debug_ebreakm_i && !debug_mode_q) || // ebreak with forced entry\n- (enter_debug_mode)) begin // halt request\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- if (debug_req_i) begin\n- debug_cause_o = DBG_CAUSE_HALTREQ;\n- end else if (ebrk_insn_i) begin\n- debug_cause_o = DBG_CAUSE_EBREAK;\n+ if (ebrk_insn_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+ // update dcsr and dpc\n+ if ((ebrk_insn_i && debug_ebreakm_i && !debug_mode_q) || // ebreak with forced entry\n+ (enter_debug_mode)) begin // halt request\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+ if (debug_req_i) begin\n+ debug_cause_o = DBG_CAUSE_HALTREQ;\n+ end else begin\n+ debug_cause_o = DBG_CAUSE_EBREAK;\n+ end\n end\n- end\n \n- // enter debug mode\n- debug_mode_d = 1'b1;\n+ // enter debug mode\n+ debug_mode_d = 1'b1;\n+ end\n \n ctrl_fsm_ns = DECODE;\n end\n", "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// Davide Schiavone - pschiavo@iis.ee.ethz.ch //\n// //\n// Design Name: Main controller //\n// Project Name: ibex //\n// Language: SystemVerilog //\n// //\n// Description: Main controller of the processor //\n// //\n////////////////////////////////////////////////////////////////////////////////\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_status_i, // decoder has CSR status instr\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\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_defines::pc_sel_e pc_mux_o, // IF stage fetch address selector\n // (boot, normal, exception...)\n output ibex_defines::exc_pc_sel_e exc_pc_mux_o, // IF stage selector for exception PC\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 // External Interrupt Req Signals, used to wake up from wfi even if the interrupt is not taken\n input logic irq_i,\n // Interrupt Controller Signals\n input logic irq_req_ctrl_i,\n input logic [4:0] irq_id_ctrl_i,\n input logic m_IE_i, // interrupt enable bit from CSR\n // (M mode)\n\n output logic irq_ack_o,\n output logic [4:0] irq_id_o,\n\n output ibex_defines::exc_cause_e exc_cause_o,\n output logic exc_ack_o,\n output logic exc_kill_o,\n\n // debug signals\n input logic debug_req_i,\n output ibex_defines::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_restore_dret_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 output logic id_out_valid_o, // ID stage has valid output\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_defines::*;\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 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 exc_req;\n logic exc_req_lsu;\n logic special_req;\n logic enter_debug_mode;\n logic handle_irq;\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_i) 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 // exception requests\n assign exc_req = ecall_insn_i | ebrk_insn_i | illegal_insn_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_status_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 = irq_req_ctrl_i & m_IE_i & ~debug_mode_q;\n assign exc_kill_o = 1'b0;\n\n /////////////////////\n // Core controller //\n /////////////////////\n\n always_comb begin\n // Default values\n instr_req_o = 1'b1;\n\n exc_ack_o = 1'b0;\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_restore_dret_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 irq_ack_o = 1'b0;\n irq_id_o = irq_id_ctrl_i;\n\n debug_csr_save_o = 1'b0;\n debug_cause_o = DBG_CAUSE_EBREAK;\n debug_mode_d = debug_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 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_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_ID;\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 pc_mux_o = PC_EXC;\n pc_set_o = 1'b1;\n\n exc_pc_mux_o = EXC_PC_IRQ;\n exc_cause_o = exc_cause_e'({1'b1, irq_id_ctrl_i});\n\n csr_save_cause_o = 1'b1;\n csr_save_if_o = 1'b1;\n\n irq_ack_o = 1'b1;\n exc_ack_o = 1'b1;\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 // 3. halt request during decode\n // regular ebreak's go through FLUSH.\n //\n // for 1. do not update dcsr and dpc, for 2. and 3. do so [Debug Spec v0.13.2, p.39]\n // jump to debug exception handler in debug memory\n if (ebrk_insn_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 // update dcsr and dpc\n if ((ebrk_insn_i && debug_ebreakm_i && !debug_mode_q) || // ebreak with forced entry\n (enter_debug_mode)) begin // halt request\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 if (debug_req_i) begin\n debug_cause_o = DBG_CAUSE_HALTREQ;\n end else begin\n debug_cause_o = DBG_CAUSE_EBREAK;\n end\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 (illegal_insn_i) 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\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 end else if (dret_insn_i) begin\n pc_mux_o = PC_DRET;\n pc_set_o = 1'b1;\n csr_restore_dret_id_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\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 // signal that ID stage has valid output\n assign id_out_valid_o = ~stall & instr_valid_i & ~special_req;\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 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 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", "selected_doc_paths": ["doc/exception_interrupts.rst", "doc/debug.rst", "doc/instruction_fetch.rst"]}}