foxygit / fake-08-xbox360 Log in
main xbox360 commits tags

/platform/xex/runtime/video.c · 34.69 KB

raw
/*
 * Scanout of CPU-drawn frames: C port of xenon-forge's xbox360-video crate
 * (src/crates/xbox360-video: lib.rs, ring.rs, memory.rs, fetch.rs;
 * https://github.com/landaire/xenon-forge, MIT/Apache-2.0).
 *
 * The title takes the GPU engines (VdInitializeEngines with the kernel's
 * microcode), runs a command ring of its own, and flips between two tiled
 * front buffers with VdSwap at vertical blank. xex_video_shutdown (also run
 * at exit) gives the engines back so the dashboard can draw again.
 */
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <xbox360/xboxkrnl.h>

#include "xex_video.h"

/* Imports declared in extra_imports.S */
extern void VdQueryVideoMode(void *mode);
extern ULONG VdInitializeScalerCommandBuffer(ULONG source_xy, ULONG source_wh, ULONG output_xy,
                                             ULONG output_wh, ULONG front_buffer_wh,
                                             ULONG vertical_filter_type, void *vertical_filter,
                                             ULONG horizontal_filter_type, void *horizontal_filter,
                                             ULONG unknown9, PULONG commands, ULONG command_dwords);

extern void VdCallGraphicsNotificationRoutines(ULONG event, const void *data);

void (*xex_video_trace)(const char *fmt, ...);
#define TRACE(...) do { if (xex_video_trace) xex_video_trace(__VA_ARGS__); } while (0)

static inline uint64_t timebase_now(void)
{
    uint64_t tb;
    __asm__ volatile("mftb %0" : "=r"(tb));
    return tb;
}
/* 100 ms at 49.875 MHz */
#define WAIT_TIMEOUT_TB 4987500ull

/* ------------------------------------------------------------------------ */
/* GPU registers, memory, processor helpers                                 */

#define GPU_REGISTERS 0x7fc80000u

static inline uint32_t gpu_read(uint32_t index)
{
    return *(volatile uint32_t *)(GPU_REGISTERS + index * 4);
}

static inline void gpu_write(uint32_t index, uint32_t value)
{
    *(volatile uint32_t *)(GPU_REGISTERS + index * 4) = value;
}

static inline void cpu_sync(void)          { __asm__ volatile("sync" ::: "memory"); }
static inline void low_priority_hint(void) { __asm__ volatile("or 31, 31, 31" ::: "memory"); }

#define MEMORY_REGION_TITLE 1
#define PAGE_READWRITE_     0x004
#define PAGE_NOCACHE_       0x200
#define PAGE_WRITECOMBINE_  0x400

typedef struct {
    uint32_t *words;      /* virtual */
    uint32_t physical;    /* GPU address */
    uint32_t bytes;
} phys_buffer;

static int phys_alloc(phys_buffer *b, uint32_t bytes, uint32_t caching)
{
    bytes = (bytes + 0xfff) & ~0xfffu;
    void *p = MmAllocatePhysicalMemoryEx(MEMORY_REGION_TITLE, bytes, PAGE_READWRITE_ | caching,
                                         0, 0x1fffffff, 0x1000);
    if (!p) return -1;
    b->words = (uint32_t *)p;
    b->physical = MmGetPhysicalAddress(p);
    b->bytes = bytes;
    return 0;
}

static void phys_free(phys_buffer *b)
{
    if (b->words) {
        MmFreePhysicalMemory(MEMORY_REGION_TITLE, b->words);
        b->words = NULL;
    }
}

static inline uint32_t read_word(const phys_buffer *b, uint32_t offset)
{
    return ((volatile uint32_t *)b->words)[offset / 4];
}

/* ------------------------------------------------------------------------ */
/* Command ring (ring.rs)                                                   */

#define RING_WRITE_POINTER      0x1c5
#define RING_BYTES              0x8000u
#define RING_DWORDS             (RING_BYTES / 4)
#define GRANULE_DWORDS          8u
#define WRITEBACK_BYTES         0x1000u
#define ENGINE_INIT_MASK        0x3ffu
#define ENGINE_INIT_STEP        0x80u
#define ENGINE_INIT_WORD12      0x00010800u
#define REGISTER_0D02           0x0d02
#define KERNEL_REGISTER_0D02    0x800u
#define PIPELINE_CONTROL_05C8   0x05c8
#define PIPELINE_CONTROL_05C8_VALUE 0x00020000u
#define ENGINE_INIT_WORD13      7u
#define WAIT_MEMORY_EQUAL       0x13u
#define WAIT_INTERVAL           0x100u
#define EVENT_SHADER_DONE       3u
#define ENDIAN_8_IN_32          2u
#define SWAP_IDENTIFIER_OFFSET  0x08u
#define READ_POINTER_OFFSET     0x3cu
#define PIPELINE_FENCE_OFFSET   0x40u

#define OPCODE_NOP              0x10
#define OPCODE_WAIT             0x3c
#define OPCODE_EVENT_WRITE      0x58
#define OPCODE_REGISTER_RMW     0x21
#define OPCODE_ENGINE_INIT      0x48

static inline uint32_t type0(uint32_t reg, uint32_t count)
{
    return ((count - 1) << 16) | reg;
}

static inline uint32_t type3(uint32_t opcode, uint32_t count)
{
    return 0xc0000000u | ((count - 1) << 16) | (opcode << 8);
}

