/* spu_workload.c — SPU workload / task dispatch registry (see spu_workload.h).
 *
 * Maps a registered SPU image (by FNV-1a-64 content fingerprint) to its
 * pre-lifted native entry, loads the image into a 256 KB local store, and runs
 * it with the SPURS task ABI. cellSpurs's AddWorkload/CreateTask call
 * spu_workload_dispatch(); the registry is populated by the title's lifted set.
 */
#include "spu_workload.h"
#include "spu_lifted_job.h"   /* spu_run_lifted_job */
#include "../ps3_log.h"      /* ps3_log_verbose */
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <sys/stat.h>
#endif
#include "ps3emu/log_first.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <pthread.h>
#include <errno.h>
#include "../platform/win32_compat.h"   /* LONG, InterlockedExchange, Sleep */
#endif

/* Set by the MFC DMA engine (spu_dma.h) when the cri task (image 22) issues a
 * real video-payload GET (>256B from a non-context EA) = it actually decoded,
 * as opposed to the 64-byte context handshake DMAs. The dispatcher's
 * YDKJ_CRI_RESUME poll-loop watches this to know real work arrived. */
int g_cri_video_dma = 0;

/* Explicit-identity async dispatch (defined below; also in spu_workload.h). */
int spu_workload_dispatch_async_task(const uint8_t* image, uint32_t image_size,
                                     uint32_t args_ea, uint32_t taskset_ea,
                                     uint32_t taskid);

/* ---- fingerprint ------------------------------------------------------- */

uint64_t spu_workload_fingerprint(const void* data, size_t n)
{
    const uint8_t* p = (const uint8_t*)data;
    uint64_t h = 1469598103934665603ULL;          /* FNV offset basis */
    for (size_t i = 0; i < n; i++) {
        h ^= p[i];
        h *= 1099511628211ULL;                     /* FNV prime */
    }
    return h;
}

/* ---- registry ---------------------------------------------------------- */

#ifndef SPU_WORKLOAD_MAX
#define SPU_WORKLOAD_MAX 256
#endif

typedef struct {
    uint64_t            fp;
    spu_lifted_entry_fn fn;
    int                 image_id;
    const char*         name;
} spu_workload_entry;

static spu_workload_entry s_registry[SPU_WORKLOAD_MAX];
static unsigned           s_registry_count = 0;

void spu_workload_register_img(uint64_t fingerprint, spu_lifted_entry_fn fn,
                               int image_id, const char* name)
{
    if (!fn) return;
    for (unsigned i = 0; i < s_registry_count; i++) {
        if (s_registry[i].fp == fingerprint) {     /* idempotent on fingerprint */
            s_registry[i].fn       = fn;
            s_registry[i].image_id = image_id;
            s_registry[i].name     = name;
            return;
        }
    }
    if (s_registry_count >= SPU_WORKLOAD_MAX) {
        fprintf(stderr, "[spu_workload] registry full (%u); dropping '%s'\n",
                SPU_WORKLOAD_MAX, name ? name : "?");
        return;
    }
    s_registry[s_registry_count].fp       = fingerprint;
    s_registry[s_registry_count].fn       = fn;
    s_registry[s_registry_count].image_id = image_id;
    s_registry[s_registry_count].name     = name;
    s_registry_count++;
}

void spu_workload_register(uint64_t fingerprint, spu_lifted_entry_fn fn,
                           const char* name)
{
    spu_workload_register_img(fingerprint, fn, 0, name);
}

spu_lifted_entry_fn spu_workload_find(uint64_t fingerprint)
{
    for (unsigned i = 0; i < s_registry_count; i++)
        if (s_registry[i].fp == fingerprint)
            return s_registry[i].fn;
    return NULL;
}

spu_lifted_entry_fn spu_workload_find_img(uint64_t fingerprint, int* image_id_out)
{
    for (unsigned i = 0; i < s_registry_count; i++)
        if (s_registry[i].fp == fingerprint) {
            if (image_id_out) *image_id_out = s_registry[i].image_id;
            return s_registry[i].fn;
        }
    if (image_id_out) *image_id_out = 0;
    return NULL;
}

unsigned spu_workload_count(void) { return s_registry_count; }

/* ---- SPU ELF loader (32-bit big-endian) -------------------------------- */

static uint16_t rd_be16(const uint8_t* p) { return (uint16_t)((p[0] << 8) | p[1]); }
static uint32_t rd_be32(const uint8_t* p)
{
    return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8)  |  (uint32_t)p[3];
}

int spu_elf_load_to_ls(const uint8_t* image, size_t image_size, uint8_t* ls, uint32_t* entry_out)
{
    if (!image || !ls || image_size < 0x34) return 0;

    /* ELF ident: 0x7F 'E' 'L' 'F', ELFCLASS32 (1), ELFDATA2MSB (2). */
    if (!(image[0] == 0x7F && image[1] == 'E' && image[2] == 'L' && image[3] == 'F'))
        return 0;
    if (image[4] != 1 /*ELFCLASS32*/ || image[5] != 2 /*ELFDATA2MSB*/)
        return 0;

    uint32_t e_entry     = rd_be32(image + 0x18);
    uint32_t e_phoff     = rd_be32(image + 0x1C);
    uint16_t e_phentsize = rd_be16(image + 0x2A);
    uint16_t e_phnum     = rd_be16(image + 0x2C);
    if (e_phentsize < 0x20) e_phentsize = 0x20;

    for (uint16_t i = 0; i < e_phnum; i++) {
        size_t po = (size_t)e_phoff + (size_t)i * e_phentsize;
        if (po + 0x20 > image_size) break;
        const uint8_t* ph = image + po;

        uint32_t p_type   = rd_be32(ph + 0x00);
        if (p_type != 1 /*PT_LOAD*/) continue;
        uint32_t p_offset = rd_be32(ph + 0x04);
        uint32_t p_vaddr  = rd_be32(ph + 0x08);
        uint32_t p_filesz = rd_be32(ph + 0x10);
        uint32_t p_memsz  = rd_be32(ph + 0x14);

        /* bounds: segment must fit in local store and in the image */
        if ((uint64_t)p_vaddr + p_memsz > SPU_LS_SIZE)            return 0;
        if ((uint64_t)p_offset + p_filesz > image_size)          return 0;

        if (p_filesz) memcpy(ls + p_vaddr, image + p_offset, p_filesz);
        if (p_memsz > p_filesz)
            memset(ls + p_vaddr + p_filesz, 0, p_memsz - p_filesz);
    }
    if (entry_out) *entry_out = e_entry;
    return 1;
}

size_t spu_elf_image_size(const uint8_t* image, size_t max_avail)
{
    if (!image || max_avail < 0x34) return 0;
    if (!(image[0] == 0x7F && image[1] == 'E' && image[2] == 'L' && image[3] == 'F'))
        return 0;
    if (image[4] != 1 || image[5] != 2) return 0;     /* ELFCLASS32, ELFDATA2MSB */

    uint32_t e_phoff     = rd_be32(image + 0x1C);
    uint32_t e_shoff     = rd_be32(image + 0x20);
    uint16_t e_phentsize = rd_be16(image + 0x2A);
    uint16_t e_phnum     = rd_be16(image + 0x2C);
    uint16_t e_shentsize = rd_be16(image + 0x2E);
    uint16_t e_shnum     = rd_be16(image + 0x30);

    uint64_t end = (uint64_t)e_shoff + (uint64_t)e_shnum * e_shentsize;

    for (uint16_t k = 0; k < e_phnum; k++) {           /* program headers */
        size_t po = (size_t)e_phoff + (size_t)k * e_phentsize;
        if (po + 0x14 > max_avail) break;
        uint32_t p_offset = rd_be32(image + po + 0x04);
        uint32_t p_filesz = rd_be32(image + po + 0x10);
        uint64_t e = (uint64_t)p_offset + p_filesz;
        if (e > end) end = e;
    }
    for (uint16_t k = 0; k < e_shnum; k++) {           /* section headers */
        size_t so = (size_t)e_shoff + (size_t)k * e_shentsize;
        if (so + 0x18 > max_avail) break;
        uint32_t sh_type   = rd_be32(image + so + 0x04);
        uint32_t sh_offset = rd_be32(image + so + 0x10);
        uint32_t sh_size   = rd_be32(image + so + 0x14);
        if (sh_type != 8 /*SHT_NOBITS*/) {
            uint64_t e = (uint64_t)sh_offset + sh_size;
            if (e > end) end = e;
        }
    }
    if (end > max_avail) end = max_avail;
    return (size_t)end;
}

/* ---- dispatch ---------------------------------------------------------- */

int spu_workload_dispatch(const uint8_t* image, uint32_t image_size,
                          uint32_t args_ea)
{
    if (!image || image_size == 0) return 0;

    uint64_t fp = spu_workload_fingerprint(image, image_size);
    spu_lifted_entry_fn fn = NULL;
    int image_id = 0;
    for (unsigned i = 0; i < s_registry_count; i++)
        if (s_registry[i].fp == fp) { fn = s_registry[i].fn; image_id = s_registry[i].image_id; break; }
    if (!fn) {
        fprintf(stderr,
            "[spu_workload] dispatch MISS fp=0x%016llX size=%u "
            "(no lifted SPU binary registered for this image)\n",
            (unsigned long long)fp, image_size);
        return 0;
    }

    /* Load the SPU ELF into a fresh local store, then run the lifted entry with
     * the task arg in r3. 256 KB is heap-allocated (too large for the stack,
     * and spu_run_lifted_job already builds a full spu_context on its stack). */
    uint8_t* ls = (uint8_t*)calloc(1, SPU_LS_SIZE);
    if (!ls) return 0;

    uint32_t entry = 0;
    if (!spu_elf_load_to_ls(image, image_size, ls, &entry)) {
        fprintf(stderr, "[spu_workload] dispatch fp=0x%016llX: not a valid SPU ELF\n", (unsigned long long)fp);
        free(ls);
        return 0;
    }

    if (rr_spurs_verbose()) fprintf(stderr,
        "[spu_workload] dispatch HIT fp=0x%016llX entry=0x%05X args=0x%08X image=%d -> running\n",
        (unsigned long long)fp, entry, args_ea, image_id);

    spu_run_lifted_job_img(fn, ls, args_ea, image_id);

    free(ls);
    return 1;
}

/* Async dispatch: run the SPU job on its OWN host thread so the PPU caller is
 * not blocked. SPURS service/worker tasks are persistent — they loop waiting on
 * PPU-side signals (DMA, event flags, event queues), so running them inline (as
 * spu_workload_dispatch does) deadlocks: the PPU can never deliver the signal
 * the SPU is waiting for because it is stuck inside the dispatch. Real SPUs run
 * concurrently with the PPU; a detached host thread models that. The image bytes
 * and args live in the shared guest arena (vm_base), so they stay valid. */
typedef struct {
    const uint8_t*      image;
    uint32_t            image_size;
    uint32_t            args_ea;
    spu_lifted_entry_fn fn;
    int                 image_id;
    uint32_t            r3[4];        /* captured race-free at dispatch time */
    int                 have_r3;
    uint32_t            taskset_ea;   /* captured race-free at dispatch (globals get clobbered) */
    uint32_t            taskid;
} spu_async_job;

/* ---- Persistent per-taskset local store (LBP_PERSIST_LS) ------------------
 * Real SPURS time-multiplexes a taskset's tasks onto SPUs, saving/restoring a
 * shared taskset context in LS. Our default model runs each task ONCE on a
 * fresh calloc'd LS, so state one task establishes (e.g. FMOD's SPU DSP handler
 * table at LS 0x39Dxx, built by the init task) is invisible to the next task of
 * the same taskset, which reads the uninitialised image sentinel and
 * branch-to-0's. Give each taskset a PERSISTENT LS reused across its task
 * dispatches (image loaded once, state retained) and SERIALIZE its tasks (one
 * at a time) so they observe each other's setup without racing the shared
 * store -- a cooperative approximation of the kernel's context save/restore.
 * With LBP_WS_DRAIN (a task parked in WAIT_SIGNAL resumes + releases the
 * taskset, letting the next task run), the FMOD init + DSP tasks share one LS
 * and the handler table is populated when the DSP dispatch reads it. Opt-in;
 * default keeps per-dispatch fresh LS. */
typedef struct {
    uint32_t taskset_ea;   /* 0 = free slot */
    uint32_t taskid;       /* slot key is (taskset, task): on real SPURS each
                            * task has a PRIVATE LS context (the kernel saves/
                            * restores per task); one shared slot per TASKSET
                            * serialized siblings behind one lock, and FMOD's
                            * persistent mixer (task 0, never returns) starved
                            * its producer (task 1) forever -- the mixer then
                            * DMA-polled a NULL control EA for the whole run. */
    uint8_t* ls;           /* persistent LS (NULL until first task loads it) */
    int      loaded;       /* image loaded into ls */
#ifdef _WIN32
    SRWLOCK  lock;         /* serializes re-dispatches of this ONE task */
#else
    pthread_mutex_t lock;
#endif
} spu_ts_ls_slot;

#define SPU_TS_LS_MAX 24
static spu_ts_ls_slot s_ts_ls[SPU_TS_LS_MAX];
#ifdef _WIN32
static SRWLOCK s_ts_ls_dir = SRWLOCK_INIT;
#else
static pthread_mutex_t s_ts_ls_dir = PTHREAD_MUTEX_INITIALIZER;
#endif

