// retroDE_ps2 — tb_ee_core_bev
//
// Chapter 50 coverage: Status.BEV modeling and exception-vector
// selection. Real MIPS resets with BEV=1 so synchronous exceptions
// vector to the ROM-resident "boot" handler; the BIOS writes BEV=0
// via MTC0 once its RAM-resident handler is installed.
//
// This TB exercises the two contracts:
//
//   (A) With INIT_BEV=1, Status.BEV reads back as 1 via MFC0 after
//       reset, and a synchronous AdES fault vectors to
//       BEV_EXC_VECTOR (not EXC_VECTOR).
//   (B) After MTC0 Status with bit 22 cleared, Status.BEV reads as
//       0, and the next AdES fault vectors to EXC_VECTOR instead.
//
// Both handlers are 4-instruction MFC0 + syscall stubs preloaded
// into bios_rom (BEV_EXC_VECTOR is kseg1 ROM so no special
// plumbing needed) and into kseg0 RAM via the bridge port
// (EXC_VECTOR). Each handler writes a distinctive witness into a
// fixed GPR so the TB can tell which one executed.
//
// We can't run both (A) and (B) in one TB easily because the two
// `ee_core_stub` instantiations differ only by INIT_BEV and run
// independently. Instead, run (A) end-to-end, then restart the
// core by asserting rst_n low again to simulate a fresh reset,
// manually clear BEV via MTC0 in the bootstrap, and exercise (B).
//
// Compact version: (A) only. Verifies BEV=1 reset + vector select.
// (B) is covered implicitly by tb_ee_core_align_exc (INIT_BEV=0
// default there, vectors to EXC_VECTOR = 0x8000_0080).