typedef struct {
    phys_buffer commands;
    phys_buffer writeback;
    uint32_t write;   /* next dword, from the ring base */
    uint32_t read;    /* last read pointer read back */
    uint32_t fence;
} ring_t;

static uint32_t ring_read_pointer(const ring_t *r)
{
    return read_word(&r->writeback, READ_POINTER_OFFSET);
}

static uint32_t ring_free(const ring_t *r)
{
    return (r->read - r->write - 1) % RING_DWORDS;
}

static void ring_kick(ring_t *r)
{
    uint32_t next = (r->write + GRANULE_DWORDS - 1) / GRANULE_DWORDS * GRANULE_DWORDS;
    uint32_t pad = next - r->write;
    if (pad == 1) pad += GRANULE_DWORDS;   /* a NOP is at least two dwords */
    if (pad != 0) {
        r->commands.words[r->write] = type3(OPCODE_NOP, pad - 1);
    }
    r->write = (r->write + pad) % RING_DWORDS;
    cpu_sync();   /* write-combined stores reach memory before the GPU looks */
    gpu_write(RING_WRITE_POINTER, r->write);
}

static void ring_wait_free(ring_t *r, uint32_t dwords)
{
    while (ring_free(r) < dwords) {
        r->read = ring_read_pointer(r);
        if (ring_free(r) < dwords) low_priority_hint();
    }
}

static uint32_t *ring_reserve(ring_t *r, uint32_t dwords)
{
    uint32_t needed = dwords + GRANULE_DWORDS + 1;
    if (r->write + needed > RING_DWORDS || ring_free(r) < needed) {
        ring_kick(r);
    }
    if (r->write + needed > RING_DWORDS) {
        uint32_t tail = RING_DWORDS - r->write;
        ring_wait_free(r, tail);
        r->commands.words[r->write] = type3(OPCODE_NOP, tail - 1);
        r->write = 0;
        ring_kick(r);
    }
    ring_wait_free(r, needed);
    return &r->commands.words[r->write];
}

static void ring_commit(ring_t *r, uint32_t dwords)
{
    r->write += dwords;
}

static void ring_wait_for_pipeline(ring_t *r)
{
    r->fence++;
    uint32_t address = r->writeback.physical + PIPELINE_FENCE_OFFSET;
    uint32_t *w = ring_reserve(r, 10);
    w[0] = type3(OPCODE_EVENT_WRITE, 3);
    w[1] = EVENT_SHADER_DONE;
    w[2] = address | ENDIAN_8_IN_32;
    w[3] = r->fence;
    w[4] = type3(OPCODE_WAIT, 5);
    w[5] = WAIT_MEMORY_EQUAL;
    w[6] = address | ENDIAN_8_IN_32;
    w[7] = r->fence;
    w[8] = 0xffffffffu;
    w[9] = WAIT_INTERVAL;
    ring_commit(r, 10);
}

static int ring_pipeline_drained(const ring_t *r)
{
    return read_word(&r->writeback, PIPELINE_FENCE_OFFSET) == r->fence;
}

static void ring_block_until_idle(ring_t *r)
{
    uint32_t *w = ring_reserve(r, 2);
    w[0] = type0(PIPELINE_CONTROL_05C8, 1);
    w[1] = PIPELINE_CONTROL_05C8_VALUE;
    ring_commit(r, 2);
    ring_wait_for_pipeline(r);
    ring_kick(r);
    while (!ring_pipeline_drained(r)) low_priority_hint();
}

static void ring_wait_idle(const ring_t *r)
{
    while (ring_read_pointer(r) != r->write) low_priority_hint();
}

static int ring_init(ring_t *r)
{
    memset(r, 0, sizeof(*r));
    if (phys_alloc(&r->commands, RING_BYTES, PAGE_WRITECOMBINE_) != 0) return -1;
    if (phys_alloc(&r->writeback, WRITEBACK_BYTES, PAGE_NOCACHE_) != 0) {
        phys_free(&r->commands);
        return -1;
    }
    memset(r->writeback.words, 0, WRITEBACK_BYTES);

    /* log2(dwords) - 1 and log2(bytes / 512), as D3D derives them */
    VdInitializeRingBuffer(r->commands.physical, 12 /* log2(0x2000) - 1 */);
    VdEnableRingBufferRPtrWriteBack(r->writeback.physical + READ_POINTER_OFFSET, 6 /* log2(0x8000 >> 9) */);
    VdSetSystemCommandBufferGpuIdentifierAddress((PULONG)((uint32_t)r->writeback.words + SWAP_IDENTIFIER_OFFSET));

    uint32_t *w = ring_reserve(r, 21);
    w[0] = type3(OPCODE_ENGINE_INIT, 18);
    w[1] = ENGINE_INIT_MASK;
    w[2] = 0;
    w[3] = 0;
    for (int i = 0; i < 8; i++) w[4 + i] = (uint32_t)i * ENGINE_INIT_STEP;
    w[12] = ENGINE_INIT_WORD12;
    w[13] = ENGINE_INIT_WORD13;
    for (int i = 14; i < 19; i++) w[i] = 0;
    w[19] = type0(REGISTER_0D02, 1);
    w[20] = ENGINE_INIT_WORD12;
    ring_commit(r, 21);
    ring_kick(r);
    return 0;
}

