// retroDE_ps2 — tb_gs_demo_psmt4_swizzle_trxdir_e2e (Ch142)
//
// Companion to Ch141 (raster-driven PSMT4 e2e): same EE-bootlet
// → DMAC → GIF data plane and same all-three-gates-on
// instantiation, but the framebuffer is filled by a TRXDIR/IMAGE
// upload through `gif_image_xfer_stub` instead of by raster. The
// Ch139 PSMT4 image-xfer write-side swizzle gate becomes
// LOAD-BEARING inside the demo flow — every nibble the GS
// produces comes out of the image-xfer engine at canonical PSMT4
// swizzled (addr, nibble_hi) slots, and the raster path is
// dormant. Mirrors Ch124's PSMCT32 TRXDIR demo, Ch130's PSMCT16
// TRXDIR demo, and Ch136's PSMT8 TRXDIR demo for the fourth (and
// last) common GS PSM. Ch141 + Ch142 together close the PSMT4
// byte-accuracy milestone end-to-end through the full driver-
// shaped flow — same Ch123+Ch124 (PSMCT32), Ch129+Ch130
// (PSMCT16), and Ch135+Ch136 (PSMT8) shape — completing the
// **four-PSM × three-path × dual-driver-shape e2e foundation**.
//
// Codex framing for Ch142: "TRXDIR-driven PSMT4 swizzled e2e,
// mirroring Ch124/Ch130/Ch136."
//
// Topology (mirrors Ch123 / Ch129 / Ch135 — only the PSM and
// gate parameters differ):
//
//   bios_rom_stub  ── ee_core_stub ─┐
//                                   │
//                          ee_memory_map_stub ─── dmac_reg_stub
//                                   │                  │
//                          ee_gs_priv_bridge_stub      │
//                                   │                  ▼
//                                   ▼      ┌── gif_packed_stub ─→ gif_image_xfer_stub#(PSMT4_SWIZZLE=1)
//                          gs_stub#(PSMT4_SWIZZLE=1) ─┤
//                                   │      └── (image-xfer writes on swizzled PSMT4 nibble slots)
//                                   ▼
//                                vram_stub
//                                   │
//                          gs_pcrtc_stub#(PSMT4_SWIZZLE=1) → r/g/b
//
// What's the same as Ch141:
//   - BIOS-resident EE bootlet at 0xBFC0_0000.
//   - EE program does GS-priv bring-up (DISPFB1 / DISPLAY1 lo /
//     DISPLAY1 hi / PMODE.EN1) THEN DMAC kick (MADR / QWC / CHCR)
//     THEN SYSCALL halt — same Ch113/Ch114 sequence. The DISPFB1
//     immediate is identical (PSM=PSMT4, FBP=0, FBW=2).
//   - DMAC ch2 streams a GIF qword payload from RAM through
//     gif_packed_stub. The down-stream module that consumes it
//     differs (gif_image_xfer_stub instead of gs_stub raster).
//   - All three modules instantiated with PSMT4_SWIZZLE=1 (and
//     PSMCT32_SWIZZLE=0 + PSMCT16_SWIZZLE=0 + PSMT8_SWIZZLE=0).
//     Same per-quadrant nibbles Q0=0xA / Q1=0x4 / Q2=0xC /
//     Q3=0x6 → grayscale 0xAA / 0x44 / 0xCC / 0x66 — the verify
//     side reuses Ch141's per-pixel pattern unchanged.
//   - vram_stub is the storage; gs_pcrtc_stub drives scanout.
//   - DBW must be even for PSMT4 → DBW=2 here (same as PSMT8
//     since both have 128 px-wide pages). The 16×8 image fits
//     inside the upper-left of block (0,0) of page 0 (PSMT4
//     block = 32×16 px); within-block columnTable4 yb=0..7,
//     xb=0..15 covers nibble_idx values [0..127] so the
//     swizzled write set lives in [byte 0..63] of the block.
//     Linear-only separator at byte 128 (linear y=2 row start
//     at PSMT4 stride=64 with FBW=2) stays 0 — same separator
//     as Ch141.
//
// What's new for Ch142:
//   - GIF payload swap: 4 SPRITE PACKED packets (Ch141) → U1
//     PACKED A+D TRX setup + U2 IMAGE NLOOP=N. The Ch139 PSMT4
//     image-xfer gate is now LOAD-BEARING (raster path is
//     dormant). Specifically:
//       - U1: 1 GIFtag (NREG=4, EOP=0) + 4 PACKED A+D dispatches
//         (BITBLTBUF{DBP=0, DBW=2, DPSM=PSMT4} / TRXPOS{DSAX=
//         DSAY=0} / TRXREG{RRW=16, RRH=8} / TRXDIR{XDIR=0=host→
//         local}). The TRXDIR commit pulses gs_stub.trxdir_wr_q,
//         which arms gif_image_xfer_stub. 5 qwords.
//       - U2: 1 GIFtag (FLG=2 IMAGE, NLOOP=4, EOP=1) + 4 IMAGE
//         qwords. Each qword carries 32 PSMT4 nibbles (32
//         px/qword × 4 qwords = 128 PSMT4 pixels). At RRW=16 a
//         qword holds 2 rows: lanes 0..15 = row 2*qi, lanes
//         16..31 = row 2*qi+1 — same packing the focused Ch139
//         image-xfer TB uses. The nibble pattern matches Ch141's
//         per-quadrant tiling so the verify side is unchanged.
//         5 qwords.
//     Total QWC = 10 (= 5 + 5).
//   - DMAC QWC immediate in the EE bootlet drops from 24 to 10.
//   - Counts: trxdir_arms=1 (single TRX setup), xfer_writes=128
//     (one per PSMT4 nibble), raster emits=0 (raster path
//     dormant), giftags=2 (U1 + U2), packed A+D dispatches=4
//     (U1 only — IMAGE qwords don't count as packed A+D).
//   - New per-emit observer on the image-xfer side asserts
//     every xfer_we pulse fires with be=4'b0001 + mask ∈
//     {0x0000_000F, 0x0000_00F0} — the PSMT4 nibble RMW shape
//     (low or high nibble of the targeted byte, keyed by the
//     swizzle's nibble_hi). Different from PSMT8 (mask=0xFFFFFFFF).
//   - The raster-side observer now requires raster_emits_seen=0
//     (dormant); it stays as a dead-path guard requiring CT4
//     shape if raster ever fires (psm=0x14, be=4'b0001).
//   - Verification (mirrors Ch141): (a) full 16×8 scanout frame
//     capture; (b) per-pixel NIBBLE readback at the canonical
//     swizzled (addr, nibble_hi) slot via vram_stub's 2nd port,
//     using addr[1:0]-keyed byte selection then nibble_hi-keyed
//     nibble selection. Both modules instantiate the same
//     gs_swizzle_psmt4_stub (and use its nibble_hi output for
//     the nibble selector), so a successful match proves the
//     write side and read side agree at nibble level even when
//     the framebuffer fill comes from real-shape DMAC-delivered
//     IMAGE qwords parsed by gif_packed_stub (rather than from
//     raster).
//
// PASS criteria:
//   - 1 EV_DMA_START / 10 EV_DMA_BEAT / 1 EV_DMA_DONE (5 + 5 = 10).
//   - 2 GIFtag accepts (U1 + U2); 4 PACKED A+D dispatches (U1).
//   - 4 EE-CPU MMIO writes the map decoded as GS-priv (PMODE +
//     DISPFB1 + DISPLAY1 ×2); 4 corresponding gs_stub.reg_wr_*
//     fires from the bridge.
//   - 3 EE-CPU MMIO writes the map decoded as DMAC ch2 (MADR +
//     QWC + CHCR), in that exact (offset, data) order.
//   - trxdir_arms_seen=1 (one TRXDIR commit arms image-xfer).
//   - 128 image-xfer VRAM writes (one per PSMT4 nibble), all
//     with be=4'b0001, mask ∈ {0x0F, 0xF0}.
//   - 0 raster_pixel_emit pulses (raster path dormant).
//   - core_halt asserts exactly once (SYSCALL halt), no trap.
//   - Captured 16×8 frame: each pixel matches its quadrant's
//     nibble (PCRTC PSMT4 grayscale r=g=b={nibble, nibble}).
//   - Per-pixel nibble readback at swizzled (addr, nibble_hi)
//     matches the quadrant's expected nibble (same per-quadrant
//     pattern as Ch141).
//   - Strict separator at byte 128 stays 0.
//   - Default-off TBs unchanged: this is a NEW TB; existing
//     demos all keep their parameter defaults.