static int spu_persist_ls_enabled(void)
{ static int _p = -1; if (_p < 0) _p = getenv("LBP_PERSIST_LS") ? 1 : 0; return _p; }

/* ---- Global SPU execution serialization (LBP_SPU_SERIAL) ------------------
 * Default runs each SPU task on its own detached host thread, so N tasks race:
 * timing jitter sends each boot down a different path to a different dead end
 * (one run hangs on the FMOD DSP null, the next on an unrelated PPU init spin),
 * which makes any single failure impossible to reproduce and debug. Serialize:
 * only ONE SPU task executes at a time (global lock), so the SPU stage becomes
 * a fixed, repeatable sequence. A task that parks in WAIT_SIGNAL RELEASES the
 * lock so another task can run (and possibly signal it) -- cooperative, mirrors
 * a single SPU's task scheduling; with LBP_WS_DRAIN a genuinely unsignalled
 * task drains and releases. Opt-in; default keeps concurrent per-thread SPU. */
static int spu_serial_enabled(void)
{ static int _s = -1; if (_s < 0) _s = getenv("LBP_SPU_SERIAL") ? 1 : 0; return _s; }
#ifdef _WIN32
static SRWLOCK s_spu_serial = SRWLOCK_INIT;
void spu_serial_acquire(void){ if (spu_serial_enabled()) AcquireSRWLockExclusive(&s_spu_serial); }
void spu_serial_release(void){ if (spu_serial_enabled()) ReleaseSRWLockExclusive(&s_spu_serial); }
#else
static pthread_mutex_t s_spu_serial = PTHREAD_MUTEX_INITIALIZER;
void spu_serial_acquire(void){ if (spu_serial_enabled()) pthread_mutex_lock(&s_spu_serial); }
void spu_serial_release(void){ if (spu_serial_enabled()) pthread_mutex_unlock(&s_spu_serial); }
#endif

/* Find-or-create the slot for a (taskset, task) pair (directory lock held
 * briefly). Per-task keying is load-bearing: see spu_ts_ls_slot.taskid. */
static spu_ts_ls_slot* ts_ls_get(uint32_t taskset_ea, uint32_t taskid)
{
    spu_ts_ls_slot* slot = NULL;
#ifdef _WIN32
    AcquireSRWLockExclusive(&s_ts_ls_dir);
#else
    pthread_mutex_lock(&s_ts_ls_dir);
#endif
    for (int i = 0; i < SPU_TS_LS_MAX && !slot; i++)
        if (s_ts_ls[i].taskset_ea == taskset_ea && s_ts_ls[i].taskid == taskid)
            slot = &s_ts_ls[i];
    for (int i = 0; i < SPU_TS_LS_MAX && !slot; i++)
        if (s_ts_ls[i].taskset_ea == 0) {
            s_ts_ls[i].taskset_ea = taskset_ea;
            s_ts_ls[i].taskid = taskid;
#ifdef _WIN32
            InitializeSRWLock(&s_ts_ls[i].lock);
#else
            pthread_mutex_init(&s_ts_ls[i].lock, NULL);
#endif
            slot = &s_ts_ls[i];
        }
#ifdef _WIN32
    ReleaseSRWLockExclusive(&s_ts_ls_dir);
#else
    pthread_mutex_unlock(&s_ts_ls_dir);
#endif
    return slot;
}

/* Minimal taskset scheduling for tasks the PPU never created.
 *
 * SPU code can create tasks itself, or mark existing ones ready, and rely on
 * the taskset policy module to schedule them. Tasks created from the PPU are
 * dispatched by our cellSpursCreateTask, but nothing looked at the taskset
 * afterwards, so SPU-scheduled work never ran. Guitar Hero III's Havok task
 * hands the rest of each physics step to other tasks and EXITs, and the step
 * then waits forever.
 *
 * Runs when a task of the taskset returns (our runner returns on the EXIT
 * syscall; waiting tasks park instead). The returning task's ready, pending
 * and enabled bits are cleared, as the real policy does on exit, and every
 * other enabled task that is pending or ready and not already running here is
 * started from its ELF.
 *
 * Taskset layout: bitsets of 16 bytes at +0x10 ready, +0x20 pending,
 * +0x30 enabled (task 0 = MSB of byte 0); task_info[t] at +0x80 + 0x30*t with
 * the ELF EA at +0x14 and the context save EA at +0x1C. */
#define TS_TRACK 8
static struct { uint32_t ea; uint8_t running[16]; } s_ts_run[TS_TRACK];
static volatile LONG s_ts_lock;
static _Thread_local int s_ts_held;   /* this thread holds s_ts_lock */
static uint8_t* ts_running(uint32_t taskset_ea)
{
    for (int i = 0; i < TS_TRACK; i++) if (s_ts_run[i].ea == taskset_ea) return s_ts_run[i].running;
    for (int i = 0; i < TS_TRACK; i++) if (!s_ts_run[i].ea) { s_ts_run[i].ea = taskset_ea; return s_ts_run[i].running; }
    return NULL;
}
static void ts_lock(void)   { while (InterlockedExchange(&s_ts_lock, 1)) Sleep(0); }
static void ts_unlock(void) { InterlockedExchange(&s_ts_lock, 0); }

static void spu_taskset_mark(uint32_t taskset_ea, uint32_t t, int on)
{
    if (!taskset_ea || t >= 128 || s_ts_held) return;   /* held: caller set it */
    ts_lock();
    uint8_t* r = ts_running(taskset_ea);
    uint8_t m = (uint8_t)(0x80u >> (t & 7));
    if (r) { if (on) r[t / 8] |= m; else r[t / 8] &= (uint8_t)~m; }
    ts_unlock();
}

/* For cellSpursCreateTask: mark the slot running BEFORE its ready/enabled
 * bits go into the taskset, or a task exiting in between starts it too. */
void spu_taskset_mark_running(uint32_t taskset_ea, uint32_t t)
{
    spu_taskset_mark(taskset_ea, t, 1);
}

/* CellSpursTaskset2 keeps a 16-byte task_exit_code[128] at +0x1980 that the
     * SPU-side join reads: byte 14 must be 0 (non-zero reads as ESRCH), byte 15 low nibble =
     * state (2 = exited, 4 = joined), exit code at +8. The SPURS kernel writes
     * it when a task exits; nothing here did, so a task that joins its workers
     * (Havok's master SPU task does) retried forever and the PPU waited on it.
     * Only Taskset2s have the array -- a v1 taskset ends at 0x1900. */
static uint32_t s_ts2[16]; static int s_n_ts2;
void spu_taskset2_register(uint32_t ea)
{
    for (int i = 0; i < s_n_ts2; i++) if (s_ts2[i] == ea) return;
    if (s_n_ts2 < 16) s_ts2[s_n_ts2++] = ea;
}
static int spu_taskset_is_v2(uint32_t ea)
{
    for (int i = 0; i < s_n_ts2; i++) if (s_ts2[i] == ea) return 1;
    return 0;
}
void spu_taskset2_set_exit(uint32_t taskset_ea, uint32_t task, int exited, uint32_t code)
{
    extern uint8_t* vm_base;
    if (task >= 128 || !spu_taskset_is_v2(taskset_ea)) return;
    extern void spu_lockline_lock(void); extern void spu_lockline_unlock(void);
    extern void spu_coh_notify_write(uint32_t);
    const uint32_t ea = taskset_ea + 0x1980 + 16u * task;
    uint8_t* e = vm_base + ea;
    spu_lockline_lock();   /* a joining SPU may hold a reservation on this line */
    memset(e, 0, 16);
    if (exited) {
        e[8] = (uint8_t)(code >> 24); e[9] = (uint8_t)(code >> 16); e[10] = (uint8_t)(code >> 8); e[11] = (uint8_t)code;
        e[15] = 2;   /* exited, not yet joined; byte 14 must stay 0 or the join reports ESRCH */
    }
    spu_coh_notify_write(ea);
    spu_lockline_unlock();
}

static int spu_taskset_task_exited(uint32_t taskset_ea, uint32_t done_task)
{
    extern uint8_t* vm_base;
    extern uint32_t g_ydkj_real_taskset_ea, g_ydkj_real_taskid;
    extern void spu_lockline_lock(void); extern void spu_lockline_unlock(void);
    extern void spu_coh_notify_write(uint32_t);
    ts_lock(); s_ts_held = 1;
    uint8_t* ts = vm_base + taskset_ea;
    uint8_t* run = ts_running(taskset_ea);
    if (done_task < 128) spu_taskset2_set_exit(taskset_ea, done_task, 1, 0);
    /* The ready/pending/enabled bitsets share the taskset's first line with the
     * SPU task library (GETLLAR/PUTLLC) and with cellSpursCreateTask, which
     * update them under the lock-line lock. Update them under the same lock,
     * then drop the reservations on the line, so neither side undoes the
     * other's change. Tasks to start are collected here and dispatched after
     * the lock is released (the dispatch writes guest memory itself). */
    uint32_t start_t[128], start_elf[128], start_ctx[128];
    size_t start_sz[128];
    int n_start = 0;
    spu_lockline_lock();
    if (done_task < 128) {
        uint8_t m = (uint8_t)(0x80u >> (done_task & 7));
        ts[0x10 + done_task / 8] &= (uint8_t)~m;
        ts[0x20 + done_task / 8] &= (uint8_t)~m;
        ts[0x30 + done_task / 8] &= (uint8_t)~m;
        if (run) run[done_task / 8] &= (uint8_t)~m;
    }
    for (uint32_t t = 0; t < 128 && run; t++) {
        uint8_t m = (uint8_t)(0x80u >> (t & 7));
        if (!(ts[0x30 + t / 8] & m) || (run[t / 8] & m)) continue;
        if (!((ts[0x10 + t / 8] | ts[0x20 + t / 8]) & m)) continue;
        const uint8_t* ti = ts + 0x80 + 0x30 * t;
        uint32_t elf = ((uint32_t)ti[0x14] << 24) | ((uint32_t)ti[0x15] << 16) |
                       ((uint32_t)ti[0x16] << 8) | ti[0x17];
        elf &= ~0xFu;   /* low bits are flags: an SPU-side CreateTask2 stores elf|4 */
        uint32_t ctx = ((uint32_t)ti[0x1C] << 24) | ((uint32_t)ti[0x1D] << 16) |
                       ((uint32_t)ti[0x1E] << 8) | ti[0x1F];
        /* TaskInfo stores ELF metadata in the low three bits. Keep those
         * guest bytes intact and use only the address for loading. */
        elf &= ~7u;
        if (!elf) continue;
        size_t sz = spu_elf_image_size(vm_base + elf, 2u * 1024 * 1024);
        if (!sz) continue;
        ts[0x20 + t / 8] &= (uint8_t)~m;                 /* pending -> started */
        run[t / 8] |= m;
        start_t[n_start] = t; start_elf[n_start] = elf; start_ctx[n_start] = ctx;
        start_sz[n_start] = sz; n_start++;
    }
    spu_coh_notify_write(taskset_ea);
    spu_lockline_unlock();
    for (int i = 0; i < n_start; i++) {
        if (rr_spurs_verbose()) fprintf(stderr, "[taskset] start task %u of taskset 0x%08X elf=0x%08X "
                        "(after task %u exited)\n", start_t[i], taskset_ea, start_elf[i], done_task);
        g_ydkj_real_taskset_ea = taskset_ea; g_ydkj_real_taskid = start_t[i];
        spu_workload_dispatch_async_task(vm_base + start_elf[i], (uint32_t)start_sz[i], start_ctx[i],
                                         taskset_ea, start_t[i]);
    }
    s_ts_held = 0; ts_unlock();
    return n_start;
}

/* Start any task that is enabled + ready/pending but not running. The scan
 * otherwise runs only when a task exits, and a task an SPU creates after the
 * last exit (Havok's master recreates its workers) was never noticed. */
void spu_taskset_start_pending(uint32_t taskset_ea)
{
    if (!taskset_ea) return;
    int n = spu_taskset_task_exited(taskset_ea, 0xFFFFFFFFu);
    if (n > 0) { static volatile long s_cs; long k = InterlockedIncrement(&s_cs);
        if (k <= 16 || (k % 1000) == 0)
            fprintf(stderr, "[taskset] commit-start#%ld: started %d SPU-scheduled task(s) "
                    "of taskset 0x%08X with no task exit pending\n", k, n, taskset_ea);
        fflush(stderr); }
}

/* spurs-20261108: an SPU that commits the taskset's header line (the running/
 * ready/pending/enabled bitsets live in its first 128 bytes) may just have made
 * a task runnable -- an SPU-side create, or marking an idle task ready. The real
 * taskset policy would schedule it on the next free SPU without waiting for an
 * unrelated task to exit; our only scan ran on task exit, so a task readied by
 * an SPU that then waits for it (instead of exiting) never started.
 * spu_taskset_start_pending() above existed for exactly this but had no caller.
 * Run the same scan when such a commit lands. Only tasksets this runtime
 * already dispatched tasks for are considered, and the scan skips every task it
 * has marked running (PPU-created tasks are marked before their bits are set),
 * so nothing is started twice. RR_TS_COMMIT_START=0 restores exit-only. */