static void ring_detach(ring_t *r)
{
    ring_block_until_idle(r);
    ring_wait_idle(r);
    gpu_write(REGISTER_0D02, KERNEL_REGISTER_0D02);
    VdSetSystemCommandBufferGpuIdentifierAddress(NULL);
}

/* ------------------------------------------------------------------------ */
/* Display (lib.rs)                                                         */

#define TILE_EDGE               32
#define SCANOUT_CONTROL         0x1841
#define SCANOUT_ADDRESS         0x1844
#define SCANOUT_UPDATE          0x1851
#define UPDATE_PENDING          (1u << 0)
#define UPDATE_TAKEN            (1u << 1)
#define SCANOUT_FORMAT_1930     0x1930
#define SCANOUT_CONTROL_KEEP    0xfffff8ffu
#define SWAP_DWORDS             64u
#define FLIP_DWORDS             (2u + 4u + 2u)
#define RETRAIN_COMMAND_DWORDS  0x1000u
#define RETRAIN_WORK_BYTES      0x800u

typedef struct {
    phys_buffer memory;
    uint32_t fetch_constant[6];
} front_buffer;

typedef struct { uint32_t address, pitch, x_end, y_end; } display_surface_t;

static struct {
    int open;
    ring_t ring;
    front_buffer buffers[2];
    int back;
    uint32_t pitch_tiles;
    uint32_t tile_x, tile_y, width, height;
    int pending;
    uint32_t pending_identifier;
    uint32_t pending_address;
    const char *error;
    int presented;
    uint32_t surface_height;
    /* The Guide: XAM's surface shows in place of ours while VdSwap hands it back. */
    int pending_system;
    display_surface_t pending_surface;
    int showing_system;
    unsigned system_frames;
    int guide_supported;
    /* A display controller answers (the LUT autofill finishes): show
     * surfaces through its registers. Xenia has none and shows what VdSwap
     * names; writing its scanout register directly turns its picture white. */
    int controller;
    /* front buffers of the output's size, scaler off */
    int native;
    uint32_t output_width, output_height;
} display;

/* fetch.rs: texture fetch constant of a tiled 8:8:8:8 front buffer */
static void front_buffer_fetch(uint32_t out[6], uint32_t base, uint32_t pitch_tiles,
                               uint32_t width, uint32_t height)
{
    out[0] = (1u << 31) | (pitch_tiles << 22) | 2u;          /* tiled, pitch, texture */
    out[1] = base | (2u << 6) | 6u;                           /* 8-in-32, k_8_8_8_8 */
    out[2] = (width - 1) | ((height - 1) << 13);
    out[3] = 0;
    out[4] = 0;
    out[5] = 1u << 9;                                         /* 2D */
}

static int retraining_after_swap_due;

static void retrain_edram(int at_init)
{
    static uint8_t work[RETRAIN_WORK_BYTES] __attribute__((aligned(16)));
    ULONG flags = at_init ? 1 : 0;

    memset(work, 0, sizeof(work));
    KeEnterCriticalRegion();
    if (at_init) {
        VdRetrainEDRAMWorker(0);
    }
    ULONG state = 0;
    PULONG commands = NULL;
    ULONG due = VdRetrainEDRAM(flags, &commands, RETRAIN_COMMAND_DWORDS, &state, work, RETRAIN_WORK_BYTES);
    if (at_init || due) TRACE("retrain(%s): due=%u state=%u", at_init ? "init" : "swap", (unsigned)due, (unsigned)state);
    if (due) {
        if (!at_init) {
            ring_block_until_idle(&display.ring);
        }
        for (;;) {
            uint32_t *start = ring_reserve(&display.ring, RETRAIN_COMMAND_DWORDS);
            PULONG cursor = (PULONG)start;
            ULONG more = VdRetrainEDRAM(flags, &cursor, RETRAIN_COMMAND_DWORDS, &state, work, RETRAIN_WORK_BYTES);
            ring_commit(&display.ring, (uint32_t)((uint32_t *)cursor - start));
            ring_block_until_idle(&display.ring);
            if (!more) break;
        }
        retraining_after_swap_due = 1;
    }
    KeLeaveCriticalRegion();
}

static unsigned flip_count;

/*
 * Showing a surface the way XAM does (found on hardware by xsdk,
 * https://github.com/jessenic/xsdk src/display.c, MIT): the surface goes
 * into 0x2840/0x2844 and the D1GRPH registers, then 0x60EC
 * (D1CRTC_DOUBLE_BUFFER_CONTROL) = 1 makes the display take it; the
 * display clears it again. Without this the screen stays black.
 */
#define REG_SURFACE_2840        (0x2840 / 4)
#define REG_PITCH_2844          (0x2844 / 4)
#define REG_D1GRPH_PITCH        (0x6120 / 4)
#define REG_D1GRPH_X_END        (0x6134 / 4)
#define REG_D1GRPH_Y_END        (0x6138 / 4)
#define REG_DOUBLE_BUFFER_CTL   (0x60ec / 4)

typedef display_surface_t display_surface;
static display_surface old_surface;

/*
 * Scaler registers (byte offsets; xsdk src/display.c): enable, tap control,
 * viewport size, viewport width / 4 - 1, then filter control, scale (8.24)
 * and start phase, horizontal and vertical. 0x65CC bit 16 holds them until
 * it's released.
 */
#define SCALER_REGISTERS 10
static const uint16_t scaler_offsets[SCALER_REGISTERS] = {
    0x6590, 0x6594, 0x6584, 0x65e8, 0x65b0, 0x65b4, 0x65b8, 0x65c0, 0x65c4, 0x65c8};
