{"repo": "lowRISC/ibex", "pr_id": 2224, "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."} {"repo": "lowRISC/ibex", "pr_id": 2229, "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."} {"repo": "lowRISC/ibex", "pr_id": 2250, "spec": "# Behavioral Design Specification: FPGA Register File\n\n## Overview\n\nThis module implements a RISC‑V register file intended for FPGA synthesis. It contains either 31 or 15 general-purpose registers, each 32‑bits wide. Register `x0` is permanently tied to a constant value (by default zero); writes to it have no effect and reads from it always return that constant value.\n\nThe register file provides two independent read ports and one write port. Read data is available in the same clock cycle the address is presented; there is no forwarding path from the write port to the read ports. Consequently, if a register is both read and written in the same cycle, the read returns the **value present before the write** takes effect.\n\nThe design uses synchronous write and combinational (asynchronous) read semantics, allowing FPGA synthesis tools to infer dedicated RAM primitives (e.g., Xilinx RAM32M). The module supports optional error‑checking features that can detect certain illegal access patterns.\n\n## Functional Interface\n\n- **Clock and Reset**: \n The register file operates on the rising edge of a single clock. The reset signal is present only for compatibility and is **not used** by this implementation; the register file powers‑up with all registers initialized to a known constant value (see *Initialization*).\n\n- **Read Ports** (two ports, denoted R1 and R2): \n Each port receives a 5‑bit read address and outputs the corresponding register’s contents in the same clock cycle. \n - If the address is zero, the output is the constant value `WordZeroVal` (default 0). \n - If the address is non‑zero and points to a valid register, the output is the current value of that register. \n - There is no data dependency between simultaneous reads and writes: a read sees the state **before** any concurrent write completes.\n\n- **Write Port** (one port, denoted W1): \n The write port consists of a write address, write data, and a write enable signal. \n - A write is performed on the rising clock edge only when: \n - the write enable is asserted, **and** \n - the write address is **not** zero. \n - Writes to address zero are always ignored. \n - Data written replaces the content of the addressed register on the clock edge.\n\n- **Error Output**: \n A single error indication is asserted (`1`) when any of the optional error detection checks fails. In the absence of those checks, the error output is always `0`. (See *Error Detection* for the conditions that cause an error.)\n\n## Read Operations\n\n- **Combinational read**: The output value for each read port settles within the same clock cycle after the address is applied. \n- **Zero register**: Reading address 0 does **not** access the internal register array; the output is forced to the value of the `WordZeroVal` parameter. \n- **No forwarding**: Because reads are combinational and writes are synchronous, a read that occurs in the same cycle as a write to the same address obtains the **old** value (the value stored before the write clock edge). This is true regardless of the relative order of the read address and write enable in that cycle.\n\n## Write Operations\n\n- **Synchronous write**: The register file updates only on the rising edge of the clock. \n- **Write enable gating**: An internal write is performed **only** when the write enable signal is asserted and the write address is non‑zero. \n- **Write to register zero**: Even if the write enable is asserted, a write address of zero is silently ignored. No internal state changes.\n\n## Error Detection\n\nThe module can be configured to detect two classes of illegal access conditions via the `WrenCheck` and `RdataMuxCheck` parameters. When enabled, the error output is asserted (`1`) if any of the following conditions occurs:\n\n### 1. Spurious Write Enable Glitch Detection (`WrenCheck` enabled)\n\n- A spurious write enable is defined as a situation where the write enable signal is sampled high at the clock edge **when it should not be active**. \n- The detection logic compares the write enable sampled at the clock edge with the intended write enable. If they differ (i.e., the sampled enable is high but the intended enable is low), an error is flagged.\n\n### 2. Read Address One‑Hot Checking (`RdataMuxCheck` enabled)\n\n- For each read port, the supplied address is checked to ensure it is correctly formed as a one‑hot encoded value (exactly one bit high). \n- Glitches or non‑one‑hot patterns on the read address bus cause the corresponding error flag to be asserted. \n- Additionally, when this check is enabled, the read data multiplexer is implemented using a one‑hot select structure (instead of a binary decoder), which itself can be checked for correct operation.\n\n### Error Aggregation\n\nThe error output is the logical OR of: \n- any read address one‑hot error (per port), \n- any spurious write enable error.\n\nWhen the corresponding check is disabled, the respective error signal is forced to `0`, so the error output only reflects enabled checks.\n\n## Initialization and Reset\n\n- **Power‑up / Initialization**: All registers in the register file are **initialized** to the value of the `WordZeroVal` parameter (default `0`) at the start of simulation or after configuration. This initialization occurs once and does **not** depend on the reset signal. \n- **Reset signal**: The reset input (`rst_ni`) is not used for any functional purpose and is tied off internally. There is no requirement to assert reset for correct operation.\n\n## Parameter Impacts\n\n| Parameter | Values | Effect on Behavior |\n|------------------|--------|-------------------|\n| `RV32E` | 0 or 1 | When `1`, only 15 registers are implemented (address bits [3:0] are used; address bit 4 is ignored). When `0`, all 31 registers are available. Register `x0` is still handled specially. |\n| `DataWidth` | integer (default 32) | Determines the width of all registers and data paths. |\n| `WordZeroVal` | logic vector of `DataWidth` | The constant value returned when reading address 0. Also the initial value loaded into all registers at startup. |\n| `WrenCheck` | 0 or 1 | Enables or disables the spurious write enable detection (see *Error Detection*). |\n| `RdataMuxCheck` | 0 or 1 | Enables or disables the one‑hot read address checking and the one‑hot‑based read multiplexer (see *Error Detection*). |\n| `DummyInstructions` | 0 or 1 | This parameter is present for compatibility with other register file flavors but has **no effect** on the FPGA register file’s behavior. The associated input signals are tied off. |\n\n## Additional Notes\n\n- The module does **not** use the test enable or dummy instruction signals; these are wired to unused logic. \n- The register file is designed to be synthesizable into FPGA block RAM (BRAM) or distributed RAM primitives. Asynchronous reads and synchronous writes are the natural model for such primitives. \n- There is **no write‑to‑read forwarding**; software or hardware must insert appropriate stalls or dependencies to avoid reading the wrong value when a write and read to the same register occur in the same cycle."} {"repo": "lowRISC/ibex", "pr_id": 2307, "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."} {"repo": "lowRISC/ibex", "pr_id": 2449, "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."} {"repo": "lowRISC/ibex", "pr_id": 2241, "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."} {"repo": "lowRISC/ibex", "pr_id": 2269, "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."} {"repo": "lowRISC/ibex", "pr_id": 2261, "spec": "# Behavioral Specification for the Ibex Core Controller\n\n## 1. Overview\n\nThe core controller is the central finite-state machine that governs the overall execution flow of the Ibex processor. It coordinates startup from reset, instruction execution, exception and interrupt handling, debug mode entry and exit, sleep/wake‑up, and all changes to the program counter (PC). The controller interacts with the instruction fetch (IF) stage, the instruction decode/execute (ID/EX) stage, and the optional writeback (WB) stage to ensure the pipeline operates correctly under all conditions.\n\nThe controller’s behavior depends on two key parameters:\n\n- **Writeback stage present** – When a third pipeline stage (WB) is instantiated, load/store errors are reported on the instruction in WB and take priority over any exception from the ID/EX stage.\n- **Branch predictor present** – When enabled, the controller handles not‑taken branch mispredictions by requesting a PC correction and flushing the ID/EX stage.\n- **Memory ECC support** – When enabled, a load integrity error generates an internal non‑maskable interrupt (NMI) with a dedicated cause code and address.\n\n## 2. Reset and Boot Sequence\n\nAfter reset, the core must be idle. The controller shall:\n\n1. Request the PC to be set to the boot address (supplied externally).\n2. Perform one additional cycle to propagate the boot address into the fetch stage.\n3. Begin fetching instructions from the boot address.\n4. Transition to normal execution once the first instruction is available in the ID/EX stage.\n\nDuring boot, the controller shall disable all instruction requests until the PC is set.\n\n## 3. Normal Instruction Execution\n\nWhen no special events (exceptions, interrupts, debug requests, or pipeline stalls) are present, the controller shall allow instructions to proceed from IF into ID/EX and be executed.\n\n### 3.1 Branches and Jumps\n\n- When a branch is resolved as taken (branch condition true), the controller **must** request a PC change to the branch target address. \n If the branch predictor is enabled and the branch was *already* predicted taken, no additional PC change is needed – the predictor already redirected the fetch. The controller shall only update the PC if the predictor did not already do so.\n- When a branch is resolved as not taken but was predicted taken (misprediction), the controller **must** request a PC change back to the sequential next instruction and flush the ID/EX stage.\n- When a jump instruction (e.g., `jal` or `jalr`) is executed, the controller **must** always request a PC change to the jump target.\n\n### 3.2 Stalls and Pipeline Control\n\nThe controller shall stall the ID/EX stage whenever:\n\n- The ID/EX stage cannot complete a multi‑cycle instruction (e.g., load, store, multiply, divide, branch, or jump).\n- The writeback stage is not ready to accept a new result.\n\nDuring a stall, the controller shall:\n\n- Prevent the IF stage from supplying a new instruction (halt the IF).\n- Keep the current instruction in the ID/EX stage valid.\n- If the stall is due to a multi‑cycle instruction, retain the instruction’s validity until it finishes.\n\nWhen the stall condition ends, normal flow resumes.\n\n## 4. Exception Handling\n\nThe controller shall handle all synchronous exceptions that occur during instruction execution. Exceptions can arise from:\n\n- Instruction fetch error (access fault).\n- Illegal instruction.\n- Environment call (`ecall`).\n- Breakpoint (`ebreak`).\n- Load access fault.\n- Store access fault.\n\n### 4.1 Exception Priority\n\nWhen multiple exception sources are active in the same cycle, the controller must apply the following priority (highest first). The order differs depending on whether a writeback stage is present.\n\n**With writeback stage (WB present):**\n\n1. Store access fault (from instruction in WB)\n2. Load access fault (from instruction in WB)\n3. Instruction fetch error\n4. Illegal instruction\n5. Environment call (`ecall`)\n6. Breakpoint (`ebreak`)\n\n**Without writeback stage:**\n\n1. Instruction fetch error\n2. Illegal instruction\n3. Environment call (`ecall`)\n4. Breakpoint (`ebreak`)\n5. Store access fault\n6. Load access fault\n\n### 4.2 Exception Processing\n\nWhen a non‑maskable exception is detected and no higher‑priority exception is pending, the controller shall:\n\n- Flush the pipeline: discard the instruction in the ID/EX stage and halt IF.\n- Set the PC to the exception handler address (from `mtvec` CSR).\n- Save the appropriate return PC (from the ID/EX stage, or from the WB stage for load/store faults when WB is present) into `mepc`.\n- Save the exception cause into `mcause`.\n- Save `mstatus.MIE` into `mstatus.MPIE` and clear `mstatus.MIE`.\n- Optionally set `mtval` to the faulting address or instruction encoding, depending on the exception type.\n- Transition back to normal execution after the PC is set and CSRs are updated.\n\nFor an **`ebreak` instruction** that would normally raise a breakpoint exception, the controller shall instead enter debug mode if the core is not yet in debug mode and the appropriate debug CSR bits (`ebreakm` or `ebreaku`) are set. In that case the exception path is overridden by a debug entry (see Section 6).\n\n### 4.3 Handling of `mret` and `dret`\n\n`mret` and `dret` are treated as special instructions that cause a pipeline flush:\n\n- **`mret`** : Restore the PC from `mepc`, restore `mstatus.MIE` from `mstatus.MPIE`, and if the core is currently handling an NMI, exit NMI mode.\n- **`dret`** : Restore the PC from `dpc` and exit debug mode.\n\nBoth instructions flush the ID/EX stage and halt IF before the return address is fetched.\n\n## 5. Interrupt Handling\n\nThe controller shall support the following interrupt sources, ordered by priority (high to low):\n\n1. Non‑maskable interrupt (NMI) – external or internal.\n2. Fast local interrupts (15 sources, `irq_fast[14:0]`).\n3. External interrupt (`irq_external`).\n4. Software interrupt (`irq_software`).\n5. Timer interrupt (`irq_timer`).\n\n### 5.1 Interrupt Enable Conditions\n\nAn interrupt may only be taken when:\n\n- The core is **not** in debug mode.\n- The core is **not** single‑stepping.\n- The core is **not** already handling an NMI (no nesting).\n- The global interrupt enable (`mstatus.MIE`) is set, **or** the core is in User Mode (U‑Mode), where interrupts are always enabled regardless of `MIE` (since `MIE` only applies in M‑Mode).\n\nThe NMI is always enabled and ignores `mstatus.MIE` and `mie` CSR settings.\n\n### 5.2 Interrupt Taking Procedure\n\nWhen an interrupt condition is met and no higher‑priority event (exception or debug) is pending, the controller shall:\n\n- Halt the IF stage to prevent new instructions from being fetched.\n- Wait for any currently executing instruction in ID/EX or WB to complete (including any pending loads or stores) before flushing the pipeline.\n- Set the PC to the interrupt handler address: \n - For NMI: `mtvec` + offset 0x7C. \n - For fast interrupts: `mtvec` + 4 × (16 + interrupt ID). \n - For external, software, or timer interrupts: `mtvec` + 4 × interrupt ID.\n- Save the current PC (from the IF stage) into `mepc`.\n- Save the interrupt cause into `mcause`.\n- Save `mstatus.MIE` into `mstatus.MPIE` and clear `mstatus.MIE`.\n- If an internal NMI (e.g., load integrity error) is taken, set `mtval` to the faulting address.\n- Enter NMI mode when an NMI is taken (both external and internal). In NMI mode, all further interrupts are ignored until NMI mode is exited by `mret`.\n\n### 5.3 Internal Interrupts (Load Integrity Error)\n\nWhen memory ECC protection is enabled, a load response with an integrity error shall set a pending internal NMI. The controller must:\n\n- Record the address of the faulting load.\n- Assert the internal NMI request.\n- The NMI is taken at most one instruction after the faulting load; a subsequent memory operation may execute before the interrupt is taken.\n\nUpon entering the internal NMI handler, the pending flag is automatically cleared. The external NMI has higher priority; if an external NMI arrives while an internal NMI is pending, the external NMI is taken first and the internal NMI remains pending.\n\n## 6. Debug Support\n\nDebug mode entry can be triggered by:\n\n- An external `debug_req` signal.\n- Hardware breakpoint (trigger match) when debug triggers are enabled.\n- Single‑step mode (dcsr.step = 1) after every completed instruction.\n- An `ebreak` instruction when the corresponding debug CSR bit (`ebreakm`/`ebreaku`) is set.\n\n### 6.1 Priority of Debug Entry\n\nDebug entries have the following priority (high to low):\n\n1. `ebreak` with debug entry enabled.\n2. External `debug_req`.\n3. Single‑step.\n4. Trigger match.\n\nA trigger match is only honored if no higher‑priority debug event or exception is pending and the instruction that caused the match is actually executing (i.e., not flushed by a higher‑priority event).\n\n### 6.2 Debug Mode Entry Sequence\n\nWhen the controller decides to enter debug mode, it shall:\n\n- **If entering from a debug event that does not involve an `ebreak` (e.g., debug_req, single‑step, or trigger):** \n - Flush the ID/EX stage. \n - Set the PC to the debug exception address (`DmHaltAddr`). \n - Save the current PC (from IF stage) into `dpc`. \n - Save the debug cause into `dcsr.cause`. \n - Set the debug mode flag. \n - Flush the IF stage.\n\n- **If entering due to an `ebreak` instruction with debug entry enabled (and core not already in debug mode):** \n - Flush the ID/EX stage. \n - Set the PC to the debug exception address. \n - Save the PC of the `ebreak` instruction (from ID stage) into `dpc`. \n - Save the debug cause into `dcsr.cause`. \n - Set the debug mode flag. \n - Do **not** take the breakpoint exception.\n\n- **If an `ebreak` occurs while already in debug mode:** \n - The controller shall re‑enter debug mode by saving the current PC to `dpc` and updating `dcsr.cause`. The core remains in debug mode.\n\nAfter entering debug mode, the controller returns to normal instruction execution, but the core is now in debug mode and reacts as defined by the RISC‑V debug specification.\n\n### 6.3 Debug Mode Exit\n\nDebug mode is exited by executing a `dret` instruction, which restores the PC from `dpc` and clears the debug mode flag.\n\n### 6.4 Interrupts and Exceptions in Debug Mode\n\nWhile in debug mode:\n\n- All interrupts (including NMI) are ignored.\n- Synchronous exceptions that occur inside debug mode are handled using the debug exception address (`DmExceptionAddr`) rather than the normal `mtvec`. The core remains in debug mode.\n\n## 7. WFI and Sleep\n\nThe `wfi` instruction puts the core into a low‑power sleep state. The controller shall:\n\n- Flush the ID/EX stage and halt IF.\n- Enter a sleep state where no instructions are fetched.\n- Remain in sleep until one of the following wake‑up events occurs:\n - Any unmasked interrupt (including NMI) becomes pending.\n - External debug request is asserted.\n - The core was already in debug mode or single‑step mode when `wfi` was executed (in that case `wfi` acts as a NOP and exits sleep immediately).\n- Upon wake‑up, the controller shall restart instruction fetch from the current PC (no interrupt/exception is taken at this point – the core reverts to normal execution unless an interrupt is also pending, in which case the interrupt will be taken in the next cycle).\n\n## 8. Pipeline Flush Behaviors\n\nThe controller must flush the ID/EX stage under the following circumstances:\n\n- A taken branch or jump that was not predicted (or a mispredicted branch).\n- An exception or interrupt is taken.\n- An `mret` or `dret` instruction is executed.\n- A `wfi` instruction is executed (to prevent any previously fetched instruction from executing).\n- A CSR‑related pipeline flush is requested (e.g., after modifying `mstatus` or `mtvec`).\n- When entering or exiting debug mode (pipeline must be empty to ensure consistent debug state).\n\nDuring a flush, the controller:\n\n- Sets a signal to clear the instruction valid flag in the ID/EX stage.\n- Halts the IF stage so no new instruction enters ID/EX.\n- For exceptions and interrupts, the PC is set to the appropriate handler address in the same cycle as the flush.\n\n## 9. Distinction Between WB and ID/EX Exceptions (Writeback Stage)\n\nWhen a writeback (WB) stage is present, load/store faults are detected on the instruction in WB, not in ID/EX. The controller must:\n\n- Prioritize a load/store fault from WB over any exception from ID/EX.\n- When a WB exception is taken, save the return PC from the WB stage into `mepc` (not from ID/EX).\n- Indicate that the instruction in ID/EX must not be executed if a WB exception occurs.\n\nWhen no writeback stage exists, load/store faults occur in ID/EX and are handled like any other ID/EX exception.\n\n## 10. CSR Save and Restore Signals\n\nThe controller shall generate the necessary strobes to save and restore CSR state at the appropriate times:\n\n- **Save IF PC**: when an interrupt or debug entry is taken (save PC from IF stage).\n- **Save ID PC**: when an exception is taken for a non‑load/store fault (save PC from ID/EX stage).\n- **Save WB PC**: when a load/store fault occurs and a WB stage is present (save PC from WB stage).\n- **Save CSR cause**: whenever an exception or interrupt is taken.\n- **Restore on `mret`**: restore `mepc` and `mstatus.MPIE`.\n- **Restore on `dret`**: restore `dpc` and clear debug mode.\n- **Save debug CSR**: when entering debug mode (save cause to `dcsr` and PC to `dpc`).\n\nThese saves and restores are performed in coordination with the PC set and pipeline flush actions.\n\n## 11. Performance Monitoring\n\nThe controller shall provide output flags for performance counters:\n\n- **Jump taken**: asserted when a jump instruction (any variant) resolves as taken.\n- **Taken branch**: asserted when a branch resolves as taken.\n\nThese outputs are used by performance counter logic elsewhere in the core.\n\n## 12. Summary of State Transitions\n\nThe controller proceeds through several major operational phases, though the exact internal states are an implementation detail. The externally visible behavior is:\n\n| Phase | Observable Action |\n|-------|-------------------|\n| Reset | Set PC to boot address, start fetch. |\n| Normal (Decode) | Allow instructions to flow, handle branches/jumps, detect special requests. |\n| Flush | Discard ID/EX instruction, wait for WB ready, then set PC and CSRs for exception/interrupt/special instruction. |\n| Interrupt Taken | Save IF PC, cause, `mstatus`, set PC to handler, enter NMI mode if NMI. |\n| Debug Taken (IF) | Save IF PC, cause, set PC to debug handler, enter debug mode. |\n| Debug Taken (ID) | Save ID PC (from ebreak), cause, set PC to debug handler, enter debug mode. |\n| Sleep | Halt pipeline, wait for wake event, then restart fetch. |\n| Boot Set | Intermediate state during reset to propagate boot address. |\n\nThe controller ensures that only one active special request (exception, interrupt, debug) is handled at a time according to the defined prioritisation rules. After handling, normal execution resumes from the appropriate PC.\n\n--- \n\n*This specification describes the required functional behavior of the Ibex core controller. It does not prescribe internal implementation details such as state encoding or exact timing of internal signals.*"} {"repo": "lowRISC/ibex", "pr_id": 1881, "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."} {"repo": "lowRISC/ibex", "pr_id": 1879, "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."} {"repo": "lowRISC/ibex", "pr_id": 1839, "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."} {"repo": "lowRISC/ibex", "pr_id": 1816, "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)."} {"repo": "lowRISC/ibex", "pr_id": 1824, "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)."} {"repo": "lowRISC/ibex", "pr_id": 1744, "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."} {"repo": "lowRISC/ibex", "pr_id": 1780, "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. |"} {"repo": "lowRISC/ibex", "pr_id": 1975, "spec": "# Behavioral Design Specification for ibex_top (Ibex RISC-V Core)\n\n## 1. Overview\n\n`ibex_top` is the top-level module of the Ibex RISC-V processor core. It implements a 32-bit, in-order, single-issue RISC-V CPU that can execute the RV32I base integer instruction set, optionally extended with:\n\n- **RV32E** (embedded, 16 registers)\n- **RV32M** (multiply/divide)\n- **RV32B** (bit manipulation)\n\nThe core supports configurable physical memory protection (PMP), hardware performance counters, debug triggers, and a set of security features for fault detection and timing‑side‑channel mitigation.\n\n`ibex_top` integrates the CPU pipeline, register file, optional instruction cache (I$), and optional dual‑core lockstep logic. The module provides standard bus interfaces for instruction and data memory, interrupt and debug inputs, alert outputs, and a clock‑gating control signal.\n\n## 2. Configuration Parameters\n\nThe following parameters shall be static (set at synthesis time) and determine the core’s capabilities and behavior.\n\n| Parameter | Effect on Behavior |\n|-------------------------|------------------------------------------------------------------------------------------------------|\n| `PMPEnable` | When 1, physical memory protection (PMP) checking is active on instruction and data accesses. |\n| `PMPGranularity` | Minimum address region size for PMP matching (0 = 4‑byte granularity). |\n| `PMPNumRegions` | Number of PMP configuration regions (1–16). |\n| `MHPMCounterNum` | Number of hardware performance‑monitor counters (0–10). |\n| `MHPMCounterWidth` | Bit width of each performance counter (1–64). |\n| `RV32E` | When 1, only 16 integer registers (x0–x15) are implemented and instructions using x16–x31 are illegal. |\n| `RV32M` | Selects multiplier/divider implementation: none, slow, fast, single‑cycle. |\n| `RV32B` | Selects bit‑manipulation extension: none, balanced, full, or a specific subset. |\n| `RegFile` | Selects register file implementation: flip‑flop, FPGA‑optimised, or latch‑based. |\n| `BranchTargetALU` | When 1, a dedicated branch target ALU is added to remove a stall cycle on taken branches. |\n| `WritebackStage` | When 1, a third pipeline stage (writeback) is added for improved load/store throughput. |\n| `ICache` | When 1, an instruction cache replaces the simple prefetch buffer. |\n| `ICacheECC` | When 1 and `ICache`=1, SECDED ECC protection is added to cache tag and data RAMs. |\n| `ICacheScramble` | When 1 and `ICache`=1, cache RAMs are replaced by scrambling primitives for data confidentiality. |\n| `BranchPredictor` | When 1, static branch prediction is used to reduce taken‑branch stalls. |\n| `DbgTriggerEn` | When 1, a single debug trigger (data‑address match) is supported. |\n| `DbgHwBreakNum` | Number of hardware breakpoints (currently must be ≤ 1). |\n| `SecureIbex` | When 1, all security‑related features are enabled (dummy instructions, bus integrity, register file ECC, glitch detection, shadow CSRs, lockstep). |\n| `RndCnstLfsrSeed` | Initial seed for the LFSR used by dummy instruction generation (only with `SecureIbex`). |\n| `RndCnstLfsrPerm` | Output permutation for the LFSR (only with `SecureIbex`). |\n| `DmHaltAddr` | Address to jump to when entering debug mode (default 0x1A110800). |\n| `DmExceptionAddr` | Address to jump to on exceptions occurring in debug mode (default 0x1A110808). |\n| `RndCnstIbexKey` | Default scramble key for cache scrambling (only with `ICacheScramble`). |\n| `RndCnstIbexNonce` | Default nonce for cache scrambling (only with `ICacheScramble`). |\n\n## 3. Interfaces and Functional Behavior\n\n### 3.1 Clock, Reset, and Test\n\n- **Clock (`clk_i`):** All synchronous logic operates on the rising edge of this clock.\n- **Reset (`rst_ni`):** Active‑low asynchronous reset. When asserted, the core shall be in a known reset state (PC taken from `boot_addr_i`, all CSR state cleared to architectural reset values, pipeline flushed).\n- **Test enable (`test_en_i`):** When asserted, all clock gating shall be disabled to allow full scan testing.\n- **Scan reset (`scan_rst_ni`):** A separate test‑controlled reset. In non‑test operation this must be tied high.\n- **RAM configuration (`ram_cfg_i`):** Provides configuration signals to the internal RAM instances (icache). The exact encoding is defined by the platform’s memory compiler.\n\n### 3.2 Core Identification and Boot\n\n- **Hart ID (`hart_id_i`):** A static 32‑bit identifier for this processor core, readable via the `mhartid` CSR.\n- **Boot address (`boot_addr_i`):** After reset, the core shall start fetching instructions from `boot_addr_i + 0x80` (the reset vector is at `boot_addr_i + 0x80`, following the standard RISC‑V convention; the first eight words are reserved for exception vectors).\n\n### 3.3 Instruction Fetch Interface\n\nThe core fetches instructions through a request‑grant‑response protocol.\n\n- **Request (`instr_req_o`):** When asserted, a new instruction fetch is requested. The core shall hold this signal stable until the memory system asserts `instr_gnt_i`.\n- **Address (`instr_addr_o`):** The word‑aligned address of the instruction to be fetched.\n- **Grant (`instr_gnt_i`):** When asserted, the memory system accepts the request. After grant, the core may change the address in the next cycle.\n- **Response valid (`instr_rvalid_i`):** Asserted for exactly one cycle per accepted request to indicate that `instr_rdata_i` and `instr_err_i` are valid.\n- **Read data (`instr_rdata_i`):** The fetched instruction data (32 bits). The lower two bits determine whether the instruction is compressed (2‑byte) or uncompressed (4‑byte).\n- **Integrity bits (`instr_rdata_intg_i`):** When `SecureIbex`=1, these 7 bits provide error‑detection code for the data. The core shall verify these bits against the data and signal a bus major alert on mismatch.\n- **Error (`instr_err_i`):** When high, the memory access failed (e.g., bus error or PMP violation). The core shall take an instruction‑access exception.\n\n**Protocol:** The core may have multiple outstanding instruction requests (prefetch buffer width). Responses shall be returned in order. The core shall not assert `instr_req_o` again after a PMP error on the same line until a branch occurs.\n\n### 3.4 Data Memory Interface\n\nThe load‑store unit (LSU) uses a similar request‑grant‑response protocol but also includes write control.\n\n- **Request (`data_req_o`):** Asserted to begin a data memory access. Held until `data_gnt_i` is asserted.\n- **Address (`data_addr_o`):** The word‑aligned address of the memory access.\n- **Write enable (`data_we_o`):** High for store operations, low for loads.\n- **Byte enables (`data_be_o`):** 4‑bit mask indicating which bytes of the addressed word are accessed.\n- **Write data (`data_wdata_o`):** Data to be written (32 bits), valid only for stores.\n- **Write data integrity (`data_wdata_intg_o`):** When `SecureIbex`=1, the LU generates integrity bits for write data. These should be transmitted alongside `data_wdata_o` and checked at the memory.\n- **Grant (`data_gnt_i`):** The memory system accepts the request. After grant the core may change address/write data.\n- **Response valid (`data_rvalid_i`):** High for one cycle per request; indicates that `data_rdata_i`, `data_rdata_intg_i`, and `data_err_i` are valid.\n- **Read data (`data_rdata_i`):** Data returned from a load operation (32 bits). For stores, this signal is ignored except for integrity checking.\n- **Read data integrity (`data_rdata_intg_i`):** When `SecureIbex`=1, the core shall check these bits against `data_rdata_i` and signal a bus major alert on mismatch.\n- **Error (`data_err_i`):** High indicates a bus error or PMP violation. The core shall take a data‑access exception.\n\n**Protocol:** The LSU can have up to two outstanding requests (for misaligned accesses). Responses must be returned in order. An error on the first of a pair of misaligned requests does not prevent the second request from being issued, but its response is ignored.\n\n### 3.5 Misaligned Accesses\n\nThe core shall handle misaligned loads and stores (e.g., a 32‑bit load from address 0x3) by performing two word‑aligned bus accesses. Each access follows the standard protocol. If the first access returns an error, the second access is still performed; the core shall take the exception for the first error and discard the second result. The core shall not service a new load/store while waiting for an abandoned second part.\n\n### 3.6 Interrupts\n\nThe core supports the standard RISC‑V interrupt model with configurable delegation and priority.\n\n- **Software interrupt (`irq_software_i`):** Corresponds to `mip.MSIP`.\n- **Timer interrupt (`irq_timer_i`):** Corresponds to `mip.MTIP`.\n- **External interrupt (`irq_external_i`):** Corresponds to `mip.MEIP`.\n- **Fast interrupts (`irq_fast_i[14:0]`):** Up to 15 user‑defined interrupt lines (mapped to `mip` bits 16–30).\n- **Non‑maskable interrupt (`irq_nm_i`):** The highest priority interrupt; taken regardless of `mstatus.MIE` and cannot be masked. The core shall handle it as an NMI, jumping to the `mtvec` address for NMIs (a separate vector from regular exceptions).\n\nAll interrupts are sampled synchronously. The core shall wake from a `WFI` instruction if any interrupt is pending (including NMI). The `irq_pending` internal signal is used for clock gating.\n\n### 3.7 Debug Interface\n\n- **Debug request (`debug_req_i`):** When asserted, the core shall enter debug mode (halt execution) at the next instruction boundary if debug mode is enabled and not already in debug mode. The core jumps to `DmHaltAddr`.\n- **Crash dump (`crash_dump_o`):** A set of registers that can be captured on reset for post‑mortem debugging. It includes the current PC, next PC, last data address, exception PC, and exception address (if any).\n- **Double-fault seen (`double_fault_seen_o`):** This output shall be asserted for one or more cycles when a double fault is detected (i.e., a synchronous exception occurs while already handling a synchronous exception in a context where the handler cannot be re‑entered without a hardware reset or specific CSR bits). The precise conditions are defined by the `SecureIbex` configuration.\n\n### 3.8 Control Signals\n\n- **Fetch enable (`fetch_enable_i`):** A multi‑bit (mubi) signal that gates instruction fetching. When the value is `IbexMuBiOff`, the core shall stop fetching new instructions and float to sleep once any in‑flight instructions complete. When set to `IbexMuBiOn`, normal fetching resumes. Other values are treated as off in non‑secure mode, or as an error in secure mode.\n- **Core sleep (`core_sleep_o`):** High when the core is in a `WFI` sleep state and has no outstanding instruction or data bus transactions. The core shall wake (deassert `core_sleep_o`) upon an interrupt, NMI, or debug request.\n- **Alert outputs:**\n - `alert_minor_o`: A single‑cycle pulse when a recoverable security event is detected (e.g., ECC error in instruction cache).\n - `alert_major_internal_o`: A pulse (possibly multi‑cycle) when an internal, unrecoverable fault is detected (e.g., register file ECC error, lockstep mismatch, hardened PC check failure).\n - `alert_major_bus_o`: A pulse when a bus integrity error is detected (mismatch between data and integrity bits on instruction or data interface).\n\n### 3.9 Scrambling Interface (ICacheScramble)\n\nWhen the instruction cache is configured with scrambling (`ICacheScramble`=1), the core provides a request/acknowledge interface for receiving a fresh encryption key from an external source (e.g., OTP).\n\n- **Key request (`scramble_req_o`):** Asserted when the core needs a new key, typically after a `FENCE.I` instruction that requests key renewal.\n- **Key valid (`scramble_key_valid_i`):** When asserted, `scramble_key_i` and `scramble_nonce_i` carry a valid key and nonce. The core shall latch these values and use them for subsequent cache line encryptions.\n- **Key and nonce (`scramble_key_i`, `scramble_nonce_i`):** The 128‑bit (or configurable‑width) key and nonce used by the scrambling engine.\n\nThe core shall deassert `scramble_req_o` once the key is latched. If a second `FENCE.I` occurs while a request is pending, it shall be ignored (or handled as described in the cache documentation). After a key is received, an automatic cache invalidation shall occur, and all subsequent allocations use the new key.\n\n## 4. Security Features (when `SecureIbex` = 1)\n\n### 4.1 Dummy Instruction Insertion\n\nWhen enabled via a CSR control bit, the core shall insert random dummy instructions into the pipeline at intervals that vary pseudo‑randomly. Dummy instructions write only to register x0 and have no architectural effect. The insertion rate is configurable. This feature requires the `RV32M` parameter to be non‑none.\n\n### 4.2 Data‑Independent Timing\n\nWhen enabled via a CSR control bit, all instructions (including branches, multiplies, and divides) shall execute in the same number of cycles regardless of input data. This prevents timing side‑channels.\n\n### 4.3 Bus Integrity Checking\n\nAs described in the memory interfaces, the core shall generate and check integrity bits (39‑bit inverted Hsaio code) on all data and instruction bus transactions. Mismatches cause a major bus alert and suppress the load register update (for load operations). For stores, the integrity check is done on the response; a mismatch also causes an alert.\n\n### 4.4 Register File ECC and Write‑Enable Glitch Detection\n\nAll reads from the register file shall be checked against an ECC code written at store time. An ECC error (any single or double bit) shall cause an internal major alert. Additionally, the write‑enable signal of the register file shall be tested to ensure it is one‑hot; multiple asserted enables shall trigger an alert.\n\n### 4.5 Shadow CSRs\n\nCritical CSRs (`mstatus`, `mtvec`, `cpuctrl`, `pmpcfg`, `pmpaddr`) shall be duplicated with complemented copies. A continuous comparison shall be made; a mismatch causes an internal major alert. (Note: this feature may be subsumed by lockstep when `SecureIbex` is enabled.)\n\n### 4.6 Hardened PC\n\nA check that the instruction‑fetch PC increments correctly between branches shall be performed. Mismatch triggers an internal major alert.\n\n### 4.7 Dual‑Core Lockstep\n\nWhen `SecureIbex`=1, a second shadow core is instantiated that receives delayed copies of all inputs and compares its outputs against delayed versions of the main core’s outputs. Any difference in outputs (including bus requests, register file addresses, cache control signals, etc.) shall cause an internal major alert. The lockstep logic does not duplicate the register file or cache RAMs; these are protected by ECC.\n\n## 5. Instruction Cache Behavior (when `ICache` = 1)\n\nThe instruction cache acts as a drop‑in replacement for the prefetch buffer. It shall:\n- Cache instructions in a set‑associative structure (number of ways and line size parameterized).\n- On a hit, supply data from the cache in the same cycle as tag lookup (two‑stage pipeline).\n- On a miss, fetch the missing cache line from the instruction memory and allocate it according to the filling policy.\n- Support cache invalidation on `FENCE.I` instruction (or on reset).\n- When `ICacheECC`=1, detect single/double‑bit ECC errors in the tag and data RAMs. On any error, treat it as a cache miss, invalidate the affected line, and signal a minor alert.\n- When `ICacheScramble`=1, all data stored in the cache shall be encrypted using the supplied key/nonce. The encryption is transparent to the rest of the core.\n\nThe cache interface includes a `busy_o` signal that remains high during invalidation or while any external memory request is outstanding.\n\n## 6. Power Management\n\nThe core shall support the `WFI` instruction (wait for interrupt). After executing `WFI`, the core shall deassert `core_sleep_o` only when an enabled interrupt, NMI, or debug request occurs. While sleeping, the internal clocks may be gated; the instruction cache shall also stop fetching. The core shall resume normal operation when a wake event is detected.\n\n## 7. Initialization and Reset\n\nUpon deassertion of `rst_ni`, the core shall:\n- Load the program counter with `boot_addr_i + 0x80`.\n- Clear all CSR state to the architectural reset values (including `mstatus.MIE` = 0, `mtvec` = reset vector, etc.).\n- Invalidate the instruction cache if present.\n- Set any lockstep shadow core to the same reset state.\n- Wait for `fetch_enable_i` to indicate `IbexMuBiOn` before beginning instruction fetching.\n\n## 8. Error Handling\n\n- **Instruction bus errors:** Cause an instruction‑access exception (`mcause` = 1).\n- **Data bus errors:** Cause a load‑access or store‑access exception (`mcause` = 5 or 7).\n- **PMP violations:** Cause the same exceptions as bus errors.\n- **Double faults:** If a synchronous exception occurs while `mstatus.MPRV` is set such that the exception handler cannot be entered, the core shall set `double_fault_seen_o` and may reset itself or enter an infinite loop (implementation‑dependent). The precise behavior is defined by the crash dump and security logic.\n\n## 9. Formal Interface (RVFI)\n\nWhen compiled with `RISCV_FORMAL` define, the core shall output a standard RISC‑V Formal Interface (RVFI) trace of every retired instruction, including register write data, memory access details, and exception status. This interface is used for formal verification and is not required for normal operation.\n\n## 10. Assertion Coverage\n\nThe module includes a suite of SystemVerilog assertions that verify:\n- Output signals are not unknown (X).\n- Instruction and data interfaces follow the described protocol.\n- Maximum outstanding data‑side transactions is never exceeded.\n- Dummy instructions only write to register zero.\n- Crash dump signals are connected to the correct internal signals.\n- Double‑fault detection logic is consistent with the retirement trace (when RVFI is present).\n\nThese assertions are for verification purposes and shall not be synthesized."} {"repo": "lowRISC/ibex", "pr_id": 1488, "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."} {"repo": "lowRISC/ibex", "pr_id": 1917, "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`."} {"repo": "lowRISC/ibex", "pr_id": 1735, "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."} {"repo": "lowRISC/ibex", "pr_id": 1595, "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."} {"repo": "lowRISC/ibex", "pr_id": 1547, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 1725, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 2251, "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)."} {"repo": "lowRISC/ibex", "pr_id": 1446, "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)."} {"repo": "lowRISC/ibex", "pr_id": 1554, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 1643, "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."} {"repo": "lowRISC/ibex", "pr_id": 1699, "spec": "# `core_ibex_dut_probe_if` Design Specification\n\n## Overview\n\nThe `core_ibex_dut_probe_if` interface provides a standardized, cycle‑accurate channel for the UVM testbench to observe and control specific internal signals of the Ibex core. It is used within the `core_ibex` UVM environment to enable functional coverage, assertions, and directed stimulus without modifying the core’s external ports. All signals in this interface are synchronous to the provided clock.\n\n## Interface Characteristic\n\n- **Clock**: The interface is driven and sampled on the rising edge of the input clock.\n- **Direction of signals**: \n – Signals that originate from the DUT (inputs to the interface) are sampled by the testbench. \n – Signals that are driven by the testbench (outputs from the interface) are driven into the DUT.\n- **Reset**: The interface does not contain its own reset logic; the `reset` signal from the DUT is made visible for monitoring.\n\n## Signal Description\n\n### Observability Signals (DUT → Interface)\n\nThese signals reflect internal states of the Ibex core. The testbench shall sample them on the rising edge of the clock as defined by the provided clocking block.\n\n| Signal | Description |\n|---------------------|-------------|\n| `reset` | Indicates the core is held in reset. When asserted (high), all core state is initialised. |\n| `illegal_instr` | Asserted for one cycle when the core decodes an illegal instruction. |\n| `ecall` | Asserted for one cycle when an ECALL instruction is executed (environment call). |\n| `wfi` | Asserted for one cycle when a WFI (wait for interrupt) instruction is executed. |\n| `ebreak` | Asserted for one cycle when an EBREAK (breakpoint) instruction is executed. |\n| `dret` | Asserted for one cycle when a DRET (debug return) instruction is executed. |\n| `mret` | Asserted for one cycle when an MRET (machine‑mode return) instruction is executed. |\n| `core_sleep` | Indicates the core is in a low‑power sleep state (after WFI). Remains asserted until an interrupt or debug request wakes the core. |\n| `alert_minor` | Asserted for a configurable number of cycles when a minor security event is detected (e.g., ECC correctable errors). |\n| `alert_major_internal` | Asserted for a configurable number of cycles when a major internal security event is detected (e.g., register file ECC error, PC integrity violation, shadow CSR mismatch). |\n| `alert_major_bus` | Asserted for a configurable number of cycles when a major bus integrity event is detected (e.g., load data check‑bit mismatch). |\n| `priv_mode` | Current privilege level of the core – `PrivLvlM` (Machine) or `PrivLvlU` (User). |\n| `ctrl_fsm_cs` | Current state of the core’s main control finite‑state machine in the ID/EX pipeline stage. |\n\n### Control Signals (Interface → DUT)\n\nThese signals are driven by the testbench to influence core behaviour. They shall be driven on the rising edge of the clock as defined by the clocking block.\n\n| Signal | Description |\n|-----------------|-------------|\n| `fetch_enable` | Controls instruction fetching. When de‑asserted, the core stops fetching new instructions (the pipeline is stalled). Must be initialised to a known value before core operation starts. |\n| `debug_req` | Requests the core to enter Debug Mode (as defined by the RISC‑V Debug Specification). Asserted by the testbench to trigger synchronous debug entry. The testbench must de‑assert this signal after the core acknowledges the request. |\n\n## Clocking Block Behaviour\n\nA clocking block named `dut_cb` is provided for use in testbench components (e.g., drivers, monitors). It defines the timing discipline for all signals.\n\n- **Sampling** (`input` items in clocking block): \n All observability signals (from DUT) are sampled at the **beginning** of each clock cycle (on the rising edge). This ensures that the testbench sees the exact value driven by the core in that cycle.\n\n- **Driving** (`output` items in clocking block): \n The control signals (`fetch_enable`, `debug_req`) are driven **synchronously** on the rising edge of the clock. The testbench must ensure that these signals are stable before the clock edge and held long enough to meet the core’s input setup/hold requirements.\n\n### Clocking Block Signal Listing\n\n| Direction | Signals |\n|-----------|---------|\n| Output (driven by testbench) | `fetch_enable`, `debug_req` |\n| Input (sampled from DUT) | `reset`, `illegal_instr`, `ecall`, `wfi`, `ebreak`, `dret`, `mret`, `core_sleep`, `alert_minor`, `alert_major_internal`, `alert_major_bus`, `priv_mode`, `ctrl_fsm_cs` |\n\n## Initialisation Behaviour\n\nAt the start of simulation (time zero), the interface shall initialise the driven signal `debug_req` to logic `0`. This prevents an inadvertent debug request from being issued before the testbench has configured the core and debug environment.\n\n*Note*: The `fetch_enable` signal is not initialised by the interface; the testbench shall drive it to an appropriate value (typically `1`) before the core starts fetching.\n\n## Usage Rules\n\n1. All transactions between the testbench and the DUT via this interface must be synchronised using the provided clocking block. Direct assignments outside the clocking block are not recommended.\n2. The testbench must ensure that `debug_req` is asserted only when the core is not in Debug Mode and is not already responding to a previous debug request.\n3. The observability signals are **purely for monitoring**; they are inputs to the interface and must not be driven by the testbench.\n4. The interface does **not** perform any override of the DUT’s internal logic – it only samples and drives according to the timing model defined by the clocking block.\n5. The interface shall not be used to drive signals that are not listed in the clocking block’s output list.\n\n## Relationship to Core Functional Behaviour\n\nThe meaning of each observability signal corresponds to the Ibex core’s documented behaviour:\n\n- **Exceptions and Interrupts** (`illegal_instr`, `ecall`, `ebreak`, `mret`, `dret`): \n Refer to the core’s exception/interrupt handling specification. These signals are asserted for exactly one cycle when the corresponding event occurs in the execution pipeline.\n\n- **Security Alerts** (`alert_minor`, `alert_major_internal`, `alert_major_bus`): \n Defined in the core’s security feature documentation. The duration of the pulse may vary depending on the event; typically held for a configurable number of cycles.\n\n- **Debug** (`debug_req`): \n Complies with the RISC‑V Debug Specification v0.13. The testbench should assert this signal when it requires the core to enter Debug Mode. The core will respond by halting at a safe instruction boundary and then asserting its internal debug flag.\n\n- **Core Sleep** (`core_sleep`): \n Asserted when the core has executed a WFI instruction and no interrupt or debug request is pending. Remains asserted until an event wakes the core.\n\n- **Privilege Mode** (`priv_mode`): \n Reflects the current mode (Machine or User) as defined by the `mstatus` CSR. Changed only by MRET, SRET (if supported), or exception entry.\n\n- **Control FSM State** (`ctrl_fsm_cs`): \n Mirrors the state of the ID/EX stage control FSM. Useful for tracking pipeline progress and stalling conditions.\n\nThis interface is purely a testbench observation and control point; it does **not** alter the functional correctness of the core. The testbench shall rely on these signals only for verification purposes and must not assume they affect core behaviour in simulation."} {"repo": "lowRISC/ibex", "pr_id": 1443, "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)."} {"repo": "lowRISC/ibex", "pr_id": 1326, "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."} {"repo": "lowRISC/ibex", "pr_id": 1179, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 1107, "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."} {"repo": "lowRISC/ibex", "pr_id": 1620, "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."} {"repo": "lowRISC/ibex", "pr_id": 1300, "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)."} {"repo": "lowRISC/ibex", "pr_id": 1380, "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."} {"repo": "lowRISC/ibex", "pr_id": 1216, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 1087, "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."} {"repo": "lowRISC/ibex", "pr_id": 1176, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 1002, "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."} {"repo": "lowRISC/ibex", "pr_id": 1136, "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."} {"repo": "lowRISC/ibex", "pr_id": 1130, "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."} {"repo": "lowRISC/ibex", "pr_id": 1036, "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."} {"repo": "lowRISC/ibex", "pr_id": 1037, "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)."} {"repo": "lowRISC/ibex", "pr_id": 1054, "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)."} {"repo": "lowRISC/ibex", "pr_id": 903, "spec": "# Behavioral Specification for Ibex Physical Memory Protection (PMP) Module\n\n## 1. Overview\n\nThe Physical Memory Protection (PMP) module provides region-based access control for memory and I/O transactions in accordance with the RISC-V Privileged Specification (version 1.11). It monitors address requests from multiple independent channels (e.g., instruction fetch and load/store) and checks them against a set of programmable PMP regions. The module asserts an error signal for each channel when the access is not permitted.\n\nThe module is only present in the design when the top‑level `PMPEnable` parameter is set to 1.\n\n## 2. Configuration Parameters\n\n| Parameter | Legal Range | Description |\n|-------------------|-------------|-------------|\n| `PMPGranularity` | 0–31 | Minimum region granularity in bytes: 2^(G+2). Affects address matching and disables NA4 mode when >0. |\n| `PMPNumChan` | ≥1 | Number of independent access check channels (e.g., 1 for I‑side, 1 for D‑side). |\n| `PMPNumRegions` | 1–16 | Number of implemented PMP regions (0 is not allowed when the module is instantiated). |\n\n## 3. Interfaces\n\n### 3.1 Inputs\n- **Clock and reset** (active-low asynchronous reset).\n- **PMP configuration registers** for each region: mode (OFF, NA4, NAPOT, TOR), read/write/execute permissions, and a **lock** bit. The address register for each region is also provided.\n- **Privilege level** for each channel (Machine or User/Supervisor).\n- **Address request** (34‑bit physical address) for each channel.\n- **Access type** for each channel: read, write, or execute.\n\n### 3.2 Outputs\n- **Access error** for each channel: asserted when the access is not permitted; de‑asserted when access is allowed.\n\n## 4. Functional Behavior\n\n### 4.1 Address Matching\n\nEach PMP region defines an address range using its mode and the associated address register(s). The module performs a logical comparison between the incoming request address and each region’s range. A region is said to **match** when the request address falls within its defined range, under the qualifications below:\n\n- **OFF mode**: The region is disabled and never matches.\n- **NA4 mode** (only valid when `PMPGranularity = 0`): The region covers exactly 4 bytes starting at the programmed address (the address must be aligned to 4 bytes). \n If `PMPGranularity > 0`, NA4 mode is not supported and is treated as OFF mode.\n- **NAPOT mode**: The region covers a naturally aligned power‑of‑two size. The size is derived from the least‑significant set of contiguous 1s in the programmed address; matching ignores address bits that fall within the programmed granule. \n The minimum size is **2^(PMPGranularity+2)** bytes when `PMPGranularity > 0`.\n- **TOR mode**: The region covers all addresses from the *previous* region’s address register (or zero for region 0) up to but not including the region’s own address register. The region matches when the request address is greater than or equal to the start address and less than the end address.\n\nAll comparisons use address bits from the most‑significant down to bit (PMPGranularity+2), effectively ignoring the `PMPGranularity+2` least‑significant address bits for matching purposes. This implements the minimum region granularity.\n\n### 4.2 Permission Validation\n\nFor a given channel, each region that matches the request address is checked to see if it **grants** the requested access type. The required permission for an access type is:\n\n| Access Type | Required Permission Bit |\n|-------------|------------------------|\n| Execute | `exec` |\n| Write | `write` |\n| Read | `read` |\n\nA region is considered to permit the access when the corresponding permission bit is set.\n\n### 4.3 Access Fault Determination\n\nThe access fault output for a channel is determined by the following rules:\n\n1. **Base default**: \n - When the privilege level is **User or Supervisor** (i.e., not Machine mode), the default is to **deny** access (fault). \n - When the privilege level is **Machine mode**, the default is to **allow** access (no fault).\n\n2. **Overriding by matching regions** (static priority): \n The regions are evaluated in order from highest index (PMPNumRegions‑1) down to 0. For each matching region, the final fault decision is overridden according to the rules below. Once an override occurs, lower‑index regions are ignored. If multiple regions match, the **lowest‑numbered** (highest priority) region among those that caused an override actually takes effect. (In the implementation, the loop runs from highest to lowest index so that the lowest‑index match wins.)\n\n - **Machine mode access**: \n A matching region *allows* the access (clears the fault) unless the region’s lock bit is set AND the required permission is not granted. \n In other words, if the region is locked and does not grant the required permission, a fault is raised. If the region is unlocked, the access is allowed regardless of the permission bits (Machine mode has unrestricted access to unlocked regions). If the region is locked and does grant the required permission, access is also allowed.\n\n - **User/Supervisor mode access**: \n A matching region *allows* the access only if the required permission is granted. The lock bit has no effect in determining faults for non‑Machine modes. If the required permission is not granted, a fault is raised.\n\n3. **Result**: \n The final fault decision is applied to the corresponding channel’s error output. If a fault is raised, the output is asserted; otherwise it is de‑asserted.\n\n### 4.4 Effects of PMP Granularity\n\nThe `PMPGranularity` parameter reduces the hardware cost by increasing the minimum region size. This parameter affects address matching as described above, and additionally:\n\n- NA4 mode becomes unavailable (treated as OFF) when `PMPGranularity > 0`.\n- All region boundaries (both start and end addresses) are effectively rounded down to a multiple of `2^(PMPGranularity+2)` bytes. The programmer must ensure the programmed addresses respect this alignment; otherwise, the effective range may be larger than intended.\n\n### 4.5 Lock Bit Behavior\n\nThe lock bit (provided in the PMP configuration register for each region) interacts only with Machine‑mode accesses, as described in 4.3. It does not affect fault determination for User/Supervisor mode accesses. The lock bit is not used for any other purpose in the PMP module.\n\n### 4.6 Multiple Channels and Concurrent Checks\n\nEach channel operates independently. The same set of PMP configuration registers is used for all channels. There is no ordering or dependency between channels; the module computes the fault signal for every channel in the same clock cycle.\n\n## 5. Reset Behavior\n\nUpon reset (asynchronous reset asserted, then de‑asserted synchronously), the module’s internal state is initialized. The PMP configuration registers are not part of this module; they are assumed to be reset externally (typically to zero). With all regions in OFF mode and all permission bits cleared, the module’s default fault behavior (see 4.3) applies: Machine mode accesses are allowed; all other accesses are denied until a region is correctly programmed.\n\n## 6. Summary of Observability\n\nThe module’s only observable outputs are the per‑channel error signals. These signals indicate whether the requested access to the given address, by the given privilege level and access type, is permitted according to the programmed PMP policy. There is no internal state that affects future checks beyond the current set of configuration register values.\n\n---\n\n*This specification describes the behavioral requirements of the `ibex_pmp` module as derived from the RTL implementation and the accompanying documentation.*"} {"repo": "lowRISC/ibex", "pr_id": 1182, "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."} {"repo": "lowRISC/ibex", "pr_id": 1050, "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."} {"repo": "lowRISC/ibex", "pr_id": 855, "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."} {"repo": "lowRISC/ibex", "pr_id": 813, "spec": "# Load-Store Unit (LSU) Specification\n\n## Overview\nThe Load-Store Unit (LSU) is responsible for executing all load and store memory operations issued by the processor core. It handles word (32-bit), halfword (16-bit), and byte (8-bit) accesses, including misaligned accesses that cross word boundaries. The LSU manages the data memory interface, performs byte-enable generation, data alignment, sign extension, and error reporting. It operates as a finite state machine that coordinates memory request/response handshaking, supports split transactions for misaligned accesses, and ensures correct ordering and completion of operations.\n\n## Interface Description\nThe LSU connects to the processor pipeline (ID/EX stage) and to an external data memory or bus system.\n\n### Signals from the Pipeline\n- Load/Store type (word, halfword, byte).\n- Write enable (indicates store vs. load).\n- Data to be written (for stores).\n- Sign extension flag (for loads, indicates signed vs. unsigned extension).\n- Request valid (indicates a new load or store operation is pending).\n- Memory address (computed by the ALU, provided as a 32‑bit value).\n\n### Signals to the Pipeline\n- Read data (aligned and sign‑extended to 32 bits).\n- Read data valid (asserted when read data is available).\n- Address increment request (asserted during misaligned accesses to request the next transaction’s address).\n- Last address (for exception handling and misaligned address generation).\n- Request done (asserted when the current operation is fully completed, i.e., the LSU has received the final response and is ready for a new request).\n- Response valid (asserted when a transaction response – load data or store acknowledgement – is available).\n- Load error / Store error (asserted when an error is detected on a load or store, respectively).\n- Busy (asserted while the LSU is processing an outstanding transaction).\n\n### Signals to the Data Memory\n- Request valid (stays high until granted).\n- Address (word‑aligned, 32 bits).\n- Write enable (high for stores, low for loads).\n- Byte enables (4‑bit mask indicating which bytes to read/write).\n- Write data (32 bits, aligned for the target byte lanes).\n- Grant input (acknowledges the request; the address and control signals may change in the next cycle).\n- Read data valid (asserted for one cycle when response is available).\n- Read data (32 bits of read data, valid when read data valid is high).\n- Error input (asserted with read data valid to indicate a bus or memory error).\n\n## Functional Description\n\n### Access Types\nThe LSU supports three access sizes:\n- **Word**: 4 bytes, natural alignment at 4‑byte boundary.\n- **Halfword**: 2 bytes, natural alignment at 2‑byte boundary.\n- **Byte**: 1 byte, any address.\n\nFor loads, the data is sign‑extended (or zero‑extended) to 32 bits according to the sign extension flag. For stores, the write data is aligned and masked appropriately.\n\n### Normal (Aligned) Accesses\nWhen an access address is naturally aligned for the given size, the LSU performs a single word‑aligned memory transaction. The byte enables are set to cover the exact bytes of the access. For example:\n- Word at offset 0: all four byte enables active.\n- Halfword at offset 0: enables for bytes 0 and 1.\n- Halfword at offset 2: enables for bytes 2 and 3.\n- Byte at any offset: enables only the corresponding byte lane.\n\nThe write data is rotated so that the least‑significant byte of the data is placed in the byte lane addressed by the lower two address bits.\n\nFor loads, the returned 32‑bit read data is shifted and sign‑extracted to produce the final value. The LSU internally captures the offset of the original access to correctly reconstruct the result.\n\n### Misaligned Accesses\nAccesses that cross a word boundary are automatically split into two separate word‑aligned transactions. A misaligned access is defined as:\n- **Word access** when the lower two address bits are not `00`.\n- **Halfword access** when the lower two address bits are `11` (address ends in `0b11`).\n\nByte accesses are never misaligned.\n\nThe LSU handles misaligned accesses in the following manner:\n1. The first transaction uses the original (misaligned) address, but the address sent to the memory is forced word‑aligned (lower two bits set to `00`). The byte enables and write data are generated to cover only the bytes that belong to the first part of the access.\n2. The LSU outputs an address increment request to the pipeline, instructing it to increment the original address by 4 for the second part. The pipeline updates the address and presents it to the LSU.\n3. The second transaction uses the incremented, word‑aligned address. The byte enables and write data are generated to cover the remaining bytes.\n4. For loads, the data from the two read responses is combined internally. The bytes from the first response are stored in a temporary register; the bytes from the second response are merged with the stored bytes to form the complete 32‑bit value, which is then sign‑extracted according to the access type.\n\nThe LSU asserts the address increment request during the entire time it is waiting for the second transaction to complete, ensuring the pipeline does not change the address prematurely.\n\n### Byte Enable Generation\nByte enables are a 4‑bit mask indicating which byte lanes in the 32‑bit word are accessed. They are generated based on:\n- Access type (word, halfword, byte).\n- Lower two bits of the original address (byte offset).\n- Whether this is the first or second part of a misaligned access.\n\nFor the first part of a misaligned word access, the byte enables cover the bytes from the offset to the end of the word (e.g., offset `01` → enables `1110`). For the second part, enables cover the bytes from the beginning of the next word up to just before the offset (e.g., offset `01` → enables `0001`). The same logic applies for halfword accesses: the first part covers bytes from offset to the end (or part of the halfword) and the second part covers the remaining byte(s) at the start of the next word.\n\n### Data Alignment\n\n#### Write Data\nFor store operations, the write data is rotated so that the least‑significant byte of the data appears on the byte lane addressed by the lower two address bits. This rotation is performed irrespective of whether the access is aligned or misaligned (the byte enables ensure only the correct bytes are written).\n\n#### Read Data (Loads)\nFor load operations, the LSU performs sign extension after reconstructing the final data. The read data is processed as follows:\n- **Word load**: The 32‑bit value is taken directly from the memory response. For misaligned word loads, the value is reconstructed from two memory responses using the temporarily stored upper bytes from the first response.\n- **Halfword load**: The relevant 16‑bit halfword is extracted from the word (aligned according to the original address offset) and then sign‑extended (or zero‑extended) to 32 bits.\n- **Byte load**: The relevant byte is extracted and sign‑extended (or zero‑extended) to 32 bits.\n\nThe sign extension flag determines whether the MSB of the extracted halfword or byte is extended (signed) or a zero is extended (unsigned).\n\n### Error Handling\nThe memory system can signal an error for any transaction via the error input, which is valid only when the read data valid signal is asserted. Additionally, a physical memory protection (PMP) error input is provided; it is considered valid only during the address phase (when a request is issued and accepted).\n\n- **Store error**: Asserted when the final response of a store transaction indicates an error (either data error or PMP error).\n- **Load error**: Asserted when the final response of a load transaction indicates an error.\n\nIf an error occurs on the first part of a misaligned access, the LSU does not cancel the second part; it still issues the second transaction and waits for its response. However, the data/response from the second part is ignored, and the error from the first part is reported as the final outcome. The address presented to the memory for the second part is still generated, but the pipeline is not required to provide a new address update if the first part already failed (though the LSU may still request the address increment – the pipeline must still respond appropriately).\n\nThe LSU stores the last transaction address for exception handling (`mtval`) and for generating the second address in misaligned accesses. The stored address is updated only when a transaction completes without error. If an error occurs, the address is not updated, thus preserving the faulting address.\n\n### Protocol Timing\nThe LSU follows a request‑grant‑response protocol with the data memory:\n\n1. **Request phase**: The LSU asserts a request, provides the address, write enable, byte enables, and write data (for stores). The request stays high until the memory asserts a grant.\n2. **Grant**: The memory may assert the grant in the same cycle as the request or any later cycle. After receiving the grant, the LSU may change the address and control signals in the next cycle for a subsequent transaction.\n3. **Response phase**: After one or more cycles following the grant, the memory asserts read data valid for exactly one cycle. At that time, the error flag and read data (if any) are valid. The LSU expects responses in the same order as the transactions were granted.\n\nThe LSU can have multiple outstanding transactions (e.g., both parts of a misaligned access). The memory system must return responses in‑order.\n\n### Finite State Machine\nThe LSU operates as a finite state machine with the following states:\n\n- **IDLE**: No transaction pending. When a new request arrives, the LSU issues the first request and moves to either a wait state for a misaligned access or directly to IDLE if the request is granted immediately for an aligned access.\n- **WAIT_GNT_MIS**: Waiting for a grant for the first part of a misaligned access.\n- **WAIT_RVALID_MIS**: Waiting for the read data valid for the first part of a misaligned access. During this state, the LSU also issues the second request (if the first part has not yet been granted) or waits for the second part’s grant/rvalid.\n- **WAIT_GNT**: Waiting for a grant for the second part of a misaligned access (or for a non‑misaligned access if the first grant was delayed).\n- **WAIT_RVALID_MIS_GNTS_DONE**: The second part of a misaligned access has already been granted, and the LSU is waiting for the first part’s read data valid. Once received, it will then wait for the second part’s response.\n\nThe state machine transitions back to IDLE when the final response is received and the transaction is complete.\n\n### Performance Monitoring\nThe LSU outputs performance counter pulses:\n- A pulse for a load operation when the request is first issued.\n- A pulse for a store operation when the request is first issued.\n\nThese pulses are independent of misaligned splits; only one pulse is generated per pipeline load or store operation.\n\n## Constraints and Assumptions\n- The address from the pipeline is a 32‑bit value. The LSU always outputs a word‑aligned address (lower two bits zero) to the memory.\n- The LSU does not handle atomic operations or cache coherency.\n- Error responses are assumed to be persistent: if an error is received, the LSU will report it and not retry.\n- The memory system is assumed to process requests in‑order and return responses in‑order.\n- The pipeline must provide a new address when the address increment request is asserted, and must not issue a new load/store request until the previous one is complete (as indicated by the request done signal).\n- The PMP error signal is valid only during an address phase; it is sampled when a grant is received or when a new request is issued (depending on the state). The LSU may use a registered version of the PMP error to avoid losing it before the corresponding response."} {"repo": "lowRISC/ibex", "pr_id": 699, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 969, "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."} {"repo": "lowRISC/ibex", "pr_id": 905, "spec": "# Behavioral Specification: Instruction Cache (ibex_icache)\n\n## Overview\n\nThis module implements an instruction cache (I$) that sits between the processor core and the instruction memory bus. Its primary purpose is to reduce instruction fetch latency by storing recently used instructions and fetching ahead. The cache can be configured in size, associativity, line size, ECC protection, and caching policy.\n\nThe cache communicates with the core via a ready/valid handshake and with the instruction memory using a request/grant/data-valid interface. It supports speculative prefetching, cache invalidation, and error handling (including memory errors and PMP violations).\n\n## Core Interface Behavior\n\n### Instruction Request and Address Tracking\n\nThe core indicates that it will need instructions by asserting a request signal. When this signal is de‑asserted, the cache stops making new memory requests after completing any ongoing line fills.\n\nAn internal address counter tracks the next instruction to deliver. This counter is updated in one of two ways:\n- On a **branch**: when the core asserts a branch signal along with a valid target address, the counter is set to that address. The branch signal must be accompanied by a speculative branch signal (available earlier in the cycle). If the speculative branch is asserted but the actual branch is not, any lookup started that cycle is cancelled.\n- On **sequential execution**: when the core accepts an instruction, the counter increments by 2 or 4 bytes depending on whether the instruction is compressed (bottom two bits not equal to `2'b11`) or uncompressed.\n\nAfter reset (or when `rst_ni` is de‑asserted), the address counter is undefined. The core **must** assert a branch on or before the first cycle that the request signal is asserted after reset, otherwise the cache may fetch from arbitrary addresses.\n\n### Instruction Output\n\nValid instruction data (32 bits, aligned to the address output) is presented along with a `valid` signal. Once `valid` is asserted, all output signals remain stable until the core either accepts the instruction (by asserting `ready`) or the core issues a new branch. The only exception is after an error is reported: after an error, output signals are unconstrained until the next branch.\n\nThe instruction width is determined from the bottom two bits of the returned data:\n- If they equal `2'b11`, the instruction is 32 bits (uncompressed). Otherwise it is 16 bits (compressed).\n- For compressed instructions, the upper 16 bits of the 32‑bit output are unspecified and may change even after valid is asserted.\n\n### Alignment and Skid Buffer\n\nInstructions are always fetched as words (32 bits). To handle misalignment caused by compressed instructions, the cache contains a 16‑bit skid buffer:\n- If the output address is halfword‑aligned and the instruction is compressed, the lower 16 bits are used and the next word’s upper halfword may be buffered.\n- If the output address is word‑aligned and the instruction is uncompressed, both halves are delivered in one cycle.\n- If an uncompressed instruction straddles a word boundary (i.e., address bit 1 is high), the first halfword is buffered and the second halfword is delivered in a subsequent cycle.\n- Branches flush the skid buffer.\n\n### Error Reporting\n\nErrors from the instruction memory (both bus errors and PMP violations) are propagated to the core. An error is signalled on the output when an instruction fetch fails. When an error is reported, the data output is not specified. For uncompressed instructions that span two words, a second error signal indicates whether the second halfword caused the error; this is only meaningful when an error is reported.\n\nAfter the core observes an error on the output, it must issue a branch before accepting the next instruction. The output signals are otherwise unconstrained after an error.\n\n### Ready/Valid Handshake\n\nThe core accepts an instruction by asserting `ready` while `valid` is high. If `valid` is high and `ready` is not asserted, the output must remain stable until either `ready` is asserted or a branch occurs. A correctly behaving core must not assert `ready` while the request signal is de‑asserted.\n\n## Instruction Memory Interface\n\n### Request and Data Transfer\n\nThe cache requests instructions from memory using a standard request/grant/data-valid protocol. The request address is always aligned to the bus width (32 bits). A single request may be granted on the same cycle; after grant, the cache expects a data valid response (with optional error) for that request. Multiple requests can be outstanding.\n\n### Speculative Requests\n\nThe cache may issue speculative requests in parallel with a cache lookup. By default, speculative requests are made only on a branch. When the `SpecRequest` parameter is set, speculative requests are also made on every lookup attempt (even when not branching). This improves performance for workloads that have low cache hit rates, at the cost of extra bus traffic.\n\n### PMP Error Handling\n\nA dedicated PMP error input indicates that the fetch is disallowed by a physical memory protection check. When this signal is asserted together with a grant, the cache treats the request as if it were granted but never expects a data valid response. The entire cache line fetch for that address is aborted, and an error is reported to the core. If both grant and PMP error are asserted, the error takes precedence.\n\n## Cache Operation Modes\n\n### Pass‑Through Mode\n\nWhen the cache enable signal is de‑asserted, the cache operates in pass‑through mode:\n- Every instruction request from the core is fetched directly from memory.\n- No instruction data is stored in the cache RAMs.\n- The prefetch buffer is used only to supply sequential instructions; on a branch the buffer is discarded.\n- The core still receives instructions through the same interface, but no caching takes place.\n\n### Normal Caching (All Misses Allocated)\n\nWhen caching is enabled, every missing fetch that passes through the cache pipeline results in a cache line allocation. The victim way is chosen using a per‑set pseudo‑random round‑robin counter, preferring invalid ways if any exist.\n\n### Branch‑Only Caching\n\nWhen the `BranchCache` parameter is set, the cache only allocates lines for the target of a branch and the two subsequent cache lines. All other misses are not cached. This mode reduces cache pollution for workloads that can be effectively prefetched, while still accelerating branch targets.\n\n### Prefetching\n\nThe cache maintains a prefetch address that advances in cache‑line increments after each granted lookup. On every branch, the prefetch address is set to the branch target. The prefetcher continues to request sequential lines as long as the request signal is high and the fill buffers are not overloaded.\n\n## Cache Invalidation\n\nThe cache is invalidated:\n- **After reset**: a full invalidation of all tag entries is performed automatically.\n- **On request**: when the cache invalidation input is asserted for at least one cycle, an invalidation sequence begins.\n\nDuring invalidation, the cache behaves as if caching is disabled (no new allocations), but existing lookups and instruction fetches can still proceed. The invalidation walks through all cache indices and clears the valid bit in the tag RAM for all ways. Once the walk completes, normal caching resumes. If a second invalidation request is received while an invalidation is in progress, it is ignored (invalidation does not need to restart).\n\n## Cache ECC Protection\n\nIf ECC is enabled, each tag and data RAM entry includes SECDED checkbits. On a cache read (at the end of the pipeline), the ECC logic checks both tag and data for errors:\n- Any single‑ or double‑bit error in a tag or data RAM is detected.\n- When an error is detected, the cache treats the current lookup as a miss: the request is served from the instruction memory, and the erroneous line(s) are invalidated (valid bit cleared) in the following cycle.\n- No inline correction is performed; the corrupted data is always discarded.\n- Lookups are blocked while the invalidation write for the erroneous way is in progress.\n\n## Fill Buffers\n\nThe cache contains a set of fill buffers (at least 2) that manage the lifecycle of each cache line fetch. Every lookup request (whether it hits or misses) acquires a fill buffer. The fill buffer tracks:\n\n- **External requests**: multiple bus requests to fetch all beats of the cache line.\n- **Received data**: counting returning beats.\n- **Output data**: supplying beats to the core as they become available.\n- **Cache allocation**: once all beats have been received, if the line is to be cached (and no error occurred), it is written into the data and tag RAMs.\n- **Cancellation**: fill buffers are cancelled on a branch if no external requests have been issued. If requests have already been issued, they complete and the line may still be allocated (unless the cache is disabled or an invalidation is in progress).\n\nFill buffers are age‑ordered; the oldest buffer that has data available supplies the next beat to the core. Data can come from three sources: a cache hit (data from the data RAM), buffered data in the fill buffer, or directly from the bus (rvalid data). Hitting lines supply the first word immediately from the RAMs; subsequent words are buffered and supplied on demand.\n\n## Busy Signal\n\nThe cache asserts a busy signal when it is performing any operation that prevents clock gating:\n- While an invalidation is in progress.\n- While any fill buffer has an outstanding external request that has not yet received its data (i.e., it is still waiting for bus responses).\n\nWhen the busy signal is de‑asserted, the cache has no pending bus transactions and is not invalidating; it is safe to gate the clock.\n\n## Configuration Parameter Effects\n\nThe following parameters alter the observable behavior:\n\n| Parameter | Effect |\n|-----------|--------|\n| `BusWidth` | Fixed at 32 bits for the current Ibex system. |\n| `CacheSizeBytes` | Total cache capacity (all ways combined). |\n| `LineSize` | Width of each cache line in bits. Must be greater than 32. Larger lines increase area efficiency but can cause higher latency on misaligned branches. |\n| `NumWays` | Associativity (number of ways per set). |\n| `ICacheECC` | When set, SECDED ECC is added to tag and data RAMs; error detection and invalidation on error are enabled. |\n| `SpecRequest` | When set, speculative bus requests are made on every lookup; otherwise only on branches. |\n| `BranchCache` | When set, only branch targets (and two following lines) are cached; all other misses bypass the cache. |\n\n## Behavioral Assumptions and Constraints\n\n- The core must ensure that `branch_spec_i` is asserted whenever `branch_i` is asserted.\n- The core must not assert `ready` when the request signal is de‑asserted.\n- After an error is reported, the core must issue a branch before accepting further instructions.\n- The cache does not perform any write‑back or coherence; invalidations are global and unconditional.\n- The cache is designed for a single‑core system with no snooping or DMA."} {"repo": "lowRISC/ibex", "pr_id": 854, "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."} {"repo": "lowRISC/ibex", "pr_id": 835, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 836, "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)"} {"repo": "lowRISC/ibex", "pr_id": 560, "spec": "# Behavioral Specification: `core_ibex_env_cfg`\n\n## Overview\n\nThe `core_ibex_env_cfg` module is a configuration object used within the UVM testbench for the Ibex RISC‑V core. It defines the control knobs that dictate how interrupt and debug stimulus is generated during simulation, as well as the signature address used for the handshaking mechanism between the core and the testbench. This configuration is populated from command‑line plusargs at the start of simulation and is then accessed by the test environment to drive external events.\n\n## Configuration Parameters\n\nThe object contains the following behavioral parameters. Default values are `0` for all bit fields and `0` for the maximum interval, unless explicitly overridden via simulation plusargs.\n\n### `enable_irq_single_seq`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the testbench must generate single interrupt requests to the core. When `0`, no single‑interrupt sequences are produced. This allows selective testing of single vs. multiple interrupt scenarios.\n\n### `enable_irq_multiple_seq`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the testbench must generate sequences that assert multiple interrupts concurrently or in rapid succession. When `0`, multi‑interrupt sequences are not generated.\n\n### `enable_nested_irq`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the test environment must enable scenarios where an interrupt is taken while the core is already servicing another interrupt (i.e., nested interrupt handling). When `0`, nested interrupt scenarios are disabled.\n\n### `enable_debug_seq`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the testbench must generate debug request sequences (via `debug_req_i`) to cause the core to enter Debug Mode. When `0`, debug sequences are not generated.\n\n### `max_interval`\n- **Type**: 32‑bit unsigned integer\n- **Behavior**: Specifies the maximum number of clock cycles or instruction executions (depending on the sequence implementation) between successive interrupt or debug events. This controls the density of external stimulus. A value of `0` may be interpreted as no constraint.\n\n### `require_signature_addr`\n- **Type**: Boolean (0 or 1)\n- **Behavior**: When set to `1`, the test environment must use the handshaking mechanism based on the signature address. This instructs the core to write status information to that address during runtime, which is then read by the testbench for verification.\n\n### `signature_addr`\n- **Type**: 32‑bit unsigned integer (physical address)\n- **Behavior**: The memory address used for the handshaking protocol. The core writes a signature (status word) to this address. The testbench monitors this location to track core state transitions, such as entry into interrupt handlers or Debug Mode. The default address (if not overridden) is `0x8ffffffc`, as documented in the verification guide.\n\n## Initialization\n\nUpon construction of the `core_ibex_env_cfg` object, the module shall read the following simulation plusargs to set its fields. If a plusarg is not provided, the corresponding field retains its default value (zero for bits, zero for `max_interval`, and an empty string for `signature_addr_str`, which results in `signature_addr` being zero unless explicitly set).\n\n| Plusarg Name | Field Set | Value Interpretation |\n|-----------------------------|-------------------------------|------------------------------------------|\n| `enable_irq_single_seq` | `enable_irq_single_seq` | Decimal integer (0 or 1) |\n| `enable_irq_multiple_seq` | `enable_irq_multiple_seq` | Decimal integer (0 or 1) |\n| `enable_nested_irq` | `enable_nested_irq` | Decimal integer (0 or 1) |\n| `enable_debug_seq` | `enable_debug_seq` | Decimal integer (0 or 1) |\n| `max_interval` | `max_interval` | Decimal integer |\n| `require_signature_addr` | `require_signature_addr` | Decimal integer (0 or 1) |\n| `signature_addr` | `signature_addr` | Hexadecimal string (e.g., `0x8ffffffc`) |\n\nThe string value of the `signature_addr` plusarg is converted to a 32‑bit integer using an `atohex` conversion. If the string is empty or invalid, the resulting address shall be zero.\n\n## Functional Behavior in the Test Environment\n\nThe `core_ibex_env_cfg` object is used by the test environment to configure the behavior of the interrupt agent, debug agent, and the test‑sequence library. Specifically:\n\n- The **interrupt agent** shall generate interrupt requests only for the classes of interrupts that are enabled (single, multiple, nested) and shall respect the `max_interval` constraint when scheduling those events.\n- The **debug agent** shall generate `debug_req_i` assertions only if `enable_debug_seq` is set.\n- The **handshaking mechanism** (used for runtime verification of interrupt and debug scenarios) shall be activated only when `require_signature_addr` is true. In that case, the testbench must configure the core, via the compiled program, to write a signature to the specified `signature_addr`. The testbench then polls that address to detect core state changes and perform correctness checks.\n\nAll configuration fields are accessible after initialization. The testbench shall not modify them during simulation; they remain static for the duration of the test. This ensures deterministic and reproducible stimulus generation per test."} {"repo": "lowRISC/ibex", "pr_id": 470, "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)."} {"repo": "lowRISC/ibex", "pr_id": 658, "spec": "# Behavioral Design Specification: ibex_id_stage (Instruction Decode Stage)\n\n## 1. Overview\n\nThe `ibex_id_stage` module implements the instruction decode (ID) stage of the Ibex RISC‑V processor. It receives a fetched instruction from the instruction fetch (IF) stage, decodes it, reads the register file, prepares operands, and forwards control signals to the execution unit (ALU, multiplier/divider), load‑store unit (LSU), CSR block, and the core controller. The stage handles both single‑cycle and multi‑cycle instructions, manages pipeline stalls, and participates in exception, interrupt, and debug handling.\n\nThe ID stage operates in a two‑stage pipeline together with the IF stage. All instructions spend at least one cycle in the ID stage; multi‑cycle instructions stall the ID stage until they complete.\n\n## 2. Interfaces\n\nThe module communicates with the following blocks:\n\n- **Instruction Fetch (IF) stage** – receives a valid instruction, instruction data, compressed instruction indication, fetch errors, and the current program counter (PC). It can kill the IF‑ID pipeline register and signal readiness for a new instruction.\n- **Core Controller** – receives decoded information about illegal instructions, exception causes (ecall, mret, dret, wfi, ebreak), and provides signals for PC updates, exception PCs, interrupt handling, debug entry, and stall indications.\n- **Decoder** – a sub‑block that produces all decoded control signals (ALU operation, operand selection, immediate types, register file addresses, data memory control, CSR access, mult/div control, jump/branch flags).\n- **Register File** – internal to the ID stage; provides two read ports and one write port. Selection of write data comes from the execution stage, LSU result, or CSR read data.\n- **Execution Block (EX)** – receives ALU operands and operation code, multiplier/divider operands and modes, and branch target ALU signals.\n- **Load‑Store Unit (LSU)** – receives data memory request signals (address, write enable, data type, sign extension, write data) and provides responses (load data, address increment requests, last address).\n- **CSR Block** – receives CSR access requests and operation type; supplies CSR read data; provides privilege level and illegal CSR instruction status.\n- **Interrupt/Debug inputs** – interrupt pending, debug requests, single‑step, trigger match, etc.\n- **Write‑back path** – LS unit write data, execution write data, CSR read data are all available for register file write.\n- **Performance counters** – outputs for jump, branch, taken branch, instruction retired events.\n\n## 3. Functional Description\n\n### 3.1 Instruction Decode\n\nThe ID stage decodes an uncompressed 32‑bit instruction (or a compressed instruction expanded to 32 bits by the IF stage). Decoding produces all control signals required for execution, including:\n\n- ALU operation and operand source selection (register a, register b, immediate, current PC, loop‑forwarded address).\n- Immediate values for I, S, B, U, J types and the ZIMM used for CSR immediate.\n- Register file read and write addresses (ports a, b, and write address).\n- Data memory request type (load/store, size, sign extension).\n- Multiplier/divider enable and mode.\n- CSR access and operation.\n- Jump/branch identification.\n\nThe decoding is combinational; all control signals are available in the same cycle the instruction enters the ID stage.\n\n### 3.2 Operand Preparation\n\nOperand A for the ALU can be selected from:\n- Register file port A data.\n- A forwarded address from the LSU (for misaligned access handling).\n- The current PC (PC of the instruction in the ID stage).\n- A zero‑extended immediate (Zimm).\n\nOperand B can be selected from:\n- An immediate value (selected from one of I, S, B, U, J, or a PC increment constant).\n- Register file port B data.\n\nFor the multiplier/divider, operands are taken directly from register file ports A and B.\n\n### 3.3 Register File\n\nThe ID stage contains the processor’s register file. It comprises either 31 or 15 general‑purpose registers (depending on the RV32E configuration), with register x0 statically bound to zero. The register file has two read ports (addresses from decoder) and one write port. Read data is available in the same cycle as the read address is presented.\n\nWrite data comes from one of three sources:\n- Execution unit result (e.g., ALU output).\n- LSU load data.\n- CSR read data.\n\nThe write enable is gated so that:\n- Writes are suppressed when an illegal CSR instruction is detected.\n- Writes are suppressed when the ID stage is not executing an instruction (e.g., stalled).\n- For load, store, and multiply/divide instructions, writes occur only when the data is ready (write‑back stage).\n- Writes are suppressed if a load error is received.\n\nThe register file has no write‑to‑read forwarding; a read of a register being written in the same cycle returns the old value.\n\n### 3.4 ALU Output\n\nThe ALU operation code and the two operands are forwarded to the execution stage. The ALU is used for integer computational instructions, address calculation for loads/stores, branch condition evaluation, branch target computation (if `BranchTargetALU` parameter is disabled), and for multi‑cycle division algorithm support.\n\n### 3.5 Branch Target ALU\n\nWhen the parameter `BranchTargetALU` is enabled, a separate adder in the execution stage computes the branch target in parallel with the main ALU evaluating the branch condition. In this case the ID stage provides a 12‑bit immediate (bits from the B‑type immediate) to the branch target ALU. Otherwise, the handle is not used.\n\n### 3.6 Multi‑Cycle Instruction Handling\n\nSome instructions require more than one cycle in the ID stage. The ID stage contains a small finite‑state machine (FSM) to manage these instructions. The FSM transitions from an **Idle** state to a **Wait** state when the instruction is a multi‑cycle operation, and returns to **Idle** when the operation completes.\n\nThe following instruction classes are multi‑cycle and cause stalling:\n\n- **Load/Store operations** – stall until the LSU returns data (load) or acknowledges completion (store). At least one stall cycle is incurred.\n- **Multiply/Divide operations** – stall until the multiplier/divider block finishes. The number of cycles depends on the multiplier implementation and whether a divide‑by‑zero occurs (see pipeline details).\n- **Branches (taken)** – stall for two cycles without branch target ALU, or one cycle with it. The FSM waits for the branch target computation and the resulting PC request.\n- **Jumps (unconditional)** – stall for at least one cycle to flush the prefetch buffer and issue a new PC request.\n- **Fence.I** – treated as a jump; stalls accordingly.\n\nSingle‑cycle instructions (e.g., integer computational instructions, CSR accesses, branches not taken) complete in the ID stage in one cycle and do not cause stalling.\n\n#### 3.6.1 Stall Generation\n\nThe ID stage generates stall signals for the controller:\n- **Stall LSU**: asserted during load/store operations until `lsu_valid_i` is received.\n- **Stall multiplier/divider**: asserted during multiply/divide operations until the execution stage indicates completion (`ex_valid_i`).\n- **Stall branch**: asserted for taken branches during the second stall cycle.\n- **Stall jump**: asserted during jumps.\n\n#### 3.6.2 Write‑Back Control\n\nFor multi‑cycle instructions, the register file write enable is produced by the FSM when the result is available (`regfile_we_wb`). For single‑cycle instructions, the write enable is directly taken from the decoder (`regfile_we_dec`).\n\n### 3.7 Exception, Interrupt, and Debug Handling\n\nThe ID stage forwards decoded exception‑related signals (illegal instruction, ecall, ebreak, mret, dret, wfi) to the controller. It also receives external status:\n\n- **Illegal instruction** – asserted when the decoder detects an illegal instruction or when an illegal CSR instruction is flagged.\n- **CSR access** – the decoder supplies the CSR operation and address; the ID stage also provides a pipe flush signal used by the controller.\n- **Interrupts** – interrupt pending (including fast interrupts, timer, external, software) and machine status enable bits are received and combined in the controller.\n- **Debug** – debug requests, single‑step, ebreak configuration, trigger match, and privilege‑level specific ebreak behavior are fed to the controller. The ID stage outputs debug mode and debug cause signals.\n\nThe ID stage participates in saving/restoring CSR state for exceptions and debug entry (e.g., CSR save at IF and ID boundaries). It also provides the `mtval` value for exceptions (instruction or address causing the trap).\n\n### 3.8 Misaligned Load/Store Support\n\nWhen the LSU detects a misaligned access, it requests a second address increment (`lsu_addr_incr_req_i`). In response, the ID stage overrides the ALU operand selection to:\n- Operand A: use the forwarded last address from the LSU (`lsu_addr_last_i`).\n- Operand B: use an immediate of 4 (increment).\n- Immediate selection: use the increment immediate.\n\nThis causes the ALU to compute the address for the second part of the misaligned access.\n\n### 3.9 Performance Counters\n\nThe ID stage generates the following performance events:\n- **Jump performed** – active when a jump instruction is executed.\n- **Branch performed** – active for every branch instruction (taken or not taken).\n- **Taken branch performed** – active only for taken branches.\n- **Instruction retired** – active when an instruction completes (including branch instructions, regardless of outcome).\n- **Compressed instruction retired** – active when a retired instruction was compressed.\n\nThese signals are used by the performance counter block to count events.\n\n## 4. Pipeline State Machine (ID/EX/WB FSM)\n\nThe FSM manages instruction progress through the ID stage. It operates in two states:\n\n- **IDLE**: Normal operation. When a new instruction is received (and no fetch error), the machine:\n - For single‑cycle operations: completes the cycle and returns to IDLE.\n - For multi‑cycle operations: enters WAIT_MULTICYCLE and asserts appropriate stall.\n - For taken branches: may directly enter WAIT or return, depending on the FSM logic.\n\n- **WAIT_MULTICYCLE**: The FSM remains here until the multi‑cycle operation finishes. Completion is signaled by:\n - Load/store: when `lsu_valid_i` is asserted.\n - Multiply/divide: when `ex_valid_i` is asserted (since the mul/div block is in the execution stage).\n - Branch/jump: no explicit completion signal; the FSM returns to IDLE based on a combination of `ex_valid_i` and `data_req_dec` (jumps/branches use the ALU for target calculation which is single‑cycle, but the controller manages the PC change; the FSM uses the condition that the operation is no longer a data request and `ex_valid_i` is asserted).\n\nWhen returning to IDLE, the FSM asserts the write‑back enable for loads/stores and multiply/divide results, and activates the instruction retired signal.\n\n## 5. Output Summary\n\nThe ID stage drives the following key outputs (not exhaustive):\n\n- **To IF/Controller**: PC set, PC multiplexer select, exception PC multiplexer select, exception cause, instruction request, kill IF‑ID register, ID ready.\n- **To ALU**: operation code, operand A, operand B.\n- **To Branch Target ALU**: immediate operand.\n- **To Multiplier/Divider**: enable, select, operation, signed mode, operands.\n- **To CSR**: access, operation, save/restore signals, mtval.\n- **To LSU**: request, write enable, data type, sign extension, write data.\n- **To Write‑Back**: register file write data (via the register file’s write port).\n- **Performance counters**: jump, branch, taken branch, instruction retired, compressed retired.\n- **Debug**: debug mode, debug cause, debug CSR save.\n\n## 6. Configuration Parameters\n\nThe module is parameterized by:\n\n- **RV32E**: When set, the register file contains 15 registers instead of 31.\n- **RV32M**: Enables the multiplication/division extension.\n- **BranchTargetALU**: When set, a dedicated adder computes branch targets in parallel with the condition evaluation, reducing branch penalty by one cycle.\n\n## 7. Assertions and Assumptions\n\nThe design assumes that:\n- The input instruction is well‑formed (no X values) when valid and not an error.\n- A branch decision input is stable when a branch instruction is decoded.\n- Only one multi‑cycle operation (load/store, multiply/divide, branch, jump) is active at a time.\n- The duplicate instruction flops (`instr_rdata_i` and `instr_rdata_alu_i`) always match when the instruction is valid.\n- For the latch‑based register file, the clock gating cell ensures the latches capture data correctly."} {"repo": "lowRISC/ibex", "pr_id": 693, "spec": "# Behavioral Design Specification: `ibex_counters`\n\n## Overview\n\nThe `ibex_counters` module implements a bank of programmable up-counters used for performance monitoring in the Ibex RISC‑V processor. Each counter is a 64‑bit accumulator that can be incremented by one per clock cycle, loaded with a 32‑bit value (into either the lower or upper half), or left unchanged. The number of active counters, their bit width, and the maximum number of counters are all parametrizable at synthesis time. The module provides a read‑only view of all counter values as a 64‑bit vector per counter.\n\n## Behavior\n\n### Counter Array\n\n- The module maintains up to `MaxNumCounters` independent 64‑bit counters. However, only the first `NumCounters` counters are physically implemented; all other counter outputs are fixed to zero.\n- Each implemented counter has a configurable width `CounterWidth` (1 to 64 bits). The counter behaves as if it were an unsigned integer of that width. Any overflow beyond the configured width is discarded.\n- The value of each counter is presented on a dedicated 64‑bit output port. For counters with `CounterWidth < 64`, the upper (most significant) bits above the configured width are always zero.\n\n### Counter Update\n\nEvery cycle, each active counter updates its value based on three control signals:\n\n1. **Increment** – When asserted, the counter is incremented by one. Increment is independent of any write operation and only takes effect when no write is performed during the same cycle (see priority below).\n2. **Write** – When asserted, the counter is loaded with an externally supplied 32‑bit value. The write operation can target either:\n - the lower 32 bits of the counter, or\n - the upper 32 bits of the counter.\n \n The selection between lower‑half and upper‑half write is made by a dedicated per‑counter control signal. When writing the upper half, the lower half retains its current value; when writing the lower half, the upper half retains its current value.\n3. **No operation** – If neither increment nor write is asserted, the counter holds its current value.\n\n**Priority**: If a write is asserted for a counter in the same cycle as an increment, the write takes precedence. The increment is ignored for that counter during that cycle.\n\n### Reset\n\n- On reset, every implemented counter is cleared to zero.\n- The reset polarity is active low (`rst_ni`). The reset itself is either asynchronous or synchronous with respect to the clock, depending on the synthesis target (see FPGA considerations).\n\n### Outputs\n\n- All counter values are continuously available on a 64‑bit output bus. The outputs reflect the state of the counters after the most recent clock edge.\n- Unused counter positions (i.e., indices ≥ `NumCounters`) output constant zero.\n\n## Configuration Parameters\n\n| Parameter | Description | Default |\n|-----------------|-----------------------------------------------------------------------------|---------|\n| `MaxNumCounters`| Maximum number of counter slots (the size of the internal array and output bus). | 29 |\n| `NumCounters` | Number of counters that are actually instantiated. Must be ≤ `MaxNumCounters`. | 0 |\n| `CounterWidth` | Bit width of each implemented counter (1 to 64). Overflow bits are truncated. | 32 |\n\n- Setting `NumCounters = 0` disables all counters; all outputs are zero.\n- The performance counters in Ibex (see `doc/performance_counters.rst`) map directly to the first 29 counter slots: `mcycle` and `minstret` occupy slots 0 and 2, while `mhpmcounter3` through `mhpmcounter31` occupy slots 3–31. However, this module is a generic counter bank and does not enforce any specific event mapping or CSR interface.\n\n## FPGA Considerations\n\n- For Xilinx FPGA targets, the module may optionally infer DSP slices (DSP48E1 or similar) to implement the counter logic. This inference is enabled by defining the preprocessor macro `FPGA_XILINX` before synthesis.\n- When DSP inference is active, the counter width is limited to 48 bits for efficient DSP usage. Counters of width 32 or 48 bits can be implemented using a single DSP slice, reducing logic and flip‑flop utilization.\n- The reset behavior changes when DSP slices are used: the counter register becomes synchronous-reset only (i.e., reset is sampled on the rising edge of the clock). Without DSP inference, the counter register uses an asynchronous reset (sensitive to both clock and reset falling edge).\n\n## Functional Summary\n\n| Condition | Counter Behavior |\n|---------------------------------------------------|---------------------------------------------------------|\n| Reset active (low) | Counter becomes zero |\n| Write asserted (any half) | Counter loaded with supplied 32‑bit value at selected half; other half unchanged |\n| Increment asserted, no write | Counter increments by 1 |\n| Neither increment nor write asserted | Counter holds its current value |\n| Write and increment simultaneously asserted | Write takes priority; increment is ignored |\n| Counter index ≥ `NumCounters` | Output is permanently zero |\n| Counter width < 64 | Upper bits (above `CounterWidth-1`) are forced to zero |\n\n## Signal Interface (Behavioral Description)\n\n- **Clock**: Rising‑edge clock drives all counter updates.\n- **Reset**: Active‑low reset clears all counters.\n- **Increment enables**: One bit per counter slot. When high, the corresponding counter is incremented (unless a write occurs).\n- **Write enables**: Two sets of one‑bit enables per counter slot:\n - Lower‑half write enable – when high, the 32‑bit input value is written to bits [31:0] of the counter.\n - Upper‑half write enable – when high, the 32‑bit input value is written to bits [63:32] of the counter.\n- **Write data**: A single 32‑bit value driven to all counter slots. Each counter uses its own write‑enable signals to determine whether to capture this value.\n- **Counter outputs**: A 64‑bit vector per counter slot, representing the current counter value (or zero for unused slots).\n\n> Note: While the RTL uses specific port names, the behavior described here is independent of those names and should be considered the functional contract of the module."} {"repo": "lowRISC/ibex", "pr_id": 640, "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."} {"repo": "lowRISC/ibex", "pr_id": 507, "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."} {"repo": "lowRISC/ibex", "pr_id": 408, "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."} {"repo": "lowRISC/ibex", "pr_id": 416, "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.)"} {"repo": "lowRISC/ibex", "pr_id": 377, "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."} {"repo": "lowRISC/ibex", "pr_id": 613, "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."} {"repo": "lowRISC/ibex", "pr_id": 425, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 401, "spec": "# Behavioral Design Specification: ibex_controller\n\n## Overview\n\nThe controller is the main state machine that governs the overall execution of the RISC-V processor. It manages the transition of the processor through its operational phases: reset, boot, instruction fetch, decode/execute, exception handling, interrupt handling, debug mode entry/exit, and sleep (WFI). The controller interacts with the instruction fetch stage, the decode/execute stage, the load-store unit (LSU), the CSR block, and the debug module to ensure correct sequencing of operations.\n\nThe controller is responsible for:\n\n- Starting the processor from reset and performing the initial boot sequence.\n- Directing the instruction fetch stage to the correct program counter (PC) for normal fetching, jumps, branches, exceptions, and debug entries.\n- Coordinating pipeline stalls, halts, and flushes to ensure architectural correctness.\n- Recognizing exception conditions (illegal instructions, ecall, ebreak, fetch errors, load/store errors) and initiating appropriate trap handling.\n- Recognizing interrupt requests (including NMI, fast interrupts, external, timer, software) and initiating interrupt handling.\n- Supporting entry into debug mode via external request, single-step, or ebreak instruction.\n- Controlling the sleep state entered by the WFI instruction and waking up on interrupts or debug requests.\n- Generating performance monitoring signals for jumps and taken branches.\n\n## Reset and Boot\n\nUpon system reset, the controller must hold the processor in a reset state until the `fetch_enable` signal is asserted. During reset, the instruction fetch stage must be held inactive (no requests). Once `fetch_enable` is asserted, the controller must transition to a boot set state. In the boot set state, the controller must set the program counter to the boot address and force the instruction fetch stage to request an instruction from that address. Immediately after boot set, the controller enters the first fetch state, which fetches the first instruction. After the first fetch completes (the decode stage indicates readiness), the controller transitions to the decode state for normal operation.\n\nThe boot address is provided externally (typically via a CSR or other configuration). The controller ensures that the first instruction fetch starts from that address.\n\n## Normal Instruction Flow\n\nIn normal operation (decode state), the controller monitors the validity of the instruction in the decode stage (`instr_valid`). While an instruction is valid and no special conditions occur, the controller allows the pipeline to proceed:\n\n- If a taken branch or jump is detected, the controller must set the program counter to the target address (via PC_JUMP) and issue a PC set request. The instruction fetch stage will begin fetching from that address on the next cycle. A taken branch also triggers a performance event (taken branch), and a jump triggers a performance event (jump).\n- If no branch or jump occurs, the controller simply allows the current instruction to complete and the next instruction to enter the decode stage.\n\nThe controller must handle pipeline stalls caused by multi-cycle instructions (loads, stores, multiplications, divisions, jumps, branches). When a stall is asserted by the LSU, multiplier/divider, jump, or branch logic, the controller must:\n\n- Halt the instruction fetch stage (prevent new instructions from entering the IF/ID pipeline register).\n- Keep the decode stage valid until the stall is released.\n\nWhen the stall is released, the controller must allow the next instruction to enter the decode stage.\n\nThe controller must also support a \"halt IF\" signal, which stops the fetch stage while keeping the decode stage valid. This is used during certain exception handling sequences where the current instruction remains in the decode stage for analysis.\n\nIf a pipeline flush is needed (e.g., due to an exception, interrupt, or debug entry), the controller must clear the instruction in the IF/ID pipeline register by asserting an invalidate signal (`instr_valid_clear`). The flush signal is distinct from a stall: a flush immediately invalidates the current instruction, whereas a stall preserves it.\n\n## Exceptions\n\nThe controller must detect and handle the following exception sources:\n\n- Illegal instruction (including illegal DRET in non-debug mode and illegal instructions in user mode that require machine mode)\n- Environment call (ECALL) from either machine or user mode\n- Breakpoint (EBREAK) instruction\n- Instruction fetch error (access fault during instruction fetch)\n- Load access fault (error response from LSU during a load)\n- Store access fault (error response from LSU during a store)\n\nThese exceptions are registered and latched on the cycle they are detected, then serviced on the following cycle when the controller enters a flush state.\n\nWhen an exception is recognized, the controller must:\n\n1. Halt the instruction fetch stage (no new instructions fetched).\n2. Flush the pipeline (invalidate the instruction in the decode stage and the IF/ID register).\n3. Set the program counter to the exception handler address. The handler address is selected based on the current privilege mode and whether the core is in debug mode (debug mode uses the debug exception address).\n4. Save necessary CSR state: save the current PC to `mepc` (or `dpc` if in debug mode), record the exception cause in `mcause` (or `dcause`), and optionally set `mtval` with additional information (instruction bits, faulting address, etc.).\n5. After the flush, the controller returns to the decode state, and the first instruction of the exception handler will be fetched.\n\nException priorities follow the RISC-V Privileged Specification (v1.11). Within the flush state, the controller must evaluate which exception has highest priority and set the appropriate cause and CSR values. The order of priority (highest first) is:\n\n- Instruction fetch error\n- Illegal instruction\n- ECALL\n- EBREAK (breakpoint) - note that EBREAK may lead to debug mode entry instead of an exception (see Debug section)\n- Store access fault\n- Load access fault\n\nThe `mtval` CSR must be set with the relevant information: for instruction fetch errors, the PC of the faulting instruction; for illegal instructions, the instruction encoding (compressed or full); for load/store faults, the last accessed address.\n\n## Interrupts\n\nThe controller must support the following interrupt sources:\n\n- Non-maskable interrupt (NMI) – highest priority, enabled even when interrupts are globally disabled, and not visible in `mip` CSR.\n- Fast interrupts (15 local interrupts, IDs 16–30)\n- External interrupt (ID 11)\n- Timer interrupt (ID 7)\n- Software interrupt (ID 3)\n\nAll interrupts except NMI are controlled by the global interrupt enable (`mstatus.MIE`) and per-interrupt enable bits in `mie`. Interrupts are ignored when the core is in debug mode, regardless of MIE.\n\nThe controller must evaluate interrupts in the decode state, but only when the current instruction completes (i.e., no stall and no special instruction pending). Interrupts have lower priority than debug requests but higher than normal instruction execution after the current instruction finishes.\n\nWhen an interrupt is taken, the controller must:\n\n1. Halt the instruction fetch stage.\n2. Flush the pipeline.\n3. Set the program counter to the vector table base address (from `mtvec`) plus four times the interrupt ID (vectored mode). For NMI, the offset is 0x7C (ID 31 * 4).\n4. Save the current PC to `mepc`, save the current interrupt enable state to `mstatus.MPIE`, and clear `mstatus.MIE`.\n5. Record the interrupt cause in `mcause`. The cause encoding follows RISC-V conventions: cause bit 31 is set for interrupts, and the lower bits contain the interrupt ID (with fast interrupts mapped to IDs 16-30).\n6. Enter NMI mode if the interrupt is an NMI. This mode records that an NMI is being serviced; subsequent NMIs are ignored until the NMI handler returns (signalled by MRET). The NMI mode is implemented via a dedicated flip-flop.\n\nAfter the interrupt handling sequence, the controller returns to the decode state and the first instruction of the interrupt handler is fetched.\n\n## Debug\n\nThe controller implements debug support as defined in the RISC-V Debug Specification v0.13. The debug entry can be triggered by:\n\n- Assertion of the external debug request (`debug_req`).\n- Single-step mode (when `debug_single_step` is set) – the core enters debug mode after executing each instruction.\n- Execution of an EBREAK instruction when the respective `ebreakm` or `ebreaku` CSR bit is set to force debug entry.\n\nDebug requests have higher priority than interrupts but lower priority than exceptions (exceptions in progress will complete and then debug entry may occur).\n\nWhen entering debug mode:\n\n1. The controller must save the appropriate PC to `dpc`. If debug entry occurs while a valid instruction is in the decode stage (e.g., after ebreak or single-step), the PC saved is the address of that instruction. If entry occurs in the fetch stage (e.g., from external debug request or single-step before a new instruction), the PC saved is the address of the next instruction to be fetched.\n2. The controller must set `dcsr` with the cause of debug entry (halt request, single-step, or ebreak).\n3. The controller must set the program counter to the debug halt address (`DmHaltAddr`).\n4. The controller must flush the pipeline and inhibit new instruction fetches until the PC is set.\n5. After debug entry, the core is in debug mode. All interrupts (including NMI) are ignored while in debug mode.\n6. Debug mode is exited by executing a DRET instruction (see below).\n\nSpecial handling for EBREAK:\n\n- If the core is already in debug mode and executes an EBREAK, it re-enters debug mode without updating `dpc` or `dcsr`. This allows the debugger to re-enter.\n- If the core is not in debug mode but `ebreakm` or `ebreaku` is set, the EBREAK causes debug entry (with `dpc` and `dcsr` updated) rather than an exception.\n- Otherwise, EBREAK causes a breakpoint exception as described in the Exceptions section.\n\nThe controller must also support single-step: after each instruction execution (when `debug_single_step` is set), the core enters debug mode. The instruction that just completed is the one that was single-stepped; its PC is saved to `dpc`.\n\nThe DRET instruction:\n\n- When executed, the controller must set the program counter to the value stored in `dpc` (using PC_DRET) and exit debug mode (clear the debug mode internal state).\n\n## Sleep (WFI)\n\nWhen a WFI instruction is decoded, the controller must:\n\n1. Halt the instruction fetch stage.\n2. Flush the pipeline.\n3. Transition to a sleep state where the core is not busy (`ctrl_busy` deasserted).\n4. Remain in sleep until a wake-up event occurs.\n\nWake-up events include:\n\n- Any pending interrupt (NMI or regular interrupt that would be taken if interrupts were enabled – i.e., if `mstatus.MIE` is set and individual enable matches).\n- Debug request (external or single-step).\n- The core is already in debug mode or single-step mode (WFI is treated as NOP and the core immediately resumes).\n\nThe `mstatus.TW` bit can cause a trap to machine mode when WFI is executed in user mode. In that case, the WFI instruction is treated as illegal for user mode, and an illegal instruction exception is raised instead of entering sleep.\n\n## CSR Pipeline Flush\n\nSome CSR writes require a pipeline flush to ensure correct behavior of subsequent instructions that depend on the updated CSR state. When the decoder asserts a CSR pipeline flush request, the controller must treat it similarly to a special instruction: halt IF, flush ID in the next cycle, and then continue normal execution. This ensures that any stale pipeline state is cleared.\n\n## Performance Monitoring\n\nThe controller must provide two performance event outputs:\n\n- Jump performed: asserted when a jump instruction (JAL, JALR) is executed and the jump is taken.\n- Taken branch: asserted when a branch instruction is executed and the branch condition is taken.\n\nThese events are generated in the decode state when the respective signals from the decoder indicate a branch or jump. The outputs are valid only for the cycle in which the instruction is executed.\n\n## Pipeline Control Summary\n\nThe controller manages three main pipeline control signals:\n\n- **Stall**: The controller must hold the current instruction in the decode stage while external units (LSU, multiplier/divider, jump, branch) are busy. During a stall, instruction fetch is halted, and the decode stage state is preserved.\n- **Halt IF**: The controller must prevent new instructions from being fetched while allowing the current instruction in decode to remain valid. This is used when the controller needs to inspect the current instruction before deciding the next action (e.g., during exception evaluation).\n- **Flush ID**: The controller must invalidate the instruction in the decode stage and the IF/ID pipeline register. This is used when the controller decides to discard the current instruction (e.g., after an exception or interrupt).\n\nThe decode stage readiness signal indicates when the controller is ready to accept a new instruction: it is asserted when there is no stall and no halt condition. The instruction valid clear signal is asserted when the controller is not stalling or halting, or when a flush is requested.\n\nThe controller outputs a busy signal that indicates the core is actively processing instructions. It is deasserted only during the sleep state (after WFI) when the core is idle and waiting for wake-up.\n\n## State Machine Summary\n\nThe controller implements a finite state machine with the following states (the exact encoding is implementation-specific, but the behavior must follow):\n\n- **Reset**: Waiting for fetch enable.\n- **Boot Set**: Set PC to boot address and request first fetch.\n- **First Fetch**: Waiting for first instruction to be fetched.\n- **Decode**: Normal operation, executing instructions.\n- **Flush**: Handling exceptions, interrupts, debug entry, or special instructions (MRET, DRET, WFI, CSR flush). Performs PC set and CSR save/restore as needed, then returns to decode.\n- **Irq Taken**: Saving state for an interrupt and setting PC to the handler.\n- **Debug Taken IF**: Saving state for debug entry from the fetch stage (external request or single-step).\n- **Debug Taken ID**: Saving state for debug entry from the decode stage (EBREAK re-entry or forced debug entry).\n- **Wait Sleep**: Transition to sleep after WFI.\n- **Sleep**: Idle, waiting for wake-up event.\n\nThe state machine must handle all transitions correctly, ensuring that no architectural state is lost or corrupted. For example, when an exception occurs while a debug request is pending, the exception is handled first, then debug entry may occur on the next cycle after returning to decode.\n\n## Summary of Requirements\n\n- The controller must correctly sequence the core from reset to normal operation.\n- It must properly handle all exceptions and interrupts according to the RISC-V Privileged Specification v1.11 and Debug Specification v0.13.\n- It must support debug mode entry via external request, single-step, and ebreak.\n- It must manage pipeline stalls, halts, and flushes without introducing data hazards or losing state.\n- It must generate correct exception cause and trap values for `mcause`, `mtval`, `mepc`, and corresponding debug CSRs.\n- It must support WFI sleep and wake-up.\n- It must provide performance signals for jumps and taken branches.\n- It must not rely on any specific internal signal names or implementation choices; the described behavior is the required functional contract.\n\nThis specification defines the expected behavior of the controller as seen from the rest of the core and external debugger interfaces."} {"repo": "lowRISC/ibex", "pr_id": 461, "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."} {"repo": "lowRISC/ibex", "pr_id": 375, "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)."} {"repo": "lowRISC/ibex", "pr_id": 316, "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."} {"repo": "lowRISC/ibex", "pr_id": 373, "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`."} {"repo": "lowRISC/ibex", "pr_id": 289, "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."} {"repo": "lowRISC/ibex", "pr_id": 302, "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."} {"repo": "lowRISC/ibex", "pr_id": 295, "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."} {"repo": "lowRISC/ibex", "pr_id": 272, "spec": "# Ibex Controller Behavioral Specification\n\n## Overview\n\nThe Ibex controller is the central FSM that governs the flow of instructions through the Ibex RISC-V core pipeline. It orchestrates the fetch, decode, exception handling, interrupt processing, debug entry, and sleep/wake transitions. The controller reacts to the processor state and external inputs (interrupts, debug requests, load‑store unit errors, etc.) to adjust the pipeline and the instruction fetch address.\n\nThe controller must:\n\n- Manage the core’s reset and boot sequence.\n- Direct the fetch unit (prefetcher) to request instructions from the instruction memory.\n- Coordinate start/stop of instruction decoding based on stalls, exceptions, interrupts, and debug events.\n- Generate control signals to save/restore architectural state (CSRs) on trap handling and return from traps.\n- Generate signals to invalidate pipeline registers when necessary.\n- Provide performance monitoring outputs for taken branches and jumps.\n\n## States and Basic Operation\n\nThe controller implements a finite state machine with the following logical phases:\n\n- **Reset / Boot**\n- **Decode (normal execution)**\n- **First Fetch (after reset or wake)**\n- **Flush (on exceptions, special instructions, or CSR pipeline flushes)**\n- **Interrupt Taken**\n- **Debug Taken (from IF or ID)**\n- **Wait for Sleep / Sleep**\n\nThe controller must transition between these phases according to the rules below.\n\n### Reset and Boot\n\nUpon assertion of the core’s reset signal, the controller must:\n\n- Disable instruction fetch requests.\n- Cause the fetch address to be set to the boot address.\n- Wait for the `fetch_enable` input to be asserted.\n\nWhen `fetch_enable` is asserted, the controller must ensure that the first instruction request is made to the boot address, and then transition to fetching and decoding instructions.\n\n### Normal Instruction Execution – Decode Phase\n\nIn the decode phase, the controller must direct the fetch unit to continue requesting instructions. It must monitor the `instruction_valid` signal from the IF‑ID pipeline register.\n\nWhile an instruction is valid in the ID stage, the controller must consider:\n\n- **Branch or jump signals**: If the instruction is a taken branch or jump, the controller must immediately cause the fetch address to be updated to the branch/jump target (via the `pc_set` and `pc_mux` signals). It must also assert performance counter outputs for the corresponding event.\n\n- **Special instructions and exceptions**: If the instruction is an `ECALL`, `EBREAK`, `MRET`, `DRET`, `WFI`, causes an illegal instruction exception, triggers a pipeline flush through a CSR write, or any instruction fetch error, the controller must transition to the flush phase (see below).\n\n- **Stall conditions**: If the instruction requires multiple cycles (e.g., load/store, multiply/divide) the controller must stall the IF stage until the instruction completes. During this stall, debug and interrupt requests may be held pending but not serviced until the instruction finishes.\n\n- **Debug single-stepping**: When single‑step mode is active (outside debug mode), the controller must halt the IF stage after the current instruction completes and then enter debug mode (unless an exception or special instruction prevents immediate entry).\n\n- **Debug requests and interrupts**: If a debug request or an interrupt (maskable or NMI) is pending and the pipeline is not stalled, the controller must halt the IF/ID stages and transition to the appropriate handling state (debug or interrupt taken) as soon as the current instruction finishes.\n\n> **Note on priority**: While instructions are being decoded, the controller must give the highest priority to executing the current instruction (including its side effects, such as exceptions it might cause). After the instruction is complete, it may service debug requests (higher priority than interrupts) or interrupts.\n\n### First Fetch Phase\n\nImmediately after reset and before the first instruction is fetched, the controller must enter a special “first fetch” phase. During this phase it must:\n\n- Indicate that the core is in the first fetch state.\n- Wait until the IF‑ID stage signals it is ready to accept a new instruction.\n- Upon ready, transition to normal decode.\n\nInterrupts and debug requests must still be serviced during this phase (i.e., if a request is pending, the controller may skip the first fetch and directly enter the interrupt/debug handling state).\n\n### Flush Phase\n\nThe flush phase is entered when an exception, a special instruction (`MRET`, `DRET`, `WFI`), or a CSR‑related pipeline flush is recognized during decode.\n\nDuring the flush phase, the controller must:\n\n- Halt both the IF and ID stages (prevent new instructions from entering the pipeline).\n- For true **exceptions** (including instruction fetch errors, illegal instructions, `ECALL`, `EBREAK`, load/store errors) the controller must:\n - Set the fetch address to the appropriate exception vector (based on whether the core is in debug mode).\n - Save the program counter (from the ID stage) into the `mepc` CSR.\n - Set the exception cause (`mcause`) according to the exception type.\n - Optionally write exception‑specific information to `mtval` (e.g., faulting address for load/store errors, faulting instruction for illegal instructions).\n - For `EBREAK` occurring in debug mode, the controller must not save state again; instead, it must transition to the debug‑taken (ID) phase.\n- For **MRET**: restore `mstatus.MIE` from `mstatus.MPIE`, exit NMI mode if active, and set the fetch address to the value in `mepc`.\n- For **DRET**: exit debug mode and set the fetch address to the value in `dpc`.\n- For **WFI**: transition to the sleep state (see below).\n- For **CSR pipeline flushes** that occur while an interrupt is pending and enabled, the controller may skip the normal flush and instead go directly to interrupt‑taken state.\n- If **debug single‑stepping** is active (outside debug mode), the exception state must be saved in the CSR registers but the fetch address must **not** be updated; instead, the controller must go to debug‑taken (IF) state.\n\n### Interrupt Handling\n\nInterrupts are taken only if:\n\n- The core is **not** in debug mode.\n- The interrupt is pending (for maskable interrupts, the global interrupt enable `MIE` in `mstatus` must be asserted, except for NMI which is always enabled independent of `MIE`).\n- The current instruction has completed (flush phase not needed; if in decode while stalled, the interrupt is delayed until the stall ends).\n\nWhen an interrupt is taken, the controller must:\n\n- Override the fetch address to the interrupt vector (base address from `mtvec` plus 4× interrupt ID).\n- Save the program counter (from the IF stage by default) into `mepc`.\n- Save the interrupt cause (`mcause`) with interrupt bit set.\n- For NMI, set the NMI‑mode flag (so that subsequent NMIs are not nested).\n- After saving state, the controller returns to the decode phase to begin executing the interrupt handler.\n\nInterrupt priority (highest priority first):\n\n1. Non‑maskable interrupt (NMI, ID=31)\n2. Fast interrupts (IDs 30–16)\n3. External interrupt (ID=11)\n4. Software interrupt (ID=3)\n5. Timer interrupt (ID=7)\n\n### Debug Mode\n\nThe core enters debug mode under three conditions:\n\n1. **Debug request** (`debug_req` asserted while not already in debug mode).\n2. **Single‑step** (when the instruction just retired with single‑step enabled).\n3. **EBREAK instruction** when the `ebreakm` parameter is set (or when already in debug mode).\n\nWhile in debug mode:\n\n- All interrupts (including NMI) are ignored.\n- Single‑step behavior is suppressed.\n- Exceptions (other than EBREAK) are handled normally but use the debug exception address (`DmExceptionAddr`) instead of the normal exception vector.\n\n**Entering debug mode from IF (debug request, single‑step):**\n\n- The controller must save the program counter from the IF stage into `dpc`.\n- Set the fetch address to the debug halt address (`DmHaltAddr`).\n- Set the debug cause (`dcsr.cause`) to “halt request” (for `debug_req`) or “single step” (for single‑step).\n- Enter debug mode.\n\n**Entering debug mode from ID (EBREAK handling):**\n\n- For an EBREAK that triggers debug entry (either already in debug mode or with `ebreakm` set), the controller must:\n - If not already in debug mode and `ebreakm` is set: save the program counter from the ID stage into `dpc`, save the debug cause as “EBREAK”, and set the fetch address to the debug halt address.\n - If already in debug mode: do **not** update `dpc` or `dcsr`; simply redirect to the debug halt address.\n- In both cases enter debug mode.\n\n**Exiting debug mode:** The `DRET` instruction must exit debug mode and set the fetch address to the value in `dpc`.\n\n### Sleep State\n\nWhen a `WFI` instruction is executed, the controller must:\n\n- Suspend instruction fetch.\n- Halt both IF and ID stages.\n- Indicate that the core is not busy (e.g., for power management).\n- Wait in the sleep state until any of the following occurs:\n - An interrupt (maskable or NMI) or a debug request is asserted.\n - The core was already in debug mode or single‑step mode (the controller immediately wakes up; `WFI` is treated as a NOP).\n- Upon wake, transition to the first fetch phase to resume instruction execution.\n\n### Stall Control\n\nThe controller must aggregate stall signals from multiple sources:\n\n- Load‑store unit (LSU)\n- Multiplier/divider unit\n- Branch execution unit\n- Jump execution unit\n\nIf any stall source is asserted, the controller must prevent the IF‑ID pipeline register from accepting a new instruction. The ID stage must continue executing the current instruction until the stall is deasserted. The controller must also signal the IF stage that the ID stage is not ready for new instructions.\n\nDuring a stall, the controller must maintain the ability to handle exceptions or debug/interrupt requests only **after** the stall ends. It must not let new instructions advance into the ID stage while the stall is active.\n\n### Pipeline Flush and Invalidations\n\nThe controller must generate signals to:\n\n- Clear the IF‑ID pipeline register when the current instruction is ready to be retired (i.e., when not stalled, or when an exception/special instruction forces a flush).\n- Kill the IF‑ID register on certain conditions (e.g., when a multicycle instruction causes an exception, or when the controller itself decides to flush).\n\n### Performance Monitor Outputs\n\nThe controller must produce two performance counter events:\n\n- **Taken branch**: When a branch taken signal is asserted.\n- **Jump**: When a jump taken signal is asserted (including `JAL`, `JALR`, etc.).\n\nThese outputs must be valid for exactly one cycle per event.\n\n## Behavior Under Reset\n\nWhen reset is active (low):\n\n- All internal state (FSM, debug mode flag, NMI mode flag, LSU error flags) must be cleared.\n- The core must be in the reset / boot phase, waiting for `fetch_enable`.\n- No instruction requests shall be made.\n\n## Timing / Protocol Requirements\n\n- The controller must produce all control signals (e.g., fetch address mux, PC set, CSR save/restore, pipeline stalls) combinatorially from the current state and inputs, meeting the pipeline timing closure requirements.\n- The instruction fetch address and related controls must be updated as soon as a branch, jump, exception, or interrupt is recognized, so that the prefetcher can start fetching from the new address in the next cycle.\n- The controller must not introduce any bubble in the pipeline beyond those required by stalls or hazards; it shall keep the IF stage active whenever possible.\n\n## Summary of Key External Interactions\n\n- **Instruction fetch**: The controller commands the prefetcher to request instructions, sets the fetch target address, and indicates when the ID stage is ready.\n- **Decoder**: The controller uses decoder outputs (type of instruction, illegal/ecall/ebrk etc.) to decide actions.\n- **CSR logic**: The controller initiates saving of `mepc`, `mcause`, `mtval`, debug registers, restores on `MRET`/`DRET`, and updates NMI and debug mode flags.\n- **Load‑store unit**: The controller samples load/store error signals to generate exceptions and records the faulting address.\n- **Interrupt controller**: The controller evaluates interrupt pending signals and the global enable to decide whether to take an interrupt.\n- **Debug module**: The controller responds to debug requests and implements single‑step behavior according to the RISC‑V Debug Specification v0.13.\n\nThe controller must adhere to all the priorities and rules described in the sections above to guarantee correct RISC‑V trap handling and debug support."} {"repo": "lowRISC/ibex", "pr_id": 294, "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."} {"repo": "lowRISC/ibex", "pr_id": 167, "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"} {"repo": "lowRISC/ibex", "pr_id": 54, "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."} {"repo": "lowRISC/ibex", "pr_id": 286, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 222, "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."} {"repo": "lowRISC/ibex", "pr_id": 196, "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."} {"repo": "lowRISC/ibex", "pr_id": 169, "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.*"} {"repo": "lowRISC/ibex", "pr_id": 172, "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."} {"repo": "lowRISC/ibex", "pr_id": 48, "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."} {"repo": "lowRISC/ibex", "pr_id": 176, "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."} {"repo": "lowRISC/ibex", "pr_id": 166, "spec": "# Behavioral Design Specification: ibex_decoder\n\n## Overview\nThe decoder module is the instruction decoder for the Ibex RISC-V core. It takes a 32-bit instruction word from the IF/ID pipeline register and generates all control signals required by subsequent pipeline stages (ALU, load/store unit, register file, CSR unit, multiply/divide unit, branch/jump logic). It also identifies illegal instructions and outputs exception triggers for `ecall`, `ebreak`, `mret`, `dret`, and `wfi`.\n\nThe decoder supports:\n- RV32I base instruction set\n- RV32M extension (multiply/divide) – enabled by a parameter\n- RV32E embedded extension (reduced register file) – enabled by a parameter\n- RISC-V privilege level 1.11 CSRs\n- Compressed instruction extension (via an external illegal compressed instruction indicator)\n\nThe decoder must operate in a single combinatorial block; all outputs are valid within the same cycle as the input instruction.\n\n## Inputs\n- **Instruction word** (32 bits) from the IF/ID pipeline register.\n- **Instruction new** indication: asserts when a new instruction enters the decode stage. Used to differentiate the first (address calculation) and second (result write-back) cycles for jumps (JAL/JALR) and branches.\n- **Illegal compressed instruction**: external flag indicating that a compressed instruction (16‑bit) failed its own decode. When asserted, the decoder must treat the instruction as illegal regardless of its own decoding.\n\n## Outputs\nThe decoder produces the following categories of outputs:\n\n### Register File Control\n- Read addresses for two source registers (rs1, rs2).\n- Write address for destination register (rd).\n- Write enable for the register file.\n- Selection of the data to be written back: from ALU result (EX), from load data (LSU), or from CSR read data.\n\n### Immediate Generation\n- Five sign- or zero-extended immediates for I‑type, S‑type, B‑type, U‑type, and J‑type instructions.\n- A zero-extended immediate from the rs1 field for CSR immediate operations (zimm).\n- Selection muxes for operand A and B of the ALU: these choose between a register value, the current PC, an immediate, or zero.\n\n### ALU Control\n- ALU operation (add, sub, slt, sltu, xor, or, and, sll, srl, sra, eq, ne, lt, ge, ltu, geu).\n- Selection muxes for ALU operand A and operand B.\n\n### Multiply/Divide Control\n- Enable signals for multiply and divide.\n- Operation type (MUL, MULH, DIV, REM, etc.).\n- Signed mode indication (both signed, both unsigned, mixed).\n\n### Load/Store Control\n- Data request enable.\n- Write enable (load vs store).\n- Data size (byte, halfword, word).\n- Sign extension flag for loads.\n- Byte offset within the register for stores.\n\n### Branch/Jump Control\n- Branch in decode indicator (tells the pipeline that a branch is being evaluated).\n- Jump in decode indicator (tells the pipeline that a jump is being calculated).\n- Jump set signal (used to redirect the PC in the first cycle of a jump).\n\n### CSR Control\n- CSR access enable.\n- CSR operation (read, write, set, clear).\n- CSR status flush indicator for accesses to `mstatus`, `dcsr`, `dpc`, `dscratch0`, `dscratch1`.\n\n### Exception / Trap Flags\n- Illegal instruction flag.\n- `ecall` instruction detected.\n- `ebreak` instruction detected.\n- `mret` instruction detected.\n- `dret` instruction detected.\n- `wfi` instruction detected.\n\n## Functional Behavior\n\n### 1. Immediate Extraction\nFor every instruction, the decoder must extract the appropriate immediate fields from the instruction word and sign-extend or zero-extend them to 32 bits. The following immediates are always produced:\n\n- **I-type**: 12‑bit signed immediate (bits 31:20 sign-extended).\n- **S-type**: 12‑bit signed immediate (bits 31:25 and 11:7 concatenated, sign-extended).\n- **B-type**: 13‑bit signed immediate (bits 31, 7, 30:25, 11:8 concatenated with a trailing 0, sign-extended).\n- **U-type**: 20‑bit unsigned immediate (bits 31:12 placed in the upper 20 bits, lower 12 bits zero).\n- **J-type**: 21‑bit signed immediate (bits 19:12, 20, 30:21 concatenated with a trailing 0, sign-extended).\n- **zimm**: 5‑bit zero‑extended immediate from the rs1 field (bits 19:15 zero‑extended).\n\nThe usage of these immediates is selected by the `imm_a_mux_sel` and `imm_b_mux_sel` mux controls. The decoder must route the appropriate immediate to the ALU operand B mux (IMM_B_I, IMM_B_S, IMM_B_B, IMM_B_U, IMM_B_J, IMM_B_INCR_PC) and to the operand A mux (IMM_A_ZERO, IMM_A_Z).\n\n### 2. Register File Access\nThe decoder must extract the three register fields from the instruction:\n\n- Source register 1 address (rs1) from bits 19:15.\n- Source register 2 address (rs2) from bits 24:20.\n- Destination register address (rd) from bits 11:7.\n\nThe register file write enable and write address are determined by the decoded instruction type. For instructions that write to the register file (e.g., ALU ops, loads, LUI, AUIPC, JAL, JALR, CSR reads), write enable must be asserted. For jumps, the write enable is **deasserted in the first cycle** (address calculation) and **asserted in the second cycle** (PC+4 write‑back). The decoder must also enforce that CSR‑related instructions that write a value of zero to the CSR (via immediate or x0) are treated as reads only (CSR write‑enable is suppressed).\n\n### 3. ALU Operations\nThe decoder selects the ALU operation based on the opcode and funct3/funct7 fields.\n\n- **LUI**: ALU adds zero to the U‑type immediate (effectively passes the immediate forward).\n- **AUIPC**: ALU adds U‑type immediate to the current PC.\n- **OP_IMM**: ALU performs the operation specified by funct3 (ADD, SLT, SLTU, XOR, OR, AND). For shifts (SLL, SRL, SRA) the funct7 field must be checked: only shift operations with funct7 == 0x00 (SLL, SRL) or 0x20 (SRA) are legal; otherwise the instruction is illegal.\n- **OP**: For RV32I, the ALU operation is determined by funct7 and funct3 (ADD, SUB, SLT, SLTU, XOR, OR, AND, SLL, SRL, SRA). Any instruction with bit 31 set (indicating an invalid funct7) must be illegal. The ALU operation is also used for branches (EQ, NE, LT, GE, LTU, GEU) and jumps (ADD for target calculation).\n- **Load/Store**: ALU must perform ADD to compute the effective address using either an immediate offset (I‑type for loads, S‑type for stores) or a register offset (for the “reg‑reg” load encoding).\n- **Branches**: ALU first evaluates the branch condition (comparison between rs1 and rs2) and then later calculates the target address (PC + B‑immediate). The ALU operation for condition evaluation is selected based on funct3.\n- **JAL/JALR**: In the first cycle, ALU adds the relevant immediate to PC (JAL) or rs1 (JALR) to compute the jump target. In the second cycle, ALU adds 4 to the current PC to produce the return address.\n\n### 4. Branch and Jump Control\n- **Branches**: When a branch instruction (opcode = OPCODE_BRANCH) is decoded, `branch_in_dec` must be asserted. In the cycle when `instr_new` is asserted, the ALU evaluates the branch condition (comparison of rs1 and rs2). In the following cycle (when `instr_new` is deasserted), the ALU calculates the target address.\n- **JAL**: `jump_in_dec` is asserted. In the first cycle (`instr_new` asserted), the ALU calculates the jump target (PC + J‑imm) and `jump_set` is asserted to redirect the fetch. In the second cycle, the ALU calculates PC+4 for writing back to rd. Register write enable is asserted only in the second cycle.\n- **JALR**: Similar to JAL, but the jump target is computed as (rs1 + I‑imm). The low‑order bit of the calculated target must be forced to 0 (as per the RISC‑V specification). Any funct3 value other than 0x0 is illegal.\n\n### 5. Load and Store Instructions\n- **Store**: The decoder must enable `data_req` and set `data_we` to 1. The ALU computes the store address (rs1 + offset). The offset can be either an S‑type immediate (when bit 14 of the instruction is 0) or a register offset (when bit 14 is 1 – note: this is not supported and must be treated as illegal). The data size is encoded in bits 13:12: 00 → byte (SB), 01 → halfword (SH), 10 → word (SW). Bits 13:12 == 11 is illegal. The decoder must also output the byte offset (`data_reg_offset`) for partial‑width stores (derived from the two least‑significant address bits).\n- **Load**: The decoder must enable `data_req` and set `regfile_we` to 1. The ALU computes the load address (rs1 + offset). By default the offset is an I‑type immediate. A second encoding (funct3 == 111) uses rs2 as the offset (register‑register load). For that encoding, the sign/zero extension and size are determined by a different instruction field (bits 31:25). The size encoding for both standard and reg‑reg loads: 00 → word (LW), 01 → halfword (LH/LHU), 10 → byte (LB/LBU). Sign extension is controlled by the highest order bit of the funct3 field (bit 14 for standard loads, bit 30 for reg‑reg loads); a 0 indicates signed, a 1 indicates unsigned (zero extension). Any load with funct3 == 011 (LD) must be illegal on RV32.\n\n### 6. Multiply/Divide Instructions (RV32M)\nWhen the RV32M parameter is enabled, the decoder must recognize the 8 multiply/divide instructions within the OP opcode (funct7 = 0x01). For each, it must set `mult_en` or `div_en` accordingly and select the appropriate operation and signed mode. When RV32M is disabled, these instructions must cause an illegal instruction exception.\n\n- MUL: signed x signed, lower 32 bits → `MD_OP_MULL`, signed_mode = 00.\n- MULH: signed x signed, upper 32 bits → `MD_OP_MULH`, signed_mode = 11.\n- MULHSU: signed x unsigned, upper 32 bits → `MD_OP_MULH`, signed_mode = 01.\n- MULHU: unsigned x unsigned, upper 32 bits → `MD_OP_MULH`, signed_mode = 00.\n- DIV: signed division → `MD_OP_DIV`, signed_mode = 11.\n- DIVU: unsigned division → `MD_OP_DIV`, signed_mode = 00.\n- REM: signed remainder → `MD_OP_REM`, signed_mode = 11.\n- REMU: unsigned remainder → `MD_OP_REM`, signed_mode = 00.\n\n### 7. CSR Instructions\nInstructions with opcode = SYSTEM and funct3 != 0 are CSR accesses. The decoder must:\n- Enable `csr_access`.\n- Set `regfile_wdata_sel` to RF_WD_CSR so the CSR read value is written to the register file.\n- Use the I‑type immediate for the CSR address (bits 31:20). The CSR value to write comes from either the rs1 register field (if funct3 bit 14 == 0) or from the zero‑extended zimm immediate (if funct3 bit 14 == 1).\n- Set the CSR operation according to funct3[1:0]: 01 → CSR_OP_WRITE, 10 → CSR_OP_SET, 11 → CSR_OP_CLEAR. Any other value (00) is illegal.\n- Override the CSR operation to CSR_OP_READ when the write data is zero: for SET/CLEAR operations, if the source (rs1 or zimm) is zero, then the instruction behaves as a read only (no write to the CSR).\n- Assert `csr_status` (flush pipeline) when the accessed CSR address matches `mstatus` (0x300), `dcsr` (0x7B0), `dpc` (0x7B1), `dscratch0` (0x7B2), or `dscratch1` (0x7B3). This flag indicates that subsequent instructions may be affected by the CSR change.\n\n### 8. System Instructions (non‑CSR)\nFunct3 == 0 of the SYSTEM opcode encodes special instructions. The decoder must detect:\n\n- `ecall` (bits 31:20 = 0x000) → trigger `ecall_insn`.\n- `ebreak` (bits 31:20 = 0x001) → trigger `ebreak_insn`.\n- `mret` (bits 31:20 = 0x302) → trigger `mret_insn`.\n- `dret` (bits 31:20 = 0x7B2) → trigger `dret_insn`.\n- `wfi` (bits 31:20 = 0x105) → trigger `wfi_insn`.\n- All other values → illegal instruction.\n- Additionally, the rs1 and rd fields must both be zero; otherwise the instruction is illegal.\n\n### 9. Other Instructions\n- **Fence instructions** (opcode = MISC‑MEM, funct3 = 000): must be treated as a NOP – all control signals remain at their safe defaults (register file not written, no data request). Any other funct3 value (e.g., fence.i) must be treated as illegal.\n\n### 10. Illegal Instruction Detection\nThe decoder must detect illegal instructions based on:\n- Unrecognized opcode (including reserved opcodes).\n- Invalid funct3, funct7, or register fields within a recognized opcode.\n- Instructions that require unimplemented extensions (e.g., RV64 loads when parameter RV32 is selected, register‑offset stores when not supported).\n- Use of registers x16–x31 when the RV32E parameter is enabled and the register is actually read/written (see Section 12).\n- The external `illegal_c_insn` input, which forces the instruction to be considered illegal regardless of decode.\n\nWhen an illegal instruction is detected, the decoder must:\n- Set `illegal_insn` to 1.\n- Suppress all side effects by forcing:\n - Register file write enable to 0.\n - Data request and data write enable to 0.\n - Multiply/divide enable to 0.\n - Jump in decode and branch in decode to 0.\n - CSR access to 0.\n\nThe illegal instruction status is combined with the RV32E register violation check to produce the final `illegal_insn` output.\n\n### 11. Defaults for Unused or Invalid Scenarios\nThe decoder must provide safe default values for all outputs. Typical defaults are chosen so that an illegal instruction does not cause unintended actions:\n- ALU operation: SLTU (arbitrary, but must not cause writeback to be enabled).\n- Operand mux selections: immediate and zero.\n- Immediate mux selections: I‑type and zero.\n- All enables (regfile, data, mult, div, CSR) are low.\n- All exception flags are low.\n\n### 12. Parameter‑Dependent Behavior\n#### RV32E (Embedded)\nWhen the RV32E parameter is set, only registers x0–x15 are available (5‑bit address space with MSB = 1 illegal). The decoder must check:\n- If rs1 is read (i.e., the ALU operand A mux selects `OP_A_REG_A` and the instruction actually uses a register read) and the rs1 address has bit 4 = 1, the instruction is illegal.\n- If rs2 is read (operand B mux selects `OP_B_REG_B` and a register read is used) and the rs2 address has bit 4 = 1, the instruction is illegal.\n- If the destination register write is enabled and the rd address has bit 4 = 1, the instruction is illegal.\n\nWhen any such violation occurs, the `illegal_reg_rv32e` signal is asserted, which is ORed with the internal `illegal_insn` to produce the final `illegal_insn`. The register file write enable is also suppressed.\n\n#### RV32M (Multiply/Divide)\nWhen the RV32M parameter is set to 0, any multiplication or division instruction (funct7 = 0x01) must be treated as illegal. When RV32M is 1, those instructions are legal and produce the corresponding enable signals.\n\n### 13. Wiring and Outputs\nAll outputs must be driven combinatorially from the input instruction and the `instr_new` flag. The decoder does not contain state; the pipeline handshake is managed externally. The immediate values (imm_*_type_o) and register addresses are always produced, even for illegal instructions, but they may be ignored by downstream logic due to the suppression of enables."} {"repo": "lowRISC/ibex", "pr_id": 157, "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*"} {"repo": "lowRISC/ibex", "pr_id": 113, "spec": "# Behavioral Design Specification for ibex_core (RISC-V Processor Core)\n\n## 1. Introduction\n\nThe `ibex_core` module implements a 32-bit RISC-V processor core that executes the RV32I base instruction set. It supports the optional extensions RV32E (embedded, 16 registers) and RV32M (multiply/divide). The core is designed as a three-stage in-order pipeline (Instruction Fetch, Instruction Decode, Execute) with a separate load-store unit (LSU). It provides separate instruction and data memory interfaces, a simple interrupt controller, and debug support.\n\nThe core shall be fully compliant with the RISC-V Unprivileged Specification (version 2.1 or later) for the implemented instruction set variants, and with the RISC-V Privileged Architecture (version 1.10) for machine-level CSRs and interrupt handling.\n\n## 2. Configuration Parameters\n\nThe core’s behavior is configurable through the following parameters at instantiation time:\n\n- **MHPMCounterNum** (integer, 0…8): Number of hardware performance monitor counters (machine-level). Zero disables all custom counters.\n- **MHPMCounterWidth** (integer, 1…64): Bit width of each performance monitor counter. The counters wrap naturally on overflow.\n- **RV32E** (bit): When set to 1, the core operates in RV32E mode: only the lower 16 registers (x0–x15) are implemented, and all instructions referring to registers x16–x31 cause an illegal instruction exception.\n- **RV32M** (bit): When set to 1, the M extension is enabled (multiply, divide, remainder instructions). When set to 0, those instructions raise an illegal instruction exception.\n- **DmHaltAddr** (32-bit, default 0x1A110800): The program counter to jump to when entering debug mode.\n- **DmExceptionAddr** (32-bit, default 0x1A110808): The program counter to jump to when an exception occurs while the core is already in debug mode.\n\nAll parameters are static; changing them during operation is not permitted.\n\n## 3. Interfaces\n\n### 3.1 Clock and Reset\n- **clk_i**: Main clock input. All synchronous logic is clocked on the rising edge.\n- **rst_ni**: Active-low synchronous reset. When low, the core must be fully reset. The reset must be deasserted synchronously.\n- **test_en_i**: Test enable input. When high, it un-gates all clock gates for test purposes. During normal operation it must be low.\n\n### 3.2 Core Identification and Boot\n- **core_id_i[3:0]**: Static core identifier. It is readable via the `mhartid` CSR.\n- **cluster_id_i[5:0]**: Static cluster identifier. Readable via a custom CSR (not defined in RISC-V spec but provided for system integration).\n- **boot_addr_i[31:0]**: Address from which the core starts fetching instructions after reset.\n\n### 3.3 Instruction Memory Interface\nThe core fetches instructions from a separate instruction memory using a simple handshake protocol. The interface consists of:\n- **Request (output)**: Signal `instr_req_o` must be asserted to start a fetch. It may remain high across multiple cycles until a grant is received.\n- **Address (output)**: `instr_addr_o[31:0]` gives the word-aligned address (the two LSBs are zero). The address may change while the request is active (e.g., after a branch), but the memory must return data corresponding to the address at grant time.\n- **Grant (input)**: The memory asserts `instr_gnt_i` to accept the request. After grant, the core may change the address for the next request.\n- **Data valid (input)**: `instr_rvalid_i` is asserted for exactly one cycle to indicate that `instr_rdata_i` holds valid instruction data.\n- **Data (input)**: `instr_rdata_i[31:0]` contains the 32-bit instruction or the upper/lower half of a compressed instruction pair.\n\nThe protocol is request-grant with a separate response. The core must handle wait states: the grant may come any number of cycles after request, and the response may come any number of cycles after grant.\n\n### 3.4 Data Memory Interface (Load-Store Unit)\nThe LSU accesses data memory with a request-grant‑response protocol, similar to the instruction interface but with additional control signals:\n- **Request (output)**: `data_req_o` asserted to start a data transaction.\n- **Write enable (output)**: `data_we_o` high for stores, low for loads.\n- **Byte enables (output)**: `data_be_o[3:0]` specifies which bytes are accessed. For a word load, all four bytes are enabled; for halfword, two bytes; for byte, one byte. During stores, only the enabled bytes are written.\n- **Address (output)**: `data_addr_o[31:0]` – typically word-aligned, but may be misaligned (handled internally by the LSU by performing multiple aligned accesses).\n- **Write data (output)**: `data_wdata_o[31:0]` – data to be written during a store, aligned to byte lanes according to `data_be_o`.\n- **Grant (input)**: `data_gnt_i` – the memory accepts the request. After grant, the core may change all outputs for the next request.\n- **Response valid (input)**: `data_rvalid_i` – asserted for one cycle when `data_rdata_i` and `data_err_i` are valid.\n- **Read data (input)**: `data_rdata_i[31:0]` – data returned for loads.\n- **Error (input)**: `data_err_i` – asserted with response to signal an error. The core must take an exception for such requests.\n\nThe LSU must handle misaligned accesses transparently. For a load or store to a misaligned address, the core performs two or more aligned transactions, but from the outside no extra signals are needed. The response (including error) for the original access is only given when all sub‑transactions complete.\n\n### 3.5 Interrupt Interface\nThe core supports one interrupt input:\n- **irq_i**: Level-sensitive interrupt request. Must be held high until the core acknowledges it.\n- **irq_id_i[4:0]**: Interrupt identifier (interrupt cause value). Used to set the `mcause` CSR when the interrupt is taken.\n- **irq_ack_o**: Acknowledgment signal. The core asserts this for one cycle when it takes the interrupt (starts the trap handler).\n- **irq_id_o[4:0]**: Interrupt identifier output at the time of acknowledgment, reflecting the interrupt that was taken.\n\nThe core must take an interrupt only when the machine-level interrupt enable (`MIE`) bit in `mstatus` is set. The interrupt causes the core to save PC to `mepc`, set `mcause` to the value of `irq_id_i`, and jump to `mtvec`. After the interrupt handler completes with an `MRET` instruction, execution resumes at the address saved in `mepc`.\n\n### 3.6 Debug Interface\n- **debug_req_i**: Debug request input. When asserted, the core will enter debug mode after completing the current instruction (or immediately if halted). The core must set the appropriate debug cause and jump to `DmHaltAddr`. While in debug mode, the core executes a separate code sequence. Exceptions in debug mode jump to `DmExceptionAddr`. The debug mode behavior follows the RISC-V Debug Specification (version 0.13).\n\n### 3.7 Core Control\n- **fetch_enable_i**: Core enable. When low, the core must stop fetching new instructions and eventually become idle. The core must not execute any new instructions. When high, the core resumes normal operation.\n\n## 4. Functional Requirements\n\n### 4.1 Reset Behavior\nUpon deassertion of `rst_ni`, the core must:\n- Reset all architectural registers (including x0 which always reads 0).\n- Initialize program counter to the value of `boot_addr_i`.\n- Set `mstatus` with `MIE` cleared (interrupts disabled).\n- Clear all CSRs, including `mepc`, `mcause`, `mtvec`, `mtval`, and performance counters.\n- Set `mhartid` to `core_id_i`.\n- Begin fetching instructions from `boot_addr_i` only when `fetch_enable_i` is high.\n\n### 4.2 Instruction Fetch (IF) Behavior\nThe IF stage must:\n- Continuously fetch instructions from the instruction memory as long as `fetch_enable_i` is high and the pipeline is not stalled.\n- Support compressed instructions (RVC) by internally handling halfword-aligned addresses. The external interface always uses word-aligned addresses; the core internally selects the correct halfword.\n- Detect illegal compressed instructions and forward them as illegal instructions to the ID stage.\n- Accept branch and jump target addresses from the execute stage and update the program counter accordingly.\n- Support single-step and debug entry via the IF stage's interaction with the CSR block.\n\n### 4.3 Instruction Decode (ID) Behavior\nThe ID stage must:\n- Decode all supported RISC‑V instructions.\n- Read the register file (either 16 or 32 registers depending on RV32E).\n- Detect illegal instructions (including unsupported opcodes, illegal CSR accesses, and RV32E register references to registers x16–x31). When an illegal instruction is detected, the core must raise an illegal instruction exception (cause 2) and not commit any side effects.\n- Generate control signals for the execute stage and LSU.\n- Handle pipeline stalls caused by data hazards (load-use) or structural hazards (busy LSU, busy IF).\n- Detect interrupt requests, debug requests, and exception conditions (from IF, ID, or LSU) and initiate the appropriate trap or debug entry sequence.\n\n### 4.4 Execute Stage Behavior\nThe execute stage must:\n- Perform arithmetic and logical operations (ALU) as required by the instruction.\n- Execute multiply, divide, and remainder operations if the RV32M parameter is enabled, else these instructions are illegal.\n- Compute branch and jump target addresses.\n- Generate the branch decision signal (taken/not taken) forwarded back to ID for PC update.\n- Forward arithmetic results to the register file write port (bypass for register writes) and to the LSU for store data and address computation.\n\n### 4.5 Load-Store Unit (LSU) Behavior\nThe LSU must:\n- Perform load and store operations of size byte, halfword, or word.\n- Handle misaligned accesses by performing multiple aligned bus transactions, keeping the entire access atomic from the programmer’s perspective.\n- Provide the loaded data for register write-back after the response is received.\n- Report memory errors to the ID stage, which then raises an appropriate exception (load access fault or store access fault).\n- Indicate busy status so that the pipeline stalls until the LSU is free.\n\n### 4.6 Exception and Interrupt Handling\nThe core must support the following synchronous exceptions and asynchronous interrupts:\n\n- **Instruction access fault** (cause 1): raised by the instruction memory interface if the fetch fails (not shown on the interface, but can be triggered by the system).\n- **Illegal instruction** (cause 2): as described above.\n- **Load address misaligned** (cause 4): generated by the LSU when a load address is misaligned and cannot be handled (only if the system requires alignment; by default the LSU handles misalignment, so this exception should not occur unless the system declares load misaligned as an error).\n- **Load access fault** (cause 5): raised when the data memory returns an error for a load.\n- **Store address misaligned** (cause 6): similar to load misaligned.\n- **Store access fault** (cause 7): raised when the data memory returns an error for a store.\n- **Environment call from M-mode** (cause 11): generated by the `ECALL` instruction.\n- **Breakpoint** (cause 3): generated by `EBREAK` instruction (unless in debug mode, where it is handled by the debug module).\n\n- **Machine external interrupt** (cause 0x80000000 | irq_id): taken when `irq_i` is high and `mstatus.MIE` is set.\n\nFor any trap (exception or interrupt), the core must:\n1. Set `mepc` to the PC of the instruction that caused the trap (or for interrupts, the PC of the next instruction to resume).\n2. Set `mcause` to the appropriate cause value.\n3. Optionally set `mtval` to an exception-specific value (e.g., address for access faults, zero otherwise).\n4. Disable interrupts by clearing `mstatus.MIE`.\n5. Set the PC to `mtvec` (address of trap handler).\n\nReturn from handler is done via `MRET`, which restores `mstatus.MIE` and PC from `mepc`.\n\n### 4.7 Debug Mode Behavior\nWhen `debug_req_i` is asserted, the core shall enter debug mode after the current instruction completes. In debug mode:\n- The core jumps to `DmHaltAddr`.\n- Additional debug CSRs (like `dcsr`, `dpc`) are used to store the return address and control debug behavior.\n- The core can single-step (`dscsr.singlestep` set) or respond to `EBREAK` depending on `dcsr` configuration.\n- An exception in debug mode causes a jump to `DmExceptionAddr` (instead of `mtvec`).\n- The core exits debug mode upon executing a `DRET` instruction.\n\n### 4.8 Performance Counters\nIf `MHPMCounterNum > 0`, the core includes that many 64‑bit (or `MHPMCounterWidth`‑bit) counters that count events such as:\n- Retired instructions\n- Instruction cache misses\n- Jumps (unconditional branches)\n- Branches (conditional)\n- Taken branches\n- Loads\n- Stores\n\nThese counters are accessible via the `mhpmcounter` CSRs and can be configured to count arbitrary events via `mhpmevent` CSRs (if implemented). The counters saturate or wrap at their maximum width (the implementer may choose). The core must increment the counters on the appropriate cycle when the event occurs.\n\n### 4.9 Core Busy and Clock Gating\nThe core shall automatically gate its main clock (except the debug unit) when it is idle. Idle means:\n- No instruction fetch pending or in progress.\n- No instructions in the pipeline.\n- No outstanding LSU transaction.\n- No interrupt or debug request waiting.\n\nWhen the core is idle, the clock enable output (internal) is deasserted to the clock gate. The core must wake up on any interrupt, debug request, or when `fetch_enable_i` is asserted after being low.\n\n### 4.10 RISC-V Formal Interface (Optional)\nWhen compiled with `RISCV_FORMAL` define, the core shall provide the `rvfi_*` output signals conforming to the RISC-V Formal Interface (RVFI) specification. These outputs capture the retirement of each instruction, including PC, instruction word, register reads and writes, memory access details, and trap information. The formal interface must be cycle-accurate for verification.\n\n## 5. Constraints and Assumptions\n\n- The instruction and data memory systems must be coherent (i.e., a store to a location that is also used for instruction fetch is not automatically visible; the core does not implement hardware coherence or store-to-load forwarding for instructions).\n- The interrupt input `irq_i` is level‑sensitive; after acknowledgment the system must deassert it; failure to do so may cause repeated interrupts.\n- The debug request `debug_req_i` should remain asserted until the core acknowledges it via the debug logic (no external handshake).\n- The `test_en_i` shall only be used for ATPG; during functional operation it must be low.\n- The reset signal `rst_ni` must be synchronous to the clock.\n\n## 6. Summary of Supported Instructions\n\n- **RV32I**: All base integer instructions (including `FENCE`, `ECALL`, `EBREAK`, `CSRRW`, etc.).\n- **RV32C** (implicit if not disabled): All compressed instructions as per the C extension, automatically detected and decoded. The core supports both aligned and halfword-aligned instructions.\n- **RV32M** (optional): `MUL`, `MULH`, `MULHSU`, `MULHU`, `DIV`, `DIVU`, `REM`, `REMU`.\n- **RV32E** (optional): Restricts register file to 16 registers; otherwise instruction behavior is identical to RV32I.\n\n## 7. Reference\n\nThis specification is based on the lowRISC/ibex RTL source (version as provided) and the official documentation for integration, instruction fetch, and load-store unit. The core’s behavior is intended to comply with the RISC-V Privileged and Unprivileged Specifications as of version 1.10 and 2.1, respectively."} {"repo": "lowRISC/ibex", "pr_id": 40, "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."} {"repo": "lowRISC/ibex", "pr_id": 131, "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."}