diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md
index adb32c9e1..4d22fb1e5 100644
--- a/docs/macos/configuration.md
+++ b/docs/macos/configuration.md
@@ -54,6 +54,9 @@ them for measurements or to isolate a problem.
| `SHARPEMU_METAL_V2_IMAGE_BUDGET_MB` | computed | Fixed byte budget for the detiled image cache, at least 256. By default the budget follows the memory the host has free. |
| `SHARPEMU_METAL_V2_SINGLE_COPY` | on | `0` never releases guest memory that a clean texture's Metal copy duplicates. Requires the chunked guest backing. |
| `SHARPEMU_METAL_V2_WHOLE_STALE_RELOAD` | on | `0` restores the old refusal: a GPU-written image whose every byte an alias has since written keeps its older texels instead of reloading them, and writes them back over the alias's bytes. For A/B comparisons only. |
+| `SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS` | on | A streamed texture whose T# starts past mip 0 is described from that level (upstream's resident-mip textures, `ImageDescription.FirstLevel`). The image cache looks it up as its whole chain and, while the guest has not mapped that chain, never holds or reads a level before the binding's base level, whatever `SHARPEMU_METAL_V2_BASE_LEVEL` says. Image uploads read guest bytes as upstream does: every byte must be mapped (or partially resident PRT/AMM memory), else the GPU stops with `Could not read the mapped guest image backing`; `SHARPEMU_IMAGE_BACKING_HOLES=1` reads unmapped pages after a mapped first page as zero instead. `0` keeps whole-chain requests and reads image bytes as a binding does (the readable prefix, zeros after it). |
+| `SHARPEMU_METAL_V2_BINDLESS_UNMAPPED_NULL` | on | A bindless texture table entry whose image's first byte the guest has not mapped binds the null texture and is looked up again at every bind until the memory is mapped, as the Vulkan bindless heap skips such a record. The counter `BindlessUnmappedEntries` counts them. `0` uploads the entry, which stops the GPU with `Could not read the mapped guest image backing` unless the bytes are partially resident PRT/AMM memory. |
+| `SHARPEMU_MANAGED_WRITE_LEASE_GATE` | on | An emulator write into guest GPU memory takes the managed-write lease (`GuestWriteReservations`) only after a backend that makes GPU claims has registered. The Vulkan buffer cache registers when it is built; the Metal backend makes no claims, so on macOS a managed write marks its pages before and after the copy, as before the lease existed. `0` makes every managed write take the lease, as upstream does. |
| `SHARPEMU_METAL_V2_STAGED_CACHE_MB` | `256` | Budget of the staged-range cache. |
| `SHARPEMU_METAL_V2_TRANSIENT_COMMIT_MB` | `256` | Transient staging a command buffer may hold before it is committed early. |
| `SHARPEMU_METAL_V2_RESIDENCY_SET` | off | `1` puts every guest window in an `MTLResidencySet`. |
@@ -65,11 +68,26 @@ them for measurements or to isolate a problem.
| Variable | Default | Effect |
| --- | --- | --- |
| `SHARPEMU_METAL_MESH_SHADERS` | on | `0` disables mesh pipelines for primitive-shader draws. |
+| `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. |
+| `SHARPEMU_METAL_BINDLESS_HEAP` | on | `0` turns off the bindless heap. By default an image or sampler a program reads from a descriptor table at a record only the shader knows is read through the heap: the shader marks the records it reads, the host resolves each marked record's texture or sampler from guest memory, and the program reads it from a later draw on (the first read of a record returns zeros). `0` plans those tables as before (bindless image tables, at most 256 candidates, off-class candidates read null). |
+| `SHARPEMU_HEAP_BULK_READS` | on | `0` reads each bindless heap record on its own when the host compares a heap view's records with guest memory again. By default the records of a view are read in runs of nearby records (at most 64 KiB, gaps of at most 1 KiB), one guest read per run; a run that cannot be read (a page a GPU write may still own, an unmapped one) falls back to the per-record read for its records, and a record that resolved ends its run. Same name and default as upstream's switch. |
+| `SHARPEMU_METAL_SHADER_CALLS` | on | `0` turns off linked shader calls, as before they were ported to Metal. By default a program that calls functions with `S_SWAPPC_B64` is compiled with its callees linked in: the call compares the caller's address and argument with the dispatch's call targets and runs the matching callee. With the bindless heap on, a program can also be linked with run-time call records: the host writes the table of each dispatch's records and resolves the images and samplers they hold into the heap, and a call to a callee the program lacks is marked so the program cache links it later. A call that no record names ends its wave and logs `[UNLINKED_CALL]`. `0` compiles the caller alone, which skips the call. The callee lists are kept in `pipeline_cache/
/metal-v2/linked`. `SHARPEMU_CALL_RECORD_SPANS=0` reads each record field by field instead of once per record (same result); `SHARPEMU_RUNTIME_CALL_RECORDS=0` links one copy of a callee per record instead of using run-time records. |
+| `SHARPEMU_METAL_SHARED_CALL_BODIES` | on | `0` inlines one copy of a callee per record, as the call linker emits it. By default the copies of one callee at one call site of a program linked per record (`SHARPEMU_RUNTIME_CALL_RECORDS=0`, or a caller the program cache links per record) share one body: each record's entry stores its slot and branches into the last copy, and an instruction whose records bind different resources is emitted once per record under a test of the slot. The MSL source and the Metal compile then grow with the records' tests instead of records x callee size (64 records of a 34-instruction callee: 207 KB / 65 ms instead of 1282 KB / 206 ms). Same results either way. |
+| `SHARPEMU_METAL_STABLE_IMAGE_BINDINGS` | on | `0` gives every program compact image bindings again. By default a program whose images fit Metal's per-stage argument-buffer limits (textures 1M; samplers 996 on Apple7/8, 500K on Apple9+, at most `maxArgumentBufferSamplerCount`) binds one texture per image slot, so one specialization serves every draw however its slots repeat descriptors (fewer shader compiles). Programs over the limits, and bindless, indirect, linked and dynamic-mip ones, keep compact bindings (one texture per distinct descriptor). The setting is part of the shader prewarm stamp: changing it re-prewarms once. |
+| `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. |
+| `SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS` | on | `0` restores the old bound of a formatted buffer load whose format is fixed at translation: the whole element had to fit below the buffer's size. By default each selected component is checked at its own address, wrapping past 2^32 as on the hardware, so a component that wraps to the buffer's start is read, and the load reads its constants only when a selected component is out of range. An element that fits whole still takes one compare. Loads whose format is read at run time always check per component. |
+| `SHARPEMU_METAL_SHADER_CLOCK_STEP` | on | Metal has no shader clock, so `S_MEMTIME`/`S_MEMREALTIME` read a per-invocation counter of their own reads (logged once per shader as `[MSL][WARN][SHADER_CLOCK]`). By default each read moves it 2^32 + 1, as upstream's SPIR-V fallback moves its high dword: a guest wait on the 64-bit difference for fewer than 2^32 ticks ends at its next read, and a wait on the low dword still sees one tick per read. `0` steps by 1, so such a wait runs one loop trip per tick. |
+| `SHARPEMU_METAL_PIXEL_SUBGROUP_ARITHMETIC` | on | `0` turns off the wave32 row reductions in translated pixel shaders. By default, on a GPU with SIMD-group reductions (Apple7 and later, every Apple silicon Mac), a pixel shader's DPP row scan read at lane 15 or 31 is computed as a SIMD-group reduction over its row, so a row of the guest wave the fragment simdgroup holds no fragment of reads the identity as on the PS5. `0` keeps the scan's own lane reads. |
+| `SHARPEMU_GRAPHICS_PARTIAL_LANES` | off | `1` makes pixel-shader lane reads (DPP, DPP8, PERMLANE16, V_READLANE) of a lane the fragment simdgroup never launched read the reading lane's own value, and treats such a lane as active when the guest EXEC mask has its bit. Off by default, as upstream: it changes every pixel shader with cross-lane operations. |
| `SHARPEMU_METAL_MESHLETS` | on | `0` disables the meshlet cache. |
| `SHARPEMU_METAL_V2_BINARY_ARCHIVE` | on | `0` disables the on-disk library and pipeline archives. |
| `SHARPEMU_METAL_V2_BINARY_ARCHIVE_BUDGET_MB` | `8192` | Size bound of the archives on disk. |
+| `SHARPEMU_TRANSLATION_CACHE` | on | `0` stops keeping translated shaders on disk. By default each translation (MSL and its reflection) is kept in `pipeline_cache//metal-v2/translations`, up to 8 GiB per game, and a later session of the same build takes it from there instead of translating the program again. A new build, translator switch, device or OS uses a new folder. |
+| `SHARPEMU_SHADER_ANALYSIS_CACHE_PATH` | per game | Folder of the scalar-graph cache of shader planning. By default `pipeline_cache//metal-v2/analysis`; `0` turns the cache off. |
| `SHARPEMU_METAL_V2_ASYNC_PIPELINES` | on | `0` builds pipeline states on the GPU worker thread. |
+| `SHARPEMU_METAL_COMPUTE_COMPILE_WAIT` | on | A dispatch that must have its compute pipeline, and a linked module's bounded wait, wait on the compile still running for it (as upstream's host hands it out) instead of polling every millisecond. `0` polls as before. |
| `SHARPEMU_METAL_V2_ASYNC_LIBRARIES` | on | `0` compiles each shader library on the thread that needs it, not on the compile pool. |
+| `SHARPEMU_METAL_V2_GRAPHICS_WAIT_OFF_CACHE` | on | A draw that cannot be left out while its pipeline compiles waits for the compile outside the shared pipeline cache's lock, so other draws' programs keep resolving. `0` builds the pipeline under the lock, as before. Only with `SHARPEMU_METAL_V2_ASYNC_GRAPHICS` on. |
| `SHARPEMU_RESOLVE_SHARDS` | `1` | Threads that resolve draw and dispatch programs ahead of the GPU worker, 1 to 8. With more than one, each has its own queue and its own part of the resolve memo, and a draw always goes to the same one. `1` is the single resolver; `2` measured no frame-time gain in Demon's Souls for more resolver CPU. Logged once at start; per-thread counts and the shared-lock wait are in the `shards=(...)` field of the `[METAL-V2][PERF]` prefetch counters. |
| `SHARPEMU_PREFETCH_EXACT_EFFECTS` | on | A dispatch or draw resolved ahead of a dispatch the host consumed as a kernel fill or copy is no longer refused for that alone: its take refuses it only when the fill's or copy's logged write covers what its resolution read (the same check as across any other dispatch). DCC and constant fills, image clears, metadata clears, image copies and CPU-predicted dispatches still refuse every dispatch and draw resolved ahead of them. The prefetch counters report `dispatch_effects=(...)` by kind and `exact_effects=(mode,refused,taken,draws,draw_refused,draw_taken)`, the jobs the old rule would have refused that the check refused or took. `dispatch` keeps the old rule for draws only; `0` refuses on every effect again. |
| `SHARPEMU_RESOLVE_UNSHARED_COMPUTE` | on | With more than one resolve shard, a dispatch whose kept program still holds, or whose kept program only needs new user data on a fast plan with a permutation already made, is answered on its own thread without the shared lock. `0` sends every dispatch through the shared lock. The `shards=(...)` counters split the shared-lock takes and wait by reason (`shared_by=`, `shared_wait_by=`) and count the dispatches answered without it (`unshared_compute=`) and why a rebinding still took it (`rebind_shared_by=`). |
@@ -114,6 +132,24 @@ undoes an optimization to isolate a miscompile:
| `SHARPEMU_METAL_V2_BUFFER_WORD_COMPUTE` | on | The same variants for compute pipelines: a dispatch runs the generic pipeline until a background compile has made the one with its words folded in (same results). Off whenever `SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS=0`. `0` keeps every compute dispatch on its generic pipeline while draws keep their variants, so the two can be measured apart; it does not change the MSL. The periodic counter line reports `buffer_words_compute=[...]` (`generic_off` counts dispatches the switch kept generic). |
| `SHARPEMU_LOD_STATS` | guarded | `always` compiles the LOD statistics counters into every pixel pipeline. |
+## GPU command stream
+
+| Variable | Default | Effect |
+| --- | --- | --- |
+| `SHARPEMU_METAL_V2_DEFERRED_LABEL_LANDINGS` | on | An end-of-pipe label that Metal defers to GPU completion still reports the submission it lands with, so another queue's soft wait (`SHARPEMU_END_OF_PIPE_SOFT_WAITS`) ends when that submission completes. `0` gives deferred labels no landing again: such a wait ends only at its cap. |
+| `SHARPEMU_METAL_V2_DYNAMIC_STENCIL_OPS` | on | A draw's stencil operations and compare functions come from its own dynamic state, not from the draw its pipeline was first built for. `0` takes them from the pipeline again. |
+| `SHARPEMU_DRAW_REPLAY` | on | A draw that repeats the command-thread item before it in all but its user data (same programs, descriptor words, vertex input and targets) binds what that draw bound, with its own user data patched into the push data, instead of preparing and binding again (`MetalRenderHost.Replay.cs`). The host refuses, and the draw takes the full path, when anything that binding stood on has moved: the command buffer, the render pass, the image cache's binding epoch or image set, a read-only buffer's or vertex stream's read-binding memo answer, or the stage object. Draws with written buffers, storage images, movie planes, bindless tables, device addresses or per-draw argument fields are never captured. The `[METAL-V2][TBDR]` line reports the engine's `draw_replays` / `replay_miss` and the host's `replay_host=(draws,captured,capture_refused=[...],miss=[...])`. Needs the command thread (`SHARPEMU_METAL_V2_COMMAND_THREAD`, on). `0` binds every draw in full. |
+| `SHARPEMU_DISPATCH_REPLAY` | on | The same for a compute dispatch that repeats the one before it in all but its user data and thread limits: its shader data is built again from its own snapshot, and a dispatch that writes takes its buffers' whole binding chain again (a range other than the captured one rewrites the argument buffer, counted as `rebound`). Reported as `dispatch_replay_host=(...)` on the same line. `0` binds every dispatch in full. |
+| `SHARPEMU_POSTED_WORD_COPY` | on | A bounded word-copy kernel whose source is final and whose destination holds no image or surface metadata is taken out of the dispatch path at its place in the stream. The counter line reports `word_copy=[posted=...,unsupported=...,image=...,busy=...,host_store=...]`. `0` runs every such kernel as a dispatch. |
+| `SHARPEMU_METAL_V2_POSTED_WORD_COPY_HOST_STORE` | on | How a posted word copy is applied. Upstream's Vulkan host stores the words on the host, which is sound there because GPU readers take a copy of their bytes when recorded. Metal reads guest memory in place, so the store is taken only when no recorded or submitted GPU work remains (`host_store`); otherwise the copy is refused as `busy` and runs as its dispatch, which readers read through as a pending copy. `0` posts every copy as a held command-processor write instead, which costs Demon's Souls about 20 ms a frame. |
+| `SHARPEMU_METAL_V2_CONCURRENT_OVERLAY_READS` | on | A look-ahead resolution, and the render thread's clean read, take words a pending command-processor write still owes from that write's overlay when it covers them whole, instead of abandoning the resolution or waiting for the GPU. Counted as `concurrent_overlay_reads` and `clean_overlay_reads`. `0` abandons and waits as before. |
+| `SHARPEMU_DISPATCH_OVERLAP_HAZARDS` | on | A dispatch the stream marks as free to overlap the ones before it (no barrier between them) is ordered after them when it reads what one of them wrote, writes what one of them touched, or either side's accesses are not all known. The console overlaps such dispatches too, but a dependency its timing hides is a race on the host. Counted as `overlap_ordered=[hazard:...,unknown:...]`. `0` honours every mark. |
+| `SHARPEMU_DISPATCH_OVERLAP_WRITES_APART` | on | Two marked dispatches that only write the same buffer bytes or the same image, with no read on either side, stay beside each other. `0` orders them. |
+| `SHARPEMU_DISPATCH_OVERLAP_ATOMICS_APART` | on | Two marked dispatches whose shared buffer bytes both sides touch only through atomics (a counter chain) stay beside each other. `0` orders them. |
+| `SHARPEMU_DISPATCH_OVERLAP_IMAGE_SPANS` | on | Two images conflict for the overlap check only where their guest bytes meet. `0` treats any image written beside any image read or written as a conflict. |
+| `SHARPEMU_GUARD_READS_REFUSE_PENDING` | on | A branch predicate word of a shader that writes memory (upstream's branch blocks for writers) is answered from the pending command-processor overlay or pending copy when a GPU write still owes it, and otherwise refused, so the shader keeps both paths of that branch. Counted as `guard_refused` in `clean_under_write`. `0` makes the render thread wait for the GPU and the look-ahead abandon, about 90 waits every 2 s in Demon's Souls. |
+| `SHARPEMU_METAL_V2_POSTED_WORD_COPY_EXACT_IMAGE` | on | A posted word copy is refused for an image only when an image's guest bytes lie in its destination. Sharing a page with an image is not enough (upstream 90d306cb1). `0` refuses any destination an image shares a page with. |
+
## Diagnostics
| Variable | Effect |
diff --git a/docs/sharpemu-gui-undocumented-env-vars.md b/docs/sharpemu-gui-undocumented-env-vars.md
index 0bdaf50d7..d7d5ed7c8 100644
--- a/docs/sharpemu-gui-undocumented-env-vars.md
+++ b/docs/sharpemu-gui-undocumented-env-vars.md
@@ -111,7 +111,7 @@ result filters, mutex warning sampling, and diagnostic selection.
| Group | Variables |
| --- | --- |
| Behavior switches | 19 |
-| GPU and Vulkan | 61 |
+| GPU and Vulkan | 63 |
| GnmMode | 4 (plus 2 shared switches listed below; trophy key also exposed in GUI) |
| Audio and video | 6 |
| Input | 5 |
@@ -235,11 +235,13 @@ These variables change the GPU path or the Vulkan presenter.
| `SHARPEMU_FORCE_TITLE_VERTEX_OUTPUTS_ONE` | `1` | Vertex export targets 32 to 35 write the vector (1, 1, 1, 1). This applies only to the vertex shader at guest address 0x0000000500780000. Default is off. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_GPU_BACKEND` | `vulkan` or `metal` | Optional assertion of the guest GPU backend. Each host has exactly one backend (Metal on macOS, Vulkan on Windows and Linux); any other value stops startup with an error. | `GuestGpu.cs` |
| `SHARPEMU_GPU_WAIT_SPIN_US` | number (microseconds) | Sets how long a wait for GPU work polls before it blocks. A short poll saves the wake-up delay when the GPU finishes soon. `0` blocks at once. The default is 150. | `GpuWaitSpin.cs` |
+| `SHARPEMU_GRAPHICS_PIPELINE_LIBRARY` | `0` | `0` builds every graphics pipeline whole, with one descriptor set. By default, on a device that links `VK_EXT_graphics_pipeline_library` parts fast, the vertex input, vertex stage, pixel stage and color outputs compile once as separate parts and each pipeline links them: the vertex set is pushed, the bindless heap is set 1 and the pixel set comes from a descriptor pool. Render workers take pixel sets from their own pools, which return when the slice's submission completes. Enabling the extension changes the device, so the driver may compile every pipeline again after a change. | `VulkanVideoPresenter.PipelineLibraries.cs`, `VulkanVideoPresenter.Device.Setup.cs` |
| `SHARPEMU_GRAPHICS_SUBGROUPS` | `0` or `1` | Set `1` to use native Vulkan subgroup operations in graphics shaders. Set `0` to use the fallback path. When unset, the presenter uses them only if the subgroup size is 32 and the vertex and fragment stages support subgroups. | `VulkanVideoPresenter.cs`, `VulkanVideoPresenter.Device.Setup.cs` |
| `SHARPEMU_IMAGE_LOOKUP_MEMO` | `0` | `0` turns off the image lookup memo. The default keeps the result of each image lookup that found an image with the same backing, and gives it again for the same request until an image is registered or removed. | `GuestImageCache.Lookup.cs` |
| `SHARPEMU_OCCLUSION_GPU_DUMPS` | `0` | `0` turns off GPU copies of pending occlusion results. By default, later GPU buffer reads receive these results without waiting for CPU publication. Guest memory publication remains ordered in both modes. | `VulkanVideoPresenter.Occlusion.cs`, `VulkanOcclusionQueries.GpuResults.cs` |
| `SHARPEMU_MARK_PIXEL_PCS` | list of `pc:register` pairs | Makes the SPIR-V pixel shader write the float value 1.0 to a shader register when execution reaches the given instruction PC. Use decimal numbers, a register below 256, and a comma between pairs. It has an effect only for the shader address in `SHARPEMU_CAPTURE_PIXEL_VGPR_ADDRESS`. | `Gen5SpirvTranslator.cs` |
| `SHARPEMU_MAX_GUEST_WORK_PER_RENDER` | number | Sets the maximum number of guest command stream slices that the Vulkan presenter runs in one render pass. The default is 1024, or 256 on macOS. The value must be more than 0. | `VulkanVideoPresenter.cs`, `VulkanVideoPresenter.CommandStream.cs` |
+| `SHARPEMU_READBACK_LINEAR_IMAGES` | `0` | `0` turns off the readback of linear images. By default, a linear storage image or color target that the GPU writes is copied back to guest memory when its work completes, so a CPU thread that waits for a GPU-filled image, such as an occlusion buffer whose sentinel it wrote, continues. An image is read back in the frame the GPU first writes it, and in the frame the CPU stores into it and the next one; an image only the GPU writes is not read back again every frame. A GnmMode target that is tiled in guest memory but laid out linear on the host is never read back, because its host bytes do not follow the guest's layout. The log names the first 16 images read back (`linear image readback`). | `VulkanVideoPresenter.Scheduler.cs`, `GuestImageCache.Tracking.cs`, `HostLayoutTargets.cs` |
| `SHARPEMU_RENDERDOC_CAPTURE_TIMEOUT_SECONDS` | number (seconds) | Set the maximum time for a RenderDoc frame capture. The emulator discards a capture that does not end in this time. The range is 1 to 120. The default is 15. | `RenderDocCapture.cs` |
| `SHARPEMU_RENDERDOC_DLL` | path | Set the path of the RenderDoc library file. The emulator tries this path first. When unset or when the load fails, it searches the default library name and the known install paths. | `RenderDocCapture.cs` |
| `SHARPEMU_RENDERDOC_WAIT` | number (seconds) or `enter` | Set to make the emulator wait before it starts Vulkan, so that you can attach RenderDoc. `enter` waits until you press Enter. A number waits that many seconds, from 1 to 300. Other text waits 15 seconds. | `VulkanVideoPresenter.Device.Setup.cs` |
diff --git a/scripts/ps5_names.txt b/scripts/ps5_names.txt
index bf976217a..42138179d 100644
--- a/scripts/ps5_names.txt
+++ b/scripts/ps5_names.txt
@@ -115733,6 +115733,7 @@ _sceLibcFree
_sceLibcGetMallocParam
_sceLibcInitialize
_sceLibcInternal
+_sceLibcInternalThreadAtexit
_sceLibcLockFinalize
_sceLibcLockInitialize
_sceLibcMalloc
diff --git a/src/SharpEmu.CLI/Program.cs b/src/SharpEmu.CLI/Program.cs
index aeb1506ad..3c3451406 100644
--- a/src/SharpEmu.CLI/Program.cs
+++ b/src/SharpEmu.CLI/Program.cs
@@ -43,6 +43,9 @@ private static readonly (string Name, string Value)[] ServerGarbageCollector =
("DOTNET_gcServer", "1"),
("DOTNET_GCHeapCount", "4"),
("DOTNET_GCNoAffinitize", "1"),
+ // Guest memory keeps the machine's memory load above the GC's high-memory thresholds, where it runs a blocking
+ // compacting generation-2 collection of most of a second every few seconds. The value is hexadecimal (99 percent).
+ ("DOTNET_GCHighMemPercent", "63"),
];
private const int ATTACH_PARENT_PROCESS = -1;
private const int STD_INPUT_HANDLE = -10;
diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs
index a27a534af..4286a6b20 100644
--- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs
+++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs
@@ -683,15 +683,17 @@ private unsafe static bool TryResolveGpuFault(EXCEPTION_RECORD* exceptionRecord)
&& GuestGpuMemoryHook.TryResolveFault(kind, exceptionRecord->ExceptionInformation[1]);
}
+ private static readonly bool GuestAllocatorHoleRecoveryDisabled = string.Equals(
+ Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_GUEST_ALLOCATOR_HOLE_RECOVERY"),
+ "1",
+ StringComparison.Ordinal);
+
private unsafe static bool TryRecoverGuestAllocatorHole(
EXCEPTION_RECORD* exceptionRecord,
void* contextRecord,
ulong rip)
{
- if (string.Equals(
- Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_GUEST_ALLOCATOR_HOLE_RECOVERY"),
- "1",
- StringComparison.Ordinal) ||
+ if (GuestAllocatorHoleRecoveryDisabled ||
exceptionRecord->NumberParameters < 2 ||
exceptionRecord->ExceptionInformation[0] != 0 ||
exceptionRecord->ExceptionInformation[1] != 8 ||
diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs
index fe6fbfd68..42313dcef 100644
--- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs
+++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.FastPath.cs
@@ -672,6 +672,21 @@ void EmitRealtimeIntoStack()
return code;
}
+ ///
+ /// With r10 = cursor end minus cursor (bytes), leaves r10 = the available dwords exactly as
+ /// AgcExports.GetRemainingCommandDwords computes them before the reserve: the signed byte
+ /// distance divided by four (toward zero), truncated to 32 bits. An end below the cursor (a null
+ /// end) therefore still has room, as titles rely on. Uses r11; changes the flags.
+ ///
+ private static void EmitAgcAvailableDwords(List code)
+ {
+ code.AddRange([0x4D, 0x8D, 0x5A, 0x03]); // lea r11, [r10+3]
+ code.AddRange([0x4D, 0x85, 0xD2]); // test r10, r10
+ code.AddRange([0x4D, 0x0F, 0x48, 0xD3]); // cmovs r10, r11 a negative span rounds toward zero
+ code.AddRange([0x49, 0xC1, 0xFA, 0x02]); // sar r10, 2
+ code.AddRange([0x45, 0x89, 0xD2]); // mov r10d, r10d truncated to 32 bits
+ }
+
///
/// An sceAgc builder that appends one fixed-shape packet, as guest-side code: with the command
/// buffer in RDI it reads the cursor, the end and the reserve, declines (jumps to the import's
@@ -708,11 +723,7 @@ void EmitBranchToSlowPath(byte shortOpcode)
Emit(0x48, 0x8B, 0x47, CursorUpOffset); // mov rax, [rdi+0x10] cursor
Emit(0x4C, 0x8B, 0x57, CursorDownOffset); // mov r10, [rdi+0x18] end
Emit(0x49, 0x29, 0xC2); // sub r10, rax
- EmitBranchToSlowPath(0x72); // jb slow: end below the cursor
- Emit(0x49, 0xC1, 0xEA, 0x02); // shr r10, 2 available dwords
- Emit(0x41, 0xBB); EmitImm32(0xFFFF_FFFFu); // mov r11d, 0xFFFFFFFF
- Emit(0x4D, 0x39, 0xDA); // cmp r10, r11
- EmitBranchToSlowPath(0x77); // ja slow: the export clamps the span to 32 bits
+ EmitAgcAvailableDwords(code); // r10 = available dwords, as the export truncates them
Emit(0x44, 0x8B, 0x5F, ReservedDwordsOffset); // mov r11d, [rdi+0x30] reserve
Emit(0x49, 0x83, 0xC3, checked((byte)spec.SizeDwords)); // add r11, size
Emit(0x4D, 0x39, 0xDA); // cmp r10, r11
@@ -761,6 +772,20 @@ void EmitModifierSlot(SharpEmu.Libs.Agc.AgcModifierSgprSlot slot)
Emit(0xF7, (byte)(0xC0 | (source & 7))); EmitImm32(slot.EnableMask);
Emit(0x74, 0);
var disabledFixup = code.Count - 1;
+ var vgprFixup = -1;
+ if (slot.DisableMask != 0)
+ {
+ // test reg32, disableMask / jnz disabled (the values come in VGPRs: no slot)
+ if (source >= 8)
+ {
+ Emit(0x41);
+ }
+
+ Emit(0xF7, (byte)(0xC0 | (source & 7))); EmitImm32(slot.DisableMask);
+ Emit(0x75, 0);
+ vgprFixup = code.Count - 1;
+ }
+
if (slot.FieldShift < 0)
{
Emit(0x41, 0xBA); EmitImm32(1); // mov r10d, 1
@@ -786,6 +811,11 @@ void EmitModifierSlot(SharpEmu.Libs.Agc.AgcModifierSgprSlot slot)
Emit(0xEB, 0x06); // jmp done
code[disabledFixup] = checked((byte)(code.Count - (disabledFixup + 1)));
+ if (vgprFixup >= 0)
+ {
+ code[vgprFixup] = checked((byte)(code.Count - (vgprFixup + 1)));
+ }
+
Emit(0x41, 0xBA); EmitImm32(slot.Disabled); // disabled: mov r10d, imm32
if (slot.ShiftLeft != 0)
{
@@ -996,11 +1026,7 @@ void EmitLoopBack(int target)
Emit(0x48, 0x8B, 0x47, CursorUpOffset); // mov rax, [rdi+0x10] cursor
Emit(0x4C, 0x8B, 0x57, CursorDownOffset); // mov r10, [rdi+0x18] end
Emit(0x49, 0x29, 0xC2); // sub r10, rax
- EmitBranchToSlowPath(0x72); // jb slow
- Emit(0x49, 0xC1, 0xEA, 0x02); // shr r10, 2 available dwords
- Emit(0x41, 0xBB); EmitImm32(0xFFFF_FFFFu); // mov r11d, 0xFFFFFFFF
- Emit(0x4D, 0x39, 0xDA); // cmp r10, r11
- EmitBranchToSlowPath(0x77); // ja slow
+ EmitAgcAvailableDwords(code); // r10 = available dwords, as the export truncates them
Emit(0x44, 0x8B, 0x5F, ReservedDwordsOffset); // mov r11d, [rdi+0x30] reserve
if (range)
{
diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs
index e1230e880..d514be537 100644
--- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs
+++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs
@@ -2362,7 +2362,12 @@ private bool ShouldLogImportResult(in ImportStubEntry entry, OrbisGen2Result res
// and deciding used to cost thirteen eagerly evaluated string comparisons
// against the NID. The one code each of those imports expects is resolved
// at stub setup, so the decision is now a single integer compare.
- if (resultValue != entry.ExpectedBenignResult)
+ // sceSaveDataConvert reports a save directory that is missing or already in the current format; titles
+ // then mount it as usual. Two codes, so it stays outside the one-code table; the code is compared first.
+ var expectedSaveDataNoConversion =
+ (resultValue == unchecked((int)0x809F0008) || resultValue == unchecked((int)0x809F001E)) &&
+ string.Equals(nid, "2mfSRGdshtk", StringComparison.Ordinal);
+ if (resultValue != entry.ExpectedBenignResult && !expectedSaveDataNoConversion)
{
return ShouldSampleImportResult(nid, resultValue, out mutexOccurrence);
}
diff --git a/src/SharpEmu.Core/Loader/GuestRedZonePatcher.Cache.cs b/src/SharpEmu.Core/Loader/GuestRedZonePatcher.Cache.cs
index f1c8148a6..3002fdce7 100644
--- a/src/SharpEmu.Core/Loader/GuestRedZonePatcher.Cache.cs
+++ b/src/SharpEmu.Core/Loader/GuestRedZonePatcher.Cache.cs
@@ -11,7 +11,7 @@ namespace SharpEmu.Core.Loader;
internal static partial class GuestRedZonePatcher
{
- private const int PatchCacheVersion = 1;
+ private const int PatchCacheVersion = 2;
private const int MaximumPatchCacheBytes = 32 << 20;
private sealed record CachedSite(ulong Offset, int Length, bool TerminalBranch);
private sealed record CachedPlan(int Version, string Key, PatchResult Scan, CachedSite[] Sites);
diff --git a/src/SharpEmu.Core/Loader/GuestRedZonePatcher.cs b/src/SharpEmu.Core/Loader/GuestRedZonePatcher.cs
index 6149ac43f..7504cc39d 100644
--- a/src/SharpEmu.Core/Loader/GuestRedZonePatcher.cs
+++ b/src/SharpEmu.Core/Loader/GuestRedZonePatcher.cs
@@ -21,6 +21,7 @@ internal static partial class GuestRedZonePatcher
private const ulong MaximumRelativeJumpDistance = 0x7FFF_FFFF;
private const int MaximumJumpTableEntries = 4096;
private const int MaximumJumpTableSetupInstructions = 6;
+ private const int MaximumJumpTableSliceInstructions = 16;
private const ulong LargeExecutableBytes = 32UL << 20;
private static readonly TimeSpan ProgressInterval = TimeSpan.FromSeconds(2);
@@ -291,6 +292,7 @@ private static List CollectPatchSites(
continue;
}
+ segmentFunctions = AddDirectCallTargets(segmentBytes, segmentStart, segmentEnd, segmentFunctions);
for (var functionIndex = 0; functionIndex < segmentFunctions.Length; functionIndex++)
{
progress?.Report(scannedFunctions++);
@@ -420,6 +422,39 @@ private static List CollectPatchSites(
return sites;
}
+ // .eh_frame_hdr lists only the functions that have unwind entries, so the span between two entries can hold many
+ // functions: one red-zone leaf among them sends every access of its neighbours to a trampoline, and one unresolved
+ // indirect jump among them leaves the leaf unprotected. Direct call targets are function entries too.
+ private static ulong[] AddDirectCallTargets(byte[] segmentBytes, ulong segmentStart, ulong segmentEnd, ulong[] functionStarts)
+ {
+ var starts = new HashSet(functionStarts);
+ for (var index = 0; index < functionStarts.Length; index++)
+ {
+ var start = functionStarts[index];
+ var end = index + 1 < functionStarts.Length ? functionStarts[index + 1] : segmentEnd;
+ var reader = new ArraySliceCodeReader(segmentBytes, checked((int)(start - segmentStart)), checked((int)(end - start)));
+ var decoder = Decoder.Create(64, reader, DecoderOptions.None);
+ decoder.IP = start;
+ while (decoder.IP < end && reader.CanRead)
+ {
+ decoder.Decode(out var instruction);
+ if (instruction.Code == Code.INVALID)
+ {
+ break;
+ }
+
+ if (instruction.FlowControl == FlowControl.Call &&
+ instruction.Op0Kind == OpKind.NearBranch64 &&
+ instruction.NearBranch64 >= segmentStart && instruction.NearBranch64 < segmentEnd)
+ {
+ starts.Add(instruction.NearBranch64);
+ }
+ }
+ }
+
+ return starts.Count == functionStarts.Length ? functionStarts : starts.Order().ToArray();
+ }
+
private static List DecodeFunction(
byte[] segmentBytes,
ulong segmentStart,
@@ -489,8 +524,9 @@ private static bool TryCollectJumpTableTargets(
HashSet branchTargets,
bool hoistedTables = false)
{
- List? resolvedTargets = null;
HashSet? instructionBoundaries = null;
+ Dictionary>? jumpTargets = null;
+ List? unresolved = null;
for (var instructionIndex = 0; instructionIndex < decoded.Count; instructionIndex++)
{
if (decoded[instructionIndex].Instruction.FlowControl != FlowControl.IndirectBranch)
@@ -501,8 +537,20 @@ private static bool TryCollectJumpTableTargets(
instructionBoundaries ??= decoded
.Select(static entry => entry.Instruction.IP)
.ToHashSet();
- resolvedTargets ??= new List();
- if (!TryResolveJumpTable(
+ var targets = new List();
+ if (TryResolveJumpTable(
+ memory,
+ programHeaders,
+ imageBase,
+ decoded,
+ instructionIndex,
+ functionStart,
+ functionEnd,
+ instructionBoundaries,
+ branchTargets,
+ targets,
+ hoistedTables) ||
+ TryResolveSlicedJumpTable(
memory,
programHeaders,
imageBase,
@@ -512,16 +560,51 @@ private static bool TryCollectJumpTableTargets(
functionEnd,
instructionBoundaries,
branchTargets,
- resolvedTargets,
- hoistedTables))
+ null,
+ targets))
{
- return false;
+ (jumpTargets ??= new())[instructionIndex] = targets;
+ }
+ else
+ {
+ (unresolved ??= new()).Add(instructionIndex);
+ }
+ }
+
+ // A switch inside a loop loads its table address before the loop; the jumps resolved above give the data flow
+ // their exact edges.
+ if (unresolved is not null)
+ {
+ jumpTargets ??= new();
+ foreach (var jumpIndex in unresolved)
+ {
+ var targets = new List();
+ if (!TryResolveSlicedJumpTable(
+ memory,
+ programHeaders,
+ imageBase,
+ decoded,
+ jumpIndex,
+ functionStart,
+ functionEnd,
+ instructionBoundaries!,
+ branchTargets,
+ jumpTargets,
+ targets))
+ {
+ return false;
+ }
+
+ jumpTargets[jumpIndex] = targets;
}
}
- if (resolvedTargets is not null)
+ if (jumpTargets is not null)
{
- branchTargets.UnionWith(resolvedTargets);
+ foreach (var targets in jumpTargets.Values)
+ {
+ branchTargets.UnionWith(targets);
+ }
}
return true;
@@ -783,6 +866,420 @@ private static bool IsEpiloguePop(IReadOnlyList decoded, int
return false;
}
+ // Compilers interleave independent instructions with the table load, bound the selector with AND or with CMP; JA far
+ // from the jump, and load the table address once before a loop that holds the switch. Follow the data flow instead of
+ // fixed positions: jmp T, where T = movsxd [B + S*4] + B and B = lea [rip + table]. B comes from straight-line code no
+ // branch enters, or, once 'resolvedJumps' gives the function's other tables, from the one LEA that reaches the load
+ // on every path; that needs a bounded selector and holds only if the table's own edges keep it the one definition.
+ // A bounded table must name instructions of this function throughout; any other is read until an entry stops naming
+ // one, which can only add targets.
+ private static bool TryResolveSlicedJumpTable(
+ IVirtualMemory memory,
+ IReadOnlyList programHeaders,
+ ulong imageBase,
+ IReadOnlyList decoded,
+ int jumpIndex,
+ ulong functionStart,
+ ulong functionEnd,
+ IReadOnlySet instructionBoundaries,
+ IReadOnlySet knownBranchTargets,
+ IReadOnlyDictionary>? resolvedJumps,
+ List targets)
+ {
+ var jump = decoded[jumpIndex].Instruction;
+ if (jump.Mnemonic != Mnemonic.Jmp || jump.OpCount != 1 || jump.GetOpKind(0) != OpKind.Register ||
+ jump.GetOpRegister(0).GetSize() != sizeof(ulong) || knownBranchTargets.Contains(jump.IP))
+ {
+ return false;
+ }
+
+ var factory = new InstructionInfoFactory();
+ var targetRegister = jump.GetOpRegister(0);
+ var addIndex = FindDefinition(decoded, jumpIndex - 1, targetRegister, Register.None, knownBranchTargets, factory);
+ if (addIndex < 0)
+ {
+ return false;
+ }
+
+ var add = decoded[addIndex].Instruction;
+ if (add.Mnemonic != Mnemonic.Add || add.OpCount != 2 ||
+ add.GetOpKind(0) != OpKind.Register || add.GetOpRegister(0) != targetRegister ||
+ add.GetOpKind(1) != OpKind.Register || add.GetOpRegister(1).GetSize() != sizeof(ulong) ||
+ add.GetOpRegister(1) == targetRegister || knownBranchTargets.Contains(add.IP))
+ {
+ return false;
+ }
+
+ var tableRegister = add.GetOpRegister(1);
+ var loadIndex = FindDefinition(decoded, addIndex - 1, targetRegister, tableRegister, knownBranchTargets, factory);
+ if (loadIndex < 0)
+ {
+ return false;
+ }
+
+ var load = decoded[loadIndex].Instruction;
+ if (load.Mnemonic != Mnemonic.Movsxd || load.OpCount != 2 ||
+ load.GetOpKind(0) != OpKind.Register || load.GetOpRegister(0) != targetRegister ||
+ load.GetOpKind(1) != OpKind.Memory || load.MemorySize.GetSize() != sizeof(int) ||
+ load.MemoryBase != tableRegister || load.MemoryIndexScale != sizeof(int) ||
+ load.MemoryIndex.GetSize() != sizeof(ulong) || load.MemoryIndex.GetFullRegister() == tableRegister.GetFullRegister() ||
+ load.MemoryDisplacement64 != 0 || knownBranchTargets.Contains(load.IP))
+ {
+ return false;
+ }
+
+ var entryLimit = MaximumJumpTableEntries;
+ var bounded = TryFindSelectorBound(decoded, loadIndex, load.MemoryIndex, knownBranchTargets, factory, out var comparedEntries);
+ if (bounded)
+ {
+ entryLimit = comparedEntries;
+ }
+ else
+ {
+ var selectorIndex = FindDefinition(decoded, loadIndex - 1, load.MemoryIndex, Register.None, knownBranchTargets, factory);
+ if (selectorIndex >= 0)
+ {
+ var selector = decoded[selectorIndex].Instruction;
+ // A 32-bit AND clears the upper half too; a narrower one would leave it.
+ if (selector.Mnemonic == Mnemonic.And && selector.OpCount == 2 &&
+ selector.GetOpKind(0) == OpKind.Register && selector.GetOpRegister(0).GetSize() >= sizeof(int) &&
+ TryGetNonNegativeImmediate(selector, 1, out var mask) && mask < MaximumJumpTableEntries)
+ {
+ entryLimit = (int)mask + 1;
+ bounded = true;
+ }
+ else if (ComparesBeforeRedefinition(decoded, selectorIndex, load.MemoryIndex))
+ {
+ // The bounds check applied to the value the redefinition replaced.
+ return false;
+ }
+ }
+ }
+
+ Dictionary? index = null;
+ var leaIndex = FindDefinition(decoded, loadIndex - 1, tableRegister, Register.None, knownBranchTargets, factory);
+ if (leaIndex < 0 && bounded && resolvedJumps is not null)
+ {
+ index = new Dictionary(decoded.Count);
+ for (var position = 0; position < decoded.Count; position++)
+ {
+ index[decoded[position].Instruction.IP] = position;
+ }
+
+ leaIndex = FindReachingDefinition(decoded, index, loadIndex, tableRegister, jumpIndex, null, resolvedJumps, factory);
+ }
+
+ if (leaIndex < 0)
+ {
+ return false;
+ }
+
+ var lea = decoded[leaIndex].Instruction;
+ if (lea.Mnemonic != Mnemonic.Lea || lea.OpCount != 2 || !lea.IsIPRelativeMemoryOperand ||
+ lea.GetOpRegister(0) != tableRegister)
+ {
+ return false;
+ }
+
+ var tableAddress = lea.IPRelativeMemoryAddress;
+ var firstTarget = targets.Count;
+ Span entry = stackalloc byte[sizeof(int)];
+ for (var entryIndex = 0; entryIndex < entryLimit; entryIndex++)
+ {
+ var entryAddress = tableAddress + (ulong)entryIndex * sizeof(int);
+ if (!IsRangeInReadableLoad(programHeaders, imageBase, entryAddress, sizeof(int)) ||
+ !memory.TryRead(entryAddress, entry) ||
+ !TryAddSignedOffset(tableAddress, BinaryPrimitives.ReadInt32LittleEndian(entry), out var target) ||
+ target < functionStart || target >= functionEnd ||
+ !instructionBoundaries.Contains(target))
+ {
+ if (bounded || entryIndex == 0)
+ {
+ targets.RemoveRange(firstTarget, targets.Count - firstTarget);
+ return false;
+ }
+
+ break;
+ }
+
+ targets.Add(target);
+ }
+
+ if (index is not null &&
+ FindReachingDefinition(decoded, index, loadIndex, tableRegister, jumpIndex, targets.GetRange(firstTarget, targets.Count - firstTarget),
+ resolvedJumps!, factory) != leaIndex)
+ {
+ targets.RemoveRange(firstTarget, targets.Count - firstTarget);
+ return false;
+ }
+
+ return true;
+ }
+
+ // CMP S, N; JA default, then straight-line code that leaves S alone and that no known branch enters, up to the
+ // table load: S indexes N + 1 entries.
+ private static bool TryFindSelectorBound(
+ IReadOnlyList decoded,
+ int loadIndex,
+ Register selector,
+ IReadOnlySet knownBranchTargets,
+ InstructionInfoFactory factory,
+ out int entryCount)
+ {
+ entryCount = 0;
+ var fullSelector = selector.GetFullRegister();
+ for (var index = loadIndex - 1; index > 0 && index > loadIndex - MaximumJumpTableSliceInstructions; index--)
+ {
+ var instruction = decoded[index].Instruction;
+ if (instruction.Mnemonic == Mnemonic.Ja)
+ {
+ var compare = decoded[index - 1].Instruction;
+ if (compare.Mnemonic != Mnemonic.Cmp || compare.OpCount != 2 || compare.GetOpKind(0) != OpKind.Register ||
+ compare.GetOpRegister(0).GetFullRegister() != fullSelector ||
+ compare.GetOpRegister(0).GetSize() < sizeof(int) ||
+ !TryGetNonNegativeImmediate(compare, 1, out var maximum) || maximum >= MaximumJumpTableEntries)
+ {
+ return false;
+ }
+
+ entryCount = (int)maximum + 1;
+ return true;
+ }
+
+ if (instruction.FlowControl != FlowControl.Next || knownBranchTargets.Contains(instruction.IP) ||
+ WritesRegister(instruction, fullSelector, factory))
+ {
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ // The one instruction whose write of 'register' reaches 'use' on every path, or -1. Paths follow fall-through and
+ // direct branches inside the function; a resolved jump table reaches its targets, and every other indirect jump
+ // (the one at 'jumpIndex' too when 'jumpTargets' is null) may reach any instruction. The function entry, and any
+ // other instruction that neither direct flow nor a known table reaches, brings in an unknown value; when
+ // 'jumpTargets' is null that is only the entry, which can name the definition but not confirm it. A call ends a
+ // caller-saved register's value.
+ private static int FindReachingDefinition(
+ IReadOnlyList decoded,
+ IReadOnlyDictionary index,
+ int use,
+ Register register,
+ int jumpIndex,
+ IReadOnlyList? jumpTargets,
+ IReadOnlyDictionary> resolvedJumps,
+ InstructionInfoFactory factory)
+ {
+ const int MaximumDefinitions = 63;
+ const int MaximumPasses = 128;
+ var fullRegister = register.GetFullRegister();
+ var callerSaved = fullRegister is Register.RAX or Register.RCX or Register.RDX or Register.RSI or Register.RDI or
+ Register.R8 or Register.R9 or Register.R10 or Register.R11;
+ var count = decoded.Count;
+ var definition = new int[count];
+ var definitions = new List { -1 };
+ var reached = new bool[count];
+ for (var position = 0; position < count; position++)
+ {
+ var instruction = decoded[position].Instruction;
+ definition[position] = -1;
+ if (instruction.FlowControl is FlowControl.Call or FlowControl.IndirectCall)
+ {
+ if (callerSaved) definition[position] = 0;
+ }
+ else if (WritesRegister(instruction, fullRegister, factory))
+ {
+ if (definitions.Count > MaximumDefinitions) return -1;
+ definition[position] = definitions.Count;
+ definitions.Add(position);
+ }
+
+ if (instruction.FlowControl is FlowControl.Next or FlowControl.ConditionalBranch or FlowControl.Call or
+ FlowControl.IndirectCall && position + 1 < count)
+ {
+ reached[position + 1] = true;
+ }
+
+ if (instruction.FlowControl is FlowControl.ConditionalBranch or FlowControl.UnconditionalBranch &&
+ TryGetNearBranchTarget(instruction, out var target) && index.TryGetValue(target, out var targetIndex))
+ {
+ reached[targetIndex] = true;
+ }
+ }
+
+ var input = new ulong[count];
+ input[0] = 1;
+ if (jumpTargets is not null)
+ {
+ foreach (var targets in resolvedJumps.Values)
+ foreach (var target in targets)
+ if (index.TryGetValue(target, out var targetIndex)) reached[targetIndex] = true;
+ foreach (var target in jumpTargets)
+ if (index.TryGetValue(target, out var targetIndex)) reached[targetIndex] = true;
+ for (var position = 1; position < count; position++)
+ {
+ var instruction = decoded[position].Instruction;
+ if (!reached[position] && instruction.Mnemonic is not (Mnemonic.Nop or Mnemonic.Int3))
+ {
+ input[position] = 1;
+ }
+ }
+ }
+
+ var anywhere = 0UL;
+ for (var pass = 0; ; pass++)
+ {
+ if (pass == MaximumPasses) return -1;
+ var changed = false;
+ for (var position = 0; position < count; position++)
+ {
+ var instruction = decoded[position].Instruction;
+ var output = definition[position] >= 0 ? 1UL << definition[position] : input[position] | anywhere;
+ switch (instruction.FlowControl)
+ {
+ case FlowControl.Next:
+ case FlowControl.Call:
+ case FlowControl.IndirectCall:
+ Flow(position + 1, output);
+ break;
+ case FlowControl.ConditionalBranch:
+ Flow(position + 1, output);
+ FlowTo(instruction, output);
+ break;
+ case FlowControl.UnconditionalBranch:
+ FlowTo(instruction, output);
+ break;
+ case FlowControl.IndirectBranch:
+ var targets = position == jumpIndex ? jumpTargets : resolvedJumps.GetValueOrDefault(position);
+ if (targets is null)
+ {
+ if ((anywhere | output) != anywhere)
+ {
+ anywhere |= output;
+ changed = true;
+ }
+ }
+ else
+ {
+ foreach (var target in targets)
+ if (index.TryGetValue(target, out var targetIndex)) Flow(targetIndex, output);
+ }
+
+ break;
+ }
+ }
+
+ if (!changed) break;
+
+ void Flow(int target, ulong mask)
+ {
+ if (target >= count || (input[target] | mask) == input[target]) return;
+ input[target] |= mask;
+ changed = true;
+ }
+
+ void FlowTo(in Instruction branch, ulong mask)
+ {
+ if (TryGetNearBranchTarget(branch, out var target) && index.TryGetValue(target, out var targetIndex))
+ Flow(targetIndex, mask);
+ }
+ }
+
+ var reaching = input[use] | anywhere;
+ if (reaching == 0 || (reaching & 1) != 0 || (reaching & (reaching - 1)) != 0) return -1;
+ return definitions[System.Numerics.BitOperations.TrailingZeroCount(reaching)];
+ }
+
+ private static bool WritesRegister(in Instruction instruction, Register fullRegister, InstructionInfoFactory factory)
+ {
+ foreach (var used in factory.GetInfo(instruction).GetUsedRegisters())
+ {
+ if (used.Access is (OpAccess.Write or OpAccess.CondWrite or OpAccess.ReadWrite or OpAccess.ReadCondWrite) &&
+ used.Register.GetFullRegister() == fullRegister)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static bool ComparesBeforeRedefinition(IReadOnlyList decoded, int definitionIndex, Register register)
+ {
+ var fullRegister = register.GetFullRegister();
+ for (var index = definitionIndex - 1; index >= 0 && index > definitionIndex - MaximumJumpTableSliceInstructions; index--)
+ {
+ var instruction = decoded[index].Instruction;
+ if (instruction.Mnemonic == Mnemonic.Cmp && instruction.OpCount == 2 &&
+ instruction.GetOpKind(0) == OpKind.Register && instruction.GetOpRegister(0).GetFullRegister() == fullRegister)
+ {
+ return true;
+ }
+
+ if (instruction.FlowControl is not (FlowControl.Next or FlowControl.ConditionalBranch))
+ {
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ // The last instruction at or before 'from' that writes 'register', through straight-line code that leaves
+ // 'protectedRegister' alone and that no known branch enters past the definition; -1 when there is none nearby.
+ private static int FindDefinition(
+ IReadOnlyList decoded,
+ int from,
+ Register register,
+ Register protectedRegister,
+ IReadOnlySet knownBranchTargets,
+ InstructionInfoFactory factory)
+ {
+ var fullRegister = register.GetFullRegister();
+ var fullProtected = protectedRegister == Register.None ? Register.None : protectedRegister.GetFullRegister();
+ for (var index = from; index >= 0 && index > from - MaximumJumpTableSliceInstructions; index--)
+ {
+ var instruction = decoded[index].Instruction;
+ if (instruction.FlowControl != FlowControl.Next)
+ {
+ return -1;
+ }
+
+ var writesRegister = false;
+ foreach (var used in factory.GetInfo(instruction).GetUsedRegisters())
+ {
+ if (used.Access is not (OpAccess.Write or OpAccess.CondWrite or OpAccess.ReadWrite or OpAccess.ReadCondWrite))
+ {
+ continue;
+ }
+
+ var written = used.Register.GetFullRegister();
+ if (written == fullRegister)
+ {
+ writesRegister = true;
+ }
+ else if (written == fullProtected)
+ {
+ return -1;
+ }
+ }
+
+ if (writesRegister)
+ {
+ return index;
+ }
+
+ if (knownBranchTargets.Contains(instruction.IP))
+ {
+ return -1;
+ }
+ }
+
+ return -1;
+ }
+
private static bool IsStoreToMemory(in Instruction instruction) =>
instruction.Mnemonic == Mnemonic.Mov && instruction.OpCount == 2 && instruction.GetOpKind(0) == OpKind.Memory;
diff --git a/src/SharpEmu.Core/Loader/GuestStackFrameAnalysis.cs b/src/SharpEmu.Core/Loader/GuestStackFrameAnalysis.cs
index d44fbe4d0..3ee7ce69c 100644
--- a/src/SharpEmu.Core/Loader/GuestStackFrameAnalysis.cs
+++ b/src/SharpEmu.Core/Loader/GuestStackFrameAnalysis.cs
@@ -44,8 +44,8 @@ internal static bool UsesFrameRedZone(IReadOnlyList instructions)
if (indices.TryGetValue(instruction.NearBranchTarget, out var target)) Merge(target, next);
break;
case FlowControl.IndirectBranch:
- // Unknown targets can enter any instruction with unknown stack state.
- for (var targetIndex = 0; targetIndex < instructions.Count; targetIndex++) Merge(targetIndex, new(null, null));
+ // Unknown targets get no state: an access only they reach proves nothing, and the jump cannot undo
+ // a red-zone access that direct flow from the entry already proved.
break;
}
}
diff --git a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs
index 53f57d12f..fc3cc1be8 100644
--- a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs
+++ b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs
@@ -2791,13 +2791,12 @@ private bool TryWriteCore(ulong virtualAddress, ReadOnlySpan source,
// there). Pre-visit the span so tracked pages are unprotected and
// their owners dirtied before the copy; guest addresses are
// host-identical, matching the tracker's fault addresses.
- GuestImageWriteTracker.NotifyManagedWrite(virtualAddress, (ulong)source.Length);
- GuestGpuMemoryHook.MarkCpuWrite(virtualAddress, (ulong)source.Length);
+ // HLE's managed-write lease (BeginCpuWrite) does the image-tracker pre-visit and MarkCpuWrite before the
+ // write, holds the CPU reservation a GPU claim waits on, and marks the range landed when it ends.
+ using var write = GuestGpuMemoryHook.BeginCpuWrite(virtualAddress, (ulong)source.Length);
var written = TryWriteBytesCore(virtualAddress, source, out failure, out diagnosticSpace);
- // Backed writes go through an alias no page watch covers: an upload between the mark above
- // and the write took the old bytes and left the pages clean, and no fault reports the new ones.
- GuestGpuMemoryHook.MarkCpuWriteLanded(virtualAddress, (ulong)source.Length);
+ // The lease publishes landed bytes before admitting another overlapping GPU claim.
return written;
}
@@ -3016,19 +3015,71 @@ public bool TryCopy(ulong destinationAddress, ulong sourceAddress, ulong length)
return false;
}
- // Match TryWrite's managed-write notification before touching an
- // identity-mapped guest page protected by the image tracker.
- GuestImageWriteTracker.NotifyManagedWrite(destinationAddress, length);
- GuestGpuMemoryHook.MarkCpuWrite(destinationAddress, length);
- var copied = TryCopyCore(destinationAddress, sourceAddress, length);
+ // Match TryWrite's managed-write lease (image-tracker pre-visit, MarkCpuWrite, landed mark) before touching
+ // an identity-mapped guest page protected by the image tracker.
+ bool copied, needsStaging;
+ using (GuestGpuMemoryHook.BeginCpuWrite(destinationAddress, length))
+ {
+ copied = TryCopyCore(destinationAddress, sourceAddress, length, out needsStaging);
+ }
- // As in TryWrite: an upload after the mark may have taken the bytes from before the copy.
- GuestGpuMemoryHook.MarkCpuWriteLanded(destinationAddress, length);
- return copied;
+ // Staging re-enters TryWrite, whose premark may wait on the GPU. Each piece obtains
+ // its own reservation; no outer reservation may span that nested premark.
+ return needsStaging ? CopyThroughStaging(destinationAddress, sourceAddress, length) : copied;
}
- private bool TryCopyCore(ulong destinationAddress, ulong sourceAddress, ulong length)
+ // HostCallTrims.MixedCopyDirect, under the read lock: a copy between the backing and private memory in one call,
+ // when the private side resolves, is committed and needs no protection change, as the TryRead or TryWrite of each
+ // staging piece would find it. The backing's read or write checks its whole span before it copies a byte, and the
+ // write notification is the one TryWrite makes. False leaves both sides untouched, and the caller stages the copy.
+ private bool TryCopyMixedDirect(ulong destinationAddress, ulong sourceAddress, ulong length,
+ MemoryRegion? sourceRegion, MemoryRegion? destinationRegion, bool sourceBacked)
{
+ var privateAddress = sourceBacked ? destinationAddress : sourceAddress;
+ var privateRegion = sourceBacked ? destinationRegion : sourceRegion;
+ // Armed watches depend on the ordinary staging pieces' call boundaries and lengths.
+ if (GuestWriteWatch.Armed || length > int.MaxValue || privateRegion is null || privateRegion.IsReservedOnly ||
+ !TryResolveRegionOffset(privateAddress, length, privateRegion, out var offset))
+ {
+ return false;
+ }
+
+ var pointer = privateRegion.VirtualAddress + offset;
+ if (sourceBacked)
+ {
+ if (!CanWriteWithoutProtectionChange(pointer, length, privateRegion))
+ {
+ return false;
+ }
+
+ var target = new Span((void*)pointer, (int)length);
+ if (!_backedSpace!.TryReadBacking(sourceAddress, target))
+ {
+ return false;
+ }
+
+ NotifyGuestWriteWatch(destinationAddress, target);
+ return true;
+ }
+
+ if (!CanReadWithoutProtectionChange(pointer, length, privateRegion))
+ {
+ return false;
+ }
+
+ var source = new ReadOnlySpan((void*)pointer, (int)length);
+ if (!_backedSpace!.TryWriteBacking(destinationAddress, source))
+ {
+ return false;
+ }
+
+ NotifyGuestWriteWatch(destinationAddress, source);
+ return true;
+ }
+
+ private bool TryCopyCore(ulong destinationAddress, ulong sourceAddress, ulong length, out bool needsStaging)
+ {
+ needsStaging = false;
_gate.EnterReadLock();
try
{
@@ -3050,6 +3101,12 @@ private bool TryCopyCore(ulong destinationAddress, ulong sourceAddress, ulong le
// The staged path re-enters TryRead/TryWrite, which may need the write lock.
if (sourceBacked || destinationBacked)
{
+ if (global::SharpEmu.HLE.HostCallTrims.MixedCopyDirect &&
+ TryCopyMixedDirect(destinationAddress, sourceAddress, length, sourceRegion, destinationRegion, sourceBacked))
+ {
+ return true;
+ }
+
goto staged;
}
@@ -3087,7 +3144,8 @@ private bool TryCopyCore(ulong destinationAddress, ulong sourceAddress, ulong le
}
staged:
- return CopyThroughStaging(destinationAddress, sourceAddress, length);
+ needsStaging = true;
+ return false;
}
private bool TryReadExclusive(ulong virtualAddress, Span destination)
diff --git a/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs b/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs
index 0cf7d3ddc..7b0cb2cb4 100644
--- a/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs
+++ b/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs
@@ -209,6 +209,7 @@ public OrbisGen2Result Run(string ebootPath)
SaveDataExports.ConfigureApplicationInfo(image.TitleId);
NpEntitlementAccessExports.ConfigureApplicationInfo(image.TitleId);
SystemServiceExports.ConfigureApplicationInfo(image.TitleId, _systemLanguage);
+ VideoOutExports.StartPresenter();
_ = RegisterLoadedModule(normalizedEbootPath, image, isMain: true, isSystemModule: false);
KernelRuntimeCompatExports.ConfigureProcessProcParamAddress(image.ProcParamAddress);
Console.Error.WriteLine($"[RUNTIME] Entry: 0x{image.EntryPoint:X16}");
@@ -1591,6 +1592,16 @@ public void Dispose()
_aprSession?.Dispose();
+ if (HostSessionControl.IsShutdownRequested)
+ {
+ // A host shutdown tears the presentation down on its own thread, which still returns pages to their guest
+ // protection and downloads GPU results into guest memory; the process exits after it. Releasing the page
+ // guard or unmapping the guest space here would race that teardown.
+ Console.Error.WriteLine(
+ "[RUNTIME] Host shutdown: the presentation tears down guest GPU memory; keeping the guest address space mapped.");
+ return;
+ }
+
if (_gpuMemory != null && _gpuMemory.HasActiveWatches())
{
// A host shutdown can end the guest before the presenter drops its cached images,
diff --git a/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs b/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs
index 81ff7e076..4bc4731e3 100644
--- a/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs
+++ b/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs
@@ -614,6 +614,8 @@ private static void TranslateColorTarget(GpuCommandInterpreter interpreter, Targ
Attrib3 = (1u << 24) | ((uint)hostTile << 14),
};
interpreter.TypedRegisters.MarkWritten(1u << (int)RegisterStamp.ColorTargets);
+ if (!linear && hostTile == GuestTileMode.Linear)
+ HostLayoutTargets.Mark(target.BaseAddress);
GcnImageDescriptor.ObserveColorTarget(guestAddress, in target, pitch, height, tileIndex);
}
diff --git a/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs b/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs
index cd94fee07..872afaefa 100644
--- a/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs
+++ b/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs
@@ -67,6 +67,7 @@ private static bool IsDepthTarget(ReadOnlySpan words)
internal static void ResetLayouts()
{
ColorTargets.Clear();
+ HostLayoutTargets.Reset();
LinearPitches.Clear();
DepthTargets.Clear();
ReportedDepthCopies.Clear();
@@ -178,6 +179,11 @@ private static ImageRequest DepthCopyRequest(ulong address, ulong size)
return new ImageRequest(description, default, ImageRole.DepthTarget);
}
+ // A GCN texture is converted into a linear chain the translator writes whole, so every level
+ // is there: it never takes the resident-levels image of a streamed texture.
+ private static TextureRequestResolution WholeChain(TextureRequestResolution resolution) =>
+ resolution with { Request = ImageRequestBuilders.WithWholeMipChain(resolution.Request) };
+
internal static TextureRequestResolution ResolveTexture(ReadOnlySpan words, in ShaderImageShape shape,
ulong shaderHash, int imageIndex)
{
@@ -187,7 +193,7 @@ internal static TextureRequestResolution ResolveTexture(ReadOnlySpan words
linear.Width == descriptor.Width + 1 && linear.Height == descriptor.Height + 1 &&
linear.Format == descriptor.Format && TileGeometry.TryGetElementLayout(linear.Format, out var element))
{
- var pitched = ImageRequestBuilders.Texture(words, shape, shaderHash, imageIndex);
+ var pitched = WholeChain(ImageRequestBuilders.Texture(words, shape, shaderHash, imageIndex));
var pitchedRequest = pitched.Request;
var size = (linear.Pitch + (ulong)element.TexelWidth - 1) / element.TexelWidth *
((linear.Height + (ulong)element.TexelHeight - 1) / element.TexelHeight) * element.Bytes;
@@ -197,7 +203,7 @@ internal static TextureRequestResolution ResolveTexture(ReadOnlySpan words
return pitched with { Request = pitchedRequest };
}
if (descriptor.TileMode != GuestTileMode.RenderTarget)
- return ImageRequestBuilders.Texture(words, shape, shaderHash, imageIndex);
+ return WholeChain(ImageRequestBuilders.Texture(words, shape, shaderHash, imageIndex));
// GNM placements can be 32 KiB aligned. Only known GPU attachments use the
// shared host layout; CPU-resident GCN tiles still require a real detiler.
@@ -205,7 +211,7 @@ internal static TextureRequestResolution ResolveTexture(ReadOnlySpan words
var address = (descriptor.BaseAddress + 0xFFFFUL) & ~0xFFFFUL;
aligned[0] = (uint)(address >> 8);
aligned[1] = (aligned[1] & ~63u) | (uint)(address >> 40);
- var resolution = ImageRequestBuilders.Texture(aligned, shape, shaderHash, imageIndex);
+ var resolution = WholeChain(ImageRequestBuilders.Texture(aligned, shape, shaderHash, imageIndex));
var request = resolution.Request;
request.Description.Data = request.Description.Data with { Address = descriptor.BaseAddress };
return resolution with { Request = request };
diff --git a/src/SharpEmu.GpuRemote/GpuProcessLauncher.cs b/src/SharpEmu.GpuRemote/GpuProcessLauncher.cs
index ba2b599c4..a32961c9c 100644
--- a/src/SharpEmu.GpuRemote/GpuProcessLauncher.cs
+++ b/src/SharpEmu.GpuRemote/GpuProcessLauncher.cs
@@ -111,7 +111,8 @@ public static int Spawn(string executable, IReadOnlyList arguments)
private const string HeapCountVariable = "DOTNET_GCHeapCount";
private const string HostHeapCount = "4";
- private static List EnvironmentBlock()
+ // Internal for tests: process B reads its switches (SHARPEMU_DRAW_REPLAY and the rest) from this block.
+ internal static List EnvironmentBlock()
{
var block = new List();
var gen0Set = false;
diff --git a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs
index fda4b01d4..1112d82a0 100644
--- a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs
+++ b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs
@@ -12,8 +12,9 @@ public static class GpuRemoteProtocol
/// 2: the B → A call table, the application block and the split's messages (GpuSplitMessages.cs).
/// 3: .
/// 4: frame-boundary messages. 5: input-change and display reservations.
- /// 6: pending-writeback pages. 7: combined frame, input and writeback layout.
- public const uint Version = 7;
+ /// 6: pending-writeback pages. 7: combined frame, input and writeback layout.
+ /// 8: .
+ public const uint Version = 8;
}
@@ -136,6 +137,9 @@ public enum GpuRemoteSyncOpcode : uint
/// → : the waiting half of a split SubmitDone.
WaitFrameBoundary = 11,
+
+ /// → nothing: a PRT aperture or the AMM area changed in A.
+ ResidencyRange = 12,
}
/// Opcodes of the B → A synchronous call table: what B's GPU code asks of A's video-out state.
diff --git a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs
index 359b55cb2..d331dd9e1 100644
--- a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs
+++ b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs
@@ -473,6 +473,21 @@ public struct SpanRequest
public ulong BracketId;
}
+///
+/// A guest range whose unmapped pages GPU reads see as zero (a PRT aperture or the AMM area), set, moved or dropped
+/// ( 0) by the guest process's kernel: PartiallyResidentRanges.
+///
+[StructLayout(LayoutKind.Sequential)]
+public struct ResidencyRangeRequest
+{
+ public ulong Address;
+ public ulong Size;
+ public int Id;
+
+ /// 1: the kernel also registered the range as lazily backed GPU memory (GuestGpuMemoryHook.NoteLazyRange).
+ public uint LazilyBacked;
+}
+
[StructLayout(LayoutKind.Sequential)]
public struct QueryRequest
{
diff --git a/src/SharpEmu.GpuSplit/SplitGpuHost.cs b/src/SharpEmu.GpuSplit/SplitGpuHost.cs
index 56a97e9df..0a74bcb5f 100644
--- a/src/SharpEmu.GpuSplit/SplitGpuHost.cs
+++ b/src/SharpEmu.GpuSplit/SplitGpuHost.cs
@@ -584,6 +584,10 @@ public int HandleCall(uint opcode, ReadOnlySpan request, Span respon
return 0;
}
+ case GpuRemoteSyncOpcode.ResidencyRange:
+ MirrorResidencyRange(GpuSplitWire.Read(request));
+ return 0;
+
case GpuRemoteSyncOpcode.Query:
return Query(GpuSplitWire.Read(request), response);
@@ -600,6 +604,38 @@ public int HandleCall(uint opcode, ReadOnlySpan request, Span respon
}
}
+ // A PRT aperture or the AMM area the guest process's kernel set, moved or dropped (PartiallyResidentRanges): image
+ // reads here answer from it as the kernel answers there (ResidentImageBacking), and an aperture the kernel registered
+ // as lazily backed GPU memory is registered with this process's manager as GuestGpuMemoryHook.NoteLazyRange does
+ // there, so a managed write into it reaches the caches here and the ledger stays the guest process's.
+ private void MirrorResidencyRange(in ResidencyRangeRequest call)
+ {
+ var range = new PartiallyResidentRanges.Range(call.Id, call.Address, call.Size, call.LazilyBacked != 0);
+ _ = PartiallyResidentRanges.Mirror(range);
+ var memory = _memory!;
+ lock (_lazyRanges)
+ {
+ if (_lazyRanges.Remove(call.Id, out var lazy))
+ {
+ memory.UnregisterLazyRange(lazy.Address, lazy.Size);
+ }
+
+ if (range.LazilyBacked && GuestGpuMemoryHook.IsWithinGpuAddressSpace(range.Address, range.Size))
+ {
+ _lazyRanges[call.Id] = (range.Address, range.Size);
+ memory.RegisterLazyRange(range.Address, range.Size);
+ }
+ }
+
+ Interlocked.Increment(ref _residencyChanges);
+ }
+
+ private readonly Dictionary _lazyRanges = [];
+ private long _residencyChanges;
+
+ /// PRT/AMM range changes the guest process sent ().
+ internal long ResidencyChanges => Interlocked.Read(ref _residencyChanges);
+
private int BeginBracket(in BracketBeginRequest call, Span response, out int status)
{
status = GpuSplitStatus.Ok;
diff --git a/src/SharpEmu.GpuSplit/SplitGpuSession.cs b/src/SharpEmu.GpuSplit/SplitGpuSession.cs
index 79cb28b06..3923d735a 100644
--- a/src/SharpEmu.GpuSplit/SplitGpuSession.cs
+++ b/src/SharpEmu.GpuSplit/SplitGpuSession.cs
@@ -73,6 +73,7 @@ public sealed class SplitGpuSession : IDisposable
private long _protectsApplied;
private long _protectsSkipped;
private bool _globalsInstalled;
+ private bool _residencyMirrored;
internal SplitGpuSession(GpuRemoteChannel channel, object outboundLock, GuestGpuMemory memory, GuestViewTable viewTable,
ISplitGuestSide guest, IDisposable? process = null, IDisposable? memoryServer = null)
@@ -261,9 +262,43 @@ private void InstallGlobals()
}
HostWindowInput.Connect(new SplitGamepadOutput(Writer));
+ MirrorResidencyRanges();
_globalsInstalled = true;
}
+ ///
+ /// Sends the kernel's PRT apertures and AMM area to the GPU process, the current ones now and every change from
+ /// then on (): its image reads ask the same question of them as the kernel answers
+ /// here (ResidentImageBacking), and its GPU memory manager covers the lazily backed ones as this process's does.
+ ///
+ ///
+ /// A call, as span registrations are: it returns once the GPU process applied it, so a submission or a span change
+ /// this process makes after the kernel call that changed a range finds it applied there; and a span the kernel
+ /// registers inside an aperture after the aperture was set reaches the GPU process's ledger after the aperture's
+ /// lazy registration, in this process's order. One call per aperture or area change (the kernel's rare calls), none
+ /// per read.
+ ///
+ internal void MirrorResidencyRanges()
+ {
+ PartiallyResidentRanges.Attach(SendResidencyRange);
+ _residencyMirrored = true;
+ }
+
+ private void SendResidencyRange(PartiallyResidentRanges.Range range)
+ {
+ if (!Call(GpuRemoteSyncOpcode.ResidencyRange, new ResidencyRangeRequest
+ {
+ Id = range.Id,
+ Address = range.Address,
+ Size = range.Size,
+ LazilyBacked = range.LazilyBacked ? 1u : 0u,
+ }, LongCallNanoseconds))
+ {
+ Report($"The GPU process did not take PRT/AMM range {range.Id} (0x{range.Address:X16}+0x{range.Size:X}); " +
+ "its image reads there stop instead of reading unmapped pages as zero.");
+ }
+ }
+
private void SendFusedProgram(ulong entry, ulong entryHeader, ulong continuation, ulong continuationHeader) =>
_ = Writer.Write(GpuRemoteMessage.FusedProgram, new FusedProgramMessage
{
@@ -758,6 +793,11 @@ private void Detach()
_memory.AttachGpuQueue(null, null);
_memory.AttachStores(null, null);
FrameOverlapDiagnostic.RemoteReadFault = null;
+ if (_residencyMirrored)
+ {
+ PartiallyResidentRanges.Attach(null);
+ }
+
if (_globalsInstalled)
{
AgcBackendServices.ShaderHeaderObserver = null;
diff --git a/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs b/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs
index e6aeb47e1..7e1d35187 100644
--- a/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs
+++ b/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs
@@ -16,13 +16,28 @@ private sealed class Node(ulong start, ulong end)
public int Count = 1;
}
+ // A new snapshot copies the last one's spans outside the extent of every span removed or inserted since, and walks the
+ // tree only inside it. SHARPEMU_SPAN_SNAPSHOT_SPLICE=0 walks the whole tree.
+ private static readonly bool SpliceSnapshots = Environment.GetEnvironmentVariable("SHARPEMU_SPAN_SNAPSHOT_SPLICE") != "0";
+
private Node? _root;
private SpanSnapshot? _snapshot = SpanSnapshot.Empty;
+ private SpanSnapshot _built = SpanSnapshot.Empty;
+ private ulong _changedStart = ulong.MaxValue;
+ private ulong _changedEnd;
+ internal int SplicedSnapshots { get; private set; }
public bool IsEmpty => _root is null;
public void Clear()
{
_root = null;
- _snapshot = SpanSnapshot.Empty;
+ Built(SpanSnapshot.Empty);
+ }
+
+ private void NoteChange(ulong start, ulong end)
+ {
+ _snapshot = null;
+ _changedStart = Math.Min(_changedStart, start);
+ _changedEnd = Math.Max(_changedEnd, end);
}
public void Add(ulong address, ulong size)
@@ -37,13 +52,13 @@ public void Add(ulong address, ulong size)
start = previous.Start;
_root = Delete(_root, start);
}
- _snapshot = null;
for (var next = FindAtOrAbove(start); next is not null && next.Start <= end; next = FindAtOrAbove(start))
{
end = Math.Max(end, next.End);
_root = Delete(_root, next.Start);
}
_root = Insert(_root, start, end);
+ NoteChange(start, end);
}
public void Remove(ulong address, ulong size)
@@ -53,11 +68,11 @@ public void Remove(ulong address, ulong size)
var current = FindAtOrBelow(address);
if (current is null || current.End <= address) current = FindAtOrAbove(address);
if (current is null || current.Start >= end) return;
- _snapshot = null;
while (current is not null && current.Start < end)
{
var spanStart = current.Start;
var spanEnd = current.End;
+ NoteChange(spanStart, spanEnd);
_root = Delete(_root, spanStart);
if (spanStart < address) _root = Insert(_root, spanStart, address);
if (spanEnd > end)
@@ -93,12 +108,90 @@ public bool Overlaps(ulong address, ulong size)
public SpanSnapshot Snapshot()
{
if (_snapshot is { } snapshot) return snapshot;
- if (_root is null) return _snapshot = SpanSnapshot.Empty;
+ if (_root is null) return Built(SpanSnapshot.Empty);
var starts = new ulong[_root.Count];
var ends = new ulong[starts.Length];
- var index = 0;
- Collect(_root, starts, ends, ref index);
- return _snapshot = new SpanSnapshot(starts, ends);
+ if (SpliceSnapshots && TrySplice(starts, ends))
+ {
+ SplicedSnapshots++;
+ }
+ else
+ {
+ var index = 0;
+ Collect(_root, starts, ends, ref index);
+ }
+
+ return Built(new SpanSnapshot(starts, ends));
+ }
+
+ private SpanSnapshot Built(SpanSnapshot snapshot)
+ {
+ _changedStart = ulong.MaxValue;
+ _changedEnd = 0;
+ return _snapshot = _built = snapshot;
+ }
+
+ // The spans that end before the changed extent or start after it are the last snapshot's; the tree gives the ones
+ // between. False when the counts disagree, and the caller walks the whole tree.
+ private bool TrySplice(ulong[] starts, ulong[] ends)
+ {
+ var builtStarts = _built.Starts;
+ var builtEnds = _built.Ends;
+ var before = FirstAtOrAbove(builtEnds, _changedStart);
+ var after = FirstAbove(builtStarts, _changedEnd);
+ var tail = builtStarts.Length - after;
+ var middle = starts.Length - before - tail;
+ if (middle < 0) return false;
+ builtStarts[..before].CopyTo(starts);
+ builtEnds[..before].CopyTo(ends);
+ var index = before;
+ if (!CollectWithin(_root, _changedStart, _changedEnd, starts, ends, ref index, before + middle) ||
+ index != before + middle)
+ {
+ return false;
+ }
+
+ builtStarts[after..].CopyTo(starts.AsSpan(index));
+ builtEnds[after..].CopyTo(ends.AsSpan(index));
+ return true;
+ }
+
+ private static int FirstAtOrAbove(ReadOnlySpan values, ulong bound)
+ {
+ int low = 0, high = values.Length;
+ while (low < high)
+ {
+ var middle = (low + high) >>> 1;
+ if (values[middle] < bound) low = middle + 1;
+ else high = middle;
+ }
+ return low;
+ }
+
+ private static int FirstAbove(ReadOnlySpan values, ulong bound)
+ {
+ int low = 0, high = values.Length;
+ while (low < high)
+ {
+ var middle = (low + high) >>> 1;
+ if (values[middle] <= bound) low = middle + 1;
+ else high = middle;
+ }
+ return low;
+ }
+
+ // In order, the spans that touch [low, high]; false when they would pass the limit.
+ private static bool CollectWithin(Node? node, ulong low, ulong high, ulong[] starts, ulong[] ends, ref int index, int limit)
+ {
+ if (node is null) return true;
+ if (node.Start >= low && !CollectWithin(node.Left, low, high, starts, ends, ref index, limit)) return false;
+ if (node.End >= low && node.Start <= high)
+ {
+ if (index == limit) return false;
+ starts[index] = node.Start;
+ ends[index++] = node.End;
+ }
+ return node.End > high || CollectWithin(node.Right, low, high, starts, ends, ref index, limit);
}
public List GetOverlappingRanges(ulong address, ulong size)
diff --git a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs
index c02894a09..130eb15b0 100644
--- a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs
+++ b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs
@@ -236,6 +236,136 @@ AddressSpace is not IGuestBackedSpace backing ||
private const ulong GuestWriteGranule = 0x4000;
+ // Both hooks execute outside admission/tracker/image locks. The reserved hook is for
+ // deterministic tests only: it must never request work from the GPU queue.
+ internal Action? BeforeManagedWriteReservationForTest;
+ internal Action? ManagedWriteReservedForTest;
+
+ internal readonly ref struct ManagedWriteLease(GuestGpuMemory memory, ulong address, ulong size,
+ GuestWriteReservations.CpuAttempt? attempt, bool emulatorWrite, bool unleased = false)
+ {
+ public void Dispose()
+ {
+ if (memory is null || attempt?.Released == true) return;
+ try
+ {
+ // Include partial or failed copies: any page may have received new bytes.
+ memory.MarkManagedWriteParts(address, size, landed: true, emulatorWrite);
+ }
+ finally
+ {
+ if (unleased) GuestWriteReservations.ExitUnleasedWrite();
+ else attempt?.Dispose();
+ }
+ }
+ }
+
+ // emulatorWrite: the write goes through one backing view, so the stores take PrepareEmulatorWrite before it and
+ // NoteEmulatorWrite after it; otherwise MarkCpuWrite before and MarkCpuWriteLanded after.
+ internal ManagedWriteLease BeginManagedWrite(ulong address, ulong size, bool emulatorWrite = false)
+ {
+ var valid = address != 0 && size != 0 && new GuestSpan(address, size).IsValid;
+ // No backend makes GPU claims over these pages (GuestWriteReservations.Gate.cs): the write marks the stores before
+ // and after it lands, as it did before the lease, and its thread's depth lets a claimant that registers meanwhile
+ // wait for it to land.
+ var reservations = _pages.ManagedWrites;
+ if (valid && !reservations.LeasesWrites)
+ {
+ GuestImageWriteTracker.NotifyManagedWrite(address, size);
+ MarkManagedWriteParts(address, size, landed: false, emulatorWrite);
+ if (reservations.TryEnterUnleasedWrite())
+ {
+ return new ManagedWriteLease(this, address, size, null, emulatorWrite, unleased: true);
+ }
+
+ // A claimant registered after the check: the write takes the lease, and its premark repeats.
+ }
+
+ for (var retry = 0; ; retry++)
+ {
+ GuestWriteReservations.CpuAttempt? attempt = valid ? reservations.BeginCpuAttempt(address, size) : null;
+ try
+ {
+ // Recovery can relay to the GPU; no reservation is held yet.
+ GuestImageWriteTracker.NotifyManagedWrite(address, size);
+ MarkManagedWriteParts(address, size, landed: false, emulatorWrite);
+ BeforeManagedWriteReservationForTest?.Invoke(retry);
+ if (attempt is { } activeAttempt && !activeAttempt.TryReserve())
+ {
+ activeAttempt.Dispose();
+ continue;
+ }
+ if (attempt is not null) ManagedWriteReservedForTest?.Invoke();
+ return new ManagedWriteLease(this, address, size, attempt, emulatorWrite);
+ }
+ catch
+ {
+ attempt?.Dispose();
+ throw;
+ }
+ }
+ }
+
+ private void MarkManagedWriteParts(ulong address, ulong size, bool landed, bool emulatorWrite)
+ {
+ if (size == 0 || !new GuestSpan(address, size).IsValid) return;
+ var snapshot = Volatile.Read(ref _spanSnapshot) ?? throw new ObjectDisposedException(nameof(GuestGpuMemory));
+ var lazy = Volatile.Read(ref _lazySnapshot);
+ if (snapshot.Contains(address, size) || lazy.Contains(address, size))
+ {
+ MarkManagedWritePart(address, size, landed, emulatorWrite);
+ return;
+ }
+
+ MarkPartialManagedWrite(snapshot, lazy, address, size, landed, emulatorWrite);
+ }
+
+ private void MarkManagedWritePart(ulong address, ulong size, bool landed, bool emulatorWrite)
+ {
+ if (emulatorWrite)
+ {
+ if (landed) NoteEmulatorWrite(address, size);
+ else PrepareEmulatorWrite(address, size);
+ }
+ else if (landed)
+ {
+ MarkCpuWriteLanded(address, size);
+ }
+ else
+ {
+ _ = MarkCpuWrite(address, size);
+ }
+ }
+
+ // Keep the callback closure off the common full-span path. Every intersection with a registered span or a lazily backed
+ // range matters; a part both cover is marked twice, which repeats the same conservative mark.
+ private void MarkPartialManagedWrite(SpanSnapshot snapshot, SpanSnapshot lazy, ulong address, ulong size, bool landed,
+ bool emulatorWrite)
+ {
+ // HostCallTrims.MarkClosureFree: the same overlap walk, its state passed in by value instead of a closure allocated
+ // for each call.
+ if (HostCallTrims.MarkClosureFree)
+ {
+ var state = (Memory: this, Landed: landed, Emulator: emulatorWrite);
+ snapshot.ForEachOverlap(address, size, state,
+ static (part, partAddress, partSize) => part.Memory.MarkManagedWritePart(partAddress, partSize, part.Landed, part.Emulator));
+ lazy.ForEachOverlap(address, size, state,
+ static (part, partAddress, partSize) => part.Memory.MarkManagedWritePart(partAddress, partSize, part.Landed, part.Emulator));
+ return;
+ }
+
+ MarkPartialManagedWriteWithClosure(snapshot, lazy, address, size, landed, emulatorWrite);
+ }
+
+ // A separate method: a lambda capturing a parameter allocates its closure on entry to the method that holds it.
+ private void MarkPartialManagedWriteWithClosure(SpanSnapshot snapshot, SpanSnapshot lazy, ulong address, ulong size,
+ bool landed, bool emulatorWrite)
+ {
+ void Visit(ulong partAddress, ulong partSize) => MarkManagedWritePart(partAddress, partSize, landed, emulatorWrite);
+ snapshot.ForEachOverlap(address, size, Visit);
+ lazy.ForEachOverlap(address, size, Visit);
+ }
+
public bool MarkCpuWrite(ulong address, ulong size)
{
diff --git a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemoryHook.cs b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemoryHook.cs
index 963fcec98..c7cc9d840 100644
--- a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemoryHook.cs
+++ b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemoryHook.cs
@@ -180,6 +180,15 @@ public static bool TryResolveFault(FaultKind kind, ulong address)
return false;
}
+ // Capture the attached manager once, and hold its reservation through the landed notification.
+ internal static GuestGpuMemory.ManagedWriteLease BeginCpuWrite(ulong address, ulong size, bool emulatorWrite = false)
+ {
+ if (size == 0) return default;
+ if (_current is { } current) return current.BeginManagedWrite(address, size, emulatorWrite);
+ GuestImageWriteTracker.NotifyManagedWrite(address, size);
+ return default;
+ }
+
// Notify the stores before a managed write changes guest memory.
public static void MarkCpuWrite(ulong address, ulong size)
{
diff --git a/src/SharpEmu.HLE/GpuMemory/GuestPageTracker.cs b/src/SharpEmu.HLE/GpuMemory/GuestPageTracker.cs
index 6e992c71e..c17da4eb4 100644
--- a/src/SharpEmu.HLE/GpuMemory/GuestPageTracker.cs
+++ b/src/SharpEmu.HLE/GpuMemory/GuestPageTracker.cs
@@ -138,7 +138,9 @@ public bool MayHaveCpuDirtyPages(ulong vaddr, ulong size)
while (remaining != 0)
{
var bytes = Math.Min(BlockBytes - offset, remaining);
- if (Volatile.Read(ref _regions[index]) is not { } region || region.IsModified(WriteOrigin.Cpu, offset, bytes))
+ // A clear summary bit means the block has no CPU-dirty page; IsKnownCpuClean trusts the same bit.
+ if (Volatile.Read(ref _regions[index]) is not { } region ||
+ (_cpuDirtySummary.IsDirty(index) && region.IsModified(WriteOrigin.Cpu, offset, bytes)))
{
return true;
}
@@ -903,13 +905,19 @@ private static PageMask SpanPages(GuestSpan[] spans, ref int nextSpan, ulong blo
return pages;
}
+ // 64 blocks per step: a block is known clean when its region is present and its summary bit is clear. The present bit
+ // is set after the region is stored, so a clear one is at worst a region not seen yet.
private bool IsKnownCpuClean(ulong vaddr, ulong size)
{
ValidateRange(vaddr, size);
+ var first = vaddr / BlockBytes;
var last = (vaddr + size - 1) / BlockBytes;
- for (var index = vaddr / BlockBytes; index <= last; index++)
+ for (var word = first / 64; word <= last / 64; word++)
{
- if (Volatile.Read(ref _regions[index]) == null || _cpuDirtySummary.IsDirty(index))
+ var possiblyDirty = ~(ulong)Volatile.Read(ref _presentRegions[word]) | _cpuDirtySummary.Word((int)word);
+ var low = word == first / 64 ? (int)(first % 64) : 0;
+ var high = word == last / 64 ? (int)(last % 64) : 63;
+ if ((possiblyDirty & (ulong.MaxValue >> (63 - high)) & (ulong.MaxValue << low)) != 0)
{
return false;
}
diff --git a/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.Gate.cs b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.Gate.cs
new file mode 100644
index 000000000..6c08be71a
--- /dev/null
+++ b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.Gate.cs
@@ -0,0 +1,132 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+using System.Runtime.InteropServices;
+
+namespace SharpEmu.HLE.GpuMemory;
+
+// The managed-write lease guards a CPU write against a GPU claim over its pages, and only a backend that makes GPU claims
+// (the Vulkan buffer cache) gives it a meaning: the Metal backend never claims (it orders its own guest-memory writes
+// another way), so on macOS every managed write paid for a reservation nothing ever waited on. A managed write therefore
+// takes the lease only once a claimant has registered with these reservations (RegisterClaimant: the Vulkan cache when it
+// is constructed, and any first claim before it proceeds); until then it runs as it did before the lease existed, with
+// one per-thread depth counter around its copy and landed notification.
+//
+// No claim can meet a write that started before registration unprotected. Registration first raises _claimant, then
+// makes every thread either see it or show its depth (Interlocked.MemoryBarrierProcessWide), then waits until every
+// unleased depth is zero, and only then lets a claim proceed (_registered). An unleased write raises its thread's depth
+// after its premark and reads _claimant afterwards: either the read sees the claimant, and the write backs out and takes
+// the lease (its premark repeats, which marks the same pages again), or its depth store precedes the barrier, and
+// registration waits for the write to land and be marked. The write's own side needs no fence, as for the chunk marks of
+// the lease's lock-free path. The premark stays outside the depth, as it stays outside the reservation (it may relay to
+// the GPU, whose claim must not wait on it).
+//
+// SHARPEMU_MANAGED_WRITE_LEASE_GATE=0 makes every managed write take the lease, as upstream does.
+public sealed partial class GuestWriteReservations
+{
+ /// False: every managed write takes the lease (SHARPEMU_MANAGED_WRITE_LEASE_GATE=0). Tests switch it.
+ public static bool GateEnabled { get; set; } =
+ Environment.GetEnvironmentVariable("SHARPEMU_MANAGED_WRITE_LEASE_GATE") != "0";
+
+ private readonly object _registration = new();
+ private int _claimant;
+ private int _registered;
+
+ // Each thread's unleased writes in progress, padded so two threads never share a cache line.
+ [StructLayout(LayoutKind.Explicit, Size = 128)]
+ private struct UnleasedRecord
+ {
+ [FieldOffset(64)] public int Depth;
+ }
+
+ private static readonly UnleasedRecord[] s_unleased = new UnleasedRecord[RecordCount];
+ private static int s_unleasedTaken;
+
+ // The thread's record: its index + 1, 0 before its first unleased write, -1 when every record is taken.
+ [ThreadStatic] private static int t_unleased;
+
+ /// Whether a managed write over these reservations takes the lease: a claimant registered, or the gate is off.
+ public bool LeasesWrites => Volatile.Read(ref _claimant) != 0 || !GateEnabled;
+
+ /// Whether a backend that makes GPU claims registered with these reservations.
+ public bool HasClaimant => Volatile.Read(ref _registered) != 0;
+
+ ///
+ /// A backend that makes GPU claims (): every managed write from now on takes the lease, and
+ /// this returns once every write that started without one has landed. Idempotent; the first claim calls it too.
+ ///
+ public void RegisterClaimant()
+ {
+ if (Volatile.Read(ref _registered) != 0)
+ {
+ return;
+ }
+
+ lock (_registration)
+ {
+ if (_registered != 0)
+ {
+ return;
+ }
+
+ Volatile.Write(ref _claimant, 1);
+ // Every thread either reads the claimant from now on or has its depth store visible below.
+ Interlocked.MemoryBarrierProcessWide();
+ var own = t_unleased;
+ var records = Math.Min(Volatile.Read(ref s_unleasedTaken), RecordCount);
+ for (var index = 0; index < records; index++)
+ {
+ if (index + 1 == own && Volatile.Read(ref s_unleased[index].Depth) != 0)
+ {
+ throw new InvalidOperationException("A managed CPU writer cannot register a GPU claimant inside its own write.");
+ }
+
+ var spin = new SpinWait();
+ while (Volatile.Read(ref s_unleased[index].Depth) != 0)
+ {
+ spin.SpinOnce(sleep1Threshold: -1);
+ }
+ }
+
+ Volatile.Write(ref _registered, 1);
+ }
+ }
+
+ ///
+ /// A managed write after its premark, with no claimant registered: counts it in the thread's depth. False when a
+ /// claimant registered meanwhile (or no record is left): the write takes the lease instead.
+ ///
+ internal bool TryEnterUnleasedWrite()
+ {
+ var index = t_unleased;
+ if (index == 0)
+ {
+ index = Interlocked.Increment(ref s_unleasedTaken);
+ t_unleased = index = index <= RecordCount ? index : -1;
+ }
+
+ if (index < 0)
+ {
+ return false;
+ }
+
+ ref var record = ref s_unleased[index - 1];
+ var depth = record.Depth;
+ Volatile.Write(ref record.Depth, depth + 1);
+ // No fence: registration makes the depth store visible before it reads the depths.
+ if (Volatile.Read(ref _claimant) == 0)
+ {
+ return true;
+ }
+
+ Volatile.Write(ref record.Depth, depth);
+ return false;
+ }
+
+ /// The landed end of a write counted.
+ internal static void ExitUnleasedWrite()
+ {
+ ref var record = ref s_unleased[t_unleased - 1];
+ Volatile.Write(ref record.Depth, record.Depth - 1);
+ }
+}
diff --git a/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs
new file mode 100644
index 000000000..488f5b594
--- /dev/null
+++ b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs
@@ -0,0 +1,651 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+using System.Runtime.InteropServices;
+
+namespace SharpEmu.HLE.GpuMemory;
+
+// Premark may relay to the GPU. Only the subsequent copy and landed notification reserve pages.
+// Admission and validation share this gate; no store, copy or relay executes while it is held.
+//
+// A managed write inside one 2 MiB region takes no lock while no GPU claim covers the region, as almost every guest
+// store does. Its reservation is an entry in the region's slot of a small table, published before it reads the slot's
+// claim count; a GPU claim counts itself into the slots of its regions before it reads their entries, so either the
+// write sees the claim or the claim sees the write. A write that meets a claim or a locked reservation in its region,
+// spans regions or finds its slot full takes the locked path, under the same rules. A claim that began in the region
+// while the write premarked is looked up in the history of recent claims, so only a claim over the write's own pages
+// invalidates it, as on the locked path.
+//
+// Most guest stores go to memory that no GPU claim has ever covered, such as command buffers. A claim marks the 64 KiB
+// chunks of its range for good. A write inside one region whose chunks are unmarked reserves its pages in its thread's
+// own record instead of the shared slot table and then reads the marks again; a mark that appeared while the write
+// premarked sends it on to the slot table, where the claim history decides whether it premarks again. The claim that
+// marks a chunk first makes every thread either see the mark or show its record (Interlocked.MemoryBarrierProcessWide)
+// and waits out every recorded write in the chunk. Writes on unmarked chunks do not exclude each other; each landed
+// notification marks its pages again.
+public sealed partial class GuestWriteReservations
+{
+ private readonly object _gate = new();
+ private readonly List _cpu = [];
+ private readonly List _gpu = [];
+ private long _nextClaim;
+ private long _nextCpuAttempt;
+
+ private const int RegionShift = 21;
+ private const int SlotBits = 10;
+ private const int SlotCount = 1 << SlotBits;
+ private const int Ways = 4;
+ private const int HistorySize = 64;
+ // An entry being filled in: its range is not readable yet, so it counts as overlapping everything.
+ private const long Filling = -1;
+ private readonly Slot[] _slots = new Slot[SlotCount];
+ private readonly long[] _entryTokens = new long[SlotCount * Ways];
+ private readonly ulong[] _entryStarts = new ulong[SlotCount * Ways];
+ private readonly ulong[] _entryEnds = new ulong[SlotCount * Ways];
+ private readonly ClaimRecord[] _history = new ClaimRecord[HistorySize];
+ private long _claimSequence;
+
+ // One bit per 64 KiB chunk of the guest GPU address space that a GPU claim has covered.
+ private const int ChunkShift = 16;
+ private readonly long[] _claimedChunks = new long[(int)(TrackerLayout.SpaceBytes >> ChunkShift >> 6)];
+
+ // Each thread's reservation on unmarked chunks, shared by every owner: a thread reserves one write at a time.
+ private const int RecordCount = 1024;
+ private static readonly ThreadRecord[] s_records = new ThreadRecord[RecordCount];
+ private static int s_recordsTaken;
+
+ [ThreadStatic] private static FastAttempt? t_fast;
+ [ThreadStatic] private static uint t_tokens;
+ [ThreadStatic] private static List? t_lockedReserved;
+
+ // Tests may only signal asynchronous continuations from these hooks, which run under the gate.
+ internal Action? GpuClaimWaitingForTest;
+ internal Action? CpuAttemptWaitingForTest;
+ private readonly record struct Claim(long Id, ulong Start, ulong End, int Thread);
+ private readonly record struct ClaimRecord(long Sequence, ulong Start, ulong End);
+
+ private record struct CpuReservation(long Id, ulong Start, ulong End, int Thread)
+ {
+ internal bool Invalidated;
+ internal bool Reserved;
+ }
+
+ // A region's GPU claims (begun and not released), its locked reservations and the count of claims begun in it.
+ [StructLayout(LayoutKind.Explicit, Size = 64)]
+ private struct Slot
+ {
+ [FieldOffset(0)] public int Claims;
+ [FieldOffset(4)] public int LockedReserved;
+ [FieldOffset(8)] public long Epoch;
+ }
+
+ // Padded so that two threads' records never share a cache line.
+ [StructLayout(LayoutKind.Explicit, Size = 128)]
+ private struct ThreadRecord
+ {
+ [FieldOffset(64)] public long Token;
+ [FieldOffset(72)] public ulong Start;
+ [FieldOffset(80)] public ulong End;
+ [FieldOffset(88)] public GuestWriteReservations? Owner;
+ }
+
+ // The thread's lock-free attempt. A thread holds at most one; a nested attempt takes the locked path.
+ private sealed class FastAttempt
+ {
+ public GuestWriteReservations? Owner;
+ public GuestWriteReservations? LockedNext;
+ public long Token;
+ public ulong Start;
+ public ulong End;
+ public int Slot;
+ public int Entry = -1;
+ // The thread's record, or -1 when every record is taken.
+ public readonly int Record = TakeRecord();
+ public long Epoch;
+ public long Sequence;
+ public bool Active;
+ public bool Reserved;
+ public bool Invalidated;
+ public bool InRecord;
+ }
+
+ private static int TakeRecord()
+ {
+ var index = Interlocked.Increment(ref s_recordsTaken) - 1;
+ return index < RecordCount ? index : -1;
+ }
+
+ // A copied or stale token names only its original admission; a later write never reuses that id. Locked attempts
+ // have positive ids, lock-free ones the negated token of their thread.
+ internal readonly struct CpuAttempt(GuestWriteReservations owner, long id) : IDisposable
+ {
+ internal bool Released => owner is null || owner.IsReleased(id);
+ internal bool TryReserve() => owner is not null ? owner.TryReserve(id)
+ : throw new InvalidOperationException("The CPU write attempt is not available on this thread.");
+ public void Dispose() => owner?.Release(id);
+ }
+
+ public readonly struct GpuClaim : IDisposable
+ {
+ private readonly GuestWriteReservations? owner;
+ private readonly long id;
+
+ internal GpuClaim(GuestWriteReservations owner, long id)
+ {
+ this.owner = owner;
+ this.id = id;
+ }
+
+ public void Dispose() => owner?.ReleaseGpu(id);
+ }
+
+ internal CpuAttempt BeginCpuAttempt(ulong address, ulong size)
+ {
+ var (start, end) = Pages(address, size);
+ RejectFastReservedReentry();
+ var fast = t_fast;
+ if (fast?.LockedNext == this)
+ {
+ fast.LockedNext = null;
+ }
+ else if (start >> RegionShift == (end - 1) >> RegionShift && fast is not { Active: true } &&
+ t_lockedReserved is not { Count: > 0 })
+ {
+ fast ??= t_fast = new FastAttempt();
+ var slot = SlotOf(start >> RegionShift);
+ // Sequence, then the marks, then epoch, then the counts: a claim marks its chunks and counts itself into the
+ // slot before it advances the epoch and takes its sequence number.
+ var sequence = Volatile.Read(ref _claimSequence);
+ var inRecord = fast.Record >= 0 && ChunksUnmarked(start, end);
+ // An epoch no slot reaches: a write that leaves its record looks up every claim since the sequence.
+ var epoch = inRecord ? -1 : Volatile.Read(ref _slots[slot].Epoch);
+ if (inRecord ||
+ (Volatile.Read(ref _slots[slot].Claims) == 0 && Volatile.Read(ref _slots[slot].LockedReserved) == 0))
+ {
+ fast.Owner = this;
+ fast.Token = ((long)Environment.CurrentManagedThreadId << 32) | ++t_tokens;
+ fast.Start = start;
+ fast.End = end;
+ fast.Slot = slot;
+ fast.Entry = -1;
+ fast.Epoch = epoch;
+ fast.Sequence = sequence;
+ fast.Active = true;
+ fast.Reserved = false;
+ fast.Invalidated = false;
+ fast.InRecord = inRecord;
+ return new CpuAttempt(this, -fast.Token);
+ }
+ }
+
+ return BeginLockedCpuAttempt(start, end);
+ }
+
+ private CpuAttempt BeginLockedCpuAttempt(ulong start, ulong end)
+ {
+ var thread = Environment.CurrentManagedThreadId;
+ lock (_gate)
+ {
+ RejectReservedReentry(thread);
+ while (ReservedOverlap(start, end) || GpuOverlap(start, end, thread) || FastEntryOverlaps(start, end))
+ {
+ CpuAttemptWaitingForTest?.Invoke();
+ WaitForRelease(start, end, thread, cpu: true);
+ }
+ var id = checked(++_nextCpuAttempt);
+ _cpu.Add(new CpuReservation(id, start, end, thread));
+ return new CpuAttempt(this, id);
+ }
+ }
+
+ private bool TryReserve(long id)
+ {
+ if (id < 0)
+ {
+ return TryReserveFast(-id);
+ }
+
+ lock (_gate)
+ {
+ for (var index = _cpu.Count - 1; index >= 0; index--)
+ {
+ var attempt = _cpu[index];
+ if (attempt.Id != id) continue;
+ if (attempt.Reserved || attempt.Thread != Environment.CurrentManagedThreadId)
+ break;
+ if (attempt.Invalidated || ReservedOverlap(attempt.Start, attempt.End) ||
+ GpuOverlap(attempt.Start, attempt.End, attempt.Thread))
+ return false;
+ // Counted into the slots before the entries are read: a lock-free write that publishes later sees the count.
+ AddLockedReserved(attempt.Start, attempt.End, 1);
+ if (FastEntryOverlaps(attempt.Start, attempt.End))
+ {
+ AddLockedReserved(attempt.Start, attempt.End, -1);
+ return false;
+ }
+ attempt.Reserved = true;
+ _cpu[index] = attempt;
+ (t_lockedReserved ??= []).Add(this);
+ return true;
+ }
+ throw new InvalidOperationException("The CPU write attempt is not available on this thread.");
+ }
+ }
+
+ private bool TryReserveFast(long token)
+ {
+ var fast = t_fast;
+ if (fast is null || !fast.Active || fast.Owner != this || fast.Token != token || fast.Reserved)
+ throw new InvalidOperationException("The CPU write attempt is not available on this thread.");
+ if (fast.Invalidated)
+ return false;
+
+ if (fast.InRecord)
+ {
+ ref var record = ref s_records[fast.Record];
+ record.Owner = this;
+ record.Start = fast.Start;
+ record.End = fast.End;
+ Volatile.Write(ref record.Token, token);
+ // No fence: the claim that marks a chunk first makes this store visible before it reads the records.
+ if (ChunksUnmarked(fast.Start, fast.End))
+ {
+ fast.Reserved = true;
+ return true;
+ }
+
+ // A claim marked a chunk while the write premarked.
+ Volatile.Write(ref record.Token, 0);
+ fast.InRecord = false;
+ }
+
+ var slot = fast.Slot;
+ var entry = -1;
+ for (var way = 0; way < Ways; way++)
+ {
+ var index = slot * Ways + way;
+ if (Volatile.Read(ref _entryTokens[index]) != 0 ||
+ Interlocked.CompareExchange(ref _entryTokens[index], Filling, 0) != 0)
+ continue;
+ _entryStarts[index] = fast.Start;
+ _entryEnds[index] = fast.End;
+ // Published with a full fence, so the counts read below are not read before the entry is visible.
+ Interlocked.Exchange(ref _entryTokens[index], token);
+ entry = index;
+ break;
+ }
+
+ if (entry < 0)
+ {
+ fast.LockedNext = this;
+ return false;
+ }
+
+ if (Volatile.Read(ref _slots[slot].Claims) != 0 || Volatile.Read(ref _slots[slot].LockedReserved) != 0 ||
+ OtherEntryOverlaps(slot, entry, fast.Start, fast.End))
+ {
+ ClearEntry(entry);
+ fast.LockedNext = this;
+ return false;
+ }
+
+ if (Volatile.Read(ref _slots[slot].Epoch) != fast.Epoch && ClaimBeganSince(fast.Sequence, fast.Start, fast.End))
+ {
+ ClearEntry(entry);
+ fast.Invalidated = true;
+ return false;
+ }
+
+ fast.Entry = entry;
+ fast.Reserved = true;
+ return true;
+ }
+
+ // Enter before tracker/image/backing locks; retain the claim through its publication.
+ public GpuClaim BeginGpuClaim(ulong address, ulong size)
+ {
+ if (size == 0) return default;
+ // Managed writes take leases only once a claimant registered (GuestWriteReservations.Gate.cs).
+ RegisterClaimant();
+ var (start, end) = Pages(address, size);
+ var thread = Environment.CurrentManagedThreadId;
+ RejectFastReservedReentry();
+ lock (_gate)
+ {
+ RejectReservedReentry(thread);
+ // Marked before the sequence: a write that read the sequence before this claim took its number and then found
+ // the chunks unmarked looks the claim up in the history.
+ MarkChunks(start, end);
+ // Counted into the slots before the entries are read: a lock-free write that publishes later sees the count.
+ var walk = new SlotWalk(start, end);
+ while (walk.Next(out var slot))
+ {
+ Interlocked.Increment(ref _slots[slot].Claims);
+ Interlocked.Increment(ref _slots[slot].Epoch);
+ }
+ var sequence = Interlocked.Increment(ref _claimSequence);
+ _history[sequence % HistorySize] = new ClaimRecord(sequence, start, end);
+ try
+ {
+ while (ReservedOverlap(start, end) || FastEntryOverlaps(start, end))
+ {
+ GpuClaimWaitingForTest?.Invoke();
+ WaitForRelease(start, end, thread, cpu: false);
+ }
+ }
+ catch
+ {
+ walk = new SlotWalk(start, end);
+ while (walk.Next(out var slot))
+ {
+ Interlocked.Decrement(ref _slots[slot].Claims);
+ }
+ throw;
+ }
+ var id = unchecked(++_nextClaim);
+ if (id == 0) id = unchecked(++_nextClaim);
+ _gpu.Add(new Claim(id, start, end, thread));
+ for (var index = 0; index < _cpu.Count; index++)
+ {
+ var attempt = _cpu[index];
+ if (!Overlaps(start, end, attempt.Start, attempt.End)) continue;
+ attempt.Invalidated = true;
+ _cpu[index] = attempt;
+ }
+ return new GpuClaim(this, id);
+ }
+ }
+
+ // Waits under the gate for a release. Locked reservations and claims pulse the gate when they are released, and the
+ // timeout bounds the wait should a pulse still be missed. A lock-free write holds its entry for one copy and releases it
+ // without the gate, so a wait on lock-free entries alone spins outside the gate until they clear.
+ private void WaitForRelease(ulong start, ulong end, int thread, bool cpu)
+ {
+ if (ReservedOverlap(start, end) || (cpu && GpuOverlap(start, end, thread)))
+ {
+ Monitor.Wait(_gate, 10);
+ return;
+ }
+
+ Monitor.Exit(_gate);
+ try
+ {
+ var spin = new SpinWait();
+ while (FastEntryOverlaps(start, end))
+ {
+ spin.SpinOnce(sleep1Threshold: -1);
+ }
+ }
+ finally
+ {
+ Monitor.Enter(_gate);
+ }
+ }
+
+ private void RejectFastReservedReentry()
+ {
+ if (t_fast is { Active: true, Reserved: true } fast && fast.Owner == this)
+ throw new InvalidOperationException("A reserved CPU writer cannot enter another premark or GPU claim.");
+ }
+
+ private void RejectReservedReentry(int thread)
+ {
+ foreach (var attempt in _cpu)
+ if (attempt.Reserved && attempt.Thread == thread)
+ throw new InvalidOperationException("A reserved CPU writer cannot enter another premark or GPU claim.");
+ }
+
+ private bool ReservedOverlap(ulong start, ulong end)
+ {
+ foreach (var attempt in _cpu)
+ if (attempt.Reserved && Overlaps(start, end, attempt.Start, attempt.End)) return true;
+ return false;
+ }
+
+ // A GPU owner may perform a managed store inside its own claim, but not another thread's claim.
+ private bool GpuOverlap(ulong start, ulong end, int exceptThread)
+ {
+ foreach (var claim in _gpu)
+ if (claim.Thread != exceptThread && Overlaps(start, end, claim.Start, claim.End)) return true;
+ return false;
+ }
+
+ // A lock-free reservation over the range. An entry replaced while it is read may give a mixed range; its new writer
+ // publishes after the caller's count and so finds that count itself.
+ private bool FastEntryOverlaps(ulong start, ulong end)
+ {
+ var walk = new SlotWalk(start, end);
+ while (walk.Next(out var slot))
+ {
+ if (OtherEntryOverlaps(slot, -1, start, end)) return true;
+ }
+ return false;
+ }
+
+ private bool OtherEntryOverlaps(int slot, int exceptEntry, ulong start, ulong end)
+ {
+ for (var way = 0; way < Ways; way++)
+ {
+ var index = slot * Ways + way;
+ if (index == exceptEntry) continue;
+ var token = Volatile.Read(ref _entryTokens[index]);
+ if (token == 0) continue;
+ if (token == Filling) return true;
+ if (Overlaps(start, end, Volatile.Read(ref _entryStarts[index]), Volatile.Read(ref _entryEnds[index]))) return true;
+ }
+ return false;
+ }
+
+ // Marks the chunks of a claim's range. The claim that marks a chunk first waits until every thread either sees the
+ // mark or shows its record, and then until every recorded write in its chunks has released, over its own pages or
+ // not: a later claim over another page of a marked chunk reads no records. No write that begins afterwards reserves a
+ // marked chunk in its record.
+ private void MarkChunks(ulong start, ulong end)
+ {
+ var first = start >> ChunkShift;
+ var last = (end - 1) >> ChunkShift;
+ var marked = false;
+ for (var word = first >> 6; word <= last >> 6; word++)
+ {
+ var mask = ChunkMask(word, first, last);
+ if ((Volatile.Read(ref _claimedChunks[word]) & mask) == mask) continue;
+ Interlocked.Or(ref _claimedChunks[word], mask);
+ marked = true;
+ }
+
+ if (!marked) return;
+ Interlocked.MemoryBarrierProcessWide();
+ var spin = new SpinWait();
+ while (RecordOverlaps(first << ChunkShift, (last + 1) << ChunkShift))
+ {
+ GpuClaimWaitingForTest?.Invoke();
+ spin.SpinOnce(sleep1Threshold: -1);
+ }
+ }
+
+ private bool ChunksUnmarked(ulong start, ulong end)
+ {
+ var first = start >> ChunkShift;
+ var last = (end - 1) >> ChunkShift;
+ for (var word = first >> 6; word <= last >> 6; word++)
+ {
+ if ((Volatile.Read(ref _claimedChunks[word]) & ChunkMask(word, first, last)) != 0) return false;
+ }
+ return true;
+ }
+
+ private static long ChunkMask(ulong word, ulong first, ulong last)
+ {
+ var low = word == first >> 6 ? (int)(first & 63) : 0;
+ var high = word == last >> 6 ? (int)(last & 63) : 63;
+ var bits = high - low + 1;
+ return bits == 64 ? -1L : (long)(((1UL << bits) - 1) << low);
+ }
+
+ // A recorded write of this owner over the range. A record whose token changes while it is read is skipped: the write
+ // it named has released, and a write that shows its record only now reads the marks afterwards.
+ private bool RecordOverlaps(ulong start, ulong end)
+ {
+ var count = Math.Min(Volatile.Read(ref s_recordsTaken), RecordCount);
+ for (var index = 0; index < count; index++)
+ {
+ ref var record = ref s_records[index];
+ var token = Volatile.Read(ref record.Token);
+ if (token == 0 || record.Owner != this ||
+ !Overlaps(start, end, Volatile.Read(ref record.Start), Volatile.Read(ref record.End))) continue;
+ if (Volatile.Read(ref record.Token) == token) return true;
+ }
+ return false;
+ }
+
+ // Whether a claim over the range began after the attempt read the sequence. When the history does not reach back to
+ // the attempt, the answer is yes.
+ private bool ClaimBeganSince(long sequence, ulong start, ulong end)
+ {
+ lock (_gate)
+ {
+ var current = _claimSequence;
+ if (current - sequence > HistorySize) return true;
+ for (var next = sequence + 1; next <= current; next++)
+ {
+ var record = _history[next % HistorySize];
+ if (record.Sequence != next || Overlaps(start, end, record.Start, record.End)) return true;
+ }
+ return false;
+ }
+ }
+
+ private void AddLockedReserved(ulong start, ulong end, int delta)
+ {
+ var walk = new SlotWalk(start, end);
+ while (walk.Next(out var slot))
+ {
+ Interlocked.Add(ref _slots[slot].LockedReserved, delta);
+ }
+ }
+
+ // Cleared after the copy's stores; a waiter on lock-free entries spins until it reads the entry free.
+ private void ClearEntry(int entry) => Volatile.Write(ref _entryTokens[entry], 0);
+
+ private bool IsReleased(long id)
+ {
+ if (id < 0)
+ {
+ var fast = t_fast;
+ return fast is null || !fast.Active || fast.Owner != this || fast.Token != -id;
+ }
+
+ lock (_gate)
+ {
+ foreach (var attempt in _cpu)
+ if (attempt.Id == id) return false;
+ return true;
+ }
+ }
+
+ private void Release(long id)
+ {
+ if (id < 0)
+ {
+ var fast = t_fast;
+ if (fast is not { Active: true } || fast.Owner != this || fast.Token != -id) return;
+ fast.Active = false;
+ if (fast.Reserved)
+ {
+ fast.Reserved = false;
+ if (fast.InRecord) Volatile.Write(ref s_records[fast.Record].Token, 0);
+ else ClearEntry(fast.Entry);
+ }
+ fast.Entry = -1;
+ fast.InRecord = false;
+ return;
+ }
+
+ lock (_gate)
+ {
+ for (var index = _cpu.Count - 1; index >= 0; index--)
+ {
+ var attempt = _cpu[index];
+ if (attempt.Id != id) continue;
+ _cpu.RemoveAt(index);
+ if (attempt.Reserved)
+ {
+ AddLockedReserved(attempt.Start, attempt.End, -1);
+ t_lockedReserved?.Remove(this);
+ }
+ Monitor.PulseAll(_gate);
+ return;
+ }
+ }
+ }
+
+ private void ReleaseGpu(long id)
+ {
+ lock (_gate)
+ {
+ for (var index = _gpu.Count - 1; index >= 0; index--)
+ {
+ var claim = _gpu[index];
+ if (claim.Id != id) continue;
+ _gpu.RemoveAt(index);
+ var walk = new SlotWalk(claim.Start, claim.End);
+ while (walk.Next(out var slot))
+ {
+ Interlocked.Decrement(ref _slots[slot].Claims);
+ }
+ Monitor.PulseAll(_gate);
+ return;
+ }
+ }
+ }
+
+ private static int SlotOf(ulong region) => (int)((region * 0x9E3779B97F4A7C15UL) >> (64 - SlotBits));
+
+ // The slots of a page range's regions, one per region (two regions may share a slot); a range over more regions than
+ // there are slots visits every slot once.
+ private struct SlotWalk
+ {
+ private ulong _region;
+ private readonly ulong _last;
+ private readonly bool _every;
+ private int _index;
+
+ public SlotWalk(ulong start, ulong end)
+ {
+ _region = start >> RegionShift;
+ _last = (end - 1) >> RegionShift;
+ _every = _last - _region >= SlotCount;
+ _index = 0;
+ }
+
+ public bool Next(out int slot)
+ {
+ if (_every)
+ {
+ slot = _index;
+ return _index++ < SlotCount;
+ }
+
+ if (_region > _last)
+ {
+ slot = 0;
+ return false;
+ }
+
+ slot = SlotOf(_region++);
+ return true;
+ }
+ }
+
+ private static bool Overlaps(ulong aStart, ulong aEnd, ulong bStart, ulong bEnd) =>
+ aStart < bEnd && bStart < aEnd;
+
+ private static (ulong Start, ulong End) Pages(ulong address, ulong size)
+ {
+ if (address == 0 || size == 0 || address >= TrackerLayout.SpaceBytes ||
+ size > TrackerLayout.SpaceBytes - address)
+ throw new ArgumentOutOfRangeException(nameof(address), "The reservation must fit the guest GPU address space.");
+ return (address & ~(TrackerLayout.PageBytes - 1),
+ (address + size + TrackerLayout.PageBytes - 1) & ~(TrackerLayout.PageBytes - 1));
+ }
+}
diff --git a/src/SharpEmu.HLE/GpuMemory/PageGuard.cs b/src/SharpEmu.HLE/GpuMemory/PageGuard.cs
index fac9d0ea8..2ab6cbbbb 100644
--- a/src/SharpEmu.HLE/GpuMemory/PageGuard.cs
+++ b/src/SharpEmu.HLE/GpuMemory/PageGuard.cs
@@ -183,6 +183,8 @@ public bool HasActiveWatches()
return false;
}
+ public GuestWriteReservations ManagedWrites { get; } = new();
+
public void Dispose()
{
foreach (var block in _blocks)
diff --git a/src/SharpEmu.HLE/GpuMemory/PartiallyResidentRanges.cs b/src/SharpEmu.HLE/GpuMemory/PartiallyResidentRanges.cs
new file mode 100644
index 000000000..508f0e426
--- /dev/null
+++ b/src/SharpEmu.HLE/GpuMemory/PartiallyResidentRanges.cs
@@ -0,0 +1,143 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+namespace SharpEmu.HLE.GpuMemory;
+
+///
+/// Guest ranges a GPU read may find partly mapped, whose unmapped pages read as zero: the kernel's PRT apertures
+/// (sceKernelSetPrtAperture) and the AMM area (Ampr). The kernel answers that question itself in the process that runs it
+/// (KernelRuntimeCompatExports.ContainsPrtRange); the GPU process of the two-process split has no kernel, so the guest
+/// process publishes each change here and the split mirrors it there (SplitGpuSession, SplitGpuHost).
+///
+///
+/// Published (the guest process): the kernel's last value per range, and an observer the split attaches.
+/// Attaching replays the current values through the observer under the same lock every later change takes, so the GPU
+/// process never receives an older value after a newer one.
+///
+/// Mirrored (the GPU process): what the split received. Read lock-free by image reads
+/// (ResidentImageBacking); empty in a process with a kernel, so there it changes nothing.
+///
+/// Only the extent of each range crosses. Which pages inside it are mapped is the shared view table's, which the
+/// GPU process reads live; a range here only lets an unmapped page read as zero, it never makes a read of a page the
+/// guest unmapped possible.
+///
+public static class PartiallyResidentRanges
+{
+ /// The id of the AMM area; PRT apertures use their aperture id.
+ public const int AmmArea = 0x100;
+
+ /// One range: 0 removes the range with that id.
+ /// The kernel also registered it as a lazily backed range of the GPU memory manager
+ /// (GuestGpuMemoryHook.NoteLazyRange), which the GPU process's manager has to know as well.
+ public readonly record struct Range(int Id, ulong Address, ulong Size, bool LazilyBacked);
+
+ private static readonly object _gate = new();
+ // Its own lock: the observer holds _gate while the GPU process mirrors the change, which in a test runs in this process.
+ private static readonly object _mirrorGate = new();
+ private static readonly Dictionary _published = [];
+ private static readonly Dictionary _mirroredById = [];
+ private static Action? _observer;
+ private static Range[] _mirrored = [];
+
+ /// The guest process: the kernel set, moved or (size 0) dropped a range.
+ public static void Publish(int id, ulong address, ulong size, bool lazilyBacked)
+ {
+ var range = new Range(id, address, size, lazilyBacked);
+ lock (_gate)
+ {
+ if (size == 0)
+ {
+ _ = _published.Remove(id);
+ }
+ else
+ {
+ _published[id] = range;
+ }
+
+ // Under the lock: the observer sees the changes in the order the table took them.
+ _observer?.Invoke(range);
+ }
+ }
+
+ ///
+ /// The guest process: sends every change to from now on, starting with the current
+ /// value of every range. Null detaches.
+ ///
+ public static void Attach(Action? observer)
+ {
+ lock (_gate)
+ {
+ _observer = observer;
+ if (observer is null)
+ {
+ return;
+ }
+
+ foreach (var range in _published.Values.OrderBy(static range => range.Id))
+ {
+ observer(range);
+ }
+ }
+ }
+
+ /// The guest process: the ranges as the kernel last published them.
+ public static Range[] SnapshotPublished()
+ {
+ lock (_gate)
+ {
+ return [.. _published.Values.OrderBy(static range => range.Id)];
+ }
+ }
+
+ /// The GPU process: a change the guest process published. Returns the value it replaces (size 0: none).
+ public static Range Mirror(Range range)
+ {
+ lock (_mirrorGate)
+ {
+ _ = _mirroredById.Remove(range.Id, out var previous);
+ if (range.Size != 0)
+ {
+ _mirroredById[range.Id] = range;
+ }
+
+ Volatile.Write(ref _mirrored, [.. _mirroredById.Values]);
+ return previous;
+ }
+ }
+
+ /// The ranges this process mirrors (none in a process with a kernel).
+ public static Range[] Mirrored => Volatile.Read(ref _mirrored);
+
+ ///
+ /// The GPU process: whether one mirrored range holds all of [address, address + size), as
+ /// KernelRuntimeCompatExports.ContainsPrtRange answers for an address the caller has translated.
+ ///
+ public static bool MirrorContains(ulong address, ulong size)
+ {
+ var ranges = Volatile.Read(ref _mirrored);
+ if (ranges.Length == 0 || size == 0 || address > ulong.MaxValue - size)
+ {
+ return false;
+ }
+
+ foreach (var range in ranges)
+ {
+ if (address >= range.Address && size <= range.Size && address - range.Address <= range.Size - size)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /// Tests: forgets the mirrored ranges (a process with a kernel never has any).
+ public static void ResetMirror()
+ {
+ lock (_mirrorGate)
+ {
+ _mirroredById.Clear();
+ Volatile.Write(ref _mirrored, []);
+ }
+ }
+}
diff --git a/src/SharpEmu.HLE/GpuMemory/SpanSet.cs b/src/SharpEmu.HLE/GpuMemory/SpanSet.cs
index faed6ff1f..031210a1f 100644
--- a/src/SharpEmu.HLE/GpuMemory/SpanSet.cs
+++ b/src/SharpEmu.HLE/GpuMemory/SpanSet.cs
@@ -7,7 +7,39 @@ public sealed class SpanSnapshot(ulong[] starts, ulong[] ends)
{
public static readonly SpanSnapshot Empty = new([], []);
- public bool Contains(ulong address, ulong size)
+ internal ReadOnlySpan Starts => starts;
+ internal ReadOnlySpan Ends => ends;
+ // Contains remembers, per thread, the span of its last complete hit in a snapshot; SHARPEMU_SPAN_CONTAINS_CACHE=0
+ // searches every query.
+ private static readonly bool CacheLastHit = Environment.GetEnvironmentVariable("SHARPEMU_SPAN_CONTAINS_CACHE") != "0";
+
+ [ThreadStatic] private static SpanSnapshot? _lastSnapshot;
+ [ThreadStatic] private static int _lastIndex;
+
+ public bool Contains(ulong address, ulong size) => CacheLastHit
+ ? ContainsWithLastHit(address, size)
+ : ContainsUncached(address, size);
+
+ internal bool ContainsWithLastHit(ulong address, ulong size)
+ {
+ // Snapshot identity includes mapping changes. Only a complete positive range can hit; a zero-sized or
+ // overflowing request gives the answer ContainsUncached gives.
+ if (ReferenceEquals(_lastSnapshot, this) && size != 0 &&
+ address >= starts[_lastIndex] && address < ends[_lastIndex] && size <= ends[_lastIndex] - address)
+ return true;
+
+ var index = Array.BinarySearch(starts, address);
+ if (index < 0) index = ~index - 1;
+ var contained = index >= 0 && ends[index] >= address + size;
+ if (contained && size != 0 && address < ends[index] && size <= ends[index] - address)
+ {
+ _lastIndex = index;
+ _lastSnapshot = this;
+ }
+ return contained;
+ }
+
+ private bool ContainsUncached(ulong address, ulong size)
{
var index = Array.BinarySearch(starts, address);
if (index < 0)
@@ -18,6 +50,34 @@ public bool Contains(ulong address, ulong size)
return index >= 0 && ends[index] >= address + size;
}
+ // Immutable snapshot: callbacks may recover GPU data without holding the mapping lock.
+ internal void ForEachOverlap(ulong address, ulong size, Action visit)
+ {
+ var end = address + size;
+ var index = Array.BinarySearch(starts, address);
+ if (index < 0) index = Math.Max(0, ~index - 1);
+ for (; index < starts.Length && starts[index] < end; index++)
+ {
+ var first = Math.Max(address, starts[index]);
+ var last = Math.Min(end, ends[index]);
+ if (first < last) visit(first, last - first);
+ }
+ }
+
+ // The walk above with its state passed to a static callback; the same overlaps, in the same order.
+ internal void ForEachOverlap(ulong address, ulong size, TState state, Action visit)
+ {
+ var end = address + size;
+ var index = Array.BinarySearch(starts, address);
+ if (index < 0) index = Math.Max(0, ~index - 1);
+ for (; index < starts.Length && starts[index] < end; index++)
+ {
+ var first = Math.Max(address, starts[index]);
+ var last = Math.Min(end, ends[index]);
+ if (first < last) visit(state, first, last - first);
+ }
+ }
+
public bool TryGetContaining(ulong address, out ulong start, out ulong end)
{
var index = Array.BinarySearch(starts, address);
diff --git a/src/SharpEmu.HLE/HostCallTrims.cs b/src/SharpEmu.HLE/HostCallTrims.cs
new file mode 100644
index 000000000..6fb0ea2a7
--- /dev/null
+++ b/src/SharpEmu.HLE/HostCallTrims.cs
@@ -0,0 +1,28 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+namespace SharpEmu.HLE;
+
+// Exact trims on the guest threads' host calls, each read at startup and on unless its variable is 0.
+// - SHARPEMU_MARK_CLOSURE_FREE: a managed write that is not inside one GPU span walks its overlaps with its state passed
+// by value, without allocating a closure for each mark.
+// - SHARPEMU_MIXED_COPY_DIRECT: a guest copy between the backing and private memory that needs no commit or protection
+// change copies in one call under the read lock instead of through 64 KiB staging pieces.
+public static class HostCallTrims
+{
+ private static readonly bool MarkClosureFreeConfigured =
+ Environment.GetEnvironmentVariable("SHARPEMU_MARK_CLOSURE_FREE") != "0";
+
+ private static readonly bool MixedCopyConfigured =
+ Environment.GetEnvironmentVariable("SHARPEMU_MIXED_COPY_DIRECT") != "0";
+
+ // Tests: override the switches on this thread.
+ [ThreadStatic]
+ internal static bool? MarkClosureFreeOverrideForTests;
+ [ThreadStatic]
+ internal static bool? MixedCopyOverrideForTests;
+
+ public static bool MarkClosureFree => MarkClosureFreeOverrideForTests ?? MarkClosureFreeConfigured;
+
+ public static bool MixedCopyDirect => MixedCopyOverrideForTests ?? MixedCopyConfigured;
+}
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs
index 95dfed3ff..0591ce78e 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs
@@ -244,6 +244,23 @@ public static int AcbAcquireMemGetSize(CpuContext ctx)
return (int)ctx[CpuRegister.Rax];
}
+ // Matches the packet AcbWaitRegMem writes: 7 dwords for a 32-bit label, 9 for a 64-bit one.
+ [SysAbiExport(
+ Nid = "idlaArvdXEs",
+ ExportName = "sceAgcAcbWaitOnAddressGetSize",
+ Target = Generation.Gen5,
+ LibraryName = "libSceAgc")]
+ public static int AcbWaitOnAddressGetSize(CpuContext ctx)
+ {
+ ctx[CpuRegister.Rax] = (uint)ctx[CpuRegister.Rdi] switch
+ {
+ 0 => 7u * sizeof(uint),
+ 1 => 9u * sizeof(uint),
+ _ => 0,
+ };
+ return (int)ctx[CpuRegister.Rax];
+ }
+
[SysAbiExport(
Nid = "htn36gPnBk4",
ExportName = "sceAgcAcbWaitRegMem",
@@ -332,12 +349,26 @@ public static int CbReleaseMem(CpuContext ctx)
var cachePolicy = (uint)(ctx[CpuRegister.R8] & 0xFF);
var destinationAddress = ctx[CpuRegister.R9];
var stackAddress = ctx[CpuRegister.Rsp];
- if (!TryReadUInt64(ctx, stackAddress + 8, out var dataSelectionRaw) ||
- !TryReadUInt64(ctx, stackAddress + 16, out var data) ||
- !TryReadUInt64(ctx, stackAddress + 24, out var gdsOffsetRaw) ||
- !TryReadUInt64(ctx, stackAddress + 32, out var gdsSizeRaw) ||
- !TryReadUInt64(ctx, stackAddress + 40, out var interruptRaw) ||
- !TryReadUInt64(ctx, stackAddress + 48, out var interruptContextIdRaw))
+ ulong dataSelectionRaw, data, gdsOffsetRaw, gdsSizeRaw, interruptRaw, interruptContextIdRaw;
+ // AgcPacketWrites: the six stack words (Rsp + 8 to Rsp + 48) in one read of the same bytes; when it fails, the
+ // six reads below.
+ Span stackWords = stackalloc byte[6 * sizeof(ulong)];
+ if (AgcPacketWrites.Active && stackAddress <= ulong.MaxValue - 7 * sizeof(ulong) &&
+ ctx.Memory.TryRead(stackAddress + 8, stackWords))
+ {
+ dataSelectionRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords);
+ data = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[8..]);
+ gdsOffsetRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[16..]);
+ gdsSizeRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[24..]);
+ interruptRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[32..]);
+ interruptContextIdRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[40..]);
+ }
+ else if (!TryReadUInt64(ctx, stackAddress + 8, out dataSelectionRaw) ||
+ !TryReadUInt64(ctx, stackAddress + 16, out data) ||
+ !TryReadUInt64(ctx, stackAddress + 24, out gdsOffsetRaw) ||
+ !TryReadUInt64(ctx, stackAddress + 32, out gdsSizeRaw) ||
+ !TryReadUInt64(ctx, stackAddress + 40, out interruptRaw) ||
+ !TryReadUInt64(ctx, stackAddress + 48, out interruptContextIdRaw))
{
return ReturnPointer(ctx, 0);
}
@@ -656,20 +687,32 @@ public static int DcbWaitRegMem(CpuContext ctx)
var packetDwords = size == 0 ? 7u : 9u;
var packetRegister = size == 0 ? RWaitMem32 : RWaitMem64;
- var header = Pm4(packetDwords, ItNop, packetRegister);
- var addressLow = (uint)address & (size == 0 ? ~0x3u : ~0x7u);
- var addressHigh = (uint)(address >> 32) & 0x3FFFFu;
- // One write for the whole packet: each guest write is checked against the GPU caches.
- var emitted = size == 0
- ? TryEmitCommandDwords(
- ctx, commandBufferAddress, out var commandAddress,
- header, addressLow, addressHigh, (uint)mask, (uint)reference,
- EncodeWaitRegMem32Control(compareFunction, operation, cachePolicy), EncodeWaitRegMemPoll(pollCycles))
- : TryEmitCommandDwords(
- ctx, commandBufferAddress, out commandAddress,
- header, addressLow, addressHigh, (uint)mask, (uint)(mask >> 32), (uint)reference, (uint)(reference >> 32),
- EncodeWaitRegMem64Control(compareFunction, operation, cachePolicy), EncodeWaitRegMemPoll(pollCycles));
- if (!emitted)
+ // One write for the whole packet and the NOP that pads it to the native size
+ // sceAgcDcbWaitOnAddressGetSize reports: each guest write is checked against the GPU caches.
+ Span dwords = stackalloc uint[(int)(9u + WaitOnAddressPadDwords)];
+ dwords = dwords[..(int)(packetDwords + WaitOnAddressPadDwords)];
+ dwords.Clear();
+ dwords[0] = Pm4(packetDwords, ItNop, packetRegister);
+ dwords[1] = (uint)address & (size == 0 ? ~0x3u : ~0x7u);
+ dwords[2] = (uint)(address >> 32) & 0x3FFFFu;
+ dwords[3] = (uint)mask;
+ if (size == 0)
+ {
+ dwords[4] = (uint)reference;
+ dwords[5] = EncodeWaitRegMem32Control(compareFunction, operation, cachePolicy);
+ dwords[6] = EncodeWaitRegMemPoll(pollCycles);
+ }
+ else
+ {
+ dwords[4] = (uint)(mask >> 32);
+ dwords[5] = (uint)reference;
+ dwords[6] = (uint)(reference >> 32);
+ dwords[7] = EncodeWaitRegMem64Control(compareFunction, operation, cachePolicy);
+ dwords[8] = EncodeWaitRegMemPoll(pollCycles);
+ }
+
+ dwords[(int)packetDwords] = Pm4(WaitOnAddressPadDwords, ItNop, RZero);
+ if (!TryEmitCommandDwords(ctx, commandBufferAddress, out var commandAddress, dwords))
{
return ReturnPointer(ctx, 0);
}
@@ -683,6 +726,10 @@ public static int DcbWaitRegMem(CpuContext ctx)
return ReturnPointer(ctx, commandAddress);
}
+ // A DCB wait takes the native size sceAgcDcbWaitOnAddressGetSize reports: the wait packet, then a NOP over the rest.
+ // Titles size buffers with that export and fill them with waits (UE's submission prologue), so the two must agree.
+ private const uint WaitOnAddressPadDwords = 7;
+
[SysAbiExport(
Nid = "43WJ08sSugE",
ExportName = "sceAgcDcbWaitOnAddressGetSize",
@@ -693,8 +740,8 @@ public static int GetWaitOnAddressSize(CpuContext context)
var labelSize = (uint)context[CpuRegister.Rdi];
context[CpuRegister.Rax] = labelSize switch
{
- 0 => 14u * sizeof(uint),
- 1 => 16u * sizeof(uint),
+ 0 => (7u + WaitOnAddressPadDwords) * sizeof(uint),
+ 1 => (9u + WaitOnAddressPadDwords) * sizeof(uint),
_ => 0,
};
return (int)context[CpuRegister.Rax];
@@ -791,15 +838,21 @@ public static int DcbPushMarker(CpuContext ctx)
{
var commandBufferAddress = ctx[CpuRegister.Rdi];
var markerAddress = ctx[CpuRegister.Rsi];
+ var atOnce = AgcPacketWrites.Active;
+ byte[] marker;
if (commandBufferAddress == 0 ||
- !TryReadGuestCString(ctx, markerAddress, 4095, out var marker))
+ !(atOnce
+ ? TryReadGuestCStringInChunks(ctx, markerAddress, 4095, out marker)
+ : TryReadGuestCString(ctx, markerAddress, 4095, out marker)))
{
return ReturnPointer(ctx, 0);
}
var payloadDwords = Math.Max(((uint)marker.Length + 4) / 4, 1);
var packetDwords = payloadDwords + 1;
- if (!TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords, out var commandAddress) ||
+ // A marker from a thread other than the buffer's writer is skipped (null pointer): it must not reserve space inside
+ // that writer's unpublished inline packet.
+ if (!TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords, out var commandAddress, isMarker: true) ||
!TryWriteUInt32(ctx, commandAddress, Pm4(packetDwords, ItNop, RPushMarker)))
{
return ReturnPointer(ctx, 0);
@@ -849,7 +902,8 @@ public static int DcbPopMarker(CpuContext ctx)
{
var commandBufferAddress = ctx[CpuRegister.Rdi];
if (commandBufferAddress == 0 ||
- !TryEmitCommandDwords(ctx, commandBufferAddress, out var commandAddress, Pm4(2, ItNop, RPopMarker), 0))
+ !TryAllocateCommandDwords(ctx, commandBufferAddress, 2, out var commandAddress, isMarker: true) ||
+ !TryWriteCommandDwords(ctx, commandAddress, Pm4(2, ItNop, RPopMarker), 0))
{
return ReturnPointer(ctx, 0);
}
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs b/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs
index 3c89fabe2..476a93474 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs
@@ -283,6 +283,8 @@ public static int AcbJumpGetSize(CpuContext ctx)
LibraryName = "libSceAgc")]
public static int AcbJump(CpuContext ctx)
{
+ // (acb, cachePolicy, target, sizeDwords): an ACB jump always chains, so unlike
+ // sceAgcDcbJump it takes no mode argument.
var acb = ctx[CpuRegister.Rdi];
var cachePolicy = (uint)ctx[CpuRegister.Rsi];
var target = ctx[CpuRegister.Rdx];
@@ -294,7 +296,7 @@ public static int AcbJump(CpuContext ctx)
const uint chainMode = 1;
var control = 0x0F20_0000u |
- (cachePolicy << 28) |
+ ((cachePolicy & 0x3u) << 28) |
(chainMode << 20) |
(sizeDwords & 0xFFFFFu);
if (!TryAllocateCommandDwords(ctx, acb, 4, out var cmd) ||
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.DmaPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.DmaPackets.cs
index 90327ec55..5c04fe540 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.DmaPackets.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.DmaPackets.cs
@@ -15,7 +15,12 @@ public static partial class AgcExports
ExportName = "sceAgcDcbCopyData",
Target = Generation.Gen5,
LibraryName = "libSceAgc")]
- public static int DcbCopyData(CpuContext ctx)
+ public static int DcbCopyData(CpuContext ctx) =>
+ CopyData(ctx, rawSelectors: false);
+
+ // The DCB selectors carry the CP engine in bit 0 above the hardware selector; the ACB selectors are the MEC's
+ // raw hardware values, with no engine.
+ private static int CopyData(CpuContext ctx, bool rawSelectors)
{
var commandBufferAddress = ctx[CpuRegister.Rdi];
var destinationSelector = (uint)(ctx[CpuRegister.Rsi] & 0xFF);
@@ -36,14 +41,15 @@ public static int DcbCopyData(CpuContext ctx)
var elementSize = (uint)(elementSizeRaw & 0xFF);
var confirmWrite = (uint)(confirmWriteRaw & 0xFF);
+ var selectors = rawSelectors
+ ? (sourceSelector & 0xFu) | ((destinationSelector & 0xFu) << 8)
+ : ((sourceSelector >> 1) & 0xFu) | (((destinationSelector >> 1) & 0xFu) << 8) | ((sourceSelector & 0x1u) << 30);
var control =
- ((sourceSelector >> 1) & 0xFu) |
- (((destinationSelector >> 1) & 0xFu) << 8) |
+ selectors |
((sourcePolicy & 0x3u) << 13) |
((elementSize & 0x1u) << 16) |
((confirmWrite & 0x1u) << 20) |
- ((destinationPolicy & 0x3u) << 25) |
- ((sourceSelector & 0x1u) << 30);
+ ((destinationPolicy & 0x3u) << 25);
if (!TryWriteUInt32(ctx, packetAddress, Pm4(6, ItCopyData, 0)) ||
!TryWriteUInt32(ctx, packetAddress + 4, control) ||
@@ -56,10 +62,36 @@ public static int DcbCopyData(CpuContext ctx)
}
TraceAgc(
- $"agc.dcb_copy_data buf=0x{commandBufferAddress:X16} cmd=0x{packetAddress:X16} dstSel=0x{destinationSelector:X2} srcSel=0x{sourceSelector:X2} dst=0x{destinationAddress:X16} src=0x{sourceValue:X16} control=0x{control:X8}");
+ $"agc.{(rawSelectors ? "acb" : "dcb")}_copy_data buf=0x{commandBufferAddress:X16} cmd=0x{packetAddress:X16} dstSel=0x{destinationSelector:X2} srcSel=0x{sourceSelector:X2} dst=0x{destinationAddress:X16} src=0x{sourceValue:X16} control=0x{control:X8}");
return ReturnPointer(ctx, packetAddress);
}
+ // Matches the fixed 6-dword COPY_DATA packet DcbCopyData and AcbCopyData write.
+ [SysAbiExport(
+ Nid = "b5u0Jzm8TF8",
+ ExportName = "sceAgcDcbCopyDataGetSize",
+ Target = Generation.Gen5,
+ LibraryName = "libSceAgc")]
+ [SysAbiExport(
+ Nid = "CbQh3DKMSno",
+ ExportName = "sceAgcAcbCopyDataGetSize",
+ Target = Generation.Gen5,
+ LibraryName = "libSceAgc")]
+ public static int CopyDataGetSize(CpuContext ctx)
+ {
+ ctx[CpuRegister.Rax] = 6u * sizeof(uint);
+ return (int)ctx[CpuRegister.Rax];
+ }
+
+ // The ACB form takes the same arguments; its selectors are the raw MEC values.
+ [SysAbiExport(
+ Nid = "qzMN2XKGA4k",
+ ExportName = "sceAgcAcbCopyData",
+ Target = Generation.Gen5,
+ LibraryName = "libSceAgc")]
+ public static int AcbCopyData(CpuContext ctx) =>
+ CopyData(ctx, rawSelectors: true);
+
[SysAbiExport(
Nid = "WmAc2MEj6Io",
ExportName = "sceAgcDcbDmaData",
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs
index bef4d6ab4..a65d9c0b9 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs
@@ -169,25 +169,33 @@ public static int DcbDrawIndex(CpuContext ctx)
// the submitted-command parser and the complete scene was discarded.
// With the room for all of them, the index base, buffer size and draw are one allocation and
// one write; otherwise each packet is allocated on its own, as the buffer's callback expects.
- ulong baseCommand, drawCommand;
- if (TryReserveCommandDwordsInPlace(ctx, commandBufferAddress, 11, out baseCommand, out var nextCursor))
+ ulong baseCommand = 0, drawCommand = 0;
+ bool reserved;
+ using (new CommandBufferAppendScope(ctx, commandBufferAddress))
{
- drawCommand = baseCommand + 5 * sizeof(uint);
- if (!TryCommitCommandDwords(ctx, commandBufferAddress, nextCursor, baseCommand,
- [Pm4(3, ItIndexBase, 0), (uint)indexAddress, (uint)(indexAddress >> 32), Pm4(2, ItIndexBufferSize, 0), indexCount,
- Pm4(6, ItDrawIndex2, 0), indexCount, (uint)indexAddress, (uint)(indexAddress >> 32), indexCount, drawInitiator]))
+ reserved = TryReserveCommandDwordsInPlace(ctx, commandBufferAddress, 11, out baseCommand, out var nextCursor);
+ if (reserved)
{
- return ReturnPointer(ctx, 0);
+ drawCommand = baseCommand + 5 * sizeof(uint);
+ if (!TryCommitCommandDwords(ctx, commandBufferAddress, nextCursor, baseCommand,
+ [Pm4(3, ItIndexBase, 0), (uint)indexAddress, (uint)(indexAddress >> 32), Pm4(2, ItIndexBufferSize, 0), indexCount,
+ Pm4(6, ItDrawIndex2, 0), indexCount, (uint)indexAddress, (uint)(indexAddress >> 32), indexCount, drawInitiator]))
+ {
+ return ReturnPointer(ctx, 0);
+ }
}
}
- else if (TryDeclineLeaf(ctx))
+
+ // Without the room (and outside the scope: the full callback must run without the lock) the two
+ // packets would be allocated one at a time, the second after the first was written, so a leaf
+ // backs out before either.
+ if (!reserved && TryDeclineLeaf(ctx))
{
- // The two packets would be allocated one at a time, the second after the first was
- // written, so a leaf backs out before either.
return ReturnPointer(ctx, 0);
}
- else if (!TryEmitCommandDwords(ctx, commandBufferAddress, out baseCommand, Pm4(3, ItIndexBase, 0), (uint)indexAddress, (uint)(indexAddress >> 32), Pm4(2, ItIndexBufferSize, 0), indexCount) ||
- !TryEmitCommandDwords(ctx, commandBufferAddress, out drawCommand, Pm4(6, ItDrawIndex2, 0), indexCount, (uint)indexAddress, (uint)(indexAddress >> 32), indexCount, drawInitiator))
+
+ if (!reserved && (!TryEmitCommandDwords(ctx, commandBufferAddress, out baseCommand, Pm4(3, ItIndexBase, 0), (uint)indexAddress, (uint)(indexAddress >> 32), Pm4(2, ItIndexBufferSize, 0), indexCount) ||
+ !TryEmitCommandDwords(ctx, commandBufferAddress, out drawCommand, Pm4(6, ItDrawIndex2, 0), indexCount, (uint)indexAddress, (uint)(indexAddress >> 32), indexCount, drawInitiator)))
{
return ReturnPointer(ctx, 0);
}
@@ -297,7 +305,37 @@ public static int DcbDrawIndexIndirect(CpuContext ctx)
ExportName = "sceAgcDcbDrawIndexIndirectMulti",
Target = Generation.Gen5,
LibraryName = "libSceAgc")]
- public static int DcbDrawIndexIndirectMulti(CpuContext ctx)
+ public static int DcbDrawIndexIndirectMulti(CpuContext ctx) =>
+ EmitDrawIndirectMulti(ctx, ItDrawIndexIndirectMulti, "agc.dcb_draw_index_indirect_multi");
+
+ [SysAbiExport(
+ Nid = "kUlvghKs-mA",
+ ExportName = "sceAgcDcbDrawIndirectMulti",
+ Target = Generation.Gen5,
+ LibraryName = "libSceAgc")]
+ public static int DcbDrawIndirectMulti(CpuContext ctx) =>
+ EmitDrawIndirectMulti(ctx, ItDrawIndirectMulti, "agc.dcb_draw_indirect_multi");
+
+ private const uint DrawModifierStartVertex = 1u << 0;
+ private const uint DrawModifierStartInstance = 1u << 2;
+ private const uint DrawModifierDrawIndex = 1u << 3;
+ private const uint DrawModifierUserVgprs = 1u << 4;
+
+ // The shader register of a user-data slot the modifier enables, as sce::Agc::get{VertexOffset,InstanceOffset,
+ // DrawIndex}UserDataSlot read it: five bits at slotShift, no slot when the modifier passes the values in VGPRs.
+ // Bits 29-31 name the frontmost stage; the hull stages' user data starts at 0x10C, the others' at 0x8C.
+ private static uint DrawModifierRegister(uint modifierBits, uint enable, int slotShift)
+ {
+ if ((modifierBits & (enable | DrawModifierUserVgprs)) != enable)
+ return 0x280u;
+
+ var userData0 = (modifierBits >> 29) is 3 or 5 ? 0x10Cu : 0x8Cu;
+ return userData0 + ((modifierBits >> slotShift) & 0x1Fu);
+ }
+
+ // Both multi draws take the same arguments and write the same ten-dword packet; the register the modifier names
+ // holds the base vertex of an indexed draw and the start vertex of the other.
+ private static int EmitDrawIndirectMulti(CpuContext ctx, uint opcode, string trace)
{
var commandBufferAddress = ctx[CpuRegister.Rdi];
var dataOffset = (uint)ctx[CpuRegister.Rsi];
@@ -309,12 +347,18 @@ public static int DcbDrawIndexIndirectMulti(CpuContext ctx)
!TryReadUInt64(ctx, ctx[CpuRegister.Rsp] + sizeof(ulong), out var modifier))
return ReturnPointer(ctx, 0);
- var registerLocations = IndexIndirectRegisterLocations(modifier);
- var drawInitiator = IndirectDrawInitiator(modifier);
+ var modifierBits = (uint)modifier;
+ var registerLocations = DrawModifierRegister(modifierBits, DrawModifierStartVertex, 9) |
+ ((ulong)DrawModifierRegister(modifierBits, DrawModifierStartInstance, 19) << 32);
+ var drawIndexRegister = DrawModifierRegister(modifierBits, DrawModifierDrawIndex, 24);
+ if (drawIndexRegister != 0x280u)
+ registerLocations |= ((ulong)drawIndexRegister << 16) | (1UL << 59);
+ var drawInitiator = (modifier & (1UL << 32)) != 0
+ ? 2u : ((modifierBits >> 3) & 0x20u) | 2u;
if (commandBufferAddress == 0 ||
!TryAllocateCommandDwords(ctx, commandBufferAddress, 10, out var commandAddress) ||
- !TryWriteUInt32(ctx, commandAddress, Pm4(10, ItDrawIndexIndirectMulti, 0)) ||
+ !TryWriteUInt32(ctx, commandAddress, Pm4(10, opcode, 0)) ||
!TryWriteUInt32(ctx, commandAddress + 4, dataOffset) ||
!ctx.TryWriteUInt64(commandAddress + 8, registerLocations) ||
!TryWriteUInt32(ctx, commandAddress + 16, countFromMemory << 30) ||
@@ -327,7 +371,7 @@ public static int DcbDrawIndexIndirectMulti(CpuContext ctx)
}
TraceAgc(
- $"agc.dcb_draw_index_indirect_multi buf=0x{commandBufferAddress:X16} cmd=0x{commandAddress:X16} offset=0x{dataOffset:X8} draws={drawCount} stride={stride} modifier=0x{modifier:X8}");
+ $"{trace} buf=0x{commandBufferAddress:X16} cmd=0x{commandAddress:X16} offset=0x{dataOffset:X8} draws={drawCount} stride={stride} modifier=0x{modifier:X8}");
return ReturnPointer(ctx, commandAddress);
}
@@ -425,33 +469,23 @@ public static int DriverUnknownKRzWekV120(CpuContext ctx)
#pragma warning restore SHEM006
///
- /// The user-SGPR locations an indexed indirect draw's modifier selects, as the packet's two
- /// location dwords (low dword first). Low 32 bits of the modifier only: bit 0 selects the
- /// base-vertex register (field 9..13, else 0x280), bit 1 the draw-index register (field 14..18,
- /// in bits 16..31) and the bit-59 flag, bit 2 the first-instance register (field 19..23, else
- /// 0x280), each relative to 0x10C for stages 3 and 5 (bits 29..31) and to 0x8C otherwise. The
- /// native stubs encode the same slots (AgcPacketStubWordKind.ModifierSgprSlots).
+ /// The user-SGPR locations a single indirect draw's modifier selects, as the packet's two
+ /// location dwords (low dword first): the start-vertex (base-vertex) register from bit 0 and
+ /// field 9..13, and the start-instance register from bit 2 and field 19..23, each 0x280 when
+ /// its bit is clear or the modifier passes the values in VGPRs (bit 4); see DrawModifierRegister.
+ /// Only the multi draws have the CP write a draw index, so a single draw names no draw-index
+ /// register. The native stubs encode the same slots (AgcPacketStubWordKind.ModifierSgprSlots).
///
public static ulong IndexIndirectRegisterLocations(ulong modifier)
{
var modifierBits = (uint)modifier;
- var scalarRegisterBase = (modifierBits >> 29) is 3 or 5 ? 0x10Cu : 0x8Cu;
- ulong registerLocations = (modifierBits & 1u) != 0
- ? scalarRegisterBase + ((modifierBits >> 9) & 0x1Fu) : 0x280u;
- var firstInstanceRegister = (modifierBits & 4u) != 0
- ? scalarRegisterBase + ((modifierBits >> 19) & 0x1Fu) : 0x280u;
- registerLocations |= (ulong)firstInstanceRegister << 32;
- if ((modifierBits & 2u) != 0)
- {
- registerLocations |= ((ulong)(scalarRegisterBase + ((modifierBits >> 14) & 0x1Fu)) << 16) | (1UL << 59);
- }
-
- return registerLocations;
+ return DrawModifierRegister(modifierBits, DrawModifierStartVertex, 9) |
+ ((ulong)DrawModifierRegister(modifierBits, DrawModifierStartInstance, 19) << 32);
}
- /// The first-vertex and first-instance locations of a non-indexed indirect draw (no draw-index slot).
+ /// The first-vertex and first-instance locations of a non-indexed indirect draw (the same slots).
public static ulong DrawIndirectRegisterLocations(ulong modifier) =>
- IndexIndirectRegisterLocations(modifier & ~2UL);
+ IndexIndirectRegisterLocations(modifier);
/// An indirect draw's initiator: 2, plus bit 5 from modifier bit 8 unless bit 32 is set.
public static uint IndirectDrawInitiator(ulong modifier) =>
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.Events.cs b/src/SharpEmu.Libs/Agc/AgcExports.Events.cs
index 95892d46b..1edd84b06 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.Events.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.Events.cs
@@ -86,6 +86,23 @@ public static int DcbEventWrite(CpuContext ctx)
return ReturnPointer(ctx, commandAddress);
}
+ // Matches the packet DcbEventWrite writes: 4 dwords for the two event types that carry an address, 2 for the rest.
+ [SysAbiExport(
+ Nid = "C4l9fB17t8w",
+ ExportName = "sceAgcDcbEventWriteGetSize",
+ Target = Generation.Gen5,
+ LibraryName = "libSceAgc")]
+ public static int DcbEventWriteGetSize(CpuContext ctx)
+ {
+ ctx[CpuRegister.Rax] = (uint)(ctx[CpuRegister.Rdi] & 0xFF) switch
+ {
+ 0x38 or 0x39 => 4u * sizeof(uint),
+ <= 0x3F => 2u * sizeof(uint),
+ _ => 0,
+ };
+ return (int)ctx[CpuRegister.Rax];
+ }
+
[SysAbiExport(
Nid = "MWiElSNE8j8",
ExportName = "sceAgcDcbWaitUntilSafeForRendering",
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs b/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs
index 08852bd68..e61bbb7c6 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.PacketStubs.cs
@@ -39,11 +39,15 @@ public enum AgcPacketStubWordKind : byte
///
/// One register location an indirect draw's modifier (the low 32 bits of )
/// selects, shifted left by : when modifier & EnableMask is
-/// clear, ; else, for -1, the flag 1;
-/// else the stage's user-SGPR base (0x10C for stages 3 and 5 in bits 29..31, 0x8C otherwise) plus
-/// (modifier >> FieldShift) & 0x1F.
+/// clear or modifier & DisableMask is not, ; else, for
+/// -1, the flag 1; else the stage's user-SGPR base (0x10C for stages
+/// 3 and 5 in bits 29..31, 0x8C otherwise) plus (modifier >> FieldShift) & 0x1F.
///
-public readonly record struct AgcModifierSgprSlot(AgcStubRegister Register, uint EnableMask, int FieldShift, uint Disabled, int ShiftLeft);
+public readonly record struct AgcModifierSgprSlot(AgcStubRegister Register, uint EnableMask, int FieldShift, uint Disabled, int ShiftLeft)
+{
+ /// Modifier bits that, when any is set, disable the slot (the user-VGPR bit 4).
+ public uint DisableMask { get; init; }
+}
public sealed record AgcPacketStubWord(uint Constant, AgcPacketStubPart[] Parts, AgcPacketStubWordKind Kind = AgcPacketStubWordKind.Parts)
{
@@ -88,12 +92,13 @@ private static AgcPacketStubWord DrawInitiatorOfRcx() =>
private static AgcPacketStubWord Slots(params AgcModifierSgprSlot[] slots) =>
new(0, [], AgcPacketStubWordKind.ModifierSgprSlots) { Slots = slots };
- // The modifier slots of IndexIndirectRegisterLocations (rdx = modifier): base vertex (bit 0),
- // draw index (bit 1, high half of the low dword), first instance (bit 2) and the bit-59 flag.
- private static readonly AgcModifierSgprSlot BaseVertexSlot = new(AgcStubRegister.Rdx, 1, 9, 0x280, 0);
- private static readonly AgcModifierSgprSlot DrawIndexSlot = new(AgcStubRegister.Rdx, 2, 14, 0, 16);
- private static readonly AgcModifierSgprSlot FirstInstanceSlot = new(AgcStubRegister.Rdx, 4, 19, 0x280, 0);
- private static readonly AgcModifierSgprSlot DrawIndexFlagSlot = new(AgcStubRegister.Rdx, 2, -1, 0, 59 - 32);
+ // The modifier slots of IndexIndirectRegisterLocations (rdx = modifier): base vertex (bit 0) and
+ // first instance (bit 2), each none (0x280) when the modifier passes the values in VGPRs (bit 4).
+ // A single draw has no draw-index slot.
+ private static readonly AgcModifierSgprSlot BaseVertexSlot =
+ new(AgcStubRegister.Rdx, DrawModifierStartVertex, 9, 0x280, 0) { DisableMask = DrawModifierUserVgprs };
+ private static readonly AgcModifierSgprSlot FirstInstanceSlot =
+ new(AgcStubRegister.Rdx, DrawModifierStartInstance, 19, 0x280, 0) { DisableMask = DrawModifierUserVgprs };
// IndirectDrawInitiator of rdx.
private static AgcPacketStubWord IndirectDrawInitiatorOfRdx() =>
@@ -140,7 +145,7 @@ private static AgcPacketStubWord IndirectDrawInitiatorOfRdx() =>
["t1vNu082-jM"] = new(5, 0, // sceAgcDcbDrawIndexIndirect
[
Const(Pm4(5, ItDrawIndexIndirect, 0)), Arg(AgcStubRegister.Rsi),
- Slots(BaseVertexSlot, DrawIndexSlot), Slots(FirstInstanceSlot, DrawIndexFlagSlot), IndirectDrawInitiatorOfRdx(),
+ Slots(BaseVertexSlot), Slots(FirstInstanceSlot), IndirectDrawInitiatorOfRdx(),
]),
["1q1titRBL6o"] = new(5, 0, // sceAgcDcbDrawIndirect
[
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs
index 73a59a268..6f1929aef 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs
@@ -97,6 +97,7 @@ public static int CbSetShRegistersDirect(CpuContext ctx)
start = end;
}
+ using var appendScope = new CommandBufferAppendScope(ctx, commandBufferAddress);
if (TryReserveCommandDwordsInPlace(ctx, commandBufferAddress, totalDwords, out var batchAddress, out var nextCursor))
{
runs = runCount;
@@ -215,7 +216,7 @@ public static int CbSetShRegisterRangeDirect(CpuContext ctx)
return ReturnPointer(ctx, 0);
}
- ulong commandAddress;
+ ulong commandAddress = 0;
var payloadWritten = false;
using (AgcRegisterPacketProfile.Measure(AgcRegisterPacketProfile.Phase.PacketSetup))
{
@@ -223,33 +224,41 @@ public static int CbSetShRegisterRangeDirect(CpuContext ctx)
// leading dwords one write - with a small payload, read first, in it too: each guest write
// and cursor update is a backing admission, and this runs once per draw on GTA V's render
// threads.
- if (TryReserveCommandDwordsInPlace(ctx, commandBufferAddress, 2 + packetDwords, out var markerAddress, out var nextCursor))
+ bool reserved;
+ using (new CommandBufferAppendScope(ctx, commandBufferAddress))
{
- commandAddress = markerAddress + 2 * sizeof(uint);
- Span packet = stackalloc uint[4 + (int)Math.Min(valueCount, InlinePayloadDwords)];
- packet[0] = Pm4(2, ItNop, RZero);
- packet[1] = CbSetShRegisterRangeMarker;
- packet[2] = Pm4(packetDwords, ItSetShReg, 0);
- packet[3] = offset;
- payloadWritten = valuesAddress != 0 && valueCount <= InlinePayloadDwords &&
- (valuesAddress >= markerAddress + (2 + (ulong)packetDwords) * sizeof(uint) ||
- valuesAddress + (ulong)valueCount * sizeof(uint) <= markerAddress) &&
- ctx.Memory.TryRead(valuesAddress, System.Runtime.InteropServices.MemoryMarshal.AsBytes(packet[4..]));
- if (!TryCommitCommandDwords(ctx, commandBufferAddress, nextCursor, markerAddress, payloadWritten ? packet : packet[..4]))
+ reserved = TryReserveCommandDwordsInPlace(ctx, commandBufferAddress, 2 + packetDwords, out var markerAddress, out var nextCursor);
+ if (reserved)
{
- AgcRegisterPacketProfile.RecordResult(false);
- return ReturnPointer(ctx, 0);
+ commandAddress = markerAddress + 2 * sizeof(uint);
+ Span packet = stackalloc uint[4 + (int)Math.Min(valueCount, InlinePayloadDwords)];
+ packet[0] = Pm4(2, ItNop, RZero);
+ packet[1] = CbSetShRegisterRangeMarker;
+ packet[2] = Pm4(packetDwords, ItSetShReg, 0);
+ packet[3] = offset;
+ payloadWritten = valuesAddress != 0 && valueCount <= InlinePayloadDwords &&
+ (valuesAddress >= markerAddress + (2 + (ulong)packetDwords) * sizeof(uint) ||
+ valuesAddress + (ulong)valueCount * sizeof(uint) <= markerAddress) &&
+ ctx.Memory.TryRead(valuesAddress, System.Runtime.InteropServices.MemoryMarshal.AsBytes(packet[4..]));
+ if (!TryCommitCommandDwords(ctx, commandBufferAddress, nextCursor, markerAddress, payloadWritten ? packet : packet[..4]))
+ {
+ AgcRegisterPacketProfile.RecordResult(false);
+ return ReturnPointer(ctx, 0);
+ }
}
}
- else if (TryDeclineLeaf(ctx))
+
+ // Without the room the fallback runs outside the append scope: the full callback must run without the lock.
+ if (!reserved && TryDeclineLeaf(ctx))
{
// The marker and the packet would be allocated one after the other: a leaf backs out
// before either is written.
return ReturnPointer(ctx, 0);
}
- else if (!TryEmitCommandDwords(ctx, commandBufferAddress, out _, Pm4(2, ItNop, RZero), CbSetShRegisterRangeMarker) ||
+
+ if (!reserved && (!TryEmitCommandDwords(ctx, commandBufferAddress, out _, Pm4(2, ItNop, RZero), CbSetShRegisterRangeMarker) ||
!TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords, out commandAddress) ||
- !TryWriteCommandDwords(ctx, commandAddress, Pm4(packetDwords, ItSetShReg, 0), offset))
+ !TryWriteCommandDwords(ctx, commandAddress, Pm4(packetDwords, ItSetShReg, 0), offset)))
{
AgcRegisterPacketProfile.RecordResult(false);
return ReturnPointer(ctx, 0);
@@ -508,6 +517,18 @@ public static int DcbSetCfRegisterRangeDirect(CpuContext ctx) =>
public static int DcbSetCxRegisterDirect(CpuContext ctx) =>
DcbSetRegisterDirect(ctx, ItSetContextReg, "cx");
+ // Matches the 3-dword SET_CONTEXT_REG packet DcbSetCxRegisterDirect writes.
+ [SysAbiExport(
+ Nid = "1DeUNpRIDDA",
+ ExportName = "sceAgcDcbSetCxRegisterDirectGetSize",
+ Target = Generation.Gen5,
+ LibraryName = "libSceAgc")]
+ public static int DcbSetCxRegisterDirectGetSize(CpuContext ctx)
+ {
+ ctx[CpuRegister.Rax] = 3u * sizeof(uint);
+ return (int)ctx[CpuRegister.Rax];
+ }
+
private static int DcbSetRegisterRangeDirect(CpuContext ctx, uint op, string registerSpace)
{
var commandBufferAddress = ctx[CpuRegister.Rdi];
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs b/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs
index 41c049734..c0173e21a 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs
@@ -448,6 +448,76 @@ private static bool IsReadableByCopy(ICpuMemory memory, ulong address, int lengt
finally { System.Buffers.ArrayPool.Shared.Return(scratch); }
}
+ // ABI: EDI is the queue (the owner sceAgcDriverSubmitAcb takes), RSI points to addresses, RDX points to dword
+ // counts, and ECX contains the count.
+ [SysAbiExport(
+ Nid = "HF3YllT3mXU",
+ ExportName = "sceAgcDriverSubmitMultiAcbs",
+ Target = Generation.Gen5,
+ LibraryName = "libSceAgcDriver")]
+ public static int DriverSubmitMultiAcbs(CpuContext ctx)
+ {
+ if (HostSessionControl.IsShutdownRequested)
+ {
+ return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_CANCELED);
+ }
+
+ var ownerHandle = (uint)ctx[CpuRegister.Rdi];
+ var addressArray = ctx[CpuRegister.Rsi];
+ var sizeArray = ctx[CpuRegister.Rdx];
+ var bufferCount = (uint)ctx[CpuRegister.Rcx];
+ if (addressArray == 0 || sizeArray == 0 || bufferCount == 0 || bufferCount > 4096)
+ {
+ return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT);
+ }
+
+ (GuestGpu.Current as IGuestImageSnapshotBackend)?.AttachGuestMemory(ctx.Memory);
+ var gpuState = _submittedGpuStates.GetValue(CanonicalMemory(ctx.Memory), static _ => new SubmittedGpuState());
+ List? preparations = null;
+ lock (gpuState.CommandSubmissionGate)
+ lock (gpuState.Gate)
+ {
+ for (uint bufferIndex = 0; bufferIndex < bufferCount; bufferIndex++)
+ {
+ if (!ctx.TryReadUInt64(addressArray + bufferIndex * 8, out var commandAddress) ||
+ commandAddress == 0 ||
+ !ctx.TryReadUInt32(sizeArray + bufferIndex * 4, out var dwordCount) ||
+ dwordCount == 0)
+ {
+ continue;
+ }
+
+ if (_traceAgc)
+ {
+ TraceAgc(
+ $"agc.driver_submit_multi_acbs owner={ownerHandle} index={bufferIndex}/{bufferCount} " +
+ $"addr=0x{commandAddress:X16} dwords={dwordCount}");
+ }
+
+ SubmissionFlowProfile.RecordGuest(SubmissionFlowProfile.EventKind.SubmitEntered,
+ ownerHandle, 0, commandAddress, dwordCount);
+ if (!TrySubmitCommandStream(
+ ctx.Memory,
+ ownerHandle,
+ commandAddress,
+ dwordCount,
+ ++gpuState.SubmissionSequence,
+ null, out var preparation))
+ {
+ return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_CANCELED);
+ }
+ if (preparation is not null) (preparations ??= []).Add(preparation);
+ }
+ }
+
+ if (preparations is not null)
+ foreach (var preparation in preparations)
+ if (!TryWaitSubmissionPreparation(preparation))
+ return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_CANCELED);
+ ctx[CpuRegister.Rax] = 0;
+ return (int)OrbisGen2Result.ORBIS_GEN2_OK;
+ }
+
private static Dictionary? CaptureSubmittedTables(CpuContext ctx, ulong address, ReadOnlySpan commands)
{
var words = System.Runtime.InteropServices.MemoryMarshal.Cast(commands);
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.SubmittedGeometry.cs b/src/SharpEmu.Libs/Agc/AgcExports.SubmittedGeometry.cs
index ddff4b5cf..b3e2bdb72 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.SubmittedGeometry.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.SubmittedGeometry.cs
@@ -237,6 +237,15 @@ private static bool TryReadPacketUInt64(CpuContext ctx, ulong address, out ulong
return indexSnapshots is { Count: > 0 } ? indexSnapshots : null;
}
+ // AgcPacketWrites: the walk below with TryReadUInt32 serving the buffer's words from a copy loaded page by page as
+ // the walk reads them (a chained buffer gets its own copy at its depth). The walk writes no guest memory, so the
+ // copy holds what the word reads would return on this thread. A buffer that is too large or was walked already is
+ // walked with direct word reads.
+ [ThreadStatic]
+ private static byte[]?[]? _scanBuffers;
+ [ThreadStatic]
+ private static ulong[]?[]? _scanLoadedPages;
+
private static void CaptureSubmittedIndexPacketsCore(
CpuContext ctx,
ulong commandAddress,
@@ -248,6 +257,67 @@ private static void CaptureSubmittedIndexPacketsCore(
ref long retainedIndexBytes,
ref long retainedVertexBytes,
int depth)
+ {
+ byte[]? buffer = null;
+ ulong[]? loaded = null;
+ var bytes = (int)Math.Min(dwordCount, AgcPacketWrites.MaximumScanDwords) * sizeof(uint);
+ if (AgcPacketWrites.Active && commandAddress != 0 && dwordCount != 0 && dwordCount <= AgcPacketWrites.MaximumScanDwords &&
+ depth <= 8 && commandAddress <= ulong.MaxValue - (ulong)bytes && !visited.Contains((commandAddress, dwordCount)))
+ {
+ var buffers = _scanBuffers ??= new byte[]?[9];
+ var loadedPages = _scanLoadedPages ??= new ulong[]?[9];
+ buffer = buffers[depth];
+ if (buffer is null || buffer.Length < bytes)
+ {
+ buffer = new byte[Math.Max(bytes, ScanPageBytes)];
+ buffers[depth] = buffer;
+ }
+
+ // Pages the window overlaps, from the page holding its start: at most bytes / 4 KiB + 1.
+ var words = (bytes / ScanPageBytes + 2 + 63) / 64;
+ loaded = loadedPages[depth];
+ if (loaded is null || loaded.Length < words)
+ {
+ loaded = new ulong[words];
+ loadedPages[depth] = loaded;
+ }
+ else
+ {
+ Array.Clear(loaded, 0, words);
+ }
+ }
+
+ if (buffer is null)
+ {
+ CaptureSubmittedIndexPacketsWalk(ctx, commandAddress, dwordCount, visited, indexSnapshots, vertexSnapshots,
+ captureState, ref retainedIndexBytes, ref retainedVertexBytes, depth);
+ return;
+ }
+
+ var (outerWindow, outerStart, outerLength, outerLoaded) = (_scanWindow, _scanWindowStart, _scanWindowLength, _scanLoaded);
+ (_scanWindow, _scanWindowStart, _scanWindowLength, _scanLoaded) = (buffer, commandAddress, bytes, loaded);
+ try
+ {
+ CaptureSubmittedIndexPacketsWalk(ctx, commandAddress, dwordCount, visited, indexSnapshots, vertexSnapshots,
+ captureState, ref retainedIndexBytes, ref retainedVertexBytes, depth);
+ }
+ finally
+ {
+ (_scanWindow, _scanWindowStart, _scanWindowLength, _scanLoaded) = (outerWindow, outerStart, outerLength, outerLoaded);
+ }
+ }
+
+ private static void CaptureSubmittedIndexPacketsWalk(
+ CpuContext ctx,
+ ulong commandAddress,
+ uint dwordCount,
+ HashSet<(ulong Address, uint Dwords)> visited,
+ Dictionary? indexSnapshots,
+ Dictionary? vertexSnapshots,
+ SubmittedDcbState captureState,
+ ref long retainedIndexBytes,
+ ref long retainedVertexBytes,
+ int depth)
{
if (commandAddress == 0 || dwordCount == 0 || depth > 8 ||
!visited.Add((commandAddress, dwordCount)))
diff --git a/src/SharpEmu.Libs/Agc/AgcExports.cs b/src/SharpEmu.Libs/Agc/AgcExports.cs
index ff1216dc8..c5570f789 100644
--- a/src/SharpEmu.Libs/Agc/AgcExports.cs
+++ b/src/SharpEmu.Libs/Agc/AgcExports.cs
@@ -33,6 +33,7 @@ public static partial class AgcExports
private const uint ItDrawIndexMultiAuto = 0x30;
private const uint ItDrawIndexOffset2 = 0x35;
private const uint ItDrawIndexIndirectMulti = 0x38;
+ private const uint ItDrawIndirectMulti = 0x2C;
private const uint DrawIndexedIndirectArgsSize = 20;
private const uint DrawIndexedIndirectMaxScan = 1024;
private const uint ItWriteData = 0x37;
@@ -495,13 +496,113 @@ private static ulong ComputeFingerprint(ReadOnlySpan bytes)
return fingerprint;
}
- private static bool TryAllocateCommandDwords(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, out ulong commandAddress)
- => TryPrepareCommandDwords(ctx, commandBufferAddress, sizeDwords, true, out commandAddress);
+ private static bool TryAllocateCommandDwords(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, out ulong commandAddress,
+ bool isMarker = false)
+ => TryPrepareCommandDwords(ctx, commandBufferAddress, sizeDwords, true, out commandAddress, isMarker);
+
+ // Guest threads run HLE exports concurrently. Two exports appending to one command buffer both read its cursor before
+ // either stores it back, and the second packet overwrites the first: a game's DCB lost the header of a
+ // SET_SH_REG to a concurrent PopMarker (seen as "The packet opcode is unknown" right after a PopMarker).
+ // The cursor update is atomic per buffer, under a striped lock that is released around the guest's buffer-full callback.
+ private const int CommandBufferLockStripes = 64;
+ private static readonly object[] _commandBufferLocks = Enumerable.Range(0, CommandBufferLockStripes).Select(static _ => new object()).ToArray();
+
+ // Inline guest stores do not take the lock. The last ordinary packet writer of each buffer is remembered, so a
+ // diagnostic marker from another guest thread is skipped (null packet pointer) instead of reserving space inside that
+ // writer's unpublished inline packet. An ordinary export takes the buffer over, which allows a handoff between threads.
+ // Writers are scoped to the guest memory, and guest thread handles survive migration between host threads.
+ private static readonly ConditionalWeakTable
bool ConsumesSubmittedCommandBytes => true;
+ // The shader of a translation the translation disk cache kept (TranslationDiskCache); null when the backend keeps none.
+ IGuestCompiledShader? CreateCachedShader(byte[] payload, uint? inputLocationMask) => null;
+
+ // The same for the request the translation is taken for: a backend whose payload names the request it was made from
+ // refuses (null) one made for another. A cache hit gives the shader a translation of request would give.
+ IGuestCompiledShader? CreateCachedShader(byte[] payload, uint? inputLocationMask, ShaderCompileRequest request) =>
+ CreateCachedShader(payload, inputLocationMask);
+
// The vertex stage a tessellated pipeline requires and the control stage that feeds the guest's hull factors to the tessellator.
(IGuestCompiledShader Vertex, IGuestCompiledShader Control) CompileTessellationBridge(
SharpEmu.ShaderCompiler.Resources.BindingLayout layout, Gen5TessellationDomain domain) =>
diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestPixelFormats.cs b/src/SharpEmu.Libs/Gpu/Images/GuestPixelFormats.cs
index 5e12f340f..0b234a582 100644
--- a/src/SharpEmu.Libs/Gpu/Images/GuestPixelFormats.cs
+++ b/src/SharpEmu.Libs/Gpu/Images/GuestPixelFormats.cs
@@ -307,7 +307,7 @@ private readonly record struct FormatFacts(
[
new(GuestPixelFormat.Bits8UNorm, 1, 0, 1, true, false),
new(GuestPixelFormat.Bits8UScaled, 1, 0, 1, true, false),
- new(GuestPixelFormat.Bits8SNorm, 0, 0, 1, false, false),
+ new(GuestPixelFormat.Bits8SNorm, 1, 0, 1, true, false),
new(GuestPixelFormat.Bits8UInt, 1, 0, 1, true, true),
new(GuestPixelFormat.Bits8SInt, 1, 0, 1, true, false, true),
new(GuestPixelFormat.Bits16UNorm, 2, 0, 2, true, false),
@@ -431,6 +431,7 @@ private readonly record struct RenderTargetLayoutFacts(
private static readonly (GuestPixelFormat Guest, GpuFormat Host)[] HostFormats =
[
(GuestPixelFormat.Bits8UNorm, GpuFormat.R8Unorm),
+ (GuestPixelFormat.Bits8SNorm, GpuFormat.R8SNorm),
(GuestPixelFormat.Bits8UInt, GpuFormat.R8Uint),
(GuestPixelFormat.Bits8SInt, GpuFormat.R8Sint),
(GuestPixelFormat.Bits16UNorm, GpuFormat.R16Unorm),
diff --git a/src/SharpEmu.Libs/Gpu/Images/HostLayoutTargets.cs b/src/SharpEmu.Libs/Gpu/Images/HostLayoutTargets.cs
new file mode 100644
index 000000000..ff6cdab60
--- /dev/null
+++ b/src/SharpEmu.Libs/Gpu/Images/HostLayoutTargets.cs
@@ -0,0 +1,17 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+using System.Collections.Concurrent;
+
+namespace SharpEmu.Libs.Gpu.Images;
+
+internal static class HostLayoutTargets
+{
+ private static readonly ConcurrentDictionary Addresses = new();
+
+ public static void Mark(ulong address) => Addresses.TryAdd(address, 0);
+
+ public static bool Holds(ulong address) => !Addresses.IsEmpty && Addresses.ContainsKey(address);
+
+ public static void Reset() => Addresses.Clear();
+}
diff --git a/src/SharpEmu.Libs/Gpu/Images/ImageDescription.cs b/src/SharpEmu.Libs/Gpu/Images/ImageDescription.cs
index 27426c456..6875e82d0 100644
--- a/src/SharpEmu.Libs/Gpu/Images/ImageDescription.cs
+++ b/src/SharpEmu.Libs/Gpu/Images/ImageDescription.cs
@@ -147,6 +147,42 @@ public static uint FullChainLevels(uint width, uint height, uint depth) =>
public bool Bgra16;
public MipLevelLayouts MipLayout;
+ // The first guest level the host image holds. A streamed texture maps only its resident
+ // mips and its descriptor starts at the first of them; its image starts there too, while
+ // Extent and MipLayout keep describing the whole guest chain the data is laid out in.
+ // Resources.Levels counts the host levels, from this one.
+ public uint FirstLevel;
+
+ // The host extent of the image's first level.
+ public readonly GpuExtent3D HostExtent => FirstLevel == 0
+ ? Extent
+ : new GpuExtent3D(Math.Max(Extent.Width >> (int)FirstLevel, 1u), Math.Max(Extent.Height >> (int)FirstLevel, 1u), Extent.Depth);
+
+ // The bytes of the guest range the image's levels occupy: the whole range, or for an image of
+ // resident levels only the span of those levels (the levels before FirstLevel are not part of
+ // the image and take no memory in the working-set accounting).
+ public readonly ulong HeldGuestSize
+ {
+ get
+ {
+ if (FirstLevel == 0)
+ {
+ return Data.Size;
+ }
+
+ var begin = ulong.MaxValue;
+ ulong end = 0;
+ for (var level = FirstLevel; level < FirstLevel + Resources.Levels && level < MaxLevels; level++)
+ {
+ var layout = MipLayout[(int)level];
+ begin = Math.Min(begin, layout.Offset);
+ end = Math.Max(end, layout.Offset + layout.Size);
+ }
+
+ return end > begin && end <= Data.Size ? end - begin : Data.Size;
+ }
+ }
+
public static ImageDescription Create() => new()
{
HtileClearMask = uint.MaxValue,
@@ -211,7 +247,10 @@ public readonly int FindMatchingMipLevel(in ImageDescription container)
// Return the matching slice in the containing mip level, or -1 if none matches.
public readonly int FindMatchingArraySlice(in ImageDescription container, int mip)
{
- if (!IsCompatible(container) || TileMode != container.TileMode || Type != container.Type || IsVolume ||
+ // A view inside another image's chain is found by guest level; an image holding only the
+ // resident tail of its chain numbers its levels from another one, so it never matches.
+ if (FirstLevel != 0 || container.FirstLevel != 0 ||
+ !IsCompatible(container) || TileMode != container.TileMode || Type != container.Type || IsVolume ||
Resources.Levels != 1 || Resources.Layers == 0 || container.Resources.Layers == 0 || mip < 0 ||
(uint)mip >= container.Resources.Levels || container.Resources.Levels > MaxLevels ||
!IsValidRange(Data) || !IsValidRange(container.Data) || Data.Address < container.Data.Address || Data.End > container.Data.End)
@@ -418,6 +457,11 @@ public readonly void Validate()
throw GpuFatal.Fatal($"The image type is not a base type: type={(uint)Type}.");
}
+ if (FirstLevel != 0 && (Samples != 1 || IsVolume || FirstLevel + Resources.Levels > MaxLevels))
+ {
+ throw GpuFatal.Fatal($"A resident-mip image needs a single-sample 2D chain: firstLevel={FirstLevel} levels={Resources.Levels} samples={Samples} type={Type}.");
+ }
+
if (Samples > 1 && Resources.Levels != 1)
{
throw GpuFatal.Fatal($"A multisampled image cannot have mip levels: samples={Samples} levels={Resources.Levels}.");
diff --git a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs
index de66951be..f62610e79 100644
--- a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs
+++ b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs
@@ -12,15 +12,22 @@ namespace SharpEmu.Libs.Gpu.Images;
// A descriptor the texture builder rejected inside ImageRequestBuilders.RejectInvalidDescriptors.
public sealed class TextureDescriptorRejectedException(string message) : Exception(message);
-// A texture request built from the descriptor words and the shape the shader was compiled with.
-public readonly record struct TextureRequestResolution(ImageRequest Request, bool ExactFormat, GpuFormat ViewFormat, uint Swizzle);
+// A texture request built from the descriptor words and the shape the shader was compiled with. Fields, not properties:
+// a request is about 560 bytes, and passing a property to an `in` parameter copies it.
+public struct TextureRequestResolution(ImageRequest request, bool exactFormat, GpuFormat viewFormat, uint swizzle)
+{
+ public ImageRequest Request = request;
+ public bool ExactFormat = exactFormat;
+ public GpuFormat ViewFormat = viewFormat;
+ public uint Swizzle = swizzle;
+}
public static partial class ImageRequestBuilders
{
[ThreadStatic] private static int _rejectInvalidDescriptors;
// Inside this scope a descriptor the builder cannot turn into a texture request throws TextureDescriptorRejectedException
- // instead of stopping the GPU: a call record holds whatever the game last wrote there.
+ // instead of stopping the GPU: a bindless heap record holds whatever the game last wrote there.
public static RejectionScope RejectInvalidDescriptors()
{
_rejectInvalidDescriptors++;
@@ -49,6 +56,23 @@ private static Exception InvalidDescriptor(string message) =>
Atomic: image.Atomic,
Atomic64: image.Atomic64);
+ // The unsigned format of a signed-integer one: the view of a write-only signed storage image the program writes as
+ // unsigned bits (ResourceMaterializer). Undefined for any other format.
+ private static GpuFormat UnsignedOfSigned(GpuFormat format) => format switch
+ {
+ GpuFormat.R8Sint => GpuFormat.R8Uint,
+ GpuFormat.R8G8Sint => GpuFormat.R8G8Uint,
+ GpuFormat.R8G8B8A8Sint => GpuFormat.R8G8B8A8Uint,
+ GpuFormat.R16Sint => GpuFormat.R16Uint,
+ GpuFormat.R16G16Sint => GpuFormat.R16G16Uint,
+ GpuFormat.R16G16B16A16Sint => GpuFormat.R16G16B16A16Uint,
+ GpuFormat.R32Sint => GpuFormat.R32Uint,
+ GpuFormat.R32G32Sint => GpuFormat.R32G32Uint,
+ GpuFormat.R32G32B32A32Sint => GpuFormat.R32G32B32A32Uint,
+ GpuFormat.A2B10G10R10SintPack32 => GpuFormat.A2B10G10R10UintPack32,
+ _ => GpuFormat.Undefined,
+ };
+
private static TextureNumericClass NumericClassOf(ImageResource image) => image.NumericClass switch
{
ImageNumericClass.Uint or ImageNumericClass.Uint64 => TextureNumericClass.Uint,
@@ -171,13 +195,15 @@ public static void PopulateTextureMipLayout(ref ImageDescription description)
// The view follows the compiled module: a volume, a layer window to the last layer, or one layer.
private static ImageViewDescription TextureView(
in TextureDescriptorWords descriptor, in ShaderImageShape shape, GpuFormat format, bool shaderConversion, uint viewLevels, uint imageLayers,
- ulong shaderHash, int imageIndex)
+ ulong shaderHash, int imageIndex, uint firstLevel)
{
+ // The image's levels count from its first resident guest level.
+ var baseLevel = descriptor.BaseLevel - firstLevel;
var mapping = shape.Storage || shaderConversion ? default : ViewFormatRules.ComponentMapping(DestinationSwizzle(descriptor));
var usage = shape.Storage ? GpuImageUsage.StorageBit : GpuImageUsage.SampledBit;
if (shape.Volume)
{
- return WithMinLod(new ImageViewDescription(format, GpuImageViewType.Type3D, GpuImageAspect.ColorBit, descriptor.BaseLevel, viewLevels, 0, 1, mapping, usage), descriptor, shape);
+ return WithMinLod(new ImageViewDescription(format, GpuImageViewType.Type3D, GpuImageAspect.ColorBit, baseLevel, viewLevels, 0, 1, mapping, usage), descriptor, shape, firstLevel);
}
var baseLayer = descriptor.BaseArray;
@@ -194,15 +220,39 @@ private static ImageViewDescription TextureView(
var type = shape.OneDimensional
? shape.Arrayed ? GpuImageViewType.Type1DArray : GpuImageViewType.Type1D
: shape.Arrayed ? GpuImageViewType.Type2DArray : GpuImageViewType.Type2D;
- return WithMinLod(new ImageViewDescription(format, type, GpuImageAspect.ColorBit, descriptor.BaseLevel, viewLevels, baseLayer, layerCount, mapping, usage), descriptor, shape);
+ return WithMinLod(new ImageViewDescription(format, type, GpuImageAspect.ColorBit, baseLevel, viewLevels, baseLayer, layerCount, mapping, usage), descriptor, shape, firstLevel);
}
+ // Set by a backend whose image cache understands ImageDescription.FirstLevel (an image of the
+ // resident levels only, WithWholeMipChain): Vulkan, and Metal unless SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS=0
+ // (MetalImageCache.ResidentLevels takes the request as its whole chain and holds the texture from its level).
+ // Requests cached under the other setting describe other images: a change drops every thread's cache at its next
+ // lookup (_textureCacheSetting).
+ public static bool PartialMipChains
+ {
+ get => _partialMipChains;
+ set
+ {
+ if (_partialMipChains != value)
+ {
+ _partialMipChains = value;
+ Interlocked.Increment(ref _partialMipChainsSetting);
+ }
+ }
+ }
+
+ private static volatile bool _partialMipChains;
+ private static int _partialMipChainsSetting;
+ [ThreadStatic]
+ private static int _textureCacheSetting;
+
// MIN_LOD (4.8 fixed point, absolute mip levels) keeps sampling off mips a streamed texture has not
// loaded yet; ignoring it sampled the unloaded mip 0 of Astro Bot's stadium sky and bloom spread its
// garbage HDR values over the screen. Storage views address levels explicitly and are not clamped.
- private static ImageViewDescription WithMinLod(ImageViewDescription view, in TextureDescriptorWords descriptor, in ShaderImageShape shape)
+ private static ImageViewDescription WithMinLod(ImageViewDescription view, in TextureDescriptorWords descriptor, in ShaderImageShape shape, uint firstLevel)
{
- var minLod = descriptor.MinLod / 256f;
+ // The view's levels are host levels, which start at the image's first guest level.
+ var minLod = descriptor.MinLod / 256f - firstLevel;
if (shape.Storage || minLod <= view.BaseLevel)
{
return view;
@@ -211,6 +261,31 @@ private static ImageViewDescription WithMinLod(ImageViewDescription view, in Tex
return view with { MinLod = Math.Min(minLod, view.BaseLevel + view.LevelCount - 1) };
}
+ // The same texture as an image of the whole guest mip chain, viewed from the descriptor's base
+ // level: the request a texture gets when its larger mips are mapped or another image holds them.
+ public static ImageRequest WithWholeMipChain(in ImageRequest request)
+ {
+ var firstLevel = request.Description.FirstLevel;
+ if (firstLevel == 0)
+ {
+ return request;
+ }
+
+ var whole = request;
+ whole.Description.Resources = new SubresourceCount(request.Description.Resources.Levels + firstLevel, request.Description.Resources.Layers);
+ whole.Description.FirstLevel = 0;
+ whole.View = RebaseView(request.View, firstLevel);
+ return whole;
+ }
+
+ // A view of an image whose first level is `levels` guest levels lower than the view was built for.
+ public static ImageViewDescription RebaseView(in ImageViewDescription view, uint levels) =>
+ levels == 0 ? view : view with
+ {
+ BaseLevel = view.BaseLevel + levels,
+ MinLod = view.MinLod == 0 ? 0 : view.MinLod + levels,
+ };
+
public static uint DestinationSwizzle(in TextureDescriptorWords descriptor) =>
ViewFormatRules.PackDestinationSelect(descriptor.DestinationSelectX, descriptor.DestinationSelectY, descriptor.DestinationSelectZ, descriptor.DestinationSelectW);
@@ -243,6 +318,13 @@ public static TextureRequestResolution Texture(ReadOnlySpan words, in Shad
Span key = stackalloc uint[8];
words[..Math.Min(words.Length, 8)].CopyTo(key);
var cacheKey = new TextureKey(key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], shape);
+ var setting = Volatile.Read(ref _partialMipChainsSetting);
+ if (_textureCacheSetting != setting)
+ {
+ _textureCache = null;
+ _textureCacheSetting = setting;
+ }
+
var cache = _textureCache ??= new Dictionary();
if (cache.TryGetValue(cacheKey, out var cached))
{
@@ -382,7 +464,10 @@ private static TextureRequestResolution BuildTexture(ReadOnlySpan words, i
var rawSint32 = format == GuestPixelFormat.Bits32SInt && shape.NumericClass != TextureNumericClass.Sint;
var storageViewFormat = storage && shape.Atomic64
? shape.NativeInt64Atomics ? GpuFormat.R64Uint : GpuFormat.R32G32Uint
- : storage && (shape.Atomic || rawSint32) ? GpuFormat.R32Uint : ViewFormatRules.SrgbStorageFormat(pixelFormat);
+ : storage && (shape.Atomic || rawSint32) ? GpuFormat.R32Uint
+ : storage && shape.NumericClass == TextureNumericClass.Uint && UnsignedOfSigned(pixelFormat) is var unsigned and not GpuFormat.Undefined
+ ? unsigned
+ : ViewFormatRules.SrgbStorageFormat(pixelFormat);
var viewFormat = storage && storageViewFormat != GpuFormat.Undefined ? storageViewFormat : pixelFormat;
var blockBytes = GuestPixelFormats.BlockCompressedBytes(format);
var description = ImageDescription.Create();
@@ -416,8 +501,24 @@ private static TextureRequestResolution BuildTexture(ReadOnlySpan words, i
PopulateTextureMipLayout(ref description);
}
+ // A sampled texture whose descriptor starts past mip 0 never reads the levels before it, and a
+ // streamed texture has not even mapped them: the request holds only the levels from there.
+ // The image cache returns it to the whole chain when that memory is mapped, so a texture view
+ // of a lower mip of a rendered or fully loaded chain stays the same image (WithWholeMipChain).
+ // Only a backend whose image cache sizes images by ImageDescription.FirstLevel takes the
+ // resident levels alone (PartialMipChains); the others keep the whole chain, as before.
+ var firstLevel = PartialMipChains && !storage && !volume && samples == 1 && baseLevel > 0 && baseLevel < levels &&
+ description.Metadata.Kind == MetadataKind.None && !description.IsDepth
+ ? baseLevel
+ : 0u;
+ if (firstLevel != 0)
+ {
+ description.FirstLevel = firstLevel;
+ description.Resources = new SubresourceCount(levels - firstLevel, imageLayers);
+ }
+
var view = TextureView(descriptor, shape, viewFormat, shaderConversion, viewLevels, description.Resources.Layers,
- shaderHash, imageIndex);
+ shaderHash, imageIndex, firstLevel);
if (NativeColorClearMetadata && !shape.R128 && descriptor.MetadataCompress && !description.IsDepth && !shaderConversion &&
tile == GuestTileMode.RenderTarget && levels == 1 && samples == 1 &&
type is GuestImageType.Color2D or GuestImageType.Color2DArray or GuestImageType.Color3D &&
diff --git a/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs b/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs
new file mode 100644
index 000000000..946653c1c
--- /dev/null
+++ b/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs
@@ -0,0 +1,122 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+using SharpEmu.HLE;
+using SharpEmu.HLE.GpuMemory;
+using SharpEmu.Libs.Kernel;
+
+namespace SharpEmu.Libs.Gpu.Images;
+
+// A texture streamed into its address range maps only its resident mips. A tiled chain puts
+// the mip tail and small levels at the start and level 0 at the end, so the resident part is
+// a backed prefix. The GPU samples only resident levels; the unmapped rest reads as zero.
+// Public for the Metal image cache, which reads guest image bytes with the same policy (no InternalsVisibleTo
+// for extracted backends).
+public static class ResidentImageBacking
+{
+ private const ulong Page = 1UL << 12;
+
+ // SHARPEMU_IMAGE_BACKING_HOLES=1 (default off): unmapped pages anywhere after the first are zero-filled instead of
+ // failing. Games sample images whose backing has a backed page after a hole, and that failure is
+ // fatal.
+ private static readonly bool AllowHoles =
+ Environment.GetEnvironmentVariable("SHARPEMU_IMAGE_BACKING_HOLES") == "1";
+
+ // Reads image bytes from CPU-visible backing or PRT backing. A streamed texture's image holds only its
+ // resident levels and its upload reads only their bytes, so an unmapped byte inside them is an error,
+ // not a level to zero; SHARPEMU_IMAGE_BACKING_HOLES=1 still zero-fills the unmapped pages instead.
+ public static bool TryRead(IGuestBackedSpace backing, ulong address, Span destination) =>
+ TryRead(backing, address, destination, AllowHoles);
+
+ // SHARPEMU_IMAGE_BACKING_HOLES as this process read it; a caller with its own test switch passes that instead.
+ public static bool HolesAllowed => AllowHoles;
+
+ // TryRead with the hole policy given rather than read from the environment.
+ public static bool TryRead(IGuestBackedSpace backing, ulong address, Span destination, bool allowHoles) =>
+ backing.TryReadBacking(address, destination) ||
+ KernelMemoryCompatExports.TryReadPrtBacking(backing, address, destination) ||
+ TryReadMirroredPrtBacking(backing, address, destination) ||
+ allowHoles && TryReadResidentPrefix(backing, address, destination, allowHoles: true);
+
+ // PRT backing in a process without the kernel (the GPU process of the two-process split): the guest process mirrors
+ // its PRT apertures and AMM area (PartiallyResidentRanges), and which pages are mapped is the shared view table's,
+ // which this process's backing reads. Same result as KernelMemoryCompatExports.TryReadPrtBacking: the address is
+ // translated as the kernel translates it, mapped 16 KiB chunks are read, and every other byte reads as zero. (The kernel
+ // reads a mapping that is backed whole in one piece; mappings are 16 KiB aligned, so that is the same bytes.)
+ // Empty, and so false at once, in a process that has the kernel.
+ internal static bool TryReadMirroredPrtBacking(IGuestBackedSpace backing, ulong address, Span destination)
+ {
+ if (PartiallyResidentRanges.Mirrored.Length == 0)
+ {
+ return false;
+ }
+
+ var size = (ulong)destination.Length;
+ address = GuestVaHole.TranslateRange(address, size);
+ if (!PartiallyResidentRanges.MirrorContains(address, size))
+ {
+ return false;
+ }
+
+ destination.Clear();
+ var end = address + size;
+ for (var chunk = address; chunk < end;)
+ {
+ var next = Math.Min(end, (chunk & ~(PrtProbeBytes - 1)) + PrtProbeBytes);
+ if (backing.IsBackedRange(chunk, next - chunk) &&
+ !backing.TryReadBacking(chunk, destination.Slice((int)(chunk - address), (int)(next - chunk))))
+ {
+ return false;
+ }
+
+ chunk = next;
+ }
+
+ Interlocked.Increment(ref _mirroredPrtReads);
+ return true;
+ }
+
+ // The kernel's probe size for a partly backed mapping (KernelMemoryCompatExports.PrtResidencyProbeBytes).
+ private const ulong PrtProbeBytes = 0x4000;
+
+ private static long _mirroredPrtReads;
+
+ /// Image reads answered from the mirrored PRT/AMM ranges (the split's GPU process).
+ public static long MirroredPrtReads => Interlocked.Read(ref _mirroredPrtReads);
+
+ // Copies the backed prefix page by page and zero-fills the unmapped tail. A backed page
+ // after a hole is not a mip chain, so it is rejected unless allowHoles.
+ internal static bool TryReadResidentPrefix(IGuestBackedSpace backing, ulong address, Span destination) =>
+ TryReadResidentPrefix(backing, address, destination, AllowHoles);
+
+ internal static bool TryReadResidentPrefix(IGuestBackedSpace backing, ulong address, Span destination, bool allowHoles)
+ {
+ var size = (ulong)destination.Length;
+ if (size == 0 || !backing.IsBackedRange(address, 1))
+ {
+ return false;
+ }
+
+ var resident = true;
+ for (ulong offset = 0; offset < size;)
+ {
+ var chunk = Math.Min(Page - ((address + offset) & (Page - 1)), size - offset);
+ var target = destination.Slice((int)offset, (int)chunk);
+ var backed = backing.IsBackedRange(address + offset, chunk);
+ if (backed && !resident && !allowHoles)
+ {
+ return false;
+ }
+
+ resident = backed && backing.TryReadBacking(address + offset, target);
+ if (!resident)
+ {
+ target.Clear();
+ }
+
+ offset += chunk;
+ }
+
+ return true;
+ }
+}
diff --git a/src/SharpEmu.Libs/Gpu/Images/ViewFormatRules.cs b/src/SharpEmu.Libs/Gpu/Images/ViewFormatRules.cs
index 7b99e6c24..72e5ea77e 100644
--- a/src/SharpEmu.Libs/Gpu/Images/ViewFormatRules.cs
+++ b/src/SharpEmu.Libs/Gpu/Images/ViewFormatRules.cs
@@ -284,20 +284,28 @@ public static uint SelectSampledColorView(GpuFormat imageFormat, GpuFormat viewF
public static bool IsSupportedSampledDepthView(GpuFormat imageFormat, GpuFormat viewFormat, uint swizzle)
{
- if (!IsSupportedSampledDepthFormat(imageFormat, viewFormat))
+ if (!IsSupportedSampledDepthFormat(imageFormat, viewFormat) || (swizzle & ~0xfffu) != 0)
{
return false;
}
// A depth view has one channel: the hardware reads its missing green and blue as 0 and
// alpha as 1, so the identity select samples exactly as (X, 0, 0, 1) does.
- var single = swizzle;
if (swizzle == PackDestinationSelect(4, 5, 6, 7))
{
- single = PackDestinationSelect(4, 0, 0, 1);
+ return true;
}
- return single == PackDestinationSelect(4, 4, 4, 4) || single == PackDestinationSelect(4, 0, 0, 0) || single == PackDestinationSelect(4, 0, 0, 1);
+ // Otherwise the swizzle may repeat the one channel and fill the others with 0 or 1.
+ for (uint channel = 0; channel < 4; channel++)
+ {
+ if (DestinationSelect(swizzle, channel) is not (0 or 1 or 4))
+ {
+ return false;
+ }
+ }
+
+ return true;
}
public static uint SelectSampledDepthView(GpuFormat imageFormat, GpuFormat viewFormat, uint swizzle) =>
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/BoundedFillDetector.cs b/src/SharpEmu.Libs/Gpu/Pipelines/BoundedFillDetector.cs
index ee8241157..9f0b4d435 100644
--- a/src/SharpEmu.Libs/Gpu/Pipelines/BoundedFillDetector.cs
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/BoundedFillDetector.cs
@@ -50,7 +50,30 @@ public static class BoundedFillDetector
"BufferLoadFormatX", "BufferStoreFormatX", "SEndpgm",
];
- public static BoundedCopy? DetectCopy(Gen5ShaderProgram program) => DetectModuloCopy(program) ?? DetectMaskedCopy(program);
+ private const ulong DemonsSoulsPatternCopyShader = 0xEB7456322124ECC7UL;
+ private const uint PatternCopyGroupRegister = 12;
+ private const uint PatternCopyParameters = 8;
+
+ // The structural matchers run first; upstream's hash-keyed Demon's Souls pattern copy only
+ // answers for a program neither of them recognizes.
+ public static BoundedCopy? DetectCopy(Gen5ShaderProgram program, ulong hash = 0) =>
+ DetectModuloCopy(program) ?? DetectMaskedCopy(program) ?? DetectPatternCopy(hash);
+
+ private static BoundedCopy? DetectPatternCopy(ulong hash)
+ {
+ if (hash != DemonsSoulsPatternCopyShader)
+ {
+ return null;
+ }
+
+ static FillWord UserWord(uint register) => new(FillWordSource.UserData, register, 0, 0);
+ return new BoundedCopy(
+ PatternCopyGroupRegister,
+ new FillWord(FillWordSource.BufferResource, PatternCopyParameters, 0, 0),
+ new FillWord(FillWordSource.BufferResource, PatternCopyParameters, 0, sizeof(uint)),
+ [.. Enumerable.Range(0, 4).Select(word => UserWord((uint)word))],
+ [.. Enumerable.Range(4, 4).Select(word => UserWord((uint)word))]);
+ }
private static BoundedCopy? DetectModuloCopy(Gen5ShaderProgram program)
{
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/CallRecordBufferPolicy.cs b/src/SharpEmu.Libs/Gpu/Pipelines/CallRecordBufferPolicy.cs
new file mode 100644
index 000000000..4dc9d7f5e
--- /dev/null
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/CallRecordBufferPolicy.cs
@@ -0,0 +1,17 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+namespace SharpEmu.Libs.Gpu.Pipelines;
+
+// What a buffer a linked callee reads through its call record needs at a dispatch (ShaderProgramCache.ClassifyRecordBuffer),
+// as a public contract for a backend that prepares call records outside this assembly (the Metal backend).
+public static class CallRecordBufferPolicy
+{
+ // The buffer is made resident as a device-address range.
+ public static bool Resident(ulong address, ulong size, bool written) =>
+ ShaderProgramCache.ClassifyRecordBuffer(address, size, written) == ShaderProgramCache.RecordBuffer.Resident;
+
+ // The words describe no buffer and the callee writes through them: the record is left out (its call returns at once).
+ public static bool LeavesRecordOut(ulong address, ulong size, bool written) =>
+ ShaderProgramCache.ClassifyRecordBuffer(address, size, written) == ShaderProgramCache.RecordBuffer.LeaveRecordOut;
+}
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ComputeStageInputResolver.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ComputeStageInputResolver.cs
index 6a332df32..ac3a44dea 100644
--- a/src/SharpEmu.Libs/Gpu/Pipelines/ComputeStageInputResolver.cs
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/ComputeStageInputResolver.cs
@@ -20,7 +20,8 @@ public static ComputeInputInfo Resolve(
bool needsLocalDataShareBarriers,
uint dispatchX,
uint dispatchY,
- uint dispatchZ)
+ uint dispatchZ,
+ bool gpuThreadCounts = false)
{
var threadDimensions = (dispatchInitiator & UseThreadDimensionsBit) != 0;
return new ComputeInputInfo
@@ -29,6 +30,7 @@ public static ComputeInputInfo Resolve(
ThreadsY = compute.ThreadsY & 0xFFFFu,
ThreadsZ = compute.ThreadsZ & 0xFFFFu,
DispatchThreadDimensions = threadDimensions,
+ IndirectThreadCounts = threadDimensions && gpuThreadCounts,
DispatchThreadsX = threadDimensions ? dispatchX : 0,
DispatchThreadsY = threadDimensions ? dispatchY : 0,
DispatchThreadsZ = threadDimensions ? dispatchZ : 0,
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs
index 6bbfcd0c1..00472efa8 100644
--- a/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/GraphicsProgramsComparer.cs
@@ -176,6 +176,7 @@ void Jagged(string name, uint[][] a, uint[][] b)
if (memo.PositionExportControl != full.PositionExportControl) return "vertex.position_export";
if (!SameClipSpace(memo.ClipSpace, full.ClipSpace)) return "vertex.clip_space";
if (memo.StartInstanceUserData != full.StartInstanceUserData) return "vertex.start_instance";
+ if (memo.BaseVertexUserData != full.BaseVertexUserData) return "vertex.base_vertex";
return StageDifference("vertex", memo.Stage, full.Stage);
}
@@ -244,7 +245,9 @@ static string Side(ComputeProgram program) => program.Input.Stage.Program is not
{
if (!ReferenceEquals(memo.Program, full.Program)) return stage + ".program";
if (memo.ShaderBase != full.ShaderBase) return stage + ".shader_base";
- if (memo.ThreadLimits != full.ThreadLimits || memo.MeshDraw != full.MeshDraw) return stage + ".launch";
+ if (memo.ThreadLimits != full.ThreadLimits || memo.GpuThreadLimits != full.GpuThreadLimits || memo.MeshDraw != full.MeshDraw)
+ return stage + ".launch";
+ if (!Equals(memo.CompileFallback, full.CompileFallback)) return stage + ".compile_fallback";
if (!SameArray(memo.TessellationData, full.TessellationData)) return stage + ".tessellation_data";
if (!SameArray(memo.CallArguments, full.CallArguments) || !SameArray(memo.CallTargets, full.CallTargets) ||
!SameArray(memo.CallRecords, full.CallRecords) || !SameArray(memo.CallRecordRanges, full.CallRecordRanges))
@@ -263,6 +266,7 @@ static string Side(ComputeProgram program) => program.Input.Stage.Program is not
if (!memo.UserData.AsSpan().SequenceEqual(full.UserData)) return stage + ".user_data";
if (!memo.DeviceAddressRanges.AsSpan().SequenceEqual(full.DeviceAddressRanges)) return stage + ".ranges";
if (!SameArray(memo.MipStatistics, full.MipStatistics)) return stage + ".mip_statistics";
+ if (!memo.Heaps.AsSpan().SequenceEqual(full.Heaps)) return stage + ".heaps";
if (memo.BindlessImages.Length != full.BindlessImages.Length) return stage + ".bindless";
for (var index = 0; index < memo.BindlessImages.Length; index++)
{
@@ -315,6 +319,7 @@ void MixStage(in ShaderStageResources stage)
MixWords(snapshot.UserData);
MixWords(snapshot.MipStatistics ?? []);
foreach (var range in snapshot.DeviceAddressRanges) Mix((ulong)range.GetHashCode());
+ foreach (var heap in snapshot.Heaps) Mix((ulong)heap.GetHashCode());
}
Mix(programs.Vertex.Id);
@@ -325,6 +330,7 @@ void MixStage(in ShaderStageResources stage)
foreach (var attribute in vertex.Attributes) Mix((ulong)attribute.GetHashCode());
Mix((ulong)(vertex.ClipSpace with { UserClipPlanes = null }).GetHashCode());
Mix((uint)vertex.StartInstanceUserData);
+ Mix((uint)vertex.BaseVertexUserData);
Mix((vertex.IeeeMode ? 1u : 0u) | (vertex.Dx10Clamp ? 2u : 0u) | ((ulong)vertex.FloatMode << 8));
MixStage(vertex.Stage);
var pixel = programs.PixelInput;
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs
index f4789e668..63a6112a2 100644
--- a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs
@@ -48,6 +48,7 @@ public enum KernelWriteRefusal
PendingWrite,
Image,
Metadata,
+ Input,
Count,
}
@@ -78,6 +79,10 @@ public interface IShaderPipelineHost
{
uint MaxPushDescriptors { get; }
+ StableImageDescriptorLimits ComputeImageDescriptorLimits => default;
+
+ StableImageDescriptorLimits GraphicsImageDescriptorLimits => default;
+
bool ComputeWave64Supported { get; }
// True when a 64-invocation wave64 compute workgroup runs as one 64-lane host subgroup.
@@ -87,6 +92,9 @@ public interface IShaderPipelineHost
bool MipStatisticsSubgroupReduction => false;
+ // The host subgroup of a pixel shader is one guest wave32 and has arithmetic operations.
+ bool PixelSubgroupArithmetic => false;
+
// Whether the host reads a linked program's call records at run time, through descriptor set 1.
bool RuntimeCallRecordsSupported => false;
@@ -107,10 +115,24 @@ public interface IShaderPipelineHost
// emitted as real 64-bit atomics instead of a non-atomic 32-bit pair.
bool SharedInt64AtomicsEnabled { get; }
+ // The device supports shaderBufferInt64Atomics, so a 64-bit buffer atomic (BUFFER_ATOMIC_*_X2) is
+ // one 64-bit atomic instead of a pair of 32-bit ones, which is not atomic as a pair.
+ bool BufferInt64AtomicsEnabled => false;
+
// The device supports shaderImageInt64Atomics, so an atomic on a 64-bit image texel
// (a 32_32 UINT image) can be compiled; without it such a program is rejected.
bool ImageInt64AtomicsEnabled => false;
+
+ // The device supports shaderDeviceClock, so a program can read a running clock.
+ bool ShaderDeviceClockEnabled => false;
bool ShaderSignedZeroInfNanPreserveFloat32Supported => false;
+
+ // The device was created with robustBufferAccess2: a storage buffer access past its descriptor's range reads zero and
+ // writes nothing.
+ bool RobustBufferAccess2Enabled => false;
+
+ // The device was created with shaderFloat16 and converts f16 exactly under float controls (NativeFloat16Conversions).
+ bool NativeFloat16Conversions => false;
bool ExecGuardElisionEnabled => true;
ShaderPrewarmList? ShaderPrewarm => null;
GraphicsPrewarmList? GraphicsPrewarm => null;
@@ -144,6 +166,16 @@ public interface IShaderPipelineHost
// out of the pipeline key instead of splitting one pipeline per bounds a draw happens to use.
bool DepthBoundsInPipelineState => true;
+ // The device has the bindless heap set (descriptor indexing with update-after-bind and partially bound arrays, and
+ // null descriptors): an image or sampler read from one heap V# at an index the host cannot evaluate becomes a heap
+ // record instead of rejecting the program.
+ bool SupportsBindlessHeap => false;
+
+ // The host's translator implements storage image channel maps read from shader data (RuntimeImageSwizzle): the plan
+ // then moves a storage image's destination select out of the specialization. False keeps the select in the
+ // specialization (the MSL translator refuses a program that reads it from shader data).
+ bool RuntimeImageSwizzlesSupported => false;
+
// The sample counts a pipeline without attachments can rasterize at.
GpuSampleCount NoAttachmentSampleCounts { get; }
@@ -232,6 +264,28 @@ bool TryCreateGraphicsPipeline(GraphicsPipelineDescription description, out Pipe
return true;
}
+ // The host implements WaitForGraphicsPipeline: a draw that must have its pipeline starts the compile with
+ // TryCreateGraphicsPipeline and waits in WaitForGraphicsPipeline outside the pipeline cache's lock. False keeps
+ // the compile blocking in CreateGraphicsPipeline under that lock.
+ bool WaitsForGraphicsPipelines => false;
+
+ // Blocks until the compile TryCreateGraphicsPipeline left running for this description is done. The caller holds no
+ // pipeline cache lock, so programs of later draws resolve meanwhile.
+ void WaitForGraphicsPipeline(GraphicsPipelineDescription description)
+ {
+ }
+
+ // A pixel program was created; the host can start compiling what depends on the program alone.
+ void PixelProgramCreated(ShaderProgramInfo program, ulong module)
+ {
+ }
+
+ // A vertex or mesh program was recorded for the prewarm under prewarmIdentity (ShaderPrewarmList.Identity); the host
+ // records the states it compiles the program's pre-rasterization libraries with.
+ void VertexProgramRecorded(ulong module, ulong prewarmIdentity)
+ {
+ }
+
PipelineHandle CreateComputePipeline(ComputePipelineDescription description);
Task? GetComputePipelineCompletion(ShaderProgram program) => null;
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/LinkedPrewarmOrder.cs b/src/SharpEmu.Libs/Gpu/Pipelines/LinkedPrewarmOrder.cs
new file mode 100644
index 000000000..9a6deb575
--- /dev/null
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/LinkedPrewarmOrder.cs
@@ -0,0 +1,33 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+using SharpEmu.Libs.VideoOut;
+using SharpEmu.ShaderCompiler.Resources;
+
+namespace SharpEmu.Libs.Gpu.Pipelines;
+
+// The order in which the boot prewarm compiles the linked records of earlier sessions (ComputePrewarmRecord with linked
+// callees), as a public contract for a backend outside this assembly (the Metal backend; Libs gives extracted backends
+// public contracts only). It is upstream's background lane order (ShaderPrewarmQueue.LinkedLaneOrder, used by
+// VulkanVideoPresenter.StartLinkedPrewarm): every caller's first record before any caller's second; a caller's first is
+// the record whose library links the callees an earlier session kept for it (ShaderCallUnionStore, the library a session
+// links first), else its oldest, and its others follow newest first; within a round, callers a session saw compile for
+// minutes (ShaderPrewarmList.IsSlowLinkedCompile) go first, then the order in which callers were first recorded.
+public static class LinkedPrewarmOrder
+{
+ // Whether the record is a linked permutation (its program holds callees).
+ public static bool IsLinked(ComputePrewarmRecord record) => record.Linked is not null;
+
+ // The linked records in the lane's order. linkedDirectory: the host's LinkedProgramCacheDirectory (null keeps none).
+ public static T[] Order(IReadOnlyList records, Func record, ShaderPrewarmList list,
+ string? linkedDirectory) =>
+ Order(records, item => record(item).Hash, item => record(item).Linked, list.IsSlowLinkedCompile, linkedDirectory);
+
+ internal static T[] Order(IReadOnlyList records, Func caller, Func linked,
+ Func slow, string? linkedDirectory)
+ {
+ var kept = ShaderCallUnionStore.Open(linkedDirectory);
+ return ShaderPrewarmQueue.LinkedLaneOrder(records, caller, slow,
+ item => linked(item) is { } library && kept.KeepsCalleesOf(ShaderStage.Compute, caller(item), library));
+ }
+}
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/LinkedShaderPrewarm.cs b/src/SharpEmu.Libs/Gpu/Pipelines/LinkedShaderPrewarm.cs
new file mode 100644
index 000000000..dbf820d0e
--- /dev/null
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/LinkedShaderPrewarm.cs
@@ -0,0 +1,148 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+using System.Buffers.Binary;
+using SharpEmu.ShaderCompiler;
+
+namespace SharpEmu.Libs.Gpu.Pipelines;
+
+// The exact library used by one linked program, independent of live tables and the next session's latest union.
+// Code is stored once per target address; sites retain target order, arguments and return registers.
+internal sealed record LinkedShaderPrewarm(bool RuntimeRecords, bool CallMarks, bool BindlessHeap,
+ LinkedPrewarmFunction[] Functions, LinkedPrewarmSite[] Sites)
+{
+ public static LinkedShaderPrewarm Capture(ShaderCallLibrary library, bool runtimeRecords, bool callMarks, bool bindlessHeap)
+ {
+ var functions = library.Calls.SelectMany(site => site.Targets).Select(target => target.Address).Distinct().Order()
+ .Select(address => new LinkedPrewarmFunction(address, library.CodeRuns[address]
+ .Select(run => new CodeRange(run.Address, run.Bytes.ToArray())).ToArray())).ToArray();
+ var sites = library.Calls.Select(site => new LinkedPrewarmSite(
+ site.Pc, site.AddressRegister, site.ArgumentRegister, site.ReturnRegister, site.ReturnAddress,
+ site.Targets.Select(target => new LinkedPrewarmTarget(target.Address, target.Argument)).ToArray())).ToArray();
+ return new(runtimeRecords, callMarks, bindlessHeap, functions, sites);
+ }
+
+ public Gen5ShaderProgram Link(Gen5ShaderProgram caller)
+ {
+ var functions = new Dictionary();
+ foreach (var function in Functions)
+ {
+ var memory = new ReplayCpuMemory(function.Ranges);
+ var decoded = ShaderFunctionReader.Read(function.Address, (ulong address, out uint word) =>
+ {
+ Span bytes = stackalloc byte[sizeof(uint)];
+ var read = memory.TryRead(address, bytes);
+ word = read ? BinaryPrimitives.ReadUInt32LittleEndian(bytes) : 0;
+ return read;
+ });
+ if (!decoded.Complete)
+ throw new InvalidOperationException($"The prewarm callee cannot be decoded: address=0x{function.Address:X16} {decoded.Error}");
+ functions.Add(function.Address, decoded.Program);
+ }
+
+ var sites = Sites.Select(site => new ShaderCallSite(site.Pc, site.AddressRegister, site.ArgumentRegister,
+ site.ReturnRegister, site.ReturnAddress, site.Targets.Select(target => new ShaderCallTarget(
+ target.Address, target.Argument, functions[target.Address])).ToArray())).ToArray();
+ // The captured library already excludes any callees runtime linking refused. Replay must not drop more.
+ return Gen5ShaderCallLinker.Link(caller, sites, RuntimeRecords);
+ }
+
+ public void Write(BinaryWriter writer)
+ {
+ writer.Write(RuntimeRecords);
+ writer.Write(CallMarks);
+ writer.Write(BindlessHeap);
+ writer.Write(Functions.Length);
+ foreach (var function in Functions)
+ {
+ writer.Write(function.Address);
+ writer.Write(function.Ranges.Length);
+ foreach (var range in function.Ranges)
+ {
+ writer.Write(range.Address);
+ writer.Write(range.Bytes.Length);
+ writer.Write(range.Bytes);
+ }
+ }
+ writer.Write(Sites.Length);
+ foreach (var site in Sites)
+ {
+ writer.Write(site.Pc);
+ writer.Write(site.AddressRegister);
+ writer.Write(site.ArgumentRegister);
+ writer.Write(site.ReturnRegister);
+ writer.Write(site.ReturnAddress);
+ writer.Write(site.Targets.Length);
+ foreach (var target in site.Targets)
+ {
+ writer.Write(target.Address);
+ writer.Write(target.Argument);
+ }
+ }
+ }
+
+ public static LinkedShaderPrewarm Read(BinaryReader reader)
+ {
+ var runtimeRecords = reader.ReadBoolean();
+ var callMarks = reader.ReadBoolean();
+ var bindlessHeap = reader.ReadBoolean();
+ if (callMarks && !runtimeRecords) throw new ArgumentException("Prewarm call marks require runtime records.");
+ var functions = new LinkedPrewarmFunction[Count(reader, 12)];
+ var addresses = new HashSet();
+ for (var index = 0; index < functions.Length; index++)
+ {
+ var address = reader.ReadUInt64();
+ if (!addresses.Add(address)) throw new ArgumentException("Duplicate prewarm callee address.");
+ var ranges = new CodeRange[Count(reader, 16)];
+ if (ranges.Length == 0) throw new ArgumentException("The prewarm callee has no code.");
+ ulong end = 0;
+ for (var run = 0; run < ranges.Length; run++)
+ {
+ var start = reader.ReadUInt64();
+ var length = Count(reader, 1);
+ if (length == 0 || (length & 3) != 0 || (start & 3) != 0 ||
+ start < address || (run != 0 && start < end) || start > ulong.MaxValue - (ulong)length)
+ throw new ArgumentException("Invalid prewarm callee code range.");
+ var bytes = reader.ReadBytes(length);
+ if (bytes.Length != length) throw new EndOfStreamException();
+ ranges[run] = new CodeRange(start, bytes);
+ end = start + (ulong)length;
+ }
+ functions[index] = new LinkedPrewarmFunction(address, ranges);
+ }
+ var sites = new LinkedPrewarmSite[Count(reader, 28)];
+ var pcs = new HashSet();
+ for (var index = 0; index < sites.Length; index++)
+ {
+ var pc = reader.ReadUInt32();
+ if (!pcs.Add(pc)) throw new ArgumentException("Duplicate prewarm call site.");
+ var addressRegister = reader.ReadUInt32();
+ var argumentRegister = reader.ReadUInt32();
+ var returnRegister = reader.ReadUInt32();
+ var returnAddress = reader.ReadUInt64();
+ var targets = new LinkedPrewarmTarget[Count(reader, 16)];
+ for (var target = 0; target < targets.Length; target++)
+ {
+ var address = reader.ReadUInt64();
+ var argument = reader.ReadUInt64();
+ if (!addresses.Contains(address)) throw new ArgumentException("The prewarm call target has no code.");
+ targets[target] = new LinkedPrewarmTarget(address, argument);
+ }
+ sites[index] = new LinkedPrewarmSite(pc, addressRegister, argumentRegister, returnRegister, returnAddress, targets);
+ }
+ return new(runtimeRecords, callMarks, bindlessHeap, functions, sites);
+ }
+
+ private static int Count(BinaryReader reader, int minimumBytes)
+ {
+ var count = reader.ReadInt32();
+ if (count < 0 || count > (reader.BaseStream.Length - reader.BaseStream.Position) / minimumBytes)
+ throw new ArgumentException("The prewarm linked record count is out of range.");
+ return count;
+ }
+}
+
+internal sealed record LinkedPrewarmFunction(ulong Address, CodeRange[] Ranges);
+internal sealed record LinkedPrewarmTarget(ulong Address, ulong Argument);
+internal sealed record LinkedPrewarmSite(uint Pc, uint AddressRegister, uint ArgumentRegister, uint ReturnRegister,
+ ulong ReturnAddress, LinkedPrewarmTarget[] Targets);
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/MeshDrawPlanner.cs b/src/SharpEmu.Libs/Gpu/Pipelines/MeshDrawPlanner.cs
index 4147e16f8..155cd69b5 100644
--- a/src/SharpEmu.Libs/Gpu/Pipelines/MeshDrawPlanner.cs
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/MeshDrawPlanner.cs
@@ -14,6 +14,9 @@ internal readonly record struct MeshDrawPlan
internal static class MeshDrawPlanner
{
+ // A primitive shader subgroup exports at most 256 primitives.
+ private const uint MaximumSubgroupPrimitives = 256;
+
internal static MeshDrawPlan? Create(VertexStageRegisters vertex,
ShaderInterfaceRegisters shaderInterface, ContextRegisters context,
UserConfigRegisters userConfig, MeshShaderLimits limits, uint subgroupSize)
@@ -47,8 +50,25 @@ internal static class MeshDrawPlanner
var outputPrimitiveCapacity = fusedGeometry
? checked((uint)group.PrimitiveGroupSize * (verticesPerPrimitive - 2))
: (uint)group.PrimitiveGroupSize;
- var threadsPerGroup = checked(((outputVertexCapacity + waveSize - 1) / waveSize) * waveSize);
- var deviceInvocationCount = waveSize == 64 && subgroupSize == 32 ? threadsPerGroup / 2 : threadsPerGroup;
+ var threadsPerGroup = WholeWaves(outputVertexCapacity, waveSize);
+ // GE_NGG_SUBGRP_CNTL.PRIM_AMP_FACTOR bounds the primitives one input primitive produces. A mesh-style primitive
+ // shader (one input point per subgroup) exports its own triangles, more than a strip of VGT_GS_MAX_VERT_OUT
+ // vertices holds, and each lane exports one of them, so the subgroup needs a lane per primitive too. The plan
+ // only grows, and only while the device can run it.
+ var amplification = shaderInterface.PrimitiveShaderSubgroupControl & 0x1FFu;
+ if (fusedGeometry && amplification != 0)
+ {
+ var amplified = Math.Min(MaximumSubgroupPrimitives, checked((uint)group.PrimitiveGroupSize * amplification));
+ var amplifiedThreads = WholeWaves(Math.Max(outputVertexCapacity, amplified), waveSize);
+ var amplifiedInvocations = DeviceInvocations(amplifiedThreads, waveSize, subgroupSize);
+ if (amplified > outputPrimitiveCapacity && amplified <= limits.OutputPrimitiveCapacity &&
+ amplifiedInvocations <= limits.MaxInvocations && amplifiedInvocations <= limits.MaxWorkGroupSizeX)
+ {
+ outputPrimitiveCapacity = amplified;
+ threadsPerGroup = amplifiedThreads;
+ }
+ }
+ var deviceInvocationCount = DeviceInvocations(threadsPerGroup, waveSize, subgroupSize);
var localDataShareDwords = (uint)vertex.GeometryResource2.LocalDataShareSize * 128;
var sharedBytes = checked((localDataShareDwords + outputVertexCapacity + 5) * sizeof(uint));
if (inputPrimitiveCountPerWorkgroup == 0 || deviceInvocationCount > limits.MaxInvocations || deviceInvocationCount > limits.MaxWorkGroupSizeX ||
@@ -87,4 +107,10 @@ subgroupSize is not (32 or 64) || subgroupSize > waveSize ||
},
};
}
+
+ private static uint WholeWaves(uint threads, uint waveSize) => checked((threads + waveSize - 1) / waveSize * waveSize);
+
+ // A wave64 subgroup runs as two 32-lane halves on a 32-lane device.
+ private static uint DeviceInvocations(uint threads, uint waveSize, uint subgroupSize) =>
+ waveSize == 64 && subgroupSize == 32 ? threads / 2 : threads;
}
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.TableScan.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.TableScan.cs
new file mode 100644
index 000000000..553fe63f2
--- /dev/null
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.TableScan.cs
@@ -0,0 +1,310 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+using System.Runtime.InteropServices;
+using System.Runtime.Intrinsics;
+using SharpEmu.ShaderCompiler;
+using SharpEmu.ShaderCompiler.Resources;
+
+namespace SharpEmu.Libs.Gpu.Pipelines;
+
+// The read of a run-time-record caller's tables in one pass per table. A ray tracer's hit table reserves far more
+// records than a frame fills (megabytes of records, a few thousand of them live), and every pass reads it. The
+// per-record read keeps a set of records per site and a ShaderCallTarget per record, then derives the library's records
+// and each site's distinct callees from those (WithRuntimeArguments). This read skips zero targets four records at a
+// time and keeps only what the library holds: each site's distinct callees by address in first occurrence, and the
+// distinct records of all sites in first occurrence, site by site. The library it returns equals the per-record read's
+// (records, sites, code hashes and runs, current code hashes in the same order, current sites); each function is read
+// and validated once per address and read, as the per-record read does, and every failure throws the same exception.
+// On by default; SHARPEMU_CALL_TABLE_SCAN=0, or any value but 1, turns it off.
+internal sealed partial record ShaderCallLibrary
+{
+ internal enum TableScanMode { Off, On }
+
+ internal static readonly TableScanMode ConfiguredTableScan =
+ Environment.GetEnvironmentVariable("SHARPEMU_CALL_TABLE_SCAN") switch
+ {
+ null or "" or "1" => TableScanMode.On,
+ _ => TableScanMode.Off,
+ };
+
+ // Tests: this thread's mode, whatever the configuration.
+ [ThreadStatic] internal static TableScanMode? TableScanOverride;
+
+ internal static TableScanMode TableScan => TableScanOverride ?? ConfiguredTableScan;
+
+ // The host reads the tables and the functions they name as it reads any shader code and resource table, so bytes
+ // the GPU wrote are brought back and an image the GPU wrote over memory the game has since reused does not refuse
+ // the game's own bytes.
+ // With memo (call-library reuse), a run-time-record library whose topology a previous read derived reuses it
+ // (ShaderCallLibraryMemo.Runtime); the tables and functions are read as without it.
+ // With runtimeArguments and the table scan on, the tables are read in one pass each (see above).
+ public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable memory,
+ ResourceSnapshot snapshot, GuestWordReader read, ShaderFunctionCache? functionCache = null, bool runtimeArguments = false,
+ uint userDataBase = 0, ResidentGuestBytesReader? readBytes = null, ShaderCallLibraryMemo? memo = null)
+ {
+ var mode = runtimeArguments && BitConverter.IsLittleEndian ? TableScan : TableScanMode.Off;
+ if (mode == TableScanMode.Off)
+ return ReadOriginal(caller, memory, snapshot, read, functionCache, runtimeArguments, userDataBase, readBytes, memo);
+ return ReadScanned(caller, memory, snapshot, read, functionCache, userDataBase, readBytes, memo);
+ }
+
+ // ReadOriginal with runtimeArguments, in one pass per table. The checks, their order and their exceptions are the
+ // original's; the records, sites, code hashes and runs and current sites it derives are the ones the original's
+ // collections yield.
+ private static ShaderCallLibrary ReadScanned(Gen5ShaderProgram caller, MemoryAccessTable memory, ResourceSnapshot snapshot,
+ GuestWordReader read, ShaderFunctionCache? functionCache, uint userDataBase, ResidentGuestBytesReader? readBytes,
+ ShaderCallLibraryMemo? memo)
+ {
+ var scan = _tableScan ??= new TableScanState();
+ scan.Begin(caller.Address, functionCache, read);
+ try
+ {
+ var calls = new List();
+ foreach (var callSite in CallSites(caller, userDataBase, (uint)snapshot.UserData.Length))
+ {
+ if (callSite.Refusal is { } refusal) throw new InvalidOperationException(refusal);
+ var call = caller.Instructions[callSite.Index];
+ if (callSite.UserData is { } userData)
+ {
+ // A function pointer the dispatch passes in user data: one target, read as the original's Target reads it.
+ var userTarget = UserDataPair(snapshot, userDataBase, userData.Target);
+ var userArgument = UserDataPair(snapshot, userDataBase, userData.Argument);
+ var userArgumentRegister = call.Sources[0].Value + 2;
+ var userReturn = unchecked(caller.Address + call.ProgramOffset + (ulong)call.Words.Count * sizeof(uint));
+ var userTargets = new List(1);
+ if (userTarget != 0)
+ {
+ scan.BeginSite(call.Pc, userTargets, 0);
+ scan.VisitUserTarget(userTarget, userArgument);
+ }
+
+ calls.Add(new(call.Pc, call.Sources[0].Value, userArgumentRegister, call.Destinations[0].Value, userReturn, userTargets));
+ continue;
+ }
+
+ var load = callSite.Load!;
+ var loadControl = (Gen5ScalarMemoryControl)load.Control!;
+ var argumentRegister = callSite.ArgumentRegister;
+ var access = memory.Find(load.Pc);
+ if (access is null || access.Resource >= snapshot.Buffers.Length)
+ throw new InvalidOperationException("The shader call table has no materialized buffer.");
+ var descriptor = snapshot.Buffers[access.Resource];
+ var address = descriptor[0] | ((ulong)(descriptor[1] & 0xFFFF) << 32);
+ var stride = (descriptor[1] >> 16) & 0x3FFF;
+ var size = (ulong)descriptor[2] * Math.Max(stride, 1u);
+ var returnAddress = unchecked(caller.Address + call.ProgramOffset + (ulong)call.Words.Count * sizeof(uint));
+ if (size == 0)
+ {
+ calls.Add(new(call.Pc, call.Sources[0].Value, argumentRegister, call.Destinations[0].Value, returnAddress, []));
+ continue;
+ }
+
+ if (size > MaxRuntimeTableBytes || (size & 15) != 0 || (descriptor[1] & 0x80000000) != 0)
+ throw new InvalidOperationException(
+ $"The shader call table extent or layout is not supported: address=0x{address:X} stride={stride} records={descriptor[2]} " +
+ $"swizzle={descriptor[1] >> 31} dynamic={loadControl.DynamicOffsetRegister.HasValue} offset={loadControl.ImmediateOffsetBytes}.");
+ ReadOnlySpan table = ReadTable(address, (int)size, read, readBytes);
+ if ((ulong)table.Length != size)
+ throw new InvalidOperationException(
+ $"The shader call table is not CPU-readable at this submission: address=0x{address:X} bytes={size} readable={table.Length}.");
+ var targets = new List();
+ var firstRecord = checked((int)loadControl.ImmediateOffsetBytes);
+ if (firstRecord < 0 || (firstRecord & 15) != 0 || firstRecord > table.Length - 16)
+ throw new InvalidOperationException("The shader call record is outside the table or is not aligned.");
+ var recordEnd = loadControl.DynamicOffsetRegister.HasValue ? table.Length : firstRecord + 16;
+ scan.BeginSite(call.Pc, targets, address);
+ ScanRecords(scan, MemoryMarshal.Cast(table[firstRecord..recordEnd]), firstRecord / 16);
+ calls.Add(new(call.Pc, call.Sources[0].Value, argumentRegister, call.Destinations[0].Value, returnAddress, targets));
+ }
+
+ var records = scan.TakeRecords();
+ return (memo?.Runtime(caller, calls, scan.CodeHashes, scan.CodeRuns, records) ??
+ WithRuntimeArguments(caller, calls, scan.CodeHashes, scan.CodeRuns, records)) with
+ {
+ CurrentSites = scan.CurrentSites,
+ };
+ }
+ finally
+ {
+ scan.End();
+ }
+ }
+
+ // Each record of a table whose target is nonzero, in order (words: the records' target and argument words, little
+ // endian; first: the first record's index in the table). A zero target names no call; four records whose targets are
+ // all zero are skipped together.
+ private static void ScanRecords(TableScanState scan, ReadOnlySpan words, int first)
+ {
+ var index = 0;
+ if (Vector256.IsHardwareAccelerated && words.Length >= 8)
+ {
+ ref var start = ref MemoryMarshal.GetReference(words);
+ var targets = Vector256.Create(ulong.MaxValue, 0UL, ulong.MaxValue, 0UL);
+ for (; index <= words.Length - 8; index += 8)
+ {
+ var low = Vector256.LoadUnsafe(ref start, (nuint)index);
+ var high = Vector256.LoadUnsafe(ref start, (nuint)(index + 4));
+ if (((low | high) & targets) == Vector256.Zero) continue;
+ for (var word = index; word < index + 8; word += 2)
+ {
+ if (words[word] != 0) scan.Visit(words[word], words[word + 1], first + (word >> 1));
+ }
+ }
+ }
+
+ for (; index < words.Length; index += 2)
+ {
+ if (words[index] != 0) scan.Visit(words[index], words[index + 1], first + (index >> 1));
+ }
+ }
+
+ [ThreadStatic] private static TableScanState? _tableScan;
+
+ // One thread's state of a scanned read. The collections a library holds are made for each read; the rest is kept.
+ private sealed class TableScanState
+ {
+ // A callee the tables named in this read: its target as a library's site holds it (argument 0), null until its
+ // function is read; whether a table record could not read it (the original's unreadable set: its later table
+ // records are left out, also when a user-data site reads it after all); and the last site that named it.
+ private sealed class Callee
+ {
+ public ShaderCallTarget? Target;
+ public bool Unreadable;
+ public int Site;
+ }
+
+ private readonly Dictionary _callees = new();
+ private readonly HashSet<(ulong Target, ulong Argument)> _seen = new();
+ private (ulong Target, ulong Argument)[] _records = new (ulong, ulong)[256];
+ private int _recordCount;
+ private int _site;
+ private uint _sitePc;
+ private ulong _table;
+ private ulong _caller;
+ private List? _siteTargets;
+ private ShaderFunctionCache? _functionCache;
+ private GuestWordReader? _read;
+
+ public Dictionary CodeHashes = [];
+ public Dictionary CodeRuns = [];
+ public Dictionary> CurrentSites = [];
+
+ public void Begin(ulong caller, ShaderFunctionCache? functionCache, GuestWordReader read)
+ {
+ _caller = caller;
+ _functionCache = functionCache;
+ _read = read;
+ CodeHashes = [];
+ CodeRuns = [];
+ CurrentSites = [];
+ _site = 0;
+ _recordCount = 0;
+ }
+
+ public void End()
+ {
+ _callees.Clear();
+ _seen.Clear();
+ _recordCount = 0;
+ _siteTargets = null;
+ _functionCache = null;
+ _read = null;
+ }
+
+ public void BeginSite(uint pc, List targets, ulong table)
+ {
+ _site++;
+ _sitePc = pc;
+ _siteTargets = targets;
+ _table = table;
+ }
+
+ // A table record with a nonzero target, as the original's loop takes it: a target whose function cannot be read
+ // leaves the record out, and every later table record naming it in this read.
+ public void Visit(ulong target, ulong argument, int record)
+ {
+ if (!_callees.TryGetValue(target, out var callee))
+ {
+ callee = new Callee();
+ _callees.Add(target, callee);
+ var result = ReadFunction(target);
+ if (!result.Complete)
+ {
+ callee.Unreadable = true;
+ if (Interlocked.Increment(ref _unreadableTargetReports) <= 8)
+ {
+ Console.Error.WriteLine(
+ $"[GPU][WARN][LINKED_PROGRAM] A call table record names a function that cannot be read; its calls return at once: " +
+ $"caller=0x{_caller:X} table=0x{_table:X} record={record} target=0x{target:X} error={result.Error}.");
+ }
+
+ return;
+ }
+
+ Resolve(callee, target, result);
+ }
+ else if (callee.Unreadable)
+ {
+ return;
+ }
+
+ Name(callee, target);
+ AddRecord(target, argument);
+ }
+
+ // A user-data site's target, as the original's Target reads it: a function a table record could not read is read
+ // again, and a failure throws.
+ public void VisitUserTarget(ulong target, ulong argument)
+ {
+ if (!_callees.TryGetValue(target, out var callee) || callee.Target is null)
+ {
+ var result = ReadFunction(target);
+ if (!result.Complete) throw new ShaderFunctionReadException(target, result);
+ if (callee is null)
+ {
+ callee = new Callee();
+ _callees.Add(target, callee);
+ }
+
+ Resolve(callee, target, result);
+ }
+
+ Name(callee, target);
+ AddRecord(target, argument);
+ }
+
+ public (ulong Target, ulong Argument)[] TakeRecords() => _records.AsSpan(0, _recordCount).ToArray();
+
+ private ShaderFunctionReadResult ReadFunction(ulong address) =>
+ _functionCache?.Read(address, _read!) ?? ShaderFunctionReader.Read(address, _read!);
+
+ private void Resolve(Callee callee, ulong address, ShaderFunctionReadResult result)
+ {
+ callee.Target = new ShaderCallTarget(address, 0, result.Program);
+ CodeHashes.Add(address, CodeDigest(result));
+ CodeRuns.Add(address, result.Runs);
+ }
+
+ // The site holds each callee once, in first occurrence, and the callee's current sites name the site.
+ private void Name(Callee callee, ulong address)
+ {
+ if (callee.Site == _site) return;
+ callee.Site = _site;
+ _siteTargets!.Add(callee.Target!);
+ if (!CurrentSites.TryGetValue(address, out var namedAt))
+ {
+ CurrentSites.Add(address, namedAt = []);
+ }
+
+ namedAt.Add(_sitePc);
+ }
+
+ private void AddRecord(ulong target, ulong argument)
+ {
+ if (!_seen.Add((target, argument))) return;
+ if (_recordCount == _records.Length) Array.Resize(ref _records, _records.Length * 2);
+ _records[_recordCount++] = (target, argument);
+ }
+ }
+}
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.cs
index 9770d7ba9..86dea22d3 100644
--- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.cs
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.cs
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary;
+using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using SharpEmu.ShaderCompiler;
using SharpEmu.ShaderCompiler.Ir;
@@ -16,15 +17,24 @@ internal sealed record UnitedCallee(ShaderCallTarget Target, byte[] Code, (ulong
// Identity names the tables and code exactly. LayoutIdentity names them up to the values of the records' arguments: it
// keeps which records share an argument and which have none. A game rebuilds its tables with the argument data
// elsewhere as often as every frame; such a table links to the same program, whose plan and module read Arguments (the
-// distinct nonzero record arguments, Gen5ShaderCallLinker.CallEntryArguments) from each dispatch.
-internal sealed record ShaderCallLibrary(string Identity, IReadOnlyList Calls, string LayoutIdentity,
+// distinct nonzero record arguments, Gen5ShaderCallLinker.CallEntryArguments) from each dispatch. A library read with
+// runtimeArguments holds its records as dispatch data (Records): its Identity is its LayoutIdentity.
+internal sealed partial record ShaderCallLibrary(string Identity, IReadOnlyList Calls, string LayoutIdentity,
ulong[] Arguments)
{
private const ulong MaxTableBytes = 65536;
// With runtimeArguments a site links each callee once, so a table's size sets only how many records the host reads and
- // resolves at each dispatch.
- private const ulong MaxRuntimeTableBytes = 1 << 20;
+ // resolves at each dispatch. A ray tracer's hit table can reserve hundreds of thousands of records: up to 16 MiB.
+ private const ulong MaxRuntimeTableBytes = 16 << 20;
+
+ private static int _unreadableTargetReports;
+
+ // Each callee's code hash, computed once for the decoded function the function cache returns while its code is unchanged.
+ private static readonly ConditionalWeakTable CodeDigests = new();
+
+ private static byte[] CodeDigest(ShaderFunctionReadResult function) =>
+ CodeDigests.GetValue(function, static result => SHA256.HashData(result.Bytes));
// Read with runtimeArguments, a site's Calls hold each callee once (in the order of their code, so the program does not
// depend on the tables' order), LayoutIdentity names only the sites and the callees' code, and Records holds every
@@ -37,7 +47,7 @@ internal sealed record ShaderCallLibrary(string Identity, IReadOnlyList CodeHashes { get; init; } = [];
- // The words each callee's decode read, by address, when read with runtimeArguments.
+ // The words each callee's decode read, by address; also retained for exact prewarm replay of static links.
public Dictionary CodeRuns { get; init; } = [];
// The hash of the code at each address the tables name, as this dispatch read it; CodeHashes holds the code the library
@@ -47,68 +57,96 @@ internal sealed record ShaderCallLibrary(string Identity, IReadOnlyList> CurrentSites { get; init; } = [];
- // The host reads the tables and the functions they name as it reads any shader code and resource table, so bytes
- // the GPU wrote are brought back and an image the GPU wrote over memory the game has since reused does not refuse
- // the game's own bytes.
- public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable memory,
- ResourceSnapshot snapshot, GuestWordReader read, ShaderFunctionCache? functionCache = null, bool runtimeArguments = false)
+ // With call-library reuse on, the token of this library's topology: every field but Records, CurrentCodeHashes and
+ // CurrentSites, which are this dispatch's own (ShaderCallLibraryMemo). Null otherwise.
+ internal object? Topology { get; init; }
+
+ // Read without the one-pass table scan (ShaderCallLibrary.TableScan.cs), which is also the scan's reference.
+ private static ShaderCallLibrary ReadOriginal(Gen5ShaderProgram caller, MemoryAccessTable memory,
+ ResourceSnapshot snapshot, GuestWordReader read, ShaderFunctionCache? functionCache, bool runtimeArguments,
+ uint userDataBase, ResidentGuestBytesReader? readBytes, ShaderCallLibraryMemo? memo)
{
- using var identity = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
- using var layout = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+ // A runtime-argument library names its sites from the callees' code hashes (WithRuntimeSites), so its read hashes
+ // neither the tables nor the code.
+ using var identity = runtimeArguments ? null : IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+ using var layout = runtimeArguments ? null : IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
var calls = new List();
var functions = new Dictionary();
var codeHashes = new Dictionary();
var codeRuns = new Dictionary();
var currentSites = new Dictionary>();
- foreach (var (call, index) in caller.Instructions.Select((instruction, index) => (instruction, index)))
+
+ var unreadable = new HashSet();
+
+ // A target a site names: its function, read once per library, joins both identities.
+ ShaderCallTarget Target(uint site, ulong address, ulong argument) =>
+ TryTarget(site, address, argument, out var target, out var failure)
+ ? target
+ : throw new ShaderFunctionReadException(address, failure!);
+
+ bool TryTarget(uint site, ulong address, ulong argument, out ShaderCallTarget target, out ShaderFunctionReadResult? failure)
{
- if (call.Opcode != "SSwappcB64") continue;
- if (call.Sources.Count != 1 || call.Destinations.Count != 1 ||
- call.Sources[0].Kind != Gen5OperandKind.ScalarRegister || call.Destinations[0].Kind != Gen5OperandKind.ScalarRegister)
- throw new InvalidOperationException("The shader call does not use a supported table record.");
- Gen5ShaderInstruction load;
- Gen5ScalarMemoryControl loadControl;
- uint argumentRegister = 0;
- if (TryFindDirectRecordLoads(caller, index, out var targetLoad, out var directArgumentRegister))
+ target = null!;
+ failure = null;
+ if (!functions.TryGetValue(address, out var function))
{
- load = targetLoad;
- loadControl = (Gen5ScalarMemoryControl)targetLoad.Control!;
- argumentRegister = directArgumentRegister;
- }
- else
- {
- if (index < 6) throw new InvalidOperationException("The shader call does not use a supported table record.");
- var loadIndex = index - 6;
- while (loadIndex >= 0 && caller.Instructions[loadIndex] is { Opcode: "VMovB32", Destinations.Count: 1 } vectorMove &&
- vectorMove.Destinations[0].Kind == Gen5OperandKind.VectorRegister) loadIndex--;
- if (loadIndex < 0) throw new InvalidOperationException("The shader call table load is missing.");
- load = caller.Instructions[loadIndex];
- if (load.Opcode != "SBufferLoadDwordx4" || load.Control is not Gen5ScalarMemoryControl recordControl ||
- load.Destinations.Count != 4 || caller.Instructions[index - 5].Opcode != "SWaitcnt")
- throw new InvalidOperationException("The shader call table load is not supported.");
- loadControl = recordControl;
- if (loadControl.DynamicOffsetRegister is { } selector)
+ var result = functionCache?.Read(address, read) ?? ShaderFunctionReader.Read(address, read);
+ if (!result.Complete)
+ {
+ failure = result;
+ return false;
+ }
+
+ function = result.Program;
+ identity?.AppendData(result.Bytes);
+ layout?.AppendData(result.Bytes);
+ functions.Add(address, function);
+ if (runtimeArguments)
{
- var scale = caller.Instructions.Take(loadIndex).Reverse().FirstOrDefault(instruction =>
- instruction.Opcode.StartsWith("SCbranch", StringComparison.Ordinal) || instruction.Opcode is "SBranch" or "SSwappcB64" ||
- instruction.Destinations.Any(destination => destination.Kind == Gen5OperandKind.ScalarRegister &&
- selector >= destination.Value && selector - destination.Value < instruction.DestinationWidth));
- if (scale is null || scale.Opcode != "SLshlB32" || scale.Destinations.Count != 1 || scale.Destinations[0] != Gen5Operand.Scalar(selector) ||
- scale.Sources.Count != 2 || scale.Sources[1] != new Gen5Operand(Gen5OperandKind.EncodedConstant, 132))
- throw new InvalidOperationException("The shader call table does not use 16-byte records.");
+ codeHashes.Add(address, CodeDigest(result));
}
- for (var component = 0; component < 4; component++)
+ codeRuns.Add(address, result.Runs);
+ }
+
+ if (runtimeArguments)
+ {
+ if (!currentSites.TryGetValue(address, out var namedAt))
{
- var move = caller.Instructions[index - 4 + component];
- if (move.Opcode != "SMovB32" || move.Sources.Count != 1 || move.Destinations.Count != 1 ||
- move.Sources[0] != load.Destinations[component] || move.Destinations[0].Kind != Gen5OperandKind.ScalarRegister)
- throw new InvalidOperationException("The shader call record has an unsupported register transfer.");
- if (component == 2) argumentRegister = move.Destinations[0].Value;
- var expected = component < 2 ? call.Sources[0].Value + (uint)component : argumentRegister + (uint)component - 2;
- if (move.Destinations[0].Value != expected)
- throw new InvalidOperationException("The shader call record does not use register pairs.");
+ currentSites.Add(address, namedAt = []);
}
+
+ namedAt.Add(site);
+ }
+
+ layout?.AppendData(BitConverter.GetBytes(address));
+ target = new(address, argument, function);
+ return true;
+ }
+
+ foreach (var callSite in CallSites(caller, userDataBase, (uint)snapshot.UserData.Length))
+ {
+ if (callSite.Refusal is { } refusal) throw new InvalidOperationException(refusal);
+ var call = caller.Instructions[callSite.Index];
+ if (callSite.UserData is { } userData)
+ {
+ // A function pointer the dispatch passes in user data: one target, which the linked program still checks
+ // against the call registers when the call runs. Its argument is a record argument like a table's.
+ var userTarget = UserDataPair(snapshot, userDataBase, userData.Target);
+ var userArgument = UserDataPair(snapshot, userDataBase, userData.Argument);
+ var userArgumentRegister = call.Sources[0].Value + 2;
+ var userReturn = unchecked(caller.Address + call.ProgramOffset + (ulong)call.Words.Count * sizeof(uint));
+ identity?.AppendData(BitConverter.GetBytes(userTarget));
+ identity?.AppendData(BitConverter.GetBytes(userArgument));
+ layout?.AppendData(BitConverter.GetBytes(call.Pc));
+ layout?.AppendData(BitConverter.GetBytes(userArgumentRegister));
+ List userTargets = userTarget == 0 ? [] : [Target(call.Pc, userTarget, userArgument)];
+ layout?.AppendData(BitConverter.GetBytes(userTargets.Count));
+ calls.Add(new(call.Pc, call.Sources[0].Value, userArgumentRegister, call.Destinations[0].Value, userReturn, userTargets));
+ continue;
}
+ var load = callSite.Load!;
+ var loadControl = (Gen5ScalarMemoryControl)load.Control!;
+ var argumentRegister = callSite.ArgumentRegister;
var access = memory.Find(load.Pc);
if (access is null || access.Resource >= snapshot.Buffers.Length)
throw new InvalidOperationException("The shader call table has no materialized buffer.");
@@ -117,8 +155,8 @@ public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable
var stride = (descriptor[1] >> 16) & 0x3FFF;
var size = (ulong)descriptor[2] * Math.Max(stride, 1u);
var returnAddress = unchecked(caller.Address + call.ProgramOffset + (ulong)call.Words.Count * sizeof(uint));
- layout.AppendData(BitConverter.GetBytes(call.Pc));
- layout.AppendData(BitConverter.GetBytes(argumentRegister));
+ layout?.AppendData(BitConverter.GetBytes(call.Pc));
+ layout?.AppendData(BitConverter.GetBytes(argumentRegister));
if (size == 0)
{
// A buffer without records reads zero for every load: a null target, so the call has no target.
@@ -129,11 +167,11 @@ public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable
throw new InvalidOperationException(
$"The shader call table extent or layout is not supported: address=0x{address:X} stride={stride} records={descriptor[2]} " +
$"swizzle={descriptor[1] >> 31} dynamic={loadControl.DynamicOffsetRegister.HasValue} offset={loadControl.ImmediateOffsetBytes}.");
- var table = ShaderCallDump.ReadPrefix(address, (int)size, read);
+ ReadOnlySpan table = ReadTable(address, (int)size, read, readBytes);
if ((ulong)table.Length != size)
throw new InvalidOperationException(
$"The shader call table is not CPU-readable at this submission: address=0x{address:X} bytes={size} readable={table.Length}.");
- identity.AppendData(table);
+ identity?.AppendData(table);
var targets = new List();
var records = new HashSet<(ulong, ulong)>();
var firstRecord = checked((int)loadControl.ImmediateOffsetBytes);
@@ -142,68 +180,127 @@ public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable
var recordEnd = loadControl.DynamicOffsetRegister.HasValue ? table.Length : firstRecord + 16;
for (var offset = firstRecord; offset < recordEnd; offset += 16)
{
- var target = BinaryPrimitives.ReadUInt64LittleEndian(table.AsSpan(offset));
- var argument = BinaryPrimitives.ReadUInt64LittleEndian(table.AsSpan(offset + 8));
- if (target == 0 || !records.Add((target, argument))) continue;
- if (!functions.TryGetValue(target, out var function))
+ var target = BinaryPrimitives.ReadUInt64LittleEndian(table[offset..]);
+ var argument = BinaryPrimitives.ReadUInt64LittleEndian(table[(offset + 8)..]);
+ if (target == 0 || !records.Add((target, argument)) || unreadable.Contains(target)) continue;
+ if (!runtimeArguments)
{
- var result = functionCache?.Read(target, read) ?? ShaderFunctionReader.Read(target, read);
- if (!result.Complete) throw new ShaderFunctionReadException(target, result);
- function = result.Program;
- identity.AppendData(result.Bytes);
- layout.AppendData(result.Bytes);
- functions.Add(target, function);
- if (runtimeArguments)
- {
- codeHashes.Add(target, SHA256.HashData(result.Bytes));
- codeRuns.Add(target, result.Runs);
- }
+ targets.Add(Target(call.Pc, target, argument));
+ continue;
}
- targets.Add(new(target, argument, function));
- if (runtimeArguments)
+
+ // A table can hold records past the ones the game wrote for this dispatch, naming functions it has since
+ // unloaded, and the GPU never calls those. A record whose function cannot be read is left out: its call
+ // returns at once, as one to a callee the program does not hold does.
+ if (TryTarget(call.Pc, target, argument, out var linked, out var failure))
{
- if (!currentSites.TryGetValue(target, out var namedAt))
- {
- currentSites.Add(target, namedAt = []);
- }
+ targets.Add(linked);
+ continue;
+ }
- namedAt.Add(call.Pc);
+ unreadable.Add(target);
+ if (Interlocked.Increment(ref _unreadableTargetReports) <= 8)
+ {
+ Console.Error.WriteLine(
+ $"[GPU][WARN][LINKED_PROGRAM] A call table record names a function that cannot be read; its calls return at once: " +
+ $"caller=0x{caller.Address:X} table=0x{address:X} record={offset / 16} target=0x{target:X} error={failure!.Error}.");
}
- layout.AppendData(BitConverter.GetBytes(target));
}
- layout.AppendData(BitConverter.GetBytes(targets.Count));
+ layout?.AppendData(BitConverter.GetBytes(targets.Count));
calls.Add(new(call.Pc, call.Sources[0].Value, argumentRegister, call.Destinations[0].Value, returnAddress, targets));
}
- identity.AppendData(BitConverter.GetBytes(caller.Address));
+ identity?.AppendData(BitConverter.GetBytes(caller.Address));
if (runtimeArguments)
- return WithRuntimeArguments(caller, Convert.ToHexString(identity.GetHashAndReset()), calls, codeHashes, codeRuns) with
+ return (memo?.Runtime(caller, calls, codeHashes, codeRuns) ?? WithRuntimeArguments(caller, calls, codeHashes, codeRuns)) with
{
CurrentSites = currentSites,
};
- layout.AppendData(BitConverter.GetBytes(caller.Address));
+ var identityHash = identity!;
+ var layoutHash = layout!;
+ layoutHash.AppendData(BitConverter.GetBytes(caller.Address));
ulong[] recordArguments = [.. calls.SelectMany(site => site.Targets).Select(target => target.Argument)];
ulong[] arguments = [.. recordArguments.Where(argument => argument != 0).Distinct()];
var slotOf = arguments.Select((argument, slot) => (argument, slot)).ToDictionary(entry => entry.argument, entry => entry.slot);
foreach (var argument in recordArguments)
- layout.AppendData(BitConverter.GetBytes(argument == 0 ? -1 : slotOf[argument]));
- return new(Convert.ToHexString(identity.GetHashAndReset()), calls, Convert.ToHexString(layout.GetHashAndReset()), arguments);
+ layoutHash.AppendData(BitConverter.GetBytes(argument == 0 ? -1 : slotOf[argument]));
+ return new(Convert.ToHexString(identityHash.GetHashAndReset()), calls, Convert.ToHexString(layoutHash.GetHashAndReset()), arguments)
+ { CodeRuns = codeRuns };
}
- private static ShaderCallLibrary WithRuntimeArguments(Gen5ShaderProgram caller, string identity, List calls,
- Dictionary codeHashes, Dictionary codeRuns)
+ // A code hash as text. With call-library reuse on, one string per code array: the arrays are never written.
+ internal static string CodeKey(byte[] code) => ShaderCallLibraryMemo.Enabled
+ ? CodeKeys.GetValue(code, static bytes => Convert.ToHexString(bytes))
+ : Convert.ToHexString(code);
+
+ private static readonly ConditionalWeakTable CodeKeys = new();
+
+ // The table bytes of the call site being read; valid until the next table read on this thread.
+ [ThreadStatic]
+ private static byte[]? _tableScratch;
+
+ // A table is copied at once when the host can read it without first bringing back bytes the GPU wrote; otherwise it is
+ // read a word at a time, as the host reads any shader resource. Either way into one buffer per thread: a ray tracer's
+ // table is megabytes, read at each of its dispatches, and a new array each time is a large-object allocation.
+ private static ReadOnlySpan ReadTable(ulong address, int size, GuestWordReader read, ResidentGuestBytesReader? readBytes)
+ {
+ var scratch = _tableScratch;
+ if (scratch is null || scratch.Length < size)
+ {
+ _tableScratch = scratch = new byte[(size + 0xFFFF) & ~0xFFFF];
+ }
+
+ var bytes = scratch.AsSpan(0, size);
+ if (readBytes is not null && readBytes(address, bytes, false))
+ {
+ return bytes;
+ }
+
+ // As ShaderCallDump.ReadPrefix: whole words up to the first unreadable one.
+ var offset = 0;
+ while (offset + sizeof(uint) <= (size & ~3) && address <= ulong.MaxValue - (ulong)offset - 3 &&
+ read(address + (ulong)offset, out var word))
+ {
+ BinaryPrimitives.WriteUInt32LittleEndian(bytes[offset..], word);
+ offset += sizeof(uint);
+ }
+
+ return bytes[..offset];
+ }
+
+ internal static ShaderCallLibrary WithRuntimeArguments(Gen5ShaderProgram caller, List calls,
+ Dictionary codeHashes, Dictionary codeRuns) =>
+ WithRuntimeArguments(caller, calls, codeHashes, codeRuns, RuntimeRecords(calls));
+
+ // The records of a read's sites as a run-time library holds them: every site's distinct target and argument pairs, in
+ // first occurrence, site by site.
+ internal static (ulong Target, ulong Argument)[] RuntimeRecords(List calls)
{
- var sites = new List(calls.Count);
var records = new HashSet<(ulong Target, ulong Argument)>();
foreach (var site in calls)
{
foreach (var target in site.Targets) records.Add((target.Address, target.Argument));
+ }
+
+ return [.. records];
+ }
+
+ // records: RuntimeRecords of the read's sites. A one-pass read (ReadScanned) collects them itself, and its sites hold
+ // each callee once.
+ internal static ShaderCallLibrary WithRuntimeArguments(Gen5ShaderProgram caller, List calls,
+ Dictionary codeHashes, Dictionary codeRuns,
+ (ulong Target, ulong Argument)[] records)
+ {
+ var sites = new List(calls.Count);
+ foreach (var site in calls)
+ {
sites.Add(site with
{
Targets = [.. site.Targets.DistinctBy(static target => target.Address).Select(static target => target with { Argument = 0 })],
});
}
- return WithRuntimeSites(caller.Address, identity, sites, [.. records], codeHashes, codeRuns) with { CurrentCodeHashes = codeHashes };
+ var library = WithRuntimeSites(caller.Address, "", sites, records, codeHashes, codeRuns);
+ return library with { Identity = library.LayoutIdentity, CurrentCodeHashes = codeHashes };
}
// The library of sites whose callees are each named once, in the order of their code, and whose identity names only the
@@ -245,7 +342,7 @@ private static ShaderCallLibrary WithRuntimeSites(ulong callerAddress, string id
Records = records,
CodeHashes = codeHashes,
CodeRuns = codeRuns,
- Bodies = sites.SelectMany(static site => site.Targets).Select(target => Convert.ToHexString(codeHashes[target.Address]))
+ Bodies = sites.SelectMany(static site => site.Targets).Select(target => CodeKey(codeHashes[target.Address]))
.Distinct().Count(),
};
}
@@ -279,6 +376,32 @@ public ShaderCallLibrary WithSiteCallees(ulong callerAddress, IReadOnlyDictionar
};
}
+ // This runtime-argument library without the callee at an address, at every site: a call to it returns at once.
+ public ShaderCallLibrary WithoutCallee(ulong callerAddress, ulong address) =>
+ WithSiteCallees(callerAddress, SiteCallees().ToDictionary(static site => site.Key,
+ site => site.Value.Where(callee => callee.Target.Address != address).ToDictionary(static callee => callee.Target.Address)));
+
+ // Links the sites with run-time arguments. A callee the linker cannot copy (one that calls another function, say) is left
+ // out at every site and the others still link: its records return at once, as the records of any callee a program lacks
+ // do. The library becomes the one the program holds.
+ public static Gen5ShaderProgram LinkLeavingOutUnlinkable(Gen5ShaderProgram caller, ref ShaderCallLibrary library,
+ Action leftOut)
+ {
+ while (true)
+ {
+ try
+ {
+ return Gen5ShaderCallLinker.Link(caller, library.Calls, runtimeArguments: true);
+ }
+ catch (ShaderCallLinkException failure) when (library.Calls.Any(site =>
+ site.Targets.Any(target => target.Address == failure.Target.Address)))
+ {
+ leftOut(failure);
+ library = library.WithoutCallee(caller.Address, failure.Target.Address);
+ }
+ }
+ }
+
// This runtime-argument library without a callee at any site: its program returns from every call at once, as from a
// record of a callee it does not hold, and compiles in seconds where the callees' code can take the driver minutes.
public ShaderCallLibrary WithoutCallees(ulong callerAddress) =>
@@ -292,21 +415,28 @@ public Dictionary SiteCallees() => Calls.ToDictionary(stat
// address, which this updates): a callee that leaves the tables keeps its copy, so tables that drop and regain it link
// to the same program. An address whose code changed takes the new code, and a site that would pass maxCallees starts
// over from its current callees.
- public ShaderCallLibrary Unite(ulong callerAddress, Dictionary> union, int maxCallees)
+ public ShaderCallLibrary Unite(ulong callerAddress, Dictionary> union, int maxCallees) =>
+ Unite(callerAddress, union, maxCallees, out _);
+
+ // changed: whether the union changed. A call that changed nothing returns the same library again for the same union
+ // (ShaderCallLibraryMemo keeps that result).
+ public ShaderCallLibrary Unite(ulong callerAddress, Dictionary> union, int maxCallees,
+ out bool changed)
{
+ changed = false;
// Callees whose code is the same share one decoded program, so the module can share their function: the translator
// compares instructions whose controls hold register lists by reference (SameBody).
var programs = new Dictionary();
foreach (var known in union.Values.SelectMany(static callees => callees.Values))
{
- programs.TryAdd(Convert.ToHexString(known.Code), known.Target.Program);
+ programs.TryAdd(CodeKey(known.Code), known.Target.Program);
}
UnitedCallee Current(ShaderCallTarget target)
{
var code = CodeHashes[target.Address];
- var program = programs.TryGetValue(Convert.ToHexString(code), out var shared) ? shared : target.Program;
- programs.TryAdd(Convert.ToHexString(code), program);
+ var program = programs.TryGetValue(CodeKey(code), out var shared) ? shared : target.Program;
+ programs.TryAdd(CodeKey(code), program);
return new UnitedCallee(target with { Program = program }, code, CodeRuns[target.Address]);
}
@@ -325,6 +455,7 @@ UnitedCallee Current(ShaderCallTarget target)
if (named.TryGetValue(address, out var target) && !known.Code.AsSpan().SequenceEqual(CodeHashes[address]))
{
callees[address] = Current(target);
+ changed = true;
}
}
}
@@ -363,9 +494,13 @@ UnitedCallee Current(ShaderCallTarget target)
{
foreach (var (from, to) in moved)
{
- if (callees.Remove(from) && !callees.ContainsKey(to))
+ if (callees.Remove(from))
{
- callees[to] = Current(named[to]);
+ changed = true;
+ if (!callees.ContainsKey(to))
+ {
+ callees[to] = Current(named[to]);
+ }
}
}
}
@@ -376,11 +511,13 @@ UnitedCallee Current(ShaderCallTarget target)
{
callees = [];
union.Add(site.Pc, callees);
+ changed = true;
}
if (site.Targets.Count(target => !callees.ContainsKey(target.Address)) + callees.Count > maxCallees)
{
callees.Clear();
+ changed = true;
}
foreach (var target in site.Targets)
@@ -388,6 +525,7 @@ UnitedCallee Current(ShaderCallTarget target)
if (!callees.ContainsKey(target.Address))
{
callees[target.Address] = Current(target);
+ changed = true;
}
}
}
@@ -395,6 +533,163 @@ UnitedCallee Current(ShaderCallTarget target)
return WithSiteCallees(callerAddress, union);
}
+ // A caller may also copy its target and argument pairs from user data: each of the four call registers (the
+ // target pair, then the argument pair) still holds a user-data register, reached through S_MOV_B32 and
+ // S_MOV_B64 copies (a caller may save a pair at entry and reuse it after the call registers were overwritten).
+ // A call site as the caller's code decides it: the user-data registers that hold its target and argument pairs, or the
+ // instruction that loads its record, or why it is refused. Each read takes the values from its own dispatch.
+ private sealed record CallSitePlan(int Index, string? Refusal = null, (uint Target, uint Argument)? UserData = null,
+ Gen5ShaderInstruction? Load = null, uint ArgumentRegister = 0);
+
+ private sealed record CallSitePlans(uint UserDataBase, uint UserDataCount, CallSitePlan[] Sites);
+
+ private sealed class CallSitePlanSlot
+ {
+ public volatile CallSitePlans? Plans;
+ }
+
+ // By instruction list, which a copy of the program at another address shares.
+ private static readonly ConditionalWeakTable, CallSitePlanSlot> SitePlans = new();
+
+ private static CallSitePlan[] CallSites(Gen5ShaderProgram caller, uint userDataBase, uint userDataCount)
+ {
+ var slot = SitePlans.GetValue(caller.Instructions, static _ => new CallSitePlanSlot());
+ if (slot.Plans is { } plans && plans.UserDataBase == userDataBase && plans.UserDataCount == userDataCount)
+ {
+ return plans.Sites;
+ }
+
+ var planned = new CallSitePlans(userDataBase, userDataCount, PlanSites(caller, userDataBase, userDataCount));
+ slot.Plans = planned;
+ return planned.Sites;
+ }
+
+ private static CallSitePlan[] PlanSites(Gen5ShaderProgram caller, uint userDataBase, uint userDataCount)
+ {
+ var sites = new List();
+ for (var index = 0; index < caller.Instructions.Count; index++)
+ {
+ if (caller.Instructions[index].Opcode == "SSwappcB64")
+ {
+ sites.Add(PlanSite(caller, index, userDataBase, userDataCount));
+ }
+ }
+
+ return [.. sites];
+ }
+
+ private static CallSitePlan PlanSite(Gen5ShaderProgram caller, int index, uint userDataBase, uint userDataCount)
+ {
+ try
+ {
+ return PlanSiteOrThrow(caller, index, userDataBase, userDataCount);
+ }
+ catch (InvalidOperationException refusal)
+ {
+ return new CallSitePlan(index, refusal.Message);
+ }
+ }
+
+ private static CallSitePlan PlanSiteOrThrow(Gen5ShaderProgram caller, int index, uint userDataBase, uint userDataCount)
+ {
+ var call = caller.Instructions[index];
+ if (call.Sources.Count != 1 || call.Destinations.Count != 1 ||
+ call.Sources[0].Kind != Gen5OperandKind.ScalarRegister || call.Destinations[0].Kind != Gen5OperandKind.ScalarRegister)
+ throw new InvalidOperationException("The shader call does not use a supported table record.");
+ if (TryFindUserDataCall(caller, index, userDataBase, userDataCount, out var userData))
+ return new CallSitePlan(index, UserData: userData);
+ Gen5ShaderInstruction load;
+ Gen5ScalarMemoryControl loadControl;
+ uint argumentRegister = 0;
+ if (TryFindDirectRecordLoads(caller, index, out var targetLoad, out var directArgumentRegister))
+ {
+ load = targetLoad;
+ loadControl = (Gen5ScalarMemoryControl)targetLoad.Control!;
+ argumentRegister = directArgumentRegister;
+ }
+ else
+ {
+ if (index < 6) throw new InvalidOperationException("The shader call does not use a supported table record.");
+ var loadIndex = index - 6;
+ while (loadIndex >= 0 && caller.Instructions[loadIndex] is { Opcode: "VMovB32", Destinations.Count: 1 } vectorMove &&
+ vectorMove.Destinations[0].Kind == Gen5OperandKind.VectorRegister) loadIndex--;
+ if (loadIndex < 0) throw new InvalidOperationException("The shader call table load is missing.");
+ load = caller.Instructions[loadIndex];
+ if (load.Opcode != "SBufferLoadDwordx4" || load.Control is not Gen5ScalarMemoryControl recordControl ||
+ load.Destinations.Count != 4 || caller.Instructions[index - 5].Opcode != "SWaitcnt")
+ throw new InvalidOperationException("The shader call table load is not supported.");
+ loadControl = recordControl;
+ if (loadControl.DynamicOffsetRegister is { } selector)
+ {
+ var scale = caller.Instructions.Take(loadIndex).Reverse().FirstOrDefault(instruction =>
+ instruction.Opcode.StartsWith("SCbranch", StringComparison.Ordinal) || instruction.Opcode is "SBranch" or "SSwappcB64" ||
+ instruction.Destinations.Any(destination => destination.Kind == Gen5OperandKind.ScalarRegister &&
+ selector >= destination.Value && selector - destination.Value < instruction.DestinationWidth));
+ if (scale is null || scale.Opcode != "SLshlB32" || scale.Destinations.Count != 1 || scale.Destinations[0] != Gen5Operand.Scalar(selector) ||
+ scale.Sources.Count != 2 || scale.Sources[1] != new Gen5Operand(Gen5OperandKind.EncodedConstant, 132))
+ throw new InvalidOperationException("The shader call table does not use 16-byte records.");
+ }
+ for (var component = 0; component < 4; component++)
+ {
+ var move = caller.Instructions[index - 4 + component];
+ if (move.Opcode != "SMovB32" || move.Sources.Count != 1 || move.Destinations.Count != 1 ||
+ move.Sources[0] != load.Destinations[component] || move.Destinations[0].Kind != Gen5OperandKind.ScalarRegister)
+ throw new InvalidOperationException("The shader call record has an unsupported register transfer.");
+ if (component == 2) argumentRegister = move.Destinations[0].Value;
+ var expected = component < 2 ? call.Sources[0].Value + (uint)component : argumentRegister + (uint)component - 2;
+ if (move.Destinations[0].Value != expected)
+ throw new InvalidOperationException("The shader call record does not use register pairs.");
+ }
+ }
+ return new CallSitePlan(index, Load: load, ArgumentRegister: argumentRegister);
+ }
+
+ private static ulong UserDataPair(ResourceSnapshot snapshot, uint userDataBase, uint first) =>
+ snapshot.UserData[first - userDataBase] | (ulong)snapshot.UserData[first - userDataBase + 1] << 32;
+
+ private static bool TryFindUserDataCall(Gen5ShaderProgram caller, int index, uint userDataBase, uint userDataCount,
+ out (uint Target, uint Argument) userData)
+ {
+ userData = default;
+ var callRegister = caller.Instructions[index].Sources[0].Value;
+ var sources = new uint[4];
+ for (var slot = 0; slot < sources.Length; slot++)
+ if (!TryTraceUserDataRegister(caller, index, callRegister + (uint)slot, userDataBase, userDataCount, out sources[slot]))
+ return false;
+ if (sources[1] != sources[0] + 1 || sources[3] != sources[2] + 1) return false;
+ userData = (sources[0], sources[2]);
+ return true;
+ }
+
+ // Follows one scalar register back from an instruction through register copies to the user-data register it
+ // holds. Any other writer ends the trace; a vector instruction's scalar result counts as a lane-mask pair.
+ private static bool TryTraceUserDataRegister(Gen5ShaderProgram caller, int before, uint register, uint userDataBase,
+ uint userDataCount, out uint userDataRegister)
+ {
+ userDataRegister = 0;
+ for (var cursor = before - 1; cursor >= 0; cursor--)
+ {
+ var instruction = caller.Instructions[cursor];
+ var vector = instruction.Encoding is Gen5ShaderEncoding.Vopc or Gen5ShaderEncoding.Vop3 or Gen5ShaderEncoding.Vop1 or
+ Gen5ShaderEncoding.Vop2;
+ foreach (var destination in instruction.Destinations)
+ {
+ var width = vector ? 2u : Math.Max(instruction.DestinationWidth, 1u);
+ if (destination.Kind != Gen5OperandKind.ScalarRegister || register < destination.Value ||
+ register - destination.Value >= width) continue;
+ if (instruction.Opcode is not ("SMovB32" or "SMovB64") || instruction.Sources.Count != 1 ||
+ instruction.Sources[0].Kind != Gen5OperandKind.ScalarRegister) return false;
+ register = instruction.Sources[0].Value + (register - destination.Value);
+ goto Traced;
+ }
+ continue;
+ Traced:;
+ }
+ if (register < userDataBase || register - userDataBase >= userDataCount) return false;
+ userDataRegister = register;
+ return true;
+ }
+
// A caller may also load one 16-byte record straight into the call registers: the target pair with an
// S_BUFFER_LOAD_DWORDX2 and the argument pair with another one 8 bytes further on, often with a null
// check of the target that branches past the call. Only waits, scalar compares and such a branch may stand
diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibraryMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibraryMemo.cs
new file mode 100644
index 000000000..936d20ea9
--- /dev/null
+++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibraryMemo.cs
@@ -0,0 +1,355 @@
+// Copyright (C) 2026 SharpEmu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using SharpEmu.ShaderCompiler;
+using SharpEmu.ShaderCompiler.Resources;
+
+namespace SharpEmu.Libs.Gpu.Pipelines;
+
+// Reuse of call-library work across dispatches, on by default: a ray-traced pass derives its call library again at
+// every dispatch, hundreds of times per frame. SHARPEMU_CALL_LIBRARY_REUSE=0, or any value but 1, turns it off. Unite
+// still tracks the union's changes while reuse is off, so a result kept earlier is never reused over a union the path
+// without reuse changed meanwhile.
+//
+// A run-time-record caller's library is derived again at every dispatch. Its records (which change as often as every
+// frame) are this dispatch's own, but its topology (the sites, the callees each site names and their code, and what is
+// derived from them: the callee order and slots, the layout identity, the union and the chosen callees) changes rarely:
+// - Topology: the per-record scan of the tables stays fresh (dedup, first occurrence, unreadable targets, current sites,
+// code hashes from the function cache's validated lookups). A run-time library whose sites and distinct callees (by
+// address, in first occurrence, each with the decoded program of the function cache's result) equal a previous read's
+// reuses that read's sorted sites, slots, identity and bodies, with this dispatch's records and current code hashes.
+// - Unite and WithSiteCallees depend on their input library only through its topology and carry its records, current
+// code hashes and current sites through; their results are kept by topology (and the union's version, or the chosen
+// callees map) and reused with the current dispatch's fields. A Unite that changed the union is not kept.
+// The tables and functions are read at every dispatch as without reuse (ShaderCallLibrary.Read). Whole libraries are
+// not cached by their exact input: the input words change at every dispatch.
+internal sealed class ShaderCallLibraryMemo
+{
+ internal enum Mode { Off, On }
+
+ internal static readonly Mode Configured = Environment.GetEnvironmentVariable("SHARPEMU_CALL_LIBRARY_REUSE") switch
+ {
+ null or "" or "1" => Mode.On,
+ _ => Mode.Off,
+ };
+
+ // Whether reuse is on. Code-hash text follows it (ShaderCallLibrary.CodeKey).
+ internal static bool Enabled => Configured != Mode.Off;
+
+ // Tests make a memo that always or never reuses (active true or false), whatever the configuration (the variable is
+ // read once per process). Null follows the configuration.
+ private readonly bool? _active;
+
+ internal ShaderCallLibraryMemo(bool? active = null)
+ {
+ _active = active;
+ }
+
+ private bool IsActive => _active ?? Enabled;
+
+ private const int MaxTopologies = 4096;
+
+ private enum Counter
+ {
+ TopologyHit, TopologyMiss, UniteHit, UniteMiss, UniteChanged, UniteUntokened, SitesHit, SitesMiss, SitesUntokened,
+ Off, Count,
+ }
+
+ private readonly long[] _counters = new long[(int)Counter.Count];
+
+ private void Count(Counter counter) => _counters[(int)counter]++;
+
+ // Tests: a counter's total since the memo was made, by name.
+ internal long Counted(string counter) => _counters[(int)Enum.Parse(counter)];
+
+ // ---- Read ------------------------------------------------------------------------------------------------------------
+
+ // The library of the caller's call sites, as ShaderCallLibrary.Read returns it.
+ internal ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable memory, ResourceSnapshot snapshot, GuestWordReader read,
+ ShaderFunctionCache? functionCache, bool runtimeArguments, uint userDataBase, ResidentGuestBytesReader? readBytes)
+ {
+ var active = IsActive;
+ if (!active) Count(Counter.Off);
+ return ShaderCallLibrary.Read(caller, memory, snapshot, read, functionCache, runtimeArguments, userDataBase, readBytes,
+ active ? this : null);
+ }
+
+ // ---- Topology --------------------------------------------------------------------------------------------------------
+
+ // A run-time library's topology: the caller, and per site its registers, its return address and the set of distinct
+ // callees its records name (by address), each with the program the function cache's result decoded. The static library
+ // sorts each site's callees by code and address, so the order the records name them in is not part of it.
+ private sealed class Topology(ulong[] words, object[] programs, ShaderCallLibrary library)
+ {
+ public readonly ulong[] Words = words;
+ public readonly object[] Programs = programs;
+ public readonly ShaderCallLibrary Library = library;
+ }
+
+ private readonly Dictionary<(object Instructions, ulong Hash), List> _topologies = new();
+ private int _topologyCount;
+ private readonly List _topologyWords = new(256);
+ private readonly List