static int rr_ts_commit_start_on(void)
{
    static int on = -1;
    if (on < 0) { const char* e = getenv("RR_TS_COMMIT_START");
                  on = (e && e[0] == '0' && !e[1]) ? 0 : 1; }
    return on;
}
static void rr_ts_commit_maybe_start(uint32_t line)
{
    if (s_ts_held || !rr_ts_commit_start_on()) return;
    for (int i = 0; i < TS_TRACK; i++) {
        const uint32_t ea = s_ts_run[i].ea;
        if (ea && (ea & ~127u) == line) { spu_taskset_start_pending(ea); return; }
    }
}

/* RR_TASK_LIFE=1 (spurs-20261108, diagnostic, off by default): per taskset,
 * every 2 s, how many tasks were dispatched and finished, how long they ran
 * (dispatch-thread start -> return, including WAIT_SIGNAL parks) and how many
 * are in flight. Separates "SPU tasks are slow" from "SPU tasks never run /
 * never finish" when a PPU waits on SPURS work. */
#define RR_LIFE_MAX 16
static struct { uint32_t ts; long started, finished, inflight;
                unsigned long long sum_ms, max_ms;
                /* RR_TASK_PROF=1 (prslow-20261108): summed rr_tprof_end() fields
                 * + wall us of the same finished runs; hot = longest same-line
                 * GETLLAR run seen in one task. */
                unsigned long long pf[8], wall_us, hot_run; uint32_t hot_ea; } s_life[RR_LIFE_MAX];
static volatile LONG s_life_lock;
static unsigned long long s_life_t0;
static int rr_life_on(void)
{
    static int on = -1;
    if (on < 0) { const char* e = getenv("RR_TASK_LIFE"); on = (e && *e && *e != '0') ? 1 : 0; }
    return on;
}
static void rr_life_note(uint32_t ts, int done, unsigned long long ran_ms)
{
    extern unsigned long long ps3_ms_now(void);
    if (!ts || !rr_life_on()) return;
    while (InterlockedExchange(&s_life_lock, 1)) Sleep(0);
    int k = -1;
    for (int i = 0; i < RR_LIFE_MAX; i++) {
        if (s_life[i].ts == ts) { k = i; break; }
        if (!s_life[i].ts) { s_life[i].ts = ts; k = i; break; }
    }
    if (k >= 0) {
        if (!done) { s_life[k].started++; s_life[k].inflight++; }
        else { s_life[k].finished++; s_life[k].inflight--;
               s_life[k].sum_ms += ran_ms; if (ran_ms > s_life[k].max_ms) s_life[k].max_ms = ran_ms; }
    }
    unsigned long long now = ps3_ms_now();
    if (!s_life_t0) s_life_t0 = now;
    if (now - s_life_t0 >= 2000) {
        for (int i = 0; i < RR_LIFE_MAX && s_life[i].ts; i++) {
            fprintf(stderr, "[task-life] taskset=0x%08X started=%ld finished=%ld inflight=%ld "
                    "run_mean=%.1fms run_max=%llums (last %llums)\n", s_life[i].ts,
                    s_life[i].started, s_life[i].finished, s_life[i].inflight,
                    s_life[i].finished ? (double)s_life[i].sum_ms / s_life[i].finished : 0.0,
                    s_life[i].max_ms, now - s_life_t0);
            s_life[i].started = s_life[i].finished = 0;
            s_life[i].sum_ms = s_life[i].max_ms = 0;
        }
        { extern int rr_tprof_enabled(void);
          if (rr_tprof_enabled())
            for (int i = 0; i < RR_LIFE_MAX && s_life[i].ts; i++) {
                const unsigned long long* f = s_life[i].pf; const double n = s_life[i].finished ? (double)s_life[i].finished : 1.0;
                if (!s_life[i].wall_us) continue;
                const unsigned long long busy = f[1] + f[3];
                fprintf(stderr, "[task-prof] taskset=0x%08X per-task: wall=%.2fms dma=%.0f(%.2fms) atomic=%.0f(%.2fms) "
                        "other=%.2fms | getllar=%.0f putllc_fail=%.0f rdch=%.0f rchcnt=%.0f | hot GETLLAR ea=0x%08X x%llu in one task\n",
                        s_life[i].ts, s_life[i].wall_us / n / 1000.0, f[0] / n, f[1] / n / 1000.0, f[2] / n, f[3] / n / 1000.0,
                        (s_life[i].wall_us > busy ? s_life[i].wall_us - busy : 0) / n / 1000.0,
                        f[4] / n, f[5] / n, f[6] / n, f[7] / n, s_life[i].hot_ea, s_life[i].hot_run);
                memset(s_life[i].pf, 0, sizeof s_life[i].pf);
                s_life[i].wall_us = s_life[i].hot_run = 0; s_life[i].hot_ea = 0;
            } }
        fflush(stderr);
        s_life_t0 = now;
    }
    InterlockedExchange(&s_life_lock, 0);
}
/* RR_TASK_PROF: fold one finished run's breakdown into its taskset's slot.
 * Called BEFORE rr_life_note(done=1) so the 2 s print sees it. */
static void rr_life_prof(uint32_t ts, const unsigned long long f[10], unsigned long long wall_us)
{
    if (!ts || !rr_life_on()) return;
    while (InterlockedExchange(&s_life_lock, 1)) Sleep(0);
    for (int i = 0; i < RR_LIFE_MAX; i++) {
        if (s_life[i].ts != ts) continue;
        for (int k = 0; k < 8; k++) s_life[i].pf[k] += f[k];
        s_life[i].wall_us += wall_us;
        if (f[9] > s_life[i].hot_run) { s_life[i].hot_run = f[9]; s_life[i].hot_ea = (uint32_t)f[8]; }
        break;
    }
    InterlockedExchange(&s_life_lock, 0);
}

