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

/platform/xex/runtime/video.c · 20.47 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 <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);

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;

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

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();
    }
    /* ... 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();
    }
    if (verbose) {
        TRACE("flip %u: done, scanout %08x control %08x update %08x",
              flip_count, gpu_read(SCANOUT_ADDRESS), gpu_read(SCANOUT_CONTROL), gpu_read(SCANOUT_UPDATE));
    }
    display.pending = 0;
}

static void submit_flip(uint32_t address, const uint32_t fetch_constant[6])
{
    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;

    ULONG out0, out1, out2, out3, out4;
    VdSwap((PULONG)(w + FLIP_DWORDS), (const ULONG *)fetch_constant, (PULONG)identifier_address,
           &system_buffer, identifier, &out0, &out1, &out2, &out3, &out4);

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

/*
 * Program the display scaler the way Direct3D does after device creation:
 * the kernel writes scaler packets (source surface -> output mode) into a
 * NOP-filled buffer, which goes into the command ring. Without it the
 * scanout of a title surface is not shown (black screen on hardware;
 * Xenia does not emulate the scaler).
 */
#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);
}

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

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

    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)";
            return -1;
        }
        memset(fb->memory.words, 0, fb->memory.bytes);
        front_buffer_fetch(fb->fetch_constant, (uint32_t)fb->memory.words, display.pitch_tiles, sw, sh);
        TRACE("front buffer %d: virtual %08x physical %08x bytes %u", i,
              (unsigned)(uint32_t)fb->memory.words, (unsigned)fb->memory.physical, (unsigned)fb->memory.bytes);
    }

    /* 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);
    setup_scaler(sw, sh);
    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);
    display.back ^= 1;
}

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);
    wait_for_flip();
    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);
}