// retroDE_ps2 — tb_gs_demo_psmt4_e2e_eemap (Ch112)
//
// Same demo as Ch111 (EE-shaped 32-bit MMIO control-plane writes
// driving gs_stub.reg_wr_* through ee_gs_priv_bridge_stub) but
// the bridge is no longer driven directly by the TB. Instead
// the TB drives `ee_memory_map_stub.ee_wr_*` with full 32-bit
// physical addresses targeting the GS-priv window at
// 0x1200_xxxx; the map decodes phys[28:16] == 13'h1200,
// peels the 16-bit window offset, and hands the 32-bit half-
// write to the bridge. Closes the last control-plane routing
// gap before a tiny EE instruction stream can plausibly bring
// up the display.
//
// What changes vs Ch110:
//   - New `ee_gs_priv_bridge_stub` sits between the TB's
//     EE-MMIO write port and gs_stub.reg_wr_*. It accumulates
//     32-bit writes per 8-byte slot (matching the way an EE
//     `sd` is broken into a pair of `sw`s by the EE microarch)
//     and fires a 64-bit gs_stub.reg_wr_* pulse on each EE
//     half-write. Single-half writes work for registers whose
//     interesting bits live entirely in one half (PMODE.EN1,
//     DISPFB1.PSM/FBP/FBW); paired lo+hi writes are required
//     when the interesting bits span both halves (DISPLAY1.DW
//     and DISPLAY1.DH live at bits [43:32] and [55:44], i.e.
//     in the high 32-bit half).
//   - The TB drives `ee_wr_en/ee_wr_addr/ee_wr_data/ee_wr_be`
//     into the bridge with EE-shaped 32-bit writes targeting:
//       0x12000000  PMODE      (single low-half write, EN1=1)
//       0x12000070  DISPFB1    (single low-half write, PSM=PSMT4)
//       0x12000080  DISPLAY1 lo (DX=DY=0, MAGH=MAGV=0)
//       0x12000084  DISPLAY1 hi (DW=H_ACT-1, DH=V_ACT-1)
//   - gs_stub.reg_wr_* sees the 64-bit value of each privileged
//     register exactly as Ch110 did; the same Ch110 frame
//     assertion and aggregate counts hold unchanged.
//
// What stays the same as Ch110:
//   - Palette upload via TRXDIR/TRXPOS/TRXREG/TRXDIR + IMAGE
//     packets through the GIF — the data plane is unchanged.
//   - 4 SPRITE PACKED packets + 1 TEX0_1 PACKED packet for the
//     primitive stream + CLUT-load.
//   - DMAC delivers 36 qwords; gif_image_xfer_stub does 16
//     PSMCT32 VRAM writes for the palette; raster does 32 PSMT4
//     emits for the framebuffer.
//   - Same 16×8 captured RGB frame.
//
// PASS criteria (same as Ch110 plus EE-MMIO write counter):
//   - 1 EV_DMA_START / 36 EV_DMA_BEAT / 1 EV_DMA_DONE
//   - 7 GIFtag accepts (U1 + U2 + 4×SPRITE + 1×TEX0_1)
//   - 25 PACKED A+D dispatches
//   - 16 image-xfer VRAM writes
//   - 4 EE-MMIO writes seen at the bridge input (1 PMODE +
//     1 DISPFB1 + 2 DISPLAY1)
//   - 4 corresponding gs_stub.reg_wr_* fires from the bridge
//   - 1 loader_busy rising edge
//   - Captured 16×8 frame matches expected CLUT-decoded RGB