static void spu_async_run(spu_async_job* j)
{
    spu_taskset_mark(j->taskset_ea, j->taskid, 1);
    /* Persistent per-taskset LS: acquire (+serialize) the taskset's LS, or fall
     * back to a fresh per-dispatch LS when disabled / no taskset. */
    spu_ts_ls_slot* ts_slot = NULL;
    int did_load = 0;           /* whether THIS dispatch (re)loaded the image */
    if (spu_persist_ls_enabled() && j->taskset_ea && j->image_id != 22)
        ts_slot = ts_ls_get(j->taskset_ea, j->taskid);
    uint8_t* ls;
    if (ts_slot) {
#ifdef _WIN32
        AcquireSRWLockExclusive(&ts_slot->lock);   /* serialize this taskset */
#else
        pthread_mutex_lock(&ts_slot->lock);
#endif
        if (!ts_slot->ls) ts_slot->ls = (uint8_t*)calloc(1, SPU_LS_SIZE);
        ls = ts_slot->ls;
        { static int _n = 0; if (PS3_LOG_FIRST(_n, 24))
            fprintf(stderr, "[persist-ls] taskset=0x%08X task=%u image=%d %s\n",
                    j->taskset_ea, j->taskid, j->image_id,
                    ts_slot->loaded ? "REUSE (state retained)" : "first load"); fflush(stderr); }
    } else {
        ls = (uint8_t*)calloc(1, SPU_LS_SIZE);
    }
    if (ls) {
        uint32_t entry = 0;
        /* Load the image only on a taskset's FIRST task (or every dispatch when
         * not persisting) -- reusing preserves the prior task's LS state. */
        int loaded = (ts_slot && ts_slot->loaded)
                   ? 1
                   : (did_load = 1, spu_elf_load_to_ls(j->image, j->image_size, ls, &entry));
        if (ts_slot && did_load && loaded) ts_slot->loaded = 1;
        if (!loaded)
            fprintf(stderr, "[spu_workload] async image=%d ELF LOAD FAILED\n",
                    j->image_id), fflush(stderr);
        if (loaded) {
            /* YDKJ_CRI_POLICY (cri build experiment): the cri SPU task
             * (image 22) calls the SPURS task-API via a jump table at LS 0x2700
             * and reads its task descriptor at LS 0x2FB0 — both POLICY-provided,
             * not in the task ELF (so it branch-to-0's at func_00026DE0). Preload
             * the policy module (libsre @0x30021480 -> LS 0xA00) and write the
             * task descriptor {0xFFFFFFFF, 0x400, 0x2700, 0x3000} at 0x2FB0, then
             * run the cri task, to see how much further it gets. Diagnostic only. */
            if (j->image_id == 22 && getenv("YDKJ_CRI_TASKSET")) {
                /* cri build: load the TASKSET POLICY module (libsre 0x23680 ->
                 * LS 0xA00) alongside the cri task (already at 0x3000), then RUN
                 * THE POLICY ENTRY (tsp_spu_func_00000A00) under image 23. The
                 * policy builds the 0x2700 task-API table + dispatches the cri
                 * task. Needs the SpursKernelContext at LS[0x1C0] (instance ptr)
                 * + r80=0x100 context base, mirroring the kernel->policy handoff. */
                extern uint8_t* vm_base;
                extern void tsp_spu_func_00000A00(spu_context*);
                if (vm_base) memcpy(ls + 0xA00, vm_base + 0x30023680, 0x2200);
                /* Build the REAL SpursTasksetContext at LS 0x2700 (taskset ptr @0x27B8,
                 * TaskInfo @0x2780, syscallAddr @0x27C4) from the actual game taskset,
                 * so the policy's DMAs read valid data instead of garbage. The instance
                 * ptr (LS[0x1C0]) was a hardcoded 0x40009D00 that mismatched the game's
                 * real 0x40009F00 -> policy DMA'd garbage -> null branches. */
                extern uint64_t spurs_pm_build_context(uint8_t*, uint32_t, uint32_t, uint32_t, uint32_t);
                extern uint32_t g_ydkj_real_spurs_ea, g_ydkj_real_taskset_ea, g_ydkj_real_taskid;
                if (g_ydkj_real_taskset_ea)
                    spurs_pm_build_context(ls, g_ydkj_real_taskset_ea, g_ydkj_real_taskid, 0, 0);
                uint32_t inst = g_ydkj_real_spurs_ea ? g_ydkj_real_spurs_ea : 0x40009D00u;
                uint8_t* p = ls + 0x1C0;
                p[0]=0; p[1]=0; p[2]=0; p[3]=0;                 /* hi32 of u64 */
                p[4]=(uint8_t)(inst>>24); p[5]=(uint8_t)(inst>>16);
                p[6]=(uint8_t)(inst>>8);  p[7]=(uint8_t)inst;   /* lo32 */
                fprintf(stderr, "[cri] YDKJ_CRI_TASKSET: loaded taskset policy@0xA00, LS[0x1C0]=inst, running policy entry (img23)\n");
                fflush(stderr);
                /* Run the taskset policy entry instead of the cri task entry.
                 * (Declared by spu_lifted_job.h -- a local extern re-declaration
                 * here conflicts with the header's static inline under clang.) */
                int32_t prc = spu_run_lifted_job_abi(tsp_spu_func_00000A00, ls,
                                                     j->args_ea, 23, 1, j->have_r3 ? j->r3 : 0, 0);
                fprintf(stderr, "[cri] taskset policy RETURNED rc=%d\n", prc);
                fflush(stderr);
                free(ls); free(j); return;
            }
            /* YDKJ HLE cri-task path (image 22, cri_mpvps3spurs.elf): the real
             * SPURS kernel/policy would build the task's SpursTasksetContext (LS
             * 0x2700) before dispatch. In the HLE-cellSpurs path we dispatch the
             * task ELF directly, so LS 0x2700 is empty and the task branch-to-0's:
             * cri func_00026DE0 reads syscallAddr@0x27C4 (=0) and branches there.
             * Plant a minimal context so the task-API call lands on the HLE syscall
             * trampoline (LS 0xA70, intercepted in spu_channels.c) + the task
             * descriptor @0x2FB0. Adopted from JonathanDC64/ps3recomp (aaea4158).
             * Gate: default on for image 22 unless YDKJ_NO_CRI_CTX. */
            if (j->image_id == 22 && !getenv("YDKJ_NO_CRI_CTX")) {
                extern uint64_t spurs_pm_build_context(uint8_t*, uint32_t, uint32_t, uint32_t, uint32_t);
                extern uint32_t g_ydkj_real_taskset_ea, g_ydkj_real_taskid;
                #define LSBE32(o,v) do{uint32_t _v=(v);ls[(o)+0]=(uint8_t)(_v>>24);ls[(o)+1]=(uint8_t)(_v>>16);ls[(o)+2]=(uint8_t)(_v>>8);ls[(o)+3]=(uint8_t)_v;}while(0)
                if (g_ydkj_real_taskset_ea && !getenv("YDKJ_MINIMAL_CTX")) {
                    /* REAL taskset context: build the SpursTasksetContext at LS 0x2700
                     * from the actual BE CellSpursTaskset (spurs ptr, args, TaskInfo)
                     * so the cri leaf reads valid data instead of my planted guesses. */
                    uint64_t elf = spurs_pm_build_context(ls, g_ydkj_real_taskset_ea, g_ydkj_real_taskid, 0, 0);
                    /* --- Golden-reference context fields for the CRI task, recovered from a
                     * WORKING RPCS3 SPU-LS snapshot via caner's rpcs3-guest-memory-dumper fork
                     * (github.com/canersaka/rpcs3-guest-memory-dumper): YDKJ BLUS30569, SPU0
                     * "CellSpursKernel0" mid-cri-decode. These are what the cri task's context
                     * validator (func_00026E80/F18/FC4) reads; our values differed and tripped
                     * its 0x80410911 error path. CRI-SCOPED (image 22 only) -- overriding these
                     * in the shared build_context breaks the audio SPURS task. */
                    LSBE32(0x2840, 0x53505552u); LSBE32(0x2844, 0x53544153u); /* moduleId "SPURSTASK MODULE" */
                    LSBE32(0x2848, 0x4B204D4Fu); LSBE32(0x284C, 0x44554C45u);
                    /* TI_LS_PATTERN = full-coverage (all-ones). The prior "golden fix"
                     * set this to 0 from the decode-time RPCS3 LS dump, but that region
                     * is post-validation (also zero) so it wasn't authoritative. Runtime
                     * probe YDKJ_CRI_GATE1TRACE proved 0 makes the validator func_00026E80
                     * return 0x8041090F (busy-spin poll); all-ones makes it return 0 -- the
                     * task then passes and reaches the taskset-state getllar (func_00027028).
                     * Verified by direct r3 read (YDKJ_G1_LSPAT=0xFFFFFFFF -> r3=0). */
                    LSBE32(0x27A0, 0xFFFFFFFFu); LSBE32(0x27A4, 0xFFFFFFFFu);
                    LSBE32(0x27A8, 0xFFFFFFFFu); LSBE32(0x27AC, 0xFFFFFFFFu);
                    LSBE32(0x27D0, 0x1F);                       /* dmaTagId = 0x1F (build_context wrote 0) */
                    /* still plant the cri-specific task descriptor @0x2FB0 that build_context
                     * doesn't cover (cri func_00026DE0 reads it). */
                    LSBE32(0x2FB0, 0xFFFFFFFFu); LSBE32(0x2FB4, 0x400);
                    LSBE32(0x2FB8, 0x2700);      LSBE32(0x2FBC, 0x3000);
                    /* GATE1 SWEEP (YDKJ_G1_*): the validator func_00026E80 reads the
                     * TI_CONTEXT(0x2798)/TI_LS_PATTERN(0x27A0) region; YDKJ_CRI_GATE1TRACE
                     * proved r16=rotqby(LS[0x2798],8)=0 forces its 0x8041090F return. The
                     * decode-time RPCS3 dump has this region zero (post-validation), so it
                     * can't be diffed -- sweep candidate values here and read the probe's
                     * r3. Overrides the plants above so one build tests many values. */
                    { const char* _e;
                      if ((_e=getenv("YDKJ_G1_LSPAT"))) { uint32_t v=(uint32_t)strtoul(_e,0,0);
                          LSBE32(0x27A0,v); LSBE32(0x27A4,v); LSBE32(0x27A8,v); LSBE32(0x27AC,v); }
                      if ((_e=getenv("YDKJ_G1_CTX")))   { uint32_t v=(uint32_t)strtoul(_e,0,0);
                          LSBE32(0x2798,v); LSBE32(0x279C,v); } }
                    fprintf(stderr, "[cri] REAL SpursTasksetContext built from taskset 0x%08X task %u (elf=0x%llX)\n",
                            g_ydkj_real_taskset_ea, g_ydkj_real_taskid, (unsigned long long)elf);
                } else {
                    LSBE32(0x27C0, 0x100);     /* kernelMgmtAddr -> SPURS kernel ctx @LS 0x100 */
                    LSBE32(0x27C4, 0xA70);     /* syscallAddr -> HLE PM syscall trampoline (0xA70) */
                    LSBE32(0x2FB0, 0xFFFFFFFFu); LSBE32(0x2FB4, 0x400);
                    LSBE32(0x2FB8, 0x2700);      LSBE32(0x2FBC, 0x3000);
                    fprintf(stderr, "[cri] HLE cri-task ctx (minimal plant): syscallAddr@0x27C4=0xA70\n");
                }
                #undef LSBE32
                fflush(stderr);
            }
            /* Dump the 64-byte decode context the cri task will DMA from eaContext
             * (r3.word1 = args_ea). This is the job the game's cri_mpv PPU layer is
             * supposed to populate (video-data EA, output buffer). If it's zero/garbage
             * the PPU layer never wrote a real job -> the task decodes nothing. */
            if (j->image_id == 22 && j->args_ea) {
                extern uint8_t* vm_base;
                const uint8_t* c = vm_base + (j->args_ea & 0x0FFFFFFFu);
                fprintf(stderr, "[cri] eaContext=0x%08X 64B decode-context:", j->args_ea);
                for (int i = 0; i < 64; i++) { if ((i&15)==0) fprintf(stderr,"\n     +%02X:", i); fprintf(stderr, " %02X", c[i]); }
                fprintf(stderr, "\n"); fflush(stderr);
            }
            /* Async dispatch is the SPURS-task path: the entry expects the SPURS
             * task kernel ABI in r3 ({0x40 marker, eaContext, queue EA, ...}),
             * captured at dispatch time (j->r3) so it doesn't race the PPU
             * overwriting the stack-allocated context. */
            /* Generic SPURS taskset task (LBP's audio SPEEX/MultiStream tasks,
             * image 6/7 — anything but the cri image 22 handled above): the real
             * kernel runs the task UNDER the taskset policy, which plants a
             * SpursTasksetContext at LS 0x2700 (taskset header, TaskInfo, and
             * syscallAddr=0xA70) and enters it with r3 = task args, r4 = {spurs,
             * taskset args}. We dispatch the task ELF directly, so without this it
             * runs with r3=r4=0 and no context and SPINS FOREVER (observed: image
             * 6/7 ENTER + RUN, never RETURN, 0 DMA, PPU blocks on EventFlag 0x0100).
             * Build the context here from the real taskset CreateTask recorded;
             * spu_run_lifted_job_abi then sets r3/r4 off the 0xA70 sentinel.
             * Env-gated while bringing this up — default leaves every path as-is. */
            /* Timing probe: a real SPURS task is dispatched when work is signaled.
             * We dispatch immediately at CreateTask. If LBP fills the task's work
             * buffer slightly LATER, delaying the run lets it see real data (=>
             * timing bug, fix = defer/re-dispatch on signal); if it still loops on
             * a null base, the buffer is never filled (=> an audio HLE gap). */
            if (j->image_id != 22) {
                const char* d = getenv("LBP_TASK_DELAY");
                if (d && *d) {
#ifdef _WIN32
                    Sleep((unsigned)(atoi(d) * 1000));
#endif
                }
            }
            /* A generic SPURS taskset task (image != cri 22) MUST get its
             * SpursTasksetContext planted at LS 0x2700 -- the real kernel builds
             * it from the taskset before entry, and the task reads its args and
             * every DMA base pointer out of it. Without it the task runs with a
             * null base and DMAs EVERYTHING from EA 0 (observed on LBP's FMOD
             * mixer: 105k GETs from ea=0x0, degenerate handler targets ->
             * branch-to-0, and the PPU pump blocks forever on EventFlag 0x0100).
             * Planting it makes the mixer read the real FMOD control block
             * (0x0094F5xx) and the EventFlag handshake completes. Default ON;
             * LBP_NO_TASKSET restores the old direct-dispatch for comparison. */
            if (j->image_id != 22 && !getenv("LBP_NO_TASKSET")) {
                extern uint64_t spurs_pm_build_context(uint8_t*, uint32_t, uint32_t, uint32_t, uint32_t);
                /* Use the taskset+taskid captured for THIS job at dispatch (not the
                 * globals, which the next CreateTask clobbers -- the race that made
                 * both audio tasks run task 1's descriptor). */
                if (j->taskset_ea) {
                    spurs_pm_build_context(ls, j->taskset_ea, j->taskid, 0, 0);
                    if (rr_spurs_verbose()) fprintf(stderr, "[taskset] built SpursTasksetContext image=%d "
                            "taskset=0x%08X task=%u\n", j->image_id,
                            j->taskset_ea, j->taskid);
                }
            }
            /* ---- Bink-layer probe + real-policy A/B (image 3 = binkspu) ----
             * (1) dump binkspu's Bink work-descriptor at its arg EA so we can see
             *     the output-plane EAs and the plane+0x50 "needs-decode" gate that
             *     gates the frame-output PUT (all prior PUTs went to the 0x927E80
             *     control block, never a plane). This tells us whether the missing
             *     output EA is a Bink/PPU-layer field (this descriptor) or a SPURS
             *     taskset-context field (LS 0x2700, below).
             * (2) LBP_REAL_POLICY: run the REAL lifted taskset policy to build its
             *     SpursTasksetContext and diff it against the C reimpl build_context
             *     planted in `ls` -- shows exactly which fields differ. */
            if (j->image_id == 3) {
                extern uint8_t* vm_base;
                uint32_t arg = j->args_ea;
                /* SPU DMA maps EAs as vm_base + (uint32_t)ea with NO masking
                 * (spu_dma.h:186); vm_base spans the full 4GB so VRAM 0xC0000000+
                 * is directly addressable. (The earlier &0x0FFFFFFF mask read main
                 * code at 0x10B88 instead of the real VRAM descriptor.) */
                #define RDBE32(base, off) (((uint32_t)(base)[(off)]<<24)|((uint32_t)(base)[(off)+1]<<16)| \
                                           ((uint32_t)(base)[(off)+2]<<8)|(base)[(off)+3])
                if (vm_base && arg >= 0x10000) {
                    const uint8_t* d = vm_base + arg;         /* FULL EA, no mask */
                    fprintf(stderr, "[bink-desc] arg=0x%08X 256B work-descriptor:", arg);
                    uint32_t words[64];
                    for (int i = 0; i < 256; i += 16) {
                        fprintf(stderr, "\n   +%03X:", i);
                        for (int k = 0; k < 16; k += 4) {
                            uint32_t w = RDBE32(d, i+k); words[(i+k)/4] = w;
                            fprintf(stderr, " %08X", w);
                        }
                    }
                    fprintf(stderr, "\n");
                    /* Follow each plausible pointer one level: dump +0x00..+0x60 so
                     * the output-plane EA + the plane+0x50 "needs-decode" gate show. */
                    for (int wi = 0; wi < 64; wi++) {
                        uint32_t p = words[wi];
                        if (p < 0x10000 || (p >= 0x50000000u && p < 0xC0000000u)) continue;
                        const uint8_t* q = vm_base + p;
                        fprintf(stderr, "  [desc+%02X]=0x%08X -> +00:%08X +40:%08X +50:%08X(gate) +54:%08X\n",
                                wi*4, p, RDBE32(q,0), RDBE32(q,0x40), RDBE32(q,0x50), RDBE32(q,0x54));
                    }
                    fflush(stderr);
                }
                if (getenv("LBP_REAL_POLICY") && j->taskset_ea) {
                    extern int spurs_run_taskset_policy_probe(uint32_t,uint32_t,uint32_t,
                                                              uint64_t,uint32_t,uint8_t*,uint32_t);
                    /* spurs EA from the taskset header lo32 @ +0x64 (be64 @0x60). */
                    uint32_t ts = j->taskset_ea;
                    uint32_t spurs_ea = 0;
                    if (vm_base) { const uint8_t* t = vm_base + ts;
                        spurs_ea = RDBE32(t, 0x64);
                        /* Why did the policy exit without dispatching? Dump the task
                         * bitsets it reads (task N = bit 127-N; task 2 = bit 125). */
                        fprintf(stderr, "[taskset-bits] RUNNING=%08X%08X READY=%08X%08X ENABLED=%08X%08X SIGNALLED=%08X%08X WAITING=%08X%08X\n",
                                RDBE32(t,0x00),RDBE32(t,0x04), RDBE32(t,0x10),RDBE32(t,0x14),
                                RDBE32(t,0x30),RDBE32(t,0x34), RDBE32(t,0x40),RDBE32(t,0x44),
                                RDBE32(t,0x50),RDBE32(t,0x54)); }
                    uint8_t real2700[0x180];
                    int st = spurs_run_taskset_policy_probe(ts, j->taskid, spurs_ea,
                                                            (uint64_t)ts, 3, real2700, sizeof real2700);
                    fprintf(stderr, "[real-pm] status=0x%X -- LS 0x2700 diff (build_context vs real policy):\n", st);
                    for (uint32_t o = 0; o < sizeof real2700; o += 4) {
                        uint32_t bc = ((uint32_t)ls[0x2700+o]<<24)|((uint32_t)ls[0x2700+o+1]<<16)|
                                      ((uint32_t)ls[0x2700+o+2]<<8)|ls[0x2700+o+3];
                        uint32_t rp = ((uint32_t)real2700[o]<<24)|((uint32_t)real2700[o+1]<<16)|
                                      ((uint32_t)real2700[o+2]<<8)|real2700[o+3];
                        if (bc != rp)
                            fprintf(stderr, "   0x%04X: build=%08X real=%08X\n", 0x2700+o, bc, rp);
                    }
                    /* EMPIRICAL TEST (LBP_POLICY_CTX): overlay the REAL policy's
                     * SpursTasksetContext onto binkspu's LS 0x2700, replacing the C
                     * reimpl, then let binkspu run with it. If the movie plane fills
                     * (not green) the policy's fuller ctx is the fix (H1); if still
                     * green, the frame-output gate is Bink-layer (H2). Keeps the
                     * build_context 0x100 kernel ctx (moduleId "TK") intact. */
                    if (getenv("LBP_POLICY_CTX")) {
                        memcpy(ls + 0x2700, real2700, sizeof real2700);
                        fprintf(stderr, "[real-pm] OVERLAID policy ctx onto binkspu LS 0x2700 (LBP_POLICY_CTX)\n");
                    }
                    fflush(stderr);
                }
                #undef RDBE32
            }
            spu_serial_acquire();       /* one SPU task runs at a time (LBP_SPU_SERIAL) */
            extern unsigned long long ps3_ms_now(void);
            const unsigned long long life_t0 = rr_life_on() ? ps3_ms_now() : 0;
            rr_life_note(j->taskset_ea, 0, 0);
            /* RR_TASK_PROF=1 (needs RR_TASK_LIFE=1 for the print): breakdown. */
            extern int rr_tprof_enabled(void);
            extern void rr_tprof_begin(void);
            extern void rr_tprof_end(unsigned long long out[10]);
            const int tprof = life_t0 && rr_tprof_enabled();
            LARGE_INTEGER tp_f, tp_0, tp_1;
            if (tprof) { QueryPerformanceFrequency(&tp_f); rr_tprof_begin(); QueryPerformanceCounter(&tp_0); }
            int32_t rc = spu_run_lifted_job_abi(j->fn, ls, j->args_ea, j->image_id,
                                                1, j->have_r3 ? j->r3 : 0, 0);
            if (tprof) {
                unsigned long long pf[10];
                QueryPerformanceCounter(&tp_1); rr_tprof_end(pf);
                rr_life_prof(j->taskset_ea, pf,
                             (unsigned long long)((double)(tp_1.QuadPart - tp_0.QuadPart) * 1e6 / (double)tp_f.QuadPart));
            }
            if (life_t0) rr_life_note(j->taskset_ea, 1, ps3_ms_now() - life_t0);
            /* YDKJ_CRI_RESUME: a real SPURS task is PERSISTENT -- on yield (num=0)
             * the kernel re-enters it when work is signaled. Our HLE runs it once,
             * so it polls the (concurrently PPU-updated) eaContext, finds no work,
             * yields and exits before the PPU marks work-ready. Approximate the
             * resume by re-running the task (fresh context re-read from eaContext)
             * in a bounded loop until it actually DECODES (a >256B video GET sets
             * g_cri_video_dma) or we time out. This does NOT fake data: the task
             * only decodes if the PPU genuinely populated real work meanwhile. */
            if (j->image_id == 22 && getenv("YDKJ_CRI_RESUME") && !g_cri_video_dma) {
                for (int attempt = 0; attempt < 400 && !g_cri_video_dma; attempt++) {
#ifdef _WIN32
                    Sleep(3);
#else
                    /* The pause is the point: it is the window in which the
                     * PPU marks work ready. Without it the 400 attempts are
                     * spent before the producer runs at all. */
                    { struct timespec _d = { 0, 3 * 1000 * 1000 }; nanosleep(&_d, NULL); }
#endif
                    memset(ls, 0, SPU_LS_SIZE);
                    uint32_t e2 = 0;
                    if (!spu_elf_load_to_ls(j->image, j->image_size, ls, &e2)) break;
                    rc = spu_run_lifted_job_abi(j->fn, ls, j->args_ea, j->image_id,
                                                1, j->have_r3 ? j->r3 : 0, 0);
                    if (g_cri_video_dma) {
                        fprintf(stderr, "[cri] RESUME: cri task DECODED real video (attempt %d)\n", attempt);
                        break;
                    }
                }
                if (!g_cri_video_dma)
                    fprintf(stderr, "[cri] RESUME: no work-ready after 400 polls (PPU never marked work)\n");
                fflush(stderr);
            }
            /* YDKJ_CRI_WAKE probe: on cri task (image 22) completion, wake any PPU
             * completion-waiter (the SPU->PPU cellSpursEventFlag completion isn't
             * propagated yet). Tests whether the game then advances to draw content. */
            if (j->image_id == 22 && getenv("YDKJ_CRI_WAKE")) {
                extern void ydkj_wake_all_event_flags(void);
                ydkj_wake_all_event_flags();
                fprintf(stderr, "[cri] YDKJ_CRI_WAKE: woke all event-flag waiters on cri completion\n");
            }
            /* SPU_LS_DUMP=<prefix>: write this job's whole local store when it
             * ends. A reference dump from real hardware is a full local store,
             * so the only way to ask "what ELSE is different" -- rather than
             * checking one guessed word at a time -- is to diff all 256 KB. */
            { const char* pfx = getenv("SPU_LS_DUMP");
              if (pfx) { char path[512];
                  snprintf(path, sizeof path, "%s_img%d.bin", pfx, j->image_id);
                  FILE* f = fopen(path, "wb");
                  if (f) { fwrite(ls, 1, SPU_LS_SIZE, f); fclose(f);
                      fprintf(stderr, "[spu_workload] wrote local store -> %s\n", path); } } }
            if (rc || rr_spurs_verbose()) fprintf(stderr, "[spu_workload] async image=%d RETURNED rc=%d "
                    "(%s)\n", j->image_id, rc,
                    rc ? "host execution failure; job incomplete" : "execution returned; gameplay unverified");
            spu_serial_release();
            if (j->taskset_ea) spu_taskset_task_exited(j->taskset_ea, j->taskid);
        }
        /* Persistent LS is retained in its taskset slot for the next task; a
         * per-dispatch LS is freed. */
        if (!ts_slot) free(ls);
    }
    if (ts_slot) {
#ifdef _WIN32
        ReleaseSRWLockExclusive(&ts_slot->lock);
#else
        pthread_mutex_unlock(&ts_slot->lock);
#endif
    }
    free(j);
}