#define REG_SCALER_UPDATE (0x65cc / 4)
static uint32_t kernel_scaler[SCALER_REGISTERS];
static uint32_t own_scaler[SCALER_REGISTERS];   /* for the title's surface */

static void scaler_write(const uint32_t values[SCALER_REGISTERS])
{
    if (!display.controller) return;
    gpu_write(REG_SCALER_UPDATE, 0x10000);
    for (int i = 0; i < SCALER_REGISTERS; i++) gpu_write(scaler_offsets[i] / 4, values[i]);
    gpu_write(REG_SCALER_UPDATE, 0);
}

/* The scaler filling the output with a width x height surface: 2 taps each
 * way through the built-in filter, phase (scale + taps + 1) / 2. */
static void scaler_plan(uint32_t width, uint32_t height, uint32_t values[SCALER_REGISTERS])
{
    uint32_t h = (uint32_t)(((uint64_t)width << 24) / display.output_width);
    uint32_t v = (uint32_t)(((uint64_t)height << 24) / display.output_height);
    values[0] = (h != 1u << 24 || v != 1u << 24);
    values[1] = 0x101;
    values[2] = (width << 16) | height;
    values[3] = width / 4 - 1;
    values[4] = kernel_scaler[4] | 0x100;
    values[5] = h;
    values[6] = (3u << 15) + (h >> 9);
    values[7] = kernel_scaler[7] | 0x100;
    values[8] = v;
    values[9] = (3u << 15) + (v >> 9);
}

static int display_apply(const display_surface *s)
{
    if (!display.controller) return 1;
    gpu_write(REG_SURFACE_2840, s->address);
    gpu_write(REG_PITCH_2844, s->pitch);
    gpu_write(SCANOUT_ADDRESS, s->address);
    gpu_write(REG_D1GRPH_PITCH, s->pitch);
    gpu_write(REG_D1GRPH_X_END, s->x_end);
    gpu_write(REG_D1GRPH_Y_END, s->y_end);
    gpu_write(REG_DOUBLE_BUFFER_CTL, 1);
    uint64_t start = timebase_now();
    int ok = 1;
    while (gpu_read(REG_DOUBLE_BUFFER_CTL)) {
        if (timebase_now() - start > 49875) { ok = 0; break; }   /* 1 ms; the display clears it at once */
    }
    gpu_write(REG_DOUBLE_BUFFER_CTL, 0);
    return ok;
}

static int display_show(uint32_t address)
{
    display_surface s = { address, display.pitch_tiles * TILE_EDGE, display.pitch_tiles * TILE_EDGE,
                          display.surface_height };
    return display_apply(&s);
}

static void show_system_surface(void)
{
    static uint32_t planned_for = 0;
    static uint32_t values[SCALER_REGISTERS];
    display_surface *sys = &display.pending_surface;
    uint32_t key = (sys->pitch << 16) | sys->y_end;
    if (!display.showing_system || planned_for != key) {
        scaler_plan(sys->x_end, sys->y_end, values);
        scaler_write(values);
        planned_for = key;
        if (display.system_frames < 2)
            TRACE("guide: XAM surface %08x %ux%u pitch %u", sys->address, sys->x_end, sys->y_end, sys->pitch);
    }
    display_surface s = *sys;
    s.x_end = s.pitch;
    display_apply(&s);
    display.showing_system = 1;
    display.system_frames++;
}

static void wait_for_flip(void)
{
    if (!display.pending) return;
    uint64_t start = timebase_now();
    int verbose = flip_count < 4;
    /* the swap identifier lands first ... */
    for (;;) {
        uint32_t completed = read_word(&display.ring.writeback, SWAP_IDENTIFIER_OFFSET);
        if ((int32_t)(completed - display.pending_identifier) >= 0) break;
        if (timebase_now() - start > WAIT_TIMEOUT_TB) {
            TRACE("flip %u: TIMEOUT waiting for identifier %08x (completed %08x, rptr %u, wptr %u)",
                  flip_count, display.pending_identifier, completed,
                  read_word(&display.ring.writeback, READ_POINTER_OFFSET), display.ring.write);
            display.pending = 0;
            return;
        }
        low_priority_hint();
    }
    if (display.pending_system) {
        /* XAM's commands have drawn the Guide into its surface. Nothing
         * latches at vertical blank on this path, so keep one frame per
         * refresh (60 Hz) by the clock, or the title runs fast under it. */
        static uint64_t last_system_flip;
        const uint64_t frame = 49875000ull / 60;
        uint64_t t = timebase_now();
        if (last_system_flip && t - last_system_flip < frame) {
            while (timebase_now() - last_system_flip < frame) low_priority_hint();
            last_system_flip += frame;
        } else {
            last_system_flip = t;
        }
        show_system_surface();
        display.pending = 0;
        return;
    }
    if (display.showing_system) {
        /* the Guide closed: our surface's scaling again */
        scaler_write(own_scaler);
        display.showing_system = 0;
        TRACE("guide: closed after %u frames", display.system_frames);
    }
    /* ... then the display controller takes the address ... */
    start = timebase_now();
    while (gpu_read(SCANOUT_ADDRESS) != display.pending_address) {
        if (timebase_now() - start > WAIT_TIMEOUT_TB) {
            TRACE("flip %u: TIMEOUT scanout address %08x, expected %08x",
                  flip_count, gpu_read(SCANOUT_ADDRESS), display.pending_address);
            display.pending = 0;
            return;
        }
        low_priority_hint();
    }
    /* ... and latches it at the next blank: one flip per refresh */
    start = timebase_now();
    while (gpu_read(SCANOUT_UPDATE) & (UPDATE_PENDING | UPDATE_TAKEN)) {
        if (timebase_now() - start > WAIT_TIMEOUT_TB) {
            TRACE("flip %u: TIMEOUT scanout update %08x", flip_count, gpu_read(SCANOUT_UPDATE));
            break;
        }
        low_priority_hint();
    }
    int shown = display_show(display.pending_address);
    if (verbose) {
        TRACE("flip %u: done, scanout %08x control %08x update %08x, 60EC %s",
              flip_count, gpu_read(SCANOUT_ADDRESS), gpu_read(SCANOUT_CONTROL), gpu_read(SCANOUT_UPDATE),
              shown ? "taken" : "TIMEOUT");
    }
    display.pending = 0;
}