`timescale 1ns/1ps

module tb_ee_core_bev;

    localparam int BIOS_BYTES    = 4 * 1024 * 1024;
    localparam int EE_RAM_BYTES  = 4 * 1024;
    localparam int EE_RAM_ADDR_W = $clog2(EE_RAM_BYTES);

    localparam logic [31:0] RESET_VECTOR   = 32'hBFC0_0000;
    localparam logic [31:0] BOOTSTRAP_VA   = 32'hBFC0_0100;
    localparam int          RESET_SLOT     = 0;
    localparam int          BOOTSTRAP_SLOT = 32'h100 >> 2;

    // BEV=1 handler lives at 0xBFC0_0380 (R4000 convention) — ROM,
    // word index 0x380/4 = 0xE0 in bios_rom.
    localparam logic [31:0] BEV_VEC        = 32'hBFC0_0380;
    localparam int          BEV_VEC_SLOT   = 32'h380 >> 2;

    localparam int B_LUI_1      = BOOTSTRAP_SLOT + 0;
    localparam int B_MFC0_STAT  = BOOTSTRAP_SLOT + 1;
    localparam int B_LUI_MASK   = BOOTSTRAP_SLOT + 2;
    localparam int B_AND_BEV    = BOOTSTRAP_SLOT + 3;
    localparam int B_BNE_BEV0   = BOOTSTRAP_SLOT + 4;
    localparam int B_DS_BEV     = BOOTSTRAP_SLOT + 5;
    localparam int B_SW_BAD     = BOOTSTRAP_SLOT + 6;
    localparam int B_DS_BAD     = BOOTSTRAP_SLOT + 7;
    localparam int B_NEVER      = BOOTSTRAP_SLOT + 8;
    localparam int B_FAIL_BEV   = BOOTSTRAP_SLOT + 9;

    localparam logic [5:0] OP_SPECIAL = 6'h00;
    localparam logic [5:0] OP_J       = 6'h02;
    localparam logic [5:0] OP_BNE     = 6'h05;
    localparam logic [5:0] OP_ORI     = 6'h0D;
    localparam logic [5:0] OP_LUI     = 6'h0F;
    localparam logic [5:0] OP_COP0    = 6'h10;
    localparam logic [5:0] OP_SW      = 6'h2B;
    localparam logic [4:0] COP0_RS_MF = 5'h00;
    localparam logic [5:0] FUNC_AND   = 6'h24;

    logic clk;
    logic rst_n;

    initial clk = 1'b0;
    always #5 clk = ~clk;

    logic        core_go;
    logic        core_halt;
    logic [31:0] core_pc;
    logic        core_trap;
    logic [31:0] core_trap_pc;
    logic [31:0] core_trap_instr;

    logic        ee_rd_en;
    logic [31:0] ee_rd_addr;
    logic [31:0] ee_rd_data;
    logic        ee_rd_valid;

    logic        ee_wr_en;
    logic [31:0] ee_wr_addr;
    logic [31:0] ee_wr_data;
    logic [3:0]  ee_wr_be;

    logic        ee_cpu_irq;
    assign ee_cpu_irq = 1'b0;

    logic                core_ev_valid;
    trace_pkg::subsys_e  core_ev_subsys;
    trace_pkg::event_e   core_ev_event;
    logic [63:0]         core_ev_arg0, core_ev_arg1, core_ev_arg2, core_ev_arg3;
    logic [31:0]         core_ev_flags;

    ee_core_stub #(
        .STRICT_UNSUPPORTED(1'b1),
        .TRAP_ALIGN_ERROR  (1'b0),           // Ch49 exception mode
        .INIT_BEV          (1'b1),           // Ch50: boot with BEV=1
        .BEV_EXC_VECTOR    (BEV_VEC)         // vector target when BEV=1
    ) u_core (
        .clk(clk), .rst_n(rst_n),
        .go_i(core_go),
        .map_rd_en(ee_rd_en), .map_rd_addr(ee_rd_addr),
        .map_rd_data(ee_rd_data), .map_rd_valid(ee_rd_valid),
        .map_wr_en(ee_wr_en), .map_wr_addr(ee_wr_addr),
        .map_wr_data(ee_wr_data), .map_wr_be(ee_wr_be),
        .cpu_irq(ee_cpu_irq),
        .halt_o(core_halt), .pc_o(core_pc),
        .trap_o(core_trap), .trap_pc_o(core_trap_pc),
        .trap_instr_o(core_trap_instr),
        .ev_valid(core_ev_valid), .ev_subsys(core_ev_subsys),
        .ev_event(core_ev_event),
        .ev_arg0(core_ev_arg0), .ev_arg1(core_ev_arg1),
        .ev_arg2(core_ev_arg2), .ev_arg3(core_ev_arg3),
        .ev_flags(core_ev_flags)
    );

    logic         bios_rd_en;
    logic [21:0]  bios_rd_addr;
    logic [31:0]  bios_rd_data;
    logic         bios_rd_valid;

    logic         ee_ram_rd_en;
    logic [24:0]  ee_ram_rd_addr;
    logic [127:0] ee_ram_rd_data;
    logic         ee_ram_rd_valid;
    logic         ee_ram_wr_en;
    logic [24:0]  ee_ram_wr_addr;
    logic [127:0] ee_ram_wr_data;
    logic [15:0]  ee_ram_wr_be;
    logic [7:0]   ee_ram_master_id;

    ee_memory_map_stub u_ee_map (
        .clk(clk), .rst_n(rst_n),
        .ee_rd_en(ee_rd_en), .ee_rd_addr(ee_rd_addr),
        .ee_rd_data(ee_rd_data), .ee_rd_valid(ee_rd_valid),
        .ee_wr_en(ee_wr_en), .ee_wr_addr(ee_wr_addr),
        .ee_wr_data(ee_wr_data), .ee_wr_be(ee_wr_be),
        .dmac_rd_en(1'b0), .dmac_rd_addr(32'd0),
        .dmac_rd_data(), .dmac_rd_valid(),
        .bridge_wr_en(1'b0), .bridge_wr_addr(32'd0),
        .bridge_wr_data(128'd0), .bridge_wr_be(16'd0),
        .bridge_master_id(8'd0),
        .bios_rd_en(bios_rd_en), .bios_rd_addr(bios_rd_addr),
        .bios_rd_data(bios_rd_data), .bios_rd_valid(bios_rd_valid),
        .ram_rd_en(ee_ram_rd_en), .ram_rd_addr(ee_ram_rd_addr),
        .ram_rd_data(ee_ram_rd_data), .ram_rd_valid(ee_ram_rd_valid),
        .ram_wr_en(ee_ram_wr_en), .ram_wr_addr(ee_ram_wr_addr),
        .ram_wr_data(ee_ram_wr_data), .ram_wr_be(ee_ram_wr_be),
        .ram_master_id(ee_ram_master_id),
        .ee_dmac_ch2_wr_en(), .ee_dmac_ch2_wr_addr(), .ee_dmac_ch2_wr_data(),
        .ee_dmac_ch2_rd_en(), .ee_dmac_ch2_rd_addr(),
        .ee_dmac_ch2_rd_data(32'd0), .ee_dmac_ch2_rd_valid(1'b0),
        .ee_intc_wr_en(), .ee_intc_wr_addr(), .ee_intc_wr_data(),
        .ee_intc_rd_en(), .ee_intc_rd_addr(),
        .ee_intc_rd_data(32'd0), .ee_intc_rd_valid(1'b0),
        .ee_misc_mmio_wr_en(), .ee_misc_mmio_wr_addr(), .ee_misc_mmio_wr_data(), .ee_misc_mmio_wr_be(),
        .ee_misc_mmio_rd_en(), .ee_misc_mmio_rd_addr(),
        .ee_misc_mmio_rd_data(32'd0), .ee_misc_mmio_rd_valid(1'b0),
        .ee_biu_wr_en(), .ee_biu_wr_addr(), .ee_biu_wr_data(), .ee_biu_wr_be(),
        .ee_biu_rd_en(), .ee_biu_rd_addr(),
        .ee_biu_rd_data(32'd0), .ee_biu_rd_valid(1'b0),
        .ev_valid(), .ev_subsys(), .ev_event(),
        .ev_arg0(), .ev_arg1(), .ev_arg2(), .ev_arg3(), .ev_flags()
    );

    ee_ram_stub #(.SIZE_BYTES(EE_RAM_BYTES)) u_ee_ram (
        .clk(clk), .rst_n(rst_n),
        .rd_en(ee_ram_rd_en), .rd_addr(ee_ram_rd_addr[EE_RAM_ADDR_W-1:0]),
        .rd_data(ee_ram_rd_data), .rd_valid(ee_ram_rd_valid),
        .wr_en(ee_ram_wr_en), .wr_addr(ee_ram_wr_addr[EE_RAM_ADDR_W-1:0]),
        .wr_data(ee_ram_wr_data), .wr_be(ee_ram_wr_be),
        .master_id(ee_ram_master_id),
        .ev_valid(), .ev_subsys(), .ev_event(),
        .ev_arg0(), .ev_arg1(), .ev_arg2(), .ev_arg3(), .ev_flags()
    );

    bios_rom_stub #(.SIZE_BYTES(BIOS_BYTES)) u_bios (
        .clk(clk), .rst_n(rst_n),
        .rd_en(bios_rd_en), .rd_addr(bios_rd_addr),
        .rd_data(bios_rd_data), .rd_valid(bios_rd_valid),
        .ev_valid(), .ev_subsys(), .ev_event(),
        .ev_arg0(), .ev_arg1(), .ev_arg2(), .ev_arg3(), .ev_flags()
    );

    trace_sink_stub #(.FILENAME("ee_core_bev_core.trace"), .SINK_LABEL("ee_core"))
        u_trace_core (.clk(clk), .rst_n(rst_n),
            .ev_valid(core_ev_valid), .ev_subsys(core_ev_subsys),
            .ev_event(core_ev_event), .ev_arg0(core_ev_arg0),
            .ev_arg1(core_ev_arg1), .ev_arg2(core_ev_arg2),
            .ev_arg3(core_ev_arg3), .ev_flags(core_ev_flags));

    int core_retired_events;
    int core_halt_events;
    int core_trap_events;
    int core_except_events;
    int errors;

    initial begin
        core_retired_events = 0;
        core_halt_events    = 0;
        core_trap_events    = 0;
        core_except_events  = 0;
        errors              = 0;
    end

    always_ff @(posedge clk) begin
        if (rst_n && core_ev_valid) begin
            core_retired_events <= core_retired_events + 1;
            if ((core_ev_flags & 32'h08) != 32'd0)
                core_halt_events <= core_halt_events + 1;
            if ((core_ev_flags & 32'h80) != 32'd0)
                core_trap_events <= core_trap_events + 1;
            if ((core_ev_flags & 32'h20) != 32'd0)
                core_except_events <= core_except_events + 1;
        end
    end

    task automatic bios_word(input int slot, input logic [31:0] word);
        u_bios.mem[slot] = word;
    endtask

    function automatic logic [31:0] enc_i(input logic [5:0] op,
                                          input int rs, input int rt,
                                          input logic [15:0] imm);
        return {op, rs[4:0], rt[4:0], imm};
    endfunction

    function automatic logic [31:0] enc_j(input logic [31:0] target_addr);
        return {OP_J, target_addr[27:2]};
    endfunction

    function automatic logic [15:0] branch_imm(input int branch_slot,
                                               input int target_slot);
        int diff;
        diff = target_slot - branch_slot - 1;
        return diff[15:0];
    endfunction

    function automatic logic [31:0] enc_r(input int rs, input int rt,
                                          input int rd, input int sa,
                                          input logic [5:0] func);
        return {OP_SPECIAL, rs[4:0], rt[4:0], rd[4:0], sa[4:0], func};
    endfunction

    function automatic logic [31:0] enc_mfc0(input int rt, input int rd);
        return {OP_COP0, COP0_RS_MF, rt[4:0], rd[4:0], 11'd0};
    endfunction

    task automatic bios_j(input int slot, input logic [31:0] tgt);
        bios_word(slot, enc_j(tgt));
    endtask
    task automatic bios_nop(input int slot);
        bios_word(slot, 32'd0);
    endtask
    task automatic bios_lui(input int slot, input int rt,
                            input logic [15:0] imm);
        bios_word(slot, enc_i(OP_LUI, 0, rt, imm));
    endtask
    task automatic bios_ori(input int slot, input int rt, input int rs,
                            input logic [15:0] imm);
        bios_word(slot, enc_i(OP_ORI, rs, rt, imm));
    endtask
    task automatic bios_sw(input int slot, input int rt, input int rs,
                           input logic [15:0] offs);
        bios_word(slot, enc_i(OP_SW, rs, rt, offs));
    endtask
    task automatic bios_bne(input int slot, input int rs, input int rt,
                            input int target_slot);
        bios_word(slot, enc_i(OP_BNE, rs, rt,
                              branch_imm(slot, target_slot)));
    endtask
    task automatic bios_mfc0(input int slot, input int rt, input int rd);
        bios_word(slot, enc_mfc0(rt, rd));
    endtask
    task automatic bios_and(input int slot, input int rd, input int rs,
                            input int rt);
        bios_word(slot, enc_r(rs, rt, rd, 0, FUNC_AND));
    endtask
    task automatic bios_syscall(input int slot);
        bios_word(slot, 32'h0000_000C);
    endtask

    initial begin
        rst_n   = 1'b0;
        core_go = 1'b0;

        repeat (4) @(posedge clk);
        rst_n = 1'b1;
        repeat (2) @(posedge clk);

        // Handler at BEV vector (0xBFC0_0380). Four instructions:
        //   mfc0 $16, $8    ; $16 = BadVAddr
        //   mfc0 $17, $14   ; $17 = EPC
        //   mfc0 $18, $13   ; $18 = Cause
        //   syscall         ; halt
        bios_word(BEV_VEC_SLOT + 0, enc_mfc0(16, 8));
        bios_word(BEV_VEC_SLOT + 1, enc_mfc0(17, 14));
        bios_word(BEV_VEC_SLOT + 2, enc_mfc0(18, 13));
        bios_word(BEV_VEC_SLOT + 3, 32'h0000_000C);

        // Reset entry → bootstrap
        bios_j  (RESET_SLOT,     BOOTSTRAP_VA);
        bios_nop(RESET_SLOT + 1);

        // Bootstrap:
        //   1. Verify Status.BEV is set after reset (MFC0 Status, AND
        //      against 0x00400000, branch to FAIL_BEV if not matching).
        //   2. Set up $1 = 0x80000000 (kseg0 base).
        //   3. Misaligned SW → AdES exception → vectors to BEV_VEC.
        // If step 1 failed, step 3 is never reached; if step 3's
        // handler runs at BEV_VEC, we know BEV vector select works.

        bios_lui (B_LUI_1,      1, 16'h8000);            // $1 = 0x80000000
        bios_mfc0(B_MFC0_STAT,  5, 12);                  // $5 = Status
        bios_lui (B_LUI_MASK,   6, 16'h0040);            // $6 = 0x00400000 (bit22)
        bios_and (B_AND_BEV,    7, 5, 6);                // $7 = Status & BEV
        bios_bne (B_BNE_BEV0,   7, 6, B_FAIL_BEV);       // BEV==0 → FAIL
        bios_nop (B_DS_BEV);

        bios_sw  (B_SW_BAD, 1, 1, 16'h0011);             // misaligned SW → AdES
        bios_nop (B_DS_BAD);
        bios_nop (B_NEVER);                               // never reached
        bios_syscall(B_FAIL_BEV);                        // BEV-was-clear path

        @(negedge clk);
        core_go = 1'b1;
        @(negedge clk);
        core_go = 1'b0;

        while (!core_halt) @(posedge clk);
        repeat (4) @(posedge clk);

        // Expected outcome:
        //   - Status.BEV was 1 at reset → AND matched 0x00400000 → no
        //     branch to FAIL_BEV → SW retires → AdES → pc=BEV_VEC →
        //     handler runs MFC0 sequence → syscall halts.
        //   - 0 traps, 1 exception, 1 SYSCALL halt.
        //   - Handler captured BadVAddr=0x80000011, EPC=faulting pc,
        //     Cause.ExcCode=AdES=5.
        //   - Final pc = BEV_VEC + 0xC (the syscall slot in the handler).
        if (core_trap_events != 0) begin
            $error("[tb_ee_core_bev] unexpected trap(s): %0d", core_trap_events);
            errors = errors + 1;
        end
        if (core_except_events != 1) begin
            $error("[tb_ee_core_bev] expected 1 exception, got %0d", core_except_events);
            errors = errors + 1;
        end
        if (core_halt_events != 1) begin
            $error("[tb_ee_core_bev] expected 1 SYSCALL halt, got %0d", core_halt_events);
            errors = errors + 1;
        end
        if (core_pc !== BEV_VEC + 32'h0C) begin
            $error("[tb_ee_core_bev] halt pc mismatch: got 0x%08h expected 0x%08h",
                   core_pc, BEV_VEC + 32'h0C);
            errors = errors + 1;
        end
        if (u_core.regfile[16] !== 32'h8000_0011) begin
            $error("[tb_ee_core_bev] BadVAddr mismatch: got 0x%08h", u_core.regfile[16]);
            errors = errors + 1;
        end
        if (u_core.regfile[17] !== BOOTSTRAP_VA + ((B_SW_BAD - BOOTSTRAP_SLOT) << 2)) begin
            $error("[tb_ee_core_bev] EPC mismatch: got 0x%08h", u_core.regfile[17]);
            errors = errors + 1;
        end
        if (u_core.regfile[18][6:2] !== 5'd5) begin
            $error("[tb_ee_core_bev] Cause.ExcCode mismatch: got %0d expected 5 (AdES)",
                   u_core.regfile[18][6:2]);
            errors = errors + 1;
        end

        $display("[tb_ee_core_bev] retired=%0d halt=%0d except=%0d trap=%0d pc=0x%08h $16=0x%08h $17=0x%08h $18=0x%08h errors=%0d",
                 core_retired_events, core_halt_events,
                 core_except_events, core_trap_events,
                 core_pc, u_core.regfile[16], u_core.regfile[17],
                 u_core.regfile[18], errors);

        if (errors == 0 &&
            core_trap_events == 0 &&
            core_except_events == 1 &&
            core_halt_events == 1 &&
            core_pc == BEV_VEC + 32'h0C &&
            u_core.regfile[16] == 32'h8000_0011 &&
            u_core.regfile[17] == BOOTSTRAP_VA + ((B_SW_BAD - BOOTSTRAP_SLOT) << 2) &&
            u_core.regfile[18][6:2] == 5'd5)
            $display("[tb_ee_core_bev] PASS");
        else
            $display("[tb_ee_core_bev] FAIL");

        $finish;
    end

    initial begin
        #2000000;
        $error("[tb_ee_core_bev] timeout");
        $finish;
    end

endmodule : tb_ee_core_bev
