mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
Honor NVN queue dependencies and preserve conditional state across continuations
GPU event waits now park their logical queue until its producer releases the event. Owned command and descriptor snapshots, logical sync receipts and queued presents preserve ordering and object lifetime while other queues run. Completion lands CPU-visible effects before publishing an event.
Render-enable state and pending timestamp counter values survive physical Metal prefixes; later buffer writes replace forwarded counter bytes. Native task/mesh draws compile their demanded pipeline before first use instead of silently omitting geometry during loading.
These general NVN fixes address Ocarina's scene flashes and the pale outline around Link on M4 Pro. Main's timestamp policy and unavailable-query fallback are retained; resolution and performance work are separate.
Validation: Metal-validated event/receipt80, descriptor lifetime38, continuation38, mesh first use42 and storage-writer34 checks per encoder mode; capture91, suspend22, NVN245, alias residency28, completion ordering36 in three configurations, and counter-overlap42 per mode. Documentation checks pass. Earlier bounded Ocarina captures and the user's visual test have no halo or large flash.
Broad NVN scheduling gives uncertain regression reach. The five-game check (Ocarina, Three Houses, Octopath Traveler 0, Octopath Traveler II and Okami HD) is still rebuilding current-main shaders at this push; no completed result is claimed. The older CPU-post report/GPU-byte ordering limitation remains open. PR1673's flower fix is already landed and credited in upstream e5f1adee.
This commit is contained in:
1 parent
51ecd693b0
commit
ea0c98df35
28 files changed
+1807
-124
No files matched your search
@@ -65,6 +65,14 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F
|
||||
|
||||
## Open
|
||||
|
||||
- Root cause confirmed on M4 Pro (2026-11-08): [ignored event waits](../../../docs/reference/nvn-objects.md#gpu-event-waits-order-work-across-queues) let lighting consumers run before their producers. The game issues about 25 waits and 19 signals per frame. All 297 complete traced frames submit queue 5's ambient-cache consumer `9e6b00b050e30801` before queue 1's SH producer `21d9f83e6027c565`, despite the explicit dependency. Queue 1 also waits for the CPU frame-ready event after the CPU clears the lighting buffer. At frame 3872 the consumer ran at 0.686 ms, the clear at 0.966–0.968 ms, and the producer at 1.282 ms; its release followed at 4.467 ms. Exposure writer `1bba09ec4bc8ff67` has another event dependency. The native SDK's flush/invalidate functions are no-ops for these coherent pools.
|
||||
- The pale outline around Link is produced before fog, bloom and upscaling, by task `efaa4fa6a80ba719`, mesh `066f5daf12e43c71`, fragment `5ad65c0eefd09c7f`. An offline replay matches both 768x432 RGBA16F targets byte for byte. Removing shared-buffer bytes 48–111 makes direct SH lighting agree with the cached ambient lookup (affected-pixel mean RGB error 0.100/0.136/0.218 falls to 0.0034/0.0020/0.0008): the cache lacked the SH contribution available to the later direct draw. Honoring the event dependency removes the outline, confirmed by the player and later captures.
|
||||
- A repeating patchy pale layer remained after event ordering was fixed, including with optional attachment discard disabled. [Conditional rendering state lost across queue continuations](../../../docs/reference/rendering.md#conditional-rendering-survives-queue-continuations) caused repeated clears: disabled draws and pending timestamp counter values must survive physical Metal submission boundaries. Fixing both removes the layer in 2,000 asynchronous frames covering a stationary view, loading, camera rotation and movement to the village floor. The loading peak is the normal black-to-scene fade; the camera peak is a foreground branch crossing the view. These bounded samples do not establish every later area is unaffected. Synchronous screenshots wait for the GPU and can hide the original race, so validation uses asynchronous present copies. The rebased delivery subset passes the focused queue, descriptor, continuation, completion, residency and mesh-first-use checks. The current-main shader rebuild and five-game regression are still running at the visual-fix push.
|
||||
- Diagnostic caveat: earlier shader probes used fragment buffer 30, which conflicts with alpha-test state, then buffer 28 with added atomics that can move depth testing late. Visual conclusions from those instrumented runs are inconclusive. The event trace, offline producer comparison and combined validation above use the original uninstrumented fragment libraries. The scene flash predates those probes.
|
||||
- Regression reach is uncertain because every NVN submission now passes through logical queue scheduling. The five selected checks are Ocarina (the original dependency), Three Houses (multiple queues), Octopath Traveler 0 (command-buffer fences and Unreal RHI), Octopath Traveler II (an available boot route), and Okami HD (an older NVN path). The run is in progress; its unfinished rebuild is not a passing result. The focused tests pass with Metal validation: event/receipt 80, descriptor lifetime 38, continuation 38, native mesh first use 42 and storage-writer state 34 checks per encoding mode; capture 91, suspend 22, NVN 245, alias residency 28, completion ordering 36 in each of three configurations, and counter-overlap 42 per mode. The older CPU-post report/GPU-byte ordering limitation remains open as described in the rendering reference.
|
||||
|
||||
- Open on M4 Pro: low internal resolution and frame-rate instability are separate ongoing work. The visual-fix delivery retains main's timestamp policy and unavailable-query behavior; it does not claim a performance or resolution fix. Measurements here share the Mac with a separate shader build, per the testing constraint.
|
||||
|
||||
- Resolved: the build left 9 shaders out. Six foliage compute shaders used `ATOMG.CAS` ([Global memory: descriptors, ATOMG.CAS, INC / DEC](../../../docs/reference/shaders.md#global-memory-descriptors-atomgcas-inc--dec)); `1f78730053feb036` and `e172bd7ec218ab8e` nest 259 brackets ([Bracket nesting past the front end's 256](../../../docs/reference/shaders.md#bracket-nesting-past-the-front-ends-256)); `68bbe98b3bfd9876` (`Ampere instruction 481 at 0x0`) and five more map rows were no shaders at all ([A control section's words read as a BAHS entry](../../../docs/reference/shaders.md#a-control-sections-words-read-as-a-bahs-entry)), now gone from the map. None of the eight real ones was used on the walk to Kokiri Forest.
|
||||
- Open: [the movie network](https://github.com/seedds/nxnative/issues/1375) took 35 ms a frame on an M1 Max, so movies and the title ran at about 28 fps there; on this M6 it takes 11.4 ms since [HMMA chains keep their matrices in the SIMD-group](../../../docs/reference/shaders.md#hmma-chains-keep-their-matrices-in-the-simd-group) (from 14.8), not measured on an M1 Max since.
|
||||
- Current: against a frame of console video of Navi's close-up the picture matches: hair and sign within 1–2 % in red and green. The causes, each general: [float atomics](../../../docs/reference/shaders.md#float-atomics-in-storage-memory) (too bright, yellow skin, a pale veil: the exposure read back from buffers that stayed 0), the terrain's CPU-written maps (holes, wrong materials; the profile keys above), [the gather offsets](../../../docs/reference/shaders.md#texturegatheroffsets-and-a-loop-over-its-offsets) (the dotted rows in blurred areas, born in the NDSR upscaler, three pictures from one input), and [image atomics on RGBA8](../../../docs/reference/shaders.md#image-atomics-on-a-32-bit-colour-texture) (the anti-aliasing's blend weights).
|
||||
@@ -81,6 +89,10 @@ From an empty save: at about 45 s `A` (title), `A` (New Game), then the movie. F
|
||||
## Found on this game
|
||||
|
||||
- [Position invariance across shaders](../../../docs/reference/shaders.md#position-invariance-across-shaders): white shapes on plants and bushes for single frames in Kokiri Forest, from the foliage's mesh pre-pass and mesh colour pass rounding the position apart.
|
||||
- [GPU event waits order work across queues](../../../docs/reference/nvn-objects.md#gpu-event-waits-order-work-across-queues): the lighting producer-to-consumer dependency is proven in native SDK code and 297 live traced frames; the halo disappears when it is honored.
|
||||
- [Conditional rendering survives queue continuations](../../../docs/reference/rendering.md#conditional-rendering-survives-queue-continuations): event/fence splits lost disabled draws and pending counter values, causing the remaining patchy scene flashes.
|
||||
- [Native mesh draws omitted while their pipeline compiles](../../../docs/reference/shaders.md#native-mesh-draws-omitted-while-their-pipeline-compiles): compile the first demanded native mesh pipeline before its draw; the prior background path omitted geometry and depth while loading.
|
||||
|
||||
- [An old NUP cache stamp makes the build unpack again](../../../docs/reference/packing.md#an-old-nup-cache-stamp-makes-the-build-unpack-again): after a packer update the v131072 image is checked against the NUP in 21.6 s and kept, instead of unpacked again.
|
||||
- [Uncompressed storage beside storage the GPU writes](../../../docs/reference/nvn-objects.md#uncompressed-storage-beside-storage-the-gpu-writes): resolved, the ground opening in holes after walking out of a cave and back (the terrain's height and blend maps came out as zeros once the first normal map had been drawn into their pool); a reload had hidden it.
|
||||
- [A damaged file in a NUP or a dump has no hash to fail](../../../docs/reference/packing.md#a-damaged-file-in-a-nup-or-a-dump-has-no-hash-to-fail): a contributor's NUP held three `.zs` textures beginning with zeros, and the background loader reloaded the fairy fountain model for ever (412% CPU); this repository's copy has none.
|
||||
|
||||
+34
-41
@@ -123,6 +123,7 @@ HLE_FORCE("nvnBootstrapLoader", "the NVN graphics API is replaced wholesale with
|
||||
#define B(x) ((x) & 0xff)
|
||||
|
||||
#include "nvn_obj.h"
|
||||
#include "nvn_queue.h"
|
||||
#include "nvn_capture.h" // DM_NVN_CAPTURE hooks
|
||||
|
||||
// ---------- Device ----------
|
||||
@@ -727,8 +728,8 @@ NVN(nvnProgramInitialize, NVNboolean, NVNprogram *p, NVNdevice *d) {
|
||||
(void)d; memset(p, 0, sizeof(prog_t)); ((prog_t *)p)->magic = MAGIC('P', 'R', 'O', 'G'); return 1;
|
||||
}
|
||||
NVN(nvnProgramFinalize, void, NVNprogram *p) {
|
||||
pthread_mutex_lock(&g_sub_mu); mtl_prog_forget((const prog_t *)p); pthread_mutex_unlock(&g_sub_mu);
|
||||
mtl_prog_release((prog_t *)p); ((prog_t *)p)->magic = 0;
|
||||
pthread_mutex_lock(&g_sub_mu); mtl_prog_forget((const prog_t *)p); mtl_prog_release((prog_t *)p); pthread_mutex_unlock(&g_sub_mu);
|
||||
((prog_t *)p)->magic = 0;
|
||||
}
|
||||
// A program's per-stage keys, one record per SetShaders, found by prog_t.serial (bit i of ok = stage i computed). A game may copy an NVNprogram after SetShaders and draw with
|
||||
// the copy, as on the console the struct holds the whole program: Unity does (Ori and the Will of the Wisps: 135 single-stage programs a boot). The copy carries the serial
|
||||
@@ -790,7 +791,8 @@ int prog_key(const prog_t *p, unsigned st, uint8_t key[8]) {
|
||||
NVN(nvnProgramSetShaders, NVNboolean, NVNprogram *p, int n, const NVNshaderData *sd) {
|
||||
prog_t *o = (prog_t *)p;
|
||||
if (n < 0 || n > 6) { LOG("[RED] ProgramSetShaders stage count %d", n); return 0; }
|
||||
mtl_prog_release(o); o->nstage = n; memcpy(o->sd, sd, n * sizeof *sd); o->serial = nvn_new_serial();
|
||||
pthread_mutex_lock(&g_sub_mu); mtl_prog_release(o); pthread_mutex_unlock(&g_sub_mu);
|
||||
o->nstage = n; memcpy(o->sd, sd, n * sizeof *sd); o->serial = nvn_new_serial();
|
||||
// The keys are computed here (see prog_key in nvn_obj.h): the control section is only guaranteed valid during this call; the code area lives in a memory pool and stays valid while the program is in use
|
||||
static int dump = -1; if (dump < 0) dump = getenv("DM_NVN_SHDUMP") != NULL;
|
||||
static const char *trace; static int trace_init;
|
||||
@@ -821,13 +823,13 @@ NVN(nvnProgramSetShaders, NVNboolean, NVNprogram *p, int n, const NVNshaderData
|
||||
|
||||
// ---------- Sync / events ----------
|
||||
NVN(nvnSyncInitialize, NVNboolean, NVNsync *s, NVNdevice *d) { (void)d; *(sync_t *)s = (sync_t){MAGIC('S', 'Y', 'N', 'C'), 0, 0}; return 1; }
|
||||
NVN(nvnSyncFinalize, void, NVNsync *s) { ((sync_t *)s)->magic = 0; }
|
||||
NVN(nvnSyncFinalize, void, NVNsync *s) { nvn_sync_release((sync_t *)s); ((sync_t *)s)->magic = 0; }
|
||||
NVN(nvnSyncSetDebugLabel, void, NVNsync *s, const char *l) { (void)s; (void)l; }
|
||||
// Fence = "all commands previously submitted to the queue have completed": record the fence value of the most recent submit
|
||||
NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)q; (void)c; (void)f; ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = mtl_last_fence(); }
|
||||
NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)c; (void)f; nvn_queue_fence((queue_t *)q,(sync_t *)s); }
|
||||
// A sync object that was never fenced waits until timeout, as on a real device; a fenced one is released only after the GPU has actually completed up to that fence value
|
||||
// A GPU-side wait on a sync: the host has a single Metal queue that executes submissions in order, so commands before the fence are always done first and nothing needs waiting. A sync not fenced yet (fenced later by another thread) is not waited for here; logged once
|
||||
NVN(nvnQueueWaitSync, NVNboolean, NVNqueue *q, const NVNsync *s) { (void)q; static int once; if (!((const sync_t *)s)->fenced && !once++) LOG("[nvn] QueueWaitSync: the sync object has no fence yet, the host does not wait"); return 1; }
|
||||
// Queue dependencies capture the current logical receipt; later re-fencing or finalizing the sync cannot retarget work already queued.
|
||||
NVN(nvnQueueWaitSync, NVNboolean, NVNqueue *q, const NVNsync *s) { nvn_queue_wait_sync((queue_t *)q,(const sync_t *)s); return 1; }
|
||||
// ZCull data: the host does no ZCull, so there is nothing to save / restore
|
||||
NVN(nvnCommandBufferRestoreZCullData, void, NVNcommandBuffer *c, NVNbufferAddress a, size_t n) { (void)c; (void)a; (void)n; }
|
||||
NVN(nvnCommandBufferSaveZCullData, void, NVNcommandBuffer *c, NVNbufferAddress a, size_t n) { (void)c; (void)a; (void)n; }
|
||||
@@ -838,6 +840,7 @@ static _Atomic uint64_t g_sync_ns;
|
||||
NVN(nvnSyncWait, NVNsyncWaitResult, const NVNsync *s, uint64_t timeout) {
|
||||
const sync_t *o = (const sync_t *)s;
|
||||
if (!o->fenced) return NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
|
||||
if(o->fenced==3) { if(nvn_sync_wait(o,0)) return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED; uint64_t t0=now_ns(); int ok=nvn_sync_wait(o,timeout); atomic_fetch_add(&g_sync_ns,now_ns()-t0); return ok?NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED:NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED; }
|
||||
int (*w)(uint64_t, uint64_t) = o->fenced == 2 ? mtl_wait_acq : mtl_wait;
|
||||
if (w(o->fence, 0)) return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED;
|
||||
uint64_t t0 = now_ns(); int ok = w(o->fence, timeout); atomic_fetch_add(&g_sync_ns, now_ns() - t0); // the frame's blocked SyncWait time (@sync_ms)
|
||||
@@ -854,8 +857,8 @@ NVN(nvnEventInitialize, NVNboolean, NVNevent *e, const NVNeventBuilder *b) {
|
||||
NVN_NOPROTO(nvnEventGetMemoryPool, NVNmemoryPool *, const NVNevent *e) { return (NVNmemoryPool *)((const ev_t *)e)->pool; }
|
||||
NVN_NOPROTO(nvnEventGetMemoryOffset, int64_t, const NVNevent *e) { return ((const ev_t *)e)->off; }
|
||||
NVN(nvnEventFinalize, void, NVNevent *e) { ((ev_t *)e)->magic = 0; }
|
||||
NVN(nvnEventGetValue, uint32_t, const NVNevent *e) { return *((const ev_t *)e)->val; }
|
||||
static void ev_signal(const ev_t *e, int mode, uint32_t v) { if (mode == NVN_EVENT_SIGNAL_MODE_ADD) *e->val += v; else *e->val = v; }
|
||||
NVN(nvnEventGetValue, uint32_t, const NVNevent *e) { return atomic_load_explicit((_Atomic uint32_t *)((const ev_t *)e)->val,memory_order_acquire); }
|
||||
static void ev_signal(const ev_t *e, int mode, uint32_t v) { nvn_event_publish(e->val,mode,v); }
|
||||
NVN(nvnEventSignal, void, NVNevent *e, NVNeventSignalMode m, uint32_t v) { ev_signal((const ev_t *)e, m, v); }
|
||||
|
||||
// ---------- Queue ----------
|
||||
@@ -886,13 +889,14 @@ NVN(nvnQueueInitialize, NVNboolean, NVNqueue *q, const NVNqueueBuilder *b) {
|
||||
OLOG("QueueInitialize %p", (void *)q); return 1;
|
||||
}
|
||||
NVN(nvnQueueFinalize, void, NVNqueue *q) {
|
||||
nvn_queue_forget((queue_t *)q);
|
||||
pthread_mutex_lock(&g_sub_mu); mtl_queue_forget(((queue_t *)q)->serial); ((queue_t *)q)->magic = 0; pthread_mutex_unlock(&g_sub_mu);
|
||||
}
|
||||
NVN(nvnQueueGetError, NVNqueueGetErrorResult, NVNqueue *q, NVNqueueErrorInfo *info) {
|
||||
(void)q; if (info) memset(info, 0, sizeof *info); return NVN_QUEUE_GET_ERROR_RESULT_GPU_NO_ERROR;
|
||||
}
|
||||
NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q; }
|
||||
NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; mtl_finish(); }
|
||||
NVN(nvnQueueFinish, void, NVNqueue *q) { nvn_queue_finish((queue_t *)q); }
|
||||
|
||||
// ---------- Command buffer: record into the game's command memory, perform CPU-visible side effects at submit ----------
|
||||
#define CB(c) ((cmd_t *)(c))
|
||||
@@ -1041,6 +1045,13 @@ NVN(nvnCommandBufferIsRecording, NVNboolean, const NVNcommandBuffer *c) { return
|
||||
NVN(nvnCommandBufferCopyCommands, void, NVNcommandBuffer *c, int n, const NVNcommandHandle *h) {
|
||||
for (int i = 0; i < n; i++) { uint8_t *p = cmd_alloc(CB(c), 16); put_hdr(p, OP_CALL, 16); memcpy(p + 8, &h[i], 8); }
|
||||
}
|
||||
NVN(nvnCommandBufferWaitEvent, void, NVNcommandBuffer *c, const NVNevent *e, NVNeventWaitMode mode, uint32_t value) {
|
||||
uint8_t *p=cmd_alloc(CB(c),24); put_hdr(p,OP_WAIT_EVENT,24); volatile uint32_t *word=((const ev_t *)e)->val; uint32_t m=mode;
|
||||
memcpy(p+8,&word,8); memcpy(p+16,&m,4); memcpy(p+20,&value,4);
|
||||
}
|
||||
NVN(nvnCommandBufferWaitSync, void, NVNcommandBuffer *c, const NVNsync *s) {
|
||||
uint8_t *p=cmd_alloc(CB(c),16); put_hdr(p,OP_WAIT_SYNC,16); memcpy(p+8,&s,8);
|
||||
}
|
||||
NVN(nvnCommandBufferSignalEvent, void, NVNcommandBuffer *c, const NVNevent *e, NVNeventSignalMode m, NVNeventSignalLocation loc, int flags, uint32_t v) {
|
||||
(void)loc; (void)flags;
|
||||
uint8_t *p = cmd_alloc(CB(c), 24); put_hdr(p, OP_SIGNAL_EVENT, 24);
|
||||
@@ -1404,33 +1415,14 @@ void dm_gfx_suspend(int on) {
|
||||
}
|
||||
// One submission at a time: the Metal replay keeps one command buffer and one upload batch for the submission in progress (nvn_mtl.m g_cb). Fire Emblem: Three Houses initializes two queues and
|
||||
// submits on both from two threads; the second submission arrived while the first was replaying and the host stopped with "submit re-entered" at the ninth frame. NVN orders work on different queues only
|
||||
// through syncs, so replaying the two queues' submissions in lock order is one valid order.
|
||||
// through syncs and events. The continuation scheduler parks unresolved queues and serializes only ready prefixes onto this Metal queue.
|
||||
// The first submission's prepare step (mtl_prepare: the prewarm and the pipeline prebuild) loads shaders and builds pipelines and submits no GPU work, so it runs under the lock but outside the
|
||||
// graphics gate: inside it, going to the background meanwhile (dm_gfx_suspend, on the main thread) waited for it, minutes on a first start. It stays host work for the guest scheduler. The lock
|
||||
// comes before the gate: a second submission waiting for it must not count as in flight, or the suspend waits for it while the first waits to enter the closed gate holding the lock
|
||||
#include "nvn_queue.inc"
|
||||
NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) {
|
||||
dm_host_mutex_lock(&g_sub_mu);
|
||||
dm_host_work++; mtl_prepare(); dm_host_work--;
|
||||
gfx_enter();
|
||||
uint64_t t0 = now_ns(), c0 = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID), i0, y0, s0 = thr_sys_ns(); thr_counts(&i0, &y0);
|
||||
((queue_t *)q)->submits++;
|
||||
mtl_queue_activate(((const queue_t *)q)->serial);
|
||||
mtl_set_queue_origin_lower_left(((const queue_t *)q)->origin_ll);
|
||||
nvn_cap_submit(n, (const uint64_t *)h); // DM_NVN_CAPTURE (nvn_capture.inc)
|
||||
mtl_sub_begin();
|
||||
nvn_ft_poll();
|
||||
mtl_sub_index((const uint64_t *)h, n);
|
||||
for (int i = 0; i < n; i++) { mtl_exec_rest((const uint64_t *)h + i + 1, n - i - 1); mtl_exec((const uint8_t *)h[i]); }
|
||||
mtl_exec_rest(NULL, 0);
|
||||
mtl_sub_commit();
|
||||
pthread_mutex_unlock(&g_sub_mu);
|
||||
uint64_t dw = now_ns() - t0;
|
||||
atomic_fetch_add(&g_nvn_ns, dw); atomic_fetch_add(&g_sub_wall_ns, dw);
|
||||
uint64_t i1, y1; thr_counts(&i1, &y1); uint64_t dc = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) - c0, di = i1 - i0;
|
||||
atomic_fetch_add(&g_cum_sub_cyc, y1 - y0); atomic_fetch_add(&g_cum_sub_sys_ns, thr_sys_ns() - s0); atomic_fetch_add(&g_cum_sub_wall_ns, dw);
|
||||
atomic_fetch_add(&g_sub_cpu_ns, dc); atomic_fetch_add(&g_cum_sub_cpu_ns, dc);
|
||||
atomic_fetch_add(&g_sub_instr, di); atomic_fetch_add(&g_cum_sub_instr, di);
|
||||
gfx_leave();
|
||||
nvn_queue_submit((queue_t *)q,n,(const uint64_t *)h);
|
||||
}
|
||||
|
||||
// Commands that only affect GPU state / only execute on the GPU: the null device only counts them (the thunk has already counted)
|
||||
@@ -1438,7 +1430,6 @@ static void nvn_nop(void) {}
|
||||
static const char *const g_nops[] = {
|
||||
"nvnCommandBufferSetPatchSize",
|
||||
"nvnCommandBufferSetDepthBounds",
|
||||
"nvnCommandBufferWaitSync",
|
||||
"nvnCommandBufferSetShaderScratchMemory",
|
||||
"nvnCommandBufferPushDebugGroupDynamic",
|
||||
"nvnCommandBufferPopDebugGroup",
|
||||
@@ -1448,8 +1439,6 @@ static const char *const g_nops[] = {
|
||||
"nvnCommandBufferPushDebugGroupStatic",
|
||||
"nvnCommandBufferPopDebugGroupId",
|
||||
"nvnCommandBufferInsertDebugMarkerStatic",
|
||||
"nvnCommandBufferWaitEvent",
|
||||
"nvnWindowFinalize",
|
||||
};
|
||||
__attribute__((constructor)) static void nvn_nops_register(void) {
|
||||
// Empty implementations overwrite the unimplemented stubs after the slot table is initialized; a misspelled name (not in main's name table) reports a failure and aborts at startup
|
||||
@@ -1530,7 +1519,7 @@ __attribute__((weak)) void dm_thread_cpu(char *out, size_t n, double secs) { (vo
|
||||
void mtl_res_stats(char *out, size_t n);
|
||||
void mtl_barrier_stats(uint64_t *skip, uint64_t *full);
|
||||
extern uint32_t mtl_present_qos(void);
|
||||
static uint64_t g_frame;
|
||||
static _Atomic uint64_t g_frame;
|
||||
static uint64_t g_acq_wait_ns, g_pq_wait_ns; // Accumulated display-link wait / wait for the present queue to return inside acquire, recorded per frame at present (there can be several acquires within one frame)
|
||||
static uint64_t g_fs_start, g_fs_wait; // frame step (fstep_tick): when the first acquire after a present returned (the frame's start, 0 = none yet), and its pacing wait
|
||||
uint64_t dm_nvn_frame_count(void) { return g_frame; }
|
||||
@@ -1562,12 +1551,16 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
|
||||
g_acq_wait_ns += wait; trow(g_frame, "@late_ms", wait ? (now_ns() - at) / 1e6 : 0);
|
||||
// The previous present of this texture has not yet been processed by the present thread (display cannot keep up, a whole swapchain round behind): wait for it to be returned, then hand it to the game to draw
|
||||
uint64_t tk = *idx < 4 ? o->ticket[*idx] : 0;
|
||||
if (tk) { uint64_t w0 = now_ns(); mtl_present_wait(tk); g_pq_wait_ns += now_ns() - w0; }
|
||||
if (s) { ((sync_t *)s)->fenced = 2; ((sync_t *)s)->fence = mtl_last_fence(); } // The swapchain texture becomes available once the commits before this point have completed (fenced 2: an acquire sync, for the wait ledger)
|
||||
if (tk) { uint64_t w0 = now_ns(); nvn_queue_present_wait(tk); nvn_queue_present_release(tk); o->ticket[*idx]=0; g_pq_wait_ns += now_ns() - w0; }
|
||||
if (s) { nvn_sync_release((sync_t *)s); ((sync_t *)s)->fenced = 2; ((sync_t *)s)->fence = mtl_last_fence(); } // The swapchain texture becomes available once the commits before this point have completed (fenced 2: an acquire sync, for the wait ledger)
|
||||
if (!g_fs_start) { g_fs_start = now_ns(); g_fs_wait = pace_ns; } // the frame starts when the first acquire after a present returns: on a display-link tick when on time
|
||||
return NVN_WINDOW_ACQUIRE_TEXTURE_RESULT_SUCCESS;
|
||||
}
|
||||
// The older API (NVN 53, Super Mario 3D World + Bowser's Fury): the queue waits for the texture on the GPU and no sync object is handed out. The host replays in submission order, so later commands already come after earlier presents; the same as WindowAcquireTexture without a sync object
|
||||
NVN(nvnWindowFinalize, void, NVNwindow *w) {
|
||||
win_t *o=(win_t *)w;
|
||||
for(int i=0;i<4;i++) { nvn_queue_present_release(o->ticket[i]); o->ticket[i]=0; }
|
||||
}
|
||||
NVN(nvnQueueAcquireTexture, NVNqueueAcquireTextureResult, NVNqueue *q, NVNwindow *w, int *idx) {
|
||||
(void)q; return h_nvnWindowAcquireTexture(w, NULL, idx) == NVN_WINDOW_ACQUIRE_TEXTURE_RESULT_SUCCESS ? (NVNqueueAcquireTextureResult)0 : (NVNqueueAcquireTextureResult)1;
|
||||
}
|
||||
@@ -2112,8 +2105,8 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
uint64_t t0 = now_ns();
|
||||
if (idx >= 0 && idx < o->ntex && idx < 4) { // enqueue only, return immediately
|
||||
const tex_t *t = CTX(o->tex[idx]); int lc[4]; const int *crop = present_crop(o->crop, (int)t->d.width, (int)t->d.height, lc);
|
||||
nvn_cap_present(t, crop); // DM_NVN_CAPTURE (nvn_capture.inc)
|
||||
o->ticket[idx] = mtl_present(t, present_period(o) / 1e9, crop);
|
||||
nvn_queue_present_release(o->ticket[idx]);
|
||||
o->ticket[idx] = nvn_queue_present((queue_t *)q,t,present_period(o) / 1e9,crop);
|
||||
}
|
||||
gfx_leave();
|
||||
atomic_fetch_add(&g_nvn_ns, now_ns() - t0);
|
||||
@@ -2196,7 +2189,7 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
dump_frame();
|
||||
{ void dm_vi_frame_queued(uint64_t); dm_vi_frame_queued(g_frame); } // the layer's frame history (hle_vi.c), numbered as GetLatestFrameNumber
|
||||
if (g_frame % TWIN == 0) tsummary(g_frame);
|
||||
mtl_set_frame(g_frame);
|
||||
// GPU replay carries the submitted frame, even when a later CPU frame is already queued.
|
||||
// Real-device semantics: present only enqueues and returns immediately; this frame's display time is scheduled by the pacer, and the texture can be acquired again only at "display time + one period" (blocking in AcquireTexture)
|
||||
uint64_t period = present_period(o), now = dm_detclock_enabled() ? guest_ns() : now_ns();
|
||||
g_hold_ring[o->presents % 16] = (uint8_t)present_itv(o);
|
||||
|
||||
@@ -33,7 +33,7 @@ CAP_SIZE(p_render_cond, 16); CAP_OFF(p_render_cond, mode, 0); CAP_OFF(p_render_c
|
||||
CAP_SIZE(p_multi_draw, 48); CAP_OFF(p_multi_draw, ind, 0); CAP_OFF(p_multi_draw, cnt, 8); CAP_OFF(p_multi_draw, ibuf, 16);
|
||||
CAP_OFF(p_multi_draw, stride, 24); CAP_OFF(p_multi_draw, max, 32); CAP_OFF(p_multi_draw, prim, 36); CAP_OFF(p_multi_draw, itype, 40);
|
||||
_Static_assert(OP_MULTI_DRAW == 55, "keep existing capture op numbers stable");
|
||||
_Static_assert(OP_COUNT_ == 56, "nvn_capture.c: a record op was added or removed: give it a case in cap_rec_fields");
|
||||
_Static_assert(OP_COUNT_ == 58, "nvn_capture.c: a record op was added or removed: give it a case in cap_rec_fields");
|
||||
|
||||
#define MULTI_DRAW_LAYOUT "op 55 p_multi_draw 48 ind 0 cnt 8 ibuf 16 stride 24 max 32 prim 36 itype 40\n"
|
||||
// Copy strides travel after a copy's texture snapshot (p_copy_strides) instead of as OP_COPY_STRIDE records; the replay still takes OP_COPY_STRIDE from older captures
|
||||
@@ -57,6 +57,25 @@ int cap_layout_matches(const char *layout, size_t n) {
|
||||
return (n == full || n == no_strides || n == no_multi) && !memcmp(layout, current, n);
|
||||
}
|
||||
|
||||
const char *cap_record_unsupported(uint32_t op) {
|
||||
if (op == OP_WAIT_EVENT) return "format 1 cannot replay event waits";
|
||||
if (op == OP_WAIT_SYNC) return "format 1 cannot replay sync receipt waits";
|
||||
return NULL;
|
||||
}
|
||||
void cap_queue_note(cap_queue_state *state, uint64_t serial, int waits) {
|
||||
uint64_t first = 0;
|
||||
atomic_compare_exchange_strong_explicit(&state->first, &first, serial, memory_order_relaxed, memory_order_relaxed);
|
||||
unsigned flags = waits ? CAP_QUEUE_WAIT : 0;
|
||||
if (first && first != serial) flags |= CAP_QUEUE_MULTIPLE;
|
||||
if (flags) atomic_fetch_or_explicit(&state->unsupported, flags, memory_order_relaxed);
|
||||
}
|
||||
const char *cap_queue_unsupported(const cap_queue_state *state) {
|
||||
unsigned flags = atomic_load_explicit(&state->unsupported, memory_order_relaxed);
|
||||
if (flags & CAP_QUEUE_WAIT) return "format 1 cannot capture logical event or sync waits";
|
||||
if (flags & CAP_QUEUE_MULTIPLE) return "format 1 cannot capture multiple logical NVN queues";
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// One 8-byte field at byte offset off of the payload, present only when the record is long enough to hold it
|
||||
#define HAS(off) ((uint64_t)(off) + 8 <= plen)
|
||||
#define F(off) ((uint64_t *)(payload + (off))) // records are 8-byte aligned and so are these fields
|
||||
@@ -79,10 +98,11 @@ int cap_rec_fields(uint32_t op, uint8_t *payload, uint32_t size, const cap_ops *
|
||||
return 1;
|
||||
case OP_JUMP: case OP_CALL: return HAS(0) && ops->obj(ctx, CAP_K_SEG, F(0), payload, (uint32_t)plen);
|
||||
case OP_SIGNAL_EVENT: return HAS(0) && ops->addr(ctx, F(0), 4, 1); // volatile uint32_t *val, mode, value
|
||||
case OP_WAIT_EVENT: return HAS(0) && ops->addr(ctx, F(0), 4, 0);
|
||||
case OP_REPORT_COUNTER: return HAS(8) && ops->addr(ctx, F(8), 16, 1); // type, address of the 16-byte report
|
||||
case OP_COPY_B2B: { if (!HAS(16)) return 0; uint64_t n = u64_at(payload + 16); return ops->addr(ctx, F(0), n, 0) & ops->addr(ctx, F(8), n, 1); }
|
||||
case OP_UPDATE_UB: { if (!HAS(8)) return 0; return ops->addr(ctx, F(0), u64_at(payload + 8), 1); } // dst, n, inline data
|
||||
case OP_FENCE_SYNC: return HAS(0) && ops->obj(ctx, CAP_K_SYNC, F(0), payload, (uint32_t)plen);
|
||||
case OP_FENCE_SYNC: case OP_WAIT_SYNC: return HAS(0) && ops->obj(ctx, CAP_K_SYNC, F(0), payload, (uint32_t)plen);
|
||||
case OP_SET_RT: {
|
||||
int32_t n = HAS(0) ? i32_at(payload) : -1; if (n < 0 || n > 8 || !HAS(offsetof(p_set_rt, depth))) return 0;
|
||||
for (int i = 0; i < n; i++) ok &= ops->obj(ctx, CAP_K_TEX, F(offsetof(p_set_rt, color) + 8 * (size_t)i), payload, (uint32_t)plen);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdatomic.h>
|
||||
#include "nvn_obj.h"
|
||||
|
||||
#define CAP_MAGIC "NVNCAP\0\0"
|
||||
@@ -38,6 +39,7 @@ enum {
|
||||
CAP_PRES = CAP_TAG('P', 'R', 'E', 'S'), // the present: cap_pres
|
||||
CAP_PHSH = CAP_TAG('P', 'H', 'S', 'H'), // after the frame: every region's 4 KiB block hashes as the live run left them ({u32 region, u32 blocks, u64 hash[blocks]}...), for the replayer to compare
|
||||
CAP_LPIX = CAP_TAG('L', 'P', 'I', 'X'), // the presented frame's pixels as the live run read them (level 0, rows packed, the format and size of cap_pres), for a pixel comparison; optional
|
||||
CAP_FAIL = CAP_TAG('F', 'A', 'I', 'L'), // text: why this capture cannot be replayed; readers must reject it
|
||||
CAP_END_ = CAP_TAG('E', 'N', 'D', ' '),
|
||||
};
|
||||
enum { CAP_RAW = 0, CAP_LZFSE = 1 };
|
||||
@@ -89,6 +91,13 @@ int cap_tex_fields(tex_t *t, const cap_ops *ops, void *ctx);
|
||||
// Layout fingerprint of every payload struct the walk knows (text): stored in the capture, compared by the replayer
|
||||
const char *cap_layout(void);
|
||||
int cap_layout_matches(const char *layout, size_t n);
|
||||
// Version 1 records physical submission order, not logical queues or wait dependencies.
|
||||
// Keep this separate from cap_rec_fields: the scheduler also uses that generic field walk.
|
||||
const char *cap_record_unsupported(uint32_t op);
|
||||
typedef struct { _Atomic uint64_t first; _Atomic unsigned unsupported; } cap_queue_state;
|
||||
enum { CAP_QUEUE_MULTIPLE = 1, CAP_QUEUE_WAIT = 2 };
|
||||
void cap_queue_note(cap_queue_state *state, uint64_t serial, int waits);
|
||||
const char *cap_queue_unsupported(const cap_queue_state *state);
|
||||
|
||||
// Writing: chunks, compressed with LZFSE when that makes them smaller
|
||||
typedef struct { FILE *f; uint64_t raw, stored; int err; } cap_writer;
|
||||
@@ -108,3 +117,5 @@ static inline void cap_buf_free(cap_buf *b) { free(b->p); b->p = NULL; b->n = b-
|
||||
// Host hooks (nvn_capture.inc, in nvn_mtl.m): hle_nvn.c calls them at each submit (under the submit lock, before the replay) and each present (before it is queued)
|
||||
void nvn_cap_submit(int n, const uint64_t *handles);
|
||||
void nvn_cap_present(const tex_t *t, const int crop[4]);
|
||||
// Called at logical enqueue, before the scheduler removes waits. Thread-safe; never waits for GPU work.
|
||||
void nvn_cap_queue(uint64_t serial, int waits);
|
||||
@@ -12,6 +12,8 @@
|
||||
static int g_cap_frame = -1; // -1: not parsed yet, 0: off
|
||||
static char g_cap_path[1024];
|
||||
static int g_cap_active, g_cap_done, g_cap_failed;
|
||||
static cap_queue_state g_cap_queues;
|
||||
void nvn_cap_queue(uint64_t serial, int waits) { cap_queue_note(&g_cap_queues, serial, waits); }
|
||||
static uint32_t g_cap_submit; // submits captured in the frame so far
|
||||
static uint64_t g_cap_presents; // presents seen (the frame number DM_NVN_SHOT uses)
|
||||
static cap_writer g_cap_w;
|
||||
@@ -44,6 +46,15 @@ static uint64_t cap_hash_block(const uint8_t *p, size_t n) { // a fast 64-bit
|
||||
return h;
|
||||
}
|
||||
static void cap_fail(const char *why) { if (!g_cap_failed++) MLOG("[RED] DM_NVN_CAPTURE: %s: the capture is incomplete", why); }
|
||||
static int cap_reject_queues(void) {
|
||||
const char *why = cap_queue_unsupported(&g_cap_queues); if (!why) return 0;
|
||||
cap_fail(why);
|
||||
// Replace a previous file at the requested path with an explicit failure too;
|
||||
// otherwise a rejected request could appear to have produced an old capture.
|
||||
if (!g_cap_w.f && !cap_open(&g_cap_w, g_cap_path)) MLOG("[RED] DM_NVN_CAPTURE: cannot write failure marker to %s", g_cap_path);
|
||||
if (g_cap_w.f) { cap_put(&g_cap_w, CAP_FAIL, g_cap_submit, why, strlen(why), 0); cap_close(&g_cap_w); }
|
||||
g_cap_active = 0; g_cap_done = 1; return 1;
|
||||
}
|
||||
|
||||
// ---------- Regions and the address encoding ----------
|
||||
static int cap_reg_find(uint64_t a) { // the region holding address a (regions are sorted and disjoint)
|
||||
@@ -197,6 +208,8 @@ static void cap_seg_write(uint32_t idx) { // copy the records from the segment
|
||||
for (size_t o = 0; o < n;) {
|
||||
op_hdr h; memcpy(&h, b + 8 + o, 8);
|
||||
g_cap_orig = p + o + 8; CAP_WHERE(b + 8 + o + 8, "op %u (%u bytes) at +%zu of segment %u", h.op, h.size, o, idx);
|
||||
const char *unsupported = cap_record_unsupported(h.op);
|
||||
if (unsupported) { cap_fail(unsupported); cap_put(&g_cap_w, CAP_FAIL, g_cap_cur_submit, unsupported, strlen(unsupported), 0); }
|
||||
if (!cap_rec_fields(h.op, b + 8 + o + 8, h.size, &g_cap_enc, NULL)) { cap_fail("a record the capture walk does not know"); MLOG("[RED] DM_NVN_CAPTURE: op %u size %u not walked", h.op, h.size); }
|
||||
o += h.size;
|
||||
}
|
||||
@@ -420,7 +433,7 @@ static void cap_submit_step(int n, const uint64_t *h);
|
||||
static void cap_present_step(const tex_t *t, const int crop[4]);
|
||||
// Hook: nvnQueueSubmitCommands, under the submit lock, before the submission is replayed
|
||||
void nvn_cap_submit(int n, const uint64_t *h) {
|
||||
if (!nvn_cap_enabled() || g_cap_presents + 1 != (uint64_t)g_cap_frame) return;
|
||||
if (!nvn_cap_enabled() || cap_reject_queues() || g_cap_presents + 1 != (uint64_t)g_cap_frame) return;
|
||||
cap_policy c = cap_policy_standard(); cap_submit_step(n, h); cap_policy_restore(c);
|
||||
}
|
||||
static void cap_submit_step(int n, const uint64_t *h) {
|
||||
@@ -469,7 +482,7 @@ static void cap_hex(const uint8_t *md, char out[65]) { for (int i = 0; i < 32; i
|
||||
|
||||
// Hook: nvnQueuePresentTexture, before the present is queued
|
||||
void nvn_cap_present(const tex_t *t, const int crop[4]) {
|
||||
if (!nvn_cap_enabled()) return;
|
||||
if (!nvn_cap_enabled() || cap_reject_queues()) return;
|
||||
g_cap_presents++;
|
||||
if (!g_cap_active || g_cap_presents != (uint64_t)g_cap_frame) {
|
||||
if (g_cap_presents >= (uint64_t)g_cap_frame && !g_cap_active) { MLOG("[RED] DM_NVN_CAPTURE: frame %d presented without a submit: nothing captured", g_cap_frame); g_cap_done = 1; }
|
||||
|
||||
@@ -550,12 +550,11 @@ static void geo_mesh_encode(id<MTLRenderCommandEncoder> en_) {
|
||||
// A program's task and mesh shaders are Metal object and mesh functions (dmsh_meshstage.py), kept in the tessellation stages' places (sh[3], sh[4]). The draw goes through draw() with its
|
||||
// pixel stage alone, a program of its own as a geometry draw's raster stage is, so it takes the render pass and the pixel stage's state like any draw; mtk_pso gives its pipeline and
|
||||
// mtk_encode binds the two stages and draws. The mesh stage shares the vertex stage's table, as geo_mesh_encode's does, and a task shader has the object stage's; both read the
|
||||
// draw's first workgroup at buffer 29. A pipeline is built in the background and its draws are left out until it is ready, as for a geometry mesh pipeline
|
||||
// draw's first workgroup at buffer 29. Native mesh draws have no equivalent fallback: the demanded pipeline must finish compiling before its first draw
|
||||
static struct { int on, miss; NvShader *ts, *ms; uint32_t first, count; uint64_t ind, ind_first; } g_mtk; // ind: an indirect draw's threadgroups, ind_first: where the GPU finds its first
|
||||
static void draw_(const p_draw *dw, const p_draw_idx *di);
|
||||
static uint64_t g_mtk_n, g_mtk_wait;
|
||||
static nvn_hmap g_pso_mtk = {.klen = sizeof(pso_key)}; static os_unfair_lock g_pso_mtk_lock = OS_UNFAIR_LOCK_INIT;
|
||||
static NSObject *g_pso_mtk_building;
|
||||
static nvn_hmap g_pso_mtk = {.klen = sizeof(pso_key)}; // only the submit thread creates and uses native mesh pipelines
|
||||
// A mesh pipeline must have a fragment function, where a vertex one need not (validateWithDevice). A task / mesh program with no pixel shader draws depth only (Ocarina of Time's foliage shadows)
|
||||
static id<MTLFunction> mtk_nop_fragment(void) {
|
||||
static id<MTLFunction> fn; static dispatch_once_t once;
|
||||
@@ -568,10 +567,8 @@ static id<MTLRenderPipelineState> mtk_pso(NvProg *raster) {
|
||||
pso_key k; pso_key_fill(&k, ms, fs, g_pass.cfmt, g_pass.dfmt, g_pass.sfmt, g_pass.samples, 0);
|
||||
memset(k.attr, 0, sizeof k.attr); memset(k.attr_hi, 0, sizeof k.attr_hi); memset(k.stream, 0, sizeof k.stream);
|
||||
k.fsfn = (__bridge void *)(ts ? ts->fn : ms->fn); // with ms in the key's vertex place: the task shader is the third of the pipeline's functions
|
||||
os_unfair_lock_lock(&g_pso_mtk_lock); id ps = hm_get_id(&g_pso_mtk, &k);
|
||||
if (!ps) { if (!g_pso_mtk_building) g_pso_mtk_building = [NSObject new]; hm_put_id(&g_pso_mtk, &k, g_pso_mtk_building); }
|
||||
os_unfair_lock_unlock(&g_pso_mtk_lock);
|
||||
if (ps) return ps == NSNull.null || ps == g_pso_mtk_building ? nil : ps;
|
||||
id ps = hm_get_id(&g_pso_mtk, &k);
|
||||
if (ps) return ps == NSNull.null ? nil : ps;
|
||||
MTLRenderPipelineDescriptor *d = pso_desc(&k, ms, fs, nil, 0);
|
||||
MTLMeshRenderPipelineDescriptor *m = [MTLMeshRenderPipelineDescriptor new];
|
||||
m.meshFunction = ms->fn; m.fragmentFunction = d.fragmentFunction ?: mtk_nop_fragment(); m.maxTotalThreadsPerMeshThreadgroup = ms->mesh_threads;
|
||||
@@ -579,14 +576,11 @@ static id<MTLRenderPipelineState> mtk_pso(NvProg *raster) {
|
||||
m.rasterSampleCount = d.rasterSampleCount; m.alphaToCoverageEnabled = d.alphaToCoverageEnabled;
|
||||
for (int i = 0; i < 8; i++) m.colorAttachments[i] = d.colorAttachments[i];
|
||||
m.depthAttachmentPixelFormat = d.depthAttachmentPixelFormat; m.stencilAttachmentPixelFormat = d.stencilAttachmentPixelFormat;
|
||||
const char *tk = ts ? ts->key : "-", *mk = ms->key, *fk = fs ? fs->key : "-"; pso_key kk = k;
|
||||
dispatch_async(pp_bg_queue(), ^{
|
||||
NSError *e = nil; uint64_t t0 = bp_now();
|
||||
id<MTLRenderPipelineState> p = [g_dev newRenderPipelineStateWithMeshDescriptor:m options:MTLPipelineOptionNone reflection:nil error:&e];
|
||||
MLOG("%stask / mesh pipeline: task %s mesh %s fragment %s, %.1f ms in the background%s%s", p ? "" : "[RED] ", tk, mk, fk, (bp_now() - t0) / 1e6, p ? "" : ": ", p ? "" : e.localizedDescription.UTF8String);
|
||||
os_unfair_lock_lock(&g_pso_mtk_lock); hm_put_id(&g_pso_mtk, &kk, p ?: NSNull.null); os_unfair_lock_unlock(&g_pso_mtk_lock);
|
||||
});
|
||||
return nil;
|
||||
NSError *e = nil; uint64_t t0 = bp_now();
|
||||
id<MTLRenderPipelineState> p = [g_dev newRenderPipelineStateWithMeshDescriptor:m options:MTLPipelineOptionNone reflection:nil error:&e];
|
||||
MLOG("%stask / mesh pipeline: task %s mesh %s fragment %s, %.1f ms%s%s", p ? "" : "[RED] ", ts ? ts->key : "-", ms->key, fs ? fs->key : "-", (bp_now() - t0) / 1e6, p ? "" : ": ", p ? "" : e.localizedDescription.UTF8String);
|
||||
hm_put_id(&g_pso_mtk, &k, p ?: NSNull.null);
|
||||
return p;
|
||||
}
|
||||
static void mtk_encode(id<MTLRenderCommandEncoder> en_) {
|
||||
id<MTL4RenderCommandEncoder> en = (id<MTL4RenderCommandEncoder>)en_; NvShader *ts = g_mtk.ts, *ms = g_mtk.ms;
|
||||
|
||||
@@ -43,6 +43,7 @@ void mtl_sub_event(volatile uint32_t *val, uint32_t mode, uint32_t v); // Writ
|
||||
void mtl_sub_counter(uint64_t addr, uint32_t type); // Write the counter record after completion
|
||||
uint64_t mtl_sub_commit(void);
|
||||
|
||||
uint64_t mtl_completed_fence(void); // Completed physical submissions, including CPU-visible post effects
|
||||
uint64_t mtl_last_fence(void); // Fence value of the most recent submit (0 = never submitted)
|
||||
int mtl_wait(uint64_t fence, uint64_t timeout_ns); // Returns 1 when the GPU has completed up to fence, 0 on timeout
|
||||
int mtl_wait_acq(uint64_t fence, uint64_t timeout_ns); // the same for a sync WindowAcquireTexture handed out (its own line in the wait ledger, DM_NVN_WAITS)
|
||||
|
||||
+321
-44
@@ -18,6 +18,7 @@
|
||||
#include <os/proc.h> // os_proc_available_memory: for the memory readout line
|
||||
#endif
|
||||
#include "nvn_mtl.h"
|
||||
#include "nvn_queue.h"
|
||||
#include <mach/mach.h>
|
||||
#include "nvn_obj.h"
|
||||
#include "../tex/nvn_fmt_mtl.h"
|
||||
@@ -870,33 +871,191 @@ typedef struct seg_clk seg_clk; static seg_clk *g_sclk; static void seg_clk_put(
|
||||
// second field), so after one clear the two compare equal and later conditional clears of that target are skipped. The host used to ignore the condition and write the time
|
||||
// into both fields, so every clear ran: the first tile-lighting round, the half-resolution scene depth its light volumes test against and the light accumulation were cleared
|
||||
// before the composite read them, and the 3D scene came out black.
|
||||
// Metal has no predication, so the condition is evaluated here at replay, on the CPU, from the records in memory. A report replayed earlier in this submission is not written yet
|
||||
// Metal has no predication, so the condition is evaluated here at replay, on the CPU, from the records in memory. A report in an earlier unfinished GPU prefix is not written yet
|
||||
// (that happens when the GPU completes): a timestamp one counts with its known counter 0; a samples-passed result (an occlusion query, written from the visibility buffers) is
|
||||
// unknown, and a condition on it keeps drawing, as before (occlusion culling only saves work). Inside a block evaluated false, draws and clears are dropped
|
||||
static int g_rc_skip; // a render-enable block evaluated false is active
|
||||
// Neither table may drop an entry: a timestamp report forgotten leaves the condition reading the 1 the CPU wrote, so the clear runs again. They held 256 reports a submission of both kinds, and Splatoon Raiders' 285 ink
|
||||
// queries a frame came first: every conditional clear after them ran, and the lit scene was wiped before the composite read it (a black screen with only the dialogue on it). Now only timestamps are kept per submission, and both tables grow
|
||||
static uint64_t *g_rc_pend; static uint32_t g_rc_npend, g_rc_pcap; // timestamp reports replayed in this submission: their counter is 0, though memory does not show it yet
|
||||
static uint64_t *g_rc_occ; static uint32_t g_rc_ocap, g_rc_on; // addresses ever written by a non-timestamp report (open addressing, a power of two): conditions on them keep drawing
|
||||
static int rc_occ_has(uint64_t a) { if (!g_rc_ocap) return 0; for (uint32_t i = (uint32_t)(a >> 4) & (g_rc_ocap - 1);; i = (i + 1) & (g_rc_ocap - 1)) { if (g_rc_occ[i] == a) return 1; if (!g_rc_occ[i]) return 0; } }
|
||||
static void rc_occ_add(uint64_t a) {
|
||||
if (rc_occ_has(a)) return;
|
||||
if ((g_rc_on + 1) * 2 > g_rc_ocap) { uint32_t oc = g_rc_ocap, nc = oc ? oc * 2 : 4096; uint64_t *old = g_rc_occ, *t = calloc(nc, 8); if (!t) MDIE("no memory for the query report table");
|
||||
for (uint32_t k = 0; k < oc; k++) if (old[k]) { uint32_t i = (uint32_t)(old[k] >> 4) & (nc - 1); while (t[i]) i = (i + 1) & (nc - 1); t[i] = old[k]; }
|
||||
g_rc_occ = t; g_rc_ocap = nc; free(old); }
|
||||
uint32_t i = (uint32_t)(a >> 4) & (g_rc_ocap - 1); while (g_rc_occ[i]) i = (i + 1) & (g_rc_ocap - 1);
|
||||
g_rc_occ[i] = a; g_rc_on++;
|
||||
static int g_rc_skip; // logical queue state: a render-enable block evaluated false is active
|
||||
// Latest command-ordered writer of each report counter. Completed reports are read
|
||||
// from memory, so CPU rewrites remain visible. Unfinished queries stay unknown;
|
||||
// timestamp counters and explicit writes can supply known bytes before completion.
|
||||
// Address lookup is constant-time. The dirty list stamps only this prefix's writers,
|
||||
// and the page index keeps unrelated buffer updates out of the report table.
|
||||
typedef struct rc_report {
|
||||
uint64_t addr, fence, value, report_fence, gpu_epoch;
|
||||
uint8_t known, dirty, readable, reported, report_dirty, unreliable, gpu_domain, opaque_unreliable, opaque_later, conservative;
|
||||
struct rc_report *page_next, *dirty_next;
|
||||
} rc_report;
|
||||
static nvn_hmap g_rc_reports={.klen=8}, g_rc_pages={.klen=8};
|
||||
static uint64_t *g_rc_page_order; static uint32_t g_rc_page_n, g_rc_page_cap;
|
||||
static uint32_t rc_page_lower(uint64_t page) {
|
||||
uint32_t lo=0, hi=g_rc_page_n;
|
||||
while (lo<hi) { uint32_t mid=lo+(hi-lo)/2; if (g_rc_page_order[mid]<page) lo=mid+1; else hi=mid; }
|
||||
return lo;
|
||||
}
|
||||
static void rc_note(uint64_t a, int kind) {
|
||||
if (kind == 2) { rc_occ_add(a); return; } // rc_value asks this table first
|
||||
for (uint32_t i = 0; i < g_rc_npend; i++) if (g_rc_pend[i] == a) return;
|
||||
if (g_rc_npend == g_rc_pcap) { uint32_t nc = g_rc_pcap ? g_rc_pcap * 2 : 256; uint64_t *t = realloc(g_rc_pend, (size_t)nc * 8); if (!t) MDIE("no memory for the timestamp report table"); g_rc_pend = t; g_rc_pcap = nc; }
|
||||
g_rc_pend[g_rc_npend++] = a;
|
||||
static void rc_page_add(uint64_t page) {
|
||||
uint32_t at=rc_page_lower(page);
|
||||
if (g_rc_page_n==g_rc_page_cap) {
|
||||
uint32_t cap=g_rc_page_cap ? g_rc_page_cap*2 : 64;
|
||||
uint64_t *p=realloc(g_rc_page_order,(size_t)cap*sizeof *p);
|
||||
if (!p) MDIE("no memory for the report page index");
|
||||
g_rc_page_order=p; g_rc_page_cap=cap;
|
||||
}
|
||||
memmove(g_rc_page_order+at+1,g_rc_page_order+at,(g_rc_page_n-at)*sizeof *g_rc_page_order);
|
||||
g_rc_page_order[at]=page; g_rc_page_n++;
|
||||
}
|
||||
static int rc_value(uint64_t a, uint64_t *v) { // 0 = unknown at encode time
|
||||
if (rc_occ_has(a)) return 0;
|
||||
for (uint32_t i = g_rc_npend; i-- > 0;) if (g_rc_pend[i] == a) { *v = 0; return 1; }
|
||||
*v = *(const volatile uint64_t *)a; return 1;
|
||||
static rc_report *g_rc_dirty;
|
||||
static uint64_t g_rc_gpu_epoch, g_rc_gpu_fence;
|
||||
static int g_rc_gpu_dirty;
|
||||
// Published after the CPU post effects land, before an event can wake a CPU writer.
|
||||
// g_done is later than event publication and would briefly hide such a writer.
|
||||
static _Atomic uint64_t g_rc_complete;
|
||||
static rc_report *rc_find(uint64_t addr) { return nvn_hm_get(&g_rc_reports,&addr); }
|
||||
static void rc_touch(rc_report *r) {
|
||||
r->fence=0; r->gpu_epoch=g_rc_gpu_epoch;
|
||||
if (!r->dirty) { r->dirty=1; r->dirty_next=g_rc_dirty; g_rc_dirty=r; }
|
||||
}
|
||||
static void rc_commit(uint64_t fence) {
|
||||
for (rc_report *r=g_rc_dirty,*next;r;r=next) {
|
||||
next=r->dirty_next; r->fence=fence; r->dirty=0; r->dirty_next=NULL;
|
||||
if (r->report_dirty) { r->report_fence=fence; r->report_dirty=0; }
|
||||
}
|
||||
g_rc_dirty=NULL;
|
||||
if (g_rc_gpu_dirty) { g_rc_gpu_fence=fence; g_rc_gpu_dirty=0; }
|
||||
}
|
||||
static void rc_forget(void) {
|
||||
g_rc_dirty=NULL; g_rc_gpu_epoch=g_rc_gpu_fence=0; g_rc_gpu_dirty=0;
|
||||
nvn_hm_clear(&g_rc_pages,NULL); nvn_hm_clear(&g_rc_reports,free);
|
||||
free(g_rc_page_order); g_rc_page_order=NULL; g_rc_page_n=g_rc_page_cap=0;
|
||||
}
|
||||
static rc_report *rc_ensure(uint64_t addr) {
|
||||
rc_report *r=rc_find(addr);
|
||||
if (!r) {
|
||||
r=calloc(1,sizeof *r); if (!r) MDIE("no memory for the report table");
|
||||
r->addr=addr; r->readable=1; r->gpu_epoch=g_rc_gpu_epoch; nvn_hm_put(&g_rc_reports,&addr,r);
|
||||
uint64_t page=addr>>12; r->page_next=nvn_hm_get(&g_rc_pages,&page);
|
||||
if (!r->page_next) rc_page_add(page);
|
||||
nvn_hm_put(&g_rc_pages,&page,r);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
static void rc_query_operand(rc_report *r) {
|
||||
if (r->gpu_domain) return;
|
||||
r->gpu_domain=1;
|
||||
// An earlier opaque writer may have raced this timestamp before the address
|
||||
// first participated in a query comparison. Do not expose its CPU-post bytes.
|
||||
if (r->opaque_later) { r->known=0; r->opaque_later=0; }
|
||||
if (r->opaque_unreliable) r->unreliable=1;
|
||||
}
|
||||
static void rc_note(uint64_t addr, int kind) {
|
||||
rc_report *r=rc_ensure(addr);
|
||||
if (kind!=1) r->conservative=1; // retain main's unavailable-query fallback; completed-query culling is a separate change
|
||||
// A condition compares adjacent 16-byte records. Either operand can be the
|
||||
// query; track its unreported neighbor before later explicit buffer writers.
|
||||
// Existing entries keep their own report type, pending fence and known bytes.
|
||||
if (kind==2) { rc_query_operand(r); if (addr>=16) rc_query_operand(rc_ensure(addr-16)); rc_query_operand(rc_ensure(addr+16)); }
|
||||
// Only timestamp and samples-passed reports have implemented counter values.
|
||||
// Other counter kinds retain the conservative fallback after their placeholder lands.
|
||||
r->value=0; r->known=kind==1 ? 255 : 0; r->readable=kind!=3;
|
||||
r->reported=r->report_dirty=1; r->report_fence=0; r->unreliable=r->opaque_unreliable=r->opaque_later=0; rc_touch(r);
|
||||
}
|
||||
static int rc_gpu_unknown(rc_report *r, uint64_t done) {
|
||||
if (!r->gpu_domain || r->gpu_epoch==g_rc_gpu_epoch) return 0;
|
||||
// An unbounded shader writer may race a CPU-landed query. A fresh report or
|
||||
// explicit full write can establish that counter again. Unreported reference
|
||||
// words have no deferred CPU report, so they become readable after the writer.
|
||||
if (r->reported || g_rc_gpu_dirty || g_rc_gpu_fence>done) return 1;
|
||||
r->gpu_epoch=g_rc_gpu_epoch; return 0;
|
||||
}
|
||||
static int rc_value(uint64_t addr, uint64_t *v) { // 0 = unknown at encode time
|
||||
rc_report *r=rc_find(addr);
|
||||
uint64_t done=atomic_load_explicit(&g_rc_complete,memory_order_acquire);
|
||||
if (r) {
|
||||
if (r->conservative) return 0;
|
||||
if (rc_gpu_unknown(r,done)) return 0;
|
||||
if (r->dirty || r->fence>done) { *v=r->value; return r->known==255; }
|
||||
if (!r->readable || r->unreliable) return 0;
|
||||
}
|
||||
*v=*(const volatile uint64_t *)addr; return 1;
|
||||
}
|
||||
// Counter records need not share a page with the buffer write. Include the previous
|
||||
// seven bytes so even an unaligned eight-byte counter crossing a page is covered.
|
||||
static rc_report *rc_containing(uint64_t addr) {
|
||||
uint64_t first=(addr>7 ? addr-7 : 0)>>12, last=addr>>12;
|
||||
for (uint64_t page=first;page<=last;page++)
|
||||
for (rc_report *r=nvn_hm_get(&g_rc_pages,&page);r;r=r->page_next)
|
||||
if (addr>=r->addr && addr-r->addr<8) return r;
|
||||
return NULL;
|
||||
}
|
||||
static uint8_t rc_source(uint64_t a, unsigned n, uint8_t *out, int *unreliable);
|
||||
static void rc_overwrite(rc_report *r, uint64_t dst, uint64_t n, const void *data, unsigned period, uint64_t src, uint64_t done, int opaque) {
|
||||
uint64_t lo=MAX(dst,r->addr), hi=MIN(dst+n,r->addr+8);
|
||||
if (hi<=lo) return;
|
||||
if (opaque && !r->gpu_domain) {
|
||||
// Keep ordinary timestamp forwarding unchanged, but retain this history
|
||||
// in case a later query makes the address a comparison operand.
|
||||
if (r->reported) r->opaque_unreliable=r->opaque_later=1;
|
||||
return;
|
||||
}
|
||||
int report_pending=r->reported && (r->report_dirty || r->report_fence>done);
|
||||
if (r->opaque_later) { r->known=0; r->opaque_later=0; }
|
||||
if (r->opaque_unreliable) r->unreliable=1;
|
||||
if ((r->reported && r->gpu_epoch!=g_rc_gpu_epoch) || rc_gpu_unknown(r,done)) { r->known=0; if (r->reported) r->unreliable=1; }
|
||||
if (opaque) {
|
||||
if (report_pending) r->unreliable=1;
|
||||
r->known=0; rc_touch(r); return;
|
||||
}
|
||||
// The preceding writer has landed: keep unaffected bytes from the current CPU
|
||||
// value, including a legal CPU rewrite after that writer completed.
|
||||
if (!r->dirty && r->fence<=done) {
|
||||
if (r->readable && !r->unreliable && !rc_gpu_unknown(r,done)) { r->value=*(const volatile uint64_t *)r->addr; r->known=255; }
|
||||
else r->known=0;
|
||||
}
|
||||
int unreliable=report_pending;
|
||||
unsigned at=(unsigned)(lo-r->addr), bytes=(unsigned)(hi-lo);
|
||||
if (data) {
|
||||
for (unsigned b=0;b<bytes;b++) {
|
||||
uint64_t off=lo+b-dst;
|
||||
((uint8_t *)&r->value)[at+b]=((const uint8_t *)data)[period ? off%period : off];
|
||||
r->known|=(uint8_t)(1u<<(at+b));
|
||||
}
|
||||
} else {
|
||||
uint8_t value[8], known=rc_source(src+lo-dst,bytes,value,&unreliable), mask=(uint8_t)(((1u<<bytes)-1)<<at);
|
||||
for (unsigned b=0;b<bytes;b++) if (known>>b&1) ((uint8_t *)&r->value)[at+b]=value[b];
|
||||
r->known=(r->known&~mask)|(known<<at);
|
||||
}
|
||||
if (r->known==255) r->readable=1;
|
||||
// Query reports still land on the CPU after GPU execution. A following GPU
|
||||
// overwrite/copy can therefore leave unreliable final bytes. Preserve the
|
||||
// existing conservative fallback for this unsupported ordering pattern;
|
||||
// pending command-known values remain valid, but completed memory is not used.
|
||||
if (unreliable) r->unreliable=1;
|
||||
else if (at==0 && bytes==8) r->unreliable=r->opaque_unreliable=r->opaque_later=0;
|
||||
rc_touch(r);
|
||||
}
|
||||
// A later explicit buffer write replaces the report's command-ordered knowledge,
|
||||
// including partial writes. Its bytes stay live until that writer completes.
|
||||
// This does not make CPU-landed query reports ordered GPU sources: arbitrary
|
||||
// shader-produced predicates and GPU reads of an unfinished report remain unsupported.
|
||||
static void rc_change(uint64_t dst, uint64_t n, const void *data, unsigned period, uint64_t src, int opaque) {
|
||||
if (!g_rc_reports.n || !n) return;
|
||||
uint64_t done=atomic_load_explicit(&g_rc_complete,memory_order_acquire);
|
||||
uint64_t first=(dst>7 ? dst-7 : 0)>>12, last=(dst+n-1)>>12;
|
||||
// Large writable bindings are common on every draw. Search the recorded page
|
||||
// addresses, then visit only intersecting pages; scanning every report made
|
||||
// unrelated storage buffers cost several milliseconds per frame.
|
||||
if (last-first>=8) {
|
||||
for (uint32_t i=rc_page_lower(first);i<g_rc_page_n && g_rc_page_order[i]<=last;i++)
|
||||
for (rc_report *r=nvn_hm_get(&g_rc_pages,&g_rc_page_order[i]);r;r=r->page_next) rc_overwrite(r,dst,n,data,period,src,done,opaque);
|
||||
} else {
|
||||
for (uint64_t page=first;page<=last;page++)
|
||||
for (rc_report *r=nvn_hm_get(&g_rc_pages,&page);r;r=r->page_next) rc_overwrite(r,dst,n,data,period,src,done,opaque);
|
||||
}
|
||||
}
|
||||
static void rc_write(uint64_t dst, uint64_t n, const void *data, unsigned period) { rc_change(dst,n,data,period,0,0); }
|
||||
static void rc_copy(uint64_t src, uint64_t dst, uint64_t n) { if (src!=dst) rc_change(dst,n,NULL,0,src,0); }
|
||||
static void rc_gpu_write(uint64_t dst, uint64_t n) {
|
||||
if (!n) { g_rc_gpu_epoch++; g_rc_gpu_dirty=1; }
|
||||
else rc_change(dst,n,NULL,0,0,1);
|
||||
}
|
||||
// ---------- Occlusion queries (NVN_COUNTER_TYPE_SAMPLES_PASSED) ----------
|
||||
// NVN semantics: samples passed is a cumulative counter on the queue - ResetCounter zeroes it, every draw afterwards adds to it, and ReportCounter writes out the cumulative value at that moment (+ timestamp) when the GPU completes.
|
||||
@@ -969,6 +1128,7 @@ enum { SBW_GPU = 1, SBW_REPORT = 2 };
|
||||
static uint32_t g_sbw_gen; // bumped by every write noted that this submission's shadows must respect (a cached shadow made before it is checked again)
|
||||
static void drw_note(uint64_t lo, uint64_t n); // the writes since the last drain (below g_wr_epoch)
|
||||
static void sbw_note(uint64_t lo, uint64_t n, int src) {
|
||||
if (src==SBW_GPU) rc_gpu_write(lo,n);
|
||||
if (src == SBW_GPU) { g_sbw_gen++; drw_note(lo, n); }
|
||||
if (!n) { if (src == SBW_GPU) g_sbw_over = 1; return; }
|
||||
uint64_t hi = lo + n;
|
||||
@@ -1077,7 +1237,7 @@ void mtl_prepare(void) {
|
||||
static void sub_cut_begin(void); static void ts_sub_begin(void), ts_boundary(void); static int ts_on(void);
|
||||
static void gmem_commit_patch(void); // the raw pool table words of the arguments encoded so far follow the pools (gmem_slot_note)
|
||||
void mtl_sub_begin(void) {
|
||||
mtl_init(); g_sub_serial++; g_seg = 0; seg_clk_put(g_sclk); g_sclk = NULL; g_rc_npend = 0; g_rc_skip = 0;
|
||||
mtl_init(); g_sub_serial++; g_seg = 0; seg_clk_put(g_sclk); g_sclk = NULL;
|
||||
sub_cut_begin();
|
||||
defer_drain();
|
||||
defer_reset();
|
||||
@@ -1389,6 +1549,7 @@ static id<MTL4ComputeCommandEncoder> blit(void) {
|
||||
}
|
||||
|
||||
void mtl_sub_copy(uint64_t src, uint64_t dst, uint64_t n) {
|
||||
rc_copy(src,dst,n);
|
||||
pend_add(dst, n, 2); g_mdx_epoch++;
|
||||
void *sb, *db; uint64_t so, dof;
|
||||
if (!mtl_addr(src, n, &sb, &so) || !mtl_addr(dst, n, &db, &dof))
|
||||
@@ -1611,6 +1772,30 @@ static int pend_since(uint64_t a, uint64_t b, int since, int *out) {
|
||||
return n;
|
||||
}
|
||||
int nvn_host_readable(uint64_t a, uint64_t n); // hle_nvn.c: guest memory and sparse pools
|
||||
// Only read copy sources that the command stream proves, or memory with no
|
||||
// unfinished GPU writer. Never use stale mapped bytes to replace an unknown copy.
|
||||
static uint8_t rc_source(uint64_t a, unsigned n, uint8_t *out, int *unreliable) {
|
||||
uint8_t known=0; uint64_t done=atomic_load_explicit(&g_rc_complete,memory_order_acquire);
|
||||
for (unsigned b=0;b<n;b++) {
|
||||
uint64_t p=a+b; rc_report *r=rc_containing(p);
|
||||
if (r) {
|
||||
unsigned off=(unsigned)(p-r->addr);
|
||||
if (r->unreliable || r->opaque_unreliable || (r->reported && (r->report_dirty || r->report_fence>done))) *unreliable=1;
|
||||
if (r->opaque_later) continue;
|
||||
if ((r->reported && r->gpu_epoch!=g_rc_gpu_epoch) || rc_gpu_unknown(r,done)) { *unreliable=1; continue; }
|
||||
if (!r->dirty && r->fence<=done) {
|
||||
if (r->readable && !r->unreliable && !r->opaque_unreliable) { out[b]=*(const volatile uint8_t *)p; known|=(uint8_t)(1u<<b); }
|
||||
} else if (r->known>>off&1) { out[b]=((const uint8_t *)&r->value)[off]; known|=(uint8_t)(1u<<b); }
|
||||
continue;
|
||||
}
|
||||
int kind, page=sbw_slot(p>>12,0);
|
||||
if (pend_read(p,1,&out[b],&kind)) known|=(uint8_t)(1u<<b);
|
||||
else if (!pend_hits(p,1) && !g_sbw_over && !sbw_hits(p,p+1) && (page<0 || !g_sbwp[page].src) && !gw_live_in(g_gw,p,p+1) && nvn_host_readable(p,1)) {
|
||||
out[b]=*(const uint8_t *)p; known|=(uint8_t)(1u<<b);
|
||||
}
|
||||
}
|
||||
return known;
|
||||
}
|
||||
// Shadows made from memory, per range. One is kept while no write is queued after it (the draws after an update bind the same block again and again); the next one for the same range starts
|
||||
// from it and lays over only the writes queued since (the game rewrites one block hundreds of times a submission). A range read whole from memory once is not read from memory again in the submission
|
||||
enum { UBP_CACHE = 16, UBP_MAX_BYTES = 65536 };
|
||||
@@ -1662,6 +1847,7 @@ void mtl_ubp_stats(uint64_t *made, uint64_t *reused, uint64_t *refused) { *made
|
||||
void mtl_ubp_why(uint64_t w[5]) { memcpy(w, g_ubp_why, sizeof g_ubp_why); }
|
||||
void mtl_sub_update(const void *data, uint64_t dst, uint64_t n) {
|
||||
if (!n) return;
|
||||
rc_write(dst,n,data,0);
|
||||
int pi = pend_add(dst, n, 1);
|
||||
void *db; uint64_t dof;
|
||||
if (!mtl_addr(dst, n, &db, &dof)) MDIE("uniform update target is in no memory pool dst=%#llx n=%#llx", (unsigned long long)dst, (unsigned long long)n);
|
||||
@@ -1689,6 +1875,7 @@ void mtl_sub_update(const void *data, uint64_t dst, uint64_t n) {
|
||||
// In-order buffer fill within the submission: all four bytes equal → fillBuffer; otherwise copied in chunks from a 64 KiB pattern buffer
|
||||
void mtl_sub_fill(uint64_t dst, uint64_t n, uint32_t value) {
|
||||
if (!n) return;
|
||||
rc_write(dst,n,&value,4);
|
||||
pend_add(dst, n, 3); g_mdx_epoch++;
|
||||
void *db; uint64_t dof;
|
||||
if (!mtl_addr(dst, n, &db, &dof)) MDIE("buffer fill address is in no memory pool dst=%#llx n=%#llx", (unsigned long long)dst, (unsigned long long)n);
|
||||
@@ -1705,7 +1892,7 @@ static void post(post_op o) {
|
||||
g_post[g_npost++] = o;
|
||||
}
|
||||
void mtl_sub_event(volatile uint32_t *val, uint32_t mode, uint32_t v) { post((post_op){1, val, mode, v, 0, 0, NULL}); }
|
||||
static int seg_ts(void); static void ts_clk(void);
|
||||
static void ts_clk(void);
|
||||
void mtl_sub_counter(uint64_t addr, uint32_t type) { sbw_note(addr, 16, SBW_REPORT); post((post_op){2, NULL, 0, 0, addr, type, NULL, g_seg}); ts_clk(); }
|
||||
void mtl_counter_stats(uint64_t rep[32], uint64_t rst[32]) { memcpy(rep, g_cnt_report, sizeof g_cnt_report); memcpy(rst, g_cnt_reset, sizeof g_cnt_reset); }
|
||||
|
||||
@@ -1911,7 +2098,7 @@ static void post_run(post_rec *r, uint64_t c0, uint64_t c1) {
|
||||
@autoreleasepool {
|
||||
int n = r->n; post_op *ops = r->ops; seg_clk *sc = r->sc; uint32_t seg_last = r->seg_last;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (ops[i].kind == 1) { if (ops[i].mode == 1) *ops[i].val += ops[i].v; else *ops[i].val = ops[i].v; }
|
||||
if (ops[i].kind == 1) continue; // A terminal release publishes after every earlier GPU write has landed.
|
||||
else if (ops[i].kind == 3) { // Samples passed: the sum of all slots since the reset
|
||||
vis_list *l = ops[i].vis; uint64_t sum = 0;
|
||||
for (int k = 0; k < l->n; k++) { sum += ((const uint64_t *)((__bridge id<MTLBuffer>)l->s[k].buf).contents)[l->s[k].slot]; CFRelease(l->s[k].buf); }
|
||||
@@ -1920,6 +2107,13 @@ static void post_run(post_rec *r, uint64_t c0, uint64_t c1) {
|
||||
else if (ops[i].kind == 4) mirror_rb_land(ops[i].vis);
|
||||
else { uint64_t t = rep_ticks(&ops[i], sc, seg_last, c0, c1), rec[2] = {(ops[i].type == 0 || ops[i].type == 0x10) && !DM_GAME_RENDER_COND ? t : 0, t}; memcpy((void *)ops[i].addr, rec, sizeof rec); } // render_cond: a timestamp report's counter field is 0, as on the GPU (see rc_value)
|
||||
}
|
||||
// Forwarded counter values expire once their CPU-visible reports have landed.
|
||||
// This precedes event publication so a released CPU writer is never hidden by stale knowledge.
|
||||
uint64_t completed=atomic_load_explicit(&g_rc_complete,memory_order_relaxed);
|
||||
while(completed<r->fence && !atomic_compare_exchange_weak_explicit(&g_rc_complete,&completed,r->fence,memory_order_release,memory_order_relaxed)) {}
|
||||
// Pass teardown can append mirror readbacks after the recorded signal. They are
|
||||
// preceding GPU writes, and must be CPU-visible before this prefix releases its event.
|
||||
for (int i=0;i<n;i++) if(ops[i].kind==1) nvn_event_publish_gpu(ops[i].val,ops[i].mode,ops[i].v,r->fence);
|
||||
free(ops); seg_clk_put(sc); r->ops = NULL; r->sc = NULL;
|
||||
atomic_store(&r->claimed, 1);
|
||||
pthread_mutex_unlock(&g_post_mu);
|
||||
@@ -1940,9 +2134,11 @@ static void post_complete(uint64_t fence, uint64_t c0, uint64_t c1) {
|
||||
post_run(r, f == fence && c1 ? c0 : seg_ts() ? start : 0, f == fence && c1 ? c1 : seg_ts() ? now : 0);
|
||||
}
|
||||
pthread_mutex_lock(&g_mu); if (fence > g_done) g_done = fence; pthread_cond_broadcast(&g_cv); pthread_mutex_unlock(&g_mu);
|
||||
nvn_queue_gpu_progress();
|
||||
}
|
||||
static _Atomic int g_seg_inflight; // main command buffers committed and not reported back yet (sub_cut)
|
||||
static void rt_preserve_bound(void);
|
||||
static void queue_program_preserve(void);
|
||||
uint64_t mtl_sub_commit(void) {
|
||||
lc_land(); // clears still waiting (the command list ends with them)
|
||||
defer_fallback(); // Deferred merged pass: at the end of the submission there are still P draws not replayed (the normal path never gets here)
|
||||
@@ -1954,8 +2150,9 @@ uint64_t mtl_sub_commit(void) {
|
||||
g_cut_copy = 0;
|
||||
treg_finish_submission(); // Late descriptor views retire behind this submission's fence.
|
||||
rt_preserve_bound(); // The game may reuse completed command memory; queue bindings must not point into its texture snapshots.
|
||||
queue_program_preserve(); // Submitted metadata may retire while these programs remain bound.
|
||||
uint64_t fence = ++g_fence;
|
||||
gw_commit(fence);
|
||||
gw_commit(fence); rc_commit(fence);
|
||||
if (g_vis_ring_i >= 0) g_vis_ring[g_vis_ring_i].fence = fence;
|
||||
// CPU-visible effects after completion: copy the op table into the callback
|
||||
int n = g_npost; post_op *ops = n ? malloc(n * sizeof *ops) : NULL; post_rec *pr = &g_postr[fence % POST_RING];
|
||||
@@ -2000,6 +2197,7 @@ uint64_t mtl_sub_commit(void) {
|
||||
return fence;
|
||||
}
|
||||
|
||||
uint64_t mtl_completed_fence(void) { return atomic_load_explicit(&g_done,memory_order_acquire); }
|
||||
uint64_t mtl_last_fence(void) { return g_fence; }
|
||||
int mtl_last_commit_error(void) { return atomic_load(&g_last_commit_error); }
|
||||
|
||||
@@ -2155,9 +2353,14 @@ static void image_desc_drop_pool(const void *pool) { // caller holds g_smu
|
||||
} else i++;
|
||||
}
|
||||
}
|
||||
// Deferred command descriptors and persistent bindings retain a texture serial
|
||||
// independently of the guest descriptor and the bounded recently-finalized cache.
|
||||
typedef struct { unsigned refs; void *object; } tex_pin;
|
||||
static nvn_hmap g_tex_pins={.klen=8}, g_tex_pin_objects={.klen=sizeof(uintptr_t)};
|
||||
static int tex_object_pinned(id o) { uintptr_t key=(uintptr_t)(__bridge void *)o; return o && nvn_hm_get(&g_tex_pin_objects,&key)!=NULL; }
|
||||
static CFMutableSetRef g_alias_set; // Textures in the sharing table (non-owning; used to ask "is this shared")
|
||||
static uint64_t g_alias_evicted; // shared textures evicted on pool Finalize so far (for the memory report)
|
||||
static int alias_has(id o) { return g_alias_set && o && CFSetContainsValue(g_alias_set, (__bridge const void *)o); }
|
||||
static int alias_has(id o) { return tex_object_pinned(o) || (g_alias_set && o && CFSetContainsValue(g_alias_set, (__bridge const void *)o)); }
|
||||
static void retire_wait(id o) { // defer_drain: a serial entry still holds what it retires. Caller holds g_smu
|
||||
uintptr_t k = (uintptr_t)(__bridge void *)o;
|
||||
if (!nvn_hm_get(&g_retire_held, &k)) nvn_hm_put(&g_retire_held, &k, (void *)CFBridgingRetain(o));
|
||||
@@ -2265,8 +2468,34 @@ void mtl_tex_init(const tex_t *t) {
|
||||
pthread_mutex_unlock(&g_smu);
|
||||
}
|
||||
static void obj_drop(id o) { if (alias_has(o)) defer_obj_unref(o); else defer_obj_release(o); } // caller holds g_smu
|
||||
static void tex_pin_set(tex_pin *pin,id object) { // g_smu held
|
||||
id old=(__bridge id)pin->object; if(old==object) return;
|
||||
if(old) {
|
||||
uintptr_t key=(uintptr_t)pin->object, count=(uintptr_t)nvn_hm_get(&g_tex_pin_objects,&key);
|
||||
if(count>1) nvn_hm_put(&g_tex_pin_objects,&key,(void *)(count-1)); else nvn_hm_del(&g_tex_pin_objects,&key);
|
||||
held_add(pin->object,-1); if(alias_has(old) || serial_table_holds((__bridge void *)old)) defer_obj_unref(old); else defer_obj_release(old); CFRelease(pin->object); pin->object=NULL;
|
||||
}
|
||||
if(object) {
|
||||
pin->object=(void *)CFBridgingRetain(object); uintptr_t key=(uintptr_t)pin->object;
|
||||
uintptr_t count=(uintptr_t)nvn_hm_get(&g_tex_pin_objects,&key);
|
||||
nvn_hm_put(&g_tex_pin_objects,&key,(void *)(count+1)); held_add(pin->object,1);
|
||||
}
|
||||
}
|
||||
void mtl_tex_pin(uint64_t serial) {
|
||||
if(!serial) return; pthread_mutex_lock(&g_smu);
|
||||
tex_pin *pin=nvn_hm_get(&g_tex_pins,&serial);
|
||||
if(!pin) { pin=calloc(1,sizeof *pin); if(!pin) MDIE("texture retention allocation failed"); nvn_hm_put(&g_tex_pins,&serial,pin); }
|
||||
pin->refs++;
|
||||
if(!pin->object) { id o=hm_get_id(&g_by_serial,&serial); if(!o) o=hm_get_id(&g_ghost,&serial); tex_pin_set(pin,o); }
|
||||
pthread_mutex_unlock(&g_smu);
|
||||
}
|
||||
void mtl_tex_unpin(uint64_t serial) {
|
||||
if(!serial) return; pthread_mutex_lock(&g_smu); tex_pin *pin=nvn_hm_get(&g_tex_pins,&serial);
|
||||
if(pin && !--pin->refs) { nvn_hm_del(&g_tex_pins,&serial); tex_pin_set(pin,nil); free(pin); }
|
||||
pthread_mutex_unlock(&g_smu);
|
||||
}
|
||||
static __unsafe_unretained id tex_get(uint64_t k) {
|
||||
pthread_mutex_lock(&g_smu); __unsafe_unretained id o = hm_get_id(&g_by_serial, &k); if (!o && g_ghost.n) o = hm_get_id(&g_ghost, &k); pthread_mutex_unlock(&g_smu); return o;
|
||||
pthread_mutex_lock(&g_smu); __unsafe_unretained id o = hm_get_id(&g_by_serial, &k); if (!o && g_ghost.n) o = hm_get_id(&g_ghost, &k); if(!o) { tex_pin *pin=nvn_hm_get(&g_tex_pins,&k); if(pin) o=(__bridge id)pin->object; } pthread_mutex_unlock(&g_smu); return o;
|
||||
}
|
||||
static void tex_put(uint64_t k, id o) { // serials from 2^62 up are external textures (mtl_ext_tex), never initialized by the game
|
||||
pthread_mutex_lock(&g_smu);
|
||||
@@ -2279,7 +2508,7 @@ static void tex_put(uint64_t k, id o) { // serials from 2^62 up are external t
|
||||
if (*slot) { id ev = hm_get_id(&g_ghost, slot); if (ev) { ghost_held_add((__bridge void *)ev, -1); obj_drop(ev); } hm_del_id(&g_ghost, slot); ser_note(*slot); } // the evicted serial resolves anew too
|
||||
*slot = k; g_ghost_puts++;
|
||||
}
|
||||
hm_put_id(m, &k, o); ser_note(k);
|
||||
hm_put_id(m, &k, o); tex_pin *pin=nvn_hm_get(&g_tex_pins,&k); if(pin) tex_pin_set(pin,o); ser_note(k);
|
||||
count_add(m == &g_by_serial ? &g_by_serial_held : &g_ghost_held, (__bridge void *)o, 1);
|
||||
pthread_mutex_unlock(&g_smu);
|
||||
}
|
||||
@@ -2533,6 +2762,7 @@ static id<MTLTexture> tex_upgrade(const tex_t *t, id<MTLTexture> asked, MTLTextu
|
||||
nvn_hmap *cnt = j == 0 ? &g_by_serial_held : &g_ghost_held; count_add(cnt, old, -1); count_add(cnt, (__bridge void *)upgraded, 1); // the count moves with the name
|
||||
CFRelease(old); named |= serial == t->serial;
|
||||
}
|
||||
for(uint32_t i=0;i<g_tex_pins.cap;i++) if(g_tex_pins.vals[i]) { tex_pin *pin=g_tex_pins.vals[i]; if(pin->object==(__bridge void *)base) tex_pin_set(pin,upgraded); }
|
||||
for (uint32_t i = 0; i < g_alias.cap; i++) {
|
||||
if (g_alias.vals[i] != (__bridge void *)base) continue;
|
||||
void *old = g_alias.vals[i]; g_alias.vals[i] = (void *)CFBridgingRetain(upgraded); CFRelease(old); shared = 1;
|
||||
@@ -4152,9 +4382,8 @@ static void rr_snap(const p_draw *, const p_draw_idx *);
|
||||
static void rr_reset(void);
|
||||
#endif
|
||||
static id<MTL4RenderCommandEncoder> g_enc;
|
||||
// Segment times without the segments. A report in segment mode takes the GPU start or end of the segment it fell in, and what a game's controller makes of those depends on where the boundaries lie: Ocarina of Time, given each report's own true time, went to its lowest resolution and
|
||||
// frames of 13 and 52 ms in turn. So the boundaries stay every cut_draws() draws, each with a GPU timestamp, whether or not the host commits there (sub_cut): the game reads what it read, and a GPU still busy gets no extra command buffer. The encode thread records its command
|
||||
// buffers and has no such write: with it each boundary stays a commit
|
||||
// Segment timestamps retain the existing GPU boundaries every cut_draws() draws, even when sub_cut keeps the command buffer open.
|
||||
// The encode-thread path keeps its existing feedback-based segment fallback; its exact BOTTOM stamps are recorded by DmRecCB independently of this heap.
|
||||
enum { TS_SLOTS = 4096 }; // the largest timestamp heap Metal makes
|
||||
static uint32_t g_ts_next; static int g_ts_state, g_ts_s0; // state: 0 not tried, 1 on, -1 off; s0: the slot of this submission's first boundary
|
||||
static int ts_on(void) {
|
||||
@@ -5561,7 +5790,27 @@ static __unsafe_unretained NvProg *prog_get(const prog_t *cp) { // Called only
|
||||
if (p->serial) serial_put(p->serial, o);
|
||||
return o;
|
||||
}
|
||||
void mtl_prog_release(prog_t *p) { if (p->serial) serial_del(p->serial); }
|
||||
// A submitted descriptor and a queue binding hold the compiled program by its
|
||||
// immutable initialization serial. Retaining it must not mint serial aliases:
|
||||
// alias churn invalidates texture tables and changes composite-program keys.
|
||||
typedef struct { unsigned refs, retired; } prog_pin;
|
||||
static nvn_hmap g_prog_pins={.klen=8}; // protected by the submission lock
|
||||
void mtl_prog_release(prog_t *p) {
|
||||
if(!p->serial) return;
|
||||
prog_pin *pin=nvn_hm_get(&g_prog_pins,&p->serial);
|
||||
if(pin) pin->retired=1; else serial_del(p->serial);
|
||||
}
|
||||
void mtl_prog_unpin(prog_t *p) {
|
||||
prog_pin *pin=nvn_hm_get(&g_prog_pins,&p->serial);
|
||||
if(pin && !--pin->refs) { nvn_hm_del(&g_prog_pins,&p->serial); if(pin->retired) serial_del(p->serial); free(pin); }
|
||||
}
|
||||
void mtl_prog_snapshot(prog_t *copy,const prog_t *source) {
|
||||
prog_get(source); *copy=*source;
|
||||
if(!source->serial) MDIE("cannot retain a program without an initialization serial");
|
||||
prog_pin *pin=nvn_hm_get(&g_prog_pins,&source->serial);
|
||||
if(!pin) { pin=calloc(1,sizeof *pin); if(!pin) MDIE("program retention allocation failed"); nvn_hm_put(&g_prog_pins,&source->serial,pin); }
|
||||
pin->refs++;
|
||||
}
|
||||
|
||||
// ---------- Descriptor pool: texture ID / sampler ID → object ----------
|
||||
// At registration the whole texture object is snapshotted (NVN semantics: the descriptor has been written into the pool); view: the MTLTexture for that ID (a view or the base texture, held via CFBridgingRetain) and the serial-table / guest-write generations at the time it was obtained
|
||||
@@ -6525,6 +6774,7 @@ static void prog_resolve(void) {
|
||||
}
|
||||
static int g_state_inited;
|
||||
static void state_reset(void) {
|
||||
g_rc_skip=0;
|
||||
g_state_inited = 1;
|
||||
memset(&S, 0, sizeof S);
|
||||
g_pso_dirty = g_dss_dirty = 1;
|
||||
@@ -6537,7 +6787,7 @@ static void state_reset(void) {
|
||||
|
||||
// GPU bindings belong to a queue, including across submissions. FFX/X-2 destroys its launcher's queue before creating a game's: a global S kept freed launcher programs in S.bst,
|
||||
// and X-2's first fragment-only bind dereferenced that stale vertex program in keys_hash. Separate queues also retain their own bindings when submissions alternate (Three Houses).
|
||||
typedef struct queue_state { uint64_t serial; typeof(S) s; typeof(R) r; tex_t rt_tex[9]; struct queue_state *next; } queue_state;
|
||||
typedef struct queue_state { uint64_t serial; typeof(S) s; typeof(R) r; tex_t rt_tex[9]; uint64_t rt_pins[9]; prog_t programs[6]; int rc_skip; struct queue_state *next; } queue_state;
|
||||
static queue_state *g_queue_states, *g_active_queue;
|
||||
// Recording snapshots belong to command memory, not to the queue. Keep only the
|
||||
// bound target descriptions after CPU replay, before this submission can finish
|
||||
@@ -6552,6 +6802,10 @@ static void rt_preserve_bound(void) {
|
||||
source[k] = k == 8 ? R.rt.depth : k < R.rt.n ? R.rt.color[k] : NULL;
|
||||
if (source[k] && source[k] != &owned[k]) pending |= 1u << k;
|
||||
}
|
||||
if (g_active_queue) for(int k=0;k<9;k++) {
|
||||
uint64_t serial=source[k]?source[k]->serial:0, old=g_active_queue->rt_pins[k];
|
||||
if(serial!=old) { mtl_tex_pin(serial); mtl_tex_unpin(old); g_active_queue->rt_pins[k]=serial; }
|
||||
}
|
||||
if (!pending) return;
|
||||
tex_t next[9]; // Read every source first: retained targets can be reordered or aliased.
|
||||
for (int k = 0; k < 9; k++) if (pending & (1u << k)) next[k] = *source[k];
|
||||
@@ -6560,12 +6814,32 @@ static void rt_preserve_bound(void) {
|
||||
if (k == 8) R.rt.depth = &owned[k]; else R.rt.color[k] = &owned[k];
|
||||
}
|
||||
}
|
||||
// Jobs own immutable program descriptors; the queue owns copies of bindings that survive a job.
|
||||
static void queue_program_preserve(void) {
|
||||
queue_state *q=g_active_queue; if(!q) return;
|
||||
const prog_t *bound[6]={S.bst[0],S.bst[1],S.bst[2],S.bst[3],S.bst[4],S.cprog};
|
||||
int changed=0;
|
||||
for(int i=0;i<6;i++) if(bound[i] && ((uintptr_t)bound[i]<(uintptr_t)q->programs || (uintptr_t)bound[i]>=(uintptr_t)(q->programs+6))) changed=1;
|
||||
if(!changed) return;
|
||||
prog_t next[6]={0}; int index[6],count=0;
|
||||
for(int i=0;i<6;i++) {
|
||||
index[i]=-1; if(!bound[i]) continue;
|
||||
int k=0; while(k<count && next[k].serial!=bound[i]->serial) k++;
|
||||
if(k==count) { mtl_prog_snapshot(&next[k],bound[i]); count++; }
|
||||
index[i]=k;
|
||||
}
|
||||
for(int i=0;i<6;i++) if(q->programs[i].serial) mtl_prog_unpin(&q->programs[i]);
|
||||
memset(q->programs,0,sizeof q->programs);
|
||||
for(int i=0;i<count;i++) q->programs[i]=next[i];
|
||||
for(int i=0;i<5;i++) S.bst[i]=index[i]<0?NULL:&q->programs[index[i]];
|
||||
S.cprog=index[5]<0?NULL:&q->programs[index[5]]; S.prog=bind_stages(NULL,0); args_dirty_all();
|
||||
}
|
||||
void mtl_queue_activate(uint64_t serial) { // caller holds the submission lock
|
||||
if (g_active_queue && g_active_queue->serial == serial) return;
|
||||
if (g_active_queue) { g_active_queue->s = S; g_active_queue->r = R; }
|
||||
if (g_active_queue) { g_active_queue->s = S; g_active_queue->r = R; g_active_queue->rc_skip=g_rc_skip; }
|
||||
queue_state *q = g_queue_states;
|
||||
while (q && q->serial != serial) q = q->next;
|
||||
if (q) { S = q->s; R = q->r; prog_resolve(); }
|
||||
if (q) { S = q->s; R = q->r; g_rc_skip=q->rc_skip; prog_resolve(); }
|
||||
else {
|
||||
q = calloc(1, sizeof *q); if (!q) MDIE("queue state allocation failed");
|
||||
q->serial = serial; q->next = g_queue_states; g_queue_states = q;
|
||||
@@ -6579,6 +6853,8 @@ void mtl_queue_forget(uint64_t serial) { // caller holds the submission lock
|
||||
if (!*p) return;
|
||||
queue_state *q = *p; *p = q->next;
|
||||
if (g_active_queue == q) { g_active_queue = NULL; state_reset(); memset(&R, 0, sizeof R); args_dirty_all(); }
|
||||
for(int i=0;i<6;i++) if(q->programs[i].serial) mtl_prog_unpin(&q->programs[i]);
|
||||
for(int i=0;i<9;i++) mtl_tex_unpin(q->rt_pins[i]);
|
||||
free(q);
|
||||
}
|
||||
// A finalized program leaves the bindings of every queue: NVN reads a program only when it is bound, so a game may finalize one that a queue still has bound and reuse its memory.
|
||||
@@ -7178,7 +7454,7 @@ static void lo_bind(id<MTLCommandEncoder> en) {
|
||||
#define PSO_WHOLE @"built whole" // pso_desc's label for pso_build_ex: no base, see there
|
||||
static MTLRenderPipelineDescriptor *pso_desc(const pso_key *k, NvShader *vs, NvShader *fs, id<MTLFunction> fsfn, int merged) {
|
||||
MTLRenderPipelineDescriptor *d = [MTLRenderPipelineDescriptor new];
|
||||
d.vertexFunction = vs->fn; d.fragmentFunction = fsfn ? fsfn : fs ? fs->fn : nil;
|
||||
d.vertexFunction = vs->mesh_kind == 2 ? nil : vs->fn; d.fragmentFunction = fsfn ? fsfn : fs ? fs->fn : nil; // mtk_pso copies the raster state only: a mesh function is not a vertex function
|
||||
// Diagnostic DM_NVN_HILITE=fragment shader key,...: these draws use a solid-color fragment instead (keys 1–6 in order magenta / green / cyan / yellow / blue / white), to see where the geometry lands
|
||||
// Pipelines are built on several threads at once: the keys and the library are set up once (a lazy setup raced, and a thread used a library another had just replaced: Hades II, 6 keys)
|
||||
if (fs) { static char keys[6][24]; static int nk; static id<MTLLibrary> hl; static dispatch_once_t once;
|
||||
@@ -13577,7 +13853,7 @@ void mtl_exec(const uint8_t *p) {
|
||||
PD("Y signal_event cmd=%p dst=%p mode=%u value=%u", p, val, m, v); mtl_sub_event(val, m, v); break; }
|
||||
case OP_REPORT_COUNTER: { uint64_t t, ad; memcpy(&t, a, 8); memcpy(&ad, (const uint8_t *)a + 8, 8); g_cnt_report[t & 31]++;
|
||||
PD("Q report type=%llu cmd=%p dst=%#llx", (unsigned long long)t, p, (unsigned long long)ad);
|
||||
if (DM_GAME_RENDER_COND) rc_note(ad, t == 0 || t == 0x10 ? 1 : 2);
|
||||
if (DM_GAME_RENDER_COND) rc_note(ad, t == 0 || t == 0x10 ? 1 : t == NVN_COUNTER_TYPE_SAMPLES_PASSED ? 2 : 3);
|
||||
if (t == NVN_COUNTER_TYPE_SAMPLES_PASSED) { post((post_op){3, NULL, 0, 0, ad, (uint32_t)t, vis_snapshot()}); g_vis_cur = -1; }
|
||||
else mtl_sub_counter(ad, (uint32_t)t);
|
||||
break; }
|
||||
@@ -14637,14 +14913,14 @@ __attribute__((weak)) uint64_t dm_focus_in_since(void) { return 0; }
|
||||
if (fifo && ticket > first) ticket = ticket - first >= 2 ? g_pq_in - 1 : first;
|
||||
pq_item it = g_pq[(ticket - 1) % PQ]; g_link_it_tin = it.t_in;
|
||||
g_pq_read = ticket;
|
||||
if (ticket > first) { g_link_dropped += ticket - first; for (uint64_t k = first; k < ticket; k++) g_pres[k % PRING] = (pres_ent){k, -1}; } // Old frames merged and dropped are recorded as "not presented", so the present statistics honestly count them as dropped frames
|
||||
if (ticket > first) { g_link_dropped += ticket - first; for (uint64_t k = first; k < ticket; k++) { g_pres[k % PRING] = (pres_ent){k, -1}; mtl_tex_unpin(g_pq[(k-1)%PQ].t.serial); } } // Old frames merged and dropped are recorded as "not presented", so the present statistics honestly count them as dropped frames
|
||||
if (ticket > 1 && g_pq_done < ticket - 1) g_pq_done = ticket - 1;
|
||||
g_link_ring[ticket % PRING] = (link_ent){ticket, update.targetPresentationTimestamp, (update.targetPresentationTimestamp - cb) * 1e3, gap_max * 1e3, nticks}; nticks = 0; gap_max = 0;
|
||||
pthread_cond_broadcast(&g_pq_cv);
|
||||
pthread_mutex_unlock(&g_pq_mu);
|
||||
int submitted;
|
||||
ext_wait(it.ev_val); snap_commit_wait(it.snap_v);
|
||||
@autoreleasepool { submitted = present_now(&it.t, it.period, it.frame, ticket, it.crop, update.drawable, update.targetPresentationTimestamp); }
|
||||
@autoreleasepool { submitted = present_now(&it.t, it.period, it.frame, ticket, it.crop, update.drawable, update.targetPresentationTimestamp); mtl_tex_unpin(it.t.serial); }
|
||||
g_link_hold_until = submitted && it.period > 0.025 ? update.targetPresentationTimestamp + it.period : 0;
|
||||
if (!submitted) {
|
||||
pthread_mutex_lock(&g_pq_mu);
|
||||
@@ -14751,7 +15027,7 @@ static void present_drop_for_suspend(void) {
|
||||
pthread_mutex_lock(&g_pq_mu);
|
||||
if (g_link_owns_layer) {
|
||||
uint64_t n = g_pq_in - g_pq_read;
|
||||
for (uint64_t k = g_pq_read + 1; k <= g_pq_in; k++) g_pres[k % PRING] = (pres_ent){k, -1};
|
||||
for (uint64_t k = g_pq_read + 1; k <= g_pq_in; k++) { g_pres[k % PRING] = (pres_ent){k, -1}; mtl_tex_unpin(g_pq[(k-1)%PQ].t.serial); }
|
||||
g_link_dropped += n; g_pq_read = g_pq_in;
|
||||
while (g_pq_inflight) pthread_cond_wait(&g_pq_cv, &g_pq_mu);
|
||||
if (g_pq_done < g_pq_in) g_pq_done = g_pq_in;
|
||||
@@ -14773,7 +15049,7 @@ static void *present_main(void *arg) {
|
||||
pthread_mutex_unlock(&g_pq_mu);
|
||||
int submitted;
|
||||
ext_wait(it.ev_val); snap_commit_wait(it.snap_v);
|
||||
@autoreleasepool { submitted = present_now(&it.t, it.period, it.frame, ticket, it.crop, nil, 0); }
|
||||
@autoreleasepool { submitted = present_now(&it.t, it.period, it.frame, ticket, it.crop, nil, 0); mtl_tex_unpin(it.t.serial); }
|
||||
pthread_mutex_lock(&g_pq_mu); g_classic_busy = 0; pthread_cond_broadcast(&g_pq_cv); pthread_mutex_unlock(&g_pq_mu);
|
||||
if (!submitted) {
|
||||
pthread_mutex_lock(&g_pq_mu);
|
||||
@@ -14936,6 +15212,7 @@ static uint64_t present_enqueue(const tex_t *t, double period, const int crop[4]
|
||||
slot = (int)(atomic_load(&g_snap_next) % (uint64_t)g_snap_n);
|
||||
if ((ss = snap_take(t))) { memset(&snap, 0, sizeof snap); snap.magic = MAGIC('T', 'E', 'X', 0); snap.serial = ss; t = &snap; }
|
||||
}
|
||||
mtl_tex_pin(t->serial);
|
||||
pthread_mutex_lock(&g_pq_mu);
|
||||
while (g_pq_in - g_pq_done >= PQ) pthread_cond_wait(&g_pq_cv, &g_pq_mu); // Wait only when the queue is full; normally AcquireTexture blocks first
|
||||
pq_item *it = &g_pq[g_pq_in % PQ]; *it = (pq_item){*t, period, atomic_load(&g_cur_frame), {0}, CACurrentMediaTime(), ev_val, ss ? g_snap[slot].ev : 0};
|
||||
@@ -14962,7 +15239,7 @@ void mtl_present_wait(uint64_t tk) {
|
||||
if (g_pq_read >= tk) continue;
|
||||
if (now - last < STALL_NS) { pthread_cond_timedwait(&g_pq_cv, &g_pq_mu, &ts); continue; } // The display link is still running, it is just not this one's turn yet: keep waiting (bounded, no busy spinning)
|
||||
uint64_t n = tk - g_pq_read;
|
||||
for (uint64_t k = g_pq_read + 1; k <= tk; k++) g_pres[k % PRING] = (pres_ent){k, -1};
|
||||
for (uint64_t k = g_pq_read + 1; k <= tk; k++) { g_pres[k % PRING] = (pres_ent){k, -1}; mtl_tex_unpin(g_pq[(k-1)%PQ].t.serial); }
|
||||
g_link_dropped += n; g_pq_read = tk;
|
||||
while (g_pq_inflight) pthread_cond_wait(&g_pq_cv, &g_pq_mu);
|
||||
if (g_pq_done < tk) g_pq_done = tk;
|
||||
|
||||
@@ -55,7 +55,7 @@ typedef struct { uint32_t magic; samp_par p; } samp_t;
|
||||
// The per-stage shader keys are not kept in prog_t: the game's real NVNprogram may be smaller than the header's 0xC0 (growing prog_t corrupted the adjacent object in Mario); see prog_keys in hle_nvn.c
|
||||
typedef struct { uint32_t magic, nstage; NVNshaderData sd[6]; uint64_t serial; } prog_t; FITS(prog_t, NVNprogram); // serial: table key for the replay layer's resolved result
|
||||
|
||||
typedef struct { uint32_t magic, fenced; uint64_t fence; } sync_t; /* fenced 2: by WindowAcquireTexture */ FITS(sync_t, NVNsync);
|
||||
typedef struct { uint32_t magic, fenced; uint64_t fence; } sync_t; /* fenced 1: physical, 2: acquire, 3: owned logical receipt */ FITS(sync_t, NVNsync);
|
||||
typedef struct { const pool_t *pool; int64_t off; } ev_builder_t; FITS(ev_builder_t, NVNeventBuilder);
|
||||
typedef struct { uint32_t magic; volatile uint32_t *val; const pool_t *pool; int64_t off; } ev_t; FITS(ev_t, NVNevent); // pool / off: EventGetMemoryPool / Offset
|
||||
|
||||
@@ -107,7 +107,7 @@ enum {
|
||||
OP_BIND_PROGRAM, OP_BIND_STATE, OP_BIND_VATTR, OP_BIND_VSTREAM, OP_BIND_VBUF,
|
||||
OP_BIND_UBO, OP_BIND_SSBO, OP_BIND_TEX, OP_BIND_SAMP,
|
||||
OP_STENCIL, OP_POLY_OFFSET, OP_DRAW, OP_DRAW_IDX, OP_DISPATCH, OP_BARRIER,
|
||||
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_CLEAR_BUF, OP_DEPTH_CLAMP, OP_RENDER_COND, OP_FENCE_SYNC, OP_TF_BIND, OP_TF_STATE, OP_RAST_DISCARD, OP_VP_SWIZZLE, OP_BIND_TEX1, OP_PRIM_RESTART, OP_BIND_UBO_SMALL, OP_BIND_VBUF1, OP_DRAW_TEX, OP_ALPHA_REF, OP_PUSH_CONST, OP_DLSS, OP_MULTI_DRAW, OP_COUNT_
|
||||
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_CLEAR_BUF, OP_DEPTH_CLAMP, OP_RENDER_COND, OP_FENCE_SYNC, OP_TF_BIND, OP_TF_STATE, OP_RAST_DISCARD, OP_VP_SWIZZLE, OP_BIND_TEX1, OP_PRIM_RESTART, OP_BIND_UBO_SMALL, OP_BIND_VBUF1, OP_DRAW_TEX, OP_ALPHA_REF, OP_PUSH_CONST, OP_DLSS, OP_MULTI_DRAW, OP_WAIT_EVENT, OP_WAIT_SYNC, OP_COUNT_
|
||||
};
|
||||
// Payload (immediately follows op_hdr)
|
||||
typedef struct {
|
||||
@@ -251,6 +251,8 @@ int mtl_snap_on(void); uint64_t mtl_snap_acquire_wait(void); // present snapsh
|
||||
// Texture release (at Finalize)
|
||||
void mtl_tex_init(const tex_t *t); // TextureInitialize: the serial belongs to a live texture object until mtl_tex_release
|
||||
void mtl_tex_release(tex_t *t);
|
||||
void mtl_tex_pin(uint64_t serial);
|
||||
void mtl_tex_unpin(uint64_t serial);
|
||||
void mtl_pkg_stats(uint64_t *uploads, uint64_t *reuploads);
|
||||
unsigned mtl_cpu_tex_count(void); // live textures the CPU writes (retired snapshots are excluded)
|
||||
uint64_t mtl_pkg_edge_skips(void); // packaged texture checks that found only writes beside the texture (pkg_edges_clean)
|
||||
@@ -281,6 +283,8 @@ int prog_key(const prog_t *p, unsigned stage, uint8_t key[8]);
|
||||
void nvn_ctl_lens(const void *control, uint32_t *nctl, uint32_t *ncode); // a control section's bytes in the shader key and its code area's length (NVN or NVN2), hle_nvn.c
|
||||
void mtl_reg_samp(int id, const samp_par *p);
|
||||
void mtl_prog_release(prog_t *p);
|
||||
void mtl_prog_unpin(prog_t *p); // submit lock held: release a queued descriptor or saved binding
|
||||
void mtl_prog_snapshot(prog_t *copy, const prog_t *source); // submit lock held: retain compiled shaders behind owned metadata
|
||||
void mtl_prog_prefetch(const prog_t *p); // loads a new program's shader libraries in the background (nvn_mtl.m)
|
||||
void mtl_prog_forget(const prog_t *p); // program finalize, submit lock held: drop it from every queue's bindings
|
||||
// New serial (> 0, globally increasing)
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// Guest queue completion is distinct from a physical Metal submission fence.
|
||||
#pragma once
|
||||
#include "nvn_obj.h"
|
||||
void nvn_queue_submit(queue_t *q, int n, const uint64_t *handles);
|
||||
uint64_t nvn_queue_present(queue_t *q,const tex_t *t,double period,const int crop[4]);
|
||||
void nvn_queue_present_wait(uint64_t ticket);
|
||||
void nvn_queue_present_release(uint64_t ticket);
|
||||
void nvn_queue_fence(queue_t *q, sync_t *s);
|
||||
void nvn_queue_wait_sync(queue_t *q, const sync_t *s);
|
||||
void nvn_queue_finish(queue_t *q);
|
||||
void nvn_queue_forget(queue_t *q);
|
||||
void nvn_sync_release(sync_t *s);
|
||||
int nvn_sync_wait(const sync_t *s, uint64_t timeout);
|
||||
void nvn_event_publish(volatile uint32_t *word, unsigned mode, uint32_t value);
|
||||
void nvn_event_publish_gpu(volatile uint32_t *word, unsigned mode, uint32_t value, uint64_t fence);
|
||||
void nvn_queue_gpu_progress(void);
|
||||
@@ -0,0 +1,246 @@
|
||||
#include "nvn_capture.h"
|
||||
#include "nvn_hmap.h"
|
||||
|
||||
void *objc_autoreleasePoolPush(void);
|
||||
void objc_autoreleasePoolPop(void *);
|
||||
|
||||
// Ready continuations of NVN queues share the renderer's one ordered Metal queue.
|
||||
// An unresolved wait parks its queue, never the submitting CPU or another queue.
|
||||
typedef struct nq_receipt { unsigned refs, published; uint64_t fence, present; } nq_receipt;
|
||||
typedef struct nq_node {
|
||||
struct nq_node *next;
|
||||
uint8_t *bytes; size_t length, capacity;
|
||||
unsigned kind, mode, closed, waiting; volatile uint32_t *event; uint32_t value;
|
||||
uint64_t wait_fence, event_predecessor; unsigned wait_kind; const sync_t *sync_source; nq_receipt *receipt;
|
||||
tex_t texture; double period; int crop[4];
|
||||
} nq_node;
|
||||
typedef struct nq_owned { struct nq_owned *next; unsigned kind; uint64_t data[]; } nq_owned;
|
||||
typedef struct nq_job { struct nq_job *next; nq_node *first, *last; nq_receipt *receipt; nq_owned *owned; nvn_hmap objects; uint64_t frame; } nq_job;
|
||||
static void nq_job_free(nq_job *j) {
|
||||
for(nq_owned *o=j->owned,*next;o;o=next) { next=o->next; if(o->kind==CAP_K_PROG) mtl_prog_unpin((prog_t *)o->data); else if(o->kind==CAP_K_TEX) mtl_tex_unpin(((tex_t *)o->data)->serial); free(o); }
|
||||
free(j->objects.keys); free(j->objects.vals); free(j);
|
||||
}
|
||||
static int nq_snapshot_address(void *ctx,uint64_t *field,uint64_t len,int writable) { (void)ctx;(void)field;(void)len;(void)writable;return 1; }
|
||||
static int nq_snapshot_object(void *ctx,int kind,uint64_t *field,uint8_t *payload,uint32_t size) {
|
||||
(void)payload;(void)size; nq_job *j=ctx; if(!*field || (kind!=CAP_K_PROG && kind!=CAP_K_TEX)) return 1;
|
||||
uint64_t key[2]={*field,(unsigned)kind}; nq_owned *o=nvn_hm_get(&j->objects,key);
|
||||
if(!o) {
|
||||
size_t bytes=kind==CAP_K_PROG?sizeof(prog_t):sizeof(tex_t); o=calloc(1,sizeof *o+bytes); if(!o) die("queue descriptor allocation failed");
|
||||
o->kind=kind; o->next=j->owned; j->owned=o;
|
||||
if(kind==CAP_K_PROG) mtl_prog_snapshot((prog_t *)o->data,(const prog_t *)(uintptr_t)*field);
|
||||
else { memcpy(o->data,(const void *)(uintptr_t)*field,bytes); mtl_tex_pin(((tex_t *)o->data)->serial); }
|
||||
nvn_hm_put(&j->objects,key,o);
|
||||
}
|
||||
*field=(uintptr_t)o->data;return 1;
|
||||
}
|
||||
static const cap_ops nq_snapshot_ops={nq_snapshot_address,nq_snapshot_object};
|
||||
typedef struct nq_queue {
|
||||
struct nq_queue *next; uint64_t serial, physical, present; int origin;
|
||||
nq_job *first, *last; nq_receipt *tail;
|
||||
} nq_queue;
|
||||
static pthread_mutex_t nq_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t nq_cv = PTHREAD_COND_INITIALIZER;
|
||||
static pthread_once_t nq_once = PTHREAD_ONCE_INIT;
|
||||
static nq_queue *nq_queues;
|
||||
typedef struct nq_event_write { struct nq_event_write *next; volatile uint32_t *word; uint64_t fence; } nq_event_write;
|
||||
static nq_event_write *nq_event_writes;
|
||||
static uint64_t nq_event_pending(volatile uint32_t *word) { for(nq_event_write *w=nq_event_writes;w;w=w->next) if(w->word==word) return w->fence; return 0; }
|
||||
static void nq_event_issued(volatile uint32_t *word,uint64_t fence) {
|
||||
nq_event_write *w=nq_event_writes; while(w && w->word!=word) w=w->next;
|
||||
if(!w) { w=calloc(1,sizeof *w); if(!w) die("event ordering allocation failed"); w->word=word; w->next=nq_event_writes; nq_event_writes=w; }
|
||||
w->fence=fence;
|
||||
}
|
||||
|
||||
enum { NQ_COMMANDS, NQ_EVENT, NQ_SYNC, NQ_FENCE, NQ_PRESENT };
|
||||
static nq_receipt *nq_new(void) { nq_receipt *r=calloc(1,sizeof *r); if(!r) die("queue receipt allocation failed"); r->refs=1; return r; }
|
||||
static void nq_put(nq_receipt *r) { if(r && !--r->refs) free(r); }
|
||||
static void nq_set_sync(sync_t *s,nq_receipt *r) { if(s->fenced==3) nq_put((nq_receipt *)(uintptr_t)s->fence); r->refs++; s->fence=(uintptr_t)r; s->fenced=3; }
|
||||
void nvn_sync_release(sync_t *s) { pthread_mutex_lock(&nq_mu); if(s->fenced==3) nq_put((nq_receipt *)(uintptr_t)s->fence); s->fenced=0; s->fence=0; pthread_mutex_unlock(&nq_mu); }
|
||||
static nq_queue *nq_get(queue_t *q) {
|
||||
nq_queue *p=nq_queues; while(p && p->serial!=q->serial) p=p->next;
|
||||
if(!p) { p=calloc(1,sizeof *p); if(!p) die("queue state allocation failed"); p->serial=q->serial; p->origin=q->origin_ll; p->next=nq_queues; nq_queues=p; }
|
||||
return p;
|
||||
}
|
||||
static void nq_publish(nq_receipt *r,uint64_t fence) { r->fence=fence; r->published=1; pthread_cond_broadcast(&nq_cv); }
|
||||
static int nq_predicate(uint32_t current,unsigned mode,uint32_t target) { return mode==0 ? current==target : (uint32_t)(current-target)<0x80000000u; }
|
||||
static int nq_sync_encoded(const sync_t *s,uint64_t *fence) {
|
||||
if(s->fenced==3) { nq_receipt *r=(nq_receipt *)(uintptr_t)s->fence; if(!r->published) return 0; *fence=r->fence; return 1; }
|
||||
if(!s->fenced) return 0; *fence=s->fence; return 1;
|
||||
}
|
||||
void nvn_queue_gpu_progress(void) {
|
||||
pthread_mutex_lock(&nq_mu); uint64_t done=mtl_completed_fence(); nq_event_write **p=&nq_event_writes;
|
||||
while(*p) { nq_event_write *w=*p; if(w->fence<=done) { *p=w->next; free(w); } else p=&w->next; }
|
||||
pthread_cond_broadcast(&nq_cv); pthread_mutex_unlock(&nq_mu);
|
||||
}
|
||||
static void nq_event_publish(volatile uint32_t *word,unsigned mode,uint32_t value,uint64_t gpu_fence) {
|
||||
pthread_mutex_lock(&nq_mu);
|
||||
if(mode==1) atomic_fetch_add_explicit((_Atomic uint32_t *)word,value,memory_order_release);
|
||||
else atomic_store_explicit((_Atomic uint32_t *)word,value,memory_order_release);
|
||||
atomic_thread_fence(memory_order_seq_cst);
|
||||
// Latch waits already reached: a subsequent signal must not erase a release.
|
||||
for(nq_queue *q=nq_queues;q;q=q->next) if(q->first && q->first->first) {
|
||||
nq_node *n=q->first->first;
|
||||
if(n->kind==NQ_EVENT && n->waiting && n->event==word && (gpu_fence ? gpu_fence>=n->event_predecessor : nq_event_pending(word)<=mtl_completed_fence()) && nq_predicate(atomic_load_explicit((_Atomic uint32_t *)word,memory_order_acquire),n->mode,n->value)) { n->event=NULL; n->wait_fence=gpu_fence; }
|
||||
}
|
||||
pthread_cond_broadcast(&nq_cv); pthread_mutex_unlock(&nq_mu);
|
||||
}
|
||||
void nvn_event_publish(volatile uint32_t *word,unsigned mode,uint32_t value) { nq_event_publish(word,mode,value,0); }
|
||||
void nvn_event_publish_gpu(volatile uint32_t *word,unsigned mode,uint32_t value,uint64_t fence) { nq_event_publish(word,mode,value,fence); }
|
||||
static void nq_snapshot_sync(nq_node *n,const sync_t *s) {
|
||||
n->wait_kind=s->fenced; n->wait_fence=s->fence;
|
||||
if(s->fenced==3) { n->receipt=(nq_receipt *)(uintptr_t)s->fence; n->receipt->refs++; }
|
||||
}
|
||||
typedef struct { uint64_t wall, cpu, instr, cycles, sys; } nq_cost;
|
||||
static nq_cost nq_cost_begin(void) {
|
||||
nq_cost c={.wall=now_ns(),.cpu=clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID),.sys=thr_sys_ns()};
|
||||
thr_counts(&c.instr,&c.cycles); return c;
|
||||
}
|
||||
static void nq_cost_end(nq_cost c) {
|
||||
uint64_t dw=now_ns()-c.wall, dc=clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID)-c.cpu, ins, cyc; thr_counts(&ins,&cyc);
|
||||
atomic_fetch_add(&g_nvn_ns,dw); atomic_fetch_add(&g_sub_wall_ns,dw); atomic_fetch_add(&g_cum_sub_wall_ns,dw);
|
||||
atomic_fetch_add(&g_sub_cpu_ns,dc); atomic_fetch_add(&g_cum_sub_cpu_ns,dc);
|
||||
atomic_fetch_add(&g_sub_instr,ins-c.instr); atomic_fetch_add(&g_cum_sub_instr,ins-c.instr);
|
||||
atomic_fetch_add(&g_cum_sub_cyc,cyc-c.cycles); atomic_fetch_add(&g_cum_sub_sys_ns,thr_sys_ns()-c.sys);
|
||||
}
|
||||
static void *nq_worker(void *unused) {
|
||||
(void)unused; pthread_setname_np("NVN queue replay");
|
||||
pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE,0);
|
||||
uint64_t frame=UINT64_MAX;
|
||||
for(;;) {
|
||||
pthread_mutex_lock(&nq_mu); nq_queue *q=NULL; nq_node *n=NULL; nq_job *j=NULL;
|
||||
for(;;) {
|
||||
scan_again:;
|
||||
int mapped_event_wait=0;
|
||||
for(q=nq_queues;q;q=q->next) {
|
||||
j=q->first; if(!j) continue; n=j->first;
|
||||
if(!n) { nq_publish(j->receipt,q->physical); q->first=j->next; if(!q->first) q->last=NULL; nq_put(j->receipt);
|
||||
pthread_mutex_unlock(&nq_mu); pthread_mutex_lock(&g_sub_mu); void *pool=objc_autoreleasePoolPush(); nq_job_free(j); objc_autoreleasePoolPop(pool); pthread_mutex_unlock(&g_sub_mu); pthread_mutex_lock(&nq_mu); goto scan_again; }
|
||||
if(n->kind==NQ_EVENT && n->event) {
|
||||
uint64_t predecessor=nq_event_pending(n->event);
|
||||
if(!n->waiting) n->event_predecessor=predecessor;
|
||||
if(predecessor>mtl_completed_fence() || !nq_predicate(atomic_load_explicit((_Atomic uint32_t *)n->event,memory_order_acquire),n->mode,n->value)) { n->waiting=1; mapped_event_wait=1; continue; }
|
||||
}
|
||||
if(n->kind==NQ_SYNC) {
|
||||
if(!n->wait_kind || (n->receipt && !n->receipt->published)) continue;
|
||||
// Targets are immutable snapshots. One Metal queue orders an encoded producer before this continuation.
|
||||
}
|
||||
break;
|
||||
}
|
||||
if(q) break;
|
||||
// NVN events can also be changed by plain stores through mapped pool memory.
|
||||
// A bounded notification poll only while such a word is awaited complements API/callback wakes.
|
||||
if(mapped_event_wait) { struct timespec tick={0,1000000}; pthread_cond_timedwait_relative_np(&nq_cv,&nq_mu,&tick); }
|
||||
else pthread_cond_wait(&nq_cv,&nq_mu);
|
||||
}
|
||||
j->first=n->next; if(!j->first) j->last=NULL;
|
||||
// Round-robin ready queues: a continually fed independent producer cannot starve another queue.
|
||||
if(q->next) { nq_queue **link=&nq_queues; while(*link!=q) link=&(*link)->next; *link=q->next; nq_queue *tail=nq_queues; while(tail->next) tail=tail->next; tail->next=q; q->next=NULL; }
|
||||
if(n->kind==NQ_SYNC || n->kind==NQ_EVENT) { uint64_t f=n->receipt?n->receipt->fence:n->wait_fence; if(f>q->physical) q->physical=f; }
|
||||
if(n->kind==NQ_FENCE) nq_publish(n->receipt,q->physical);
|
||||
pthread_mutex_unlock(&nq_mu);
|
||||
uint64_t fence=0, present=0;
|
||||
if(n->kind==NQ_COMMANDS || n->kind==NQ_PRESENT) {
|
||||
dm_host_mutex_lock(&g_sub_mu); void *pool=objc_autoreleasePoolPush();
|
||||
dm_host_work++; mtl_prepare(); dm_host_work--;
|
||||
gfx_enter(); nq_cost cost=nq_cost_begin();
|
||||
if(frame!=j->frame) { frame=j->frame; mtl_set_frame(frame); }
|
||||
mtl_queue_activate(q->serial); mtl_set_queue_origin_lower_left(q->origin);
|
||||
if(n->kind==NQ_COMMANDS) {
|
||||
uint64_t handle=(uintptr_t)n->bytes;
|
||||
nvn_cap_submit(1,&handle);
|
||||
mtl_sub_begin(); nvn_ft_poll(); mtl_sub_index(&handle,1);
|
||||
mtl_exec_rest(NULL,0); mtl_exec(n->bytes); fence=mtl_sub_commit();
|
||||
} else {
|
||||
nvn_cap_present(&n->texture,n->crop);
|
||||
present=mtl_present(&n->texture,n->period,n->crop); mtl_tex_unpin(n->texture.serial);
|
||||
}
|
||||
nq_cost_end(cost); gfx_leave(); objc_autoreleasePoolPop(pool); pthread_mutex_unlock(&g_sub_mu);
|
||||
}
|
||||
pthread_mutex_lock(&nq_mu); if(n->kind==NQ_PRESENT) { q->present=present; j->receipt->present=present; } if(fence) { q->physical=fence; if(n->event) nq_event_issued(n->event,fence); } if(n->receipt) nq_put(n->receipt); free(n->bytes); free(n); pthread_cond_broadcast(&nq_cv); pthread_mutex_unlock(&nq_mu);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
static void nq_start(void) { pthread_t t; if(pthread_create(&t,NULL,nq_worker,NULL)) die("NVN queue worker failed"); pthread_detach(t); }
|
||||
static nq_node *nq_append(nq_job *j,unsigned kind) { nq_node *n=calloc(1,sizeof *n); if(!n) die("queue continuation allocation failed"); n->kind=kind; if(j->last) j->last->next=n; else j->first=n; j->last=n; return n; }
|
||||
static void nq_bytes(nq_node *n,const void *bytes,size_t length) { if(n->length+length>n->capacity) { n->capacity=(n->length+length+4095)&~(size_t)4095; n->bytes=realloc(n->bytes,n->capacity); if(!n->bytes) die("queue commands allocation failed"); } memcpy(n->bytes+n->length,bytes,length); n->length+=length; }
|
||||
static void nq_end(nq_job *j) { if(j->last && j->last->kind==NQ_COMMANDS && !j->last->closed) { op_hdr end={OP_END,8}; nq_bytes(j->last,&end,8); j->last->closed=1; } }
|
||||
static void nq_flatten(nq_job *j,const uint8_t *p,unsigned depth) {
|
||||
if(depth>64) die("NVN command call nesting exceeds64");
|
||||
for(;;) {
|
||||
op_hdr h; memcpy(&h,p,8); if(h.size<8 || h.size&7) die("invalid NVN command size"); const uint8_t *a=p+8;
|
||||
if(h.op==OP_END) return;
|
||||
if(h.op==OP_JUMP) { memcpy(&p,a,8); continue; }
|
||||
if(h.op==OP_CALL) { const uint8_t *called; memcpy(&called,a,8); nq_flatten(j,called,depth+1); p+=h.size; continue; }
|
||||
if(h.op==OP_WAIT_EVENT || h.op==OP_WAIT_SYNC || h.op==OP_FENCE_SYNC) {
|
||||
nq_end(j); nq_node *n=nq_append(j,h.op==OP_WAIT_EVENT?NQ_EVENT:h.op==OP_WAIT_SYNC?NQ_SYNC:NQ_FENCE);
|
||||
if(h.op==OP_WAIT_EVENT) { memcpy(&n->event,a,8); memcpy(&n->mode,a+8,4); memcpy(&n->value,a+12,4); }
|
||||
else { memcpy(&n->sync_source,a,8); if(h.op==OP_FENCE_SYNC) n->receipt=nq_new(); }
|
||||
} else {
|
||||
nq_node *n=j->last; if(!n || n->kind!=NQ_COMMANDS || n->closed) n=nq_append(j,NQ_COMMANDS);
|
||||
size_t offset=n->length; nq_bytes(n,p,h.size);
|
||||
if(!cap_rec_fields(h.op,n->bytes+offset+8,h.size,&nq_snapshot_ops,j)) die("queue snapshot: unknown command %u",h.op);
|
||||
if(h.op==OP_SIGNAL_EVENT) { memcpy(&n->event,a,8); nq_end(j); nq_append(j,NQ_FENCE)->receipt=nq_new(); }
|
||||
}
|
||||
p+=h.size;
|
||||
}
|
||||
}
|
||||
static void nq_enqueue(nq_queue *q,nq_job *j) { if(q->last) q->last->next=j; else q->first=j; q->last=j; nq_put(q->tail); q->tail=j->receipt; q->tail->refs++; pthread_cond_broadcast(&nq_cv); }
|
||||
void nvn_queue_submit(queue_t *q,int count,const uint64_t *handles) {
|
||||
pthread_once(&nq_once,nq_start); nq_job *j=calloc(1,sizeof *j); if(!j) die("queue job allocation failed"); j->receipt=nq_new();
|
||||
j->objects.klen=16; j->frame=dm_nvn_frame_count();
|
||||
// No scheduler lock while copying descriptors or resolving shader libraries.
|
||||
dm_host_mutex_lock(&g_sub_mu); void *pool=objc_autoreleasePoolPush(); dm_host_work++; mtl_prepare(); dm_host_work--; nq_cost cost=nq_cost_begin();
|
||||
for(int i=0;i<count;i++) nq_flatten(j,(const uint8_t *)(uintptr_t)handles[i],0); nq_end(j);
|
||||
nq_cost_end(cost); objc_autoreleasePoolPop(pool); pthread_mutex_unlock(&g_sub_mu);
|
||||
int waits=0; for(nq_node *node=j->first;node;node=node->next) waits|=node->kind==NQ_EVENT || node->kind==NQ_SYNC;
|
||||
nvn_cap_queue(q->serial,waits);
|
||||
pthread_mutex_lock(&nq_mu);
|
||||
for(nq_node *node=j->first;node;node=node->next) if(node->sync_source) {
|
||||
if(node->kind==NQ_FENCE) nq_set_sync((sync_t *)node->sync_source,node->receipt); else nq_snapshot_sync(node,node->sync_source);
|
||||
node->sync_source=NULL;
|
||||
}
|
||||
nq_enqueue(nq_get(q),j); pthread_mutex_unlock(&nq_mu);
|
||||
}
|
||||
// The window retains this logical receipt until it reacquires or finalizes that image.
|
||||
// Only replay turns it into a physical display ticket; present never waits on the guest thread.
|
||||
uint64_t nvn_queue_present(queue_t *q,const tex_t *t,double period,const int crop[4]) {
|
||||
nvn_cap_queue(q->serial,0);
|
||||
pthread_once(&nq_once,nq_start); nq_job *j=calloc(1,sizeof *j); if(!j) die("queue present allocation failed");
|
||||
j->receipt=nq_new(); j->frame=dm_nvn_frame_count(); nq_node *n=nq_append(j,NQ_PRESENT);
|
||||
n->texture=*t; mtl_tex_pin(t->serial); n->period=period; if(crop) memcpy(n->crop,crop,sizeof n->crop);
|
||||
pthread_mutex_lock(&nq_mu); j->receipt->refs++; uint64_t ticket=(uintptr_t)j->receipt;
|
||||
nq_enqueue(nq_get(q),j); pthread_mutex_unlock(&nq_mu); return ticket;
|
||||
}
|
||||
void nvn_queue_present_release(uint64_t ticket) {
|
||||
if(!ticket) return; pthread_mutex_lock(&nq_mu); nq_put((nq_receipt *)(uintptr_t)ticket); pthread_mutex_unlock(&nq_mu);
|
||||
}
|
||||
void nvn_queue_present_wait(uint64_t ticket) {
|
||||
if(!ticket) return; nq_receipt *r=(nq_receipt *)(uintptr_t)ticket;
|
||||
pthread_mutex_lock(&nq_mu); while(!r->published) pthread_cond_wait(&nq_cv,&nq_mu); uint64_t physical=r->present; pthread_mutex_unlock(&nq_mu);
|
||||
if(physical) mtl_present_wait(physical);
|
||||
}
|
||||
void nvn_queue_fence(queue_t *q,sync_t *s) {
|
||||
pthread_mutex_lock(&nq_mu); nq_queue *p=nq_get(q);
|
||||
if(p->tail) nq_set_sync(s,p->tail); else { if(s->fenced==3) nq_put((nq_receipt *)(uintptr_t)s->fence); s->fenced=1; s->fence=p->physical; }
|
||||
pthread_mutex_unlock(&nq_mu);
|
||||
}
|
||||
int nvn_sync_wait(const sync_t *s,uint64_t timeout) {
|
||||
uint64_t start=now_ns(),fence=0; pthread_mutex_lock(&nq_mu);
|
||||
while(!nq_sync_encoded(s,&fence)) {
|
||||
uint64_t elapsed=now_ns()-start; if(timeout!=UINT64_MAX && elapsed>=timeout) { pthread_mutex_unlock(&nq_mu); return 0; }
|
||||
if(timeout==UINT64_MAX) pthread_cond_wait(&nq_cv,&nq_mu);
|
||||
else { uint64_t left=timeout-elapsed; struct timespec ts={(time_t)(left/1000000000ull),(long)(left%1000000000ull)}; pthread_cond_timedwait_relative_np(&nq_cv,&nq_mu,&ts); }
|
||||
}
|
||||
pthread_mutex_unlock(&nq_mu); uint64_t elapsed=now_ns()-start;
|
||||
return mtl_wait(fence,timeout==UINT64_MAX?timeout:elapsed>=timeout?0:timeout-elapsed);
|
||||
}
|
||||
void nvn_queue_wait_sync(queue_t *q,const sync_t *s) {
|
||||
nvn_cap_queue(q->serial,1);
|
||||
pthread_once(&nq_once,nq_start); nq_job *j=calloc(1,sizeof *j); if(!j) die("queue wait allocation failed"); j->receipt=nq_new();
|
||||
pthread_mutex_lock(&nq_mu); nq_snapshot_sync(nq_append(j,NQ_SYNC),s); nq_enqueue(nq_get(q),j); pthread_mutex_unlock(&nq_mu);
|
||||
}
|
||||
void nvn_queue_finish(queue_t *q) { sync_t s={0}; nvn_queue_fence(q,&s); nvn_sync_wait(&s,UINT64_MAX); nvn_sync_release(&s);
|
||||
pthread_mutex_lock(&nq_mu); uint64_t present=nq_get(q)->present; pthread_mutex_unlock(&nq_mu);
|
||||
if(present) mtl_present_wait(present);
|
||||
}
|
||||
void nvn_queue_forget(queue_t *q) { nvn_queue_finish(q); pthread_mutex_lock(&nq_mu); nq_queue **p=&nq_queues; while(*p && (*p)->serial!=q->serial) p=&(*p)->next; if(*p) { nq_queue *old=*p; *p=old->next; nq_put(old->tail); free(old); } pthread_mutex_unlock(&nq_mu); }
|
||||
@@ -209,6 +209,8 @@ check_t_present_snap: t_present_snap
|
||||
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_present_snap pacing
|
||||
DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_present_snap resize
|
||||
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_present_snap resize
|
||||
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_present_snap queued
|
||||
DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_present_snap queued
|
||||
t_reorder_chain: t_reorder_chain.m $(MTL_T_DEP)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_reorder_chain.m $(MTL_T_SRC) $(FW)
|
||||
check_t_reorder_chain: RUN_ENV = MTL_DEBUG_LAYER=1
|
||||
@@ -504,3 +506,38 @@ check_t_logic: t_logic
|
||||
# MUFU.SIN / COS lowered from turns through the fraction (InstEmitAmpereAlu.cs ATurnsToRadians), on the GPU against a double-precision reference
|
||||
t_mufu_turns: t_mufu_turns.m
|
||||
clang -O1 -g -Wall -fobjc-arc -o $@ t_mufu_turns.m -framework Metal -framework Foundation
|
||||
# Native task/mesh draws must render on the first pipeline use, with direct and threaded Metal encoding.
|
||||
t_mesh_first_use: t_mesh_first_use.m $(MTL_T_DEP)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_mesh_first_use.m $(filter-out ../nvn/hle_nvn.c,$(MTL_T_SRC)) $(FW)
|
||||
.PHONY: check_t_mesh_first_use
|
||||
check_t_mesh_first_use: t_mesh_first_use
|
||||
DM_NVN_ENC_THREAD=0 MTL_DEBUG_LAYER=1 ./t_mesh_first_use
|
||||
DM_NVN_ENC_THREAD=1 MTL_DEBUG_LAYER=1 ./t_mesh_first_use
|
||||
|
||||
t_wait_event: t_wait_event.m $(MTL_T_DEP)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_wait_event.m $(filter-out ../nvn/hle_nvn.c,$(MTL_T_SRC)) $(FW)
|
||||
|
||||
t_queue_lifetime: t_queue_lifetime.m $(MTL_T_DEP)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_queue_lifetime.m $(filter-out ../nvn/hle_nvn.c,$(MTL_T_SRC)) $(FW)
|
||||
|
||||
.PHONY: check_t_wait_event check_t_queue_lifetime
|
||||
check_t_wait_event: t_wait_event
|
||||
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=0 ./$<
|
||||
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 ./$<
|
||||
check_t_queue_lifetime: t_queue_lifetime
|
||||
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=0 ./$<
|
||||
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 ./$<
|
||||
|
||||
t_render_enable_queue: t_render_enable_queue.m $(MTL_T_DEP)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_render_enable_queue.m $(filter-out ../nvn/hle_nvn.c,$(MTL_T_SRC)) $(FW)
|
||||
.PHONY: check_t_render_enable_queue
|
||||
check_t_render_enable_queue: t_render_enable_queue
|
||||
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=0 ./$<
|
||||
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 ./$<
|
||||
|
||||
t_render_counter_overlap: t_render_counter_overlap.m $(MTL_T_DEP)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_render_counter_overlap.m $(filter-out ../nvn/hle_nvn.c,$(MTL_T_SRC)) $(FW)
|
||||
.PHONY: check_t_render_counter_overlap
|
||||
check_t_render_counter_overlap: t_render_counter_overlap
|
||||
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=0 ./$<
|
||||
MTL_DEBUG_LAYER=1 DM_NVN_ENC_THREAD=1 ./$<
|
||||
@@ -225,6 +225,20 @@ int main(int argc, char **argv) { @autoreleasepool {
|
||||
cap_reader rd; int lr = cap_load(&rd, path);
|
||||
if (lr <= 0) RFAIL("%s: %s", path, lr < 0 ? "not a capture of format 1" : "cannot read");
|
||||
for (;;) { cap_chunk c; uint8_t *d; int r = cap_next(&rd, &c, &d); if (r < 0) RFAIL("%s: corrupt chunk at byte %zu", path, rd.pos); if (!r) break;
|
||||
if (c.tag == CAP_FAIL) RFAIL("%s: capture refused: %.*s", path, (int)MIN(c.raw, 1024), (const char *)d);
|
||||
if (c.tag == CAP_SEGM) {
|
||||
uint32_t idx, len; if (c.raw < 8) RFAIL("%s: short segment chunk", path);
|
||||
memcpy(&idx, d, 4); memcpy(&len, d + 4, 4);
|
||||
if ((uint64_t)len != c.raw - 8) RFAIL("%s: segment %u size mismatch", path, idx);
|
||||
for (uint32_t off = 0; off < len;) {
|
||||
op_hdr h; if (len - off < 8) RFAIL("%s: segment %u has a short record", path, idx);
|
||||
memcpy(&h, d + 8 + off, 8);
|
||||
if (h.size < 8 || (h.size & 7) || h.size > len - off) RFAIL("%s: segment %u has a corrupt record", path, idx);
|
||||
const char *why = cap_record_unsupported(h.op);
|
||||
if (why) RFAIL("%s: submit %u segment %u: %s", path, c.submit, idx, why);
|
||||
off += h.size;
|
||||
}
|
||||
}
|
||||
rp_ch = realloc(rp_ch, (rp_nch + 1) * sizeof *rp_ch); rp_ch[rp_nch++] = (chunk){c, d}; }
|
||||
cap_unload(&rd);
|
||||
// header: game, layout, chain; then the live run's settings
|
||||
|
||||
@@ -66,6 +66,15 @@ static void walk(seg *s, uint8_t *bytes, const cap_ops *ops, const uint8_t *orig
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
cap_queue_state single = {0}, multi_queue = {0}, waited = {0};
|
||||
cap_queue_note(&single, 11, 0); cap_queue_note(&single, 11, 0);
|
||||
CHECK(!cap_queue_unsupported(&single), "one logical queue without waits remains capturable");
|
||||
cap_queue_note(&multi_queue, 11, 0); cap_queue_note(&multi_queue, 12, 0);
|
||||
CHECK(cap_queue_unsupported(&multi_queue) && atomic_load(&multi_queue.unsupported) == CAP_QUEUE_MULTIPLE, "different logical queues are rejected before their physical order can be mistaken for queue semantics");
|
||||
cap_queue_note(&waited, 11, 1);
|
||||
CHECK(cap_queue_unsupported(&waited) && atomic_load(&waited.unsupported) == CAP_QUEUE_WAIT, "wait-only queue operations cannot disappear from a capture");
|
||||
CHECK(cap_record_unsupported(OP_WAIT_EVENT) && cap_record_unsupported(OP_WAIT_SYNC), "standalone replay rejects logical waits");
|
||||
CHECK(!cap_record_unsupported(OP_FENCE_SYNC) && !cap_record_unsupported(OP_SIGNAL_EVENT), "legacy fences and event signals remain replayable");
|
||||
char path[1024]; const char *tmp = getenv("TMPDIR"); snprintf(path, sizeof path, "%s/t_capture_XXXXXX", tmp && *tmp ? tmp : "/tmp");
|
||||
int fd = mkstemp(path); CHECK(fd >= 0, "temporary file"); close(fd);
|
||||
pool_a = calloc(1, 65536); pool_b = calloc(1, 16384);
|
||||
@@ -188,6 +197,11 @@ int main(void) {
|
||||
FILE *f = fopen(path, "r+b"); fseeko(f, 0, SEEK_END); off_t n = ftello(f); fclose(f); truncate(path, n - 40);
|
||||
CHECK(cap_load(&rd, path) == 1, "a truncated capture still opens"); int r, bad = 0; while ((r = cap_next(&rd, &c, &d)) == 1) free(d); bad = r < 0; cap_unload(&rd);
|
||||
CHECK(bad, "a truncated capture ends in an error");
|
||||
CHECK(cap_open(&w, path), "replace a rejected capture with a failure marker");
|
||||
const char *why = cap_queue_unsupported(&waited);
|
||||
cap_put(&w, CAP_FAIL, 0, why, strlen(why), 0); CHECK(cap_close(&w), "close rejected capture");
|
||||
CHECK(cap_load(&rd, path) == 1 && cap_next(&rd, &c, &d) == 1 && c.tag == CAP_FAIL && c.raw == strlen(why) && !memcmp(d, why, c.raw), "failure reason survives the capture file round-trip");
|
||||
free(d); cap_unload(&rd);
|
||||
unlink(path);
|
||||
printf("t_capture: %d checks, %d failed\n", checks, failed);
|
||||
return failed != 0;
|
||||
|
||||
@@ -16,6 +16,8 @@ static int observed_mutex_lock(pthread_mutex_t *mutex);
|
||||
#define mtl_set_queue_origin_lower_left test_queue_origin
|
||||
#define mtl_sub_index test_sub_index
|
||||
#define mtl_exec_rest test_exec_rest
|
||||
#define mtl_exec test_exec
|
||||
#define mtl_set_frame test_set_frame
|
||||
#define mtl_drain test_drain
|
||||
#include "../nvn/hle_nvn.c"
|
||||
#undef pthread_mutex_lock
|
||||
@@ -26,6 +28,8 @@ static int observed_mutex_lock(pthread_mutex_t *mutex);
|
||||
#undef mtl_set_queue_origin_lower_left
|
||||
#undef mtl_sub_index
|
||||
#undef mtl_exec_rest
|
||||
#undef mtl_exec
|
||||
#undef mtl_set_frame
|
||||
#undef mtl_drain
|
||||
|
||||
module_t *g_mod; int g_nmod;
|
||||
@@ -34,7 +38,7 @@ module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000000000ull + t.tv_nsec; }
|
||||
|
||||
static dispatch_semaphore_t preparing, second_waiting, finish_prepare, prepared, suspended, returned;
|
||||
static dispatch_semaphore_t preparing, second_waiting, finish_prepare, prepared, suspended, returned, committed;
|
||||
static __thread int second_submit;
|
||||
static _Atomic int prepares, commits, drains;
|
||||
static int inflight_in_prepare, host_work_in_prepare, inflight_at_serial_wait, host_work_at_serial_wait;
|
||||
@@ -57,17 +61,21 @@ void test_prepare(void) { // the first submission's prepare step
|
||||
dispatch_semaphore_signal(prepared);
|
||||
}
|
||||
void test_sub_begin(void) {}
|
||||
uint64_t test_sub_commit(void) { atomic_fetch_add(&commits, 1); return 0; }
|
||||
uint64_t test_sub_commit(void) { atomic_fetch_add(&commits, 1); dispatch_semaphore_signal(committed); return 0; }
|
||||
void test_queue_activate(uint64_t serial) { (void)serial; }
|
||||
void test_queue_origin(int on) { (void)on; }
|
||||
void test_sub_index(const uint64_t *handles, int count) { (void)handles; (void)count; }
|
||||
void test_exec_rest(const uint64_t *handles, int count) { (void)handles; (void)count; }
|
||||
void test_exec(const uint8_t *commands) { (void)commands; }
|
||||
void test_set_frame(uint64_t frame) { (void)frame; }
|
||||
void test_drain(void) { atomic_fetch_add(&drains, 1); }
|
||||
|
||||
static NVNqueue queues[2];
|
||||
static const op_hdr work[] = {{OP_BEGIN, 8}, {OP_END, 8}};
|
||||
static void *submit(void *which) {
|
||||
second_submit = which != NULL;
|
||||
h_nvnQueueSubmitCommands(&queues[second_submit], 0, NULL);
|
||||
NVNcommandHandle handle = (uintptr_t)work;
|
||||
h_nvnQueueSubmitCommands(&queues[second_submit], 1, &handle);
|
||||
dispatch_semaphore_signal(returned);
|
||||
return NULL;
|
||||
}
|
||||
@@ -85,6 +93,9 @@ int main(void) {
|
||||
preparing = dispatch_semaphore_create(0); second_waiting = dispatch_semaphore_create(0);
|
||||
finish_prepare = dispatch_semaphore_create(0); prepared = dispatch_semaphore_create(0);
|
||||
suspended = dispatch_semaphore_create(0); returned = dispatch_semaphore_create(0);
|
||||
committed = dispatch_semaphore_create(0);
|
||||
NVNqueueBuilder qb = {0}; h_nvnQueueBuilderSetDefaults(&qb);
|
||||
h_nvnQueueInitialize(&queues[0], &qb); h_nvnQueueInitialize(&queues[1], &qb);
|
||||
pthread_t first, second, background;
|
||||
pthread_create(&first, NULL, submit, NULL);
|
||||
if (!reached(preparing, "the first submission prepares")) return 1;
|
||||
@@ -101,13 +112,37 @@ int main(void) {
|
||||
CHECK("suspend drains graphics once", atomic_load(&drains) == 1);
|
||||
dispatch_semaphore_signal(finish_prepare);
|
||||
if (!reached(prepared, "the prepare step finishes in the background")) return 1;
|
||||
CHECK("no submission returns while graphics are suspended", dispatch_semaphore_wait(returned, dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC)) != 0);
|
||||
// Submit now owns a queued continuation and may return before GPU replay.
|
||||
// Suspension constrains replay, not whether the guest has enqueued work.
|
||||
CHECK("queued work stays outside the GPU while suspended", dispatch_semaphore_wait(committed, dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC)) != 0);
|
||||
CHECK("no submission commits while graphics are suspended", atomic_load(&commits) == 0);
|
||||
dm_gfx_suspend(0);
|
||||
if (!reached(returned, "a submission returns after resume") || !reached(returned, "both submissions return after resume")) return 1;
|
||||
pthread_join(first, NULL); pthread_join(second, NULL);
|
||||
if (!reached(committed, "first queued submission commits after resume") || !reached(committed, "second queued submission commits after resume")) return 1;
|
||||
CHECK("both submissions commit", atomic_load(&commits) == 2);
|
||||
h_nvnQueueFinish(&queues[0]); h_nvnQueueFinish(&queues[1]);
|
||||
CHECK("graphics entries are balanced", g_inflight_api == 0);
|
||||
|
||||
// An unencoded wait must not make suspend wait for a future producer.
|
||||
// Releasing that event in the background must still respect the closed gate.
|
||||
_Atomic uint32_t word = 0;
|
||||
struct { op_hdr wait; volatile uint32_t *word; uint32_t mode, value; op_hdr begin, end; } parked = {
|
||||
{OP_WAIT_EVENT, 24}, (volatile uint32_t *)&word, 0, 1, {OP_BEGIN, 8}, {OP_END, 8}
|
||||
};
|
||||
NVNcommandHandle parked_handle = (uintptr_t)&parked;
|
||||
h_nvnQueueSubmitCommands(&queues[0], 1, &parked_handle);
|
||||
pthread_create(&background, NULL, suspend_graphics, NULL);
|
||||
if (!reached(suspended, "suspend returns with an unresolved queue event")) return 1;
|
||||
pthread_join(background, NULL);
|
||||
nvn_event_publish((volatile uint32_t *)&word, NVN_EVENT_SIGNAL_MODE_WRITE, 1);
|
||||
CHECK("an event release cannot submit GPU work in the background", dispatch_semaphore_wait(committed, dispatch_time(DISPATCH_TIME_NOW, 200 * NSEC_PER_MSEC)) != 0);
|
||||
dm_gfx_suspend(0);
|
||||
if (!reached(committed, "the released continuation commits after resume")) return 1;
|
||||
h_nvnQueueFinish(&queues[0]);
|
||||
CHECK("exactly the three intended command prefixes committed", atomic_load(&commits) == 3);
|
||||
CHECK("resume leaves the graphics gate balanced", g_inflight_api == 0);
|
||||
h_nvnQueueFinalize(&queues[0]); h_nvnQueueFinalize(&queues[1]);
|
||||
printf("graphics suspend: %d checks, %d failed\n", checks, failures);
|
||||
return failures != 0;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Native DrawMeshTasks has no fallback when its pipeline is missing. Its very first
|
||||
// submission must draw, including task payloads and programs with no fragment stage.
|
||||
#define nvn_game_fps nvn_game_fps_mtl_default
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
#undef nvn_game_fps
|
||||
#define g_ft g_ft_hle
|
||||
#include "../nvn/hle_nvn.c"
|
||||
#undef g_ft
|
||||
#define P(name) ((NVNT_##name)nvn_lookup(#name))
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t *g_mod; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int checks, failures;
|
||||
#define CHECK(c, name) do { int check_ok = !!(c); checks++; failures += !check_ok; if (!check_ok) fprintf(stderr, "FAIL: %s\n", name); } while (0)
|
||||
static void require(int ok, const char *name) { CHECK(ok, name); if (!ok) exit(2); }
|
||||
|
||||
static NvShader *shader(id<MTLLibrary> library, NSString *name, int stage) {
|
||||
NvShader *s = [NvShader new]; s->fn = [library newFunctionWithName:name]; s->stage = stage;
|
||||
snprintf(s->key, sizeof s->key, "first_use_%s", name.UTF8String);
|
||||
require(s->fn != nil, "test shader function exists"); return s;
|
||||
}
|
||||
int main(void) { @autoreleasepool {
|
||||
mtl_init(); NSError *error = nil;
|
||||
id<MTLLibrary> library = [g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;\n"
|
||||
"struct V { float4 position [[position]]; }; struct Payload { uint first; };\n"
|
||||
"using Mesh = metal::mesh<V, void, 3, 1, metal::topology::triangle>;\n"
|
||||
"void triangle(Mesh m, uint first) { float z = float(first) * 0.125f;\n"
|
||||
" m.set_vertex(0, V{float4(-1,-1,z,1)}); m.set_vertex(1, V{float4(3,-1,z,1)}); m.set_vertex(2, V{float4(-1,3,z,1)});\n"
|
||||
" m.set_index(0,0); m.set_index(1,1); m.set_index(2,2); m.set_primitive_count(1); }\n"
|
||||
"[[mesh]] void direct(Mesh m, uint tid [[thread_index_in_threadgroup]], constant uint& first [[buffer(29)]]) { if (!tid) triangle(m, first); }\n"
|
||||
"[[object]] void task(object_data Payload& p [[payload]], mesh_grid_properties grid, uint tid [[thread_index_in_threadgroup]], constant uint& first [[buffer(29)]]) {\n"
|
||||
" if (!tid) { p.first = first; grid.set_threadgroups_per_grid(uint3(1)); } }\n"
|
||||
"[[mesh]] void tasked(Mesh m, const object_data Payload& p [[payload]], uint tid [[thread_index_in_threadgroup]]) { if (!tid) triangle(m, p.first); }\n"
|
||||
"vertex float4 vertex_only(uint vid [[vertex_id]]) { const float2 p[] = {float2(-1,-1),float2(3,-1),float2(-1,3)}; return float4(p[vid % 3], float(vid / 3 + 1) * 0.125f, 1); }\n"
|
||||
"fragment float4 color() { return float4(0,1,0,1); }\n"
|
||||
options:nil error:&error];
|
||||
if (!library) fprintf(stderr, "%s\n", error.localizedDescription.UTF8String);
|
||||
require(library != nil, "synthetic task and mesh shaders compile");
|
||||
NvShader *ms = shader(library, @"direct", 4), *tasked = shader(library, @"tasked", 4), *ts = shader(library, @"task", 3), *fs = shader(library, @"color", 1);
|
||||
NvShader *vs = shader(library, @"vertex_only", 0);
|
||||
ms->mesh_kind = tasked->mesh_kind = 2; ms->mesh_notask = 1;
|
||||
ms->mesh_threads = tasked->mesh_threads = ts->mesh_threads = 32; ts->mesh_kind = 1; ts->mesh_payload = 4; fs->rf.color_mask = 1;
|
||||
prog_t programs[4] = {0};
|
||||
for (int kind = 0; kind < 4; kind++) {
|
||||
NvProg *p = [NvProg new]; p->sh[0] = kind == 3 ? vs : nil; p->sh[4] = kind == 3 ? nil : kind ? tasked : ms;
|
||||
p->sh[3] = kind == 1 || kind == 2 ? ts : nil; p->sh[1] = kind == 2 ? nil : fs;
|
||||
programs[kind].magic = MAGIC('P','R','O','G'); programs[kind].serial = nvn_new_serial(); serial_put(programs[kind].serial, p);
|
||||
}
|
||||
NVNdevice device; NVNdeviceBuilder db = {0}; P(nvnDeviceBuilderSetDefaults)(&db);
|
||||
require(P(nvnDeviceInitialize)(&device, &db), "device initialized");
|
||||
NVNqueue queue; NVNqueueBuilder qb = {0}; P(nvnQueueBuilderSetDefaults)(&qb); P(nvnQueueBuilderSetDevice)(&qb, &device);
|
||||
require(P(nvnQueueInitialize)(&queue, &qb), "queue initialized");
|
||||
uint8_t *memory = NULL; require(!posix_memalign((void **)&memory, getpagesize(), 65536), "command storage allocated"); memset(memory, 0, 65536);
|
||||
NVNmemoryPool pool; NVNmemoryPoolBuilder pb = {0}; P(nvnMemoryPoolBuilderSetDefaults)(&pb); P(nvnMemoryPoolBuilderSetDevice)(&pb, &device);
|
||||
P(nvnMemoryPoolBuilderSetStorage)(&pb, memory, 65536); P(nvnMemoryPoolBuilderSetFlags)(&pb, 0x24);
|
||||
require(P(nvnMemoryPoolInitialize)(&pool, &pb), "command memory pool initialized");
|
||||
NVNcommandBuffer command; require(P(nvnCommandBufferInitialize)(&command, &device), "command buffer initialized");
|
||||
P(nvnCommandBufferAddCommandMemory)(&command, &pool, 0, 65536);
|
||||
typedef void (*DrawMeshTasks)(NVNcommandBuffer *, int, int);
|
||||
DrawMeshTasks draw = (DrawMeshTasks)nvn_lookup("nvnCommandBufferDrawMeshTasks"); require(draw != NULL, "native DrawMeshTasks entry point exists");
|
||||
enum { W = 8, H = 8 };
|
||||
tex_t color = {.magic = MAGIC('T','E','X',0), .serial = nvn_new_serial()}, depth = {.magic = MAGIC('T','E','X',0), .serial = nvn_new_serial()};
|
||||
color.d = (nvn_texdesc){.target = NVN_TEXTURE_TARGET_2D, .format = NVN_FORMAT_RGBA8, .width = W, .height = H, .depth = 1, .levels = 1, .samples = 1};
|
||||
depth.d = color.d; depth.d.format = NVN_FORMAT_DEPTH32F;
|
||||
NVNdepthStencilState ds; P(nvnDepthStencilStateSetDefaults)(&ds); P(nvnDepthStencilStateSetDepthTestEnable)(&ds, 1);
|
||||
P(nvnDepthStencilStateSetDepthWriteEnable)(&ds, 1); P(nvnDepthStencilStateSetDepthFunc)(&ds, NVN_DEPTH_FUNC_LESS);
|
||||
const NVNtexture *colors[] = {(const NVNtexture *)&color}; const float viewport[] = {0, 0, W, H}, blue[] = {0, 0, 1, 1};
|
||||
for (int kind = 0; kind < 4; kind++) for (int pass = 0; pass < 2; pass++) {
|
||||
printf("%s, %s pipeline\n", kind == 0 ? "mesh only" : kind == 1 ? "task and mesh" : kind == 2 ? "depth only" : "ordinary vertex", pass ? "cached" : "first use");
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferSetRenderTargets)(&command, kind == 2 ? 0 : 1, colors, NULL, (const NVNtexture *)&depth, NULL);
|
||||
P(nvnCommandBufferSetViewports)(&command, 0, 1, viewport); P(nvnCommandBufferSetScissor)(&command, 0, 0, W, H);
|
||||
P(nvnCommandBufferSetDepthRange)(&command, 0, 1); P(nvnCommandBufferBindDepthStencilState)(&command, &ds);
|
||||
P(nvnCommandBufferClearDepthStencil)(&command, 1, 1, 0, 0);
|
||||
if (kind != 2) P(nvnCommandBufferClearColor)(&command, 0, blue, 15);
|
||||
P(nvnCommandBufferBindProgram)(&command, (const NVNprogram *)&programs[kind], 0xc3);
|
||||
if (kind == 3) P(nvnCommandBufferDrawArrays)(&command, NVN_DRAW_PRIMITIVE_TRIANGLES, pass * 3, 3);
|
||||
else draw(&command, pass + 1, 1);
|
||||
NVNcommandHandle handle = P(nvnCommandBufferEndRecording)(&command);
|
||||
P(nvnQueueSubmitCommands)(&queue, 1, &handle); P(nvnQueueFinish)(&queue);
|
||||
id<MTLBuffer> pixels = [g_dev newBufferWithLength:W * H * 8 options:MTLResourceStorageModeShared]; res_add(pixels);
|
||||
mtl_sub_begin();
|
||||
enc_b_copy_texture_buffer(blit(), tex_mtl(&depth), 0, 0, MTLOriginMake(0,0,0), MTLSizeMake(W,H,1), pixels, 0, W * 4, W * H * 4);
|
||||
if (kind != 2) enc_b_copy_texture_buffer(blit(), tex_mtl(&color), 0, 0, MTLOriginMake(0,0,0), MTLSizeMake(W,H,1), pixels, W * H * 4, W * 4, W * H * 4);
|
||||
require(mtl_wait(mtl_sub_commit(), 5000000000ull), "readback finishes"); CHECK(!mtl_last_commit_error(), "Metal reports no execution error");
|
||||
const float *z = pixels.contents; int good_depth = 1, good_color = 1;
|
||||
const uint8_t green[] = {0, 255, 0, 255};
|
||||
for (int i = 0; i < W * H; i++) {
|
||||
good_depth &= z[i] == (pass + 1) * 0.125f;
|
||||
if (kind != 2) good_color &= !memcmp((const uint8_t *)pixels.contents + W * H * 4 + i * 4, green, 4);
|
||||
}
|
||||
CHECK(good_depth, "this submission writes every expected depth pixel");
|
||||
if (kind != 2) CHECK(good_color, "this submission draws every expected color pixel");
|
||||
res_remove(pixels);
|
||||
}
|
||||
P(nvnQueueFinish)(&queue); mtl_drain();
|
||||
P(nvnCommandBufferFinalize)(&command); mtl_tex_release(&color); mtl_tex_release(&depth);
|
||||
P(nvnMemoryPoolFinalize)(&pool); free(memory); P(nvnQueueFinalize)(&queue); P(nvnDeviceFinalize)(&device);
|
||||
printf("mesh first use: %d checks, %d failed\n", checks, failures); return failures != 0;
|
||||
} }
|
||||
+16
-4
@@ -892,7 +892,7 @@ int main(void) {
|
||||
P(nvnMemoryPoolFinalize)(&mp);
|
||||
}
|
||||
|
||||
// 6d. Lifecycle: in-flight GPU work is 0 when suspend returns; submits are blocked during suspend and let through after resume
|
||||
// 6d. Lifecycle: in-flight GPU work is 0 when suspend returns; queued replay waits for resume.
|
||||
{
|
||||
size_t big = 64u << 20; uint8_t *heap; posix_memalign((void **)&heap, 16384, 2 * big); memset(heap, 0, 2 * big);
|
||||
NVNmemoryPoolBuilder hb; NVNmemoryPool hp; P(nvnMemoryPoolBuilderSetDefaults)(&hb); P(nvnMemoryPoolBuilderSetStorage)(&hb, heap, 2 * big);
|
||||
@@ -901,20 +901,32 @@ int main(void) {
|
||||
for (int i = 0; i < 24; i++) P(nvnCommandBufferCopyBufferToBuffer)(&cb, (NVNbufferAddress)heap, (NVNbufferAddress)(heap + big), big, 0);
|
||||
NVNcommandHandle hbusy = P(nvnCommandBufferEndRecording)(&cb);
|
||||
P(nvnQueueSubmitCommands)(&q, 1, &hbusy);
|
||||
uint64_t f = mtl_last_fence();
|
||||
NVNsync busy_sync; P(nvnSyncInitialize)(&busy_sync, &dev);
|
||||
P(nvnQueueFenceSync)(&q, &busy_sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
// Submit may return before the worker encodes anything. Observe this
|
||||
// queue's receipt before checking its physical GPU completion.
|
||||
uint64_t f = 0; int encoded = 0; struct timespec deadline;
|
||||
clock_gettime(CLOCK_REALTIME, &deadline); deadline.tv_sec += 5;
|
||||
pthread_mutex_lock(&nq_mu);
|
||||
while (!(encoded = nq_sync_encoded((const sync_t *)&busy_sync, &f)))
|
||||
if (pthread_cond_timedwait(&nq_cv, &nq_mu, &deadline)) break;
|
||||
pthread_mutex_unlock(&nq_mu);
|
||||
EXPECT("busy submission receives its own physical fence", 1, encoded);
|
||||
int busy_before = !mtl_wait(f, 0);
|
||||
dm_gfx_suspend(1);
|
||||
EXPECT("GPU really busy before suspend (zero-timeout wait not complete)", 1, busy_before);
|
||||
EXPECT("in-flight work complete when suspend returns", 1, mtl_wait(f, 0));
|
||||
P(nvnCommandBufferBeginRecording)(&cb); P(nvnCommandBufferBarrier)(&cb, 0); NVNcommandHandle hsmall = P(nvnCommandBufferEndRecording)(&cb);
|
||||
uint64_t suspended_fence = mtl_last_fence();
|
||||
g_sq = &q; g_sh = hsmall; g_sub = P(nvnQueueSubmitCommands); atomic_store(&g_sstarted, 0); atomic_store(&g_sdone, 0);
|
||||
pthread_t th; pthread_create(&th, NULL, susp_thr, NULL);
|
||||
int started = wait_started();
|
||||
EXPECT("during suspend another thread entered submit and has not returned", 1, started && !atomic_load(&g_sdone));
|
||||
EXPECT("during suspend another thread enters submit", 1, started);
|
||||
EXPECT("background submission has not reached the GPU", suspended_fence, mtl_last_fence());
|
||||
dm_gfx_suspend(0);
|
||||
pthread_join(th, NULL);
|
||||
EXPECT("that submit is let through and returns after resume", 1, atomic_load(&g_sdone));
|
||||
P(nvnQueueFinish)(&q); P(nvnMemoryPoolFinalize)(&hp); free(heap);
|
||||
P(nvnQueueFinish)(&q); P(nvnSyncFinalize)(&busy_sync); P(nvnMemoryPoolFinalize)(&hp); free(heap);
|
||||
}
|
||||
|
||||
// 6e. Present pacing (real-device semantics): present returns immediately; blocking happens at acquire - swapchain of 3, interval 1, 60 Hz, the 4th acquire waits until texture 0 has been displayed for a full period
|
||||
|
||||
@@ -12,6 +12,15 @@ void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int checks, failed;
|
||||
#define CHECK(name, ok) do { int pass = !!(ok); checks++; failed += !pass; printf("%s: %s\n", name, pass ? "PASS" : "FAIL"); } while (0)
|
||||
static NVNdevice fixture_device;
|
||||
static NVNqueue fixture_queue;
|
||||
static void queue_encoded(void) {
|
||||
NVNsync sync; h_nvnSyncInitialize(&sync, &fixture_device);
|
||||
h_nvnQueueFenceSync(&fixture_queue, &sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
NVNsyncWaitResult result = h_nvnSyncWait(&sync, 2000000000ull);
|
||||
CHECK("queued present reaches physical encoding", result == NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED || result == NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED);
|
||||
h_nvnSyncFinalize(&sync);
|
||||
}
|
||||
static tex_t source_n(unsigned i, int n) { // n x n texels of 73 + i (n at most 16)
|
||||
MTLTextureDescriptor *d = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:n height:n mipmapped:NO];
|
||||
d.storageMode = MTLStorageModeShared; d.usage = MTLTextureUsageShaderRead;
|
||||
@@ -73,23 +82,26 @@ static void pacing_case(void) {
|
||||
for (int i = 0; i < 4; i++) { textures[i] = source(i); win.tex[i] = (NVNtexture *)&textures[i]; }
|
||||
// Several acquires can precede their presents. A full snapshot ring must fall back to texture tickets.
|
||||
for (int i = 0; i < 4; i++) h_nvnWindowAcquireTexture((NVNwindow *)&win, NULL, &indices[i]);
|
||||
mtl_present_test_stall(150000000); double longest = 0;
|
||||
mtl_present_test_stall(150000000); double longest = 0; uint64_t copies = g_snap_v;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
uint64_t start = now_ns(); h_nvnQueuePresentTexture(NULL, (NVNwindow *)&win, indices[i]);
|
||||
uint64_t start = now_ns(); h_nvnQueuePresentTexture(&fixture_queue, (NVNwindow *)&win, indices[i]);
|
||||
double ms = (now_ns() - start) / 1e6; if (ms > longest) longest = ms;
|
||||
printf("present %d: %.3f ms, ticket %llu\n", i, ms, (unsigned long long)win.ticket[indices[i]]);
|
||||
}
|
||||
CHECK("present does not wait for the stalled display", longest < 50);
|
||||
CHECK("full ring uses the original texture ticket", win.ticket[indices[2]] != 0 && win.ticket[indices[3]] != 0);
|
||||
// Window tickets now own logical queue receipts even for snapshots. Wait
|
||||
// until the queue has encoded them and observe actual copies, not receipt IDs.
|
||||
queue_encoded();
|
||||
CHECK("full ring copies only its two available snapshot slots", g_snap_v == copies + 2);
|
||||
uint64_t start = now_ns(); int idx; h_nvnWindowAcquireTexture((NVNwindow *)&win, NULL, &idx);
|
||||
double ms = (now_ns() - start) / 1e6; printf("acquire: %.3f ms\n", ms);
|
||||
CHECK("acquire waits for snapshot capacity", ms >= 50);
|
||||
h_nvnQueuePresentTexture(NULL, (NVNwindow *)&win, idx);
|
||||
CHECK("snapshot resumes after acquire frees capacity", win.ticket[idx] == 0);
|
||||
copies = g_snap_v; h_nvnQueuePresentTexture(&fixture_queue, (NVNwindow *)&win, idx); queue_encoded();
|
||||
CHECK("snapshot resumes after acquire frees capacity", g_snap_v == copies + 1);
|
||||
mtl_present_flush(); mtl_present_test_stall(0);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
h_nvnWindowAcquireTexture((NVNwindow *)&win, NULL, &idx);
|
||||
h_nvnQueuePresentTexture(NULL, (NVNwindow *)&win, idx);
|
||||
h_nvnQueuePresentTexture(&fixture_queue, (NVNwindow *)&win, idx); queue_encoded();
|
||||
mtl_present_flush(); snap_commit_wait(g_snap_v);
|
||||
CHECK("reused snapshot completed", [g_snap_ev waitUntilSignaledValue:g_snap_v timeoutMS:2000]);
|
||||
int slot = (g_snap_next - 1) % g_snap_n; pixels(g_snap[slot].tex, 73 + idx);
|
||||
@@ -137,15 +149,68 @@ static void resize_case(void) {
|
||||
snap_present(&big);
|
||||
CHECK("slot 1's old texture leaves at its next use", ![g_snap_res containsAllocation:old1] && !g_snap[1].old);
|
||||
}
|
||||
typedef struct { win_t *window; int index; dispatch_semaphore_t started, done; } acquire_job;
|
||||
static void *acquire_thread(void *arg) { @autoreleasepool {
|
||||
acquire_job *job = arg; dispatch_semaphore_signal(job->started);
|
||||
h_nvnWindowAcquireTexture((NVNwindow *)job->window, NULL, &job->index);
|
||||
dispatch_semaphore_signal(job->done);
|
||||
} return NULL; }
|
||||
static void queued_case(void) {
|
||||
uint8_t *memory = NULL; if (posix_memalign((void **)&memory, getpagesize(), 65536)) exit(2); memset(memory, 0, 65536);
|
||||
NVNmemoryPool pool; NVNmemoryPoolBuilder pb = {0}; h_nvnMemoryPoolBuilderSetDefaults(&pb); h_nvnMemoryPoolBuilderSetDevice(&pb, &fixture_device);
|
||||
h_nvnMemoryPoolBuilderSetStorage(&pb, memory, 65536); h_nvnMemoryPoolBuilderSetFlags(&pb, 0x24);
|
||||
CHECK("event pool initialized", h_nvnMemoryPoolInitialize(&pool, &pb));
|
||||
NVNevent event; NVNeventBuilder eb = {0}; h_nvnEventBuilderSetDefaults(&eb); h_nvnEventBuilderSetStorage(&eb, &pool, 32768);
|
||||
CHECK("event initialized", h_nvnEventInitialize(&event, &eb));
|
||||
NVNcommandBuffer command; h_nvnCommandBufferInitialize(&command, &fixture_device); h_nvnCommandBufferAddCommandMemory(&command, &pool, 0, 32768);
|
||||
h_nvnCommandBufferBeginRecording(&command); h_nvnCommandBufferWaitEvent(&command, &event, NVN_EVENT_WAIT_MODE_EQUAL, 1);
|
||||
NVNcommandHandle handle = h_nvnCommandBufferEndRecording(&command);
|
||||
tex_t texture = source(0); id<MTLTexture> original = serial_get(texture.serial); // retain the original GPU backing throughout descriptor reuse
|
||||
win_t win = {.ntex = 1}; win.tex[0] = (NVNtexture *)&texture;
|
||||
int index; h_nvnWindowAcquireTexture((NVNwindow *)&win, NULL, &index);
|
||||
dispatch_semaphore_t cancel = dispatch_semaphore_create(0), rescued = dispatch_semaphore_create(0);
|
||||
NVNevent *event_ptr = &event;
|
||||
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
|
||||
if (dispatch_semaphore_wait(cancel, dispatch_time(DISPATCH_TIME_NOW, 5000000000ll))) h_nvnEventSignal(event_ptr, NVN_EVENT_SIGNAL_MODE_WRITE, 1);
|
||||
dispatch_semaphore_signal(rescued);
|
||||
});
|
||||
h_nvnQueueSubmitCommands(&fixture_queue, 1, &handle);
|
||||
uint64_t copies = g_snap_v, start = now_ns(); h_nvnQueuePresentTexture(&fixture_queue, (NVNwindow *)&win, index);
|
||||
CHECK("present returns while its queue waits for an event", now_ns() - start < 50000000);
|
||||
acquire_job job = {.window = &win, .started = dispatch_semaphore_create(0), .done = dispatch_semaphore_create(0)};
|
||||
pthread_t thread; if (pthread_create(&thread, NULL, acquire_thread, &job)) { h_nvnEventSignal(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1); exit(2); }
|
||||
dispatch_semaphore_wait(job.started, DISPATCH_TIME_FOREVER);
|
||||
int returned = dispatch_semaphore_wait(job.done, dispatch_time(DISPATCH_TIME_NOW, 100000000ll)) == 0;
|
||||
CHECK("acquire waits for the blocked queued present", !returned);
|
||||
CHECK("no snapshot copy crosses the unresolved event", g_snap_v == copies);
|
||||
h_nvnTextureFinalize((NVNtexture *)&texture); texture = source(100);
|
||||
// source() installs no pool alias or retired-serial cache entry. Finalizing
|
||||
// it removes that lookup; the queued present must retain its own source.
|
||||
h_nvnEventSignal(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1); dispatch_semaphore_signal(cancel);
|
||||
CHECK("event rescue worker retired", dispatch_semaphore_wait(rescued, dispatch_time(DISPATCH_TIME_NOW, 2000000000ll)) == 0);
|
||||
if (!returned) returned = dispatch_semaphore_wait(job.done, dispatch_time(DISPATCH_TIME_NOW, 2000000000ll)) == 0;
|
||||
CHECK("acquire finishes after event release", returned);
|
||||
if (!returned) exit(2); pthread_join(thread, NULL);
|
||||
queue_encoded(); mtl_present_flush(); snap_commit_wait(g_snap_v);
|
||||
CHECK("queued source snapshot completes", [g_snap_ev waitUntilSignaledValue:g_snap_v timeoutMS:2000]);
|
||||
CHECK("queued present produced exactly one snapshot", g_snap_v == copies + 1);
|
||||
pixels(g_snap[(g_snap_next - 1) % g_snap_n].tex, 73); pixels(original, 73);
|
||||
h_nvnWindowFinalize((NVNwindow *)&win); h_nvnQueueFinish(&fixture_queue);
|
||||
h_nvnCommandBufferFinalize(&command); h_nvnEventFinalize(&event); h_nvnMemoryPoolFinalize(&pool); free(memory);
|
||||
}
|
||||
int main(int argc, char **argv) { @autoreleasepool {
|
||||
alarm(15); setbuf(stdout, NULL);
|
||||
if (argc != 2) return 2;
|
||||
setenv("DM_PRESENT_SNAP", "1", 1); setenv("DM_PRESENT_HZ", "0", 1);
|
||||
mtl_init();
|
||||
NVNdeviceBuilder db = {0}; h_nvnDeviceBuilderSetDefaults(&db); CHECK("fixture device initialized", h_nvnDeviceInitialize(&fixture_device, &db));
|
||||
NVNqueueBuilder qb = {0}; h_nvnQueueBuilderSetDefaults(&qb); h_nvnQueueBuilderSetDevice(&qb, &fixture_device);
|
||||
CHECK("fixture queue initialized", h_nvnQueueInitialize(&fixture_queue, &qb));
|
||||
if (!strcmp(argv[1], "suspend")) suspend_case();
|
||||
else if (!strcmp(argv[1], "pacing")) pacing_case();
|
||||
else if (!strcmp(argv[1], "copy")) pending_copy_case();
|
||||
else if (!strcmp(argv[1], "resize")) resize_case();
|
||||
else if (!strcmp(argv[1], "queued")) queued_case();
|
||||
else return 2;
|
||||
printf("present snapshots: %d checks, %d failed\n", checks, failed); return failed != 0;
|
||||
} }
|
||||
@@ -0,0 +1,139 @@
|
||||
// Submitted commands own their CPU descriptors. Pool storage and shader code stay
|
||||
// alive while a wait parks the queue; only program/texture objects are reused.
|
||||
#define nvn_game_fps nvn_game_fps_mtl_default
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
#undef nvn_game_fps
|
||||
#define g_ft g_ft_hle
|
||||
#include "../nvn/hle_nvn.c"
|
||||
#undef g_ft
|
||||
#define P(name) ((NVNT_##name)nvn_lookup(#name))
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t *g_mod; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int checks, failures;
|
||||
#define CHECK(c, name) do { int check_ok = !!(c); checks++; failures += !check_ok; printf("%s: %s\n", check_ok ? "PASS" : "FAIL", name); } while (0)
|
||||
static void require(int ok, const char *name) { CHECK(ok, name); if (!ok) exit(2); }
|
||||
enum { W = 8, H = 8, BYTES = W * H * 4, POOL_BYTES = 1 << 20, TEX_A = 0x80000, TEX_B = 0x90000, OUTPUT = 0xa0000, EVENT = 0xa1000 };
|
||||
static NVNdevice device; static NVNqueue queues[2]; static NVNmemoryPool pool; static NVNcommandBuffer command;
|
||||
static NVNevent event; static NVNtexture target, replacement; static uint8_t *memory; static NVNbufferAddress output;
|
||||
static dispatch_semaphore_t cancel_rescue, rescue_done;
|
||||
static const NVNcopyRegion region = {0, 0, 0, W, H, 1};
|
||||
|
||||
static int landed(NVNsync *sync, uint64_t timeout) {
|
||||
NVNsyncWaitResult r = P(nvnSyncWait)(sync, timeout);
|
||||
return r == NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED || r == NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED;
|
||||
}
|
||||
static void submit(int queue, NVNcommandHandle handle, NVNsync *sync) {
|
||||
P(nvnSyncInitialize)(sync, &device); P(nvnQueueSubmitCommands)(&queues[queue], 1, &handle);
|
||||
// The queue-tail receipt includes retiring this job's CPU descriptors.
|
||||
P(nvnQueueFenceSync)(&queues[queue], sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
}
|
||||
static void finish(NVNsync *sync) {
|
||||
require(landed(sync, 5000000000ull), "queue tail and GPU work complete");
|
||||
P(nvnSyncFinalize)(sync);
|
||||
}
|
||||
static void park(void) {
|
||||
P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 0);
|
||||
cancel_rescue = dispatch_semaphore_create(0); rescue_done = dispatch_semaphore_create(0);
|
||||
dispatch_semaphore_t cancel = cancel_rescue, done = rescue_done;
|
||||
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
|
||||
if (dispatch_semaphore_wait(cancel, dispatch_time(DISPATCH_TIME_NOW, 2000000000ll))) P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1);
|
||||
dispatch_semaphore_signal(done);
|
||||
});
|
||||
}
|
||||
static void release(void) {
|
||||
// Every assertion path releases the event. The watchdog also releases a
|
||||
// broken implementation that blocks QueueSubmitCommands on the CPU.
|
||||
P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1); dispatch_semaphore_signal(cancel_rescue);
|
||||
require(!dispatch_semaphore_wait(rescue_done, dispatch_time(DISPATCH_TIME_NOW, 3000000000ll)), "event rescue worker retired");
|
||||
}
|
||||
static int pixels(unsigned offset, unsigned r, unsigned g, unsigned b) {
|
||||
const uint8_t want[] = {r, g, b, 255};
|
||||
for (int i = 0; i < W * H; i++) if (memcmp(memory + OUTPUT + offset + i * 4, want, 4)) return 0;
|
||||
return 1;
|
||||
}
|
||||
static void init_texture(NVNtexture *texture, unsigned offset) {
|
||||
NVNtextureBuilder tb = {0}; P(nvnTextureBuilderSetDefaults)(&tb); P(nvnTextureBuilderSetDevice)(&tb, &device);
|
||||
P(nvnTextureBuilderSetTarget)(&tb, NVN_TEXTURE_TARGET_2D); P(nvnTextureBuilderSetSize2D)(&tb, W, H);
|
||||
P(nvnTextureBuilderSetFormat)(&tb, NVN_FORMAT_RGBA8); P(nvnTextureBuilderSetStorage)(&tb, &pool, offset);
|
||||
require(P(nvnTextureInitialize)(texture, &tb), "texture initialized on retained backing storage");
|
||||
}
|
||||
static void init_program(NVNprogram *program, NvProg *compiled) {
|
||||
require(P(nvnProgramInitialize)(program, &device), "program object initialized");
|
||||
// Synthetic MSL replaces only game shader loading; recording and submission
|
||||
// use the public NVN entry points and the real serial ownership table.
|
||||
prog_t *p = (prog_t *)program; p->serial = nvn_new_serial(); serial_put(p->serial, compiled);
|
||||
}
|
||||
static NVNcommandHandle record(NVNtexture *texture, NVNprogram *program, int wait, int draw, unsigned offset) {
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
if (wait) P(nvnCommandBufferWaitEvent)(&command, &event, NVN_EVENT_WAIT_MODE_EQUAL, 1);
|
||||
const NVNtexture *colors[] = {texture}; const float viewport[] = {0, 0, W, H}, blue[] = {0, 0, 1, 1};
|
||||
P(nvnCommandBufferSetRenderTargets)(&command, 1, colors, NULL, NULL, NULL);
|
||||
P(nvnCommandBufferSetViewports)(&command, 0, 1, viewport); P(nvnCommandBufferSetScissor)(&command, 0, 0, W, H);
|
||||
P(nvnCommandBufferClearColor)(&command, 0, blue, 15);
|
||||
if (program) P(nvnCommandBufferBindProgram)(&command, program, 3);
|
||||
if (draw) P(nvnCommandBufferDrawArrays)(&command, NVN_DRAW_PRIMITIVE_TRIANGLES, 0, 3);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command, texture, NULL, ®ion, output + offset, 0);
|
||||
return P(nvnCommandBufferEndRecording)(&command);
|
||||
}
|
||||
int main(void) { @autoreleasepool {
|
||||
setbuf(stdout, NULL); mtl_init(); NSError *error = nil;
|
||||
id<MTLLibrary> library = [g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;\n"
|
||||
"vertex float4 v(uint i [[vertex_id]]) { const float2 p[] = {float2(-1,-1),float2(3,-1),float2(-1,3)}; return float4(p[i],0.5,1); }\n"
|
||||
"fragment float4 red() { return float4(1,0,0,1); } fragment float4 green() { return float4(0,1,0,1); }\n"
|
||||
options:nil error:&error];
|
||||
if (!library) fprintf(stderr, "%s\n", error.localizedDescription.UTF8String);
|
||||
require(library != nil, "synthetic shaders compile");
|
||||
NvShader *vs = [NvShader new]; vs->fn = [library newFunctionWithName:@"v"];
|
||||
NvProg *red = [NvProg new], *green = [NvProg new]; red->sh[0] = green->sh[0] = vs;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
NvShader *fs = [NvShader new]; fs->stage = 1; fs->rf.color_mask = 1; fs->fn = [library newFunctionWithName:i ? @"green" : @"red"];
|
||||
(i ? green : red)->sh[1] = fs;
|
||||
}
|
||||
NVNdeviceBuilder db = {0}; P(nvnDeviceBuilderSetDefaults)(&db); require(P(nvnDeviceInitialize)(&device, &db), "device initialized");
|
||||
for (int i = 0; i < 2; i++) { NVNqueueBuilder qb = {0}; P(nvnQueueBuilderSetDefaults)(&qb); P(nvnQueueBuilderSetDevice)(&qb, &device); require(P(nvnQueueInitialize)(&queues[i], &qb), "queue initialized"); }
|
||||
require(!posix_memalign((void **)&memory, getpagesize(), POOL_BYTES), "pool storage allocated"); memset(memory, 0, POOL_BYTES);
|
||||
NVNmemoryPoolBuilder pb = {0}; P(nvnMemoryPoolBuilderSetDefaults)(&pb); P(nvnMemoryPoolBuilderSetDevice)(&pb, &device);
|
||||
P(nvnMemoryPoolBuilderSetStorage)(&pb, memory, POOL_BYTES); P(nvnMemoryPoolBuilderSetFlags)(&pb, 0x24); require(P(nvnMemoryPoolInitialize)(&pool, &pb), "pool initialized");
|
||||
NVNbufferBuilder bb = {0}; NVNbuffer buffer; P(nvnBufferBuilderSetDefaults)(&bb); P(nvnBufferBuilderSetDevice)(&bb, &device);
|
||||
P(nvnBufferBuilderSetStorage)(&bb, &pool, OUTPUT, BYTES * 2); require(P(nvnBufferInitialize)(&buffer, &bb), "readback buffer initialized"); output = P(nvnBufferGetAddress)(&buffer);
|
||||
NVNeventBuilder eb = {0}; P(nvnEventBuilderSetDefaults)(&eb); P(nvnEventBuilderSetStorage)(&eb, &pool, EVENT); require(P(nvnEventInitialize)(&event, &eb), "event initialized");
|
||||
require(P(nvnCommandBufferInitialize)(&command, &device), "command buffer initialized"); P(nvnCommandBufferAddCommandMemory)(&command, &pool, 0, TEX_A);
|
||||
init_texture(&target, TEX_A); init_texture(&replacement, TEX_B);
|
||||
NVNprogram reused, stable_red, stable_green; init_program(&reused, red); init_program(&stable_red, red); init_program(&stable_green, green);
|
||||
NVNsync sync;
|
||||
submit(0, record(&target, &reused, 0, 1, 0), &sync); finish(&sync); CHECK(pixels(0, 255, 0, 0), "original program draws red before reuse");
|
||||
|
||||
puts("CASE submitted program object reused behind an event");
|
||||
park(); memset(memory + OUTPUT, 0x5a, BYTES);
|
||||
submit(0, record(&target, &reused, 1, 1, 0), &sync);
|
||||
CHECK(!landed(&sync, 100000000ull), "submitted draw is still parked before object reuse");
|
||||
P(nvnProgramFinalize)(&reused); init_program(&reused, green);
|
||||
release(); finish(&sync); CHECK(pixels(0, 255, 0, 0), "parked draw retains its original red program");
|
||||
submit(0, record(&target, &reused, 0, 1, 0), &sync); finish(&sync); CHECK(pixels(0, 0, 255, 0), "later bind sees the reused green program object");
|
||||
|
||||
puts("CASE bound program survives retiring its owning job");
|
||||
submit(0, record(&target, &stable_red, 0, 1, 0), &sync); finish(&sync); CHECK(pixels(0, 255, 0, 0), "job A binds and draws red");
|
||||
submit(1, record(&target, &stable_green, 0, 1, 0), &sync); finish(&sync); CHECK(pixels(0, 0, 255, 0), "another queue binds and draws green after job A retires");
|
||||
submit(0, record(&target, NULL, 0, 1, 0), &sync); finish(&sync); CHECK(pixels(0, 255, 0, 0), "job B draws with its queue's red program without another bind");
|
||||
|
||||
puts("CASE submitted texture object reused behind an event");
|
||||
submit(0, record(&replacement, NULL, 0, 0, BYTES), &sync); finish(&sync); CHECK(pixels(BYTES, 0, 0, 255), "replacement texture backing starts blue");
|
||||
park(); submit(0, record(&target, &stable_red, 1, 1, 0), &sync);
|
||||
CHECK(!landed(&sync, 100000000ull), "submitted draw is still parked before texture object reuse");
|
||||
P(nvnTextureFinalize)(&target); init_texture(&target, TEX_B);
|
||||
release(); finish(&sync); CHECK(pixels(0, 255, 0, 0), "parked draw and copy retain the original texture descriptor");
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command, &replacement, NULL, ®ion, output + BYTES, 0);
|
||||
submit(0, P(nvnCommandBufferEndRecording)(&command), &sync); finish(&sync);
|
||||
CHECK(pixels(BYTES, 0, 0, 255), "queued draw did not write the replacement texture's backing");
|
||||
|
||||
P(nvnQueueFinish)(&queues[0]); P(nvnQueueFinish)(&queues[1]);
|
||||
P(nvnProgramFinalize)(&reused); P(nvnProgramFinalize)(&stable_red); P(nvnProgramFinalize)(&stable_green);
|
||||
P(nvnTextureFinalize)(&target); P(nvnTextureFinalize)(&replacement); P(nvnCommandBufferFinalize)(&command);
|
||||
P(nvnBufferFinalize)(&buffer); P(nvnEventFinalize)(&event); P(nvnMemoryPoolFinalize)(&pool);
|
||||
P(nvnQueueFinalize)(&queues[0]); P(nvnQueueFinalize)(&queues[1]); P(nvnDeviceFinalize)(&device); free(memory);
|
||||
printf("queue lifetime: %d checks, %d failed\n", checks, failures); return failures != 0;
|
||||
} }
|
||||
@@ -0,0 +1,147 @@
|
||||
// Later explicit writes replace pending query values at conditional rendering.
|
||||
// Public NVN commands exercise the predicate; a bounded Metal gate holds reports
|
||||
// unfinished. OPEN diagnostics separately expose pre-existing CPU-post query
|
||||
// byte ordering; passing this test does not claim native GPU report bytes work.
|
||||
#define nvn_game_fps nvn_game_fps_mtl_default
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
#undef nvn_game_fps
|
||||
#define g_ft g_ft_hle
|
||||
#include "../nvn/hle_nvn.c"
|
||||
#undef g_ft
|
||||
#define P(name) ((NVNT_##name)nvn_lookup(#name))
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t *g_mod; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int checks, failures;
|
||||
#define CHECK(c, name) do { int check_ok = !!(c); checks++; failures += !check_ok; printf("%s: %s\n", check_ok ? "PASS" : "FAIL", name); } while (0)
|
||||
static void require(int ok, const char *name) { CHECK(ok, name); if (!ok) exit(2); }
|
||||
enum { W = 8, H = 8, BYTES = W * H * 4, POOL_BYTES = 1 << 20, TEX_A = 0x80000, TEX_B = 0x90000, OUTPUT = 0xa0000, EVENT = 0xa1000 };
|
||||
static NVNdevice device; static NVNqueue queues[2]; static NVNmemoryPool pool; static NVNcommandBuffer command;
|
||||
static NVNevent event; static NVNtexture target, replacement; static uint8_t *memory; static NVNbufferAddress output;
|
||||
static const NVNcopyRegion region = {0, 0, 0, W, H, 1};
|
||||
|
||||
static int landed(NVNsync *sync, uint64_t timeout) {
|
||||
NVNsyncWaitResult r = P(nvnSyncWait)(sync, timeout);
|
||||
return r == NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED || r == NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED;
|
||||
}
|
||||
static void submit(int queue, NVNcommandHandle handle, NVNsync *sync) {
|
||||
P(nvnSyncInitialize)(sync, &device); P(nvnQueueSubmitCommands)(&queues[queue], 1, &handle);
|
||||
P(nvnQueueFenceSync)(&queues[queue], sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
}
|
||||
static void finish(NVNsync *sync) {
|
||||
require(landed(sync, 5000000000ull), "queue tail and GPU work complete");
|
||||
P(nvnSyncFinalize)(sync);
|
||||
}
|
||||
static int pixels(unsigned offset, unsigned r, unsigned g, unsigned b) {
|
||||
const uint8_t want[] = {r, g, b, 255};
|
||||
for (int i = 0; i < W * H; i++) if (memcmp(memory + OUTPUT + offset + i * 4, want, 4)) return 0;
|
||||
return 1;
|
||||
}
|
||||
static void init_texture(NVNtexture *texture, unsigned offset) {
|
||||
NVNtextureBuilder tb = {0}; P(nvnTextureBuilderSetDefaults)(&tb); P(nvnTextureBuilderSetDevice)(&tb, &device);
|
||||
P(nvnTextureBuilderSetTarget)(&tb, NVN_TEXTURE_TARGET_2D); P(nvnTextureBuilderSetSize2D)(&tb, W, H);
|
||||
P(nvnTextureBuilderSetFormat)(&tb, NVN_FORMAT_RGBA8); P(nvnTextureBuilderSetStorage)(&tb, &pool, offset);
|
||||
require(P(nvnTextureInitialize)(texture, &tb), "texture initialized on retained backing storage");
|
||||
}
|
||||
static void init_program(NVNprogram *program, NvProg *compiled) {
|
||||
require(P(nvnProgramInitialize)(program, &device), "program object initialized");
|
||||
// Synthetic MSL replaces only game shader loading; recording and submission
|
||||
// use the public NVN entry points and the real serial ownership table.
|
||||
prog_t *p = (prog_t *)program; p->serial = nvn_new_serial(); serial_put(p->serial, compiled);
|
||||
}
|
||||
static NVNcommandHandle record(NVNtexture *texture, NVNprogram *program, int wait, int draw, unsigned offset) {
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
if (wait) P(nvnCommandBufferWaitEvent)(&command, &event, NVN_EVENT_WAIT_MODE_EQUAL, 1);
|
||||
const NVNtexture *colors[] = {texture}; const float viewport[] = {0, 0, W, H}, blue[] = {0, 0, 1, 1};
|
||||
P(nvnCommandBufferSetRenderTargets)(&command, 1, colors, NULL, NULL, NULL);
|
||||
P(nvnCommandBufferSetViewports)(&command, 0, 1, viewport); P(nvnCommandBufferSetScissor)(&command, 0, 0, W, H);
|
||||
P(nvnCommandBufferClearColor)(&command, 0, blue, 15);
|
||||
if (program) P(nvnCommandBufferBindProgram)(&command, program, 3);
|
||||
if (draw) P(nvnCommandBufferDrawArrays)(&command, NVN_DRAW_PRIMITIVE_TRIANGLES, 0, 3);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command, texture, NULL, ®ion, output + offset, 0);
|
||||
return P(nvnCommandBufferEndRecording)(&command);
|
||||
}
|
||||
int main(void) { @autoreleasepool {
|
||||
setbuf(stdout, NULL); mtl_init(); NSError *error = nil;
|
||||
id<MTLLibrary> library = [g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;\n"
|
||||
"vertex float4 v(uint i [[vertex_id]]) { const float2 p[] = {float2(-1,-1),float2(3,-1),float2(-1,3)}; return float4(p[i],0.5,1); }\n"
|
||||
"fragment float4 red() { return float4(1,0,0,1); } fragment float4 green() { return float4(0,1,0,1); }\n"
|
||||
options:nil error:&error];
|
||||
if (!library) fprintf(stderr, "%s\n", error.localizedDescription.UTF8String);
|
||||
require(library != nil, "synthetic shaders compile");
|
||||
NvShader *vs = [NvShader new]; vs->fn = [library newFunctionWithName:@"v"];
|
||||
NvProg *red = [NvProg new], *green = [NvProg new]; red->sh[0] = green->sh[0] = vs;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
NvShader *fs = [NvShader new]; fs->stage = 1; fs->rf.color_mask = 1; fs->fn = [library newFunctionWithName:i ? @"green" : @"red"];
|
||||
(i ? green : red)->sh[1] = fs;
|
||||
}
|
||||
NVNdeviceBuilder db = {0}; P(nvnDeviceBuilderSetDefaults)(&db); require(P(nvnDeviceInitialize)(&device, &db), "device initialized");
|
||||
for (int i = 0; i < 2; i++) { NVNqueueBuilder qb = {0}; P(nvnQueueBuilderSetDefaults)(&qb); P(nvnQueueBuilderSetDevice)(&qb, &device); require(P(nvnQueueInitialize)(&queues[i], &qb), "queue initialized"); }
|
||||
require(!posix_memalign((void **)&memory, getpagesize(), POOL_BYTES), "pool storage allocated"); memset(memory, 0, POOL_BYTES);
|
||||
NVNmemoryPoolBuilder pb = {0}; P(nvnMemoryPoolBuilderSetDefaults)(&pb); P(nvnMemoryPoolBuilderSetDevice)(&pb, &device);
|
||||
P(nvnMemoryPoolBuilderSetStorage)(&pb, memory, POOL_BYTES); P(nvnMemoryPoolBuilderSetFlags)(&pb, 0x24); require(P(nvnMemoryPoolInitialize)(&pool, &pb), "pool initialized");
|
||||
NVNbufferBuilder bb = {0}; NVNbuffer buffer; P(nvnBufferBuilderSetDefaults)(&bb); P(nvnBufferBuilderSetDevice)(&bb, &device);
|
||||
P(nvnBufferBuilderSetStorage)(&bb, &pool, OUTPUT, BYTES * 2); require(P(nvnBufferInitialize)(&buffer, &bb), "readback buffer initialized"); output = P(nvnBufferGetAddress)(&buffer);
|
||||
NVNeventBuilder eb = {0}; P(nvnEventBuilderSetDefaults)(&eb); P(nvnEventBuilderSetStorage)(&eb, &pool, EVENT); require(P(nvnEventInitialize)(&event, &eb), "event initialized");
|
||||
require(P(nvnCommandBufferInitialize)(&command, &device), "command buffer initialized"); P(nvnCommandBufferAddCommandMemory)(&command, &pool, 0, TEX_A);
|
||||
init_texture(&target, TEX_A); init_texture(&replacement, TEX_B);
|
||||
NVNprogram stable_red, stable_green; init_program(&stable_red, red); init_program(&stable_green, green);
|
||||
|
||||
|
||||
NVNsync sync, split;P(nvnSyncInitialize)(&split,&device);
|
||||
const NVNtexture *colors[]={&target};const float blue[]={0,0,1,1},red_clear[]={1,0,0,1};
|
||||
const char *names[]={"UpdateUB1", "UpdateUB1 then fence", "ClearBuffer1", "CopyBuffer1", "CopyBuffer0", "UpdateUB high32"};
|
||||
for(int k=0;k<6;k++) {
|
||||
id<MTLSharedEvent> gate=[g_dev newSharedEvent];
|
||||
dispatch_semaphore_t cancel=dispatch_semaphore_create(0), retired=dispatch_semaphore_create(0);
|
||||
[g_q4 waitForEvent:gate value:1];
|
||||
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0),^{
|
||||
if(dispatch_semaphore_wait(cancel,dispatch_time(DISPATCH_TIME_NOW,2000000000ll)))gate.signaledValue=1;
|
||||
dispatch_semaphore_signal(retired);
|
||||
});
|
||||
uint64_t *counts=(uint64_t *)(memory+EVENT+64),*source=(uint64_t *)(memory+EVENT+0x4000),*gpu_value=(uint64_t *)(memory+EVENT+256);
|
||||
counts[0]=1;counts[2]=0;*source=k==4?0:1;*gpu_value=0xdeadbeef;
|
||||
uint64_t one=1,want=k==2?0x100000001ull:k==4?0:k==5?0x100000000ull:1;
|
||||
NVNbufferAddress addr=(uintptr_t)counts;
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
P(nvnCommandBufferSetRenderTargets)(&command,1,colors,NULL,NULL,NULL);
|
||||
P(nvnCommandBufferClearColor)(&command,0,blue,15);
|
||||
P(nvnCommandBufferReportCounter)(&command,NVN_COUNTER_TYPE_TIMESTAMP,addr);
|
||||
P(nvnCommandBufferFenceSync)(&command,&split,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
if(k==0 || k==1)P(nvnCommandBufferUpdateUniformBuffer)(&command,addr,16,0,8,&one);
|
||||
if(k==2)P(nvnCommandBufferClearBuffer)(&command,addr,8,1);
|
||||
if(k==3 || k==4)P(nvnCommandBufferCopyBufferToBuffer)(&command,(uintptr_t)source,addr,8,0);
|
||||
if(k==5)P(nvnCommandBufferUpdateUniformBuffer)(&command,addr,16,4,4,&one);
|
||||
if(k==1)P(nvnCommandBufferFenceSync)(&command,&split,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
P(nvnCommandBufferSetRenderEnableConditional)(&command,(NVNconditionalRenderMode)1,addr);
|
||||
P(nvnCommandBufferClearColor)(&command,0,red_clear,15);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
P(nvnCommandBufferCopyBufferToBuffer)(&command,addr,(uintptr_t)gpu_value,8,0);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command,&target,NULL,®ion,output,0);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);
|
||||
uint64_t deadline=now_ns()+1000000000ull;int encoded=0;
|
||||
do {
|
||||
pthread_mutex_lock(&nq_mu);sync_t *st=(sync_t *)&sync;
|
||||
encoded=st->fenced==3 && ((nq_receipt *)(uintptr_t)st->fence)->published;
|
||||
pthread_mutex_unlock(&nq_mu);if(!encoded)usleep(1000);
|
||||
}while(!encoded && now_ns()<deadline);
|
||||
CHECK(encoded,"overlap commands encode while GPU completion gated");
|
||||
gate.signaledValue=1;dispatch_semaphore_signal(cancel);
|
||||
require(!dispatch_semaphore_wait(retired,dispatch_time(DISPATCH_TIME_NOW,3000000000ll)),"GPU gate rescue retired");
|
||||
finish(&sync);
|
||||
int good=pixels(0,want?255:0,0,want?0:255);
|
||||
CHECK(good,names[k]);if(k!=5) CHECK(*gpu_value==want,"GPU command-ordered bytes match latest full write");
|
||||
else printf("OPEN partial-update native GPU_A expected=%#llx actual=%#llx: timestamp report is currently CPU-post only\n",(unsigned long long)want,(unsigned long long)*gpu_value);
|
||||
printf("RESULT %s predicate=%d GPU_A=%#llx final_CPU_A=%#llx expected=%#llx\n",names[k],good,(unsigned long long)*gpu_value,(unsigned long long)counts[0],(unsigned long long)want);
|
||||
}
|
||||
P(nvnSyncFinalize)(&split);
|
||||
P(nvnQueueFinish)(&queues[0]); P(nvnQueueFinish)(&queues[1]);
|
||||
P(nvnProgramFinalize)(&stable_red); P(nvnProgramFinalize)(&stable_green);
|
||||
P(nvnTextureFinalize)(&target); P(nvnTextureFinalize)(&replacement); P(nvnCommandBufferFinalize)(&command);
|
||||
P(nvnBufferFinalize)(&buffer); P(nvnEventFinalize)(&event); P(nvnMemoryPoolFinalize)(&pool);
|
||||
P(nvnQueueFinalize)(&queues[0]); P(nvnQueueFinalize)(&queues[1]); P(nvnDeviceFinalize)(&device); free(memory);
|
||||
printf("counter overlap: %d checks, %d failed\n", checks, failures); return failures != 0;
|
||||
} }
|
||||
@@ -0,0 +1,184 @@
|
||||
// Logical render-enable state and pending query values survive scheduler chunks.
|
||||
// Every path uses public NVN recording; the last case gates only GPU completion.
|
||||
#define nvn_game_fps nvn_game_fps_mtl_default
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
#undef nvn_game_fps
|
||||
#define g_ft g_ft_hle
|
||||
#include "../nvn/hle_nvn.c"
|
||||
#undef g_ft
|
||||
#define P(name) ((NVNT_##name)nvn_lookup(#name))
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t *g_mod; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int checks, failures;
|
||||
#define CHECK(c, name) do { int check_ok = !!(c); checks++; failures += !check_ok; printf("%s: %s\n", check_ok ? "PASS" : "FAIL", name); } while (0)
|
||||
static void require(int ok, const char *name) { CHECK(ok, name); if (!ok) exit(2); }
|
||||
enum { W = 8, H = 8, BYTES = W * H * 4, POOL_BYTES = 1 << 20, TEX_A = 0x80000, TEX_B = 0x90000, OUTPUT = 0xa0000, EVENT = 0xa1000 };
|
||||
static NVNdevice device; static NVNqueue queues[2]; static NVNmemoryPool pool; static NVNcommandBuffer command;
|
||||
static NVNevent event; static NVNtexture target, replacement; static uint8_t *memory; static NVNbufferAddress output;
|
||||
static const NVNcopyRegion region = {0, 0, 0, W, H, 1};
|
||||
|
||||
static int landed(NVNsync *sync, uint64_t timeout) {
|
||||
NVNsyncWaitResult r = P(nvnSyncWait)(sync, timeout);
|
||||
return r == NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED || r == NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED;
|
||||
}
|
||||
static void submit(int queue, NVNcommandHandle handle, NVNsync *sync) {
|
||||
P(nvnSyncInitialize)(sync, &device); P(nvnQueueSubmitCommands)(&queues[queue], 1, &handle);
|
||||
P(nvnQueueFenceSync)(&queues[queue], sync, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
}
|
||||
static void finish(NVNsync *sync) {
|
||||
require(landed(sync, 5000000000ull), "queue tail and GPU work complete");
|
||||
P(nvnSyncFinalize)(sync);
|
||||
}
|
||||
static int pixels(unsigned offset, unsigned r, unsigned g, unsigned b) {
|
||||
const uint8_t want[] = {r, g, b, 255};
|
||||
for (int i = 0; i < W * H; i++) if (memcmp(memory + OUTPUT + offset + i * 4, want, 4)) return 0;
|
||||
return 1;
|
||||
}
|
||||
static void init_texture(NVNtexture *texture, unsigned offset) {
|
||||
NVNtextureBuilder tb = {0}; P(nvnTextureBuilderSetDefaults)(&tb); P(nvnTextureBuilderSetDevice)(&tb, &device);
|
||||
P(nvnTextureBuilderSetTarget)(&tb, NVN_TEXTURE_TARGET_2D); P(nvnTextureBuilderSetSize2D)(&tb, W, H);
|
||||
P(nvnTextureBuilderSetFormat)(&tb, NVN_FORMAT_RGBA8); P(nvnTextureBuilderSetStorage)(&tb, &pool, offset);
|
||||
require(P(nvnTextureInitialize)(texture, &tb), "texture initialized on retained backing storage");
|
||||
}
|
||||
static void init_program(NVNprogram *program, NvProg *compiled) {
|
||||
require(P(nvnProgramInitialize)(program, &device), "program object initialized");
|
||||
// Synthetic MSL replaces only game shader loading; recording and submission
|
||||
// use the public NVN entry points and the real serial ownership table.
|
||||
prog_t *p = (prog_t *)program; p->serial = nvn_new_serial(); serial_put(p->serial, compiled);
|
||||
}
|
||||
static NVNcommandHandle record(NVNtexture *texture, NVNprogram *program, int wait, int draw, unsigned offset) {
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
if (wait) P(nvnCommandBufferWaitEvent)(&command, &event, NVN_EVENT_WAIT_MODE_EQUAL, 1);
|
||||
const NVNtexture *colors[] = {texture}; const float viewport[] = {0, 0, W, H}, blue[] = {0, 0, 1, 1};
|
||||
P(nvnCommandBufferSetRenderTargets)(&command, 1, colors, NULL, NULL, NULL);
|
||||
P(nvnCommandBufferSetViewports)(&command, 0, 1, viewport); P(nvnCommandBufferSetScissor)(&command, 0, 0, W, H);
|
||||
P(nvnCommandBufferClearColor)(&command, 0, blue, 15);
|
||||
if (program) P(nvnCommandBufferBindProgram)(&command, program, 3);
|
||||
if (draw) P(nvnCommandBufferDrawArrays)(&command, NVN_DRAW_PRIMITIVE_TRIANGLES, 0, 3);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command, texture, NULL, ®ion, output + offset, 0);
|
||||
return P(nvnCommandBufferEndRecording)(&command);
|
||||
}
|
||||
int main(void) { @autoreleasepool {
|
||||
setbuf(stdout, NULL); mtl_init(); NSError *error = nil;
|
||||
id<MTLLibrary> library = [g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;\n"
|
||||
"vertex float4 v(uint i [[vertex_id]]) { const float2 p[] = {float2(-1,-1),float2(3,-1),float2(-1,3)}; return float4(p[i],0.5,1); }\n"
|
||||
"fragment float4 red() { return float4(1,0,0,1); } fragment float4 green() { return float4(0,1,0,1); }\n"
|
||||
options:nil error:&error];
|
||||
if (!library) fprintf(stderr, "%s\n", error.localizedDescription.UTF8String);
|
||||
require(library != nil, "synthetic shaders compile");
|
||||
NvShader *vs = [NvShader new]; vs->fn = [library newFunctionWithName:@"v"];
|
||||
NvProg *red = [NvProg new], *green = [NvProg new]; red->sh[0] = green->sh[0] = vs;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
NvShader *fs = [NvShader new]; fs->stage = 1; fs->rf.color_mask = 1; fs->fn = [library newFunctionWithName:i ? @"green" : @"red"];
|
||||
(i ? green : red)->sh[1] = fs;
|
||||
}
|
||||
NVNdeviceBuilder db = {0}; P(nvnDeviceBuilderSetDefaults)(&db); require(P(nvnDeviceInitialize)(&device, &db), "device initialized");
|
||||
for (int i = 0; i < 2; i++) { NVNqueueBuilder qb = {0}; P(nvnQueueBuilderSetDefaults)(&qb); P(nvnQueueBuilderSetDevice)(&qb, &device); require(P(nvnQueueInitialize)(&queues[i], &qb), "queue initialized"); }
|
||||
require(!posix_memalign((void **)&memory, getpagesize(), POOL_BYTES), "pool storage allocated"); memset(memory, 0, POOL_BYTES);
|
||||
NVNmemoryPoolBuilder pb = {0}; P(nvnMemoryPoolBuilderSetDefaults)(&pb); P(nvnMemoryPoolBuilderSetDevice)(&pb, &device);
|
||||
P(nvnMemoryPoolBuilderSetStorage)(&pb, memory, POOL_BYTES); P(nvnMemoryPoolBuilderSetFlags)(&pb, 0x24); require(P(nvnMemoryPoolInitialize)(&pool, &pb), "pool initialized");
|
||||
NVNbufferBuilder bb = {0}; NVNbuffer buffer; P(nvnBufferBuilderSetDefaults)(&bb); P(nvnBufferBuilderSetDevice)(&bb, &device);
|
||||
P(nvnBufferBuilderSetStorage)(&bb, &pool, OUTPUT, BYTES * 2); require(P(nvnBufferInitialize)(&buffer, &bb), "readback buffer initialized"); output = P(nvnBufferGetAddress)(&buffer);
|
||||
NVNeventBuilder eb = {0}; P(nvnEventBuilderSetDefaults)(&eb); P(nvnEventBuilderSetStorage)(&eb, &pool, EVENT); require(P(nvnEventInitialize)(&event, &eb), "event initialized");
|
||||
require(P(nvnCommandBufferInitialize)(&command, &device), "command buffer initialized"); P(nvnCommandBufferAddCommandMemory)(&command, &pool, 0, TEX_A);
|
||||
init_texture(&target, TEX_A); init_texture(&replacement, TEX_B);
|
||||
NVNprogram stable_red, stable_green; init_program(&stable_red, red); init_program(&stable_green, green);
|
||||
|
||||
NVNsync sync, dependency;
|
||||
P(nvnSyncInitialize)(&dependency, &device);
|
||||
P(nvnQueueFenceSync)(&queues[1], &dependency, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
P(nvnEventSignal)(&event, NVN_EVENT_SIGNAL_MODE_WRITE, 1);
|
||||
const NVNtexture *colors[] = {&target}; const float viewport[] = {0,0,W,H}, blue[] = {0,0,1,1};
|
||||
const char *names[] = {"unsplit disabled control", "disabled across WaitEvent", "disabled across SignalEvent", "disabled across WaitSync", "disabled across FenceSync", "conditional false across WaitEvent"};
|
||||
NVNsync split_sync; P(nvnSyncInitialize)(&split_sync, &device);
|
||||
for (int k=0;k<6;k++) {
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
P(nvnCommandBufferSetRenderTargets)(&command,1,colors,NULL,NULL,NULL);
|
||||
P(nvnCommandBufferSetViewports)(&command,0,1,viewport); P(nvnCommandBufferSetScissor)(&command,0,0,W,H);
|
||||
P(nvnCommandBufferClearColor)(&command,0,blue,15);
|
||||
P(nvnCommandBufferBindProgram)(&command,&stable_red,3);
|
||||
if(k==5) {
|
||||
uint64_t *counts=(uint64_t *)(memory+EVENT+64); counts[0]=0;counts[2]=1;
|
||||
P(nvnCommandBufferSetRenderEnableConditional)(&command,(NVNconditionalRenderMode)0,(NVNbufferAddress)(uintptr_t)counts);
|
||||
} else P(nvnCommandBufferSetRenderEnable)(&command,0);
|
||||
if(k==1 || k==5) P(nvnCommandBufferWaitEvent)(&command,&event,NVN_EVENT_WAIT_MODE_EQUAL,1);
|
||||
if(k==2) P(nvnCommandBufferSignalEvent)(&command,&event,NVN_EVENT_SIGNAL_MODE_WRITE,NVN_EVENT_SIGNAL_LOCATION_BOTTOM,0,1);
|
||||
if(k==3) P(nvnCommandBufferWaitSync)(&command,&dependency);
|
||||
if(k==4) P(nvnCommandBufferFenceSync)(&command,&split_sync,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
P(nvnCommandBufferDrawArrays)(&command,NVN_DRAW_PRIMITIVE_TRIANGLES,0,3);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command,&target,NULL,®ion,output,0);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);finish(&sync);
|
||||
CHECK(pixels(0,0,0,255),names[k]);
|
||||
}
|
||||
// No object or backing reuse: only the queue-owned render-enable state crosses jobs.
|
||||
submit(0,record(&target,NULL,0,0,0),&sync);finish(&sync);
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,0);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);finish(&sync);
|
||||
submit(1,record(&replacement,&stable_green,0,1,BYTES),&sync);finish(&sync);
|
||||
CHECK(pixels(BYTES,0,255,0),"independent queue draws with its default enabled state");
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferBindProgram)(&command,&stable_red,3);
|
||||
P(nvnCommandBufferDrawArrays)(&command,NVN_DRAW_PRIMITIVE_TRIANGLES,0,3);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command,&target,NULL,®ion,output,0);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);finish(&sync);
|
||||
CHECK(pixels(0,0,0,255),"original queue retains disabled state after another queue runs");
|
||||
|
||||
// Hold GPU completion while the real NVN recorder/replayer crosses a fence.
|
||||
// The render predicate must forward the pending timestamp's known counter0.
|
||||
id<MTLSharedEvent> gpu_gate=[g_dev newSharedEvent];
|
||||
dispatch_semaphore_t gate_cancel=dispatch_semaphore_create(0), gate_retired=dispatch_semaphore_create(0);
|
||||
[g_q4 waitForEvent:gpu_gate value:1];
|
||||
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0), ^{
|
||||
if(dispatch_semaphore_wait(gate_cancel,dispatch_time(DISPATCH_TIME_NOW,2000000000ll))) gpu_gate.signaledValue=1;
|
||||
dispatch_semaphore_signal(gate_retired);
|
||||
});
|
||||
uint64_t *counts=(uint64_t *)(memory+EVENT+64);counts[0]=1;counts[2]=0;
|
||||
const float red_clear[]={1,0,0,1};
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
P(nvnCommandBufferClearColor)(&command,0,blue,15);
|
||||
P(nvnCommandBufferReportCounter)(&command,NVN_COUNTER_TYPE_TIMESTAMP,(NVNbufferAddress)(uintptr_t)counts);
|
||||
P(nvnCommandBufferFenceSync)(&command,&split_sync,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
P(nvnCommandBufferSetRenderEnableConditional)(&command,(NVNconditionalRenderMode)1,(NVNbufferAddress)(uintptr_t)counts);
|
||||
P(nvnCommandBufferClearColor)(&command,0,red_clear,15);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command,&target,NULL,®ion,output,0);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);
|
||||
uint64_t deadline=now_ns()+1000000000ull;int encoded=0;
|
||||
do {
|
||||
pthread_mutex_lock(&nq_mu);
|
||||
sync_t *st=(sync_t *)&sync;encoded=st->fenced==3 && ((nq_receipt *)(uintptr_t)st->fence)->published;
|
||||
pthread_mutex_unlock(&nq_mu);
|
||||
if(!encoded) usleep(1000);
|
||||
} while(!encoded && now_ns()<deadline);
|
||||
CHECK(encoded,"both physical chunks encode while GPU completion is gated");
|
||||
CHECK(counts[0]==1,"timestamp counter is not CPU-visible before GPU release");
|
||||
// Release before any fatal assertion so even a broken implementation drains.
|
||||
gpu_gate.signaledValue=1;dispatch_semaphore_signal(gate_cancel);
|
||||
require(!dispatch_semaphore_wait(gate_retired,dispatch_time(DISPATCH_TIME_NOW,3000000000ll)),"GPU gate rescue retired");
|
||||
finish(&sync);
|
||||
CHECK(pixels(0,0,0,255),"pending timestamp zero survives FenceSync chunk split");
|
||||
counts[0]=1;counts[2]=0;
|
||||
P(nvnCommandBufferBeginRecording)(&command);
|
||||
P(nvnCommandBufferClearColor)(&command,0,blue,15);
|
||||
P(nvnCommandBufferSetRenderEnableConditional)(&command,(NVNconditionalRenderMode)1,(NVNbufferAddress)(uintptr_t)counts);
|
||||
P(nvnCommandBufferClearColor)(&command,0,red_clear,15);
|
||||
P(nvnCommandBufferSetRenderEnable)(&command,1);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&command,&target,NULL,®ion,output,0);
|
||||
submit(0,P(nvnCommandBufferEndRecording)(&command),&sync);finish(&sync);
|
||||
CHECK(pixels(0,255,0,0),"CPU counter write after completed report replaces pending zero");
|
||||
P(nvnSyncFinalize)(&dependency);P(nvnSyncFinalize)(&split_sync);
|
||||
P(nvnQueueFinish)(&queues[0]); P(nvnQueueFinish)(&queues[1]);
|
||||
P(nvnProgramFinalize)(&stable_red); P(nvnProgramFinalize)(&stable_green);
|
||||
P(nvnTextureFinalize)(&target); P(nvnTextureFinalize)(&replacement); P(nvnCommandBufferFinalize)(&command);
|
||||
P(nvnBufferFinalize)(&buffer); P(nvnEventFinalize)(&event); P(nvnMemoryPoolFinalize)(&pool);
|
||||
P(nvnQueueFinalize)(&queues[0]); P(nvnQueueFinalize)(&queues[1]); P(nvnDeviceFinalize)(&device); free(memory);
|
||||
printf("render enable continuation: %d checks, %d failed\n", checks, failures); return failures != 0;
|
||||
} }
|
||||
+25
-1
@@ -56,7 +56,31 @@ int main(void){@autoreleasepool{
|
||||
CHECK("a query's report stays unknown",!rc_value(0x7100000000ull+8999*16,&x)&&!rc_value(0x7100000000ull,&x));
|
||||
(void)q;for(uint64_t i=0;i<300;i++)rc_note((uint64_t)&big+0x1000+i,1);
|
||||
CHECK("more timestamp reports than the first table held",rc_value((uint64_t)&big+0x1000,&x)&&x==0);
|
||||
g_rc_npend=0;}
|
||||
rc_forget();}
|
||||
// Sparse report pages arrive out of address order. A large write must visit
|
||||
// just its intersections, including an unaligned counter on the prior page.
|
||||
{const uint64_t start=0x7200100000ull, span=0x800000, addresses[]={start+span,start-3,start+0x700000,start-16,start+32,start+0x100000};
|
||||
const uint8_t fill=0xab;uint64_t x=0;
|
||||
for(unsigned i=0;i<sizeof addresses/sizeof *addresses;i++)rc_note(addresses[i],1);
|
||||
rc_write(start,span,&fill,1);
|
||||
CHECK("wide write excludes the counter at its end",rc_value(addresses[0],&x)&&x==0);
|
||||
CHECK("wide write forwards partial counter bytes across a page",rc_value(addresses[1],&x)&&x==0xababababab000000ull);
|
||||
CHECK("wide write reaches distant intersecting report pages",rc_value(addresses[2],&x)&&x==0xababababababababull);
|
||||
CHECK("wide write excludes counters before its start",rc_value(addresses[3],&x)&&x==0);
|
||||
CHECK("wide write reaches another counter on its first page",rc_value(addresses[4],&x)&&x==0xababababababababull);
|
||||
CHECK("wide write reaches a page inserted last",rc_value(addresses[5],&x)&&x==0xababababababababull);
|
||||
rc_forget();rc_note(start+32,1);rc_write(start,span,&fill,1);
|
||||
CHECK("report page index resets before address reuse",rc_value(start+32,&x)&&x==0xababababababababull);
|
||||
rc_forget();}
|
||||
// An unbounded shader store may replace a completed report before the word
|
||||
// becomes a query operand. Copy forwarding must not read its stale CPU bytes.
|
||||
{static uint64_t rec[2];uint8_t bytes[8];int unreliable=0;uint64_t x=1;
|
||||
uint64_t completed=atomic_load(&g_rc_complete);rc_note((uint64_t)rec,1);rc_commit(completed+1);atomic_store(&g_rc_complete,completed+1);
|
||||
sbw_note(0,0,SBW_GPU);
|
||||
CHECK("a copy after an unbounded writer cannot forward completed timestamp bytes",!rc_source((uint64_t)rec,8,bytes,&unreliable)&&unreliable);
|
||||
rc_note((uint64_t)rec,1);
|
||||
CHECK("a later timestamp restores known zero after the opaque writer",rc_value((uint64_t)rec,&x)&&x==0);
|
||||
rc_forget();atomic_store(&g_rc_complete,completed);}
|
||||
pend_reset();
|
||||
printf("t_sbw: %d checks, %d failed\n",checks,failed);return failed!=0;
|
||||
}}
|
||||
@@ -0,0 +1,295 @@
|
||||
// Contract fixture: real public NVN lookup -> recording -> QueueSubmit -> Metal replay.
|
||||
// An event wait gates GPU work, but never blocks CPU submission or another NVN queue.
|
||||
#define nvn_game_fps nvn_game_fps_mtl_default
|
||||
#define nvn_event_publish_gpu event_test_publish
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
#undef nvn_event_publish_gpu
|
||||
#undef nvn_game_fps
|
||||
#define g_ft g_ft_hle
|
||||
#include "../nvn/hle_nvn.c"
|
||||
#undef g_ft
|
||||
#define P(name) ((NVNT_##name)nvn_lookup(#name))
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t *g_mod; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int checks, fails;
|
||||
#define CHECK(c,label) do { int ok=!!(c); checks++; fails+=!ok; printf("%s: %s\n",ok?"PASS":"FAIL",label); fflush(stdout); } while(0)
|
||||
// Observe the exact release boundary, then call the real event publisher. This
|
||||
// avoids a timing race between a CPU polling thread and a very small readback.
|
||||
static _Atomic uintptr_t event_test_storage;
|
||||
static _Atomic uint32_t event_test_pixel;
|
||||
static _Atomic int event_test_deferred_mirror;
|
||||
void event_test_publish(volatile uint32_t *word,unsigned mode,uint32_t value,uint64_t fence) {
|
||||
uintptr_t storage=atomic_load(&event_test_storage);
|
||||
if(storage && value==11) {
|
||||
atomic_store(&event_test_pixel,*(volatile uint32_t *)storage);
|
||||
post_rec *r=&g_postr[fence%POST_RING]; int signal=-1,mirror=-1;
|
||||
for(int i=0;i<r->n;i++) { if(r->ops[i].kind==1) signal=i; if(r->ops[i].kind==4) mirror=i; }
|
||||
atomic_store(&event_test_deferred_mirror,signal>=0 && mirror>signal);
|
||||
}
|
||||
nvn_event_publish_gpu(word,mode,value,fence);
|
||||
}
|
||||
|
||||
typedef struct job { NVNqueue *queue; NVNcommandHandle handle; dispatch_semaphore_t done; struct job *next; } job;
|
||||
static pthread_mutex_t jobs_mu=PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t jobs_cv=PTHREAD_COND_INITIALIZER;
|
||||
static job *jobs_first,*jobs_last; static int jobs_stop;
|
||||
static void *submit_worker(void *unused) { (void)unused; @autoreleasepool {
|
||||
for (;;) {
|
||||
pthread_mutex_lock(&jobs_mu);
|
||||
while (!jobs_first && !jobs_stop) pthread_cond_wait(&jobs_cv,&jobs_mu);
|
||||
if (!jobs_first) { pthread_mutex_unlock(&jobs_mu); break; }
|
||||
job *j=jobs_first; jobs_first=j->next; if (!jobs_first) jobs_last=NULL;
|
||||
pthread_mutex_unlock(&jobs_mu);
|
||||
P(nvnQueueSubmitCommands)(j->queue,1,&j->handle);
|
||||
dispatch_semaphore_signal(j->done);
|
||||
}
|
||||
} return NULL; }
|
||||
static void enqueue(job *j,NVNqueue *queue,NVNcommandHandle handle) {
|
||||
*j=(job){.queue=queue,.handle=handle,.done=dispatch_semaphore_create(0)};
|
||||
pthread_mutex_lock(&jobs_mu); if(jobs_last) jobs_last->next=j; else jobs_first=j;
|
||||
jobs_last=j; pthread_cond_signal(&jobs_cv); pthread_mutex_unlock(&jobs_mu);
|
||||
}
|
||||
static int returned(job *j,uint64_t ns) { return dispatch_semaphore_wait(j->done,dispatch_time(DISPATCH_TIME_NOW,(int64_t)ns))==0; }
|
||||
static int landed(NVNsync *s,uint64_t ns) {
|
||||
NVNsyncWaitResult r=P(nvnSyncWait)(s,ns);
|
||||
return r==NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED || r==NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED;
|
||||
}
|
||||
static void require_returned(job *j,int seen) {
|
||||
if (!seen && !returned(j,5000000000ull)) { fprintf(stderr,"submission did not return after rescue release\n"); _Exit(2); }
|
||||
}
|
||||
static NVNdevice device; static NVNqueue queues[2]; static NVNmemoryPool pool;
|
||||
static NVNevent event; static uint8_t *memory; static volatile uint32_t *source,*result;
|
||||
static NVNbufferAddress source_addr,result_addr; static NVNcommandBuffer commands[2];
|
||||
static NVNcommandHandle begin_cmd(int k) {
|
||||
P(nvnCommandBufferInitialize)(&commands[k],&device);
|
||||
P(nvnCommandBufferAddCommandMemory)(&commands[k],&pool,k*32768,32768);
|
||||
P(nvnCommandBufferBeginRecording)(&commands[k]); return 0;
|
||||
}
|
||||
static NVNcommandHandle consumer(int mode,uint32_t target,NVNsync *fence,int wait) {
|
||||
begin_cmd(0);
|
||||
if(wait) P(nvnCommandBufferWaitEvent)(&commands[0],&event,(NVNeventWaitMode)mode,target);
|
||||
P(nvnCommandBufferCopyBufferToBuffer)(&commands[0],source_addr,result_addr,4,0);
|
||||
P(nvnCommandBufferFenceSync)(&commands[0],fence,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
return P(nvnCommandBufferEndRecording)(&commands[0]);
|
||||
}
|
||||
static const uint32_t sentinel=0x13579bdf, before=0x01020304, after=0xa1b2c3d4;
|
||||
static void case_wait(const char *label,int mode,uint32_t initial,uint32_t target,int ready) {
|
||||
printf("CASE %s mode=%d initial=%#x target=%#x ready=%d\n",label,mode,initial,target,ready);
|
||||
*source=before; *result=sentinel; P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,initial);
|
||||
NVNsync fence; P(nvnSyncInitialize)(&fence,&device); job j;
|
||||
enqueue(&j,&queues[0],consumer(mode,target,&fence,1));
|
||||
int cpu_returned=returned(&j,250000000ull);
|
||||
CHECK(cpu_returned,"QueueSubmitCommands returns while the event is unresolved");
|
||||
int completed=landed(&fence,ready?1000000000ull:100000000ull);
|
||||
CHECK(completed==ready,"GPU completion follows the event predicate before CPU release");
|
||||
CHECK(*result==(ready?before:sentinel),"GPU output before CPU release");
|
||||
// Release on every path, including failed assertions and a CPU-blocking implementation.
|
||||
if(!ready) *source=after;
|
||||
P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,target);
|
||||
require_returned(&j,cpu_returned);
|
||||
int finished=landed(&fence,5000000000ull); CHECK(finished,"GPU work finishes after CPU rescue/release");
|
||||
if(!finished) { fprintf(stderr,"GPU did not finish after unconditional event release\n"); _Exit(2); }
|
||||
CHECK(*result==(ready?before:after),"GPU reads payload from the correct side of the event release");
|
||||
P(nvnSyncFinalize)(&fence);
|
||||
}
|
||||
static void case_cross_queue(void) {
|
||||
printf("CASE forward cross-queue producer\n");
|
||||
*source=before; *result=sentinel; P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,0);
|
||||
NVNsync consumed,produced; P(nvnSyncInitialize)(&consumed,&device); P(nvnSyncInitialize)(&produced,&device);
|
||||
NVNcommandHandle ch=consumer(0,1,&consumed,1);
|
||||
begin_cmd(1);
|
||||
uint32_t payload=after;
|
||||
P(nvnCommandBufferUpdateUniformBuffer)(&commands[1],source_addr,4,0,4,&payload);
|
||||
P(nvnCommandBufferSignalEvent)(&commands[1],&event,NVN_EVENT_SIGNAL_MODE_WRITE,NVN_EVENT_SIGNAL_LOCATION_BOTTOM,0,1);
|
||||
P(nvnCommandBufferFenceSync)(&commands[1],&produced,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
NVNcommandHandle ph=P(nvnCommandBufferEndRecording)(&commands[1]);
|
||||
job cj,pj; enqueue(&cj,&queues[0],ch); int cr=returned(&cj,250000000ull);
|
||||
CHECK(cr,"consumer submit returns before a later producer is submitted");
|
||||
CHECK(!landed(&consumed,100000000ull) && *result==sentinel,"consumer is gated before producer submission");
|
||||
enqueue(&pj,&queues[1],ph); int pr=returned(&pj,250000000ull);
|
||||
CHECK(pr,"producer on a different NVN queue can be submitted");
|
||||
int done=landed(&consumed,1000000000ull);
|
||||
CHECK(done,"later producer releases the consumer without CPU intervention");
|
||||
CHECK(done && *result==after,"consumer sees the later producer's GPU payload");
|
||||
// Even a single-Metal-queue deadlock is released before joining/draining.
|
||||
P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,1);
|
||||
require_returned(&cj,cr); require_returned(&pj,pr);
|
||||
int drained=landed(&consumed,5000000000ull) && landed(&produced,5000000000ull);
|
||||
CHECK(drained,"both queues drain after unconditional cleanup release");
|
||||
if(!drained) _Exit(2);
|
||||
P(nvnSyncFinalize)(&consumed); P(nvnSyncFinalize)(&produced);
|
||||
}
|
||||
// Receipt tests observe public sync completion. This helper only waits until the scheduler has encoded the logical fence, so a negative GPU assertion cannot pass merely because its CPU worker has not run yet.
|
||||
static int receipt_encoded(NVNsync *sync,uint64_t timeout) {
|
||||
uint64_t start=now_ns(),fence=0; int ready=0;
|
||||
pthread_mutex_lock(&nq_mu);
|
||||
while(!(ready=nq_sync_encoded((const sync_t *)sync,&fence))) {
|
||||
uint64_t elapsed=now_ns()-start; if(elapsed>=timeout) break;
|
||||
uint64_t left=timeout-elapsed; struct timespec ts={(time_t)(left/1000000000ull),(long)(left%1000000000ull)};
|
||||
pthread_cond_timedwait_relative_np(&nq_cv,&nq_mu,&ts);
|
||||
}
|
||||
pthread_mutex_unlock(&nq_mu); return ready;
|
||||
}
|
||||
static void receipt_unrelated_completion(void) {
|
||||
printf("CASE unrelated physical completion cannot release a parked logical fence\n");
|
||||
*source=before; *result=sentinel; P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,0);
|
||||
NVNsync command_fence,logical,unrelated; P(nvnSyncInitialize)(&command_fence,&device); P(nvnSyncInitialize)(&logical,&device); P(nvnSyncInitialize)(&unrelated,&device);
|
||||
job blocked,other; enqueue(&blocked,&queues[0],consumer(0,1,&command_fence,1)); int br=returned(&blocked,250000000ull);
|
||||
CHECK(br,"parked consumer submission returns before unrelated work");
|
||||
P(nvnQueueFenceSync)(&queues[0],&logical,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
begin_cmd(1); uint32_t payload=after; P(nvnCommandBufferUpdateUniformBuffer)(&commands[1],source_addr,4,0,4,&payload);
|
||||
P(nvnCommandBufferFenceSync)(&commands[1],&unrelated,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
enqueue(&other,&queues[1],P(nvnCommandBufferEndRecording)(&commands[1])); int or_=returned(&other,250000000ull);
|
||||
CHECK(or_,"unrelated queue submission returns"); int progressed=landed(&unrelated,1000000000ull);
|
||||
CHECK(progressed,"unrelated queue physically completes while consumer is parked");
|
||||
CHECK(!landed(&logical,0) && !landed(&command_fence,0),"neither consumer fence inherits an unrelated physical completion");
|
||||
CHECK(*result==sentinel,"parked consumer has not copied its payload");
|
||||
P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,1); // unconditional rescue before joining or reporting a fatal fixture failure
|
||||
require_returned(&blocked,br); require_returned(&other,or_);
|
||||
int drained=landed(&logical,5000000000ull) && landed(&command_fence,5000000000ull) && landed(&unrelated,5000000000ull);
|
||||
CHECK(drained && *result==after,"logical and physical work drain after the actual dependency is released"); if(!drained) _Exit(2);
|
||||
P(nvnSyncFinalize)(&command_fence); P(nvnSyncFinalize)(&logical); P(nvnSyncFinalize)(&unrelated);
|
||||
}
|
||||
static void receipt_snapshot(int command_wait) {
|
||||
printf("CASE %s wait retains its original receipt through retarget and finalize\n",command_wait?"command-buffer":"queue");
|
||||
*source=before; *result=sentinel; P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,0);
|
||||
NVNqueue completed_queue; NVNqueueBuilder qb={0}; P(nvnQueueBuilderSetDefaults)(&qb); P(nvnQueueBuilderSetDevice)(&qb,&device);
|
||||
CHECK(P(nvnQueueInitialize)(&completed_queue,&qb),"completed retarget queue initializes");
|
||||
NVNsync target_sync,consumed,producer_tail; P(nvnSyncInitialize)(&target_sync,&device); P(nvnSyncInitialize)(&consumed,&device); P(nvnSyncInitialize)(&producer_tail,&device);
|
||||
begin_cmd(0); P(nvnCommandBufferWaitEvent)(&commands[0],&event,NVN_EVENT_WAIT_MODE_EQUAL,1); uint32_t payload=after;
|
||||
P(nvnCommandBufferUpdateUniformBuffer)(&commands[0],source_addr,4,0,4,&payload);
|
||||
job producer,consumer_job,tail_job; enqueue(&producer,&queues[0],P(nvnCommandBufferEndRecording)(&commands[0])); int pr=returned(&producer,250000000ull);
|
||||
CHECK(pr,"original producer is enqueued before its receipt is captured");
|
||||
P(nvnQueueFenceSync)(&queues[0],&target_sync,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
if(!command_wait) CHECK(P(nvnQueueWaitSync)(&queues[1],&target_sync),"queue wait captures the original producer receipt");
|
||||
begin_cmd(1); if(command_wait) P(nvnCommandBufferWaitSync)(&commands[1],&target_sync);
|
||||
P(nvnCommandBufferCopyBufferToBuffer)(&commands[1],source_addr,result_addr,4,0);
|
||||
P(nvnCommandBufferFenceSync)(&commands[1],&consumed,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
enqueue(&consumer_job,&queues[1],P(nvnCommandBufferEndRecording)(&commands[1])); int cr=returned(&consumer_job,250000000ull);
|
||||
CHECK(cr,"consumer recording has captured its sync dependency");
|
||||
// Replace the producer queue's tail too: after the original job retires, the queued wait must own the old receipt itself.
|
||||
begin_cmd(0); enqueue(&tail_job,&queues[0],P(nvnCommandBufferEndRecording)(&commands[0])); int tr=returned(&tail_job,250000000ull);
|
||||
P(nvnQueueFenceSync)(&queues[0],&producer_tail,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
P(nvnQueueFenceSync)(&completed_queue,&target_sync,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
CHECK(!landed(&consumed,100000000ull) && *result==sentinel,"retargeting the source sync to a completed queue does not release the queued wait");
|
||||
P(nvnSyncFinalize)(&target_sync);
|
||||
P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,1); // release even if a stale raw pointer has already let the consumer run
|
||||
require_returned(&producer,pr); require_returned(&consumer_job,cr); require_returned(&tail_job,tr);
|
||||
int drained=landed(&consumed,5000000000ull) && landed(&producer_tail,5000000000ull);
|
||||
CHECK(drained && *result==after,"queued wait survives sync finalization and observes the original producer payload"); if(!drained) _Exit(2);
|
||||
P(nvnSyncFinalize)(&consumed); P(nvnSyncFinalize)(&producer_tail); P(nvnQueueFinalize)(&completed_queue);
|
||||
}
|
||||
static void receipt_wait_only(int command_wait) {
|
||||
printf("CASE %s wait-only queue inherits the producer GPU fence\n",command_wait?"command-buffer":"queue");
|
||||
*source=before;
|
||||
NVNsync produced,consumed; P(nvnSyncInitialize)(&produced,&device); P(nvnSyncInitialize)(&consumed,&device);
|
||||
id<MTLSharedEvent> gate=[g_dev newSharedEvent];
|
||||
pthread_mutex_lock(&g_sub_mu); rec_drain(); [g_q4 waitForEvent:gate value:1]; pthread_mutex_unlock(&g_sub_mu);
|
||||
begin_cmd(1); uint32_t payload=after; P(nvnCommandBufferUpdateUniformBuffer)(&commands[1],source_addr,4,0,4,&payload);
|
||||
job producer,waiter; enqueue(&producer,&queues[1],P(nvnCommandBufferEndRecording)(&commands[1])); int pr=returned(&producer,250000000ull);
|
||||
P(nvnQueueFenceSync)(&queues[1],&produced,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
int encoded=receipt_encoded(&produced,1000000000ull); CHECK(pr && encoded,"producer receipt publishes while its GPU work is held by a shared-event gate");
|
||||
int wr=1;
|
||||
if(command_wait) {
|
||||
begin_cmd(0); P(nvnCommandBufferWaitSync)(&commands[0],&produced);
|
||||
P(nvnCommandBufferFenceSync)(&commands[0],&consumed,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
enqueue(&waiter,&queues[0],P(nvnCommandBufferEndRecording)(&commands[0])); wr=returned(&waiter,250000000ull);
|
||||
} else {
|
||||
CHECK(P(nvnQueueWaitSync)(&queues[0],&produced),"wait-only queue accepts the producer dependency");
|
||||
P(nvnQueueFenceSync)(&queues[0],&consumed,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
}
|
||||
int wait_encoded=receipt_encoded(&consumed,1000000000ull); CHECK(wr && wait_encoded,"wait-only logical receipt publishes without adding GPU commands");
|
||||
CHECK(!landed(&produced,0) && !landed(&consumed,0),"published wait-only receipt remains pending until the producer GPU fence completes");
|
||||
gate.signaledValue=1; // always release the GPU before cleanup, including assertion failures
|
||||
require_returned(&producer,pr); if(command_wait) require_returned(&waiter,wr);
|
||||
int drained=landed(&produced,5000000000ull) && landed(&consumed,5000000000ull);
|
||||
CHECK(drained && *source==after,"wait-only fence completes after the actual producer GPU work"); if(!drained) _Exit(2);
|
||||
P(nvnSyncFinalize)(&produced); P(nvnSyncFinalize)(&consumed);
|
||||
}
|
||||
// The stale initial value must not satisfy a wait behind an earlier GPU reset.
|
||||
static void event_stale_gpu_reset(void) {
|
||||
printf("CASE queued GPU reset precedes equality evaluation\n");
|
||||
*source=before; *result=sentinel; P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,1);
|
||||
id<MTLSharedEvent> gate=[g_dev newSharedEvent];
|
||||
pthread_mutex_lock(&g_sub_mu); pthread_mutex_lock(&g_res_mu); [g_q4 waitForEvent:gate value:1]; pthread_mutex_unlock(&g_res_mu); pthread_mutex_unlock(&g_sub_mu);
|
||||
NVNsync reset,consumed; P(nvnSyncInitialize)(&reset,&device); P(nvnSyncInitialize)(&consumed,&device);
|
||||
begin_cmd(0);
|
||||
P(nvnCommandBufferSignalEvent)(&commands[0],&event,NVN_EVENT_SIGNAL_MODE_WRITE,NVN_EVENT_SIGNAL_LOCATION_BOTTOM,0,0);
|
||||
P(nvnCommandBufferFenceSync)(&commands[0],&reset,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
P(nvnCommandBufferWaitEvent)(&commands[0],&event,NVN_EVENT_WAIT_MODE_EQUAL,1);
|
||||
P(nvnCommandBufferCopyBufferToBuffer)(&commands[0],source_addr,result_addr,4,0);
|
||||
P(nvnCommandBufferFenceSync)(&commands[0],&consumed,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
job j; enqueue(&j,&queues[0],P(nvnCommandBufferEndRecording)(&commands[0])); int returned_=returned(&j,250000000ull);
|
||||
CHECK(returned_ && receipt_encoded(&reset,1000000000ull),"GPU reset prefix encodes without blocking submit");
|
||||
CHECK(!receipt_encoded(&consumed,100000000ull),"stale initial event value cannot release a wait behind an in-flight reset");
|
||||
gate.signaledValue=1;
|
||||
int reset_done=landed(&reset,5000000000ull);
|
||||
CHECK(reset_done && P(nvnEventGetValue)(&event)==0,"GPU reset reaches storage before the later CPU release");
|
||||
CHECK(!landed(&consumed,0) && *result==sentinel,"consumer remains parked after the reset");
|
||||
*source=after; P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,1);
|
||||
require_returned(&j,returned_); int done=landed(&consumed,5000000000ull);
|
||||
CHECK(done && *result==after,"later CPU release resumes the consumer with its new payload");
|
||||
if(!done) _Exit(2);
|
||||
P(nvnSyncFinalize)(&reset); P(nvnSyncFinalize)(&consumed);
|
||||
}
|
||||
static void receipt_tests(void) {
|
||||
receipt_unrelated_completion(); receipt_snapshot(0); receipt_snapshot(1); receipt_wait_only(0); receipt_wait_only(1);
|
||||
}
|
||||
static void event_mirror_publication(void) {
|
||||
printf("CASE terminal event waits for render-pass mirror publication\n");
|
||||
NVNtextureBuilder tb; NVNtexture texture; P(nvnTextureBuilderSetDefaults)(&tb);
|
||||
P(nvnTextureBuilderSetDevice)(&tb,&device); P(nvnTextureBuilderSetWidth)(&tb,8); P(nvnTextureBuilderSetHeight)(&tb,4);
|
||||
P(nvnTextureBuilderSetFormat)(&tb,NVN_FORMAT_RGBA8); P(nvnTextureBuilderSetStorage)(&tb,&pool,98304);
|
||||
NVNpackagedTextureLayout layout={{1,0,0,0,7,0,1,0}}; P(nvnTextureBuilderSetPackagedTextureLayout)(&tb,&layout);
|
||||
CHECK(P(nvnTextureInitialize)(&texture,&tb),"storage-backed render target initializes");
|
||||
memset(memory+98304,0xee,(size_t)P(nvnTextureGetStorageSize)(&texture));
|
||||
atomic_store(&event_test_pixel,0); atomic_store(&event_test_deferred_mirror,0); atomic_store(&event_test_storage,(uintptr_t)(memory+98304));
|
||||
P(nvnEventSignal)(&event,NVN_EVENT_SIGNAL_MODE_WRITE,0);
|
||||
NVNsync fence; P(nvnSyncInitialize)(&fence,&device);
|
||||
begin_cmd(0); const NVNtexture *colors[]={&texture}; float rgba[]={0.2f,0.4f,0.6f,1.f};
|
||||
P(nvnCommandBufferSetRenderTargets)(&commands[0],1,colors,NULL,NULL,NULL);
|
||||
P(nvnCommandBufferClearColor)(&commands[0],0,rgba,15);
|
||||
P(nvnCommandBufferSignalEvent)(&commands[0],&event,NVN_EVENT_SIGNAL_MODE_WRITE,NVN_EVENT_SIGNAL_LOCATION_BOTTOM,0,11);
|
||||
P(nvnCommandBufferFenceSync)(&commands[0],&fence,NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE,0);
|
||||
job submitted; enqueue(&submitted,&queues[0],P(nvnCommandBufferEndRecording)(&commands[0])); int sr=returned(&submitted,250000000ull);
|
||||
require_returned(&submitted,sr); int done=landed(&fence,5000000000ull);
|
||||
CHECK(done,"render clear and terminal signal complete"); if(!done) _Exit(2);
|
||||
CHECK(atomic_load(&event_test_deferred_mirror),"pass teardown appended the mirror after the recorded event post-op");
|
||||
CHECK(atomic_load(&event_test_pixel)==0xff996633u,"rendered bytes are already in guest storage when the event is published");
|
||||
CHECK(P(nvnEventGetValue)(&event)==11,"the terminal event publishes once the storage is visible");
|
||||
atomic_store(&event_test_storage,0); P(nvnSyncFinalize)(&fence); P(nvnTextureFinalize)(&texture);
|
||||
}
|
||||
int main(void) { @autoreleasepool {
|
||||
setbuf(stdout,NULL); setenv("DM_PSO_PREPARE","0",1);
|
||||
mtl_init();
|
||||
NVNdeviceBuilder db={0}; P(nvnDeviceBuilderSetDefaults)(&db); CHECK(P(nvnDeviceInitialize)(&device,&db),"device initialized");
|
||||
for(int i=0;i<2;i++) { NVNqueueBuilder qb={0}; P(nvnQueueBuilderSetDefaults)(&qb); P(nvnQueueBuilderSetDevice)(&qb,&device); CHECK(P(nvnQueueInitialize)(&queues[i],&qb),"NVN queue initialized"); }
|
||||
CHECK(!posix_memalign((void **)&memory,getpagesize(),131072),"pool storage allocated"); if(!memory) return 2; memset(memory,0,131072);
|
||||
NVNmemoryPoolBuilder pb={0}; P(nvnMemoryPoolBuilderSetDefaults)(&pb); P(nvnMemoryPoolBuilderSetDevice)(&pb,&device); P(nvnMemoryPoolBuilderSetStorage)(&pb,memory,131072); P(nvnMemoryPoolBuilderSetFlags)(&pb,0x24);
|
||||
CHECK(P(nvnMemoryPoolInitialize)(&pool,&pb),"memory pool initialized");
|
||||
source=(volatile uint32_t *)(memory+65536); result=(volatile uint32_t *)(memory+65540);
|
||||
NVNbufferBuilder bb={0}; NVNbuffer buffer; P(nvnBufferBuilderSetDefaults)(&bb); P(nvnBufferBuilderSetDevice)(&bb,&device); P(nvnBufferBuilderSetStorage)(&bb,&pool,65536,16); CHECK(P(nvnBufferInitialize)(&buffer,&bb),"buffer initialized");
|
||||
source_addr=P(nvnBufferGetAddress)(&buffer); result_addr=source_addr+4;
|
||||
NVNeventBuilder eb={0}; P(nvnEventBuilderSetDefaults)(&eb); P(nvnEventBuilderSetStorage)(&eb,&pool,65544); CHECK(P(nvnEventInitialize)(&event,&eb),"event initialized");
|
||||
pthread_t worker; if(pthread_create(&worker,NULL,submit_worker,NULL)) return 2;
|
||||
// Warm the actual copy/fence path before making bounded negative assertions.
|
||||
*source=before; *result=sentinel; NVNsync warm; P(nvnSyncInitialize)(&warm,&device); job w; enqueue(&w,&queues[0],consumer(0,0,&warm,0));
|
||||
require_returned(&w,0); int warm_ok=landed(&warm,5000000000ull); CHECK(warm_ok && *result==before,"real GPU copy and fence warm-up"); if(!warm_ok) _Exit(2); P(nvnSyncFinalize)(&warm);
|
||||
case_wait("CPU release equality",0,0,1,0);
|
||||
case_wait("equality rejects a larger value",0,2,1,0);
|
||||
case_wait("wrap accepts zero after ffffffff",1,0,0xffffffff,1);
|
||||
case_wait("wrap rejects ffffffff before zero",1,0xffffffff,0,0);
|
||||
case_wait("wrap accepts half-range minus one",1,0x7fffffff,0,1);
|
||||
case_wait("wrap rejects exactly half-range",1,0x80000000,0,0);
|
||||
case_cross_queue();
|
||||
event_stale_gpu_reset();
|
||||
receipt_tests();
|
||||
event_mirror_publication();
|
||||
pthread_mutex_lock(&jobs_mu); jobs_stop=1; pthread_cond_signal(&jobs_cv); pthread_mutex_unlock(&jobs_mu); pthread_join(worker,NULL);
|
||||
printf("wait-event fixture: %d checks, %d failed\n",checks,fails);
|
||||
// The process owns the fixture pool until all callbacks have retired.
|
||||
return fails?1:0;
|
||||
} }
|
||||
@@ -528,6 +528,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `CRASH sig=10` in `mtl_exec` after minutes of play, the fault address equal to `x19` and shaped like `0x1000000003`. → [Prerecorded lists in slots of their measured size](../reference/nvn-objects.md#prerecorded-lists-in-slots-of-their-measured-size)
|
||||
- a jump to pc=0 on a worker thread, with the backtrace `0x0` ← `cmd_alloc_keep` ← `h_nvnCommandBufferCopyBufferToTexture` and `lr` in the game's `main`, just after the instruction that called the game's command memory callback. → [Copy strides are command buffer state](../reference/nvn-objects.md#copy-strides-are-command-buffer-state)
|
||||
- the title showed one stretched 64×64 icon over the 3D scene, a new game a white screen; post-process passes with stale texture handles; `[RED] bind record … overwritten after recording`. → [Recorded commands patched in place by the game (`OP_BIND_TEX1`)](../reference/nvn-objects.md#recorded-commands-patched-in-place-by-the-game-op_bind_tex1)
|
||||
- intermittent scene-wide lighting flashes and a persistent pale outline around a character. Extra GPU readbacks or synchronous screenshots can make the flashes disappear temporarily. → [GPU event waits order work across queues](../reference/nvn-objects.md#gpu-event-waits-order-work-across-queues)
|
||||
- choosing X-2 after the collection launcher crashes in `keys_hash`, reading control address `0x8000000000`; the program object now contains command-buffer data. → [Bindings belong to each queue](../reference/nvn-objects.md#bindings-belong-to-each-queue)
|
||||
- about 23 s after launch, when the title screen hands over to the opening demo, a crash in `keys_hash` (`prog_key` ← `prog_get` ← `bind_stages` ← `prog_resolve` ← `mtl_queue_activate`), reading a control address made of float data; the program object now holds other data. → [Finalized programs leave every queue's bindings](../reference/nvn-objects.md#finalized-programs-leave-every-queues-bindings)
|
||||
- `nvnCommandBufferFenceSync` unimplemented, every `SyncWait` timed out at once. → [Fence syncs recorded in command buffers](../reference/nvn-objects.md#fence-syncs-recorded-in-command-buffers)
|
||||
@@ -697,6 +698,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- Scaleform fills come out as solid white or light grey sheets over the whole screen, hard-edged triangles and bands, and the menu text is missing (a language list or a title screen that is all white behind its button prompt). → [Vertex streams at addresses that are not 4-byte aligned](../reference/rendering.md#vertex-streams-at-addresses-that-are-not-4-byte-aligned)
|
||||
- hard-edged translucent slabs and triangles over the scene that move with the camera, where a full-screen pass blends an effect in (Super Mario Odyssey: white wedges through the Cascade Kingdom's waterfall mist, one edge through the centre of the screen). → [Vertex fetches past a stream's bound size](../reference/rendering.md#vertex-fetches-past-a-streams-bound-size)
|
||||
- scenes and characters black, only foliage, light shafts and the HUD drawn; pass dumps full of `Z … draw skipped: no program bound`. → [Programs bound per stage](../reference/rendering.md#programs-bound-per-stage)
|
||||
- a draw disabled by `SetRenderEnable(false)` executes after an event or fence, or a conditional clear erases a target whose preceding timestamp report should make it skip. → [Conditional rendering survives queue continuations](../reference/rendering.md#conditional-rendering-survives-queue-continuations)
|
||||
- `[RED] failed to create render pipeline (vertex 790573a52b9c5053_b fragment f39fb42850f50ecd_b): Fragment input(s) user(locn0),user(locn1) … not written by vertex shader`, once on entering the first investigation; `texture type mismatch: shader declares a cube, texture is 2D` (a pixel shader run with another pair's bindings). → [Composite program taken again after a replay state restore](../reference/rendering.md#composite-program-taken-again-after-a-replay-state-restore)
|
||||
- `no program bound before the draw`, `program has no vertex shader` (a draw after a dispatch is dropped); `the dispatched program has no compute shader` (a dispatch after a graphics bind). → [Compute programs bound apart from graphics programs](../reference/rendering.md#compute-programs-bound-apart-from-graphics-programs)
|
||||
- a red line: the 8-bit index buffer had GPU-side writes in the submission (indices read stale). → [8-bit indices widened on the GPU after a write in the same submission](../reference/rendering.md#8-bit-indices-widened-on-the-gpu-after-a-write-in-the-same-submission)
|
||||
@@ -1012,6 +1014,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- the picture bright green and white from some scene on, in runs with pipelines compiled on demand (prewarm lists off or short) and in none with `DM_NVN_PREDICT=0`. → [The precompile look-ahead restores the scissor](../reference/shaders.md#the-precompile-look-ahead-restores-the-scissor)
|
||||
- a GPU frame capture (`DM_GPU_CAPTURE`, or Xcode with `MTL_CAPTURE_ENABLED=1`) fails with `Capturing Render pipeline specialization is not supported`, or the capture layer crashes on the pipeline archive; a capture of the `MTLDevice` is refused. → [GPU frame captures need pipelines built through the device](../reference/shaders.md#gpu-frame-captures-need-pipelines-built-through-the-device)
|
||||
- the first boot sat on the loading clock for about a minute, the CPU idle, with every file read done after 12 s. → [A cold Metal cache looks like a long load](../reference/shaders.md#a-cold-metal-cache-looks-like-a-long-load)
|
||||
- missing geometry or bright patches just after loading, which disappear as background pipeline compilation finishes. → [Native mesh draws omitted while their pipeline compiles](../reference/shaders.md#native-mesh-draws-omitted-while-their-pipeline-compiles)
|
||||
- hundreds of geometry raster passes in combat, despite support for batching consecutive geometry draws. → [Geometry runs across occlusion query boundaries](../reference/shaders.md#geometry-runs-across-occlusion-query-boundaries)
|
||||
- geometry preparation dominates rendering CPU even after geometry passes have been batched; primitive assembly and capture-index deduplication repeat for unchanged meshes. → [Prepared geometry indices reused after byte comparison](../reference/shaders.md#prepared-geometry-indices-reused-after-byte-comparison)
|
||||
- geometry vertex-capture passes consume substantial GPU time before geometry compute or depth rasterization. → [Geometry capture initializes only missing words](../reference/shaders.md#geometry-capture-initializes-only-missing-words)
|
||||
|
||||
@@ -546,6 +546,8 @@ The benchmark gives each frame's GPU time; these switches split it by pass, on t
|
||||
|
||||
`DM_NVN_CAPTURE=<frame>:1:<path>` (an NVN game, Mac host) writes one frame to one file, at the boundary between recording and replay: from the frame's first `nvnQueueSubmitCommands` to its present (frames counted as `DM_NVN_SHOT` counts them). `dm/gfx/tests/nvn_replay` replays it against the replay layer of the tree it is built from (`nvn_mtl.m` and everything under it) and compares the presented frame with the live one:
|
||||
|
||||
Format 1 supports a single logical NVN queue without event or sync waits. The capture refuses a run that has used multiple queues or either wait operation, with a `[RED]` diagnostic and a failure marker at the requested path: physical replay order cannot represent those dependencies. The standalone replayer rejects failure markers and wait records before starting Metal. Existing captures without waits remain readable; capturing logical queue dependencies is still open.
|
||||
|
||||
```sh
|
||||
DM_NVN_CAPTURE=900:1:<NSP folder>/<id>-work/capture/frame900.nvncap DM_PSO_HYBRID=0 … dm/host/dmhost <modules>
|
||||
make -C dm/gfx/tests GAME=<id> nvn_replay
|
||||
|
||||
@@ -289,6 +289,14 @@ Games read this count as a position in their own command memory and size their h
|
||||
|
||||
## Queues and syncs
|
||||
|
||||
### GPU event waits order work across queues
|
||||
|
||||
- **Symptom:** intermittent scene-wide lighting flashes and a persistent pale outline around a character. Extra GPU readbacks or synchronous screenshots can make the flashes disappear temporarily.
|
||||
- **Cause:** `nvnCommandBufferWaitEvent` was registered as a no-op. Serializing NVN submissions onto one Metal queue only orders them by CPU arrival; a consumer can be submitted before its producer on another NVN queue. Its acquire must park that queue until the producer releases the event. The native SDK implements exact equality and wrapping greater-or-equal (`(uint32_t)(current - target) < 0x80000000`), and its CPU event signal publishes earlier writes with a store barrier. Ignoring either dependency lets a consumer read cleared or stale shared data.
|
||||
- **Fix:** `nvn_queue.inc` retains submitted command streams and replays ready continuations. An unresolved event or sync wait parks only its NVN queue; another queue can submit and execute its producer. GPU event signals end physical submission prefixes and publish after their completion writes, including render-target readback. CPU signals publish with release ordering. Logical queue receipts remain separate from physical Metal fences: a fence on parked work cannot accidentally inherit another queue's completion, and a queued sync wait retains its original target through later refencing. Presents remain in queue order. Descriptor snapshots and retained renderer objects survive deferred replay; the caller still owns backing-memory lifetime.
|
||||
- **Check:** `t_wait_event` exercises public NVN calls, CPU and GPU producers, wrapping predicates, a consumer submitted before its producer, and logical sync lifetime. `t_queue_lifetime` checks submitted program/texture descriptor reuse and inherited queue bindings. The focused event, receipt, descriptor and lifecycle checks pass; combined gameplay and performance validation are still pending.
|
||||
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#open), M4 Pro. Its traced lighting producer and ambient-cache consumer have an explicit event dependency; this is a general queue contract, with no shader-key or game check in the fix.
|
||||
|
||||
### Bindings belong to each queue
|
||||
|
||||
- **Symptom:** choosing X-2 after the collection launcher crashes in `keys_hash`, reading control address `0x8000000000`; the program object now contains command-buffer data.
|
||||
@@ -309,14 +317,14 @@ Games read this count as a position in their own command memory and size their h
|
||||
|
||||
- **Symptom:** `nvnCommandBufferFenceSync` unimplemented, every `SyncWait` timed out at once.
|
||||
- **Cause:** Pokémon Legends: Z-A fences once per frame from a command buffer and waits on it; Unreal's RHI records the call in its command buffers too.
|
||||
- **Fix:** a record (`OP_FENCE_SYNC`) fences the sync at replay with the fence value of the submission segment being encoded, so it signals once everything before it has completed (the replay fences the sync with the submission that reaches it).
|
||||
- **Fix:** a record (`OP_FENCE_SYNC`) establishes a logical receipt when submitted. Replay publishes its physical fence only after the preceding queue commands have been encoded; `SyncWait` then waits for that fence and its CPU-visible completion writes. An earlier unresolved event keeps the receipt pending even if another queue completes newer physical submissions ([GPU event waits](#gpu-event-waits-order-work-across-queues)).
|
||||
- **Found on:** [Pokémon Legends: Z-A](../../dm/games/0100F43008C44000/README.md) (19.3.11; one boot); [Octopath Traveler 0](../../dm/games/01005270232F2000/README.md) (new with Unreal).
|
||||
|
||||
### Submissions from two queues on two threads
|
||||
|
||||
- **Symptom:** `FATAL submit re-entered` in the first frames.
|
||||
- **Cause:** the game initializes two NVN queues and submits on both from two threads, while the Metal replay keeps one command buffer for the submission in progress.
|
||||
- **Fix:** `nvnQueueSubmitCommands` now holds a lock across the replay (`g_sub_mu` in `hle_nvn.c`). It takes the lock before the graphics gate ([Going to the background during the prepare step](#going-to-the-background-during-the-prepare-step)).
|
||||
- **Fix:** ready queue continuations replay under one lock (`g_sub_mu` in `hle_nvn.c`); submission copies its command stream and descriptors under the same lock. Queue dependencies determine which continuation can run ([GPU event waits](#gpu-event-waits-order-work-across-queues)). Replay takes the lock before the graphics gate ([Going to the background during the prepare step](#going-to-the-background-during-the-prepare-step)).
|
||||
- **Found on:** [Fire Emblem: Three Houses](../../dm/games/010055D009F78000/README.md).
|
||||
|
||||
### Going to the background during the prepare step
|
||||
@@ -324,7 +332,7 @@ Games read this count as a position in their own command memory and size their h
|
||||
- **Symptom:** going to the background (iOS `sceneDidEnterBackground`, minimizing the Mac window) while the "Preparing shaders" or "Preparing pipelines" screen is up blocks the main thread until the step ends: minutes on a first start, long enough for iOS to end the app. The log's `[nvn] graphics suspended` line comes only after the `pipeline prepare:` line.
|
||||
- **Cause:** the prepare step (the prewarm and the pipeline prebuild, `mtl_prepare` in `nvn_mtl.m`) runs in the game's first `nvnQueueSubmitCommands`, which held the graphics gate across it. `dm_gfx_suspend(1)` closes the gate and waits for every submit and present inside it to leave. The step loads shaders and builds pipelines and submits no GPU work, so it never needed the gate.
|
||||
- **Fix:** the submit entry runs the prepare step under the submit lock (`g_sub_mu`) but before it enters the gate, marked as host work for the guest scheduler (`dm_host_work`). If the app went to the background meanwhile, the submission waits at the gate for the foreground like any other. The lock now comes before the gate, taken with `dm_host_mutex_lock`: with the gate first, a second submission waiting for the lock counted as in flight, so the suspend waited for it while the first, done preparing, waited at the closed gate holding the lock. `mtl_sub_begin` still calls `mtl_prepare`, a no-op by then, for the replay tool (`nvn_replay`), which has no gate.
|
||||
- **Check:** the CPU-only `t_gfx_suspend` runs the real submit entry on two threads with a prepare step held by semaphores. It checks that the step runs outside the gate as host work, that the queued second submission is not in flight, that the suspend returns while the step holds the lock, that nothing commits in the background, and that both submissions finish after resume. With the gate taken before the lock it fails before suspending.
|
||||
- **Check:** the CPU-only `t_gfx_suspend` runs the real submit entry on two threads with a prepare step held by semaphores. It checks that the step runs outside the gate as host work, that the queued second submission is not in flight, that the suspend returns while the step holds the lock, that nothing commits in the background, and that both queued submissions execute after resume. It also suspends with an unresolved event, releases that event in the background, and verifies that its continuation executes only after resume. With the gate taken before the lock it fails before suspending.
|
||||
- **Found on:** no game named in the source (general: every NVN game with a prewarm list; a first start without the Metal cache takes longest). **Open:** not yet run by going to the background during a real game's prepare step on an iPhone.
|
||||
|
||||
### A GPU command buffer that never completes
|
||||
|
||||
@@ -881,6 +881,14 @@ The replay on Metal (`dm/gfx/nvn/nvn_mtl.m`) and the Vulkan and OpenGL layers. E
|
||||
- **Found on:** [Metroid Dread](../../dm/games/010093801237C000/README.md): the combinations it uses are (program, 0x3), (null, 0x2), (null, 0x7). [13 Sentinels: Aegis Rim](../../dm/games/01003FC01670C000/README.md) builds one program per GLSLC output and pairs them only through these composites ([Single-stage programs paired with a cover](shaders.md#single-stage-programs-paired-with-a-cover)).
|
||||
- **Note:** pass dumps print a `Z` line wherever a draw is dropped (no program, no pipeline, empty scissor, both faces culled, no render pass). That is how this one was found: 144 `Z … draw skipped: no program bound` lines in a frame whose G-buffer pass had draws but stayed black.
|
||||
|
||||
### Conditional rendering survives queue continuations
|
||||
|
||||
- **Symptom:** a draw disabled by `SetRenderEnable(false)` executes after an event or fence, or a conditional clear erases a target whose preceding timestamp report should make it skip.
|
||||
- **Cause:** physical submission initialization reset the global render-enable state and discarded known pending counter values. A logical NVN queue can continue across several Metal submissions, including [event waits](nvn-objects.md#gpu-event-waits-order-work-across-queues); those boundaries do not reset its render state. Timestamp reports are written to guest memory at GPU completion, so reading their old CPU bytes before that completion also gives the wrong predicate.
|
||||
- **Fix:** render-enable state belongs to the logical queue. Known timestamp counter values survive physical prefixes until their completion writes land. Completion expires that knowledge before an event release can wake a CPU writer; a later CPU rewrite therefore remains visible. Later inline updates, fills and copies replace overlapping counter bytes and carry the latest writer’s completion fence. Copy sources with unfinished or unknown GPU writes remain unknown. This preserves the existing conservative treatment of unavailable occlusion-query results.
|
||||
- **Check:** `t_render_enable_queue` uses the public NVN API and pixel readback to cover event, signal, sync and fence boundaries, independent queues, pending reports behind a GPU gate, and a later CPU counter rewrite. Seven checks failed before the fix; all 38 pass in both encoding modes with Metal validation. `t_render_counter_overlap` adds 42 checks for explicit updates, fills, copies, partial writes and a second fence; five predicates failed before the metadata fix and all pass in both encoding modes. This does not resolve the older CPU-post report emulation: a later GPU read can still observe the report’s previous bytes, and a late CPU report write can overwrite a later GPU write. Those limitations are recorded separately by the fixture. The game note records visual validation.
|
||||
- **Found on:** the queue-ordering investigation for [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#open), M4 Pro.
|
||||
|
||||
### Composite program taken again after a replay state restore
|
||||
|
||||
- **Symptom:** `[RED] failed to create render pipeline (vertex 790573a52b9c5053_b fragment f39fb42850f50ecd_b): Fragment input(s) user(locn0),user(locn1) … not written by vertex shader`, once on entering the first investigation; `texture type mismatch: shader declares a cube, texture is 2D` (a pixel shader run with another pair's bindings).
|
||||
|
||||
@@ -2123,6 +2123,13 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Check:** screenshots every few seconds (`ctl.sh snap` from a script) told the two apart.
|
||||
- **Found on:** [Bayonetta 3](../../dm/games/01004A4010FEA000/README.md) (SDK 13.3.2).
|
||||
|
||||
### Native mesh draws omitted while their pipeline compiles
|
||||
|
||||
- **Symptom:** missing geometry or bright patches just after loading, which disappear as background pipeline compilation finishes.
|
||||
- **Cause:** `mtk_pso` started an asynchronous native task/mesh pipeline build and returned no pipeline; the draw was omitted until a later frame found the completed pipeline. This copied the geometry-mesh optimization's behavior without its equivalent compute fallback. Native mesh draws have no such replacement. Metal validation also rejected the helper descriptor assigning a mesh function to `vertexFunction` before copying its raster state.
|
||||
- **Fix:** compile the demanded native mesh pipeline before issuing its first draw, then reuse the cached pipeline. The shared descriptor helper leaves `vertexFunction` unset for a native mesh shader; the mesh descriptor receives it as `meshFunction`. A cold pipeline can delay the first frame but cannot silently remove its draw. `t_mesh_first_use` exercises real NVN submissions with mesh-only, task/mesh, depth-only and ordinary vertex shaders: the old host failed 10 of 42 pixel/state checks; the fixed host passes all 42 with Metal validation in both encoding modes.
|
||||
- **Found on:** [Ocarina of Time](../../dm/games/0400486024DEC000/README.md), M4 Pro startup white patches. The synthetic GPU regression verifies the missing-draw mechanism; the corrected game's startup remains to be checked with the queue fix.
|
||||
|
||||
### Geometry runs across occlusion query boundaries
|
||||
|
||||
- **Symptom:** hundreds of geometry raster passes in combat, despite support for batching consecutive geometry draws.
|
||||
|
||||
Reference in new issue
Block a user