#ifdef _WIN32
static DWORD WINAPI spu_async_thread(LPVOID p) {
    /* Reserve handler headroom so a stack overflow in lifted SPU code (e.g. a
     * runaway brsl recursion) can actually reach the STACKOVERFLOW reporter
     * instead of killing the process silently with 0x80000001. */
    { ULONG g = 256 * 1024; SetThreadStackGuarantee(&g); }
    spu_async_run((spu_async_job*)p);
    /* Nothing on this stack may stay in the lock-line reserver set. */
    { ULONG_PTR lo, hi; GetCurrentThreadStackLimits(&lo, &hi);
      extern void spu_coh_forget_range(uintptr_t, uintptr_t);
      spu_coh_forget_range((uintptr_t)lo, (uintptr_t)hi);
      spu_mfc_forget_range((uintptr_t)lo, (uintptr_t)hi); }
    return 0;
}
#else
static void* spu_async_thread(void* p) { spu_async_run((spu_async_job*)p); return NULL; }
#endif

/* SPU_DUMP_MISS=<dir>: open <dir>/<name> for writing. A relative <dir> is
 * taken relative to the executable's folder (the Studio looks for
 * build/player/spu-miss beside the exe, and the process cwd is not always
 * that folder), and the folder is created if missing -- fopen on a missing
 * directory failed silently, so no dump was ever written. */
static FILE* spu_dump_miss_open(const char* dir, const char* name, char* out, size_t outn)
{
    char base[512]; base[0] = 0;
    int rel = !(dir[0] == '/' || dir[0] == '\\' || (dir[0] && dir[1] == ':'));
#ifdef _WIN32
    if (rel) {
        DWORD n = GetModuleFileNameA(NULL, base, (DWORD)sizeof(base));
        if (n > 0 && n < sizeof(base)) {
            char* sl = strrchr(base, '\\'); char* s2 = strrchr(base, '/');
            if (s2 > sl) sl = s2;
            if (sl) sl[1] = 0; else base[0] = 0;
        } else base[0] = 0;
    }
#endif
    char d[512];
    snprintf(d, sizeof(d), "%s%s", rel ? base : "", dir);
    snprintf(out, outn, "%s/%s", d, name);
    FILE* f = fopen(out, "wb");
    if (!f) {
#ifdef _WIN32
        CreateDirectoryA(d, NULL);
#else
        mkdir(d, 0777);
#endif
        f = fopen(out, "wb");
    }
    if (!f) { static int n = 0; if (n++ < 4) fprintf(stderr, "[spurs-job] dump FAILED: cannot write %s\n", out); }
    return f;
}

/* Interpreter entry for an unlifted SPURS job (binary loaded at LS 0). */
static void spu_spurs_job_interp_entry(spu_context* ctx)
{
    spu_interp_run(ctx, 0);
}

int spu_workload_dispatch_job(const uint8_t* image, uint32_t image_size,
                              uint32_t job_ea, uint32_t job_desc_size)
{
    if (!image || image_size == 0) return 0;

    uint64_t fp = spu_workload_fingerprint(image, image_size);
    spu_lifted_entry_fn fn = NULL;
    int image_id = 0;
    for (unsigned i = 0; i < s_registry_count; i++)
        if (s_registry[i].fp == fp) { fn = s_registry[i].fn; image_id = s_registry[i].image_id; break; }
    if (!fn) {
        /* Capped: an unlifted job a title dispatches every frame (Tornado
         * Outbreak's Wwise audio jobs) wrote 2 GB of these in three minutes,
         * and the logging itself distorts guest timing. */
        { static unsigned long long miss_n = 0;
          if (++miss_n <= 32 || miss_n % 100000 == 0)
            fprintf(stderr, "[spurs-job] dispatch MISS fp=0x%016llX size=%u job=0x%08X (#%llu)\n",
                    (unsigned long long)fp, image_size, job_ea, miss_n); }
        /* SPU_DUMP_MISS=<dir>: write the unrecognised image out so it can be
         * lifted and registered. SPURS job binaries are raw code+data blobs
         * the title loads from its own data files -- unlike sys_spu_image
         * programs they are NOT embedded ELFs in the EBOOT, so
         * tools/extract_spu_images.py cannot find them and this is the only
         * place the bytes exist. One file per fingerprint. */
        { const char* _dir = getenv("SPU_DUMP_MISS");
          if (_dir && *_dir) {
              static uint64_t _seen[64]; static unsigned _nseen = 0;
              unsigned _k = 0;
              for (; _k < _nseen; _k++) if (_seen[_k] == fp) break;
              if (_k == _nseen && _nseen < 64) {
                  char _path[512];
                  _seen[_nseen++] = fp;
                  char _nm[64];
                  snprintf(_nm, sizeof(_nm), "spujob_%016llX_%u.bin",
                           (unsigned long long)fp, image_size);
                  FILE* _f = spu_dump_miss_open(_dir, _nm, _path, sizeof(_path));
                  if (_f) {
                      fwrite(image, 1, image_size, _f);
                      fclose(_f);
                      fprintf(stderr, "[spurs-job] dumped -> %s\n", _path);
                  }
              }
          } }
        /* SPURS_JOB_INTERP_MISS (default on, =0 disables): run the unlifted job
         * in the SPU interpreter instead of dropping it. A dropped job never
         * writes its completion word, so the PPU waits on it forever (Midnight
         * Club LA's render thread, inFAMOUS 2). image_id -1 = pure
         * interpretation (never rejoins another image's lifted code). The job
         * returns to SPU_JOB_RETURN_LS, which holds a zero word (stop 0). */
        { static int s_im = -1;
          if (s_im < 0) { const char* e = getenv("SPURS_JOB_INTERP_MISS");
                          s_im = (e && *e == '0') ? 0 : 1; }
          if (s_im) {
              static unsigned long long im_n = 0;
              if (++im_n <= 8)
                  fprintf(stderr, "[spurs-job] interpreting unlifted job fp=0x%016llX job=0x%08X\n",
                          (unsigned long long)fp, job_ea);
              spu_run_spurs_job(spu_spurs_job_interp_entry, -1, job_ea, job_desc_size);
              return 1;
          } }
        return 0;
    }
    /* Two lines plus two explicit flushes PER JOB. A title running its audio
     * chain does ~1500 jobs/s, so this alone was ~6k writes/s through one FILE
     * lock, and it starved the guest threads competing for that lock badly
     * enough to change what the title does (see ps3_log.h). Milestones stay;
     * the per-job pair is verbose-only. */
    int verbose = ps3_log_verbose();
    if (verbose) {
        fprintf(stderr, "[spurs-job] dispatch HIT fp=0x%016llX image=%d job=0x%08X\n",
                (unsigned long long)fp, image_id, job_ea);
        fflush(stderr);
    }
    /* SPU_JOBPROF=<secs>: host time spent per job image, printed every <secs>.
     * Jobs run synchronously on the pushing thread, so this is frame time. */
    static int s_prof = -1;
    if (s_prof < 0) { const char* e = getenv("SPU_JOBPROF"); s_prof = e ? atoi(e) : 0; }
    struct timespec t0, t1;
    if (s_prof) timespec_get(&t0, TIME_UTC);
    int rc = spu_run_spurs_job(fn, image_id, job_ea, job_desc_size);
    if (s_prof) {
        static double acc[64], last; static unsigned cnt[64];
        timespec_get(&t1, TIME_UTC);
        double now = t1.tv_sec + t1.tv_nsec * 1e-9;
        unsigned k = (unsigned)image_id & 63;
        acc[k] += now - (t0.tv_sec + t0.tv_nsec * 1e-9); cnt[k]++;
        if (now - last >= s_prof) {
            last = now;
            for (unsigned i = 0; i < 64; i++) if (cnt[i]) {
                fprintf(stderr, "[jobprof] image=%u n=%u total=%.2fs avg=%.2fms\n",
                        i, cnt[i], acc[i], acc[i] * 1e3 / cnt[i]);
                acc[i] = 0; cnt[i] = 0;
            }
        }
    }
    if (verbose) {
        fprintf(stderr, "[spurs-job] job 0x%08X RETURNED rc=%d\n", job_ea, rc);
        fflush(stderr);
    }
    return 1;
}