static void submit_flip(uint32_t address, const uint32_t fetch_constant[6], uint32_t virtual_address)
{
    VD_SYSTEM_COMMAND_BUFFER system_buffer;
    ULONG identifier = 0;
    memset(&system_buffer, 0, sizeof(system_buffer));
    VdGetSystemCommandBuffer(&system_buffer, &identifier);

    uint32_t identifier_address = (uint32_t)display.ring.writeback.words + SWAP_IDENTIFIER_OFFSET;
    uint32_t *w = ring_reserve(&display.ring, FLIP_DWORDS + SWAP_DWORDS);
    w[0] = type0(SCANOUT_ADDRESS, 1);
    w[1] = address;
    w[2] = type3(OPCODE_REGISTER_RMW, 3);
    w[3] = SCANOUT_CONTROL;
    w[4] = SCANOUT_CONTROL_KEEP;
    w[5] = 0;
    w[6] = type0(SCANOUT_FORMAT_1930, 1);
    w[7] = 0;

    /* VdSwap hands back XAM's surface here while the Guide shows
     * (xsdk docs/HARDWARE.md, "The Guide shows through VdSwap"). */
    ULONG shown_address = virtual_address, format = 6, color_space = 0;
    ULONG shown_width = display.pitch_tiles * TILE_EDGE, shown_height = display.surface_height;
    VdSwap((PULONG)(w + FLIP_DWORDS), (const ULONG *)fetch_constant, (PULONG)identifier_address,
           &system_buffer, identifier, &shown_address, &format, &color_space, &shown_width, &shown_height);

    display.pending_system = 0;
    if (display.guide_supported && system_buffer.Address && system_buffer.Dwords &&
        shown_address != virtual_address && shown_address && format == 6 && color_space == 0 &&
        shown_width && shown_height) {
        /* show XAM's surface, not ours: the scanout writes become NOPs */
        for (unsigned i = 0; i < FLIP_DWORDS; i++) w[i] = 0x80000000u;
        display.pending_system = 1;
        display.pending_surface.address = MmGetPhysicalAddress((PVOID)shown_address);
        display.pending_surface.pitch = (shown_width + 31) & ~31u;
        display.pending_surface.x_end = shown_width;
        display.pending_surface.y_end = shown_height;
    }

    ring_commit(&display.ring, FLIP_DWORDS + SWAP_DWORDS);
    ring_kick(&display.ring);
    if (flip_count < 4) {
        TRACE("flip %u: submitted address %08x identifier %08x sysbuf %08x/%u state %u",
              flip_count, address, (unsigned)identifier, (unsigned)system_buffer.Address,
              (unsigned)system_buffer.Dwords, (unsigned)system_buffer.State);
    }
    flip_count++;
    retrain_edram(0);

    display.pending = 1;
    display.pending_identifier = identifier;
    display.pending_address = address;
}

/*
 * Optional (xex_video_scaler_via_kernel): the scaler program Direct3D gets
 * from the kernel. Not needed to show a picture (the kernel's scaler
 * setting is kept), and it hung on hardware with these arguments.
 */
#define SCALER_COMMAND_DWORDS 200   /* 0x320 bytes, as D3D uses */

