// Copyright (c) 2025 Eclipse Foundation
// Copyright lowRISC contributors.
// Copyright 2017 ETH Zurich and University of Bologna, see also CREDITS.md.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
/**
 * Package with constants used by CVE2
 */
package cve2_pkg;
  ////////////////
  // IO Structs //
  ////////////////
  typedef struct packed {
    logic [31:0] current_pc;
    logic [31:0] next_pc;
    logic [31:0] last_data_addr;
    logic [31:0] exception_addr;
  } crash_dump_t;
  typedef struct packed {
    logic        dummy_instr_id;
    logic [4:0]  raddr_a;
    logic [4:0]  waddr_a;
    logic        we_a;
    logic [4:0]  raddr_b;
  } core2rf_t;
  /////////////////////
  // Parameter Enums //
  /////////////////////
  typedef enum integer {
    RV32MNone        = 0,
    RV32MSlow        = 1,
    RV32MFast        = 2,
    RV32MSingleCycle = 3
  } rv32m_e;
  typedef enum integer {
    RV32BNone       = 0,
    RV32BBalanced   = 1,
    RV32BOTEarlGrey = 2,
    RV32BFull       = 3
  } rv32b_e;
  /////////////
  // Opcodes //
  /////////////
  typedef enum logic [6:0] {
    OPCODE_LOAD     = 7'h03,
    OPCODE_MISC_MEM = 7'h0f,
    OPCODE_OP_IMM   = 7'h13,
    OPCODE_AUIPC    = 7'h17,
    OPCODE_STORE    = 7'h23,
    OPCODE_OP       = 7'h33,
    OPCODE_LUI      = 7'h37,
    OPCODE_BRANCH   = 7'h63,
    OPCODE_JALR     = 7'h67,
    OPCODE_JAL      = 7'h6f,
    OPCODE_SYSTEM   = 7'h73
  } opcode_e;
  ////////////////////
  // ALU operations //
  ////////////////////
  typedef enum logic [6:0] {
    // Arithmetics
    ALU_ADD,
    ALU_SUB,
    // Logics
    ALU_XOR,
    ALU_OR,
    ALU_AND,
    // RV32B
    ALU_XNOR,
    ALU_ORN,
    ALU_ANDN,
    // Shifts
    ALU_SRA,
    ALU_SRL,
    ALU_SLL,
    // RV32B
    ALU_SRO,
    ALU_SLO,
    ALU_ROR,
    ALU_ROL,
    ALU_GREV,
    ALU_GORC,
    ALU_SHFL,
    ALU_UNSHFL,
    ALU_XPERM_N,
    ALU_XPERM_B,
    ALU_XPERM_H,
    // Address Calculations
    // RV32B
    ALU_SH1ADD,
    ALU_SH2ADD,
    ALU_SH3ADD,
    // Comparisons
    ALU_LT,
    ALU_LTU,
    ALU_GE,
    ALU_GEU,
    ALU_EQ,
    ALU_NE,
    // RV32B
    ALU_MIN,
    ALU_MINU,
    ALU_MAX,
    ALU_MAXU,
    // Pack
    // RV32B
    ALU_PACK,
    ALU_PACKU,
    ALU_PACKH,
    // Sign-Extend
    // RV32B
    ALU_SEXTB,
    ALU_SEXTH,
    // Bitcounting
    // RV32B
    ALU_CLZ,
    ALU_CTZ,
    ALU_CPOP,
    // Set lower than
    ALU_SLT,
    ALU_SLTU,
    // Ternary Bitmanip Operations
    // RV32B
    ALU_CMOV,
    ALU_CMIX,
    ALU_FSL,
    ALU_FSR,
    // Single-Bit Operations
    // RV32B
    ALU_BSET,
    ALU_BCLR,
    ALU_BINV,
    ALU_BEXT,
    // Bit Compress / Decompress
    // RV32B
    ALU_BCOMPRESS,
    ALU_BDECOMPRESS,
    // Bit Field Place
    // RV32B
    ALU_BFP,
    // Carry-less Multiply
    // RV32B
    ALU_CLMUL,
    ALU_CLMULR,
    ALU_CLMULH,
    // Cyclic Redundancy Check
    ALU_CRC32_B,
    ALU_CRC32C_B,
    ALU_CRC32_H,
    ALU_CRC32C_H,
    ALU_CRC32_W,
    ALU_CRC32C_W
  } alu_op_e;
  typedef enum logic [1:0] {
    // Multiplier/divider
    MD_OP_MULL,
    MD_OP_MULH,
    MD_OP_DIV,
    MD_OP_REM
  } md_op_e;
  //////////////////////////////////
  // Control and status registers //
  //////////////////////////////////
  // CSR operations
  typedef enum logic [1:0] {
    CSR_OP_READ,
    CSR_OP_WRITE,
    CSR_OP_SET,
    CSR_OP_CLEAR
  } csr_op_e;
  // Privileged mode
  typedef enum logic[1:0] {
    PRIV_LVL_M = 2'b11,
    PRIV_LVL_H = 2'b10,
    PRIV_LVL_S = 2'b01,
    PRIV_LVL_U = 2'b00
  } priv_lvl_e;
  // Constants for the dcsr.xdebugver fields
  typedef enum logic[3:0] {
    XDEBUGVER_NO     = 4'd0, // no external debug support
    XDEBUGVER_STD    = 4'd4, // external debug according to RISC-V debug spec
    XDEBUGVER_NONSTD = 4'd15 // debug not conforming to RISC-V debug spec
  } x_debug_ver_e;
  //////////////
  // WB stage //
  //////////////
  // Type of instruction present in writeback stage
  typedef enum logic[1:0] {
    WB_INSTR_LOAD,  // Instruction is awaiting load data
    WB_INSTR_STORE, // Instruction is awaiting store response
    WB_INSTR_OTHER  // Instruction doesn't fit into above categories
  } wb_instr_type_e;
  //////////////
  // ID stage //
  //////////////
  // Operand a selection
  typedef enum logic[1:0] {
    OP_A_REG_A,
    OP_A_FWD,
    OP_A_CURRPC,
    OP_A_IMM
  } op_a_sel_e;
  // Immediate a selection
  typedef enum logic {
    IMM_A_Z,
    IMM_A_ZERO
  } imm_a_sel_e;
  // Operand b selection
  typedef enum logic {
    OP_B_REG_B,
    OP_B_IMM
  } op_b_sel_e;
  // Immediate b selection
  typedef enum logic [2:0] {
    IMM_B_I,
    IMM_B_S,
    IMM_B_B,
    IMM_B_U,
    IMM_B_J,
    IMM_B_INCR_PC,
    IMM_B_INCR_ADDR
  } imm_b_sel_e;
  // Regfile write data selection
  typedef enum {
    RF_WD_EX,
    RF_WD_CSR,
    RF_WD_COPROC // Only used when XInterface = 1
  } rf_wd_sel_e;
  //////////////
  // IF stage //
  //////////////
  // PC mux selection
  typedef enum logic [2:0] {
    PC_BOOT,
    PC_JUMP,
    PC_EXC,
    PC_ERET,
    PC_DRET,
    PC_BP
  } pc_sel_e;
  // Exception PC mux selection
  typedef enum logic [1:0] {
    EXC_PC_EXC,
    EXC_PC_IRQ,
    EXC_PC_DBD,
    EXC_PC_DBG_EXC // Exception while in debug mode
  } exc_pc_sel_e;
  // Interrupt requests
  typedef struct packed {
    logic        irq_software;
    logic        irq_timer;
    logic        irq_external;
    logic [15:0] irq_fast; // 16 fast interrupts
  } irqs_t;
  // Exception cause
  typedef enum logic [6:0] {
    EXC_CAUSE_IRQ_SOFTWARE_M     = {1'b1, 6'd03},
    EXC_CAUSE_IRQ_TIMER_M        = {1'b1, 6'd07},
    EXC_CAUSE_IRQ_EXTERNAL_M     = {1'b1, 6'd11},
    // EXC_CAUSE_IRQ_FAST_0      = {1'b1, 6'd16},
    // EXC_CAUSE_IRQ_FAST_15     = {1'b1, 6'd31},
    EXC_CAUSE_IRQ_NM             = {1'b1, 6'd32},
    EXC_CAUSE_INSN_ADDR_MISA     = {1'b0, 6'd00},
    EXC_CAUSE_INSTR_ACCESS_FAULT = {1'b0, 6'd01},
    EXC_CAUSE_ILLEGAL_INSN       = {1'b0, 6'd02},
    EXC_CAUSE_BREAKPOINT         = {1'b0, 6'd03},
    EXC_CAUSE_LOAD_ACCESS_FAULT  = {1'b0, 6'd05},
    EXC_CAUSE_STORE_ACCESS_FAULT = {1'b0, 6'd07},
    EXC_CAUSE_ECALL_UMODE        = {1'b0, 6'd08},
    EXC_CAUSE_ECALL_MMODE        = {1'b0, 6'd11}
  } exc_cause_e;
  // Debug cause
  typedef enum logic [2:0] {
    DBG_CAUSE_NONE    = 3'h0,
    DBG_CAUSE_EBREAK  = 3'h1,
    DBG_CAUSE_TRIGGER = 3'h2,
    DBG_CAUSE_HALTREQ = 3'h3,
    DBG_CAUSE_STEP    = 3'h4
  } dbg_cause_e;
  // PMP constants
  parameter int unsigned PMP_MAX_REGIONS      = 16;
  parameter int unsigned PMP_CFG_W            = 8;
  // PMP acces type
  parameter int unsigned PMP_I  = 0;
  parameter int unsigned PMP_I2 = 1;
  parameter int unsigned PMP_D  = 2;
  typedef enum logic [1:0] {
    PMP_ACC_EXEC    = 2'b00,
    PMP_ACC_WRITE   = 2'b01,
    PMP_ACC_READ    = 2'b10
  } pmp_req_e;
  // PMP cfg structures
  typedef enum logic [1:0] {
    PMP_MODE_OFF   = 2'b00,
    PMP_MODE_TOR   = 2'b01,
    PMP_MODE_NA4   = 2'b10,
    PMP_MODE_NAPOT = 2'b11
  } pmp_cfg_mode_e;
  typedef struct packed {
    logic          lock;
    pmp_cfg_mode_e mode;
    logic          exec;
    logic          write;
    logic          read;
  } pmp_cfg_t;
  // Machine Security Configuration (ePMP)
  typedef struct packed {
    logic rlb;  // Rule Locking Bypass
    logic mmwp; // Machine Mode Whitelist Policy
    logic mml;  // Machine Mode Lockdown
  } pmp_mseccfg_t;
  // CSRs
  typedef enum logic[11:0] {
    // Machine information
    CSR_MVENDORID  = 12'hF11,
    CSR_MARCHID    = 12'hF12,
    CSR_MIMPID     = 12'hF13,
    CSR_MHARTID    = 12'hF14,
    CSR_MCONFIGPTR = 12'hF15,
    // Machine trap setup
    CSR_MSTATUS   = 12'h300,
    CSR_MISA      = 12'h301,
    CSR_MIE       = 12'h304,
    CSR_MTVEC     = 12'h305,
    CSR_MCOUNTEREN= 12'h306,
    CSR_MSTATUSH  = 12'h310,
    CSR_MENVCFG   = 12'h30A,
    CSR_MENVCFGH  = 12'h31A,
    // Machine trap handling
    CSR_MSCRATCH  = 12'h340,
    CSR_MEPC      = 12'h341,
    CSR_MCAUSE    = 12'h342,
    CSR_MTVAL     = 12'h343,
    CSR_MIP       = 12'h344,
    // Physical memory protection
    CSR_PMPCFG0   = 12'h3A0,
    CSR_PMPCFG1   = 12'h3A1,
    CSR_PMPCFG2   = 12'h3A2,
    CSR_PMPCFG3   = 12'h3A3,
    CSR_PMPADDR0  = 12'h3B0,
    CSR_PMPADDR1  = 12'h3B1,
    CSR_PMPADDR2  = 12'h3B2,
    CSR_PMPADDR3  = 12'h3B3,
    CSR_PMPADDR4  = 12'h3B4,
    CSR_PMPADDR5  = 12'h3B5,
    CSR_PMPADDR6  = 12'h3B6,
    CSR_PMPADDR7  = 12'h3B7,
    CSR_PMPADDR8  = 12'h3B8,
    CSR_PMPADDR9  = 12'h3B9,
    CSR_PMPADDR10 = 12'h3BA,
    CSR_PMPADDR11 = 12'h3BB,
    CSR_PMPADDR12 = 12'h3BC,
    CSR_PMPADDR13 = 12'h3BD,
    CSR_PMPADDR14 = 12'h3BE,
    CSR_PMPADDR15 = 12'h3BF,
    // ePMP control
    CSR_MSECCFG   = 12'h747,
    CSR_MSECCFGH  = 12'h757,
    // Debug trigger
    CSR_TSELECT   = 12'h7A0,
    CSR_TDATA1    = 12'h7A1,
    CSR_TDATA2    = 12'h7A2,
    CSR_TDATA3    = 12'h7A3,
    CSR_MCONTEXT  = 12'h7A8,
    CSR_SCONTEXT  = 12'h7AA,
    // Debug/trace
    CSR_DCSR      = 12'h7b0,
    CSR_DPC       = 12'h7b1,
    // Debug
    CSR_DSCRATCH0 = 12'h7b2, // optional
    CSR_DSCRATCH1 = 12'h7b3, // optional
    // Machine Counter/Timers
    CSR_MCOUNTINHIBIT  = 12'h320,
    CSR_MHPMEVENT3     = 12'h323,
    CSR_MHPMEVENT4     = 12'h324,
    CSR_MHPMEVENT5     = 12'h325,
    CSR_MHPMEVENT6     = 12'h326,
    CSR_MHPMEVENT7     = 12'h327,
    CSR_MHPMEVENT8     = 12'h328,
    CSR_MHPMEVENT9     = 12'h329,
    CSR_MHPMEVENT10    = 12'h32A,
    CSR_MHPMEVENT11    = 12'h32B,
    CSR_MHPMEVENT12    = 12'h32C,
    CSR_MHPMEVENT13    = 12'h32D,
    CSR_MHPMEVENT14    = 12'h32E,
    CSR_MHPMEVENT15    = 12'h32F,
    CSR_MHPMEVENT16    = 12'h330,
    CSR_MHPMEVENT17    = 12'h331,
    CSR_MHPMEVENT18    = 12'h332,
    CSR_MHPMEVENT19    = 12'h333,
    CSR_MHPMEVENT20    = 12'h334,
    CSR_MHPMEVENT21    = 12'h335,
    CSR_MHPMEVENT22    = 12'h336,
    CSR_MHPMEVENT23    = 12'h337,
    CSR_MHPMEVENT24    = 12'h338,
    CSR_MHPMEVENT25    = 12'h339,
    CSR_MHPMEVENT26    = 12'h33A,
    CSR_MHPMEVENT27    = 12'h33B,
    CSR_MHPMEVENT28    = 12'h33C,
    CSR_MHPMEVENT29    = 12'h33D,
    CSR_MHPMEVENT30    = 12'h33E,
    CSR_MHPMEVENT31    = 12'h33F,
    CSR_MCYCLE         = 12'hB00,
    CSR_MINSTRET       = 12'hB02,
    CSR_MHPMCOUNTER3   = 12'hB03,
    CSR_MHPMCOUNTER4   = 12'hB04,
    CSR_MHPMCOUNTER5   = 12'hB05,
    CSR_MHPMCOUNTER6   = 12'hB06,
    CSR_MHPMCOUNTER7   = 12'hB07,
    CSR_MHPMCOUNTER8   = 12'hB08,
    CSR_MHPMCOUNTER9   = 12'hB09,
    CSR_MHPMCOUNTER10  = 12'hB0A,
    CSR_MHPMCOUNTER11  = 12'hB0B,
    CSR_MHPMCOUNTER12  = 12'hB0C,
    CSR_MHPMCOUNTER13  = 12'hB0D,
    CSR_MHPMCOUNTER14  = 12'hB0E,
    CSR_MHPMCOUNTER15  = 12'hB0F,
    CSR_MHPMCOUNTER16  = 12'hB10,
    CSR_MHPMCOUNTER17  = 12'hB11,
    CSR_MHPMCOUNTER18  = 12'hB12,
    CSR_MHPMCOUNTER19  = 12'hB13,
    CSR_MHPMCOUNTER20  = 12'hB14,
    CSR_MHPMCOUNTER21  = 12'hB15,
    CSR_MHPMCOUNTER22  = 12'hB16,
    CSR_MHPMCOUNTER23  = 12'hB17,
    CSR_MHPMCOUNTER24  = 12'hB18,
    CSR_MHPMCOUNTER25  = 12'hB19,
    CSR_MHPMCOUNTER26  = 12'hB1A,
    CSR_MHPMCOUNTER27  = 12'hB1B,
    CSR_MHPMCOUNTER28  = 12'hB1C,
    CSR_MHPMCOUNTER29  = 12'hB1D,
    CSR_MHPMCOUNTER30  = 12'hB1E,
    CSR_MHPMCOUNTER31  = 12'hB1F,
    CSR_MCYCLEH        = 12'hB80,
    CSR_MINSTRETH      = 12'hB82,
    CSR_MHPMCOUNTER3H  = 12'hB83,
    CSR_MHPMCOUNTER4H  = 12'hB84,
    CSR_MHPMCOUNTER5H  = 12'hB85,
    CSR_MHPMCOUNTER6H  = 12'hB86,
    CSR_MHPMCOUNTER7H  = 12'hB87,
    CSR_MHPMCOUNTER8H  = 12'hB88,
    CSR_MHPMCOUNTER9H  = 12'hB89,
    CSR_MHPMCOUNTER10H = 12'hB8A,
    CSR_MHPMCOUNTER11H = 12'hB8B,
    CSR_MHPMCOUNTER12H = 12'hB8C,
    CSR_MHPMCOUNTER13H = 12'hB8D,
    CSR_MHPMCOUNTER14H = 12'hB8E,
    CSR_MHPMCOUNTER15H = 12'hB8F,
    CSR_MHPMCOUNTER16H = 12'hB90,
    CSR_MHPMCOUNTER17H = 12'hB91,
    CSR_MHPMCOUNTER18H = 12'hB92,
    CSR_MHPMCOUNTER19H = 12'hB93,
    CSR_MHPMCOUNTER20H = 12'hB94,
    CSR_MHPMCOUNTER21H = 12'hB95,
    CSR_MHPMCOUNTER22H = 12'hB96,
    CSR_MHPMCOUNTER23H = 12'hB97,
    CSR_MHPMCOUNTER24H = 12'hB98,
    CSR_MHPMCOUNTER25H = 12'hB99,
    CSR_MHPMCOUNTER26H = 12'hB9A,
    CSR_MHPMCOUNTER27H = 12'hB9B,
    CSR_MHPMCOUNTER28H = 12'hB9C,
    CSR_MHPMCOUNTER29H = 12'hB9D,
    CSR_MHPMCOUNTER30H = 12'hB9E,
    CSR_MHPMCOUNTER31H = 12'hB9F,
    CSR_CPUCTRL        = 12'h7C0,
    CSR_SECURESEED     = 12'h7C1
  } csr_num_e;
  // CSR pmp-related offsets
  parameter logic [11:0] CSR_OFF_PMP_CFG  = 12'h3A0; // pmp_cfg  @ 12'h3a0 - 12'h3a3
  parameter logic [11:0] CSR_OFF_PMP_ADDR = 12'h3B0; // pmp_addr @ 12'h3b0 - 12'h3bf
  // CSR status bits
  parameter int unsigned CSR_MSTATUS_MIE_BIT      = 3;
  parameter int unsigned CSR_MSTATUS_MPIE_BIT     = 7;
  parameter int unsigned CSR_MSTATUS_MPP_BIT_LOW  = 11;
  parameter int unsigned CSR_MSTATUS_MPP_BIT_HIGH = 12;
  parameter int unsigned CSR_MSTATUS_MPRV_BIT     = 17;
  parameter int unsigned CSR_MSTATUS_TW_BIT       = 21;
  // CSR machine ISA
  parameter logic [1:0] CSR_MISA_MXL = 2'd1; // M-XLEN: XLEN in M-Mode for RV32
  // CSR interrupt pending/enable bits
  parameter int unsigned CSR_MSIX_BIT      = 3;
  parameter int unsigned CSR_MTIX_BIT      = 7;
  parameter int unsigned CSR_MEIX_BIT      = 11;
  parameter int unsigned CSR_MFIX_BIT_LOW  = 16;
  parameter int unsigned CSR_MFIX_BIT_HIGH = 31;
  // CSR Machine Security Configuration bits
  parameter int unsigned CSR_MSECCFG_MML_BIT  = 0;
  parameter int unsigned CSR_MSECCFG_MMWP_BIT = 1;
  parameter int unsigned CSR_MSECCFG_RLB_BIT  = 2;
  // Machine Vendor ID - OpenHW JEDEC ID is '2 decimal (bank 13)'
  parameter MVENDORID_OFFSET = 7'h2;  // Final byte without parity bit
  parameter MVENDORID_BANK = 25'hC;  // Number of continuation codes
  // Machine Architecture ID (https://github.com/riscv/riscv-isa-manual/blob/master/marchid.md)
  parameter MARCHID = 32'd35;
  localparam logic [31:0] CSR_MVENDORID_VALUE  = {MVENDORID_BANK, MVENDORID_OFFSET};
  localparam logic [31:0] CSR_MARCHID_VALUE = MARCHID;
  // Implementation ID
  // 0 indicates this field is not implemeted. cve2 implementors may wish to indicate an RTL/netlist
  // version here using their own unique encoding (e.g. 32 bits of the git hash of the implemented
  // commit).
  localparam logic [31:0] CSR_MIMPID_VALUE = 32'b0;
  // Machine Configuration Pointer
  // 0 indicates the configuration data structure does not eixst. cve2 implementors may wish to
  // alter this to point to their system specific configuration data structure.
  localparam logic [31:0] CSR_MCONFIGPTR_VALUE = 32'b0;
 // RVFI CSR element
  typedef struct packed {
    bit [63:0] rdata;
    bit [63:0] rmask;
    bit [63:0] wdata;
    bit [63:0] wmask;
  } rvfi_csr_elmt_t;
  // RVFI CSR structure
  typedef struct packed {
    rvfi_csr_elmt_t fflags;
    rvfi_csr_elmt_t frm;
    rvfi_csr_elmt_t fcsr;
    rvfi_csr_elmt_t ftran;
    rvfi_csr_elmt_t dcsr;
    rvfi_csr_elmt_t dpc;
    rvfi_csr_elmt_t dscratch0;
    rvfi_csr_elmt_t dscratch1;
    rvfi_csr_elmt_t sstatus;
    rvfi_csr_elmt_t sie;
    rvfi_csr_elmt_t sip;
    rvfi_csr_elmt_t stvec;
    rvfi_csr_elmt_t scounteren;
    rvfi_csr_elmt_t sscratch;
    rvfi_csr_elmt_t sepc;
    rvfi_csr_elmt_t scause;
    rvfi_csr_elmt_t stval;
    rvfi_csr_elmt_t satp;
    rvfi_csr_elmt_t mstatus;
    rvfi_csr_elmt_t mstatush;
    rvfi_csr_elmt_t misa;
    rvfi_csr_elmt_t medeleg;
    rvfi_csr_elmt_t mideleg;
    rvfi_csr_elmt_t mie;
    rvfi_csr_elmt_t mtvec;
    rvfi_csr_elmt_t mcounteren;
    rvfi_csr_elmt_t mscratch;
    rvfi_csr_elmt_t mepc;
    rvfi_csr_elmt_t mcause;
    rvfi_csr_elmt_t mtval;
    rvfi_csr_elmt_t mip;
    rvfi_csr_elmt_t menvcfg;
    rvfi_csr_elmt_t menvcfgh;
    rvfi_csr_elmt_t mvendorid;
    rvfi_csr_elmt_t marchid;
    rvfi_csr_elmt_t mhartid;
    rvfi_csr_elmt_t mcountinhibit;
    rvfi_csr_elmt_t mcycle;
    rvfi_csr_elmt_t mcycleh;
    rvfi_csr_elmt_t minstret;
    rvfi_csr_elmt_t minstreth;
    rvfi_csr_elmt_t cycle;
    rvfi_csr_elmt_t cycleh;
    rvfi_csr_elmt_t instret;
    rvfi_csr_elmt_t instreth;
    rvfi_csr_elmt_t dcache;
    rvfi_csr_elmt_t icache;
    rvfi_csr_elmt_t acc_cons;
    rvfi_csr_elmt_t pmpcfg0;
    rvfi_csr_elmt_t pmpcfg1;
    rvfi_csr_elmt_t pmpcfg2;
    rvfi_csr_elmt_t pmpcfg3;
    rvfi_csr_elmt_t pmpaddr0;
    rvfi_csr_elmt_t pmpaddr1;
    rvfi_csr_elmt_t pmpaddr2;
    rvfi_csr_elmt_t pmpaddr3;
    rvfi_csr_elmt_t pmpaddr4;
    rvfi_csr_elmt_t pmpaddr5;
    rvfi_csr_elmt_t pmpaddr6;
    rvfi_csr_elmt_t pmpaddr7;
    rvfi_csr_elmt_t pmpaddr8;
    rvfi_csr_elmt_t pmpaddr9;
    rvfi_csr_elmt_t pmpaddr10;
    rvfi_csr_elmt_t pmpaddr11;
    rvfi_csr_elmt_t pmpaddr12;
    rvfi_csr_elmt_t pmpaddr13;
    rvfi_csr_elmt_t pmpaddr14;
    rvfi_csr_elmt_t pmpaddr15;
  } rvfi_csr_t;
  // CV-X-IF
  parameter int unsigned X_NUM_RS         = 3;
  parameter int unsigned X_ID_WIDTH       = 4;
  parameter int unsigned X_RFR_WIDTH      = 32;
  parameter int unsigned X_RFW_WIDTH      = 32;
  parameter int unsigned X_HARTID_WIDTH   = 32;
  parameter int unsigned X_DUAL_READ      = 0;
  parameter int unsigned X_DUAL_WRITE     = 0;
  parameter int unsigned X_INSTR_INFLIGHT = 2**X_ID_WIDTH;
  typedef logic [X_NUM_RS+X_DUAL_READ-1:0] readregflags_t;
  typedef logic [X_DUAL_WRITE:0]           writeregflags_t;
  typedef logic [X_ID_WIDTH-1:0]           id_t;
  typedef logic [X_HARTID_WIDTH-1:0]       hartid_t;
  // Issue Interface
  typedef struct packed {
    logic [31:0] instr;
    hartid_t     hartid;
    id_t         id;
  } x_issue_req_t;
  typedef struct packed {
    logic           accept;
    writeregflags_t writeback;
    readregflags_t  register_read;
  } x_issue_resp_t;
  // Register Interface
  typedef struct packed {
    hartid_t                              hartid;
    id_t                                  id;
    logic [X_NUM_RS-1:0][X_RFR_WIDTH-1:0] rs;
    readregflags_t                        rs_valid;
  } x_register_t;
  // Commit Interface
  typedef struct packed {
    hartid_t hartid;
    id_t     id;
    logic    commit_kill;
  } x_commit_t;
  // Result Interface
  typedef struct packed {
    hartid_t                hartid;
    id_t                    id;
    logic [X_RFW_WIDTH-1:0] data;
    logic [4:0]             rd;
    writeregflags_t         we;
  } x_result_t;