`timescale 1ns/1ps

module tb_gs_demo_psmt4_swizzle_trxdir_e2e;

    localparam int PCRTC_H_ACTIVE  = 16;
    localparam int PCRTC_V_ACTIVE  = 8;
    // RAM holds the GIF payload (0x100..0x33F). EE program no
    // longer lives here (Ch114 moved it to BIOS ROM — see below).
    // 4 KiB is enough.
    localparam int RAM_SIZE_BYTES  = 4 * 1024;
    localparam int RAM_ADDR_W      = $clog2(RAM_SIZE_BYTES);

    // Ch114 — EE program lives in BIOS ROM (kseg1 0xBFC00000),
    // NOT in RAM. With a RAM-resident program, EE instruction
    // fetches contend with DMAC GIF-payload reads through the
    // single-ported ee_ram_stub (the map's arbitration gives CPU
    // priority and silently corrupts DMAC data). Putting the
    // program in BIOS makes the EE fetch path go through
    // `bios_rd_*` / `bios_rom_stub` — a different physical
    // memory unit — so EE and DMAC can run truly in parallel.
    // This also matches real PS2: the EE boots out of BIOS ROM.
    localparam int          BIOS_SIZE_BYTES = 4 * 1024;
    localparam int          BIOS_ADDR_W     = $clog2(BIOS_SIZE_BYTES);
    localparam logic [31:0] EE_PROG_VA      = 32'hBFC0_0000;

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

    // ----------------------------------------------------------------
    // ee_ram_stub
    // ----------------------------------------------------------------
    logic                  ram_rd_en;
    logic [RAM_ADDR_W-1:0] ram_rd_addr;
    logic [127:0]          ram_rd_data;
    logic                  ram_rd_valid;
    logic                  ram_wr_en;
    logic [RAM_ADDR_W-1:0] ram_wr_addr;
    logic [127:0]          ram_wr_data;
    logic [15:0]           ram_wr_be;
    logic [7:0]            ram_master_id;

    ee_ram_stub #(.SIZE_BYTES(RAM_SIZE_BYTES)) u_ram (
        .clk(clk), .rst_n(rst_n),
        .rd_en(ram_rd_en), .rd_addr(ram_rd_addr),
        .rd_data(ram_rd_data), .rd_valid(ram_rd_valid),
        .wr_en(ram_wr_en), .wr_addr(ram_wr_addr),
        .wr_data(ram_wr_data), .wr_be(ram_wr_be),
        .master_id(ram_master_id),
        .ev_valid(), .ev_subsys(), .ev_event(),
        .ev_arg0(), .ev_arg1(), .ev_arg2(), .ev_arg3(), .ev_flags()
    );
    assign ram_master_id = ram_rd_en ? 8'd1 : 8'd0;

    // ----------------------------------------------------------------
    // bios_rom_stub (Ch114) — holds the EE bootlet at
    // 0xBFC0_0000 / phys 0x1FC0_0000. Wired to the map's
    // bios_rd_* port so EE instruction fetches go through here,
    // NOT through ee_ram_stub. That decouples EE-CPU from the
    // DMAC's RAM read traffic — both run truly in parallel.
    // ----------------------------------------------------------------
    logic                   bios_rd_en;
    logic [BIOS_ADDR_W-1:0] bios_rd_addr_full;
    logic                   bios_rd_valid;
    logic [31:0]            bios_rd_data;
    // The map drives `bios_rd_addr` as a [21:0] byte offset; trim
    // to the BIOS's address width.
    logic [21:0]            bios_rd_addr;
    assign bios_rd_addr_full = bios_rd_addr[BIOS_ADDR_W-1:0];

    bios_rom_stub #(.SIZE_BYTES(BIOS_SIZE_BYTES)) u_bios (
        .clk(clk), .rst_n(rst_n),
        .rd_en(bios_rd_en),
        .rd_addr(bios_rd_addr_full),
        .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()
    );

    // ----------------------------------------------------------------
    // DMAC + memory map. Ch114 — DMAC reg writes are now driven
    // by the EE-CPU through ee_memory_map_stub's DMAC-ch2 decode
    // (`ee_dmac_ch2_wr_*` outputs), NOT by the TB directly. The
    // signals below are wired through the map.
    // ----------------------------------------------------------------
    logic        dmac_reg_wr_en;
    logic [7:0]  dmac_reg_offset;
    logic [31:0] dmac_reg_wr_data;
    logic        dmac_mem_rd_en;
    logic [31:0] dmac_mem_rd_addr;
    logic         dmac_gif_valid;
    logic [127:0] dmac_gif_data;
    logic         dmac_gif_last;
    logic         dmac_gif_ready;          // = gif_in_ready (xfer backpressure flows through gif_packed_stub.image_data_ready in S_IMAGE only — Ch110)

    logic                dmac_ev_valid;
    trace_pkg::subsys_e  dmac_ev_subsys;
    trace_pkg::event_e   dmac_ev_event;
    logic [63:0]         dmac_ev_arg0, dmac_ev_arg1, dmac_ev_arg2, dmac_ev_arg3;
    logic [31:0]         dmac_ev_flags;

    logic [127:0] map_to_dmac_rd_data;
    logic         map_to_dmac_rd_valid;

    dmac_reg_stub u_dmac (
        .clk(clk), .rst_n(rst_n),
        .reg_wr_en(dmac_reg_wr_en), .reg_offset(dmac_reg_offset),
        .reg_wr_data(dmac_reg_wr_data),
        .reg_rd_en(1'b0), .reg_rd_data(), .reg_rd_valid(),
        .mem_rd_en(dmac_mem_rd_en), .mem_rd_addr(dmac_mem_rd_addr),
        .mem_rd_data(map_to_dmac_rd_data), .mem_rd_valid(map_to_dmac_rd_valid),
        .ep_valid(dmac_gif_valid), .ep_data(dmac_gif_data),
        .ep_last(dmac_gif_last), .ep_ready(dmac_gif_ready),
        .irq_completion_o(),
        .ev_valid(dmac_ev_valid), .ev_subsys(dmac_ev_subsys),
        .ev_event(dmac_ev_event),
        .ev_arg0(dmac_ev_arg0), .ev_arg1(dmac_ev_arg1),
        .ev_arg2(dmac_ev_arg2), .ev_arg3(dmac_ev_arg3),
        .ev_flags(dmac_ev_flags)
    );

    logic         map_ram_rd_en;
    logic [24:0]  map_ram_rd_addr;

    // Ch113 — EE-CPU instruction stream surface into
    // ee_memory_map_stub. ee_core_stub now produces the EE-side
    // reads (instruction fetches) and writes (the SW
    // instructions targeting 0x1200_xxxx). The map's GS-priv
    // decode peels those writes out and routes them to the
    // bridge below.
    logic        ee_cpu_rd_en;
    logic [31:0] ee_cpu_rd_addr;
    logic [31:0] ee_cpu_rd_data;
    logic        ee_cpu_rd_valid;
    logic        ee_cpu_wr_en;
    logic [31:0] ee_cpu_wr_addr;
    logic [31:0] ee_cpu_wr_data;
    logic [3:0]  ee_cpu_wr_be;

    // Outputs of the map's GS-priv decode (Ch112).
    logic        map_gs_priv_wr_en;
    logic [15:0] map_gs_priv_wr_addr;
    logic [31:0] map_gs_priv_wr_data;
    logic [3:0]  map_gs_priv_wr_be;

    // Map trace stream (Ch112-audit observer).
    logic                map_ev_valid;
    trace_pkg::subsys_e  map_ev_subsys;
    trace_pkg::event_e   map_ev_event;
    logic [63:0]         map_ev_arg0, map_ev_arg1, map_ev_arg2, map_ev_arg3;
    logic [31:0]         map_ev_flags;

    ee_memory_map_stub u_map (
        .clk(clk), .rst_n(rst_n),
        .ee_rd_en  (ee_cpu_rd_en),
        .ee_rd_addr(ee_cpu_rd_addr),
        .ee_rd_data(ee_cpu_rd_data),
        .ee_rd_valid(ee_cpu_rd_valid),
        .ee_wr_en  (ee_cpu_wr_en),
        .ee_wr_addr(ee_cpu_wr_addr),
        .ee_wr_data(ee_cpu_wr_data),
        .ee_wr_be  (ee_cpu_wr_be),
        .dmac_rd_en(dmac_mem_rd_en), .dmac_rd_addr(dmac_mem_rd_addr),
        .dmac_rd_data(map_to_dmac_rd_data),
        .dmac_rd_valid(map_to_dmac_rd_valid),
        .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(map_ram_rd_en), .ram_rd_addr(map_ram_rd_addr),
        .ram_rd_data(ram_rd_data), .ram_rd_valid(ram_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),
        .ram_wr_en(), .ram_wr_addr(), .ram_wr_data(),
        .ram_wr_be(), .ram_master_id(),
        .ee_dmac_ch2_wr_en  (dmac_reg_wr_en),
        .ee_dmac_ch2_wr_addr(dmac_reg_offset),
        .ee_dmac_ch2_wr_data(dmac_reg_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),
        .ee_gs_priv_wr_en  (map_gs_priv_wr_en),
        .ee_gs_priv_wr_addr(map_gs_priv_wr_addr),
        .ee_gs_priv_wr_data(map_gs_priv_wr_data),
        .ee_gs_priv_wr_be  (map_gs_priv_wr_be),
        .ev_valid (map_ev_valid),
        .ev_subsys(map_ev_subsys),
        .ev_event (map_ev_event),
        .ev_arg0  (map_ev_arg0),
        .ev_arg1  (map_ev_arg1),
        .ev_arg2  (map_ev_arg2),
        .ev_arg3  (map_ev_arg3),
        .ev_flags (map_ev_flags)
    );

    assign ram_rd_en   = map_ram_rd_en;
    assign ram_rd_addr = map_ram_rd_addr[RAM_ADDR_W-1:0];

    // ----------------------------------------------------------------
    // Ch113 — ee_core_stub. Fetches MIPS instructions from RAM via
    // ee_memory_map_stub.ee_rd_*; SW instructions write through
    // ee_memory_map_stub.ee_wr_*. The 4 control-plane SWs target
    // 0x1200_xxxx and are routed to ee_gs_priv_bridge_stub by the
    // map's GS-priv decode (Ch112).
    // ----------------------------------------------------------------
    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        core_cpu_irq;
    assign core_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 #(
        .PC_RESET(EE_PROG_VA),
        .STRICT_UNSUPPORTED(1'b0)
    ) u_core (
        .clk(clk), .rst_n(rst_n),
        .go_i(core_go),
        .map_rd_en (ee_cpu_rd_en),
        .map_rd_addr(ee_cpu_rd_addr),
        .map_rd_data(ee_cpu_rd_data),
        .map_rd_valid(ee_cpu_rd_valid),
        .map_wr_en (ee_cpu_wr_en),
        .map_wr_addr(ee_cpu_wr_addr),
        .map_wr_data(ee_cpu_wr_data),
        .map_wr_be (ee_cpu_wr_be),
        .cpu_irq(core_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)
    );

    // ----------------------------------------------------------------
    // gif_packed_stub — REAL_AD_REG_MAP=1
    // ----------------------------------------------------------------
    logic         gif_in_ready;
    logic         gif_gs_wr_en;
    logic [15:0]  gif_gs_wr_addr;
    logic [63:0]  gif_gs_wr_data;
    logic         gif_gif_reg_wr_en;
    logic [7:0]   gif_gif_reg_num;
    logic [63:0]  gif_gif_reg_data;
    logic         gif_image_data_valid;
    logic [127:0] gif_image_data;
    logic         gif_image_data_last;
    // Forward declaration so u_gif can read it. The signal is
    // driven by gif_image_xfer_stub instantiated further down.
    logic         xfer_data_ready;

    logic                gif_ev_valid;
    trace_pkg::subsys_e  gif_ev_subsys;
    trace_pkg::event_e   gif_ev_event;
    logic [63:0]         gif_ev_arg0, gif_ev_arg1, gif_ev_arg2, gif_ev_arg3;
    logic [31:0]         gif_ev_flags;

    gif_packed_stub #(.REAL_AD_REG_MAP(1'b1)) u_gif (
        .clk(clk), .rst_n(rst_n),
        .in_valid(dmac_gif_valid), .in_data(dmac_gif_data),
        .in_last(dmac_gif_last), .in_ready(gif_in_ready),
        .image_data_valid(gif_image_data_valid),
        .image_data(gif_image_data),
        .image_data_last(gif_image_data_last),
        .image_data_ready(xfer_data_ready),
        .raster_fifo_full(1'b0),
        .gs_wr_en(gif_gs_wr_en), .gs_wr_addr(gif_gs_wr_addr),
        .gs_wr_data(gif_gs_wr_data),
        .gif_reg_wr_en(gif_gif_reg_wr_en),
        .gif_reg_num(gif_gif_reg_num),
        .gif_reg_data(gif_gif_reg_data),
        .ev_valid(gif_ev_valid), .ev_subsys(gif_ev_subsys),
        .ev_event(gif_ev_event),
        .ev_arg0(gif_ev_arg0), .ev_arg1(gif_ev_arg1),
        .ev_arg2(gif_ev_arg2), .ev_arg3(gif_ev_arg3),
        .ev_flags(gif_ev_flags)
    );

    // ----------------------------------------------------------------
    // gs_stub
    // ----------------------------------------------------------------
    // Ch112 — Bridge outputs: 64-bit gs_stub.reg_wr_* drives. The
    // TB no longer declares its own ee_priv_wr_* port; instead it
    // drives ee_cpu_wr_* (declared at the u_map instantiation
    // above) with full 32-bit phys addresses targeting
    // 0x1200_xxxx, and the map's GS-priv decode hands those
    // through to the bridge.
    logic        priv_reg_wr_en;
    logic [15:0] priv_reg_wr_addr;
    logic [63:0] priv_reg_wr_data;

    logic [7:0]          bg_r, bg_g, bg_b;
    logic [63:0]         pmode_q, dispfb1_q, display1_q;
    logic [63:0]         prim_q, rgbaq_q, xyz2_q, xyzf2_q, frame_1_q, zbuf_1_q;
    logic [63:0]         tex0_1_q;
    logic [13:0]         tex0_1_cbp_q;
    logic [3:0]          tex0_1_cpsm_q;
    logic                tex0_1_csm_q;
    logic [4:0]          tex0_1_csa_q;
    logic [2:0]          tex0_1_cld_q;
    logic                tex0_1_wr_q;
    logic [63:0]         bitbltbuf_q, trxpos_q, trxreg_q, trxdir_q;
    logic                trxdir_wr_q;
    logic                prim_complete;
    logic [31:0]         prim_complete_count;
    logic [63:0]         prim_v0_q, prim_v1_q, prim_v2_q;
    logic [63:0]         prim_color_q;
    logic [63:0]         prim_color_v0_q, prim_color_v1_q, prim_color_v2_q;
    trace_pkg::vertex_t  prim_v0_decoded_q, prim_v1_decoded_q, prim_v2_decoded_q;
    trace_pkg::color_t   prim_v0_color_decoded_q, prim_v1_color_decoded_q, prim_v2_color_decoded_q;
    logic                pixel_emit;
    logic [31:0]         pixel_emit_count;
    logic [11:0]         pixel_x_q, pixel_y_q;
    logic [63:0]         pixel_color_q;
    logic [8:0]          pixel_fbp_q;
    logic [5:0]          pixel_fbw_q, pixel_psm_q;
    logic [31:0]         pixel_fb_addr_q;
    logic                raster_pixel_emit;
    logic [31:0]         raster_pixel_emit_count;
    logic [11:0]         raster_pixel_x_q, raster_pixel_y_q;
    logic [63:0]         raster_pixel_color_q;
    logic [31:0]         raster_pixel_fb_addr_q;
    logic [3:0]          raster_pixel_be_q;
    logic [31:0]         raster_pixel_mask_q;
    logic [5:0]          raster_pixel_psm_q;
    logic                raster_active;
    logic                raster_overflow;
    logic                raster_degenerate;
    logic                gs_ev_valid;
    trace_pkg::subsys_e  gs_ev_subsys;
    trace_pkg::event_e   gs_ev_event;
    logic [63:0]         gs_ev_arg0, gs_ev_arg1, gs_ev_arg2, gs_ev_arg3;
    logic [31:0]         gs_ev_flags;

    gs_stub #(
        .PSMCT32_SWIZZLE(1'b0),
        .PSMCT16_SWIZZLE(1'b0),
        .PSMT8_SWIZZLE  (1'b0),
        .PSMT4_SWIZZLE  (1'b1)
    ) u_gs (
        .clk(clk), .rst_n(rst_n),
        .reg_wr_en  (priv_reg_wr_en),
        .reg_wr_addr(priv_reg_wr_addr),
        .reg_wr_data(priv_reg_wr_data),
        .gif_reg_wr_en(gif_gif_reg_wr_en),
        .gif_reg_num  (gif_gif_reg_num),
        .gif_reg_data (gif_gif_reg_data),
        .bg_r(bg_r), .bg_g(bg_g), .bg_b(bg_b),
        .pmode_q(pmode_q), .dispfb1_q(dispfb1_q), .display1_q(display1_q),
        .prim_q(prim_q), .rgbaq_q(rgbaq_q),
        .xyz2_q(xyz2_q), .xyzf2_q(xyzf2_q),
        .frame_1_q(frame_1_q), .zbuf_1_q(zbuf_1_q),
        .tex0_1_q(tex0_1_q),
        .tex0_1_cbp_q(tex0_1_cbp_q),
        .tex0_1_cpsm_q(tex0_1_cpsm_q),
        .tex0_1_csm_q(tex0_1_csm_q),
        .tex0_1_csa_q(tex0_1_csa_q),
        .tex0_1_cld_q(tex0_1_cld_q),
        .tex0_1_wr_q(tex0_1_wr_q),
        .bitbltbuf_q(bitbltbuf_q),
        .trxpos_q(trxpos_q),
        .trxreg_q(trxreg_q),
        .trxdir_q(trxdir_q),
        .trxdir_wr_q(trxdir_wr_q),
        .prim_complete(prim_complete),
        .prim_complete_count(prim_complete_count),
        .prim_v0_q(prim_v0_q), .prim_v1_q(prim_v1_q), .prim_v2_q(prim_v2_q),
        .prim_color_q(prim_color_q),
        .prim_color_v0_q(prim_color_v0_q),
        .prim_color_v1_q(prim_color_v1_q),
        .prim_color_v2_q(prim_color_v2_q),
        .prim_v0_decoded_q(prim_v0_decoded_q),
        .prim_v1_decoded_q(prim_v1_decoded_q),
        .prim_v2_decoded_q(prim_v2_decoded_q),
        .prim_v0_color_decoded_q(prim_v0_color_decoded_q),
        .prim_v1_color_decoded_q(prim_v1_color_decoded_q),
        .prim_v2_color_decoded_q(prim_v2_color_decoded_q),
        .pixel_emit(pixel_emit),
        .pixel_emit_count(pixel_emit_count),
        .pixel_x_q(pixel_x_q), .pixel_y_q(pixel_y_q),
        .pixel_color_q(pixel_color_q),
        .pixel_fbp_q(pixel_fbp_q),
        .pixel_fbw_q(pixel_fbw_q),
        .pixel_psm_q(pixel_psm_q),
        .pixel_fb_addr_q(pixel_fb_addr_q),
        .raster_pixel_emit(raster_pixel_emit),
        .raster_pixel_emit_count(raster_pixel_emit_count),
        .raster_pixel_x_q(raster_pixel_x_q),
        .raster_pixel_y_q(raster_pixel_y_q),
        .raster_pixel_color_q(raster_pixel_color_q),
        .raster_pixel_fb_addr_q(raster_pixel_fb_addr_q),
        .raster_pixel_be_q(raster_pixel_be_q),
        .raster_pixel_mask_q(raster_pixel_mask_q),
        .raster_pixel_psm_q(raster_pixel_psm_q),
        .raster_active(raster_active),
        .raster_overflow(raster_overflow),
        .raster_degenerate(raster_degenerate),
        .ev_valid(gs_ev_valid),
        .ev_subsys(gs_ev_subsys),
        .ev_event(gs_ev_event),
        .ev_arg0(gs_ev_arg0), .ev_arg1(gs_ev_arg1),
        .ev_arg2(gs_ev_arg2), .ev_arg3(gs_ev_arg3),
        .ev_flags(gs_ev_flags)
    );

    // ----------------------------------------------------------------
    // Ch111 — ee_gs_priv_bridge_stub: EE-side 32-bit MMIO writes
    // get accumulated per 8-byte slot and fired as 64-bit
    // gs_stub.reg_wr_* pulses. Replaces the Ch110 TB-direct
    // drive_priv() path; the demo's data plane (TRXDIR/IMAGE
    // palette upload + GIF primitive stream) is unchanged.
    // ----------------------------------------------------------------
    ee_gs_priv_bridge_stub u_priv_bridge (
        .clk(clk), .rst_n(rst_n),
        // Ch112 — bridge inputs now come from ee_memory_map_stub's
        // GS-priv decode, not TB-direct. The TB drives ee_cpu_wr_*
        // (above) with full 32-bit phys addresses targeting
        // 0x1200_xxxx; the map peels the 16-bit window offset and
        // hands it to the bridge here.
        .ee_wr_en  (map_gs_priv_wr_en),
        .ee_wr_addr(map_gs_priv_wr_addr),
        .ee_wr_data(map_gs_priv_wr_data),
        .ee_wr_be  (map_gs_priv_wr_be),
        .gs_reg_wr_en  (priv_reg_wr_en),
        .gs_reg_wr_addr(priv_reg_wr_addr),
        .gs_reg_wr_data(priv_reg_wr_data)
    );

    // ----------------------------------------------------------------
    // gif_image_xfer_stub (xfer_data_ready is forward-declared
    // earlier so u_gif can read it as image_data_ready).
    // ----------------------------------------------------------------
    logic        xfer_we;
    logic [31:0] xfer_waddr;
    logic [31:0] xfer_wdata;
    logic [3:0]  xfer_wbe;
    logic [31:0] xfer_wmask;
    logic        xfer_busy;

    gif_image_xfer_stub #(
        .PSMCT32_SWIZZLE(1'b0),
        .PSMCT16_SWIZZLE(1'b0),
        .PSMT8_SWIZZLE  (1'b0),
        .PSMT4_SWIZZLE  (1'b1)
    ) u_xfer (
        .clk(clk), .rst_n(rst_n),
        .trxdir_wr_pulse(trxdir_wr_q),
        .trxdir(trxdir_q),
        .bitbltbuf(bitbltbuf_q),
        .trxpos(trxpos_q),
        .trxreg(trxreg_q),
        .data_valid(gif_image_data_valid),
        .data_qword(gif_image_data),
        .data_last (gif_image_data_last),
        .data_ready(xfer_data_ready),
        .vram_we   (xfer_we),
        .vram_waddr(xfer_waddr),
        .vram_wdata(xfer_wdata),
        .vram_wbe  (xfer_wbe),
        .vram_wmask(xfer_wmask),
        .busy      (xfer_busy)
    );

    // DMAC ready follows gif_packed_stub's in_ready directly.
    // gif_packed_stub already gates in_ready by xfer_data_ready
    // when state == S_IMAGE (Ch110), so xfer backpressure
    // propagates upstream via gif_packed_stub. Outside S_IMAGE
    // (e.g., between SPRITE GIFtags), in_ready stays high and the
    // DMAC streams freely — even if xfer is still draining the
    // tail of a previous IMAGE qword's lanes.
    assign dmac_gif_ready = gif_in_ready;

    // ----------------------------------------------------------------
    // VRAM mux: xfer-OWNED when xfer.busy, raster-OWNED otherwise.
    // (Sequenced: palette upload finishes before sprites start.)
    // ----------------------------------------------------------------
    logic        vram_we_mux;
    logic [31:0] vram_waddr_mux;
    logic [31:0] vram_wdata_mux;
    logic [3:0]  vram_wbe_mux;
    logic [31:0] vram_wmask_mux;

    assign vram_we_mux    = xfer_busy ? xfer_we    : raster_pixel_emit;
    assign vram_waddr_mux = xfer_busy ? xfer_waddr : raster_pixel_fb_addr_q;
    assign vram_wdata_mux = xfer_busy ? xfer_wdata : raster_pixel_color_q[31:0];
    assign vram_wbe_mux   = xfer_busy ? xfer_wbe   : raster_pixel_be_q;
    assign vram_wmask_mux = xfer_busy ? xfer_wmask : raster_pixel_mask_q;

    // Defensive collision check: assert xfer and raster never fire
    // the same cycle.
    int collision_count;
    initial collision_count = 0;
    always_ff @(posedge clk) begin
        if (rst_n && xfer_we && raster_pixel_emit) begin
            $error("xfer + raster fired same cycle (sequencing bug)");
            collision_count <= collision_count + 1;
        end
    end

    logic [31:0] vram_raddr;
    logic [31:0] vram_rdata;
    logic [31:0] vram_raddr2;
    logic [31:0] vram_rdata2;

    vram_stub #(.BYTES(8192)) u_vram (
        .clk(clk), .rst_n(rst_n),
        .write_en  (vram_we_mux),
        .write_addr(vram_waddr_mux),
        .write_data(vram_wdata_mux),
        .write_be  (vram_wbe_mux),
        .write_mask(vram_wmask_mux),
        .read_addr (vram_raddr),
        .read_data (vram_rdata),
        .read2_addr(vram_raddr2),
        .read2_data(vram_rdata2)
    );

    // CLUT + loader.
    // Ch129 — no CLUT path. The PSMCT16 framebuffer is direct-color,
    // so clut_stub / clut_loader_stub aren't instantiated and the
    // 2nd VRAM read port (vram_raddr2 / vram_rdata2) is FREED for
    // Phase 2 byte readback in the TB body. Tie loader status off
    // so the legacy `wait (loader_busy)` and counter assertions
    // work without the loader instance.
    logic loader_busy;
    assign loader_busy = 1'b0;

    // PCRTC.
    logic       hsync_o, vsync_o, de_o;
    logic [7:0] r_o, g_o, b_o;
    logic                pcrtc_ev_valid;
    trace_pkg::subsys_e  pcrtc_ev_subsys;
    trace_pkg::event_e   pcrtc_ev_event;
    logic [63:0]         pcrtc_ev_arg0, pcrtc_ev_arg1;
    logic [63:0]         pcrtc_ev_arg2, pcrtc_ev_arg3;
    logic [31:0]         pcrtc_ev_flags;

    gs_pcrtc_stub #(
        .H_ACTIVE(PCRTC_H_ACTIVE), .H_FRONT(1), .H_SYNC(1), .H_BACK(1),
        .V_ACTIVE(PCRTC_V_ACTIVE), .V_FRONT(1), .V_SYNC(1), .V_BACK(1),
        .PSMCT32_SWIZZLE(1'b0),
        .PSMCT16_SWIZZLE(1'b0),
        .PSMT8_SWIZZLE  (1'b0),
        .PSMT4_SWIZZLE  (1'b1)
    ) u_pcrtc (
        .clk(clk), .rst_n(rst_n),
        .pmode_q       (pmode_q),
        .dispfb1_q     (dispfb1_q),
        .display1_q    (display1_q),
        .vram_read_addr(vram_raddr),
        .vram_read_data(vram_rdata),
        .clut_enable   (1'b0),
        .clut_csa      (5'd0),
        .clut_read_idx (),
        .clut_read_data(32'd0),
        .hsync(hsync_o), .vsync(vsync_o), .de(de_o),
        .r(r_o), .g(g_o), .b(b_o),
        .ev_valid(pcrtc_ev_valid),
        .ev_subsys(pcrtc_ev_subsys),
        .ev_event(pcrtc_ev_event),
        .ev_arg0(pcrtc_ev_arg0), .ev_arg1(pcrtc_ev_arg1),
        .ev_arg2(pcrtc_ev_arg2), .ev_arg3(pcrtc_ev_arg3),
        .ev_flags(pcrtc_ev_flags)
    );

    // ----------------------------------------------------------------
    // Capture + observers.
    // ----------------------------------------------------------------
    logic [7:0] cap_r [0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    logic [7:0] cap_g [0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    logic [7:0] cap_b [0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    logic       cap_de[0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];

    int  errors;
    int  loader_starts;
    int  raster_emits_seen;
    int  giftag_seen;
    int  packed_ad_writes_seen;
    int  xfer_writes_seen;
    int  trxdir_arms_seen;       // Ch136 — pulses on trxdir_wr_q
    int  ee_priv_writes_seen;
    int  priv_bridge_fires_seen;
    int  ee_dmac_writes_seen;     // Ch114 — EE-driven DMAC reg writes
    // Ch114-audit-low — lock the EXACT DMAC reg-write sequence
    // (offset/data/order). Expected:
    //   #0 : MADR (offset 0x10) = PAYLOAD_MADR
    //   #1 : QWC  (offset 0x20) = QWC_TOTAL
    //   #2 : CHCR (offset 0x00) = 0x0000_0001 (start)
    int  dmac_seq_idx;
    int  dmac_seq_errors;
    logic [7:0]  dmac_expected_off  [0:2];
    logic [31:0] dmac_expected_data [0:2];
    int  map_gs_priv_traces_seen;
    int  map_unmapped_traces_seen;
    int  dma_start_count, dma_beat_count, dma_done_count;
    bit  capture_armed;
    bit  dma_done_seen;

    initial begin
        for (int y = 0; y < PCRTC_V_ACTIVE; y++)
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                cap_r[y][x]  = 8'd0;
                cap_g[y][x]  = 8'd0;
                cap_b[y][x]  = 8'd0;
                cap_de[y][x] = 1'b0;
            end
        errors                = 0;
        loader_starts          = 0;
        raster_emits_seen     = 0;
        giftag_seen            = 0;
        packed_ad_writes_seen  = 0;
        xfer_writes_seen       = 0;
        trxdir_arms_seen       = 0;
        ee_priv_writes_seen      = 0;
        priv_bridge_fires_seen   = 0;
        ee_dmac_writes_seen      = 0;
        dmac_seq_idx             = 0;
        dmac_seq_errors          = 0;
        dmac_expected_off [0]    = 8'h10;          // MADR
        dmac_expected_data[0]    = PAYLOAD_MADR;
        dmac_expected_off [1]    = 8'h20;          // QWC
        dmac_expected_data[1]    = 32'(QWC_TOTAL);
        dmac_expected_off [2]    = 8'h00;          // CHCR.start
        dmac_expected_data[2]    = 32'h0000_0001;
        map_gs_priv_traces_seen  = 0;
        map_unmapped_traces_seen = 0;
        dma_start_count       = 0;
        dma_beat_count        = 0;
        dma_done_count        = 0;
        capture_armed         = 1'b0;
        dma_done_seen         = 1'b0;
    end

    always_ff @(posedge clk) begin
        if (rst_n && capture_armed && de_o
            && (u_pcrtc.vcnt < PCRTC_V_ACTIVE)
            && (u_pcrtc.hcnt < PCRTC_H_ACTIVE)) begin
            cap_r [u_pcrtc.vcnt][u_pcrtc.hcnt] <= r_o;
            cap_g [u_pcrtc.vcnt][u_pcrtc.hcnt] <= g_o;
            cap_b [u_pcrtc.vcnt][u_pcrtc.hcnt] <= b_o;
            cap_de[u_pcrtc.vcnt][u_pcrtc.hcnt] <= 1'b1;
        end
    end

    always_ff @(posedge clk) begin
        if (rst_n && dmac_ev_valid) begin
            unique case (dmac_ev_event)
                trace_pkg::EV_DMA_START: dma_start_count <= dma_start_count + 1;
                trace_pkg::EV_DMA_BEAT:  dma_beat_count  <= dma_beat_count  + 1;
                trace_pkg::EV_DMA_DONE: begin
                    dma_done_count <= dma_done_count + 1;
                    dma_done_seen  <= 1'b1;
                end
                default: ;
            endcase
        end
    end

    always_ff @(posedge clk) begin
        if (rst_n && gif_ev_valid && gif_ev_event == trace_pkg::EV_GIFTAG)
            giftag_seen <= giftag_seen + 1;
    end

    always_ff @(posedge clk) begin
        if (rst_n && gif_gif_reg_wr_en)
            packed_ad_writes_seen <= packed_ad_writes_seen + 1;
        if (rst_n && trxdir_wr_q)
            trxdir_arms_seen <= trxdir_arms_seen + 1;
        if (rst_n && xfer_we) begin
            xfer_writes_seen <= xfer_writes_seen + 1;
            // Ch142 — every image-xfer emit is PSMT4: be=4'b0001
            // (low-byte commit) plus a per-bit mask of either
            // 0x0000_000F (low nibble) or 0x0000_00F0 (high nibble),
            // keyed by the swizzle's nibble_hi output. Different
            // from PSMT8 (mask=0xFFFFFFFF) and PSMCT16 (be=4'b0011).
            if (xfer_wbe !== 4'b0001) begin
                $error("xfer write %0d: be=%b (expected 4'b0001 for PSMT4)",
                       xfer_writes_seen, xfer_wbe);
                errors <= errors + 1;
            end
            if (xfer_wmask !== 32'h0000_000F && xfer_wmask !== 32'h0000_00F0) begin
                $error("xfer write %0d: mask=0x%08x (expected 0x0000000F or 0x000000F0 for PSMT4 nibble)",
                       xfer_writes_seen, xfer_wmask);
                errors <= errors + 1;
            end
        end
        // Counts EE-CPU MMIO writes that the map decoded as
        // GS-priv (i.e., reached the bridge). Equals the number
        // of `ee_priv_write32` calls the program issued.
        if (rst_n && map_gs_priv_wr_en)
            ee_priv_writes_seen <= ee_priv_writes_seen + 1;
        if (rst_n && priv_reg_wr_en)
            priv_bridge_fires_seen <= priv_bridge_fires_seen + 1;
        // Ch114 — EE-CPU `sw` to DMAC ch2 reg window. Incremented
        // by every EE-driven MADR/QWC/CHCR write. Ch114-audit-low:
        // also locks the EXACT (offset, data) sequence so a future
        // accidental aliasing (wrong offset or wrong data flowing
        // into the same dmac_reg_stub port) fails explicitly.
        if (rst_n && dmac_reg_wr_en) begin
            ee_dmac_writes_seen <= ee_dmac_writes_seen + 1;
            if (dmac_seq_idx < 3) begin
                if (dmac_reg_offset !== dmac_expected_off[dmac_seq_idx]) begin
                    $error("DMAC write %0d: offset=0x%02x (expected 0x%02x)",
                           dmac_seq_idx, dmac_reg_offset,
                           dmac_expected_off[dmac_seq_idx]);
                    dmac_seq_errors <= dmac_seq_errors + 1;
                end
                if (dmac_reg_wr_data !== dmac_expected_data[dmac_seq_idx]) begin
                    $error("DMAC write %0d: data=0x%08x (expected 0x%08x)",
                           dmac_seq_idx, dmac_reg_wr_data,
                           dmac_expected_data[dmac_seq_idx]);
                    dmac_seq_errors <= dmac_seq_errors + 1;
                end
                dmac_seq_idx <= dmac_seq_idx + 1;
            end else begin
                $error("DMAC write %0d: unexpected extra (offset=0x%02x data=0x%08x)",
                       dmac_seq_idx, dmac_reg_offset, dmac_reg_wr_data);
                dmac_seq_errors <= dmac_seq_errors + 1;
            end
        end
    end

    // Ch112-audit observer: every EE-CPU write that the map sees
    // for the GS-priv window MUST be classified as REGION_EE_GS_PRIV
    // in the trace, NOT as REGION_UNMAPPED. This is the trace-side
    // counterpart to the ee_gs_priv_wr_en routing — without the
    // Ch112-audit trace branch, valid 0x1200_xxxx writes would
    // surface to consumers as EV_UNMAPPED.
    //
    // REGION_EE_GS_PRIV = 64'd12, REGION_UNMAPPED = 64'hFF (per
    // ee_memory_map_stub.sv).
    always_ff @(posedge clk) begin
        if (rst_n && map_ev_valid && (map_ev_subsys == trace_pkg::SUBSYS_MEM)) begin
            // Filter to EE-CPU write events at the 0x1200_xxxx
            // window (arg0 carries ee_wr_addr; flags[0]=1 marks
            // a write).
            if (map_ev_flags[0] && map_ev_arg0[31:16] == 16'h1200) begin
                if (map_ev_event == trace_pkg::EV_WRITE
                    && map_ev_arg3 == 64'd12) begin
                    map_gs_priv_traces_seen <= map_gs_priv_traces_seen + 1;
                end else if (map_ev_event == trace_pkg::EV_UNMAPPED) begin
                    $error("EE-CPU write to 0x%08x classified as UNMAPPED (expected REGION_EE_GS_PRIV)",
                           map_ev_arg0[31:0]);
                    map_unmapped_traces_seen <= map_unmapped_traces_seen + 1;
                end
            end
        end
    end

    logic loader_busy_d;
    always_ff @(posedge clk) begin
        if (!rst_n) loader_busy_d <= 1'b0;
        else begin
            loader_busy_d <= loader_busy;
            if (loader_busy && !loader_busy_d)
                loader_starts <= loader_starts + 1;
        end
    end

    always_ff @(posedge clk) begin
        if (rst_n && raster_pixel_emit) begin
            raster_emits_seen <= raster_emits_seen + 1;
            // Ch142 — raster path must remain dormant in this
            // TRXDIR-driven demo (raster_emits_seen is asserted
            // == 0 below). If raster ever fires, this dead-path
            // guard at minimum requires it to be CT4-shaped:
            // PSM=0x14, be=4'b0001 (low byte) + mask 0x0F or
            // 0xF0 (Ch106 PSMT4 nibble RMW shape).
            if (raster_pixel_psm_q !== 6'h14) begin
                $error("emit %0d: psm=0x%02x (expected 0x14 PSMT4)",
                       raster_emits_seen, raster_pixel_psm_q);
                errors <= errors + 1;
            end
            if (raster_pixel_be_q !== 4'b0001) begin
                $error("emit %0d: be=%b (expected 4'b0001 for PSMT4)",
                       raster_emits_seen, raster_pixel_be_q);
                errors <= errors + 1;
            end
            if (raster_pixel_mask_q !== 32'h0000_000F && raster_pixel_mask_q !== 32'h0000_00F0) begin
                $error("emit %0d: mask=0x%08x (expected 0x0000000F or 0x000000F0)",
                       raster_emits_seen, raster_pixel_mask_q);
                errors <= errors + 1;
            end
        end
    end

    // ----------------------------------------------------------------
    // Helpers.
    // ----------------------------------------------------------------
    // Ch114 — DMAC reg writes now flow through ee_memory_map_stub
    // from EE-CPU `sw` instructions; no TB-direct write_dmac
    // task. No sync-flag poll needed either: the EE program
    // halts via SYSCALL right after kicking the DMAC, so EE and
    // DMAC don't contend for RAM after that point.

    task automatic preload_qword(input logic [RAM_ADDR_W-1:0] addr,
                                 input logic [127:0] data);
        @(negedge clk);
        ram_wr_en   = 1'b1;
        ram_wr_addr = addr;
        ram_wr_data = data;
        ram_wr_be   = 16'hFFFF;
        @(negedge clk);
        ram_wr_en   = 1'b0;
        ram_wr_addr = '0;
        ram_wr_data = 128'd0;
        ram_wr_be   = 16'd0;
    endtask

    // ----------------------------------------------------------------
    // Ch114 — EE-program preload helpers. Writes 32-bit MIPS
    // instruction words into bios_rom_stub.mem[] via hierarchical
    // ref. bios_rom_stub.mem is a flat 32-bit-word array indexed
    // by (byte_offset >> 2). Slot 0 corresponds to phys
    // 0x1FC0_0000 / kseg1 0xBFC0_0000 — the EE reset vector.
    // ----------------------------------------------------------------
    task automatic ee_prog_word(input int byte_off, input logic [31:0] word);
        int slot;
        slot = byte_off >> 2;
        u_bios.mem[slot] = word;
    endtask

    // MIPS encoding helpers. Opcodes match ee_core_stub's localparams.
    function automatic logic [31:0] enc_lui(input int rt, input logic [15:0] imm);
        return {6'h0F, 5'd0, rt[4:0], imm};
    endfunction
    function automatic logic [31:0] enc_ori(input int rt, input int rs,
                                            input logic [15:0] imm);
        return {6'h0D, rs[4:0], rt[4:0], imm};
    endfunction
    function automatic logic [31:0] enc_sw(input int rt, input int rs,
                                           input logic [15:0] imm);
        return {6'h2B, rs[4:0], rt[4:0], imm};
    endfunction
    // Ch114 — LW for the sync-flag poll, BEQ for the loop-back.
    function automatic logic [31:0] enc_lw(input int rt, input int rs,
                                           input logic [15:0] imm);
        return {6'h23, rs[4:0], rt[4:0], imm};
    endfunction
    function automatic logic [31:0] enc_beq(input int rs, input int rt,
                                            input logic signed [15:0] imm);
        return {6'h04, rs[4:0], rt[4:0], imm[15:0]};
    endfunction
    function automatic logic [31:0] enc_syscall();
        return 32'h0000_000C;
    endfunction

    function automatic logic [127:0] giftag(
        input logic [14:0] nloop,
        input logic        eop,
        input logic [1:0]  flg,
        input logic [3:0]  nreg,
        input logic [63:0] regs);
        logic [63:0] lower;
        lower = {nreg, flg, 42'd0, eop, nloop};
        return {regs, lower};
    endfunction

    function automatic logic [127:0] aplusd(input logic [7:0]  reg_num,
                                            input logic [63:0] data64);
        return {56'd0, reg_num, data64};
    endfunction

    function automatic logic [63:0] xyz2_data(input logic [11:0] x_int,
                                              input logic [11:0] y_int);
        return {32'd0, y_int, 4'd0, x_int, 4'd0};
    endfunction

    // Ch142 — restored from Ch130/Ch124/Ch136 (raster-driven Ch141
    // had these scrubbed). U1 (TRX setup) carries BITBLTBUF /
    // TRXPOS / TRXREG / TRXDIR; U2 (IMAGE) carries the PSMT4
    // nibble-packed payload (32 nibbles per qword).
    function automatic logic [63:0] bitbltbuf_pack(
        input logic [13:0] dbp_v,
        input logic [5:0]  dbw_v,
        input logic [5:0]  dpsm_v);
        logic [63:0] v;
        v = 64'd0;
        v[45:32] = dbp_v;
        v[53:48] = dbw_v;
        v[61:56] = dpsm_v;
        return v;
    endfunction
    function automatic logic [63:0] trxpos_pack(
        input logic [10:0] dsax_v,
        input logic [10:0] dsay_v);
        logic [63:0] v;
        v = 64'd0;
        v[42:32] = dsax_v;
        v[58:48] = dsay_v;
        return v;
    endfunction
    function automatic logic [63:0] trxreg_pack(
        input logic [11:0] rrw_v,
        input logic [11:0] rrh_v);
        logic [63:0] v;
        v = 64'd0;
        v[11:0]  = rrw_v;
        v[43:32] = rrh_v;
        return v;
    endfunction
    function automatic logic [63:0] trxdir_pack(input logic [1:0] xdir_v);
        return {62'd0, xdir_v};
    endfunction

    // Maps (x, y) ∈ 16×8 active area to its sprite index 0..3:
    //   spr 0 = top-left  (0,0)..(7,3)
    //   spr 1 = top-right (8,0)..(15,3)
    //   spr 2 = bot-left  (0,4)..(7,7)
    //   spr 3 = bot-right (8,4)..(15,7)
    function automatic int quadrant_idx(input int x, input int y);
        int qx, qy;
        qx = (x < 8) ? 0 : 1;
        qy = (y < 4) ? 0 : 1;
        return qy * 2 + qx;
    endfunction

    // ------------------------------------------------------------
    // Per-quadrant PSMT4 nibble table. PSMT4 raster (Ch106) takes
    // RGBAQ.R[3:0] as the nibble that hits VRAM via the existing
    // nibble-RMW machinery (write_be=4'b0001 + write_mask 0x0F or
    // 0xF0 keyed on swizzle's nibble_hi for Ch140). PCRTC's PSMT4
    // path with `clut_enable=0` (Ch103 grayscale fallback)
    // surfaces the nibble as r=g=b={n, n} at scanout, so the
    // captured 8-bit RGB IS {nibble, nibble}.
    //
    // Pick four quadrant nibbles spread across [0x0..0xF] so a
    // misrouted pixel surfaces as a distinct grayscale value
    // (matches Ch141's per-quadrant pattern verbatim — the verify
    // side is identical even though Ch142's data plane is TRXDIR-
    // driven instead of raster-driven):
    //   Quadrant 0 (TL): nibble 0xA → grayscale 0xAA
    //   Quadrant 1 (TR): nibble 0x4 → grayscale 0x44
    //   Quadrant 2 (BL): nibble 0xC → grayscale 0xCC
    //   Quadrant 3 (BR): nibble 0x6 → grayscale 0x66
    //
    // Ch142's TRXDIR-driven payload writes the nibble into VRAM
    // directly via the IMAGE qword stream (not via raster's R[3:0]
    // path), so spr_r_at returns the nibble in the low 4 bits. The
    // upper 4 bits are a don't-care (image-xfer engine drops them).
    // ------------------------------------------------------------
    function automatic logic [7:0] spr_r_at(input int idx);
        case (idx)
            0: return 8'h0A;
            1: return 8'h04;
            2: return 8'h0C;
            default: return 8'h06;
        endcase
    endfunction
    function automatic logic [7:0] spr_g_at(input int idx);
        // PSMT4 image-xfer ignores G/B/A — return 0 for all quadrants.
        return 8'h00;
    endfunction
    function automatic logic [7:0] spr_b_at(input int idx);
        return 8'h00;
    endfunction
    function automatic logic [7:0] spr_a_at(input int idx);
        return 8'h00;
    endfunction

    // PSMT4 nibble stored in VRAM = R[3:0] of RGBAQ.
    function automatic logic [3:0] expected_nibble(input int idx);
        logic [7:0] r8;
        r8 = spr_r_at(idx);
        return r8[3:0];
    endfunction

    // PCRTC PSMT4 grayscale fallback: r=g=b={nibble, nibble}.
    function automatic logic [7:0] expected_gray(input int idx);
        logic [3:0] n;
        n = expected_nibble(idx);
        return {n, n};
    endfunction

    // ------------------------------------------------------------
    // PSMT4 swizzle reference — block + column tables verbatim
    // from PCSX2 (Ch137 source-locked). Used by the Phase 2
    // nibble-readback to compute where a given (x, y) should land
    // in VRAM (returns both the byte address and the nibble_hi
    // selector since PSMT4 packs 2 pixels per byte and the
    // canonical column table reorders nibbles within a block).
    // ------------------------------------------------------------
    function automatic int ref_block_idx4(input int by, input int bx);
        case ({by[2:0], bx[1:0]})
            5'd0:  return  0;  5'd1:  return  2;  5'd2:  return  8;  5'd3:  return 10;
            5'd4:  return  1;  5'd5:  return  3;  5'd6:  return  9;  5'd7:  return 11;
            5'd8:  return  4;  5'd9:  return  6;  5'd10: return 12;  5'd11: return 14;
            5'd12: return  5;  5'd13: return  7;  5'd14: return 13;  5'd15: return 15;
            5'd16: return 16;  5'd17: return 18;  5'd18: return 24;  5'd19: return 26;
            5'd20: return 17;  5'd21: return 19;  5'd22: return 25;  5'd23: return 27;
            5'd24: return 20;  5'd25: return 22;  5'd26: return 28;  5'd27: return 30;
            5'd28: return 21;  5'd29: return 23;  5'd30: return 29;  default: return 31;
        endcase
    endfunction
    // PSMT4 columnTable4 — only the rows touched by the 16×8
    // image at FBP=0/FBW=2 are needed: yb=0..7, xb=0..15. PSMT4
    // block is 32×16 px so yb=0..7 covers the upper half and
    // xb=0..15 covers the left half of block (0,0) at page (0,0).
    // Verbatim from PCSX2 GSTables.cpp lines 149..181 (same table
    // Ch141 uses).
    function automatic int ref_col_idx4(input int yb, input int xb);
        case ({yb[3:0], xb[4:0]})
            // yb=0
            9'd0:   return   0; 9'd1:   return   8; 9'd2:   return  32; 9'd3:   return  40;
            9'd4:   return  64; 9'd5:   return  72; 9'd6:   return  96; 9'd7:   return 104;
            9'd8:   return   2; 9'd9:   return  10; 9'd10:  return  34; 9'd11:  return  42;
            9'd12:  return  66; 9'd13:  return  74; 9'd14:  return  98; 9'd15:  return 106;
            // yb=1
            9'd32:  return  16; 9'd33:  return  24; 9'd34:  return  48; 9'd35:  return  56;
            9'd36:  return  80; 9'd37:  return  88; 9'd38:  return 112; 9'd39:  return 120;
            9'd40:  return  18; 9'd41:  return  26; 9'd42:  return  50; 9'd43:  return  58;
            9'd44:  return  82; 9'd45:  return  90; 9'd46:  return 114; 9'd47:  return 122;
            // yb=2
            9'd64:  return  65; 9'd65:  return  73; 9'd66:  return  97; 9'd67:  return 105;
            9'd68:  return   1; 9'd69:  return   9; 9'd70:  return  33; 9'd71:  return  41;
            9'd72:  return  67; 9'd73:  return  75; 9'd74:  return  99; 9'd75:  return 107;
            9'd76:  return   3; 9'd77:  return  11; 9'd78:  return  35; 9'd79:  return  43;
            // yb=3
            9'd96:  return  81; 9'd97:  return  89; 9'd98:  return 113; 9'd99:  return 121;
            9'd100: return  17; 9'd101: return  25; 9'd102: return  49; 9'd103: return  57;
            9'd104: return  83; 9'd105: return  91; 9'd106: return 115; 9'd107: return 123;
            9'd108: return  19; 9'd109: return  27; 9'd110: return  51; 9'd111: return  59;
            // yb=4
            9'd128: return 192; 9'd129: return 200; 9'd130: return 224; 9'd131: return 232;
            9'd132: return 128; 9'd133: return 136; 9'd134: return 160; 9'd135: return 168;
            9'd136: return 194; 9'd137: return 202; 9'd138: return 226; 9'd139: return 234;
            9'd140: return 130; 9'd141: return 138; 9'd142: return 162; 9'd143: return 170;
            // yb=5
            9'd160: return 208; 9'd161: return 216; 9'd162: return 240; 9'd163: return 248;
            9'd164: return 144; 9'd165: return 152; 9'd166: return 176; 9'd167: return 184;
            9'd168: return 210; 9'd169: return 218; 9'd170: return 242; 9'd171: return 250;
            9'd172: return 146; 9'd173: return 154; 9'd174: return 178; 9'd175: return 186;
            // yb=6
            9'd192: return 129; 9'd193: return 137; 9'd194: return 161; 9'd195: return 169;
            9'd196: return 193; 9'd197: return 201; 9'd198: return 225; 9'd199: return 233;
            9'd200: return 131; 9'd201: return 139; 9'd202: return 163; 9'd203: return 171;
            9'd204: return 195; 9'd205: return 203; 9'd206: return 227; 9'd207: return 235;
            // yb=7
            9'd224: return 145; 9'd225: return 153; 9'd226: return 177; 9'd227: return 185;
            9'd228: return 209; 9'd229: return 217; 9'd230: return 241; 9'd231: return 249;
            9'd232: return 147; 9'd233: return 155; 9'd234: return 179; 9'd235: return 187;
            9'd236: return 211; 9'd237: return 219; 9'd238: return 243; 9'd239: return 251;
            default: return 0;
        endcase
    endfunction

    typedef struct packed {
        logic [31:0] addr;
        logic        nibble_hi;
    } psmt4_pos_t;

    function automatic psmt4_pos_t ref_pos_psmt4(
        input int fbp_v, input int fbw_v, input int x_v, input int y_v);
        psmt4_pos_t r;
        int page_x, page_y, bw_pg_v, page_idx, page_base;
        int by, bx, blk_idx, xb, yb, nibble_idx;
        int addr_v;
        page_x   = x_v / 128;
        page_y   = y_v / 128;
        bw_pg_v  = fbw_v / 2;
        page_idx = page_y * bw_pg_v + page_x;
        page_base = fbp_v * 2048 + page_idx * 8192;
        by  = (y_v % 128) / 16;
        bx  = (x_v % 128) / 32;
        blk_idx = ref_block_idx4(by, bx);
        xb = x_v % 32;
        yb = y_v % 16;
        nibble_idx = ref_col_idx4(yb, xb);
        addr_v = page_base + blk_idx * 256 + (nibble_idx >> 1);
        r.addr      = addr_v[31:0];
        r.nibble_hi = 1'(nibble_idx & 1);
        return r;
    endfunction

    // ----------------------------------------------------------------
    // Constants.
    // ----------------------------------------------------------------
    // GIF A+D register numbers used by the U1 PACKED A+D TRX
    // setup. R_PRIM / R_RGBAQ / R_XYZ2 / R_FRAME_1 are unused in
    // the TRXDIR-driven demo but kept for symmetry with the
    // raster-driven sibling (Ch141) and to avoid churning the
    // unrelated DISPFB1 / DISPLAY1 / PMODE bring-up.
    localparam logic [7:0] R_PRIM      = 8'h00;
    localparam logic [7:0] R_RGBAQ     = 8'h01;
    localparam logic [7:0] R_XYZ2      = 8'h05;
    localparam logic [7:0] R_FRAME_1   = 8'h4C;
    localparam logic [7:0] R_BITBLTBUF = 8'h50;
    localparam logic [7:0] R_TRXPOS    = 8'h51;
    localparam logic [7:0] R_TRXREG    = 8'h52;
    localparam logic [7:0] R_TRXDIR    = 8'h53;

    // PSMT4 image geometry. RRW × RRH = 16 × 8 = 128 px = 64 bytes
    // (0.5 byte/px). 32 PSMT4 px/qword → 128 / 32 = 4 IMAGE qwords.
    localparam int IMG_W      = 16;
    localparam int IMG_H      = 8;
    localparam int IMG_PIXELS = IMG_W * IMG_H;       // 128
    localparam int IMG_QWORDS = IMG_PIXELS / 32;     // 4

    localparam logic [63:0] PRIM_SPRITE     = 64'd6;
    // FRAME_1: FBP[8:0]=0, FBW[5:0]=2 (at bit 16), PSM=PSMT4(0x14 at bit 24).
    // PSMT4 needs DBW even (PCSX2 asserts (bw & 1) == 0 because
    // PSMT4 pages are 128 px wide vs FBW's 64-px units, same as
    // PSMT8), so FBW=2.
    //   FBW=2 → bits[21:16]=0x02 → 0x0002_0000.
    //   PSM=0x14 → bits[29:24]=0x14 → 0x1400_0000.
    localparam logic [63:0] FRAME_1_PSMT4 = 64'h0000_0000_1402_0000;

    localparam logic [15:0] PMODE_OFF    = 16'h0000;
    localparam logic [15:0] DISPFB1_OFF  = 16'h0070;
    localparam logic [15:0] DISPLAY1_OFF = 16'h0080;

    // CLUT-driven PSMT4 scanout uses TEX0_1.CLD path (Ch99..Ch102);
    // this Ch142 demo uses the Ch103 PSMT4 grayscale fallback
    // (clut_enable=0) so no CLUT setup is needed — the image-xfer-
    // emit nibble surfaces directly as r=g=b={n,n} at scanout.
    // A CLUT-driven Ch142 variant would be a future chapter.

    // DISPFB1: FBP[8:0]=0, FBW[5:0]=2 @bit 9, PSM=PSMT4(=0x14) @bit 15.
    //   FBW=2 → bits[14:9]=0x02 → 0x0400.
    //   PSM=0x14 → bits[19:15]=0x14 → 0xA_0000.
    localparam logic [63:0] DISPFB1_VAL  = 64'h0000_0000_000A_0400;
    localparam logic [63:0] DISPLAY1_VAL =
          (64'(PCRTC_H_ACTIVE - 1) << 32)
        | (64'(PCRTC_V_ACTIVE - 1) << 44);
    localparam logic [63:0] PMODE_EN1    = 64'h0000_0000_0000_0001;

    localparam logic [7:0] CHCR_OFF = 8'h00;
    localparam logic [7:0] MADR_OFF = 8'h10;
    localparam logic [7:0] QWC_OFF  = 8'h20;

    localparam logic [31:0] PAYLOAD_MADR = 32'h0000_0100;
    // Ch142 — QWC_TOTAL = U1 (5 qwords: 1 GIFtag + 4 PACKED A+D
    //                      BITBLTBUF/TRXPOS/TRXREG/TRXDIR)
    //                   + U2 (5 qwords: 1 GIFtag + 4 IMAGE qwords
    //                      carrying 32 PSMT4 nibbles each).
    localparam int          QWC_TOTAL    = 10;

    initial begin
        rst_n             = 1'b0;
        core_go           = 1'b0;
        ram_wr_en         = 1'b0;
        ram_wr_addr       = '0;
        ram_wr_data       = 128'd0;
        ram_wr_be         = 16'd0;

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

        // ------------------------------------------------------------
        // Preload the GIF payload into ee_ram_stub.
        //   U1 (TRX setup, PACKED A+D NREG=4 EOP=0): 1 GIFtag + 4
        //       A+D dispatches (BITBLTBUF / TRXPOS / TRXREG / TRXDIR).
        //       Total 5 qwords.
        //   U2 (IMAGE FLG=2, NLOOP=4 EOP=1): 1 GIFtag + 4 IMAGE
        //       qwords (each 32 PSMT4 nibbles). Total 5 qwords.
        //   QWC_TOTAL = 10.
        // ------------------------------------------------------------
        begin : preload_block
            int q;
            logic [31:0]           addr_full;
            logic [RAM_ADDR_W-1:0] addr_q;

            // PSMT4 quadrant nibbles reused from Ch141 (and tied
            // to the verify-side `expected_nibble(idx)` so the
            // verify pattern stays in lockstep with the source
            // pattern).
            //   Q0 (TL): 0xA   Q1 (TR): 0x4
            //   Q2 (BL): 0xC   Q3 (BR): 0x6

            q = 0;

            // ---------------------------------------------------------
            // U1: PACKED A+D NREG=4 EOP=0 — TRX setup.
            //   GIFtag: NLOOP=1, EOP=0, PRE=0, PRIM=0, FLG=0=PACKED,
            //           NREG=4, REGS = {A+D, A+D, A+D, A+D} = 4×0xE.
            //   REGS lower 64 bits = {52'd0, 4'hE, 4'hE, 4'hE, 4'hE}
            //                      = 0x0000_0000_0000_EEEE.
            // ---------------------------------------------------------
            addr_full = PAYLOAD_MADR + 32'(q * 16);
            addr_q    = addr_full[RAM_ADDR_W-1:0];
            preload_qword(addr_q, giftag(15'd1, 1'b0, 2'd0, 4'd4,
                                         64'h0000_0000_0000_EEEE));
            q = q + 1;
            // BITBLTBUF: DBP=0, DBW=2, DPSM=PSMT4 (0x14).
            addr_full = PAYLOAD_MADR + 32'(q * 16);
            addr_q    = addr_full[RAM_ADDR_W-1:0];
            preload_qword(addr_q, aplusd(R_BITBLTBUF,
                                         bitbltbuf_pack(14'd0, 6'd2, 6'h14)));
            q = q + 1;
            // TRXPOS: DSAX=DSAY=0.
            addr_full = PAYLOAD_MADR + 32'(q * 16);
            addr_q    = addr_full[RAM_ADDR_W-1:0];
            preload_qword(addr_q, aplusd(R_TRXPOS,
                                         trxpos_pack(11'd0, 11'd0)));
            q = q + 1;
            // TRXREG: RRW=16, RRH=8.
            addr_full = PAYLOAD_MADR + 32'(q * 16);
            addr_q    = addr_full[RAM_ADDR_W-1:0];
            preload_qword(addr_q, aplusd(R_TRXREG,
                                         trxreg_pack(12'(IMG_W), 12'(IMG_H))));
            q = q + 1;
            // TRXDIR: XDIR=0 (host→local). This commit pulses
            // gs_stub.trxdir_wr_q, arming gif_image_xfer_stub.
            addr_full = PAYLOAD_MADR + 32'(q * 16);
            addr_q    = addr_full[RAM_ADDR_W-1:0];
            preload_qword(addr_q, aplusd(R_TRXDIR,
                                         trxdir_pack(2'd0)));
            q = q + 1;

            // ---------------------------------------------------------
            // U2: IMAGE FLG=2 NLOOP=4 EOP=1 — 4 qwords, each carries
            // 32 PSMT4 nibbles. At RRW=16 each qword holds 2 rows:
            // lanes 0..15 = row 2*qi, lanes 16..31 = row 2*qi+1
            // (same packing the focused Ch139 image-xfer TB uses).
            // Pixel nibble = quadrant_idx(x, y) → expected_nibble()
            // (the same per-quadrant pattern Ch141 uses).
            //
            // GIFtag: NLOOP=IMG_QWORDS=4, EOP=1, PRE=0, PRIM=0,
            //         FLG=2=IMAGE, NREG=0 (ignored for IMAGE).
            // ---------------------------------------------------------
            addr_full = PAYLOAD_MADR + 32'(q * 16);
            addr_q    = addr_full[RAM_ADDR_W-1:0];
            preload_qword(addr_q, giftag(15'(IMG_QWORDS), 1'b1, 2'd2, 4'd0,
                                         64'h0000_0000_0000_0000));
            q = q + 1;

            // 4 IMAGE qwords, each carrying 32 PSMT4 nibbles
            // (2 rows × 16 pixels).
            for (int qi = 0; qi < IMG_QWORDS; qi++) begin
                logic [127:0] qw;
                qw = 128'd0;
                for (int i = 0; i < IMG_W; i++) begin
                    qw[(i +  0)*4 +: 4] = expected_nibble(quadrant_idx(i, 2*qi));
                    qw[(i + 16)*4 +: 4] = expected_nibble(quadrant_idx(i, 2*qi + 1));
                end
                addr_full = PAYLOAD_MADR + 32'(q * 16);
                addr_q    = addr_full[RAM_ADDR_W-1:0];
                preload_qword(addr_q, qw);
                q = q + 1;
            end

            if (q != QWC_TOTAL)
                $error("preload count mismatch: q=%0d expected %0d", q, QWC_TOTAL);
        end

        // ------------------------------------------------------------
        // Ch114 — EE-program preload. The full bootlet runs from
        // 0xBFC0_0000 (BIOS reset vector) and does both halves
        // of the bring-up: GS-priv writes first (DISPFB1, DISPLAY1
        // lo/hi, PMODE.EN1 last) — these are MMIO writes that
        // don't touch RAM, so no DMAC contention — then DMAC kick
        // (MADR, QWC, CHCR), then SYSCALL halt. After the SYSCALL
        // EE stops fetching → DMAC has unimpeded RAM access for
        // the rest of the transfer.
        //
        // Note on PMODE.EN1 ordering: programmed BEFORE the DMAC
        // kick so the EE-side write order remains
        // DISPFB1→DISPLAY1→PMODE.EN1 (the Ch111 driver-shaped
        // sequence). Real hardware would briefly enable scanout
        // with empty VRAM during DMA — our test's frame capture
        // happens AFTER the data plane settles, so the
        // intermediate state isn't observed.
        // ------------------------------------------------------------
        begin : preload_ee_program
            int off;
            off = 0;
            // --- GS-priv bring-up (Ch111 order, PMODE last) ---
            // r1 = 0x1200_0000 (GS-priv base).
            ee_prog_word(off       , enc_lui(1, 16'h1200));
            // r2 = 0x000A_0400 (DISPFB1: PSM=PSMT4(0x14), FBP=0,
            // FBW=2). PSMT4 also requires FBW even (PCSX2 asserts
            // (bw & 1) == 0 because PSMT4 pages are 128 px wide).
            //   FBW=2 → bits[14:9]=0x02 → 0x0400
            //   PSM=0x14 → bits[19:15]=0x14 → 0xA_0000
            ee_prog_word(off  +  4 , enc_lui(2, 16'h000A));
            ee_prog_word(off  +  8 , enc_ori(2, 2, 16'h0400));
            // SW DISPFB1.
            ee_prog_word(off  + 12 , enc_sw (2, 1, 16'h0070));
            // SW DISPLAY1 lo = 0.
            ee_prog_word(off  + 16 , enc_sw (0, 1, 16'h0080));
            // r2 = 0x700F (DISPLAY1 hi: DH=7, DW=15).
            ee_prog_word(off  + 20 , enc_ori(2, 0, 16'h700F));
            // SW DISPLAY1 hi.
            ee_prog_word(off  + 24 , enc_sw (2, 1, 16'h0084));
            // r2 = 0x0001 (PMODE.EN1).
            ee_prog_word(off  + 28 , enc_ori(2, 0, 16'h0001));
            // SW PMODE.EN1 — programmed last among GS-priv writes.
            ee_prog_word(off  + 32 , enc_sw (2, 1, 16'h0000));

            // --- DMAC bring-up (Ch114) ---
            // r10 = 0x1000_A000 (DMAC ch2 base).
            ee_prog_word(off  + 36 , enc_lui(10, 16'h1000));
            ee_prog_word(off  + 40 , enc_ori(10, 10, 16'hA000));
            // r11 = MADR = phys 0x100 (GIF payload).
            ee_prog_word(off  + 44 , enc_ori(11, 0, 16'(PAYLOAD_MADR)));
            // SW r11, 0x10(r10) — MADR.
            ee_prog_word(off  + 48 , enc_sw (11, 10, 16'h0010));
            // r11 = QWC = QWC_TOTAL = 10 (U1 5 + U2 5 = 10 qwords).
            ee_prog_word(off  + 52 , enc_ori(11, 0, 16'(QWC_TOTAL)));
            // SW r11, 0x20(r10) — QWC.
            ee_prog_word(off  + 56 , enc_sw (11, 10, 16'h0020));
            // r11 = CHCR.start = 1.
            ee_prog_word(off  + 60 , enc_ori(11, 0, 16'h0001));
            // SW r11, 0x00(r10) — CHCR (kicks DMA).
            ee_prog_word(off  + 64 , enc_sw (11, 10, 16'h0000));

            // --- Halt ---
            ee_prog_word(off  + 68 , enc_syscall());
        end

        // Pulse core_go to start the EE bootlet. The EE will run
        // the full bring-up sequence (GS-priv writes + DMAC kick),
        // then SYSCALL halt. After halt, EE stops fetching → DMAC
        // has unimpeded RAM access for the rest of the transfer.
        @(negedge clk);
        core_go = 1'b1;
        @(negedge clk);
        core_go = 1'b0;

        // Wait for the EE to halt (SYSCALL → halt_o). At this
        // point the DMAC has been kicked and is running.
        wait (core_halt == 1'b1);
        repeat (4) @(posedge clk);

        // Wait for the data plane to settle.
        wait (dma_done_seen == 1'b1);
        repeat (10) @(posedge clk);
        if (xfer_busy == 1'b1)
            wait (xfer_busy == 1'b0);
        if (raster_active == 1'b1)
            wait (raster_active == 1'b0);
        if (loader_busy == 1'b1)
            wait (loader_busy == 1'b0);
        repeat (10) @(posedge clk);

        @(posedge u_pcrtc.end_of_frame);
        @(posedge clk);
        capture_armed = 1'b1;
        @(posedge u_pcrtc.end_of_frame);
        @(posedge clk);
        capture_armed = 1'b0;

        // ------------------------------------------------------------
        // Phase 1 — scanout frame assertion. Every (x, y) in the
        // 16×8 active area should read back its quadrant's nibble
        // as PSMT4 grayscale r=g=b={n,n} via PCRTC's Ch103
        // fallback (clut_enable=0). PCRTC reads via the Ch138
        // swizzled path; the framebuffer was filled by
        // gif_image_xfer_stub via the Ch139 swizzled path under
        // DMAC TRXDIR/IMAGE delivery (raster path is dormant).
        // Agreement at this layer means both integrations land
        // at the same (byte, nibble_hi) slots for PSMT4.
        // ------------------------------------------------------------
        for (int y = 0; y < PCRTC_V_ACTIVE; y++) begin
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                int          q_idx;
                logic [7:0]  e;
                q_idx = quadrant_idx(x, y);
                e     = expected_gray(q_idx);
                if (!cap_de[y][x]) begin
                    $error("(%0d,%0d) DE never asserted", x, y);
                    errors = errors + 1;
                end
                if (cap_r[y][x] !== e || cap_g[y][x] !== e
                    || cap_b[y][x] !== e) begin
                    $error("[scanout] (%0d,%0d) got (%02x,%02x,%02x) expected gray=%02x sprite=%0d",
                           x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x],
                           e, q_idx);
                    errors = errors + 1;
                end
            end
        end

        // ------------------------------------------------------------
        // Phase 2 — write-side NIBBLE readback at swizzled (addr,
        // nibble_hi) slots. For every (x, y) in 16×8, compute the
        // canonical PCSX2 PSMT4 swizzled (byte_addr, nibble_hi)
        // pair via in-TB ref_pos_psmt4() and assert the 4-bit
        // nibble at that slot (byte selected from the 32-bit word
        // via addr[1:0], then nibble selected via nibble_hi)
        // equals the nibble the TB built into the IMAGE qword
        // stream (matching expected_nibble(quadrant_idx(x, y))
        // for the pixel's quadrant). This locks the
        // gif_image_xfer_stub Ch139 wiring independent of the
        // scanout Ch138 wiring.
        // ------------------------------------------------------------
        begin : phase2_nibble_readback
            for (int y = 0; y < PCRTC_V_ACTIVE; y++) begin
                for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                    int          q_idx;
                    psmt4_pos_t  pos;
                    logic [3:0]  expected;
                    logic [3:0]  got;
                    q_idx    = quadrant_idx(x, y);
                    pos      = ref_pos_psmt4(0, 2, x, y);
                    expected = expected_nibble(q_idx);
                    vram_raddr2 = pos.addr & ~32'd3;
                    #1;
                    case (pos.addr[1:0])
                        2'b00: got = pos.nibble_hi ? vram_rdata2[7:4]   : vram_rdata2[3:0];
                        2'b01: got = pos.nibble_hi ? vram_rdata2[15:12] : vram_rdata2[11:8];
                        2'b10: got = pos.nibble_hi ? vram_rdata2[23:20] : vram_rdata2[19:16];
                        default: got = pos.nibble_hi ? vram_rdata2[31:28] : vram_rdata2[27:24];
                    endcase
                    if (got !== expected) begin
                        $error("[nibble] (%0d,%0d) @addr 0x%08x hi=%0b got 0x%01x expected 0x%01x sprite=%0d",
                               x, y, pos.addr, pos.nibble_hi, got, expected, q_idx);
                        errors = errors + 1;
                    end
                end
            end
        end

        // ------------------------------------------------------------
        // Strict linear-vs-swizzled separator. The 16×8 PSMT4
        // image at FBP=0/FBW=2 lives entirely in the upper-left
        // of block (0,0) of page 0 under SWIZZLED (PSMT4 block
        // is 32×16 px = 256 bytes; the image is 128 pixels using
        // yb=0..7, xb=0..15 of columnTable4 which fills nibble_idx
        // values [0..127] = byte_in_block ∈ [0..63]). Under
        // LINEAR the stride is FBW*32 = 64 bytes/row, so y=2
        // starts at byte 128 — strictly outside the swizzled
        // write set [0..63]. If gif_image_xfer_stub had silently
        // fallen through to the linear path (PSMT4_SWIZZLE=0
        // branch), byte 128 would hold y=2 row nibbles. Assert
        // byte 128 stays 0 (per-byte check, not full word: a
        // neighbor byte in the same word may legitimately be
        // touched).
        // ------------------------------------------------------------
        begin : sep_byte128
            logic [7:0] sep_byte;
            vram_raddr2 = 32'd128 & ~32'd3;
            #1;
            case (32'd128 & 32'd3)
                32'd0: sep_byte = vram_rdata2[7:0];
                32'd1: sep_byte = vram_rdata2[15:8];
                32'd2: sep_byte = vram_rdata2[23:16];
                default: sep_byte = vram_rdata2[31:24];
            endcase
            if (sep_byte !== 8'd0) begin
                $error("[linear-y2-byte-128] got 0x%02x expected 0", sep_byte);
                errors = errors + 1;
            end
        end

        // ------------------------------------------------------------
        // Aggregate counts.
        // ------------------------------------------------------------
        if (dma_start_count != 1) begin
            $error("dma_start_count=%0d (expected 1)", dma_start_count);
            errors = errors + 1;
        end
        if (dma_beat_count != QWC_TOTAL) begin
            $error("dma_beat_count=%0d (expected %0d)", dma_beat_count, QWC_TOTAL);
            errors = errors + 1;
        end
        if (dma_done_count != 1) begin
            $error("dma_done_count=%0d (expected 1)", dma_done_count);
            errors = errors + 1;
        end
        if (giftag_seen != 2) begin
            $error("GIFtag accept count=%0d (expected 2: U1 + U2)", giftag_seen);
            errors = errors + 1;
        end
        if (packed_ad_writes_seen != 4) begin
            $error("PACKED A+D dispatch count=%0d (expected 4: U1 BITBLTBUF/TRXPOS/TRXREG/TRXDIR — IMAGE qwords don't count as A+D)",
                   packed_ad_writes_seen);
            errors = errors + 1;
        end
        if (trxdir_arms_seen != 1) begin
            $error("trxdir_wr_q pulses=%0d (expected 1 — single TRX setup)",
                   trxdir_arms_seen);
            errors = errors + 1;
        end
        if (xfer_writes_seen != IMG_PIXELS) begin
            $error("xfer VRAM writes=%0d (expected %0d — load-bearing image-xfer path)",
                   xfer_writes_seen, IMG_PIXELS);
            errors = errors + 1;
        end
        if (raster_pixel_emit_count != 32'd0) begin
            $error("expected 0 raster emits (raster path dormant), got %0d",
                   raster_pixel_emit_count);
            errors = errors + 1;
        end
        if (raster_emits_seen != 0) begin
            $error("raster emit observer count=%0d (expected 0 — raster dormant)",
                   raster_emits_seen);
            errors = errors + 1;
        end
        if (loader_starts != 0) begin
            $error("CLUT loader fired %0d times (expected 0 — no CLUT path in this demo)",
                   loader_starts);
            errors = errors + 1;
        end
        if (ee_priv_writes_seen != 4) begin
            $error("EE priv-MMIO writes=%0d (expected 4: PMODE + DISPFB1 + DISPLAY1×2)",
                   ee_priv_writes_seen);
            errors = errors + 1;
        end
        if (priv_bridge_fires_seen != 4) begin
            $error("priv-bridge gs_reg_wr fires=%0d (expected 4)",
                   priv_bridge_fires_seen);
            errors = errors + 1;
        end
        if (ee_dmac_writes_seen != 3) begin
            $error("EE-driven DMAC reg writes=%0d (expected 3: MADR + QWC + CHCR)",
                   ee_dmac_writes_seen);
            errors = errors + 1;
        end
        if (dmac_seq_idx != 3) begin
            $error("EE DMAC write sequence stopped at idx %0d (expected 3)",
                   dmac_seq_idx);
            errors = errors + 1;
        end
        if (dmac_seq_errors != 0) begin
            $error("EE DMAC write sequence had %0d divergences", dmac_seq_errors);
            errors = errors + dmac_seq_errors;
        end
        if (map_gs_priv_traces_seen != 4) begin
            $error("map trace classified GS-priv writes=%0d (expected 4)",
                   map_gs_priv_traces_seen);
            errors = errors + 1;
        end
        if (map_unmapped_traces_seen != 0) begin
            $error("map trace mis-classified GS-priv writes as UNMAPPED=%0d (expected 0)",
                   map_unmapped_traces_seen);
            errors = errors + 1;
        end
        // Ch113 — EE-CPU halt + trap state.
        if (!core_halt) begin
            $error("EE core did not halt (program should SYSCALL)");
            errors = errors + 1;
        end
        if (core_trap) begin
            $error("EE core trapped: pc=0x%08x instr=0x%08x",
                   core_trap_pc, core_trap_instr);
            errors = errors + 1;
        end
        if (collision_count != 0) begin
            $error("xfer/raster collision count=%0d (expected 0)", collision_count);
            errors = errors + 1;
        end
        if (raster_overflow) begin
            $error("raster_overflow asserted");
            errors = errors + 1;
        end
        if (raster_degenerate) begin
            $error("raster_degenerate asserted");
            errors = errors + 1;
        end

        $display("[tb_gs_demo_psmt4_swizzle_trxdir_e2e] dma=(%0d,%0d,%0d) ee_dmac_wr=%0d giftags=%0d ad_writes=%0d trxdir_arms=%0d xfer_writes=%0d ee_priv_wr=%0d bridge_fires=%0d core_halt=%0b core_pc=0x%08x emits=%0d loader_starts=%0d frame=%0dx%0d",
                 dma_start_count, dma_beat_count, dma_done_count,
                 ee_dmac_writes_seen,
                 giftag_seen, packed_ad_writes_seen,
                 trxdir_arms_seen, xfer_writes_seen,
                 ee_priv_writes_seen, priv_bridge_fires_seen,
                 core_halt, core_pc,
                 raster_pixel_emit_count, loader_starts,
                 PCRTC_H_ACTIVE, PCRTC_V_ACTIVE);

        if (errors == 0) $display("[tb_gs_demo_psmt4_swizzle_trxdir_e2e] PASS");
        else             $display("[tb_gs_demo_psmt4_swizzle_trxdir_e2e] FAIL");
        $finish;
    end

    initial begin
        #20000000;
        $error("[tb_gs_demo_psmt4_swizzle_trxdir_e2e] timeout");
        $finish;
    end

endmodule : tb_gs_demo_psmt4_swizzle_trxdir_e2e