static void setup_scaler(uint32_t surface_w, uint32_t surface_h)
{
    uint32_t mode[16];
    memset(mode, 0, sizeof(mode));
    VdQueryVideoMode(mode);
    uint32_t out_w = mode[0] ? mode[0] : surface_w;
    uint32_t out_h = mode[1] ? mode[1] : surface_h;
    TRACE("video mode: %ux%u interlaced %u widescreen %u hidef %u",
          (unsigned)mode[0], (unsigned)mode[1], (unsigned)mode[2], (unsigned)mode[3], (unsigned)mode[4]);

    static uint32_t vertical_filter[4] __attribute__((aligned(16)));
    static uint32_t horizontal_filter[4] __attribute__((aligned(16)));
    static uint32_t commands[SCALER_COMMAND_DWORDS] __attribute__((aligned(16)));
    memset(vertical_filter, 0, sizeof(vertical_filter));
    memset(horizontal_filter, 0, sizeof(horizontal_filter));
    for (int i = 0; i < SCALER_COMMAND_DWORDS; i++) commands[i] = 0x80000000u;

    uint32_t surface_wh = (surface_w << 16) | surface_h;
    ULONG written = VdInitializeScalerCommandBuffer(0, surface_wh, 0, (out_w << 16) | out_h, surface_wh,
                                                    1, vertical_filter, 1, horizontal_filter, 0,
                                                    (PULONG)commands, SCALER_COMMAND_DWORDS);
    int used = 0;
    for (int i = 0; i < SCALER_COMMAND_DWORDS; i++) if (commands[i] != 0x80000000u) used = i + 1;
    TRACE("scaler: %ux%u -> %ux%u, returned %u, %d dwords written, first %08x %08x %08x %08x",
          (unsigned)surface_w, (unsigned)surface_h, (unsigned)out_w, (unsigned)out_h,
          (unsigned)written, used, commands[0], commands[1], commands[2], commands[3]);
    TRACE("scaler filters: v %08x %08x %08x %08x h %08x %08x %08x %08x",
          vertical_filter[0], vertical_filter[1], vertical_filter[2], vertical_filter[3],
          horizontal_filter[0], horizontal_filter[1], horizontal_filter[2], horizontal_filter[3]);

    uint32_t *w = ring_reserve(&display.ring, SCALER_COMMAND_DWORDS);
    memcpy(w, commands, sizeof(commands));
    ring_commit(&display.ring, SCALER_COMMAND_DWORDS);
    ring_kick(&display.ring);
}

/* Display controller registers (byte offsets as in libxenon's xenos.c). */
static const struct { uint16_t offset; const char *name; } display_registers[] = {
    {0x6000, "CRTC_H_TOTAL"}, {0x6020, "CRTC_V_TOTAL"}, {0x6028, "CRTC_6028"},
    {0x6080, "CRTC_CONTROL"}, {0x6084, "CRTC_BLANK"}, {0x609c, "CRTC_STATUS"},
    {0x6100, "GRPH_ENABLE"}, {0x6104, "GRPH_CONTROL"}, {0x6110, "GRPH_SURFACE"},
    {0x6120, "GRPH_PITCH"}, {0x6124, "GRPH_OFS_X"}, {0x6128, "GRPH_OFS_Y"},
    {0x612c, "GRPH_X_START"}, {0x6130, "GRPH_Y_START"}, {0x6134, "GRPH_X_END"},
    {0x6138, "GRPH_Y_END"}, {0x6144, "GRPH_UPDATE"}, {0x6148, "GRPH_FLIP"},
    {0x6520, "MODE_6520"}, {0x6524, "MODE_6524"}, {0x6528, "MODE_DATA_FMT"},
    {0x652c, "DESKTOP_H"}, {0x6548, "MODE_6548"}, {0x6550, "MODE_6550"},
    {0x6580, "VIEWPORT_START"}, {0x6584, "VIEWPORT_SIZE"}, {0x6590, "SCL_ENABLE"},
    {0x6594, "SCL_TAP"}, {0x65a0, "SCL_65a0"}, {0x65b0, "SCL_65b0"}, {0x65b4, "SCL_65b4"},
    {0x65b8, "SCL_65b8"}, {0x65c0, "SCL_65c0"}, {0x65c4, "SCL_65c4"}, {0x65c8, "SCL_65c8"},
    {0x65cc, "SCL_UPDATE"}, {0x65d0, "SCL_65d0"}, {0x65dc, "SCL_65dc"}, {0x65e8, "SCL_65e8"},
    {0x6108, "GRPH_LUT_SEL"}, {0x6058, "MVP_BLACK_KEYER"},
    {0x6380, "CMATRIX_CNTL"}, {0x6384, "CM_1_1"}, {0x6388, "CM_1_2"}, {0x638c, "CM_1_3"},
    {0x6390, "CM_1_4"}, {0x6394, "CM_2_1"}, {0x6398, "CM_2_2"}, {0x639c, "CM_2_3"},
    {0x63a0, "CM_2_4"}, {0x63a4, "CM_3_1"}, {0x63a8, "CM_3_2"}, {0x63ac, "CM_3_3"},
    {0x63b0, "CM_3_4"}, {0x63b4, "CM_63b4"},
    {0x6484, "LUT_RW_MODE"}, {0x6488, "LUT_RW_INDEX"}, {0x649c, "LUT_WRITE_EN"},
    {0x64a0, "LUT_AUTOFILL"}, {0x64c0, "LUTA_CONTROL"}, {0x64c4, "LUTA_64c4"},
    {0x64c8, "LUTA_64c8"}, {0x64cc, "LUTA_64cc"}, {0x64d0, "LUTA_64d0"},
    {0x64d4, "LUTA_64d4"}, {0x64d8, "LUTA_64d8"},
    {0x2840, "DETILE_BASE"}, {0x2844, "DETILE_PITCH"}, {0x2848, "DETILE_2848"},
    {0x7900, "OUT_7900"}, {0x7938, "OUT_7938"}, {0x793c, "OUT_793c"},
};

void xex_video_dump_registers(const char *label)
{
    char line[200];
    int n = 0;
    TRACE("registers (%s):", label);
    for (unsigned i = 0; i < sizeof(display_registers) / sizeof(display_registers[0]); i++) {
        n += snprintf(line + n, sizeof(line) - n, " %s=%08x", display_registers[i].name,
                      (unsigned)gpu_read(display_registers[i].offset / 4));
        if (n > 120 || i + 1 == sizeof(display_registers) / sizeof(display_registers[0])) {
            TRACE("  %s", line);
            n = 0;
        }
    }
}

