// retroDE_ps2 — tb_ee_core_basic
//
// First real-decode run on the EE side. Mirrors `tb_iop_core_basic`
// but simpler — this is the EE's "prove fetch+decode+execute+halt
// works from BIOS" chapter, before any EE DMAC / INTC / CPU-side
// LW/SW plumbing. The EE core fetches 32-bit instructions from BIOS
// through `ee_memory_map_stub`'s existing `ee_rd_*` port (the same
// port `ee_fetch_stub` used in the Milestone-B chain).
//
// RAM layout preloaded by the TB via hierarchical reference into
// u_bios.mem:
//   0xBFC0_0000   j  0xBFC0_0100              ; reset entry
//   0xBFC0_0004   nop                          ; delay slot
//   0xBFC0_0008..0x00FF   default NOP sled (bios_rom_stub fixture)
//   0xBFC0_0100+  bootstrap:
//     lui   $1, 0x1234
//     ori   $1, $1, 0x5678                     ; $1 = 0x1234_5678
//     addiu $2, $0, 0x000A                     ; $2 = 10
//     addiu $3, $2, 0xFFF6                     ; $3 = 10 + (-10) = 0
//     beq   $3, $0, halt                       ; taken (0 == 0)
//     nop                                       ; delay slot
//     syscall                                   ; NOT reached (would be
//                                                 fall-through if BEQ
//                                                 missed)
//   halt:
//     syscall                                   ; reached → halt
//
// Explicit purpose of the ADDIU with 0xFFF6: exercises sign-extended
// immediate on the first EE decode run (0xFFF6 = -10). We care about
// getting this right on day one since the bug class ("I forgot to
// sign-extend imm16") is invisible until a real program does
// something with it.
//
// Acceptance:
//   - halt_o asserts exactly once (via the reached SYSCALL)
//   - 9 retires total
//   - 2 taken branches (reset J + BEQ to halt) with 2 matching
//     delay-slot retires (1:1 invariant)
//   - 0 exceptions, 0 traps
//   - every fetch went through the BIOS region of the EE map
//     (region id 0 in the EE map's trace)