endpackage
// Copyright (c) 2025 Eclipse Foundation
// Copyright lowRISC contributors.
// Copyright 2018 ETH Zurich and University of Bologna, see also CREDITS.md.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
/**
 * Main controller of the processor
 */
 // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// Macros and helper code for using assertions.
//  - Provides default clk and rst options to simplify code
//  - Provides boiler plate template for common assertions
///////////////////
// Helper macros //
///////////////////
// Default clk and reset signals used by assertion macros below.
// Converts an arbitrary block of code into a Verilog string
// ASSERT_ERROR logs an error message with either `uvm_error or with $error.
//
// This somewhat duplicates `DV_ERROR macro defined in hw/dv/sv/dv_utils/dv_macros.svh. The reason
// for redefining it here is to avoid creating a dependency.
// This macro is suitable for conditionally triggering lint errors, e.g., if a Sec parameter takes
// on a non-default value. This may be required for pre-silicon/FPGA evaluation but we don't want
// to allow this for tapeout.
// The basic helper macros are actually defined in "implementation headers". The macros should do
// the same thing in each case (except for the dummy flavour), but in a way that the respective
// tools support.
//
// If the tool supports assertions in some form, we also define INC_ASSERT (which can be used to
// hide signal definitions that are only used for assertions).
//
// The list of basic macros supported is:
//
//  ASSERT_I:     Immediate assertion. Note that immediate assertions are sensitive to simulation
//                glitches.
//
//  ASSERT_INIT:  Assertion in initial block. Can be used for things like parameter checking.
//
//  ASSERT_INIT_NET: Assertion in initial block. Can be used for initial value of a net.
//
//  ASSERT_FINAL: Assertion in final block. Can be used for things like queues being empty at end of
//                sim, all credits returned at end of sim, state machines in idle at end of sim.
//
//  ASSERT:       Assert a concurrent property directly. It can be called as a module (or
//                interface) body item.
//
//                Note: We use (__rst !== '0) in the disable iff statements instead of (__rst ==
//                '1). This properly disables the assertion in cases when reset is X at the
//                beginning of a simulation. For that case, (reset == '1) does not disable the
//                assertion.
//
//  ASSERT_NEVER: Assert a concurrent property NEVER happens
//
//  ASSERT_KNOWN: Assert that signal has a known value (each bit is either '0' or '1') after reset.
//                It can be called as a module (or interface) body item.
//
//  COVER:        Cover a concurrent property
//
//  ASSUME:       Assume a concurrent property
//
//  ASSUME_I:     Assume an immediate property
  // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// Macro bodies included by prim_assert.sv for tools that don't support assertions. See