/* ---- SPURS task signal channel (real WAIT_SIGNAL semantics) --------------
 *
 * Mirrors the kernel/RPCS3 contract (spursTasksetProcessSyscall):
 *   - _cellSpursSendSignal / cellSpursEventFlagSet mark the task's bit in the
 *     taskset's `signalled` bitset (BE, in the GUEST CellSpursTaskset) and
 *     wake it if sleeping.
 *   - The WAIT_SIGNAL taskset syscall consumes a pending signal, or sleeps
 *     the task until one arrives (POLL_SIGNAL-then-wait, no lost wakeups:
 *     the guest bit is set under the same lock the waiter checks it).
 * The bitset is guest state (SPU-visible); the host lock/condvar exist only
 * to block and wake the task's host thread. */
#include "../../libs/spurs/spurs_taskset.h"

#ifdef _WIN32
static SRWLOCK            s_sig_lock = SRWLOCK_INIT;
static CONDITION_VARIABLE s_sig_cv;   /* zero-init == CONDITION_VARIABLE_INIT */
#else
static pthread_mutex_t s_sig_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t  s_sig_cv   = PTHREAD_COND_INITIALIZER;
#endif

/* Which (taskset, task) pairs are currently parked in WAIT_SIGNAL.
 *
 * A PPU->SPU event-flag Set must be able to reach a task that parked WITHOUT
 * registering a wait slot in the flag: our Set path only signalled tasks listed
 * in the flag`s `used` bitmask, so such a task slept forever while the producer`s
 * memory looked perfectly intact. Same failure class canersaka documented for
 * SPURS queues in Yakuza Dead Souls ("the HLE previously woke only its host
 * condvar, which lifted SPU consumer tasks never wait on").
 *
 * ponytail: deliberately lock-free and racy. A missed entry costs one 1s poll
 * timeout in the waiter; a stale entry costs one spurious signal, which is safe
 * because signals are LATCHED in guest state (CSTS_SIGNALLED) and every wait
 * loop re-checks its own predicate. Add a lock only if this ever needs to be
 * authoritative rather than a hint. */
void spu_taskset_signal_task(uint32_t taskset_ea, uint32_t taskId);  /* defined below */

#define SPU_PARKED_MAX 64
static volatile uint64_t s_parked[SPU_PARKED_MAX];   /* (taskset<<32)|(taskId+1), 0 = free */
static volatile uint32_t s_parked_obj[SPU_PARKED_MAX];  /* LS[0x2FD0] wait object, 0 = unknown */

/* Object-addressed queue wakeups may race the task's transition into PARKED.
 * Keep a one-shot object latch, analogous to s_wake_latch below but usable by
 * producers which know the LFQueue wait slot rather than its taskset. */
#define SPU_OBJ_WAKE_MAX 16
static volatile uint32_t s_obj_wake[SPU_OBJ_WAKE_MAX];
static volatile uint32_t s_obj_wake_count[SPU_OBJ_WAKE_MAX];
static volatile unsigned long s_sig_sent[128], s_sig_consumed[128];
static volatile unsigned long s_obj_latch_hits, s_obj_latch_sets;

/* 2026-10-03: the parked list + object latch are now guarded by one lock. The
 * lock-free version lost wakeups (inFamous FIOS task, Windows): parked_add
 * checked the latch (empty) -> the PPU LFQueuePush published the latch and
 * scanned the parked list (empty, parked_matches=0) -> parked_add inserted and
 * the task slept in WAIT_SIGNAL forever with the latch still set. Taking the
 * lock makes "check latch + insert" and "publish latch + scan" atomic w.r.t.
 * each other. Lock order: s_park_lock -> s_sig_lock (signal_task); nothing
 * takes them in the other order. */
#ifdef _WIN32
static SRWLOCK s_park_lock = SRWLOCK_INIT;
#define PARK_LOCK()   AcquireSRWLockExclusive(&s_park_lock)
#define PARK_UNLOCK() ReleaseSRWLockExclusive(&s_park_lock)
#else
static pthread_mutex_t s_park_lock = PTHREAD_MUTEX_INITIALIZER;
#define PARK_LOCK()   pthread_mutex_lock(&s_park_lock)
#define PARK_UNLOCK() pthread_mutex_unlock(&s_park_lock)
#endif


void spu_taskset_parked_add(uint32_t taskset_ea, uint32_t taskId, uint32_t wait_obj)
{
    uint64_t key = ((uint64_t)taskset_ea << 32) | (uint64_t)(taskId + 1);
    { static int log_n = 0; if ((log_n < 24 && log_n++ < 24))
        fprintf(stderr, "[spu_workload] parked_add taskset=0x%08X task=%u obj=0x%08X\n",
                taskset_ea, taskId, wait_obj); }
    PARK_LOCK();
    if (wait_obj) {
        for (int i = 0; i < SPU_OBJ_WAKE_MAX; i++)
            if (s_obj_wake[i] == wait_obj) {
                if (s_obj_wake_count[i]) s_obj_wake_count[i]--;
                if (!s_obj_wake_count[i]) s_obj_wake[i] = 0;
                s_obj_latch_hits++;
                if (0)
                    fprintf(stderr, "[spu_workload] consumed object wake obj=0x%08X\n", wait_obj);
                spu_taskset_signal_task(taskset_ea, taskId);
                PARK_UNLOCK();
                return;
            }
    }
    for (int i = 0; i < SPU_PARKED_MAX; i++)
        if (s_parked[i] == 0) { s_parked_obj[i] = wait_obj; s_parked[i] = key; break; }
    PARK_UNLOCK();
}

void spu_taskset_parked_del(uint32_t taskset_ea, uint32_t taskId)
{
    uint64_t key = ((uint64_t)taskset_ea << 32) | (uint64_t)(taskId + 1);
    PARK_LOCK();
    for (int i = 0; i < SPU_PARKED_MAX; i++)
        if (s_parked[i] == key) { s_parked[i] = 0; break; }
    PARK_UNLOCK();
}

/* Event bits owed to a task, keyed by the OBJECT it waits on (flag - 0x80).
 *
 * Writing the bits at Set time loses a race: the guest reads them from
 * object+0x30 immediately on resuming, and a task that took the latched-wake
 * path was never parked for the Set to target. So the Set only RECORDS what is
 * owed, and the WAIT_SIGNAL handler writes it into guest memory just before it
 * hands control back -- at which point the guest cannot yet have read it. */
#define SPU_EFBITS_MAX 16
static volatile uint32_t s_efbits_obj[SPU_EFBITS_MAX];
static volatile uint32_t s_efbits_val[SPU_EFBITS_MAX];

void spu_ef_bits_post(uint32_t obj, uint16_t bits)
{
    if (!obj) return;
    for (int i = 0; i < SPU_EFBITS_MAX; i++)
        if (s_efbits_obj[i] == obj) { s_efbits_val[i] |= bits; return; }
    for (int i = 0; i < SPU_EFBITS_MAX; i++)
        if (s_efbits_obj[i] == 0) { s_efbits_val[i] = bits; s_efbits_obj[i] = obj; return; }
}

/* Take (and clear) whatever is owed to `obj`. 0 = nothing pending. */
uint16_t spu_ef_bits_take(uint32_t obj)
{
    if (!obj) return 0;
    for (int i = 0; i < SPU_EFBITS_MAX; i++)
        if (s_efbits_obj[i] == obj) {
            uint16_t v = (uint16_t)s_efbits_val[i];
            s_efbits_obj[i] = 0; s_efbits_val[i] = 0;
            return v;
        }
    return 0;
}

/* A direction-2 Set that finds NOBODY parked yet is a lost wakeup: the task
 * parks a moment later and sleeps through the signal it was meant to get. Latch
 * one pending wake per taskset; the next task to park consumes it instead of
 * sleeping. One bit, not a counter -- SPURS signals are latched, not queued, so
 * two Sets before a park must not buy two passes through the wait. */
#define SPU_WAKE_LATCH_MAX 16
static volatile uint32_t s_wake_latch[SPU_WAKE_LATCH_MAX];   /* taskset EA, 0 = free */

void spu_taskset_latch_wake(uint32_t taskset_ea)
{
    if (!taskset_ea) return;
    for (int i = 0; i < SPU_WAKE_LATCH_MAX; i++)
        if (s_wake_latch[i] == taskset_ea) return;          /* already latched */
    for (int i = 0; i < SPU_WAKE_LATCH_MAX; i++)
        if (s_wake_latch[i] == 0) { s_wake_latch[i] = taskset_ea; return; }
}

/* Consume a latched wake for this taskset. Returns 1 if one was pending. */
int spu_taskset_consume_wake(uint32_t taskset_ea)
{
    if (!taskset_ea) return 0;
    for (int i = 0; i < SPU_WAKE_LATCH_MAX; i++)
        if (s_wake_latch[i] == taskset_ea) { s_wake_latch[i] = 0; return 1; }
    return 0;
}

/* Signal every task of `taskset_ea` currently parked. Returns how many. */
/* Wake only the task parked on `wait_obj` (0 = any task of the taskset).
 * The guest names its wait object in the WAIT_SIGNAL argument, and for YDKJ`s
 * CRI tasks the flag the PPU sets is exactly wait_obj + 0x80 -- so a Set can
 * address the one task that was waiting for it instead of every parked task. */
int spu_taskset_signal_parked_obj(uint32_t taskset_ea, uint32_t wait_obj)
{
    if (!taskset_ea) return 0;
    int n = 0;
    PARK_LOCK();
    for (int i = 0; i < SPU_PARKED_MAX; i++) {
        uint64_t k = s_parked[i];
        if (!k || (uint32_t)(k >> 32) != taskset_ea) continue;
        if (wait_obj && s_parked_obj[i] && s_parked_obj[i] != wait_obj) continue;
        spu_taskset_signal_task(taskset_ea, (uint32_t)(k & 0xFFFFFFFFu) - 1u);
        n++;
    }
    PARK_UNLOCK();
    return n;
}

int spu_taskset_signal_parked_any(uint32_t wait_obj)
{
    /* Publish first so a task entering parked state concurrently cannot fall
     * through the gap between our scan and its registration. */
    PARK_LOCK();
    if (wait_obj) {
        int stored = 0;
        for (int i = 0; i < SPU_OBJ_WAKE_MAX; i++)
            if (s_obj_wake[i] == wait_obj) {
                if (s_obj_wake_count[i] != UINT32_MAX) s_obj_wake_count[i]++;
                stored = 1;
                break;
            }
        if (!stored)
            for (int i = 0; i < SPU_OBJ_WAKE_MAX; i++)
                if (s_obj_wake[i] == 0) {
                    s_obj_wake_count[i] = 1;
                    s_obj_wake[i] = wait_obj;
                    break;
                }
    }
    int n = 0;
    for (int i = 0; i < SPU_PARKED_MAX; i++) {
        uint64_t k = s_parked[i];
        if (!k || (wait_obj && s_parked_obj[i] != wait_obj)) continue;
        spu_taskset_signal_task((uint32_t)(k >> 32),
                                (uint32_t)(k & 0xFFFFFFFFu) - 1u);
        n++;
    }
    if (!n && wait_obj) s_obj_latch_sets++;
    if (n && wait_obj)
        for (int i = 0; i < SPU_OBJ_WAKE_MAX; i++)
            if (s_obj_wake[i] == wait_obj) {
                uint32_t take = (uint32_t)n;
                if (take > s_obj_wake_count[i]) take = s_obj_wake_count[i];
                s_obj_wake_count[i] -= take;
                if (!s_obj_wake_count[i]) s_obj_wake[i] = 0;
                break;
            }
    PARK_UNLOCK();
    { static int log_n = 0; if ((log_n < 24 && log_n++ < 24))
        fprintf(stderr, "[spu_workload] object wake obj=0x%08X parked_matches=%d\n",
                wait_obj, n); }
    return n;
}

/* Set or clear a task's bit in the guest `signalled` bitset from a host thread.
 *
 * SPU tasks update this same line with GETLLAR/PUTLLC (a task signalling
 * another, or a barrier releasing its waiters), and those commits are
 * serialised by the lock-line lock, not by s_sig_lock. vm_write32 takes that
 * lock for the store, but the vm_read32 before it was outside it, so an SPU
 * commit landing between the read and the write was overwritten with the stale
 * word. Twisted Metal's post-FX barrier lost a wake exactly so: the releaser set
 * task 4's bit, task 3's thread cleared its own bit from a word read just
 * before, task 4 slept forever and the frame label stopped advancing after two
 * frames. Do the whole read-modify-write under the lock, as a PPU atomic would,
 * and drop every reservation on the line. */
static void spu_signalled_update(uint32_t taskset_ea, uint32_t taskId, int set)
{
    extern void spu_lockline_lock(void); extern void spu_lockline_unlock(void);
    extern void spu_coh_notify_write(uint32_t);
    extern uint8_t* vm_base;
    /* Raw guest bytes, not vm_read32/vm_write32: vm_write32 takes the lock-line
     * lock itself when an SPU has the line reserved, and the lock does not
     * nest. */
    const uint32_t word = taskset_ea + CSTS_SIGNALLED + (taskId / 32u) * 4u;
    const uint32_t mask = (1u << 31) >> (taskId % 32u);
    uint8_t* p = vm_base + word;
    spu_lockline_lock();
    uint32_t v = ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
    v = set ? (v | mask) : (v & ~mask);
    p[0] = (uint8_t)(v >> 24); p[1] = (uint8_t)(v >> 16); p[2] = (uint8_t)(v >> 8); p[3] = (uint8_t)v;
    spu_coh_notify_write(word);
    spu_lockline_unlock();
}