`timescale 1ns/1ps

module tb_ee_core_basic;

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

    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;   // 0x40

    // Slots within the bootstrap
    localparam int B_LUI     = BOOTSTRAP_SLOT + 0;
    localparam int B_ORI     = BOOTSTRAP_SLOT + 1;
    localparam int B_ADDIU_A = BOOTSTRAP_SLOT + 2;
    localparam int B_ADDIU_B = BOOTSTRAP_SLOT + 3;
    localparam int B_BEQ     = BOOTSTRAP_SLOT + 4;
    localparam int B_DSLOT   = BOOTSTRAP_SLOT + 5;
    localparam int B_UNREACH = BOOTSTRAP_SLOT + 6;   // SYSCALL not reached
    localparam int B_HALT    = BOOTSTRAP_SLOT + 7;   // SYSCALL halt

    // Opcodes
    localparam logic [5:0] OP_SPECIAL = 6'h00;
    localparam logic [5:0] OP_J       = 6'h02;
    localparam logic [5:0] OP_BEQ     = 6'h04;
    localparam logic [5:0] OP_ADDIU   = 6'h09;
    localparam logic [5:0] OP_ORI     = 6'h0D;
    localparam logic [5:0] OP_LUI     = 6'h0F;

    logic clk;
    logic rst_n;

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

    // ------------------------------------------------------------------
    // EE core (default PC_RESET = 0xBFC0_0000)
    // ------------------------------------------------------------------

    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;   // no INTC wired this chapter

    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 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)
    );

    // ------------------------------------------------------------------
    // EE memory map + EE RAM + shared BIOS ROM
    // ------------------------------------------------------------------

    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;

    logic                ee_map_ev_valid;
    trace_pkg::subsys_e  ee_map_ev_subsys;
    trace_pkg::event_e   ee_map_ev_event;
    logic [63:0]         ee_map_ev_arg0, ee_map_ev_arg1, ee_map_ev_arg2, ee_map_ev_arg3;
    logic [31:0]         ee_map_ev_flags;

    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-read master port — unused by this TB
        .dmac_rd_en(1'b0), .dmac_rd_addr(32'd0),
        .dmac_rd_data(), .dmac_rd_valid(),
        // Bridge write port — unused by this TB
        .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(ee_map_ev_valid), .ev_subsys(ee_map_ev_subsys),
        .ev_event(ee_map_ev_event),
        .ev_arg0(ee_map_ev_arg0), .ev_arg1(ee_map_ev_arg1),
        .ev_arg2(ee_map_ev_arg2), .ev_arg3(ee_map_ev_arg3),
        .ev_flags(ee_map_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 sinks
    // ------------------------------------------------------------------

    trace_sink_stub #(.FILENAME("ee_core_basic_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));

    trace_sink_stub #(.FILENAME("ee_core_basic_map.trace"),
                      .SINK_LABEL("ee_map"))
        u_trace_map (.clk(clk), .rst_n(rst_n),
            .ev_valid(ee_map_ev_valid), .ev_subsys(ee_map_ev_subsys),
            .ev_event(ee_map_ev_event), .ev_arg0(ee_map_ev_arg0),
            .ev_arg1(ee_map_ev_arg1), .ev_arg2(ee_map_ev_arg2),
            .ev_arg3(ee_map_ev_arg3), .ev_flags(ee_map_ev_flags));

    // ------------------------------------------------------------------
    // Observers
    // ------------------------------------------------------------------

    int core_retired_events;
    int core_branch_taken_events;
    int core_halt_events;
    int core_delay_slot_events;
    int core_except_events;
    int core_trap_events;
    int map_bios_reads;
    int errors;

    initial begin
        core_retired_events      = 0;
        core_branch_taken_events = 0;
        core_halt_events         = 0;
        core_delay_slot_events   = 0;
        core_except_events       = 0;
        core_trap_events         = 0;
        map_bios_reads           = 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'h04) != 32'd0)
                core_branch_taken_events <= core_branch_taken_events + 1;
            if ((core_ev_flags & 32'h08) != 32'd0)
                core_halt_events <= core_halt_events + 1;
            if ((core_ev_flags & 32'h10) != 32'd0)
                core_delay_slot_events <= core_delay_slot_events + 1;
            if ((core_ev_flags & 32'h20) != 32'd0)
                core_except_events <= core_except_events + 1;
            if ((core_ev_flags & 32'h80) != 32'd0)
                core_trap_events <= core_trap_events + 1;
        end

        // EE map emits MEM-subsystem events; region id 0 = BIOS.
        if (rst_n && ee_map_ev_valid &&
            ee_map_ev_subsys == trace_pkg::SUBSYS_MEM &&
            ee_map_ev_event  == trace_pkg::EV_READ &&
            ee_map_ev_arg3[7:0] == 8'd0)
            map_bios_reads <= map_bios_reads + 1;
    end

    // ------------------------------------------------------------------
    // BIOS preload helpers (hierarchical reference)
    // ------------------------------------------------------------------

    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

    task automatic bios_j(input int slot, input logic [31:0] target_va);
        bios_word(slot, enc_j(target_va));
    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_addiu(input int slot, input int rt, input int rs,
                              input logic [15:0] imm);
        bios_word(slot, enc_i(OP_ADDIU, rs, rt, imm));
    endtask
    task automatic bios_beq(input int slot, input int rs, input int rt,
                            input int target_slot);
        bios_word(slot, enc_i(OP_BEQ, rs, rt,
                              branch_imm(slot, target_slot)));
    endtask
    task automatic bios_syscall(input int slot);
        bios_word(slot, 32'h0000_000C);
    endtask

    // ------------------------------------------------------------------
    // Stimulus
    // ------------------------------------------------------------------

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

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

        // Reset entry: jump into bootstrap
        bios_j  (RESET_SLOT,     BOOTSTRAP_VA);
        bios_nop(RESET_SLOT + 1);                       // delay slot

        // Bootstrap body — see header comment for operational intent.
        bios_lui  (B_LUI,      1, 16'h1234);           // $1 = 0x1234_0000
        bios_ori  (B_ORI,      1, 1, 16'h5678);        // $1 = 0x1234_5678
        bios_addiu(B_ADDIU_A,  2, 0, 16'h000A);        // $2 = 10
        bios_addiu(B_ADDIU_B,  3, 2, 16'hFFF6);        // $3 = 10 + (-10) = 0
        bios_beq  (B_BEQ,      3, 0, B_HALT);          // taken (0 == 0)
        bios_nop  (B_DSLOT);                            // delay slot
        bios_syscall(B_UNREACH);                        // NOT reached
        bios_syscall(B_HALT);                           // halt here

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

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

        // --------------------------------------------------------------
        // Post-halt checks
        // --------------------------------------------------------------
        if (core_halt_events != 1) begin
            $error("[tb_ee_core_basic] expected 1 halt event, got %0d",
                   core_halt_events);
            errors = errors + 1;
        end
        if (core_retired_events != 9) begin
            $error("[tb_ee_core_basic] expected 9 retires, got %0d",
                   core_retired_events);
            errors = errors + 1;
        end
        if (core_branch_taken_events != 2) begin
            $error("[tb_ee_core_basic] expected 2 taken branches, got %0d",
                   core_branch_taken_events);
            errors = errors + 1;
        end
        if (core_delay_slot_events != core_branch_taken_events) begin
            $error("[tb_ee_core_basic] delay-slot invariant broken: %0d delay vs %0d taken",
                   core_delay_slot_events, core_branch_taken_events);
            errors = errors + 1;
        end
        if (core_except_events != 0) begin
            $error("[tb_ee_core_basic] unexpected exception retires: %0d",
                   core_except_events);
            errors = errors + 1;
        end
        if (core_trap_events != 0) begin
            $error("[tb_ee_core_basic] unexpected strict-trap retires: %0d",
                   core_trap_events);
            errors = errors + 1;
        end
        // Final pc should park at the reached SYSCALL.
        if (core_pc !== BOOTSTRAP_VA + ((B_HALT - BOOTSTRAP_SLOT) << 2)) begin
            $error("[tb_ee_core_basic] final pc mismatch: got 0x%08h expected 0x%08h",
                   core_pc, BOOTSTRAP_VA + ((B_HALT - BOOTSTRAP_SLOT) << 2));
            errors = errors + 1;
        end
        // All 9 retires came from BIOS fetches (reset J + delay NOP +
        // 7 bootstrap ops including the reached SYSCALL). EE map
        // should report at least that many BIOS reads.
        if (map_bios_reads < 9) begin
            $error("[tb_ee_core_basic] expected >=9 BIOS reads, got %0d",
                   map_bios_reads);
            errors = errors + 1;
        end

        $display("[tb_ee_core_basic] retired=%0d taken=%0d delay=%0d halt=%0d except=%0d trap=%0d bios_reads=%0d errors=%0d",
                 core_retired_events, core_branch_taken_events,
                 core_delay_slot_events, core_halt_events,
                 core_except_events, core_trap_events, map_bios_reads,
                 errors);

        if (errors == 0 &&
            core_halt_events         == 1 &&
            core_retired_events      == 9 &&
            core_branch_taken_events == 2 &&
            core_delay_slot_events   == 2)
            $display("[tb_ee_core_basic] PASS");
        else
            $display("[tb_ee_core_basic] FAIL");

        $finish;
    end

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

endmodule : tb_ee_core_basic