// prim_assert.sv for documentation for each of the macros.
//////////////////////////////
// Complex assertion macros //
//////////////////////////////
// Assert that signal is an active-high pulse with pulse length of 1 clock cycle
// Assert that a property is true only when an enable signal is set.  It can be called as a module
// (or interface) body item.
// Assert that signal has a known value (each bit is either '0' or '1') after reset if enable is
// set.  It can be called as a module (or interface) body item.
//////////////////////////////////
// For formal verification only //
//////////////////////////////////
// Note that the existing set of ASSERT macros specified above shall be used for FPV,
// thereby ensuring that the assertions are evaluated during DV simulations as well.
// ASSUME_FPV
// Assume a concurrent property during formal verification only.
// ASSUME_I_FPV
// Assume a concurrent property during formal verification only.
// COVER_FPV
// Cover a concurrent property during formal verification
 // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// // Macros and helper code for security countermeasures.
// Helper macros
// macros for security countermeasures
 // PRIM_ASSERT_SEC_CM_SVH
 // PRIM_ASSERT_SV
 // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// Include FCOV RTL by default. Disable it for synthesis and where explicitly requested (by defining
// DV_FCOV_DISABLE).
// Disable instantiations of FCOV coverpoints or covergroups.
// Instantiates a covergroup in an interface or module.
//
// This macro assumes that a covergroup of the same name as the NAME_ arg is defined in the
// interface or module. It just adds some extra signals and logic to control the creation of the
// covergroup instance with ~bit en_<cg_name>~. This defaults to 0. It is ORed with the external
// COND_ signal. The testbench can modify it at t = 0 based on the test being run.
// NOTE: This is not meant to be invoked inside a class.
//
// NAME_ : Name of the covergroup.
// COND_ : External condition / expr that controls the creation of the covergroup.
// ARGS_ : Arguments to covergroup instance, if any. Args MUST BE wrapped in (..).
// Creates a coverpoint for an expression where only the expression true case is of interest for
// coverage (e.g. where the expression indicates an event has occured).
// Creates a SVA cover that can be used in a covergroup.
//
// This macro creates an unnamed SVA cover from the property (or an expression) `PROP_` and an event
// with the name `EV_NAME_`. When the SVA cover is hit, the event is triggered. A coverpoint can
// cover the `triggered` property of the event.
// Coverage support is not always available but it's useful to include extra fcov signals for
// linting purposes. They need to be marked as unused to avoid warnings.
// Define a signal and expression in the design for capture in functional coverage
// Define a signal and expression in the design for capture in functional coverage depending on
// design configuration. The input GEN_COND_ must be a constant or parameter.
module cve2_controller #(
 ) (
  input  logic                  clk_i,
  input  logic                  rst_ni,
  input  logic                  fetch_enable_i,          // core can fetch instructions leave RESET state
  output logic                  ctrl_busy_o,             // core is busy processing instrs
  // decoder related signals
  input  logic                  illegal_insn_i,          // decoder has an invalid instr
  input  logic                  ecall_insn_i,            // decoder has ECALL instr
  input  logic                  mret_insn_i,             // decoder has MRET instr
  input  logic                  dret_insn_i,             // decoder has DRET instr
  input  logic                  wfi_insn_i,              // decoder has WFI instr
  input  logic                  ebrk_insn_i,             // decoder has EBREAK instr
  input  logic                  csr_pipe_flush_i,        // do CSR-related pipeline flush
  input  logic                  xif_scoreboard_busy_i,   // tells if the the core is waiting for XIF
  // instr from IF-ID pipeline stage
  input  logic                  instr_valid_i,           // instr is valid
  input  logic [31:0]           instr_i,                 // uncompressed instr data for mtval
  input  logic [15:0]           instr_compressed_i,      // instr compressed data for mtval
  input  logic                  instr_is_compressed_i,   // instr is compressed
  input  logic                  instr_fetch_err_i,       // instr has error
  input  logic                  instr_fetch_err_plus2_i, // instr error is x32
  input  logic [31:0]           pc_id_i,                 // instr address
  // to IF-ID pipeline stage
  output logic                  instr_valid_clear_o,     // kill instr in IF-ID reg
  output logic                  id_in_ready_o,           // ID stage is ready for new instr
  output logic                  controller_run_o,        // Controller is in standard instruction
                                                         // run mode
  // to prefetcher
  output logic                  instr_req_o,             // start fetching instructions
  output logic                  pc_set_o,                // jump to address set by pc_mux
  output cve2_pkg::pc_sel_e     pc_mux_o,                // IF stage fetch address selector
                                                         // (boot, normal, exception...)
  output cve2_pkg::exc_pc_sel_e exc_pc_mux_o,            // IF stage selector for exception PC
  output cve2_pkg::exc_cause_e  exc_cause_o,             // for IF stage, CSRs
  // LSU
  input  logic [31:0]           lsu_addr_last_i,         // for mtval
  input  logic                  load_err_i,
  input  logic                  store_err_i,
  // jump/branch signals
  input  logic                  branch_set_i,            // branch set signal (branch definitely
                                                         // taken)
  input  logic                  jump_set_i,              // jump taken set signal
  // interrupt signals
  input  logic                  csr_mstatus_mie_i,       // M-mode interrupt enable bit
  input  logic                  irq_pending_i,           // interrupt request pending
  input  cve2_pkg::irqs_t       irqs_i,                  // interrupt requests qualified with
                                                         // mie CSR
  input  logic                  irq_nm_i,                // non-maskeable interrupt
  output logic                  nmi_mode_o,              // core executing NMI handler
  // debug signals
  input  logic                  debug_req_i,
  output cve2_pkg::dbg_cause_e  debug_cause_o,
  output logic                  debug_csr_save_o,
  output logic                  debug_mode_o,
  input  logic                  debug_single_step_i,
  input  logic                  debug_ebreakm_i,
  input  logic                  debug_ebreaku_i,
  input  logic                  trigger_match_i,
  output logic                  csr_save_if_o,
  output logic                  csr_save_id_o,
  output logic                  csr_restore_mret_id_o,
  output logic                  csr_restore_dret_id_o,
  output logic                  csr_save_cause_o,
  output logic [31:0]           csr_mtval_o,
  input  cve2_pkg::priv_lvl_e   priv_mode_i,
  input  logic                  csr_mstatus_tw_i,
  // stall & flush signals
  input  logic                  stall_id_i,
  output logic                  flush_id_o,
  // performance monitors
  output logic                  perf_jump_o,             // we are executing a jump
                                                         // instruction (j, jr, jal, jalr)
  output logic                  perf_tbranch_o           // we are executing a taken branch
                                                         // instruction
);
  import cve2_pkg::*;
  // FSM state encoding
  typedef enum logic [3:0] {
    RESET, BOOT_SET, WAIT_SLEEP, SLEEP, FIRST_FETCH, DECODE, FLUSH,
    IRQ_TAKEN, DBG_TAKEN_IF, DBG_TAKEN_ID
  } ctrl_fsm_e;
  ctrl_fsm_e ctrl_fsm_cs, ctrl_fsm_ns;
  logic nmi_mode_q, nmi_mode_d;
  logic debug_mode_q, debug_mode_d;
  logic load_err_q, load_err_d;
  logic store_err_q, store_err_d;
  logic exc_req_q, exc_req_d;
  logic illegal_insn_q, illegal_insn_d;
  // Of the various exception/fault signals, which one takes priority in FLUSH and hence controls
  // what happens next (setting exc_cause, csr_mtval etc)
  logic instr_fetch_err_prio;
  logic illegal_insn_prio;
  logic ecall_insn_prio;
  logic ebrk_insn_prio;
  logic store_err_prio;
  logic load_err_prio;
  logic stall;
  logic halt_if;
  logic retain_id;
  logic flush_id;
  logic illegal_dret;
  logic illegal_umode;
  logic exc_req_lsu;
  logic special_req;
  logic special_req_pc_change;
  logic special_req_flush_only;
  logic do_single_step_d;
  logic do_single_step_q;
  logic enter_debug_mode_prio_d;
  logic enter_debug_mode_prio_q;
  logic enter_debug_mode;
  logic ebreak_into_debug;
  logic handle_irq;
  logic [3:0] mfip_id;
  logic       unused_irq_timer;
  logic ecall_insn;
  logic mret_insn;
  logic dret_insn;
  logic wfi_insn;
  logic ebrk_insn;
  logic csr_pipe_flush;
  logic instr_fetch_err;
  ////////////////
  // Exceptions //
  ////////////////
  assign load_err_d  = load_err_i;
  assign store_err_d = store_err_i;
  // Decoder doesn't take instr_valid into account, factor it in here.
  assign ecall_insn      = ecall_insn_i      & instr_valid_i;
  assign mret_insn       = mret_insn_i       & instr_valid_i;
  assign dret_insn       = dret_insn_i       & instr_valid_i;
  assign wfi_insn        = wfi_insn_i        & instr_valid_i;
  assign ebrk_insn       = ebrk_insn_i       & instr_valid_i;
  assign csr_pipe_flush  = csr_pipe_flush_i  & instr_valid_i;
  assign instr_fetch_err = instr_fetch_err_i & instr_valid_i;
  // "Executing DRET outside of Debug Mode causes an illegal instruction exception."
  // [Debug Spec v0.13.2, p.41]
  assign illegal_dret = dret_insn & ~debug_mode_q;
  // Some instructions can only be executed in M-Mode
  assign illegal_umode = (priv_mode_i != PRIV_LVL_M) &
                         // MRET must be in M-Mode. TW means trap WFI to M-Mode.
                         (mret_insn | (csr_mstatus_tw_i & wfi_insn));
  // This is recorded in the illegal_insn_q flop to help timing.  Specifically
  // it is needed to break the path from cve2_cs_registers/illegal_csr_insn_o
  // to pc_set_o.  Clear when controller is in FLUSH so it won't remain set
  // once illegal instruction is handled.
  // All terms in this expression are qualified by instr_valid_i
  assign illegal_insn_d = (illegal_insn_i | illegal_dret | illegal_umode) & (ctrl_fsm_cs != FLUSH);
  // exception requests
  // requests are flopped in exc_req_q.  This is cleared when controller is in
  // the FLUSH state so the cycle following exc_req_q won't remain set for an
  // exception request that has just been handled.
  // All terms in this expression are qualified by instr_valid_i
  assign exc_req_d = (ecall_insn | ebrk_insn | illegal_insn_d | instr_fetch_err) &
                     (ctrl_fsm_cs != FLUSH);
  // LSU exception requests
  assign exc_req_lsu = store_err_i | load_err_i;
  // special requests: special instructions, pipeline flushes, exceptions...
  // All terms in these expressions are qualified by instr_valid_i except exc_req_lsu which can come
  // from the Writeback stage with no instr_valid_i from the ID stage
  // These special requests only cause a pipeline flush and in particular don't cause a PC change
  // that is outside the normal execution flow
  assign special_req_flush_only = wfi_insn | csr_pipe_flush;
  // These special requests cause a change in PC
  assign special_req_pc_change = mret_insn | dret_insn | exc_req_d | exc_req_lsu;
  // generic special request signal, applies to all instructions
  assign special_req = special_req_pc_change | special_req_flush_only;
  // Exception/fault prioritisation is taken from Table 3.7 of Priviledged Spec v1.11
    always_comb begin
      instr_fetch_err_prio = 0;
      illegal_insn_prio    = 0;
      ecall_insn_prio      = 0;
      ebrk_insn_prio       = 0;
      store_err_prio       = 0;
      load_err_prio        = 0;
      if (instr_fetch_err) begin
        instr_fetch_err_prio = 1'b1;
      end else if (illegal_insn_q) begin
        illegal_insn_prio = 1'b1;
      end else if (ecall_insn) begin
        ecall_insn_prio = 1'b1;
      end else if (ebrk_insn) begin
        ebrk_insn_prio = 1'b1;
      end else if (store_err_q) begin
        store_err_prio = 1'b1;
      end else if (load_err_q) begin
        load_err_prio  = 1'b1;
      end
    end
  ////////////////
  // Interrupts //
  ////////////////
  // Enter debug mode due to an external debug_req_i or because the core is in
  // single step mode (dcsr.step == 1). Single step must be qualified with
  // instruction valid otherwise the core will immediately enter debug mode
  // due to a recently flushed IF (or a delay in an instruction returning from
  // memory) before it has had anything to single step.
  // Also enter debug mode on a trigger match (hardware breakpoint)
  // Set `do_single_step_q` when a valid instruction is seen outside of debug mode and core is in
  // single step mode. The first valid instruction on debug mode entry will clear it. Hold its value
  // when there is no valid instruction so `do_single_step_d` remains asserted until debug mode is
  // entered.
  assign do_single_step_d = instr_valid_i ? ~debug_mode_q & debug_single_step_i : do_single_step_q;
  // Enter debug mode due to:
  // * external `debug_req_i`
  // * core in single step mode (dcsr.step == 1).
  // * trigger match (hardware breakpoint)
  //
  // `debug_req_i` and `do_single_step_d` request debug mode with priority. This results in a debug
  // mode entry even if the controller goes to `FLUSH` in preparation for handling an exception or
  // interrupt. `trigger_match_i` is not a priority entry into debug mode as it must be ignored
  // where control flow changes such that the instruction causing the trigger is no longer being
  // executed.
  assign enter_debug_mode_prio_d = (debug_req_i | do_single_step_d) & ~debug_mode_q;
  assign enter_debug_mode = enter_debug_mode_prio_d | (trigger_match_i & ~debug_mode_q);
  // Set when an ebreak should enter debug mode rather than jump to exception
  // handler
  assign ebreak_into_debug = priv_mode_i == PRIV_LVL_M ? debug_ebreakm_i :
                             priv_mode_i == PRIV_LVL_U ? debug_ebreaku_i :
                                                         1'b0;
  // Interrupts including NMI are ignored,
  // - while in debug mode [Debug Spec v0.13.2, p.39],
  // - while in NMI mode (nested NMIs are not supported, NMI has highest priority and
  //   cannot be interrupted by regular interrupts).
  // - while single stepping.
  assign handle_irq = ~debug_mode_q & ~nmi_mode_q &
      (irq_nm_i | (irq_pending_i & csr_mstatus_mie_i));
  // generate ID of fast interrupts, highest priority to lowest ID
  always_comb begin : gen_mfip_id
    mfip_id = 4'd0;
    for (int i = 15; i >= 0; i--) begin
      if (irqs_i.irq_fast[i]) begin
        mfip_id = i[3:0];
      end
    end
  end
  assign unused_irq_timer = irqs_i.irq_timer;
  /////////////////////
  // Core controller //
  /////////////////////
  always_comb begin
    // Default values
    instr_req_o           = 1'b1;
    csr_save_if_o         = 1'b0;
    csr_save_id_o         = 1'b0;
    csr_restore_mret_id_o = 1'b0;
    csr_restore_dret_id_o = 1'b0;
    csr_save_cause_o      = 1'b0;
    csr_mtval_o           = '0;
    // The values of pc_mux and exc_pc_mux are only relevant if pc_set is set. Some of the states
    // below always set pc_mux and exc_pc_mux but only set pc_set if certain conditions are met.
    // This avoid having to factor those conditions into the pc_mux and exc_pc_mux select signals
    // helping timing.
    pc_mux_o               = PC_BOOT;
    pc_set_o               = 1'b0;
    exc_pc_mux_o           = EXC_PC_IRQ;
    exc_cause_o            = EXC_CAUSE_INSN_ADDR_MISA; // = 6'h00
    ctrl_fsm_ns            = ctrl_fsm_cs;
    ctrl_busy_o            = 1'b1;
    halt_if                = 1'b0;
    retain_id              = 1'b0;
    flush_id               = 1'b0;
    debug_csr_save_o       = 1'b0;
    debug_cause_o          = DBG_CAUSE_EBREAK;
    debug_mode_d           = debug_mode_q;
    nmi_mode_d             = nmi_mode_q;
    perf_tbranch_o         = 1'b0;
    perf_jump_o            = 1'b0;
    controller_run_o       = 1'b0;
    unique case (ctrl_fsm_cs)
      RESET: begin
        instr_req_o   = 1'b0;
        pc_mux_o      = PC_BOOT;
        pc_set_o      = 1'b1;
        if (fetch_enable_i == 1'b1)
        begin
          ctrl_fsm_ns = BOOT_SET;
        end
      end
      BOOT_SET: begin
        // copy boot address to instr fetch address
        instr_req_o   = 1'b1;
        pc_mux_o      = PC_BOOT;
        pc_set_o      = 1'b1;
        ctrl_fsm_ns = FIRST_FETCH;
      end
      WAIT_SLEEP: begin
        ctrl_busy_o   = 1'b0;
        instr_req_o   = 1'b0;
        halt_if       = 1'b1;
        flush_id      = 1'b1;
        ctrl_fsm_ns   = SLEEP;
      end
      SLEEP: begin
        // instruction in IF stage is already valid
        // we begin execution when an interrupt has arrived
        instr_req_o   = 1'b0;
        halt_if       = 1'b1;
        flush_id      = 1'b1;
        // normal execution flow
        // in debug mode or single step mode we leave immediately (wfi=nop)
        if (irq_nm_i || irq_pending_i || debug_req_i || debug_mode_q || debug_single_step_i) begin
          ctrl_fsm_ns = FIRST_FETCH;
        end else begin
          // Make sure clock remains disabled.
          ctrl_busy_o = 1'b0;
        end
      end
      FIRST_FETCH: begin
        // Stall because of IF miss
        if (id_in_ready_o) begin
          ctrl_fsm_ns = DECODE;
        end
        // handle interrupts
        if (handle_irq) begin
          // We are handling an interrupt. Set halt_if to tell IF not to give
          // us any more instructions before it redirects to the handler, but
          // don't set flush_id: we must allow this instruction to complete
          // (since it might have outstanding loads or stores).
          ctrl_fsm_ns = IRQ_TAKEN;
          halt_if     = 1'b1;
        end
        // enter debug mode
        if (enter_debug_mode) begin
          ctrl_fsm_ns = DBG_TAKEN_IF;
          // Halt IF only for now, ID will be flushed in DBG_TAKEN_IF as the
          // ID state is needed for correct debug mode entry
          halt_if     = 1'b1;
        end
      end
      DECODE: begin
        // normal operating mode of the ID stage, in case of debug and interrupt requests,
        // priorities are as follows (lower number == higher priority)
        // 1. currently running (multicycle) instructions and exceptions caused by these
        // 2. debug requests
        // 3. interrupt requests
        controller_run_o = 1'b1;
        // Set PC mux for branch and jump here to ease timing. Value is only relevant if pc_set_o is
        // also set. Setting the mux value here avoids factoring in special_req and instr_valid_i
        // which helps timing.
        pc_mux_o = PC_JUMP;
        // Get ready for special instructions, exceptions, pipeline flushes
        if (special_req) begin
          // Halt IF but don't flush ID. This leaves a valid instruction in
          // ID so controller can determine appropriate action in the
          // FLUSH state.
          retain_id = 1'b1;
          // The FSM will always go directly to FLUSH.
          // when X-IF is active and xif_scoreboard_busy_i, wait the scoreboard to be empty before switching state
          ctrl_fsm_ns = xif_scoreboard_busy_i ? DECODE: FLUSH;
        end
        if (branch_set_i || jump_set_i) begin
          pc_set_o       = 1'b1;
          perf_tbranch_o = branch_set_i;
          perf_jump_o    = jump_set_i;
        end
        // If entering debug mode or handling an IRQ the core needs to wait until any instruction in
        // ID has finished executing. Stall IF during that time.
        if ((enter_debug_mode || handle_irq) && (stall || instr_valid_i)) begin
          halt_if = 1'b1;
        end
        if (!stall && !special_req && !instr_valid_i) begin
          if (enter_debug_mode) begin
            // enter debug mode
            ctrl_fsm_ns = xif_scoreboard_busy_i ? DECODE : DBG_TAKEN_IF;
            // Halt IF only for now, ID will be flushed in DBG_TAKEN_IF as the
            // ID state is needed for correct debug mode entry
            halt_if     = 1'b1;
          end else if (handle_irq) begin
            // handle interrupt (not in debug mode)
            ctrl_fsm_ns = xif_scoreboard_busy_i ? DECODE : IRQ_TAKEN;
            // We are handling an interrupt (not in debug mode). Set halt_if to
            // tell IF not to give us any more instructions before it redirects
            // to the handler, but don't set flush_id: we must allow this
            // instruction to complete (since it might have outstanding loads
            // or stores).
            halt_if     = 1'b1;
          end
        end
      end // DECODE
      IRQ_TAKEN: begin
        pc_mux_o     = PC_EXC;
        exc_pc_mux_o = EXC_PC_IRQ;
        if (handle_irq) begin
          pc_set_o         = 1'b1;
          csr_save_if_o    = 1'b1;
          csr_save_cause_o = 1'b1;
          // interrupt priorities according to Privileged Spec v1.11 p.31
          if (irq_nm_i && !nmi_mode_q) begin
            exc_cause_o = EXC_CAUSE_IRQ_NM;
            nmi_mode_d  = 1'b1; // enter NMI mode
          end else if (irqs_i.irq_fast != 16'b0) begin
            // generate exception cause ID from fast interrupt ID:
            // - first bit distinguishes interrupts from exceptions,
            // - third bit adds 16 to fast interrupt ID so that the interrup 0 becomes 16 and the interrupt 15 becomes 31 (hence 5bits)
            // - second bit is always 0 as the FAST interrupts are represented in the first 5bits, the 6th is always 0 cause is used by the NMI (in that case is 1 as represented by the number 32)
            // for example EXC_CAUSE_IRQ_FAST_0 = {1'b1, 6'd16}
            exc_cause_o = exc_cause_e'({3'b101, mfip_id});
          end else if (irqs_i.irq_external) begin
            exc_cause_o = EXC_CAUSE_IRQ_EXTERNAL_M;
          end else if (irqs_i.irq_software) begin
            exc_cause_o = EXC_CAUSE_IRQ_SOFTWARE_M;
          end else begin // irqs_i.irq_timer
            exc_cause_o = EXC_CAUSE_IRQ_TIMER_M;
          end
        end
        ctrl_fsm_ns = DECODE;
      end
      DBG_TAKEN_IF: begin
        pc_mux_o     = PC_EXC;
        exc_pc_mux_o = EXC_PC_DBD;
        // enter debug mode and save PC in IF to dpc
        // jump to debug exception handler in debug memory
        flush_id         = 1'b1;
        pc_set_o         = 1'b1;
        csr_save_if_o    = 1'b1;
        debug_csr_save_o = 1'b1;
        csr_save_cause_o = 1'b1;
        if (trigger_match_i) begin
          debug_cause_o = DBG_CAUSE_TRIGGER;     // (priority 4)
        end else if (debug_req_i) begin
          debug_cause_o = DBG_CAUSE_HALTREQ;     // (priority 1)
        end else begin
          debug_cause_o = DBG_CAUSE_STEP;        // (priority 0, lowest)
        end
        // enter debug mode
        debug_mode_d = 1'b1;
        ctrl_fsm_ns  = DECODE;
      end
      DBG_TAKEN_ID: begin
        // enter debug mode and save PC in ID to dpc, used when encountering
        // 1. EBREAK during debug mode
        // 2. EBREAK with forced entry into debug mode (ebreakm or ebreaku set).
        // regular ebreak's go through FLUSH.
        //
        // for 1. do not update dcsr and dpc, for 2. do so [Debug Spec v0.13.2, p.39]
        // jump to debug exception handler in debug memory
        flush_id      = 1'b1;
        pc_mux_o      = PC_EXC;
        pc_set_o      = 1'b1;
        exc_pc_mux_o  = EXC_PC_DBD;
        // update dcsr and dpc
        if (ebreak_into_debug && !debug_mode_q) begin // ebreak with forced entry
          // dpc (set to the address of the EBREAK, i.e. set to PC in ID stage)
          csr_save_cause_o = 1'b1;
          csr_save_id_o    = 1'b1;
          // dcsr
          debug_csr_save_o = 1'b1;
          debug_cause_o    = DBG_CAUSE_EBREAK;
        end
        // enter debug mode
        debug_mode_d = 1'b1;
        ctrl_fsm_ns  = DECODE;
      end
      FLUSH: begin
        // flush the pipeline
        halt_if     = 1'b1;
        flush_id    = 1'b1;
        ctrl_fsm_ns = DECODE;
        // As pc_mux and exc_pc_mux can take various values in this state they aren't set early
        // here.
        // exceptions: set exception PC, save PC and exception cause
        // exc_req_lsu is high for one clock cycle only (in DECODE)
        if (exc_req_q || store_err_q || load_err_q) begin
          pc_set_o         = 1'b1;
          pc_mux_o         = PC_EXC;
          exc_pc_mux_o     = debug_mode_q ? EXC_PC_DBG_EXC : EXC_PC_EXC;
          begin : g_no_writeback_mepc_save
            csr_save_id_o  = 1'b0;
          end
          csr_save_cause_o = 1'b1;
          // Exception/fault prioritisation logic will have set exactly 1 X_prio signal
          unique case (1'b1)
            instr_fetch_err_prio: begin
              exc_cause_o = EXC_CAUSE_INSTR_ACCESS_FAULT;
              csr_mtval_o = instr_fetch_err_plus2_i ? (pc_id_i + 32'd2) : pc_id_i;
            end
            illegal_insn_prio: begin
              exc_cause_o = EXC_CAUSE_ILLEGAL_INSN;
              csr_mtval_o = instr_is_compressed_i ? {16'b0, instr_compressed_i} : instr_i;
            end
            ecall_insn_prio: begin
              exc_cause_o = (priv_mode_i == PRIV_LVL_M) ? EXC_CAUSE_ECALL_MMODE :
                                                          EXC_CAUSE_ECALL_UMODE;
            end
            ebrk_insn_prio: begin
              if (debug_mode_q | ebreak_into_debug) begin
                /*
                 * EBREAK in debug mode re-enters debug mode
                 *
                 * "The only exception is EBREAK. When that is executed in Debug
                 * Mode, it halts the hart again but without updating dpc or
                 * dcsr." [Debug Spec v0.13.2, p.39]
                 */
                /*
                 * dcsr.ebreakm == 1:
                 * "EBREAK instructions in M-mode enter Debug Mode."
                 * [Debug Spec v0.13.2, p.42]
                 */
                pc_set_o         = 1'b0;
                csr_save_id_o    = 1'b0;
                csr_save_cause_o = 1'b0;
                ctrl_fsm_ns      = DBG_TAKEN_ID;
                flush_id         = 1'b0;
              end else begin
                /*
                 * "The EBREAK instruction is used by debuggers to cause control
                 * to be transferred back to a debugging environment. It
                 * generates a breakpoint exception and performs no other
                 * operation. [...] ECALL and EBREAK cause the receiving
                 * privilege mode's epc register to be set to the address of the
                 * ECALL or EBREAK instruction itself, not the address of the
                 * following instruction." [Privileged Spec v1.11, p.40]
                 */
                exc_cause_o      = EXC_CAUSE_BREAKPOINT;
              end
            end
            store_err_prio: begin
              exc_cause_o = EXC_CAUSE_STORE_ACCESS_FAULT;
              csr_mtval_o = lsu_addr_last_i;
            end
            load_err_prio: begin
              exc_cause_o = EXC_CAUSE_LOAD_ACCESS_FAULT;
              csr_mtval_o = lsu_addr_last_i;
            end
            default: ;
          endcase
        end else begin
          // special instructions and pipeline flushes
          if (mret_insn) begin
            pc_mux_o              = PC_ERET;
            pc_set_o              = 1'b1;
            csr_restore_mret_id_o = 1'b1;
            if (nmi_mode_q) begin
              nmi_mode_d          = 1'b0; // exit NMI mode
            end
          end else if (dret_insn) begin
            pc_mux_o              = PC_DRET;
            pc_set_o              = 1'b1;
            debug_mode_d          = 1'b0;
            csr_restore_dret_id_o = 1'b1;
          end else if (wfi_insn) begin
            ctrl_fsm_ns           = WAIT_SLEEP;
          end
        end // exc_req_q
        // Entering debug mode due to either single step or debug_req. Ensure
        // registers are set for exception but then enter debug handler rather
        // than exception handler [Debug Spec v0.13.2, p.44]
        // Leave all other signals as is to ensure CSRs and PC get set as if
        // core was entering exception handler, entry to debug mode will then
        // see the appropriate state and setup dpc correctly.
        // If an EBREAK instruction is causing us to enter debug mode on the
        // same cycle as a debug_req or single step, honor the EBREAK and
        // proceed to DBG_TAKEN_ID, as it has the highest priority.
        // [Debug Spec v1.0.0-STABLE, p.53]
        // cause==EBREAK    -> prio 3 (highest)
        // cause==debug_req -> prio 2
        // cause==step      -> prio 1 (lowest)
        if (enter_debug_mode_prio_q && !(ebrk_insn_prio && ebreak_into_debug)) begin
          ctrl_fsm_ns = DBG_TAKEN_IF;
        end
      end // FLUSH
      default: begin
        instr_req_o = 1'b0;
        ctrl_fsm_ns = RESET;
      end
    endcase
  end
  assign flush_id_o = flush_id;
  // signal to CSR when in debug mode
  assign debug_mode_o = debug_mode_q;
  // signal to CSR when in an NMI handler (for nested exception handling)
  assign nmi_mode_o = nmi_mode_q;
  ///////////////////
  // Stall control //
  ///////////////////
  // If high current instruction cannot complete this cycle. Either because it needs more cycles to
  // finish (stall_id_i)
  assign stall = stall_id_i;
  // signal to IF stage that ID stage is ready for next instr
  assign id_in_ready_o = ~stall & ~halt_if & ~retain_id;
  // kill instr in IF-ID pipeline reg that are done, or if a
  // multicycle instr causes an exception for example
  // retain_id is another kind of stall, where the instr_valid bit must remain
  // set (unless flush_id is set also). It cannot be factored directly into
  // stall as this causes a combinational loop.
  assign instr_valid_clear_o = ~(stall | retain_id) | flush_id;
  // update registers
  always_ff @(posedge clk_i or negedge rst_ni) begin : update_regs
    if (!rst_ni) begin
      ctrl_fsm_cs             <= RESET;
      nmi_mode_q              <= 1'b0;
      do_single_step_q        <= 1'b0;
      debug_mode_q            <= 1'b0;
      enter_debug_mode_prio_q <= 1'b0;
      load_err_q              <= 1'b0;
      store_err_q             <= 1'b0;
      exc_req_q               <= 1'b0;
      illegal_insn_q          <= 1'b0;
    end else begin
      ctrl_fsm_cs             <= ctrl_fsm_ns;
      nmi_mode_q              <= nmi_mode_d;
      do_single_step_q        <= do_single_step_d;
      debug_mode_q            <= debug_mode_d;
      enter_debug_mode_prio_q <= enter_debug_mode_prio_d;
      load_err_q              <= load_err_d;
      store_err_q             <= store_err_d;
      exc_req_q               <= exc_req_d;
      illegal_insn_q          <= illegal_insn_d;
    end
  end
  //////////
  // FCOV //
  //////////
  ////////////////
  // Assertions //
  ////////////////
  // Selectors must be known/valid.
endmodule