/* Deliver a signal to a task (callable from any PPU/host thread). */
/* RR_TASK_LAT=1 (agent73, 2026-11-01): per-taskset hand-off latency.
 * Every 2 s, for each taskset whose task parks in WAIT_SIGNAL, print
 *   jobs/s       wait-exits per second (one work round each)
 *   run          wall time from leaving WAIT_SIGNAL to entering it again
 *                (the task's own work per round, incl. any DMA/lock waits)
 *   wake         first signal delivered -> task back out of the wait
 *                (the SPURS signal->wakeup hand-off itself)
 *   park         time spent parked per round (idle, waiting for work)
 * on a QPC clock. ran= in the WAIT_SIGNAL log line uses GetTickCount64, so it
 * only ever shows multiples of ~15.6 ms; this is the precise version. Off by
 * default; costs one clock read and a short lock per signal/wait when on. */
#define RR_TL_MAX 16
static struct rr_tl_rec {
    uint32_t ts;
    unsigned long long sig_us;              /* first undelivered signal, 0 = none */
    unsigned n_sig, n_run, n_wake;
    unsigned long long run_sum, run_max, wake_sum, wake_max, park_sum;
} s_tl[RR_TL_MAX];
static unsigned long long s_tl_t0;
#ifdef _WIN32
static SRWLOCK s_tl_lock = SRWLOCK_INIT;
#  define RR_TL_LOCK()   AcquireSRWLockExclusive(&s_tl_lock)
#  define RR_TL_UNLOCK() ReleaseSRWLockExclusive(&s_tl_lock)
#else
static pthread_mutex_t s_tl_lock = PTHREAD_MUTEX_INITIALIZER;
#  define RR_TL_LOCK()   pthread_mutex_lock(&s_tl_lock)
#  define RR_TL_UNLOCK() pthread_mutex_unlock(&s_tl_lock)
#endif
static int rr_tl_on(void)
{
    static int on = -1;
    if (on < 0) { const char* e = getenv("RR_TASK_LAT"); on = (e && *e && *e != '0') ? 1 : 0; }
    return on;
}
static unsigned long long rr_tl_us(void)
{
#ifdef _WIN32
    static LARGE_INTEGER f; LARGE_INTEGER c;
    if (!f.QuadPart) QueryPerformanceFrequency(&f);
    QueryPerformanceCounter(&c);
    return (unsigned long long)(c.QuadPart / f.QuadPart) * 1000000ull +
           (unsigned long long)((c.QuadPart % f.QuadPart) * 1000000ull / f.QuadPart);
#else
    struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);
    return (unsigned long long)t.tv_sec * 1000000ull + (unsigned long long)t.tv_nsec / 1000ull;
#endif
}
/* Caller holds s_tl_lock. */
static struct rr_tl_rec* rr_tl_get(uint32_t ts)
{
    for (int i = 0; i < RR_TL_MAX; i++) {
        if (s_tl[i].ts == ts) return &s_tl[i];
        if (!s_tl[i].ts) { s_tl[i].ts = ts; return &s_tl[i]; }
    }
    return NULL;
}
/* Caller holds s_tl_lock. Rate-limited to one report per 2 s. */
static void rr_tl_report(unsigned long long now)
{
    if (!s_tl_t0) { s_tl_t0 = now; return; }
    if (now - s_tl_t0 < 2000000ull) return;
    const double secs = (double)(now - s_tl_t0) / 1e6;
    for (int i = 0; i < RR_TL_MAX && s_tl[i].ts; i++) {
        struct rr_tl_rec* r = &s_tl[i];
        if (!r->n_run && !r->n_wake && !r->n_sig) continue;
        fprintf(stderr, "[task-lat] taskset=0x%08X jobs/s=%.1f signals/s=%.1f "
                "run_mean=%.2fms run_max=%.2fms wake_mean=%.0fus wake_max=%.0fus park_mean=%.2fms\n",
                r->ts, r->n_wake / secs, r->n_sig / secs,
                r->n_run ? r->run_sum / 1000.0 / r->n_run : 0.0, r->run_max / 1000.0,
                r->n_wake ? (double)r->wake_sum / r->n_wake : 0.0, (double)r->wake_max,
                r->n_wake ? r->park_sum / 1000.0 / r->n_wake : 0.0);
        r->n_sig = r->n_run = r->n_wake = 0;
        r->run_sum = r->run_max = r->wake_sum = r->wake_max = r->park_sum = 0;
    }
    fflush(stderr);
    s_tl_t0 = now;
}
static void rr_tl_signal(uint32_t ts)
{
    if (!rr_tl_on()) return;
    unsigned long long now = rr_tl_us();
    RR_TL_LOCK();
    struct rr_tl_rec* r = rr_tl_get(ts);
    if (r) { r->n_sig++; if (!r->sig_us) r->sig_us = now; }
    rr_tl_report(now);
    RR_TL_UNLOCK();
}

void spu_taskset_signal_task(uint32_t taskset_ea, uint32_t taskId)
{
    if (!taskset_ea || taskId >= 128) return;
    rr_tl_signal(taskset_ea);
#ifdef _WIN32
    AcquireSRWLockExclusive(&s_sig_lock);
    spu_signalled_update(taskset_ea, taskId, 1);
    WakeAllConditionVariable(&s_sig_cv);
    ReleaseSRWLockExclusive(&s_sig_lock);
#else
    pthread_mutex_lock(&s_sig_lock);
    spu_signalled_update(taskset_ea, taskId, 1);
    pthread_cond_broadcast(&s_sig_cv);
    pthread_mutex_unlock(&s_sig_lock);
#endif
    { static int _n = 0; if (PS3_LOG_FIRST(_n, 24))
        fprintf(stderr, "[spu_workload] signal task %u (taskset 0x%08X)\n",
                taskId, taskset_ea); fflush(stderr); }
    /* SPU_SIG_STATS=1: signals per second per (taskset, task, caller). */
    { static int s_on = -1; if (s_on < 0) s_on = getenv("SPU_SIG_STATS") ? 1 : 0;
      if (s_on) {
          static uint32_t ts[32], tk[32]; static uintptr_t ca[32]; static unsigned cnt[32];
          static unsigned long long t0;
          extern unsigned long long ps3_ms_now(void);
          const uintptr_t c = (uintptr_t)__builtin_return_address(0);
          for (int i = 0; i < 32; i++) {
              if (cnt[i] && ts[i] == taskset_ea && tk[i] == taskId && ca[i] == c) { cnt[i]++; break; }
              if (!cnt[i] && !ts[i]) { ts[i] = taskset_ea; tk[i] = taskId; ca[i] = c; cnt[i] = 1; break; }
          }
          unsigned long long now = ps3_ms_now();
          if (!t0) t0 = now;
          if (now - t0 >= 5000) {
              for (int i = 0; i < 32 && ts[i]; i++) {
                  fprintf(stderr, "[sig-stats] taskset=0x%08X task=%u caller=%p %.1f/s\n",
                          ts[i], tk[i], (void*)ca[i], cnt[i] * 1000.0 / (now - t0));
                  cnt[i] = 0; ts[i] = 0;
              }
              t0 = now;
          }
      } }
}

/* A successful PUTLLC/PUTLLUC committed the 128-byte guest line `line`.
 *
 * A task signalling another task does it on the SPU, as libspurs does: a
 * GETLLAR/PUTLLC loop that sets the target's bit in the taskset's signalled
 * bitset. That updates the guest bit the waiter checks but never touches
 * s_sig_cv, so the parked task only saw it when its 1 s timed wait ran out.
 * Twisted Metal's post-FX pipeline chains its six tasks this way several
 * times a frame and took 4 s or more per frame. Wake the waiters whenever a
 * line holding a parked taskset's signalled bitset is committed; a commit
 * that did not signal them only costs a spurious wake, which the wait loop
 * re-checks. */
void spu_taskset_line_committed(uint32_t line)
{
    rr_ts_commit_maybe_start(line);   /* spurs-20261108: see rr_ts_commit_maybe_start */
    for (int i = 0; i < SPU_PARKED_MAX; i++) {
        const uint64_t k = s_parked[i];
        if (!k || (((uint32_t)(k >> 32) + CSTS_SIGNALLED) & ~127u) != line) continue;
#ifdef _WIN32
        AcquireSRWLockExclusive(&s_sig_lock);
        WakeAllConditionVariable(&s_sig_cv);
        ReleaseSRWLockExclusive(&s_sig_lock);
#else
        pthread_mutex_lock(&s_sig_lock);
        pthread_cond_broadcast(&s_sig_cv);
        pthread_mutex_unlock(&s_sig_lock);
#endif
        return;
    }
}

/* WAIT_SIGNAL from the task side (runs ON the task's host thread, called by
 * the 0xA70 taskset-syscall intercept). Consumes a pending signal or blocks
 * until one is delivered. Returns 0 (the syscall's success rc). */
int spu_taskset_wait_signal(uint32_t taskset_ea, uint32_t taskId)
{
    if (!taskset_ea || taskId >= 128) return 0;
    /* ran= is the wall time this task spent OUT of the wait (decode/mix work
     * per round) -- decisive for "is the Bink decode CPU-bound". TLS: each
     * task runs on its own host thread. */
    static _Thread_local unsigned long long s_wait_exit_ms;
    static _Thread_local unsigned long long s_tl_exit_us;
    unsigned long long tl_enter_us = 0;
    if (rr_tl_on()) {
        tl_enter_us = rr_tl_us();
        if (s_tl_exit_us) {
            unsigned long long run = tl_enter_us - s_tl_exit_us;
            RR_TL_LOCK();
            struct rr_tl_rec* r = rr_tl_get(taskset_ea);
            if (r) { r->n_run++; r->run_sum += run; if (run > r->run_max) r->run_max = run; }
            RR_TL_UNLOCK();
        }
    }
    { extern unsigned long long ps3_ms_now(void);
      unsigned long long _now = ps3_ms_now();
      static unsigned _n = 0; if (_n++ < 200 || (_n % 500) == 0)   /* unsigned: periodic, wrapping is defined */
        fprintf(stderr, "[spu_workload] WAIT_SIGNAL#%u enter task=%u taskset=0x%08X ran=%llums\n",
                _n, taskId, taskset_ea,
                s_wait_exit_ms ? (_now - s_wait_exit_ms) : 0ull); }
    /* LBP_SYNC_ACK: taskset sync-lane bookkeeping. On real SPURS the taskset
     * POLICY MODULE advances the per-SPU progress lanes (sync+0x40+16*row:
     * ticket u16 @+0, consumer lanes @+2..) as tasks are processed; our HLE
     * runs the task on a dedicated thread and re-runs the PM ~never, so the
     * lanes froze and the skip path's min-of-lanes barrier (sub_4D3730) hung
     * forever. A task ENTERING WAIT_SIGNAL has by definition drained all work
     * dispatched to it, so advancing the active lanes to the published ticket
     * here is semantically the PM's bookkeeping, batched. Validation gate. */
    static int s_sync_ack = -1; if (s_sync_ack < 0) s_sync_ack = getenv("LBP_SYNC_ACK") ? 1 : 0;
    if (s_sync_ack) {
        extern uint32_t g_barrier_sync_watch;
        uint32_t b = g_barrier_sync_watch;
        if (b) {
            for (int row = 0; row < 4; row++) {
                uint32_t p = b + 0x40 + 16u * (uint32_t)row;
                extern uint8_t* vm_base;
                uint16_t ticket = (uint16_t)((vm_base[p] << 8) | vm_base[p+1]);
                for (int lane = 0; lane < 7; lane++) {
                    uint32_t la = p + 2 + 2u * (uint32_t)lane;
                    uint16_t cur = (uint16_t)((vm_base[la] << 8) | vm_base[la+1]);
                    if (cur != 0xFFFF && cur < ticket) {
                        vm_base[la]   = (uint8_t)(ticket >> 8);
                        vm_base[la+1] = (uint8_t)ticket;
                    }
                }
            }
            { static int _a = 0; if (PS3_LOG_FIRST(_a, 8))
                fprintf(stderr, "[sync-ack] lanes advanced to tickets (sync=0x%08X)\n", b); }
        }
    }
    unsigned secs = 0;
    /* LBP_WS_DRAIN=<secs>: EXPERIMENT (general work-drained approximation).
     * A task ENTERING WAIT_SIGNAL has drained the work dispatched to it. In our
     * one-shot SPU model the producer task ran to completion already, so the
     * signal never arrives and the consumer blocks forever (movie/audio/loading
     * deadlock). If set, after <secs> of no real signal we RETURN rc=0 as if the
     * kernel resumed the task with "no pending work" -- lets it run its post-wait
     * path (complete its loop / set completion flags) instead of hanging. 0/unset
     * keeps the block-forever behaviour. Reversible, opt-in. */
    static int s_drain = -1; if (s_drain < 0) { const char* e = getenv("LBP_WS_DRAIN"); s_drain = e ? (atoi(e) > 0 ? atoi(e) : 1) : 0; }
    unsigned drain = (unsigned)s_drain;
    int drained = 0;
    /* Release the global SPU-serial lock while parked so another SPU task can
     * run (and possibly signal us); re-acquired before returning to resume. */
    spu_serial_release();
#ifdef _WIN32
    AcquireSRWLockExclusive(&s_sig_lock);
    while (!spurs_bitset_test(taskset_ea + CSTS_SIGNALLED, taskId)) {
        if (!SleepConditionVariableSRW(&s_sig_cv, &s_sig_lock, 1000, 0)) {
            static int _n = 0;
            if (++secs && _n < 16) { _n++;
                fprintf(stderr, "[spu_workload] task %u (taskset 0x%08X) sleeping "
                        "%us in WAIT_SIGNAL\n", taskId, taskset_ea, secs); fflush(stderr); }
            if (drain && secs >= drain) { drained = 1; break; }
        }
    }
    if (!drained) spu_signalled_update(taskset_ea, taskId, 0);
    ReleaseSRWLockExclusive(&s_sig_lock);
#else
    pthread_mutex_lock(&s_sig_lock);
    while (!spurs_bitset_test(taskset_ea + CSTS_SIGNALLED, taskId)) {
        struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += 1;
        if (pthread_cond_timedwait(&s_sig_cv, &s_sig_lock, &ts) != 0) {
            static int _n = 0;
            if (++secs && _n < 16) { _n++;
                fprintf(stderr, "[spu_workload] task %u (taskset 0x%08X) sleeping "
                        "%us in WAIT_SIGNAL\n", taskId, taskset_ea, secs); fflush(stderr); }
            if (drain && secs >= drain) { drained = 1; break; }
        }
    }
    if (!drained) spu_signalled_update(taskset_ea, taskId, 0);
    pthread_mutex_unlock(&s_sig_lock);
#endif
    if (drained) { static int _d = 0; if (PS3_LOG_FIRST(_d, 24))
        fprintf(stderr, "[spu_workload] task %u (taskset 0x%08X) WS_DRAIN resume "
                "after %us (no signal)\n", taskId, taskset_ea, secs); fflush(stderr); }
    spu_serial_acquire();       /* resume: re-take the serial lock */
    { extern unsigned long long ps3_ms_now(void);
      s_wait_exit_ms = ps3_ms_now(); }   /* stamp for the next entry's ran= */
    if (tl_enter_us) {
        unsigned long long now = rr_tl_us();
        RR_TL_LOCK();
        struct rr_tl_rec* r = rr_tl_get(taskset_ea);
        if (r) {
            /* A signal latched before the task parked is measured from entry. */
            unsigned long long from = r->sig_us > tl_enter_us ? r->sig_us : tl_enter_us;
            unsigned long long lat = r->sig_us ? now - from : 0;
            r->n_wake++; r->wake_sum += lat; if (lat > r->wake_max) r->wake_max = lat;
            r->park_sum += now - tl_enter_us;
            r->sig_us = 0;
        }
        rr_tl_report(now);
        RR_TL_UNLOCK();
        s_tl_exit_us = now;
    }
    return 0;
}