`timescale 1ns/1ps

module tb_gs_demo_psmt4_e2e_eemap;

    localparam int PCRTC_H_ACTIVE  = 16;
    localparam int PCRTC_V_ACTIVE  = 8;
    localparam int RAM_SIZE_BYTES  = 4 * 1024;
    localparam int RAM_ADDR_W      = $clog2(RAM_SIZE_BYTES);

    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;

    // ----------------------------------------------------------------
    // DMAC + memory 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;          // combined: gif.in_ready & xfer.data_ready

    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;

    // Ch112 — EE-CPU-side write surface into ee_memory_map_stub.
    // The TB drives 32-bit phys-address writes targeting
    // 0x1200_xxxx; the map decodes the GS-priv window and routes
    // to ee_gs_priv_wr_* outputs, which feed the bridge below.
    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(1'b0), .ee_rd_addr(32'd0),
        .ee_rd_data(), .ee_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_addr(),
        .bios_rd_data(32'd0), .bios_rd_valid(1'b0),
        .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(), .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),
        .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];

    // ----------------------------------------------------------------
    // 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 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 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.
    logic        clut_we;
    logic [7:0]  clut_widx;
    logic [31:0] clut_wdata;
    logic [7:0]  clut_ridx;
    logic [31:0] clut_rdata;

    clut_stub u_clut (
        .clk(clk), .rst_n(rst_n),
        .write_en  (clut_we),
        .write_idx (clut_widx),
        .write_data(clut_wdata),
        .read_idx  (clut_ridx),
        .read_data (clut_rdata)
    );

    logic loader_busy;

    clut_loader_stub u_loader (
        .clk(clk), .rst_n(rst_n),
        .tex0_wr_pulse  (tex0_1_wr_q),
        .tex0_cbp       (tex0_1_cbp_q),
        .tex0_cpsm      (tex0_1_cpsm_q),
        .tex0_csm       (tex0_1_csm_q),
        .tex0_csa       (tex0_1_csa_q),
        .tex0_cld       (tex0_1_cld_q),
        .vram_read_addr (vram_raddr2),
        .vram_read_data (vram_rdata2),
        .clut_write_en  (clut_we),
        .clut_write_idx (clut_widx),
        .clut_write_data(clut_wdata),
        .load_busy      (loader_busy)
    );

    // 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)
    ) 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'b1),
        .clut_csa      (tex0_1_csa_q),
        .clut_read_idx (clut_ridx),
        .clut_read_data(clut_rdata),
        .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_psmt4_emits;
    int  giftag_seen;
    int  packed_ad_writes_seen;
    int  xfer_writes_seen;
    int  ee_priv_writes_seen;
    int  priv_bridge_fires_seen;
    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_psmt4_emits     = 0;
        giftag_seen            = 0;
        packed_ad_writes_seen  = 0;
        xfer_writes_seen       = 0;
        ee_priv_writes_seen      = 0;
        priv_bridge_fires_seen   = 0;
        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 && xfer_we)
            xfer_writes_seen <= xfer_writes_seen + 1;
        // 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;
    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_psmt4_emits <= raster_psmt4_emits + 1;
            if (raster_pixel_psm_q !== 6'h14) begin
                $error("emit %0d: psm=0x%02x (expected 0x14)",
                       raster_psmt4_emits, raster_pixel_psm_q);
                errors <= errors + 1;
            end
            if (raster_pixel_be_q !== 4'b0001) begin
                $error("emit %0d: be=%b (expected 4'b0001)",
                       raster_psmt4_emits, 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 0x0F or 0xF0)",
                       raster_psmt4_emits, raster_pixel_mask_q);
                errors <= errors + 1;
            end
        end
    end

    // ----------------------------------------------------------------
    // Helpers.
    // ----------------------------------------------------------------
    task automatic write_dmac(input logic [7:0] offset, input logic [31:0] data);
        @(negedge clk);
        dmac_reg_wr_en   = 1'b1;
        dmac_reg_offset  = offset;
        dmac_reg_wr_data = data;
        @(negedge clk);
        dmac_reg_wr_en   = 1'b0;
        dmac_reg_offset  = 8'd0;
        dmac_reg_wr_data = 32'd0;
    endtask

    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

    // EE-CPU-shaped 32-bit MMIO write into the GS privileged
    // window via ee_memory_map_stub. Drives a full 32-bit phys
    // address (0x1200_0000 + offset); the map decodes the GS-priv
    // tag (phys[28:16] == 13'h1200), peels the 16-bit window
    // offset, and routes the write to ee_gs_priv_bridge_stub
    // which accumulates half-writes and drives gs_stub.reg_wr_*.
    task automatic ee_priv_write32(input logic [15:0] offset,
                                   input logic [31:0] data);
        @(negedge clk);
        ee_cpu_wr_en   = 1'b1;
        ee_cpu_wr_addr = 32'h1200_0000 | {16'd0, offset};
        ee_cpu_wr_data = data;
        ee_cpu_wr_be   = 4'b1111;
        @(posedge clk);
        @(negedge clk);
        ee_cpu_wr_en   = 1'b0;
        ee_cpu_wr_addr = 32'd0;
        ee_cpu_wr_data = 32'd0;
        ee_cpu_wr_be   = 4'b0000;
    endtask

    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

    function automatic logic [63:0] tex0_pack(
        input logic [13:0] cbp,
        input logic [3:0]  cpsm,
        input logic        csm,
        input logic [4:0]  csa,
        input logic [2:0]  cld);
        logic [63:0] v;
        v = 64'd0;
        v[50:37] = cbp;
        v[54:51] = cpsm;
        v[55]    = csm;
        v[60:56] = csa;
        v[63:61] = cld;
        return v;
    endfunction

    function automatic logic [31:0] pattern_a(input logic [7:0] i);
        logic [7:0] r8, g8, b8, a8;
        r8 = i; g8 = i + 8'h40; b8 = i + 8'h80; a8 = 8'hFF;
        return {a8, b8, g8, r8};
    endfunction

    // BITBLTBUF packer: DBP at [45:32], DBW at [53:48], DPSM at [61:56].
    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

    // TRXPOS packer: DSAX at [42:32], DSAY at [58:48].
    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

    // TRXREG packer: RRW at [11:0], RRH at [43:32].
    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

    // TRXDIR packer: XDIR at [1:0]. 0=host→local.
    function automatic logic [63:0] trxdir_pack(input logic [1:0] xdir_v);
        return {62'd0, xdir_v};
    endfunction

    function automatic logic [3:0] quad_idx_at(input int x, input int y);
        if (y <= 1 && x <= 3)                  return 4'h5;
        if (y <= 1 && x >= 4 && x <= 7)        return 4'h7;
        if (y >= 2 && y <= 3 && x <= 3)        return 4'hA;
        if (y >= 2 && y <= 3 && x >= 4 && x <= 7) return 4'hC;
        return 4'h0;
    endfunction

    // ----------------------------------------------------------------
    // Constants.
    // ----------------------------------------------------------------
    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_TEX0_1    = 8'h06;
    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;

    localparam logic [63:0] PRIM_SPRITE   = 64'd6;
    localparam logic [63:0] FRAME_1_PSMT4 = 64'h0000_0000_1401_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;

    localparam int          PALETTE_CBP  = 4;
    localparam logic [4:0]  CSA          = 5'd0;

    localparam logic [63:0] DISPFB1_VAL  = 64'h0000_0000_000A_0200;
    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;
    localparam int          QWC_TOTAL    = 36;
    // Layout:
    //   q0..q4   : U1 — TRX setup (1 GIFtag + 4 PACKED A+D)
    //   q5..q9   : U2 — IMAGE upload (1 GIFtag + 4 IMAGE qwords)
    //   q10..q33 : 4 SPRITE packets (each 6 qwords)
    //   q34..q35 : TEX0_1 packet (1 GIFtag + 1 PACKED A+D)

    initial begin
        rst_n             = 1'b0;
        ee_cpu_wr_en      = 1'b0;
        ee_cpu_wr_addr    = 32'd0;
        ee_cpu_wr_data    = 32'd0;
        ee_cpu_wr_be      = 4'b0000;
        dmac_reg_wr_en    = 1'b0;
        dmac_reg_offset   = 8'd0;
        dmac_reg_wr_data  = 32'd0;
        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 all 36 GIF qwords into ee_ram_stub.
        // ------------------------------------------------------------
        begin : preload_block
            int q;
            int p;
            logic [31:0]           addr_full;
            logic [RAM_ADDR_W-1:0] addr_q;

            // SPRITE descriptors.
            logic [7:0]  spr_r  [0:3];
            logic [11:0] spr_x0 [0:3], spr_y0 [0:3], spr_x1 [0:3], spr_y1 [0:3];
            spr_r [0] = 8'h05; spr_x0[0] = 12'd0; spr_y0[0] = 12'd0; spr_x1[0] = 12'd3; spr_y1[0] = 12'd1;
            spr_r [1] = 8'h07; spr_x0[1] = 12'd4; spr_y0[1] = 12'd0; spr_x1[1] = 12'd7; spr_y1[1] = 12'd1;
            spr_r [2] = 8'h0A; spr_x0[2] = 12'd0; spr_y0[2] = 12'd2; spr_x1[2] = 12'd3; spr_y1[2] = 12'd3;
            spr_r [3] = 8'h0C; spr_x0[3] = 12'd4; spr_y0[3] = 12'd2; spr_x1[3] = 12'd7; spr_y1[3] = 12'd3;

            q = 0;

            // ---------------------------------------------------------
            // U1 — TRX setup packet (PACKED, NREG=4, EOP=0):
            //   BITBLTBUF, TRXPOS, TRXREG, TRXDIR
            // REGS = 0xEEEE in low 4 nibble slots.
            // ---------------------------------------------------------
            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'h00000000_0000_EEEE));
            q = q + 1;
            // BITBLTBUF: DBP=PALETTE_CBP, DBW=1 (64 pixels stride), DPSM=PSMCT32.
            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'(PALETTE_CBP), 6'd1, 6'h00)));
            q = q + 1;
            // TRXPOS: DSAX=0, DSAY=0 (DIR bits stay 0 — host→local).
            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=1 (16-pixel single row).
            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'd16, 12'd1)));
            q = q + 1;
            // TRXDIR: XDIR=0 → host→local. This commit arms 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-mode upload packet (FLG=2, NLOOP=4):
            //   each qword carries 4 PSMCT32 entries (4 × 32 bits).
            //   16 entries total → 4 qwords.
            // ---------------------------------------------------------
            addr_full = PAYLOAD_MADR + 32'(q * 16);
            addr_q    = addr_full[RAM_ADDR_W-1:0];
            preload_qword(addr_q, giftag(15'd4, 1'b0, 2'd2, 4'd0, 64'd0));
            q = q + 1;
            for (int qi = 0; qi < 4; qi++) begin
                logic [31:0]  px0, px1, px2, px3;
                logic [127:0] qword;
                px0 = pattern_a(8'(qi*4 + 0));
                px1 = pattern_a(8'(qi*4 + 1));
                px2 = pattern_a(8'(qi*4 + 2));
                px3 = pattern_a(8'(qi*4 + 3));
                qword = {px3, px2, px1, px0};
                addr_full = PAYLOAD_MADR + 32'(q * 16);
                addr_q    = addr_full[RAM_ADDR_W-1:0];
                preload_qword(addr_q, qword);
                q = q + 1;
            end

            // ---------------------------------------------------------
            // 4 × SPRITE packets (PACKED, NREG=5, REGS=0xEEEEE).
            // EOP=0 except on last sprite.
            // ---------------------------------------------------------
            for (p = 0; p < 4; p++) begin
                logic spr_eop;
                spr_eop = (p == 3);
                addr_full = PAYLOAD_MADR + 32'(q * 16);
                addr_q    = addr_full[RAM_ADDR_W-1:0];
                preload_qword(addr_q, giftag(15'd1, spr_eop, 2'd0, 4'd5,
                                             64'h00000000_000E_EEEE));
                q = q + 1;
                addr_full = PAYLOAD_MADR + 32'(q * 16);
                addr_q    = addr_full[RAM_ADDR_W-1:0];
                preload_qword(addr_q, aplusd(R_PRIM, PRIM_SPRITE));
                q = q + 1;
                addr_full = PAYLOAD_MADR + 32'(q * 16);
                addr_q    = addr_full[RAM_ADDR_W-1:0];
                preload_qword(addr_q, aplusd(R_FRAME_1, FRAME_1_PSMT4));
                q = q + 1;
                addr_full = PAYLOAD_MADR + 32'(q * 16);
                addr_q    = addr_full[RAM_ADDR_W-1:0];
                preload_qword(addr_q, aplusd(R_RGBAQ,
                                             {32'd0, 8'hCC, 8'hBB, 8'hAA, spr_r[p]}));
                q = q + 1;
                addr_full = PAYLOAD_MADR + 32'(q * 16);
                addr_q    = addr_full[RAM_ADDR_W-1:0];
                preload_qword(addr_q, aplusd(R_XYZ2,
                                             xyz2_data(spr_x0[p], spr_y0[p])));
                q = q + 1;
                addr_full = PAYLOAD_MADR + 32'(q * 16);
                addr_q    = addr_full[RAM_ADDR_W-1:0];
                preload_qword(addr_q, aplusd(R_XYZ2,
                                             xyz2_data(spr_x1[p], spr_y1[p])));
                q = q + 1;
            end

            // ---------------------------------------------------------
            // TEX0_1 packet (PACKED, NREG=1, EOP=1).
            // ---------------------------------------------------------
            addr_full = PAYLOAD_MADR + 32'(q * 16);
            addr_q    = addr_full[RAM_ADDR_W-1:0];
            preload_qword(addr_q, giftag(15'd1, 1'b1, 2'd0, 4'd1,
                                         64'h00000000_0000_000E));
            q = q + 1;
            addr_full = PAYLOAD_MADR + 32'(q * 16);
            addr_q    = addr_full[RAM_ADDR_W-1:0];
            preload_qword(addr_q, aplusd(R_TEX0_1,
                                         tex0_pack(14'(PALETTE_CBP), 4'd0,
                                                   1'b1, CSA, 3'd4)));
            q = q + 1;

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

        // ------------------------------------------------------------
        // Kick the DMAC. NORMAL transfer, QWC=36.
        // ------------------------------------------------------------
        write_dmac(MADR_OFF, PAYLOAD_MADR);
        write_dmac(QWC_OFF,  32'(QWC_TOTAL));
        write_dmac(CHCR_OFF, 32'h0000_0001);

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

        // ------------------------------------------------------------
        // Privileged-block bring-up.
        // ------------------------------------------------------------
        // EE-shaped privileged-MMIO bring-up.
        // DISPFB1: only low 32 bits matter (PSM/FBP/FBW; DBX/DBY=0).
        ee_priv_write32(DISPFB1_OFF, DISPFB1_VAL[31:0]);
        // DISPLAY1: DW/DH live at bits [43:32]/[55:44] (high half),
        // DX/DY/MAGH/MAGV at [22:12]/etc. (low half). Two writes —
        // mirroring how an EE `sd 0x12000080` decomposes into
        // `sw lo, 0(0x12000080); sw hi, 4(0x12000080)`.
        ee_priv_write32(DISPLAY1_OFF        , DISPLAY1_VAL[31:0]);
        ee_priv_write32(DISPLAY1_OFF + 16'd4, DISPLAY1_VAL[63:32]);
        // PMODE: only low 32 bits (EN1 at bit 0).
        ee_priv_write32(PMODE_OFF, PMODE_EN1[31:0]);

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

        // ------------------------------------------------------------
        // Frame assertion.
        // ------------------------------------------------------------
        for (int y = 0; y < PCRTC_V_ACTIVE; y++) begin
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                logic [3:0]  expected_idx;
                logic [7:0]  effective_idx;
                logic [31:0] entry;
                logic [7:0]  er, eg, eb;

                expected_idx  = quad_idx_at(x, y);
                effective_idx = {4'd0, expected_idx} + 8'(CSA) * 8'd16;
                entry         = pattern_a(effective_idx);
                er = entry[7:0];
                eg = entry[15:8];
                eb = entry[23:16];

                if (!cap_de[y][x]) begin
                    $error("(%0d,%0d) DE never asserted", x, y);
                    errors = errors + 1;
                end
                if (cap_r[y][x] !== er || cap_g[y][x] !== eg || cap_b[y][x] !== eb) begin
                    $error("(%0d,%0d) got (%02x,%02x,%02x) expected (%02x,%02x,%02x) idx=0x%01x",
                           x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x],
                           er, eg, eb, expected_idx);
                    errors = errors + 1;
                end
            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 != 7) begin
            $error("GIFtag accept count=%0d (expected 7: U1 + U2 + 4×SPRITE + TEX0)",
                   giftag_seen);
            errors = errors + 1;
        end
        if (packed_ad_writes_seen != 25) begin
            $error("PACKED A+D dispatch count=%0d (expected 25: 4 + 4*5 + 1*1)",
                   packed_ad_writes_seen);
            errors = errors + 1;
        end
        if (xfer_writes_seen != 16) begin
            $error("xfer VRAM writes=%0d (expected 16 PSMCT32 palette entries)",
                   xfer_writes_seen);
            errors = errors + 1;
        end
        if (raster_pixel_emit_count != 32'd32) begin
            $error("expected 32 PSMT4 emits, got %0d", raster_pixel_emit_count);
            errors = errors + 1;
        end
        if (raster_psmt4_emits != 32) begin
            $error("PSMT4 emit observer count=%0d (expected 32)", raster_psmt4_emits);
            errors = errors + 1;
        end
        if (loader_starts != 1) begin
            $error("loader fired %0d times (expected 1)", 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 (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
        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_e2e_eemap] dma=(%0d,%0d,%0d) giftags=%0d ad_writes=%0d xfer_writes=%0d ee_priv_wr=%0d bridge_fires=%0d emits=%0d loader_starts=%0d frame=%0dx%0d",
                 dma_start_count, dma_beat_count, dma_done_count,
                 giftag_seen, packed_ad_writes_seen, xfer_writes_seen,
                 ee_priv_writes_seen, priv_bridge_fires_seen,
                 raster_pixel_emit_count, loader_starts,
                 PCRTC_H_ACTIVE, PCRTC_V_ACTIVE);

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

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

endmodule : tb_gs_demo_psmt4_e2e_eemap