uint32_t xex_video_read_register(uint32_t offset) { return gpu_read(offset / 4); }
void xex_video_write_register(uint32_t offset, uint32_t value) { gpu_write(offset / 4, value); }

void xex_video_dump_lut(void)
{
    static const int entries[] = {0, 1, 64, 128, 192, 255};
    for (unsigned i = 0; i < sizeof(entries) / sizeof(entries[0]); i++) {
        gpu_write(0x6488 / 4, entries[i]);
        TRACE("  LUT[%d] = %08x", entries[i], (unsigned)gpu_read(0x6494 / 4));
    }
}

/* The kernel leaves the display LUT zeroed for a starting title (every
 * colour maps to black); load an identity ramp like libxenon does. */
static int load_identity_gamma(void)
{
    gpu_write(0x6108 / 4, 0);   /* D1GRPH_LUT_SEL: LUT A */
    gpu_write(0x64c0 / 4, 0);   /* DC_LUTA_CONTROL */
    gpu_write(0x6488 / 4, 0);   /* DC_LUT_RW_INDEX */
    gpu_write(0x6484 / 4, 0);   /* DC_LUT_RW_MODE */
    gpu_write(0x649c / 4, 7);   /* DC_LUT_WRITE_EN_MASK */
    gpu_write(0x64a0 / 4, 1);   /* DC_LUT_AUTOFILL */
    uint64_t start = timebase_now();
    while (!(gpu_read(0x64a0 / 4) & 2) && timebase_now() - start < WAIT_TIMEOUT_TB) {}
    int loaded = (gpu_read(0x64a0 / 4) & 2) != 0;
    TRACE("gamma: identity LUT %s", loaded ? "loaded" : "timed out (no display controller: Xenia?)");
    return loaded;
}

int xex_video_scaler_via_kernel = 0;

/*
 * Tells XAM the title's display (graphics notification event 1, 64 bytes,
 * as D3D does), so it draws the frame under the Guide at the right size
 * (xsdk src/present.c describe_display).
 */
typedef struct {
    uint16_t front_width, front_height, output_width, output_height;
    uint32_t left, top, right, bottom;
    uint32_t scaled_width, scaled_height;
    uint32_t filters[8];
} display_description;

static void describe_display(uint32_t width, uint32_t height)
{
    uint32_t mode[16];
    memset(mode, 0, sizeof(mode));
    VdQueryVideoMode(mode);
    display.output_width = mode[0];
    display.output_height = mode[1];
    /* XAM's surface is scaled by hand; xsdk only tried progressive modes */
    display.guide_supported = display.controller && mode[0] && mode[1] && !mode[2];
    TRACE("guide: output %ux%u interlaced %u -> %s", (unsigned)mode[0], (unsigned)mode[1], (unsigned)mode[2],
          display.guide_supported ? "supported" : "not supported");
    if (!display.guide_supported) return;
    display_description d;
    memset(&d, 0, sizeof(d));
    d.front_width = (uint16_t)width;
    d.front_height = (uint16_t)height;
    d.output_width = (uint16_t)display.output_width;
    d.output_height = (uint16_t)display.output_height;
    d.right = width;
    d.bottom = height;
    d.scaled_width = display.output_width;
    d.scaled_height = display.output_height;
    VdCallGraphicsNotificationRoutines(1, &d);
}

int xex_video_guide_visible(void) { return display.showing_system; }

const char *xex_video_error(void)
{
    return display.error ? display.error : "";
}

int xex_video_native = 1;