/* mspost-20261108: the task identity (taskset EA + task id) used to reach this
 * function through the single-slot globals g_ydkj_real_taskset_ea/_taskid,
 * written by cellSpursCreateTask (PPU thread) and by the taskset exit scan
 * (SPU host thread) and read back here only AFTER the image fingerprint (an
 * FNV pass over the whole ELF). Two PPU threads creating tasks at once --
 * MotorStorm's two Havok workers do exactly that when the main thread
 * releases a physics step -- could both capture the second task's id: that
 * task ran twice, the first one never ran but stayed marked running (so the
 * exit scan never started it either), and the worker spun forever on its
 * completion byte while the main thread waited in sys_cond_wait (intermittent
 * hang right after the menu video). Callers that know the task now pass it
 * explicitly; the legacy entry snapshots the globals on entry.
 * RR_TS_EXPLICIT_TASKID=0 restores the old late read of the globals. */
static int rr_ts_explicit_on(void)
{
    static int on = -1;
    if (on < 0) { const char* e = getenv("RR_TS_EXPLICIT_TASKID");
                  on = (e && e[0] == '0' && !e[1]) ? 0 : 1; }
    return on;
}
static int spu_workload_dispatch_async_core(const uint8_t* image, uint32_t image_size,
                                            uint32_t args_ea, int have_id,
                                            uint32_t id_taskset, uint32_t id_task);
int spu_workload_dispatch_async(const uint8_t* image, uint32_t image_size,
                                uint32_t args_ea)
{
    extern uint32_t g_ydkj_real_taskset_ea, g_ydkj_real_taskid;
    const uint32_t ts = g_ydkj_real_taskset_ea, t = g_ydkj_real_taskid;
    return spu_workload_dispatch_async_core(image, image_size, args_ea,
                                            rr_ts_explicit_on(), ts, t);
}
int spu_workload_dispatch_async_task(const uint8_t* image, uint32_t image_size,
                                     uint32_t args_ea, uint32_t taskset_ea,
                                     uint32_t taskid)
{
    return spu_workload_dispatch_async_core(image, image_size, args_ea,
                                            rr_ts_explicit_on(), taskset_ea, taskid);
}
static int spu_workload_dispatch_async_core(const uint8_t* image, uint32_t image_size,
                                            uint32_t args_ea, int have_id,
                                            uint32_t id_taskset, uint32_t id_task)
{
    if (!image || image_size == 0) return 0;

    uint64_t fp = spu_workload_fingerprint(image, image_size);
    spu_lifted_entry_fn fn = NULL;
    int image_id = 0;
    for (unsigned i = 0; i < s_registry_count; i++)
        if (s_registry[i].fp == fp) { fn = s_registry[i].fn; image_id = s_registry[i].image_id; break; }
    if (!fn) {
        /* SPU_DUMP_MISS also applies here. The sync path has written the
         * unrecognised image out for a while and the async path did not, so a
         * workload policy module -- which is always dispatched async, being a
         * persistent worker -- could only ever report a fingerprint you had no
         * way to resolve. These blobs are not ELFs in the EBOOT, so this dump
         * is the only place their bytes exist. */
        { const char* _dir = getenv("SPU_DUMP_MISS");
          if (_dir && *_dir) {
              static uint64_t _seen[64]; static unsigned _nseen = 0;
              unsigned _k = 0;
              for (; _k < _nseen; _k++) if (_seen[_k] == fp) break;
              if (_k == _nseen && _nseen < 64) {
                  char _path[512];
                  _seen[_nseen++] = fp;
                  char _nm[64];
                  snprintf(_nm, sizeof(_nm), "spujob_%016llX_%u.bin",
                           (unsigned long long)fp, image_size);
                  FILE* _f = spu_dump_miss_open(_dir, _nm, _path, sizeof(_path));
                  if (_f) { fwrite(image, 1, image_size, _f); fclose(_f);
                      fprintf(stderr, "[spu_workload] wrote %s\n", _path); }
              }
          } }
        fprintf(stderr, "[spu_workload] async dispatch MISS fp=0x%016llX size=%u\n",
                (unsigned long long)fp, image_size);
        return 0;
    }

    spu_async_job* j = (spu_async_job*)malloc(sizeof(*j));
    if (!j) return 0;
    j->image = image; j->image_size = image_size; j->args_ea = args_ea;
    j->fn = fn; j->image_id = image_id;
    /* Capture the taskset+taskid NOW (PPU thread, right after cellSpursCreateTask
     * set the globals for THIS task). Reading them later in the async thread races
     * the next CreateTask overwriting the single-slot globals -- with two audio
     * tasks that made both run task 1's descriptor. */
    { extern uint32_t g_ydkj_real_taskset_ea, g_ydkj_real_taskid;
      const uint32_t g_ts = g_ydkj_real_taskset_ea, g_t = g_ydkj_real_taskid;
      if (have_id) {
          j->taskset_ea = id_taskset; j->taskid = id_task;
          /* Evidence: another thread replaced the globals while this dispatch
           * was in flight -- the old code would have run the wrong task. */
          if (g_ts != id_taskset || g_t != id_task) {
              static volatile long s_race;
              long k = InterlockedIncrement(&s_race);
              if (k <= 16 || (k % 1000) == 0) {
                  fprintf(stderr, "[taskset] dispatch-race#%ld avoided: task %u of taskset 0x%08X "
                          "(globals now say task %u of 0x%08X)\n", k, id_task, id_taskset, g_t, g_ts);
                  fflush(stderr);
              }
          }
      } else { j->taskset_ea = g_ts; j->taskid = g_t; } }
    /* Mark the task running NOW, not when its thread starts: in that gap another
     * task's exit saw it ready-but-not-running and started it a second time
     * (Twisted Metal's level-load inflate tasks each ran twice, concurrently). */
    spu_taskset_mark(j->taskset_ea, j->taskid, 1);
    /* Capture the SPURS task r3 NOW (PPU thread, synchronous) from the game's
     * descriptor at eaContext+0x10 = {0x40-marker handle, workload EAs}; the
     * async SPU thread reading it later would race the PPU stack. word1 is
     * overridden to args_ea (eaContext) in spu_run_lifted_job_abi. */
    j->have_r3 = 0;
    if (args_ea) {
        extern uint8_t* vm_base;
        const uint8_t* c = vm_base + args_ea + 0x10;
        for (int k = 0; k < 4; k++)
            j->r3[k] = ((uint32_t)c[k*4]<<24)|((uint32_t)c[k*4+1]<<16)|
                       ((uint32_t)c[k*4+2]<<8)|c[k*4+3];
        if ((j->r3[0] >> 16) == 0x40) j->have_r3 = 1;   /* valid marker */
    }

    if (rr_spurs_verbose()) fprintf(stderr,
        "[spu_workload] dispatch HIT (async) fp=0x%016llX args=0x%08X image=%d -> spawning thread\n",
        (unsigned long long)fp, args_ea, image_id);
    if (args_ea) { extern uint8_t* vm_base; const uint8_t* c = vm_base + args_ea;
        static int _d=0; if (PS3_LOG_FIRST(_d, 1)) {
            /* Dump a larger window of the task context buffer + scan for any word
             * that looks like the LS[0xBEC0] target (i.e. a small LS-range value),
             * to see if the kernel-restored LS data lives here (real game data). */
            /* The policy module restores the task context from a save buffer into
             * LS 0xB200; LS[0xBEC0] = ctxbuf + 0xCC0. Check the heap-EA candidates
             * in the descriptor for a save buffer whose +0xCC0/+0xCC8 holds a
             * small LS pointer (a valid P for LS[0xBEC8]). */
            uint32_t cand[5];
            cand[0]=((uint32_t)c[0x14]<<24)|((uint32_t)c[0x15]<<16)|((uint32_t)c[0x16]<<8)|c[0x17];
            cand[1]=((uint32_t)c[0x1C]<<24)|((uint32_t)c[0x1D]<<16)|((uint32_t)c[0x1E]<<8)|c[0x1F];
            cand[2]=((uint32_t)c[0x98]<<24)|((uint32_t)c[0x99]<<16)|((uint32_t)c[0x9A]<<8)|c[0x9B];
            cand[3]=((uint32_t)c[0xB8]<<24)|((uint32_t)c[0xB9]<<16)|((uint32_t)c[0xBA]<<8)|c[0xBB];
            cand[4]=((uint32_t)c[0x16C]<<24)|((uint32_t)c[0x16D]<<16)|((uint32_t)c[0x16E]<<8)|c[0x16F];
            for (int ci=0; ci<5; ci++) {
                uint32_t ea=cand[ci]; if (!ea || ea>=0x10000000) continue;
                const uint8_t* b = vm_base + ea + 0xCC0;
                fprintf(stderr, "[ctxbuf cand 0x%08X +0xCC0]:", ea);
                for (int k=0;k<0x20;k+=4) {
                    uint32_t w=((uint32_t)b[k]<<24)|((uint32_t)b[k+1]<<16)|((uint32_t)b[k+2]<<8)|b[k+3];
                    fprintf(stderr, " %08X%s", w, (w>0&&w<0x40000)?"<LS":"");
                }
                fprintf(stderr, "\n");
            } } }

#ifdef _WIN32
    /* 256MB RESERVE (not commit): the Bink SPU decoder's per-macroblock brsl
     * chains are deep host call chains with fat lifted frames -- a 1MB stack
     * blew the guard page (STATUS_GUARD_PAGE_VIOLATION 0x80000001, silent
     * process death) the moment the real decode path first executed. */
    HANDLE th = CreateThread(NULL, 256u << 20, spu_async_thread, j,
                             STACK_SIZE_PARAM_IS_A_RESERVATION, NULL);
    if (!th) { free(j); return 0; }
    CloseHandle(th);   /* detached */
#else
    /* Same 256 MB reservation, for the same reason: pthread stacks are
     * mmap'd and committed on touch, so this reserves address space rather
     * than memory. The default is 512 KB on Darwin, half the 1 MB that blew
     * the guard page above. */
    pthread_t th;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    int prc = EINVAL;
    if (pthread_attr_setstacksize(&attr, 256u << 20) == 0)
        prc = pthread_create(&th, &attr, spu_async_thread, j);
    pthread_attr_destroy(&attr);
    /* A host that will not reserve that much still gets the thread, on the
     * default stack: a shallow SPU job runs there, and a deep one dying
     * beats never dispatching at all. */
    if (prc != 0)
        prc = pthread_create(&th, NULL, spu_async_thread, j);
    if (prc != 0) { free(j); return 0; }
    pthread_detach(th);
#endif
    return 1;
}