int xex_video_init(void)
{
    if (display.open) return 0;

    VD_DISPLAY_INFORMATION info;
    memset(&info, 0, sizeof(info));
    VdGetCurrentDisplayInformation(&info);
    uint32_t sw = info.SurfaceWidth, sh = info.SurfaceHeight;
    TRACE("display: surface %ux%u window %u,%u-%u,%u colorspace %u",
          (unsigned)sw, (unsigned)sh, (unsigned)info.Left, (unsigned)info.Top,
          (unsigned)info.Right, (unsigned)info.Bottom, (unsigned)info.ColorSpace);
    if (sw == 0 || sh == 0 || sw % TILE_EDGE != 0) {
        display.error = "unsupported display mode";
        return -1;
    }
    if (info.Left % TILE_EDGE || info.Top % TILE_EDGE || info.Right <= info.Left ||
        info.Bottom <= info.Top || info.Right > sw || info.Bottom > sh) {
        display.error = "unsupported display window";
        return -1;
    }

    /* Null microcode selects the kernel's own. */
    ULONG engines = VdInitializeEngines(0, NULL, NULL, NULL, NULL);
    TRACE("VdInitializeEngines -> %u, scanout before: %08x control %08x",
          (unsigned)engines, gpu_read(SCANOUT_ADDRESS), gpu_read(SCANOUT_CONTROL));
    if (ring_init(&display.ring) != 0) {
        VdShutdownEngines();
        display.error = "out of memory (ring)";
        return -1;
    }
    TRACE("ring: commands %08x writeback %08x, rptr %u wptr %u",
          (unsigned)display.ring.commands.physical, (unsigned)display.ring.writeback.physical,
          read_word(&display.ring.writeback, READ_POINTER_OFFSET), display.ring.write);
    display.open = 1;
    display.back = 0;
    display.pending = 0;
    retrain_edram(1);
    /* VdInitializeScalerCommandBuffer hangs on hardware with these
     * arguments, so it is off unless a test turns it on. */
    if (xex_video_scaler_via_kernel) setup_scaler(sw, sh);
    display.presented = 0;

    /* The display's LUT is zero while a title runs: load a ramp. Whether
     * the autofill finishes also tells whether a display controller is
     * there (not in Xenia). */
    display.controller = load_identity_gamma();
    old_surface.address = gpu_read(SCANOUT_ADDRESS);
    old_surface.pitch = gpu_read(REG_D1GRPH_PITCH);
    old_surface.x_end = gpu_read(REG_D1GRPH_X_END);
    old_surface.y_end = gpu_read(REG_D1GRPH_Y_END);
    for (int i = 0; i < SCALER_REGISTERS; i++) kernel_scaler[i] = gpu_read(scaler_offsets[i] / 4);

    /* Native mode: front buffers of the output's size shown 1:1 with the
     * scaler off (as libxenon does; xsdk docs/HARDWARE.md, "a 1280x720
     * surface shows 1:1"), instead of the kernel's 640x480 surface that the
     * scaler stretches (blurry, and 4:3 pulled to 16:9). Progressive modes
     * only. */
    uint32_t mode[16];
    memset(mode, 0, sizeof(mode));
    VdQueryVideoMode(mode);
    display.output_width = mode[0];
    display.output_height = mode[1];
    display.native = xex_video_native && display.controller && mode[0] && mode[1] && !mode[2] &&
                     mode[0] % TILE_EDGE == 0 && mode[0] <= 1920 && mode[1] <= 1088;
    TRACE("output %ux%u interlaced %u -> %s", (unsigned)mode[0], (unsigned)mode[1], (unsigned)mode[2],
          display.native ? "native surface, scaler off" : "kernel surface, kernel scaling");
    if (display.native) {
        sw = mode[0];
        sh = mode[1];
        info.Left = info.Top = 0;
        info.Right = sw;
        info.Bottom = sh;
    }
    display.pitch_tiles = sw / TILE_EDGE;
    display.tile_x = info.Left / TILE_EDGE;
    display.tile_y = info.Top / TILE_EDGE;
    display.width = info.Right - info.Left;
    display.height = info.Bottom - info.Top;
    display.surface_height = sh;

    uint32_t tiles_high = (sh + TILE_EDGE - 1) / TILE_EDGE;
    uint32_t bytes = display.pitch_tiles * tiles_high * TILE_EDGE * TILE_EDGE * 4;
    for (int i = 0; i < 2; i++) {
        front_buffer *fb = &display.buffers[i];
        if (phys_alloc(&fb->memory, bytes, PAGE_WRITECOMBINE_) != 0) {
            display.error = "out of memory (front buffer)";
            xex_video_shutdown();
            return -1;
        }
        volatile uint32_t *w = fb->memory.words;
        for (uint32_t j = 0; j < fb->memory.bytes / 4; j++) w[j] = 0x000000ffu;   /* opaque black */
        front_buffer_fetch(fb->fetch_constant, (uint32_t)fb->memory.words, display.pitch_tiles, sw, sh);
        TRACE("front buffer %d: %ux%u virtual %08x physical %08x bytes %u", i, (unsigned)sw, (unsigned)sh,
              (unsigned)(uint32_t)fb->memory.words, (unsigned)fb->memory.physical, (unsigned)fb->memory.bytes);
    }

    if (display.native) {
        scaler_plan(sw, sh, own_scaler);
        scaler_write(own_scaler);
    } else {
        memcpy(own_scaler, kernel_scaler, sizeof(own_scaler));
    }
    describe_display(sw, sh);
    int shown = display_show(display.buffers[1].memory.physical);
    TRACE("show buffer 1: %s, scanout %08x", shown ? "taken" : "TIMEOUT", gpu_read(SCANOUT_ADDRESS));
    atexit(xex_video_shutdown);
    return 0;
}

xex_frame xex_video_begin(void)
{
    xex_frame f;
    memset(&f, 0, sizeof(f));
    if (!display.open) return f;
    wait_for_flip();
    f.pixels = display.buffers[display.back].memory.words;
    f.pitch = (int)(display.pitch_tiles * TILE_EDGE);
    f.window_x = (int)(display.tile_x * TILE_EDGE);
    f.window_y = (int)(display.tile_y * TILE_EDGE);
    f.window_width = (int)display.width;
    f.window_height = (int)display.height;
    return f;
}

void xex_video_present(void)
{
    if (!display.open) return;
    front_buffer *fb = &display.buffers[display.back];
    submit_flip(fb->memory.physical, fb->fetch_constant, (uint32_t)fb->memory.words);
    display.back ^= 1;
    if (display.presented++ == 0) xex_video_dump_registers("after first flip");
}

void xex_video_shutdown(void)
{
    if (!display.open) return;
    wait_for_flip();
    /* leave the scanout at address 0 as the kernel's own ring does */
    submit_flip(0, display.buffers[display.back ^ 1].fetch_constant, 0);
    wait_for_flip();
    if (display.native || display.showing_system) scaler_write(kernel_scaler);
    display_apply(&old_surface);
    ring_detach(&display.ring);
    VdShutdownEngines();
    display.open = 0;
    for (int i = 0; i < 2; i++) phys_free(&display.buffers[i].memory);
    phys_free(&display.ring.commands);
    phys_free(&display.ring.writeback);
}